Java Reference
In-Depth Information
set of conditions on the values of the attributes in A(X 0 ) [A(X 1 ) [A(X 2 ) [[A(X n )
that further constrain an application of the production. The derivation of a sentence in the
attribute grammar is satisfied if and only if the context-free grammar is satisfied and all
conditions are true.
4.8.3 j--Examples
We now look at how the semantics for some of the constructs in j-- can be expressed using
attribute grammars. Let us first consider examples involving just synthesized attributes.
Semantics of literals involves just the synthesis of their type. This can be done using a
synthesized attribute type:
literal ::= <int_literal>
type(literal) int
j <char_literal>
type(literal) char
j <string_literal>
type(literal) String
Semantics of a multiplicative expression involves checking the types of its arguments making
sure that they are numeric (integer), and synthesizing the type of the expression itself. Hence
the following attribute grammar.
multiplicativeExpression ::= unaryExpression 1
f * unaryExpression 2 g
condition: type(unaryExpression 1 ) = int and type(unaryExpression 2 ) = int
type(multiplicativeExpression) int
Now, consider a j-- expression x*5 . The variable x must be of numeric ( int ) type. We
cannot simply synthesize the type of x to int , but it must be synthesized elsewhere, that
is, at the place where it is declared, and inherited where it is used. The language semantics
also require that the variable x be declared before the occurrence of this expression. Thus,
we must inherit the context (symbol table) that stores the names of variables and their
associated types, so we can perform a lookup to see if the variable x is indeed declared.
The attribute grammar below indicates how we synthesize the context for variables at the
place where they are declared and how the context is inherited at the place the variables
are used.
localVariableDeclarationStatement ::= type variableDeclarators ;
foreach variable in variableDeclarators
add(context, defn(name(variable), type))
variableDeclarator ::= <identifier> [ = variableInitializer]
name(variableDeclarator) <identifier>
primary ::= . . .
j variable
defn lookup(context, name(variable))
if defn = null
error(``Cannot nd variable '' + name(variable))
else
type(primary) type(defn)
 
Search WWH ::




Custom Search