Docsity

Lecture Notes for CPSC 326 (Spring 2013) - Final Exam Preparation, Study notes of Programming Languages

Partial preview of the text

Download Lecture Notes for CPSC 326 (Spring 2013) - Final Exam Preparation and more Study notes Programming Languages in PDF only on Docsity!

Today ...

  • Final exam overview
  • Semantic analysis (cont.)

Final Exam

Basics

  • Wed May 8, 10:30–12:30 (HK 301)
  • Closed book, notes, computer, etc.
  • 20% of final grade
  • likely around 8 questions
  • Cummulative ... split between:
    • Haskell, Prolog, language implementation, big ideas (reading)

Dealing with left-associative operators

  • One approach is to rewrite the AST after parsing
    • similar to applying rotations in Red-Black or AVL trees
  • Another is to modify the grammar and recursive-descent parser
  • ... to construct the correct AST

Example:

e → val ( ÷ val )∗

  • for left-associative ops use iteration (Kleene star)
  • for right-associative ops use (tail) recursion

Expression* expr() { Expression* v1 = val(); advance(); while(tok.type() == DIV) { advance(); Expression* v2 = val(); v1 = new Div(v1, v2); } return v1; }

  • For instance: v1 = Num(40) v2 = Num(10), v1 = Div(Num(40), Num(10)) v2 = Num(2), v1 = Div(Div(Num(40), Num(10)), Num(2))

Operator precedence

  • Division (/) has higher precedence than addition (+)
  • For example:

2 + 3 / 4 ≡ 2 + (3 / 4) 2 / 3 + 4 ≡ (2 / 3) + 4

One solution: Encode precedence in the grammar

e → t ( ‘+’ t )∗

t → num ( ’/’ num )∗

  • This is equivalent to ... e → t e′ e′^ → ‘+’ t e′^ |  t → num t′ t′^ → ‘/’ num t′^ | 

Q: What is the parse tree for: 2 + 3 / 4?