Академический Документы
Профессиональный Документы
Культура Документы
Syntax-directed translation
Regular Languages
{a nb n }
Grammar for:
{ww R }
for:
n n
L(G ) = {a b : n ! 0}
Regular Languages
Describes parentheses: (((( ))))
Leftmost derivation:
!1 2 3 ! 4 5 !
Rightmost derivation: !
S ! AB ! aaAB ! aaB ! aaBb ! aab
1 4 5 2 3
S ! AB ! ABb ! Ab ! aaAb ! aab
Grammar String Parse Trees
a a A a a A B b
Parse Trees Parse Trees
!
Sentential forms ! !
S ! AB A "aaA | # B "Bb | # S ! AB ! aaAB sentential
form
Partial parse tree S
! ! S ! AB
Partial parse tree S A B
A B a a A
Sometimes, derivation order doesn’t matter
Does it matter here? Parse Tree
Leftmost:
S ! AB ! aaAB ! aaB ! aaBb ! aab Grammar
Stm --> id := Exp
Exp --> num
Rightmost: Exp --> ( Stm, Exp )
S ! AB ! ABb ! Ab ! aaAb ! aab
String
S
Same parse tree a := ( b := ( c := 3, 2 ), 1 )
A B
a a A B b
! !
How about here? Syntax Directed Translation or Interpretation
CS453 Lecture Context Free Grammar Intro 23 CS453 Lecture Context Free Grammar Intro 24
MiniSVG Grammar Example Parse Tree for MiniSVG
CS453 Lecture Context Free Grammar Intro 25 CS453 Lecture Context Free Grammar Intro 26
Grammar Grammar
Stm --> id := Exp (1) exp --> exp * exp
Exp --> num (2) exp --> exp + exp
Exp --> ( Stm, Exp ) (3) exp --> NUM
String String
a := ( b := ( c := 3, 2 ), 1 ) 42 + 7 * 6
CS453 Lecture Context Free Grammar Intro 27 CS453 Lecture Context Free Grammar Intro 28
Example:
Parser Parser
input S "SS derivation
grammar derivation input
string S "aSb
aabb ?
S "bSa
S "#
Exhaustive Search
! !
Phase 2 S "SS | aSb | bSa | # S "SS | aSb | bSa | #
Phase 2
S ! SS ! SSS S ! SS ! SSS
S ! SS ! aSbS aabb S ! SS ! aSbS aabb
Phase 1 ! S ! SS ! bSaS S ! SS !!S
S ! SS S ! SS ! S
S ! aSb ! aSSb
S ! aSb S ! aSb ! aSSb
S ! aSb ! aaSbb
S ! aSb ! aaSbb
Phase 3
S ! aSb ! abSab
S ! aSb ! aaSbb ! aabb
S ! aSb ! ab
Extremely bad!!!
For general context-free grammars: Example Predictive Parser
(1) start -> mesh EOF
(2) mesh -> NUM nodelist NUM elemlist
(3a & b) nodelist -> ϵ | node nodelist
There exists a parsing algorithm (4) node -> NODE NUM REAL REAL // node_id, x, y
(5a & b) elemlist -> ϵ | elem elemlist
that parses a string | w | (6a) elem -> TRI NUM NUM NUM NUM // elem_id, 3 node ids
(6b) elem -> SQR NUM NUM NUM NUM NUM //elem_id,4 node ids
in time | w |3 void start() { switch(m_lookahead) {
case NUM: mesh(); match(Token.Tag.EOF); break;
default: throw new ParseException(…);
}}
void mesh() { switch(this.m_lookahead) {
case NUM: num_nodes = ((Num)m_lookahead).value; match(NUM);
nodelist();