130 likes | 244 Views
C H A P T E R T W O. Syntactic Analysis. Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan. Syntactic Analysis:. Lexical Analysis Token Stream Remove comments and white space Classify tokens by type Token Stream Syntactic Analysis
E N D
C H A P T E R T W O Syntactic Analysis Programming Languages – Principles and Paradigms by Allen Tucker, Robert Noonan
Syntactic Analysis: • Lexical Analysis Token Stream • Remove comments and white space • Classify tokens by type • Token Stream Syntactic Analysis • Define the structure of the elements of a program: • Expressions • Assignments • Loops, conditionals and other blocks. • The whole enchilada • Detect errors • Create a parse
A Concrete Syntax for Assignments and Expressions Figure 2.7 Note that Expressions can be recursively defined Expression and Term establish precedence for operators
Parse Tree for the Expression x+2*y Figure 2.8 Traversing the parse tree in an in-order sequence defines the order of evaluation. An Expression in parentheses becomes a Factor, changing the order of evaluation.
Ambiguity: A grammar is ambiguous if it permits a string to be parsed into two or more different parse trees. AmbExp Integer | AmbExp – AmbExp Consider the program fragment 2 – 3 – 4
Two Different Parse Trees for the AmbExp 2 – 3 – 4 Figure 2.10 (2 – 3) - 4 2 – (3 – 4)
An Ambiguous If Statement Figure 2.11 if (x<0) if (y<0) y = y – 1; else y = 0;
The “Dangling Else” Grammatical Ambiguity Figure 2.12
Extended BNF: EBNF simplifies the specification of recursion in grammar rules. Expression Term | Expression + Term | Expression – Term Term Factor | Term * Factor | Term / Factor Expression Term { [ + | - ] Term } * Term Factor { [‘*’ | / ] Factor } *
EBNF-Based Parse Tree for the Expression x+2*y Figure 2.13
Extended BNF: EBNF adds optional symbols on the right hand side of rules. Conditional if ( Expression ) Statement { else Statement } opt
Next time… Linking Syntax And Semantics