Semantic analysis
The semantic analyzer walks the AST and checks various semantic rules of the language, e.g. a variable must be declared before use or types of variables must be compatible in an expression. The semantic analyzer can also print out warnings if it finds a situation that can be improved. For the example expression language, the semantic analyzer must check that each used variable is declared because that is what the language requires. A possible extension (which is not implemented here) is to print a warning if a declared variable is not used.
The semantic analyzer is implemented in the Sema
class, which is performed by the semantic()
method. Here is the complete Sema.h
header file:
#ifndef SEMA_H #define SEMA_H #include "AST.h" #include "Lexer.h" class Sema { public: bool semantic(AST *Tree); }; #endif
The implementation is in the Sema.cpp
file. The interesting part is the semantic analysis, which is implemented using a visitor...