pl9ch3 Backup
pl9ch3 Backup
Describing Syntax
and Semantics
ISBN 0-321-49362-1
Chapter 3 Topics
• Introduction
• The General Problem of Describing Syntax
• Formal Methods of Describing Syntax
• Attribute Grammars
• Describing the Meanings of Programs:
Dynamic Semantics
1-4
The General Problem of Describing
Syntax: Terminology
1-6
Scanning Fortran
← This is an identifier
← This is a loop
1-7
Formal Definition of Languages
• 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
- Detailed discussion of syntax analysis appears in
Chapter 4
• 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
1-9
Extending Regular Expressions
1-10
What is a grammar?
1-11
BNF and Context-Free Grammars
• Context-Free Grammars
– Developed by Noam Chomsky in the mid-1950s
– Language generators, meant to describe the
syntax of natural languages
– Define a class of languages called context-free
languages
1-13
BNF Fundamentals
• In BNF, abstractions are used to represent classes of syntactic
structures--they act like syntactic variables (also called nonterminal
symbols, or just terminals)
1-17
Example Grammar - 2
<program> → <stmts>
<stmts> → <stmt> | <stmt> ; <stmts>
<stmt> → <var> = <expr>
<var> → a | b | c | d
<expr> → <term> + <term> | <term> - <term>
<term> → <var> | const
<stmts>
<stmt>
<var> = <expr>
a <term> + <term>
<var> const
b
Copyright © 2009 Addison-Wesley. All rights reserved. 1-21
Another Derivation Example
1-22
Parse Tree
1-23
Ambiguity in Grammars
<expr> <expr>
<expr>
<expr> - <term>
const const
Copyright © 2009 Addison-Wesley. All rights reserved. 1-26
Example: Is it IF-THEN or IF-THEN-ELSE?
1-27
Example: Is it IF-THEN or IF-THEN-ELSE?
1-28
Example: Is it IF-THEN or IF-THEN-ELSE?
(Ambiguity removed)
1-29
Associativity of Operators
<expr>
<expr>
<expr> + const
<expr> + const
const
Copyright © 2009 Addison-Wesley. All rights reserved. 1-30
Extended BNF
• BNF
<expr> → <expr> + <term>
| <expr> - <term>
| <term>
<term> → <term> * <factor>
| <term> / <factor>
| <factor>
• EBNF
<expr> → <term> {(+ | -) <term>}
<term> → <factor> {(* | /) <factor>}
• Syntax
<assign> -> <var> = <expr>
<expr> -> <var> + <var> | <var>
<var> A | B | C
• actual_type: synthesized for <var>
and <expr>
• expected_type: inherited for <expr>
<expr>.actual_type ← <var>[1].actual_type
<expr>.actual_type =? <expr>.expected_type
1-39
Example: Derivation of Attributes
1-40
Summary