A Simple Compiler
Spring 2011 Instructor: Mike Wilson
Spring 2011
Engineering
Adding Calculator: ac
Language has
23 variables, named a-z except for f,i,p. 2 types: integer and float
Declare variables as ia fb
Arithmetic operations
a=5 b = a + 3.2
Spring 2011
Engineering
Definition of ac Language
Our We
allowed b = a + 3.2 Is a = b + 3.2 also allowed? need a formal definition of the language
We
Spring 2011
Engineering
ac Grammar
Engineering
Grammar Conventions
Grammars consist of
Nonterminals --- usually capitalized Terminals --- usually lower case Special character --- signifies the empty string Special Start symbol --- where the grammar starts Productions
AaB Applied to a string by replacing an occurrence of the LHS by the RHS xAb becomes xaBb
Spring 2011
Engineering
Grammar Types
Linear Grammars
RHS contains no more than one nonterminal
Spring 2011
Engineering
Tokens in ac
Spring 2011
Engineering
Static Semantics of ac
Concerned
with types
All variables must be declared before use Each operation plus/minus/assign must have operands of the same type
If not the same, we can use widening but never narrowing
Spring 2011
Engineering
Runtime Semantics of ac
Addition/Subtraction
sense
Assignments
the RHS
Spring 2011
Engineering
Scanner for ac
Scanner Peek Advance ScanDigits Peek Advance Peek Peek ScanDigits Advance Peek Advance Advance
LexicalError
Figures from text: Crafting a Compiler CSE 431S: Translation of Computer Languages Spring 2011 10
Engineering
Recursive Descent
Stmt Peek Match Match Val Expr Peek Match Match Error
Figure from text: Crafting a Compiler CSE 431S: Translation of Computer Languages Spring 2011 11
Engineering
Engineering
Traversing an AST
Spring 2011
13
Engineering
EnterSymbol EnterSymbol
getID getID
EnterSymbol Error
LookupSymbol
Engineering
Spring 2011
15
Engineering
+: pop the top two items on the stack, add them, push the result
26 registers a-z sr: pop the top of stack, store in register r lr: push value of register r onto stack p: print top of stack, does not pop k: Pop top of stack, set precision to this many digits
Spring 2011
16
Engineering
Code Generation
Spring 2011
17