120 likes | 169 Views
Explore parse trees, derivation, ambiguity, EBNF, BNF, syntax graphs, recursive descent, and more in computer science syntax analysis. Learn to build parsers effectively.
E N D
Syntax One - Hybrid CMSC 331
Parse Trees PS → P | P PS P → e | '(' PS ')' | '<' PS '>' | '[' PS ']' What’s the parse tree for this statement ? < [ ] [ < > ] >
Derivation for < [ ] [ < > ] > PS → P → < PS > → P PS > → < [ PS ] PS >’ → < [P] PS >’ → < [ e] PS > → <‘[ ] PS> → < [ ] P > → < [ ] [ PS ] > → < [ ] [ P] > → < [ ] [‘<PS > ] > → < [ ] [‘<P> ] >’ → < [ ] [<e’> ] > → < [ ] [ < > ] >
Ambiguity • Two parse trees for the same expression • Consider the following grammar String → String + String | String - String | DIGIT What are the two trees for 9 - 5 + 2
String String + DIGIT(2) DIGIT(9) - DIGIT(5) Parse Tree 1
String DIGIT(9) - String DIGIT(5) * DIGIT(2) Parse Tree 2
EBNF - Extended BNF • Like BNF except that • Non-terminals start w/ uppercase • Parens are used for grouping terminals • Braces {} represent zero or more occurrences (iteration ) • Brackets [] represent an optional construct , that is a construct that appears either once or not at all.
EBNF example Exp → Term { ('+' | '-') Term } Term → Factor { ('*' | '/') Factor } Factor → '(' Exp ')' | variable | constant
EBNF/BNF • EBNF and BNF are equivalent • How can {} be expressed in BNF? • How can ( ) be expressed? • How can [ ] be expressed?
EBNF for {} • X-> a { b } g • BNF • X -> a X’ • X’ -> b X’ | g • EBNF for [] • X-> a [b ] g • BNF • X -> a b g | a g
Syntax Graphs Terminal in circles Non- terminals in rectangles; Syntax Graphs - put the terminals in circles or ellipses and put the nonterminals in rectangles; connect with lines with arrowheads e.g., Pascal type declarations type_identifier ( identifier ) , constant .. constant
Recursive Descent • An easy way to build a parser • Example • Does work in the face of left recursion • Purge left recursion