Semantic analysis
The semantic analyzer walks the AST and checks for various semantic rules of the language; for example, 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 sematic analyzer must check that each used variable is declared, because that is what the language requires. A possible extension (which will not be implemented here) is to print a warning message if a declared variable is not used.
The semantic analyzer is implemented in the Sema
class, and semantic analysis 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...