I’m trying to write a declarative grammar where the order of declarations and other statements is unimportant. However, for parsing, I’d like to have the grammar output a tree in an ordered fashion. Let’s say the language consists of declarations (decl) and assignments (assign). An example might be:
decl x
assign y 2
assign x 1
decl y
I’d like to have the program represented by a tree with all the declarations in one subtree, and all the assignments in another. For the example above, something like:
(PROGRAM
(DECLARATIONS x y)
(ASSIGNMENTS
(y 2)
(x 1)))
Can I perform this rearrangement during tree construction, or should I write a tree grammar?
I think that there is an easier answer than the other one here:
Which can be adapted for as many rules as you like of course.
However, are you sure you need to do this? Why not just build the symbol table of DECL instructions in the parser, and then only build an AST of ASSIGNs, which you can check in the tree walk.
Jim