Professional Documents
Culture Documents
Chapter 3
Describing Syntax & Semantics
Principles of Programming
Languages, Robert W.
Sebesta, (10th edition),
Addison-Wesley Publishing
Company
<stmt> → <single_stmt>
| begin <stmt_list> end
is generated by
An Example Derivation
<program> => <stmts> => <stmt>
=> <var> = <expr>
=> a = <expr>
=> a = <term> + <term>
=> a = <var> + <term>
=> a = b + <term>
=> a = b + const
Can you find a sentence with two possible parse trees in this
grammar?
As an example of a syntax rule that is difficult to specify with BNF, consider type
compatibility rules. In Java, for example, a floating-point value cannot be assigned to
an integer type variable, although the opposite is legal. Although this restriction can
be specified in BNF, it requires additional non-terminal symbols and rules. If all of the
typing rules of Java were specified in BNF, the grammar would become too large to be
useful, because the size of the grammar determines the size of the syntax analyzer.
As an example of a syntax rule that cannot be specified in BNF, consider the common
rule that all variables must be declared before they are referenced. It has been proven
that this rule cannot be specified in BNF
• Functions of the form I(Xj) = f(A(X0), ... , A(Xn)), for i <= j <= n, define
inherited attributes
• The first attributes to be evaluated are the synthetic attributes of the leaf
nodes: called intrinsic attributes: which might be values read-off the
symbol table, e.g. type values etc
<expr>.actual_type <var>[1].actual_type
<expr>.actual_type =? <expr>.expected_type
Assuming this three has already been constructed, how do we compute the attributes?
Attribute Grammars (continued)
A fully attributed parse tree
• Operational Semantics
– Describe the meaning of a program by executing
its statements on a machine, either simulated or
actual. The change in the state of the machine
(memory, registers, etc.) defines the meaning of
the statement
• To use operational semantics for a high-level
language, a virtual machine is needed
• This definition requires two auxiliary functions defined in the semantic world,
where Number x Number denotes the Cartesian product.
We need two syntactic domains for the language of numerals. Phrases in this language are mapped into the
mathematical domain of natural numbers. Generally we have one semantic function for each syntactic domain
and one semantic equation for each production in the abstract syntax. To distinguish numerals (syntax) from
numbers (semantics), different typefaces are employed. Note the compositionality of the definition in that the
value of a phrase “N D” is defined in terms of the value of N and the value of D.
- Principles of Programming languages
- Principles of Programming languages
Question
• Write a denotational semantics mapping
function for the following statements:
a. Ada for
b. Java do-while
c. Java Boolean expressions
d. Java for
e. C switch