CcCompilers · Lesson 3 of 7
Parsing — Tokens to Trees
Flat token lists become a tree that captures structure: what belongs to what, what happens first. The AST — abstract syntax tree — is the data structure every language tool lives on.
Notice the layering does the precedence: parse_expr calls parse_term which calls parse_factor, so * binds tighter than + automatically. Grammars are written down formally (BNF notation), and parser generators can produce parsers from them — though production compilers mostly hand-write for better error messages.
◆ Note
Once you have an AST, an interpreter is trivial: walk the tree, evaluating children before parents. def eval(n): return n[1] if n[0]=='num' else eval(n[1]) + eval(n[2]) if n[0]=='add' else eval(n[1]) * eval(n[2]). Congratulations — lexer, parser, evaluator is a complete language implementation, and you've now seen all three.
Once you have an AST, an interpreter is trivial: walk the tree, evaluating children before parents. def eval(n): return n[1] if n[0]=='num' else eval(n[1]) + eval(n[2]) if n[0]=='add' else eval(n[1]) * eval(n[2]). Congratulations — lexer, parser, evaluator is a complete language implementation, and you've now seen all three.