Performing semantic analysis
The parser we constructed in the previous section only checks the syntax of the input. The next step is to add the ability to perform semantic analysis. In the calc example in the previous chapter, the parser constructed an AST. In a separate phase, the semantic analyzer worked on this tree. This approach can always be used. In this section, we will use a slightly different approach and intertwine the parser and the semantic analyzer more.
What does the semantic analyzer need to do? Let’s take a look:
- For each declaration, the names of variables, objects, and more must be checked to ensure they have not been declared elsewhere.
- For each occurrence of a name in an expression or statement, it must be checked that the name is declared and that the desired use fits the declaration.
- For each expression, the resulting type must be computed. It is also necessary to compute if the expression is constant and if so, which value it has. ...