Performing semantic analysis
The parser that 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.
These are some of the tasks a semantic analyzer must perform:
- For each declaration, the semantic analyzer must check if the used name has not been declared elsewhere already.
- For each occurrence of a name in an expression or statement, the semantic analyzer must check that the name is declared and that the desired use fits the declaration.
- For each expression, the semantic analyzer must compute the resulting type. It is also necessary to compute if the expression is constant and if so, which value...