Syntax Parsing: From Tokens to Structure
Syntax parsing determines whether a sequence of tokens fits a grammar and identifies its grammatical structure. You encounter it when implementing a compiler, interpreter, or expression reader. The input is normally already divided into tokens such as identifiers, operators, and parentheses. Parsing establishes how those tokens fit together; declaration checks, type checks, and evaluation are separate tasks.
From tokens to structure
A context-free grammar describes permitted structures using rules called productions. A terminal represents an input token class or a specific punctuation token. A nonterminal represents a grammatical category that can be expanded. The start symbol identifies the category required for the complete input.
The governing recognition condition is
where S is the start symbol, w is the complete token sequence, and ⇒∗ means zero or more production applications. Each application replaces one nonterminal with the right-hand side of a permitted production.
Consider this expression grammar, whose start symbol is E:
The vertical bar separates alternatives. The terminal id represents an identifier token; its particular spelling does not change which production matches it.
A parse tree records these expansions: the root is the start symbol, each nonterminal's children follow one production, and the terminal leaves read left to right reproduce the input. An empty production contributes no input token.
How grammar controls grouping
The first grammar forces an unparenthesized chain of additions into a left-associated tree. In x+y+z, the final addition combines the subtree for x+y with z. Parentheses introduce a nested expression through T→(E).
Compare it with
This is an ambiguous grammar: the same three-identifier chain permits both (x+y)+z and x+(y+z). Those parentheses describe the trees; they are not additional tokens in the original input.
Different expansion orders do not necessarily mean different parse trees. Expanding a left subtree before a right subtree, or the reverse, can construct the same tree. Ambiguity concerns distinct structures for one complete token sequence, even if those structures happen to evaluate to the same value.
Predictive choices and complete acceptance
A recursive-descent parser can build structure from the start symbol downward. The first grammar is unsuitable for direct implementation because E→E+T calls for another E before consuming input. This immediate left recursion can cause an unending call chain.
An equivalent recognition grammar avoids that problem:
The alternative ε lets R finish without consuming a token. Here, R continues on a plus token and finishes on a closing parenthesis or the end of input. An identifier immediately after a completed term provides neither choice.
This rewritten grammar preserves the accepted token sequences, but its parse-tree shape differs. Preserving a left-associated interpretation requires combining successive additions from left to right when constructing the resulting expression representation.
Situation | Parser response | Reason |
|---|---|---|
A plus follows a completed term | Continue the expression | Another term is required after the plus |
A closing parenthesis follows a completed nested expression | Finish that expression | The caller can match the closing parenthesis |
Input ends while a closing parenthesis is expected | Report a mismatch | The required terminal is missing |
A complete expression leaves extra tokens | Reject the complete input | A valid prefix does not establish full acceptance |
What to remember
- Productions connect a token sequence to grammatical structure.
- A parse tree records expansions, not their execution order.
- Predictive choices depend on the next token and the grammar's permitted continuations.
- Accept the complete input only after all required tokens and the end marker match.
Example: Checking a Nested Addition Expression
A syntax parsing routine checks addition expressions entered into a billing form. It receives identifier, plus, and parenthesis tokens and uses this grammar with start symbol E:
The lookahead is the next unconsumed token inspected when choosing a production. The parser chooses the empty R production only on a closing parenthesis or EOF, the end-of-input marker. EOF is checked after the outer expression returns; it is not a grammar production. The parser stops at its first mismatch and does not insert missing tokens.
The input is id(net) + ( id(rate) + id(fee) ) EOF. Each identifier, operator, or parenthesis shown is one token.
a) Which productions handle the first identifier and first plus, and which alternative for the following term is selected next?
Start by expanding E→TR. The first lookahead token class is ________, so choose T→id and match id(net).
The next input token is the ________ token, so choose R→+TR and match the plus. The remaining term begins with an opening parenthesis, which selects T→(E).
Thus the decisions are E→TR, T→id, R→+TR, and then T→(E). The nested expression must be parsed before the closing parenthesis can be matched.
b) How many production applications and consumed input tokens are required for the complete expression, excluding EOF?
Count every selected production, including an empty production. In execution order, the nonterminal expansions are:
- Expand the outer E using E→TR.
- Expand its first T using T→id and match id(net).
- Expand the outer R using R→+TR and match the first plus.
- Expand the next T using T→(E) and match the opening parenthesis.
- Expand the inner E using E→TR.
- Expand the inner first T using T→id and match id(rate).
- Expand the inner R using R→+TR and match the second plus.
- Expand the following T using T→id and match id(fee).
- Expand the inner trailing R using R→ε on the closing-parenthesis lookahead. Return to the parenthesized term and match that parenthesis.
- Expand the outer trailing R using R→ε on EOF.
There are ________ expansions of E and ________ expansions of T. The two continuing and two empty expansions of R give four more applications.
The input contains three identifier tokens, two plus tokens, and two parenthesis tokens:
The complete expression therefore requires 10 production applications and 7 consumed tokens, excluding EOF. Empty productions contribute to the first count but not the second.
c) If the final closing parenthesis is removed, where does the parser report its first mismatch?
The shortened input ends immediately after id(fee). The inner trailing R sees EOF and selects its empty production, since EOF is one of its permitted lookahead tokens. This selection consumes nothing.
Control returns to the unfinished production T→(E). That production has matched its opening parenthesis and nested expression, but it still requires a closing parenthesis. The next token is EOF instead.
The first mismatch is therefore expected closing parenthesis, found EOF. Finishing the nested expression does not finish the surrounding parenthesized term. The complete input is rejected because a required terminal remains unmatched.
A compiler uses a bottom-up parser to reconstruct grammatical structure from tokens. Match each parsing term to its precise description.
Replacing zero or more stack symbols matching a production's right side with its left-side nonterminal
An occurrence of a production's right side whose replacement undoes one step of a rightmost derivation
The next input token inspected to help choose an action without consuming that token
Moving the next input token onto the parser stack and advancing the input position
Shift
Reduction
Lookahead
Handle
An expression parser uses the following grammar with start symbol E:
For the input id(p) + id(q) * id(r) + id(s), how many production applications occur in its complete derivation? Count every empty production once; matching terminals does not count as a production application. Give an exact integer number of applications, with zero decimal places.