help-bison
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: About the FOR loop semantic action


From: lfinsto1
Subject: Re: About the FOR loop semantic action
Date: Sat, 20 Oct 2007 20:42:53 +0200 (CEST)
User-agent: SquirrelMail/1.4.9a

> I'm in the process of writing an interpreter for my simplified C-like
> language. I've already added the support for expressions and "if then
> else" statements but I'm having some hard time figuring out how to
> support loops.

I suggest you take a look through the archives, since this topic has been
discussed before.

> for_stmt:
>     FOR '(' expr ';' expr ';' expr ')' block
> ;
>
> My question is, how am I going to write my action so that it executes
> the for_stmt block while the second expression/condition is valid?

I don't think this is what's supposed to happen.  I think `yyparse' is
supposed to continue parsing tokens, since the contents of `block' will
also be in the language that you're defining.

I don't know how C compilers do this, but you could look at how I
implemented loops in GNU 3DLDF.  It was not particularly difficult.  The
basic idea is:  Read the loop, put it into a buffer, put code at the end
of the buffer for your conditional and start reading from the buffer
instead of the input source you were reading from.  If the conditional is
true, read the buffer again.  If it's false, discard the buffer and
continue reading input from where you were before.  If the condition is
false at the beginning, don't bother with the above.  I've left out quite
a few details, but that's the basic idea.

If you want macros in your language, you can implement them in a similar way.

> I also have a second questio: Is it possible to instruct bison to skip
> one part of a semantic rule

I don't think there's such a thing as a semantic rule.  It's a syntactic
rule.  The semantics of a language are what's done by the actions and
Bison generally isn't concerned with them.  One might consider it an
exception to this when the semantics of a language involve passing tokens
to `yyparse', as I described before.  On the other hand, that might just
be splitting hairs.

> if a given condition isn't met? It's
> typically useful for the "if then else" closure, i.e:
>
> if_stmt:
>     IF expr { update(&($2)); } block { reset(); }
> ;
>
> where block won't be parsed/executed if the expr isn't valid.

I think it's usually not a good idea to execute code in the middle of
rules like this.  I'm sure there are good reasons for it, or it wouldn't
be allowed.  However, I wouldn't do it if I didn't have to.  In fact, I
don't use this anywhere at present.

Again, I don't know how C compilers do this, but you could look at how I
do in GNU 3DLDF.  This topic has also come up here before.

Laurence Finston







reply via email to

[Prev in Thread] Current Thread [Next in Thread]