Lecture 29 | Compiler I

From Tokens to Structure

Grammars, parse trees, and recursive descent.

Parsing

A Token Stream Is Not Yet a Program

The tokenizer can recognize every token in both sequences. Only one follows the language's structural rules.

let x = x + 1;
let = x 1 + ;

Parsing determines whether the tokens fit the grammar and identifies the construct formed by each group.

Grammars

A Grammar Is a Set of Construction Rules

A programming language needs rules that say which token sequences form a valid statement, expression, or program.

Exact tokens

Words and symbols that must occur in the program, such as return and ;.

Named parts

Places filled by another valid construct, such as an expression.

Grammar rule

A recipe that combines exact tokens and named parts to form one valid construct.

Reading One Rule

Build a Return Statement, One Part at a Time

returnStatement: 'return' expression? ';'
  1. returnStatement is the name of the construct being described.
  2. The colon means “can be formed as follows.”
  3. 'return' and ';' are exact tokens that must appear.
  4. expression? means an expression may occur here, but it is optional.
Therefore: both return; and return x + 1; have the required form.
Grammar Notation

Three Patterns That Occur in Many Rules

Choice: x | y

Use either x or y. Example: 'true' | 'false'.

Optional: x?

Use zero or one x. Example: the expression in return expression? ;.

Repetition: x*

Use zero or more copies of x. Example: a block may contain zero or more statements.

Quoted text denotes an exact token. An unquoted name refers to another rule.

Exercise 1

Use the Grammar as a Checklist

returnStatement: 'return' expression? ';'

Which sequences match this rule?

return;valid
return x;valid
return xinvalid: missing ;
return x y;invalid unless x y forms one expression
Parse Trees

A Parse Tree Records How a Rule Was Used

A parse tree is a picture of the nested structure found by the parser. The rule name is at the top; the actual program tokens appear at the bottom.

returnStatement
├── 'return'
├── expression
│   └── term
│       └── x
└── ';'

This tree says that return x; is a returnStatement, and that x forms its optional expression.

Next: Read a larger parse tree using the same top-to-bottom idea.

Parse Trees

The Same Idea for a Larger Statement

Parse tree showing how a while statement is derived from a partial grammar
Exercise 2

Sketch a Small Parse Tree

letStatement: 'let' identifier '=' expression ';'
expression: term (op term)*
term: identifier | integerConstant
op: '+' | '-'

Using the same parent-child style as the previous slide, sketch the tree for let x = y + 2;.

  1. Begin with letStatement as the root.
  2. Give it children for let, x, =, expression, and ;.
  3. Now expand the expression using its rule.
Inside the expression: use a term containing y, the token +, and a second term containing 2.
Implementing the Parser

Write One Function for One Grammar Rule

We now move from describing valid programs to writing the parser. Start with the return-statement rule we already understand.

Grammar rule
returnStatement:
  'return' expression? ';'
Parser pseudocode
compileReturn():
  expect('return')
  if current token is not ';':
      compileExpression()
  expect(';')

expect(token) checks that the current token is the expected one and then moves to the next token. Calling another parser function handles a named part such as expression.

Recursive Descent

How compileWhile() Reads the Tokens

Read a token means: check that the current token is correct, record it, and move to the next token.

while (count < 100) { let count = count + 1; }
  1. compileWhile() reads while and then (.
  2. It calls compileExpression() for count < 100.
  3. When that function returns, it reads ) and then {.
  4. It calls compileStatements(), which calls compileLet().
  5. After the statements are finished, it reads the closing }.
Choosing a Rule

The Current Token Usually Decides

let→compileLet()
if→compileIf()
while→compileWhile()
do→compileDo()
return→compileReturn()

Jack was designed so that the first token usually identifies the alternative. Parsing a term that begins with an identifier requires one-token lookahead.

Exercise 3

When Is Lookahead Necessary?

An identifier can begin several kinds of term. What does the next token reveal?

scorevariable
items [array entry
draw (subroutine call
Screen .qualified subroutine call
Syntax Errors

A Failed Expectation Reveals the Error

while (x < 10 { let x = x + 1; }

After compiling the expression, the grammar requires ). The parser sees { instead.

A useful diagnostic records:what was expected;what was found;where it was found.

The same grammar that recognizes valid programs helps identify invalid ones.

Summary of This Lecture

Parsing Explains How the Tokens Fit Together

Grammar

Combines exact tokens and named parts to describe valid constructs.

Parse tree

Records the hierarchical derivation of one program.

Recursive descent

Implements each grammar rule as a mutually recursive routine.

Lecture 30 | Compiler I

Building the Jack Syntax Analyzer

From the Jack grammar to structured XML.

Go to Lecture 30