Compilation 2016
Parsing Tools
Aslan Askarov aslan@cs.au.dk
Parsing Tools Aslan Askarov aslan@cs.au.dk Today: using parsing - - PowerPoint PPT Presentation
Compilation 2016 Parsing Tools Aslan Askarov aslan@cs.au.dk Today: using parsing tools to parse 3 simple languages 1. Language of arithmetic expressions 2. Straight-line commands 3. Straight-line commands with alternative syntax Language of
Aslan Askarov aslan@cs.au.dk
expr -> id | num | expr op expr | ( expr )
datatype aexp = Id of string | Number of int | Op of binop * aexp * aexp and binop = Plus | Minus | Times | Div
Example: 1 + (2*x- 3) CFG: ML code:
ML declarations to be copied verbatim into the generated parser %% parser declarations (nonterminals, terminals, precedence, etc) %% grammar rules .grm file format parser generator .grm.sml file that implements an LR parser .grm.desc file that helps debug grammar conflicts make sure to use %verbose declaration lexer the rest of the compiler
(7 - 5) - 3 7 - (5 - 3)
Say that operator MINUS has left associativity … right associativity
error
also a possibility
associativity or error, but not right associativity
Operators Associativity Arithmetic minus, division Left Arithmetic addition, multiplication Left/Right a+b+c = (a+b)+c = a+(b+c) Assignment in C: x = y = 5 Right y is assigned the value of 5; x is assigned the updated value of y Arithmetic exponentiation 2^1^3 Right 2^1^3 = 2^ (1^3) = 2 not the same as (2^1)^3 = 8 Comparison operators 2 < 3 < 4 Non-associative parse error
5 3
left-associative parse tree
3
7 - 5 - 3
right-associative parse tree
Scenario 1
exp : exp . MINUS exp exp : exp MINUS exp . (reduce by rule 4)
stack: input string exp MINUS exp exp MINUS
Scenario 1
exp : exp . MINUS exp exp : exp MINUS exp . (reduce by rule 4)
stack: input string exp MINUS exp exp MINUS shift action Scenario 2 stack: input string exp MINUS exp exp MINUS
Scenario 1
exp : exp . MINUS exp exp : exp MINUS exp . (reduce by rule 4)
stack: input string exp MINUS exp exp MINUS shift action Scenario 2 stack: input string exp exp MINUS reduce action
%right directive
parser directives in the .grm file
… cmd -> id := aexp | if aexp then cmd | if aexp then cmd else cmd | ( cmds ) cmds -> cmd | cmd ; cmds … and cmd = Assign of id * aexp | If of aexp * cmd * cmd option | Cmds of cmd list
CFG: ML code:
Example: y:=1 + (2*x- 3); if x then if y then z := 20 else y := 2
… cmd -> id := aexp | if aexp then cmd fi | if aexp then cmd else cmd fi | ( cmds ) cmds -> cmd | cmd ; cmds … and cmd = Assign of id * aexp | If of aexp * cmd * cmd option | Cmds of cmd list
CFG: ML code:
Example: if x then if y then z := 20 else y := 2 fi fi
extra keyword to mark the end of IfThenElse same AST new grammar
your own PL and the language features are not yet stable (unlike this course)
grumpy
Example: if x then if y then z := 20 else y := 2 fi fi
associativity
source of conflicts
syntax