Lec 03 TPL
Lec 03 TPL
Lec 03 TPL
Describing Syntax
Topics
• Introduction
• The General Problem of Describing Syntax
• Formal Methods of Describing Syntax
– BNF
– Context-Free Grammars
– Derivation
– Parse Trees
– Syntax Diagrams
1-5
The General Problem of Describing Syntax:
Terminology
1-6
The General Problem of Describing Syntax:
Terminology
1-7
The General Problem of Describing Syntax:
Terminology
• Recognizers
– A recognition device reads input strings over the
alphabet of the language and decides whether
the input strings belong to the language
– Example: syntax analysis part of a compiler
• Generators
– A device that generates sentences of a language
– One can determine if the syntax of a particular
sentence is syntactically correct by comparing it
to the structure of the generator
https://www.tutorialspoint.com/compiler_design/compiler_design_syntax_analysis.htm 1-10
BNF and Context-Free Grammars
– CFG
expression identifier | number | - expression
| ( expression )
| expression operator expression
operator + | - | * | /
– BNF
expression identifier | number | - expression
| ( expression )
| expression operator expression
operator + | - | * | /
<stmt> <single_stmt>
| begin <stmt_list> end
• A derivation
– is a repeated application of rules, starting with
the start symbol and ending with a sentence (all
terminal symbols)
– show how to generate a syntactically valid string
1-19
Parse Tree
<stmts>
<stmt>
<var> = <expr>
a <term> + <term>
<var> const
b
Copyright © 2015 Pearson. All rights reserved. 1-20
Ambiguity in Grammars
• A grammar is ambiguous if and only if it generates a sentential
form that has two or more distinct parse trees
<expr>
<expr> - <term>
const const
<expr> + const
<expr> + const
const
Copyright © 2015 Pearson. All rights reserved. 1-23
Unambiguous Grammar for Selector
• C++ if-then-else grammar
<if_stmt> -> if (<logic_expr>) <stmt>
| if (<logic_expr>) <stmt> else <stmt>
AMBIGUOUS!!!
1-28