Salvatore
Salvatore

Reputation: 1185

For loop semantics in Bison/Yacc

I'm trying to write my own scripting language using flex and bison. I have a basic parser and I would like to add a for statement very similar to the C language for statement. It is not clear to me how to code the action associated to the for statement

Suppose I have the following production for the 'for' statement:

forStatement: FOR '(' expr ';' expr ';' expr ')' statements END; {}

It is not clear to me what to do in the action associated to this production.

Intuitively I understand that I should do something, in the action associated to the previous statement, such as :

evaluate($3);
while(evaluate($5)) { execute($9); evaluate($7); }
evaluate($7);

where evaluate and execute are two C functions.

So I have two questions (suppose to write C code for the action associated to the grammar production):

  1. What is the task of 'evaluate'. I mean, how do I evaluate the expression at every loop considering that the value of the expression potentially changes at every step of the loop?
  2. What is the task of 'execute'. I mean, how do I evaluate the statements inside the for loop considering that each statement has a different outcome at every step of the loop.

The values of the three expressions 'expr' changes at runtime and the same is true for the statements inside the for body.

Upvotes: 2

Views: 5590

Answers (2)

meaning-matters
meaning-matters

Reputation: 22946

Looking at your two questions, you seem to miss that an execution engine (a kind of software CPU) is needed. This engine needs to remember the state of variables, return 'addresses' of loops, ... (depending on implementation method chosen).

So parsing is just the first step. Think about creating a data structure for each statement and expression, and have these executed by this engine.

Have a look at stack-based systems.

Upvotes: 2

akim
akim

Reputation: 8769

This is a FAQ, not only on SO, but also in Bison. Please, read the documentation: http://www.gnu.org/software/bison/manual/html_node/Implementing-Gotos_002fLoops.html

Upvotes: 1

Related Questions