help-bison
[Top][All Lists]
Advanced

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

Re: Loops using flex/bison..


From: Anthony DeRobertis
Subject: Re: Loops using flex/bison..
Date: Tue, 05 Feb 2002 17:26:55 -0500

Matthew Tedder writes:

But flex/bison must have some idealized way of doing this.  If an
intermediate code was invisioned, why did they design lex and yacc to tie
directly together?  There must be some intended manner of implementing loops
and labels..

Bison is a parser. It is not an interpreter generator. Bison (along with a tokenizer, such as flex) will happily recognize sentences in your language. I think you have greatly misunderstood what a parser does. A parser doesn't have any notion of flow control, in that it can't skip over certain sections or repeat them. You _really_ want to build an intermediate representation. Abstract syntax trees (try Google) are one common form. You can create these easily from your rules. Your interpreter then does a tree traversal on the AST. Consider the simple grammar:
expr: expr '+' expr  { $$ = binary_op('+', $1, $3); }
| INT { $$ = literal_value($1); } I'll let you worry about the implementation of binary_op and literal_value. But they should return a tree. So, when you parse: 2 + 2 + 2 you get:
       +
    2     +
2 2 Now, your interpreter is pretty simple for this. In C, which may or may not work:
int expr(node_t *n) {
if (n->type == INT)
  return n->value;
else if (n->type == '+')
  return expr(n->left) + expr(n->right)
else
  /* handle invalid AST */
} Putting conditionals, loops, etc. in ASTs is easy. Interpreting them is easy. }
I hear GNU's C++ was
originally just a tool that converted C++ code to C code.

Origonal C++ implementations were with CFront, so I wouldn't be surprised. But nowadays, that's not how GCC front-ends work. The GCC people have documentation on this somewhere.



reply via email to

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