Lecture 30 | Compiler I

Building the Jack Syntax Analyzer

From the Jack grammar to structured XML.

Jack Grammar

Find the Parts Inside a Jack Class

class Main {
  function void main() {
    var int x;
    let x = 2 + 3;
    return;
  }
}
Class and subroutine

Main contains main().

Statements

let and return form the function body.

Expression

2 + 3 supplies the value for x.

Today's goal: recognize these parts and write their structure as XML, so we can test the syntax analyzer before generating VM code.

Next: Which individual tokens make up this source?

Lexical Elements

Start with Jack's Five Token Kinds

Jack lexical-element rules for keywords, symbols, integer constants, string constants, and identifiers

The tokenizer recognizes these five kinds. The parser then uses the tokens—not raw characters—to recognize larger parts.

Next: How do tokens form a complete class?

Program Structure

The Shape of a Jack Class

Jack program-structure grammar, including class declarations, variable declarations, subroutines, parameters, and subroutine bodies

Read from class downward: class-variable declarations come before subroutines. A subroutine body contains local declarations followed by statements.

Try matching a real class to these named parts.

Exercise 1

Match Source Lines to Grammar Elements

class Counter {
  field int value;
  constructor Counter new() { ... }
  method void increment() { ... }
}
CounterclassName
field int value;classVarDec
constructor ...subroutineDec
method ...subroutineDec

Next: What can appear inside a subroutine body?

Statements

Five Alternatives, Recognized by One Token

Jack statement grammar for let, if, while, do, and return statements
letifwhiledoreturn

The first keyword selects the rule. compileStatements() stops when the next token is not one of these five statement starters.

Start with the simplest statement: how would we parse return?

Exercise 2

How Would You Implement compileReturn()?

returnStatement: 'return' expression? ';'

Write the routine for both return; and return x;. Reveal the code after students have tried.

compileReturn():
    openTag('returnStatement')
    expectAndWrite('return')
    if currentToken != ';':
        compileExpression()
    expectAndWrite(';')
    closeTag('returnStatement')

Convention: expectAndWrite(t) checks, writes the XML leaf, and advances; expectIdentifierAndWrite() does the same for an identifier. Treat compileExpression() as a helper for now—we will design it later in this lecture. Small helpers need not create an enclosing XML tag.

Next: a do statement contains a subroutine call.

Exercise 3

How Would You Implement compileDo()?

doStatement: 'do' subroutineCall ';'

Try do Output.printInt(x);. Which routine should recognize the call between do and ;?

compileDo():
    openTag('doStatement')
    expectAndWrite('do')
    compileSubroutineCall()
    expectAndWrite(';')
    closeTag('doStatement')

compileSubroutineCall() is a helper we will design after expression lists. It writes tokens inside the doStatement, not an extra subroutineCall XML tag.

Next: an if statement has an optional else branch.

Exercise 4

How Would You Implement compileIf()?

ifStatement: 'if' '(' expression ')' '{' statements '}'
             ('else' '{' statements '}')?

Handle both an if without else and one with else.

compileIf():
    openTag('ifStatement')
    expectAndWrite('if'); expectAndWrite('(')
    compileExpression()
    expectAndWrite(')'); expectAndWrite('{')
    compileStatements()
    expectAndWrite('}')
    if currentToken == 'else':
        expectAndWrite('else'); expectAndWrite('{')
        compileStatements()
        expectAndWrite('}')
    closeTag('ifStatement')

Next: while follows the same pattern, without else.

Exercise 5

How Would You Implement compileWhile()?

whileStatement: 'while' '(' expression ')' '{' statements '}'

Use compileIf() as a guide. What changes?

compileWhile():
    openTag('whileStatement')
    expectAndWrite('while'); expectAndWrite('(')
    compileExpression()
    expectAndWrite(')'); expectAndWrite('{')
    compileStatements()
    expectAndWrite('}')
    closeTag('whileStatement')

Finally, a let statement can assign to a variable or an array entry.

Exercise 6

How Would You Implement compileLet()?

letStatement: 'let' varName ('[' expression ']')?
              '=' expression ';'

Cover both let x = 1; and let a[i] = x;.

compileLet():
    openTag('letStatement')
    expectAndWrite('let')
    expectIdentifierAndWrite()
    if currentToken == '[':
        expectAndWrite('[')
        compileExpression()
        expectAndWrite(']')
    expectAndWrite('=')
    compileExpression()
    expectAndWrite(';')
    closeTag('letStatement')

These routines call compileExpression(). What does an expression contain?

Expressions

Read the Complete Expression Rules

Jack expression grammar for expressions, terms, subroutine calls, operator lists, unary operators, and keyword constants

An expression begins with a term, then may continue with operator–term pairs. A term can itself contain another expression.

The symbol * appears twice here, with two different meanings.

Expressions

Two Meanings of *

Grammar notation: repeat
expression: term (op term)*

The unquoted * says “zero or more operator–term pairs.” It is an instruction to the parser, not a Jack token.

Jack token: multiply
op: '+' | '-' | '*' | ...

The quoted '*' is a Jack operator token. For now, the parser writes <symbol> * </symbol>; it does not perform multiplication.

