What is a Parse Tree (Concrete Syntax Tree)?
A Parse Tree (also known as a Concrete Syntax Tree or CST) is an ordered, rooted tree graph that visually depicts the syntactic derivation of a string according to the production rules of a Context-Free Grammar (CFG).
Unlike an Abstract Syntax Tree (which discards syntactic formalities), a parse tree records every single grammar production. Every internal node is labeled by a non-terminal grammar symbol (such as Expr, Term, Factor, or Statement), and every leaf node represents an exact terminal symbol or token from the input string (including punctuation, operators, and grouping parentheses).
Leftmost vs. Rightmost Derivations in Parse Trees
In formal language theory, a string can be generated from the start symbol through a sequence of replacement steps called a derivation:
1. Leftmost Derivation (LMD)
At every step, the leftmost non-terminal symbol in the sentential form is replaced first. Used by top-down parsers like LL(1) and recursive descent parsers.
2. Rightmost Derivation (RMD)
At every step, the rightmost non-terminal symbol is replaced first. The reverse of a rightmost derivation is produced by bottom-up parsers like LR(1), LALR, and Yacc/Bison.
Remarkably, regardless of whether a leftmost or rightmost derivation is chosen, an unambiguous grammar will produce the exact same Parse Tree.
Parse Tree (CST) vs. Abstract Syntax Tree (AST): The 5 Core Differences
| Criteria | Parse Tree (Concrete Syntax Tree) | Abstract Syntax Tree (AST) |
|---|---|---|
| What it represents | Exact derivation history according to grammar rules | High-level logical and operational semantics |
| Parentheses `( )` & Punctuation | Explicitly preserved as leaf nodes | Discarded (hierarchy implies grouping) |
| Single-Child Chains (E → T → F) | Fully preserved (shows full grammar chain) | Collapsed into direct value nodes |
| Memory & Node Count | Large node count, deeply nested | Compact, lightweight, memory-efficient |
| Where it is used | Formal language validation, grammar debugging, CYK | Compiler optimization, linters, code generation |
Detecting Grammar Ambiguity with Parse Trees
A Context-Free Grammar is formally defined as ambiguous if there exists at least one string that yields two or more distinct parse trees.
A classic example is the naive expression grammar: E → E + E | E * E | id. For the input id + id * id, this ambiguous grammar produces two distinct parse trees:
Flawed Tree (Addition at Bottom)
Evaluates addition before multiplication: yields (id + id) * id, violating standard operator precedence rules.
Correct Tree (Multiplication at Bottom)
Evaluates multiplication before addition: yields id + (id * id), correctly reflecting operator hierarchy.
Our Parse Tree Generator enforces precedence stratification (E → E + T and T → T * F) to eliminate ambiguity and produce mathematically rigorous derivations.