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


S⇒∗w,S \Rightarrow^{*} w,


where SS is the start symbol, ww is the complete token sequence, and ⇒∗\Rightarrow^{*} 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 EE:


E→E+T∣TT→id∣(E).\begin{aligned} E &\to E + T \mid T \\ T &\to \mathrm{id} \mid (E). \end{aligned}


The vertical bar separates alternatives. The terminal id\mathrm{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.


A parse tree for x plus y shows nonterminal expansions above the identifier and plus leaves.



How grammar controls grouping

The first grammar forces an unparenthesized chain of additions into a left-associated tree. In x+y+zx+y+z, the final addition combines the subtree for x+yx+y with zz. Parentheses introduce a nested expression through T→(E)T \to (E).


Compare it with


E→E+E∣id.E \to E+E \mid \mathrm{id}.


This is an ambiguous grammar: the same three-identifier chain permits both (x+y)+z(x+y)+z and x+(y+z)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+TE \to E+T calls for another EE before consuming input. This immediate left recursion can cause an unending call chain.


An equivalent recognition grammar avoids that problem:


E→TRR→+TR∣εT→id∣(E).\begin{aligned} E &\to TR \\ R &\to +TR \mid \varepsilon \\ T &\to \mathrm{id} \mid (E). \end{aligned}


The alternative ε\varepsilon lets RR finish without consuming a token. Here, RR 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 EE:


E→TRR→+TR∣εT→id∣(E).\begin{aligned} E &\to TR \\ R &\to +TR \mid \varepsilon \\ T &\to \mathrm{id} \mid (E). \end{aligned}


The lookahead is the next unconsumed token inspected when choosing a production. The parser chooses the empty RR 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→TRE \to TR. The first lookahead token class is ________, so choose T→idT \to \mathrm{id} and match id(net).


The next input token is the ________ token, so choose R→+TRR \to +TR and match the plus. The remaining term begins with an opening parenthesis, which selects T→(E)T \to (E).


Thus the decisions are E→TRE \to TR, T→idT \to \mathrm{id}, R→+TRR \to +TR, and then T→(E)T \to (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:

  1. Expand the outer EE using E→TRE \to TR.
  2. Expand its first TT using T→idT \to \mathrm{id} and match id(net).
  3. Expand the outer RR using R→+TRR \to +TR and match the first plus.
  4. Expand the next TT using T→(E)T \to (E) and match the opening parenthesis.
  5. Expand the inner EE using E→TRE \to TR.
  6. Expand the inner first TT using T→idT \to \mathrm{id} and match id(rate).
  7. Expand the inner RR using R→+TRR \to +TR and match the second plus.
  8. Expand the following TT using T→idT \to \mathrm{id} and match id(fee).
  9. Expand the inner trailing RR using R→εR \to \varepsilon on the closing-parenthesis lookahead. Return to the parenthesized term and match that parenthesis.
  10. Expand the outer trailing RR using R→εR \to \varepsilon on EOF.

There are ________ expansions of EE and ________ expansions of TT. The two continuing and two empty expansions of RR give four more applications.


Nproductions=2+4+4=10.N_{\text{productions}}=2+4+4=10.


The input contains three identifier tokens, two plus tokens, and two parenthesis tokens:


Ntokens=3+2+2=7.N_{\text{tokens}}=3+2+2=7.


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 RR 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)T \to (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 has tokenized balance + fee successfully. Its expression grammar permits addition of identifiers, but neither identifier has been declared. What can syntax parsing alone establish before declaration checks, type checks, or evaluation?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A compiler uses a bottom-up parser to reconstruct grammatical structure from tokens. Match each parsing term to its precise description.

Match each term
A.

Replacing zero or more stack symbols matching a production's right side with its left-side nonterminal

B.

An occurrence of a production's right side whose replacement undoes one step of a rightmost derivation

C.

The next input token inspected to help choose an action without consuming that token

D.

Moving the next input token onto the parser stack and advancing the input position

Shift

Reduction

Lookahead

Handle

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An expression parser uses the following grammar with start symbol EE:


E→TRR→+TR∣εT→FUU→∗FU∣εF→id.\begin{aligned} E &\to TR \\ R &\to +TR \mid \varepsilon \\ T &\to FU \\ U &\to *FU \mid \varepsilon \\ F &\to \mathrm{id}. \end{aligned}


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.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice