Coursenotes Lesson1
Coursenotes Lesson1
A program that
translates a
program from a
source language into
a target language!
What is a Compiler?
Target
Interpreter
Source
What is a Compiler?
temp =v[k]; TEMP =V(K)
High-level Language v[k] =v[k+1];
v[k+1] =temp;
V(K) =V(K+1)
V(K+1) =TEMP
C/Java Compiler Fortran Compiler
lw $to, 0($2)
Assembly Language lw
sw
$t1,
$t1,
4($2)
0($2)
sw $to, 4($2)
MIPS Assembler
0000 1001 1100 0110 1010 1111 0101 1000
Machine Language 1010 1111 0101 1000 0000 1001 1100 0110
1100 0110 1010 1111 0101 1000 0000 1001
0101 1000 0000 1001 1100 0110 1010 1111
How Compilers Work
Request Scanner Get a
a token token
Start Parser
Front End: Semantic Semantic
Action Checking Error
Analysis of
program syntax
and semantics Intermediate
Representation
157.669 produces FLOATCONST with a value of 157.669
Name How Compilers Work
found in
symbol
table Show
Fails
semantic
error
Name
not
Lookup found Put in Do Passes Generate Get Done
variable symbol semantic next
name table checks code token
Compiler Parts
Token buffer
niam
Keyword: main
Parser Quiz
Check all the statements that
Grammar Rules: are grammatically correct
given the grammar rules.
• E -> E + E a + b
• E -> E * E
• E -> -E a + b * c
• E -> (E) a b + c
• E -> id
a + b + a c
Parser
During parsing?
(Syntax checking) Semantic actions
• What are semantic
• Tokens are matched and actions?
consumed by parser
• Symbol tables
• Variables have attributes Semantic
• Declaration attached checks
attributes to variables
Symbol Table
int a,b; →
Declares a and b, Within current scope, Type integer
Use of a and b now legal
Basic Symbol Table
Name Type Scope
a int ”main”
b int ”main”
Semantic Actions
Enter variable Look up Do binding of
declaration into variables in looked-up variables
symbol table symbol table (scoping rules, etc.)
id2 id1 1 3
#do-decl
⇒ id2 1 3
id1
id3 1 3
type
Semantic Actions
Two types of semantic actions:
Translation:
Checking: generate
binding, type temporary values,
compatibility, propagate them to
scoping, etc keep semantic
context
Scanner
Start Parser
Semantic Semantic
Analysis Error
Full Compiler
Structure Intermediate
Representation
Code Assembly
Generation Code