Parsing plan: recognize a term; while the next token is an operator, record that operator and recognize another term.

Let's trace a parenthesized expression containing multiplication.

Exercise 7

Parse 2 + (3 * 4)

Which parts belong to the outer expression, and which belong to the expression inside the parentheses?

let result = 2 + (3 * 4);

Outer expression: term 2, operator +, term (3 * 4).

Inside the parentheses: term 3, operator *, term 4.

The inner compileExpression() stops before ); the outer one stops before ;. Parentheses make the intended grouping explicit—Jack does not require them around every expression.

How can parser routines follow this nesting?

Expressions

Parse Terms, Then Operator–Term Pairs

compileExpression():
    compileTerm()
    while currentToken is an operator:
        compileOperator()   // write operator and advance
        compileTerm()

compileTerm():
    if currentToken == '(':
        writeAndAdvance('(')
        compileExpression()
        writeAndAdvance(')')
    else:
        handle the other term forms

A parenthesized expression is a term. The recursive call handles its contents; the surrounding call then continues with any following operator–term pairs. compileOperator() only records the operator—it does not calculate a value.

Calls can pass zero or more expressions. How do we parse that list?

Exercise 8

How Would You Implement compileExpressionList()?

expressionList: (expression (',' expression)*)?

It must accept both f() (empty list) and f(x, 2 + y). The caller has already read (.

compileExpressionList():
    openTag('expressionList')
    if currentToken != ')':
        compileExpression()
        while currentToken == ',':
            expectAndWrite(',')
            compileExpression()
    closeTag('expressionList')

The list leaves the closing ) for its caller. compileExpression() stops before a comma or closing parenthesis because neither is an operator.

Now use this list inside a subroutine call.

Exercise 9

How Would You Implement compileSubroutineCall()?

subroutineCall: subroutineName '(' expressionList ')' |
  (className | varName) '.' subroutineName '(' expressionList ')'

Cover move(x) and Math.multiply(x, 2).

compileSubroutineCall():
    expectIdentifierAndWrite()
    if currentToken == '.':
        expectAndWrite('.')
        expectIdentifierAndWrite()
    expectAndWrite('(')
    compileExpressionList()
    expectAndWrite(')')

This helper writes tokens inside the surrounding statement or term. The Project 10 XML has an expressionList tag, but no separate subroutineCall tag.

When a term starts with an identifier, how do we choose its form?

Exercise 10

Distinguish Identifier-Led Terms

For each token prefix, choose the grammatical form.

x +variable
a [array entry
move (subroutine call
Math .qualified subroutine call

This is the principal place where the compilation engine needs one-token lookahead.

We can now recognize the parts. How do we record them for testing?

Analyzer Output

Our Goal: Record the Parse Tree as XML

Jack source code transformed by the syntax analyzer into nested XML elements

This is the output promised at the start: nested XML records which grammar rules matched the source. We can compare it with reference XML before generating VM code.

How do we tag individual tokens versus complete constructs?

Analyzer Output

Tokens and Larger Parts Get Different Tags

Individual tokens
<keyword> return </keyword>
<symbol> ; </symbol>

The tag names the token's type.

A complete construct
<returnStatement>
  ... tokens inside ...
</returnStatement>

The outer tag groups the tokens that form a return statement.

Exercise 11

Write the XML for a Return Statement

return;
<returnStatement>
  <keyword> return </keyword>
  <symbol> ; </symbol>
</returnStatement>

No <expression> appears because the expression in the grammar is optional.

Next: Which software modules produce this XML?

Software Architecture

Three Modules, Three Responsibilities

JackAnalyzerfind inputs and coordinate the work
→
JackTokenizercharacters → typed tokens
→
CompilationEnginetokens → structured XML

Keeping these responsibilities separate allows each part to be implemented and tested independently.

JackAnalyzer

The Top-Level Driver

  1. Accept one Xxx.jack file or a directory containing Jack files.
  2. For each source file, create a JackTokenizer.
  3. Create the corresponding Xxx.xml output file.
  4. Create a CompilationEngine and begin with compileClass().

Xxx.jack → Xxx.xml

CompilationEngine

Each Routine Handles Exactly One Construct

Start: the first token of the construct is current.

Do: check expected tokens, ask other routines to handle named parts, and write the matching XML tags.

Finish: move to the first token after this construct. The caller can continue from there.

compileClass()compileStatements()compileWhile()compileExpression()compileTerm()
Implementation Strategy

Build and Test in Two Stages

1Tokenizer

Generate XxxT.xml. Compare it with the supplied token files before beginning the parser.

2Parser

Begin with expressionless programs, then add expressions and test complete Jack programs.

Suggested progressionExpressionlessSquare→Square→ArrayTest

Use the supplied comparison files as the contract. Indentation is for readability; the XML structure and tokens must match.

Summary of This Week

The Syntax Analyzer Makes Structure Explicit

CharactersJack source
→
Tokenslexical analysis
→
Grammar structurerecursive descent
→
XMLtestable parse tree

Next chapter: keep the parser, add semantic information, and generate executable VM code.