UP | HOME

Syntax and parser generators I
Lecture 3

Table of Contents

Review

Questions about the last class?

Quiz

What is the difference between a compiler and an interpreter? Also, give one example of each.

Quiz Discussion

Review: Phases of a compiler

  • Syntax analysis
  • Type checking
  • Code generation

Syntax analysis

  • Turn text into a parse tree
  • Identifies words (tokens, lexemes) in the language
  • Grammar gives a name to each language construct
    • Map is not the territory
      • Nothing in the text of a sentence says "this is a sentence"
      • We know because of the word order
      • Grammar defines all the legal word orders

Type checking

  • Verifies that symbols are used correctly
    • numbers added to numbers, not function
    • Will be more specific in the next phase

Code generation

  • Intermediate code (for us this is C)
  • Machine code (this is the C to ASM compiler, which has its own compiler phases)

Review: Grammars

Using ANTLR

  • Setting up the environment

Example: calculator

  • Work out the grammar in class by hand
    • Order of operations
  • Test it with some examples

Defining Calc.g4

  • Overview of ANTLR grammars
  • Lexer vs. parser

Generating the parser

# add antlr to your classpath; your path to the runtime may vary
export CLASSPATH=/usr/share/java/antlr4-runtime.jar:$CLASSPATH
# this generates the parser
antlr4 Calc.g4
# this compiles the parser
javac *.java
# use -gui to display a parse tree graphically
echo "1*2+3" | /usr/share/antlr4/grun Calc expr -gui
# demonstrate order of operations
echo "1+2*3" | /usr/share/antlr4/grun Calc expr -gui
# use -tree to display a parse tree textually
echo "1*2+3" | /usr/share/antlr4/grun Calc expr -tree
echo "1+2*3" | /usr/share/antlr4/grun Calc expr -tree

Using the parser

Homework

(1 week)

  • Hand-copy the grammar and turn in parse trees for 2 example inputs

Author: Paul Gazzillo

Created: 2023-04-13 Thu 14:59