You are on page 1of 6

Compiler Construction

CFG EXAMPLES
ANUM ALEEM
Context-Free Grammars (CFG)

Context-Free Grammars (CFG)

 The syntax of most programming languages is specified using Context-


Free Grammars (CFG).
 Context- free syntax is specified with a four tuple grammar G=(S,N,T,P)
where
S is the start symbol (non terminal)
N is a set of non-terminal symbols that will be substituted by
terminals
T is set of terminal symbols or words that can’t be substituted
P is a set of productions or rewrite rules
 Parsing is the process of discovering a derivation for some sentence of a
language. The mathematical model of syntax is represented by a grammar
G. The language generated by the grammar is indicated by L(G)
2
 For example, the Context-Free Grammar for arithmetic expressions is
1. goal  expr
2. expr  expr op term | term
3. term  number | id
4. op  + | –

For this CFG,


S = goal
T=
{ number, id}
N = { goal,
expr, term,
op}
P = { 1, 2, 3,
3
4} i.e., all the
above 4
 Example: Given the above CFG, we can derive sentence x+2-y by
repeated substitution.
Productions Result
goal
goal  expr expr
expr  expr op term expr op term
term  id expr op y
op  - expr – y
expr  expr op term expr op term – y
term  number expr op 2 – y
op  + expr + 2 – y
expr  term term + 2 – y
term  id x+2–y

4
Production Rules Results

1. goal  expr goal  expr


2. expr  expr op term | term expr  expr op term term
3. term  number | id termnumber | id
4. op  + | –  expr op y
op  -
expr - y
expr  expr op term - y
termnumber (2) | id
expr  expr op 2 - y
op  +
 expr + 2 - y
expr  term
termnumber | id

x+2-y
Class Activity

Learn by practice:
x+3-y+z
1. goal  expr
2. expr  expr op term | term
3. term  number | id
4. op  + | –

You might also like