Download Summary

Transcript
The Frontend
Semantic analysis
The semantic analysis ensures that the code does not violate the language type
system by means of a symbol table. This table stores, among other things, mappings
between identifiers (symbols) and their respective types. An intuitive approach for
type checking is to perform it after parsing by traversing the AST while gathering
information about types from the symbol table.
Clang, on the other hand, does not traverse the AST after parsing. Instead, it
performs type checking on the fly, together with AST node generation. Let us go
back to the min.c parsing example. In this case, the ParseIfStatement function
invokes the semantic action ActOnIfStmt to perform semantic checking for the if
statement, emitting diagnostics accordingly. In lib/Parse/ParseStmt.cpp, line
1082, we can observe the transfer of control to allow the semantic analysis to happen:
…
return Actions.ActOnIfStmt(IfLoc, FullCondExp, …);
…
To aid the semantic analysis, the DeclContext base class contains references from the
first to the last Decl node for each scope. This eases the semantic analysis because,
to perform symbol lookup of name references and check both the symbol type and
whether the symbol actually exists, the semantic analysis engine can find the symbol
declarations by looking into AST nodes derived from DeclContext. Examples of such
AST nodes are TranslationUnitDecl, FunctionDecl, and LabelDecl.
Using the min.c example, you can use Clang to dump declaration contexts as
follows:
$ clang -fsyntax-only -Xclang -print-decl-contexts min.c
[translation unit] 0x7faf320288f0
<typedef> __int128_t
<typedef> __uint128_t
<typedef> __builtin_va_list
[function] f(a, b)
<parameter> a
<parameter> b
Note that only declarations inside TranslationUnitDecl and FunctionDecl
appear on the results, since they are the only nodes that derive from DeclContext.
[ 98 ]