Reputation: 23
I'm trying to make a C-to-Forth Bison parser.
I've developed most of the typical functions, but I have some troubles with some expressions.
I was thinking about using an AST during the parse, but it is slightly more difficult to code than a temporary buffer.
Could anyone recommend one strategy over the other?
Thanks
Upvotes: 2
Views: 398
Reputation: 241791
If you use the strategy of immediately producing the translation for each production, it becomes impossible to reorder clauses. That's a severe limitation.
There are a number of hacks in common use to get around the problem. One is to provide a mechanism whereby output for a production can be saved in a temporary buffer, so that it can be actually output later on.
However, the cleaner solution is to create an AST (Abstract Syntax Tree) during the parse, and then walk the AST when the parse is complete. Since the entire parse tree is available at that point, you can easily walk the child nodes of a production in an arbitrary order.
The AST strategy more cleanly separates the parse from the code generation, making it easier to implement other processing steps (pretty printing, linting, etc., etc.). It also avoids the problem of producing a partial output in the case where an error is detected and the parse is prematurely terminated.
Upvotes: 3