02 Chapter 03
02 Chapter 03
ISBN 0-321-19362-8
Syntax and Semantics
Learning Outcomes:
By the end of this module you will be able to:
1. describe the terms syntax and semantics of a programming
languages
2. describe and use BNF for describing PL syntax.
3. explain the differences among BNF, EBNF and attribute
grammars
4. outline techniques for describing dynamic semantics of
programming languages
• Introduction
• The General Problem of Describing Syntax
• Formal Methods of Describing Syntax
• Attribute Grammars
• Describing the Meanings of Programs:
Dynamic Semantics
1 class 5A{
2 static final int n = 3;
3 public static void main(int x){
4 if x > 0
5 n += x;
6 else n /= x;
7 }
8 }
• Low-level syntax
– for low-level language constructs like identifiers, numbers etc
– described using regular grammars, regular expressions or
syntax diagrams
– basis for lexers
• High-level syntax
– for language constructs like expressions, statements etc
– described using BNF/CFG (to be discussed shortly)
– basis for parsers
<stmt> <single_stmt>
| begin <stmt_list> end
<ident_list> ident
| ident, <ident_list>
<program> <stmts> L1
<stmts> <stmt>
| <stmt> ; <stmts>
<stmt> <var> = <expr>
<var> a L5
| b
| c
| d
<expr> <term> + <term> L9
| <term> - <term>
<term> <var>
| const L12
• Notice that:
– Every internal node is labeled
with a nonterminal
– Every leaf is labeled with a
terminal
• Sources of ambiguity
1. Operator precedence
• A grammar that does not specify enough hierarchical structure of
operator precedence is ambiguous
2. Operator associativity
• A grammar that does not specify enough hierarchical structure of
operator associativity is ambiguous
<expr> - <term>
const const
<expr>
<expr>
<expr> + const
<expr> + const
const
Copyright © 2004 Pearson Addison-Wesley. All rights reserved. 3-20
Discussion
• Two different derivations can have the same parse tree. T/F? Explain.
• Static semantics
– Deals with legal forms of programs
– Described using attribute grammars
• Dynamic semantics
– Deals with what programs mean or what they do
– Described using operational, axiomatic and denotational means
• Axiomatic semantics
– Uses mathematical logic (independent of a real or abstract machine)
– More suitable for language theorists
• Denotational semantics
– Uses mathematical functions (independent of a real or abstract
machine)
– More suitable for language theorists
• The process:
– Build a translator (translates source code to the machine code of an
idealized computer)
– Build a simulator for the idealized computer
• Examples
– VDL used to describe the semantics of PL/I
– SECD machine used to describe the semantics of Lisp