Semantic Analysis
What Is Semantic Analysis ?

After syntax analysis confirms that the structure of your code is valid, semantic analysis checks that the code also has meaning.
Example:
int x = "hello"; // Syntax is fine, but semantically invalid
Here, the parser is okay with the structure, but the semantic analyzer will raise an error because you’re assigning a string to an integer.
What Does Semantic Analyzer Check ?

- Type Checking
- Are values used with the correct data types?
- Example:
int x = 5 + true;→ invalid in most languages
- Scope Resolution
- Are variables declared before use?
- Is a variable accessed within its valid scope?
- Function Signatures and Calls
- Are functions called with the right number and type of arguments?
- Variable Declarations and Usage
- Prevents using undeclared variables
- Checks for duplicate declarations
Internal Working of Semantic Analysis
Semantic analysis takes the Abstract Syntax Tree (AST) generated during syntax analysis and verifies whether the program is logically meaningful.

Semantic analysis walks through this AST and attaches additional information such as variable types, scopes, function signatures, expression types. To perform these checks efficiently, the compiler maintains a symbol table alongside the AST.
AST with Semantic Information

During semantic analysis, the AST becomes enriched with semantic details.
For example:
- variables get associated with their data types
- expressions are checked for type compatibility
- function calls are validated against parameter definitions
In the diagram above:
x : intmeans variablexhas integer typesum(x : int, y : int)verifies argument typesBinaryExpr (a + b : int)confirms the expression result type
This annotated AST helps later compiler phases like optimization and code generation.
Symbol Table

The symbol table is a compiler data structure that stores information about identifiers used in the program.
It typically keeps track of:
- variable names
- data types
- scopes
- function definitions
- parameters
- memory-related metadata
For example:
xbelongs to themainscopeaandbare parameters ofsumsumis a function returningint
Semantic analysis continuously consults the symbol table while traversing the AST to validate declarations and resolve identifiers correctly.
Conclusion
- Semantic analysis ensures code is meaningful, using the AST.
- It uses a symbol table to track declarations, scopes, and types
- Errors at this stage are not structural but meaning-related