Java Reference
In-Depth Information
statements without any concern about exactly how they are represented at the
source level.
A common way to organize the semantic analysis of a program is to
create a number of semantic analysis methods , one for each kind of AST
node. To understand the semantic analysis of a particular kind of construct (an
expression, or assignment, or call) you needmerely examine the corresponding
AST node's semantic analysis method.
Using the visitor approach we developed in Chapters 7 and 8, we can
factor all our semantic analysis into a number of specialized visitors, each
implementing a portion of the overall semantic analysis task. In this chapter
we shall focus on three aspects of semantic analysis:
type correctness , reachability
and termination ,and exceptions .
Type correctness is the essence of semantic analysis. We visit an AST node
and its children to verify that the types of all components conform to program-
ming language rules. Thus, in an if statement, the control expression must be
semantically valid and return a Boolean value. Because other structures may
have similar (or even identical) type rules, the visitor classes that implement
type correctness may share methods, leading to simpler and more reliable
analysis.
Reachability and termination analysis, as discussed below (Section 9.1.1),
determines whether a construct terminates normally (many do not!) and
whether a construct can be reached during execution. Java and C
require this
semantic analysis. Even languages such as C and C
++
, for which this analysis
is optional, benefit from enhanced error analysis.
Almost all modern programming languages include some form of excep-
tion handling. In analyzing expressions and statements, we must be aware
of the fact that constructs may throw an exception rather than terminate nor-
mally. Java requires accounting for all checked exceptions. That is, if a checked
exception is thrown (see Section 9.1.7), then it must either be caught in a catch
block or listed in a method's throw list.
To enforce this rule, we will accumulate the checked exceptions that can be
generated by a given construct. Each AST node that contains an expression or
statement will have a throwsSet field. This field will reference a set of exception
types. The throwsSet will be propagated as ASTs are analyzed. It will be used
when catch blocks, methods, and constructors are analyzed.
We will organize semantic analysis using the following visitors:
SemanticsVisitor is used to check that the type rules imposed on language
constructs are satisfied. This includes checking that control expressions
are Boolean-valued, that parameters have correct types in calls, that
expected types are returned from calls, and so forth. This analysis, often
called static semantics , is a necessary part of all compilers.
 
Search WWH ::




Custom Search