Docsity

Lecture Notes for CPSC 326: Parsing and Semantic Analysis (Spring 2013), Study notes of Programming Languages

Partial preview of the text

Download Lecture Notes for CPSC 326: Parsing and Semantic Analysis (Spring 2013) and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Quiz 10
  • Parsing (cont.)
  • Semantic analysis (start)

An example grammar

Simple list of assignment statements

stmt list → stmt | stmt ‘;’ stmt list

stmt → var ‘=’ expr

var → ‘A’ | ‘B’ | ‘C’

expr → var | var ‘+’ var | var ‘-’ var

  • quotes used here to help distinguish terminals from non-terminals
  • Note: many possible grammars for our language!

Issues with our example (for LL(k))

Q: Is it left-recursive? Nope (we’re ok)

Q: Can it be left factored? Yes (need to fix)

Q: Is it ambiguous? Nope (we’re ok)

Q: How many look ahead tokens needed? 6 (need to fix)

Q: How should we fix it?

Recursive Descent Parsing

A simple approach to ad hoc parsing

  • use recursion to parse the token stream
  • divide parse into separate methods ... one for each non terminal
  • “descend” the parse tree using recursion

Example program → stmt list $$ stmt list → var ‘=’ expr stmt list tail void advance() { // helper function tok = scanner.next_token(); } void eat(int t) { // helper function if(t == tok.type()) advance(); else error(); } void program() { // program lhs advance(); // get the first token stmt_list(); // do stmt list rule eat(END); // expecting $$ } void stmt_list() { // stmt_list lhs if(tok.type != END) { var(); // do var rule assign(); // do assign rule expr(); // do expr rule stmt_list_tail(); // do statement list tail } }

Parsing – Building Abstract Syntax Trees

As we parse, we can build the AST

  • unlike a parse tree, an AST isn’t cluttered with non-semantic information
  • e.g., semicolons, intermediate grammar steps
  • Homework is an example of a simple AST

Adding AST creation to Recursive Descent example

MyProgram* program() { advance(); p = new MyProgram(); stmt_list(p); eat(END); return p; }

void stmtList(MyProgram* p) { if(tok.type != END) { Variable* v = var(); Expression* e = expr(); Statement* s = new Statement(v, e); p->addStatement(s); stmt_list_tail(p); } }