r/ProgrammingLanguages • u/Due_Battle_9890 • Jul 23 '26
Help Creating AST Nodes from a Given Grammar. What's the not dumb way to do this?
Hey,
I've been primarily focused on the backend for compilers and want to sharpend my frontend skills, so I've been revisiting chapters and creating parsers. I have a decent intuition on how you would create AST nodes for a given grammar, but nothing rigorour. For example, if given this grammar,
expr ::= term ( ( "+" | "-" ) term )*
term ::= power ( ( "*" | "/" ) power )*
power ::= unary ( "^" power )?
unary ::= "-" unary
| primary
primary ::= NUMBER
| "(" expr ")"I'd have
enum Binary {
Add { left: Box<Expr>, right: Box<Expr> },
Sub { left: Box<Expr>, right: Box<Expr> },
Mul { left: Box<Expr>, right: Box<Expr> },
Div { left: Box<Expr>, right: Box<Expr> },
Pow { left: Box<Expr>, right: Box<Expr> },
}
enum Expr {
Binary(Binary),
Num(i64),
Neg(Box<Expr>),
}but it more so feels right. I didn't do this algorithmically. I also know that some sources have a node just for grouping and some other nodes use eat. What are your thoughts on that?
10
Upvotes
19
u/Less-Resist-8733 Jul 23 '26
it's pretty standard to structure Binary expr like this
enum BinOp { Add, Sub, ... }
struct BinExpr { op: BinOp, left: Box<Expr>, right: Box<Expr>, }
...
6
u/anydalch Jul 23 '26
If you're trying to have a direct correspondence between your parser grammar and your tree structure, to the extent of having nodes for groupings, it sounds like you have a CST, or Concrete Syntax Tree, not an AST.
3
u/initial-algebra Jul 24 '26
Well, it's pretty common to have multiple types of syntax tree, depending on how far along in the pipeline you are. For example, the parser for a language with custom operators and precedence/associativity rules might output a syntax tree with concrete identifiers and group nodes for operator expressions that haven't been disambiguated yet. Then, you'd have some code that looks up the identifiers and converts them into de Bruijn indices for local variables and IDs for global variables and other definitions, but doesn't touch the group nodes yet. Finally, another bit of code applies the precedence and associativity rules (by looking them up using the IDs of the custom operators) to disambiguate the group nodes into trees of individual nodes for each operation. To avoid repeating yourself when defining these syntax tree types, you'd probably want to make them generic. You could include all node types in one tree type, even if some of them are incompatible, but then the compiler can't help you as much.
There are no hard and fast rules, you're basically just adding structure and removing useless information (such as the exact names the programmer used, or whether they wrote
x + y * zorx + (y * z)) as you progress from the source code, to concrete syntax, to abstract syntax, to fully type-annotated syntax, etc. down to the final output.1
u/WittyStick Jul 24 '26 edited Jul 24 '26
One big power up for representing an AST is GADTs, but they're not widely available. We can use types with type parameters to encode more type information statically, reduce runtime checking of types and prevent some errors.
To give a basic example in OCaml, consider expressions with just +, -, *, /, and parens (ie, PEDMAS).
Notice how the
additive_exprrule makes no reference tomultiplicative_expr, andmultiplicative_exprmakes no reference toprimary_expr- andprimary_exprmakes no reference to theexpritself - these are given as parameters. Theexprtype ties it all together in one place - making it very easy to add new syntax into your language - eg, to reintroduce power.There are actually better ways to do this - we could just leave
expras it was and introduceexprv2Writing functions over these types requires parameterizing them with functions that will be recursively called in a similar way - each rule only needs to know about itself and its parameters, but not every other rule - only the
print_exprfunction ties it together.Similarly, if we add the power rule:
Producing this AST might seem overly complex, but if we use Menhir - a parser generator that also supports parameterization of rules, we can use basically the same pattern to produce the tree.
And again, lets add the power:
Menhir is basically a parsing superpower when you use these techniques - each of our syntactic elements can be described in isolation which makes them reusable and versionable - and only our
exprrule needs adjusting to extend the grammar with new syntax. Here's a basic calculator following the same pattern as the print example above:1
u/SirKastic23 Jul 23 '26
Instead of linking the expressions by nesting boxes you can store expressions in an arena and refer to them with indexes
0
u/umlcat Jul 23 '26
Are you going to only handle binary operators ?
Or are you thinking in handling prefix / posfix unary operators ?
Or are you thinking in handling the ternary operator A.K.A. inmediate If operator ?
BTW Some develoeprs use the semicolon as a unary posfix operator.