![]() |
VOOZH | about |
Semantic Analysis is the third phase of a compiler, performed after syntax analysis. It ensures that a program is semantically correct, meaning it follows the logical rules of the programming language.
While syntax analysis checks the structure of the program, semantic analysis checks its meaning, such as correct use of variables, types, and expressions.
It works on the parse tree (or AST) and symbol table to:
During this phase, the syntax tree is enriched with type and scope information, forming an Annotated Syntax Tree, which is used in later stages like intermediate code generation.
Even if a program is syntactically correct, it may still be incorrect logically.
Example:
int a;
a = "hello"; // syntactically correct but semantically wrong
Syntax is valid, but type rules are violated.
Thus, semantic analysis ensures:
The Semantic Analyzer performs the following major tasks:
Ensures that operands of operators are of compatible types.
Example:
int x = 10;
float y = x + 2.5; // valid
Invalid case:
int x = "abc"; // type mismatchDetermines the region in which a variable is accessible.
Example:
{
int x = 10;
}
x = 20; // error: x out of scope
Automatically converts data types when required.
Example:
float x = 10.5;
float y = x * 2; // 2 → 2.0 (implicit conversion)
Ensures:
Example:
int add(int a, int b);
add(5); // error: missing argument
Ensures that all labels used in the program are properly declared and referenced.
Ensures proper use of control flow statements.
Examples:
Semantic analysis uses the symbol table to:
Semantic errors are detected after syntax analysis. Common errors include:
int x = "hello";x = 10; // not declaredint x;
int x; // redeclaration
int while = 5;int add(int a, int b);
add(1); // wrong number of arguments
Examples:
During semantic analysis, additional information is added to the syntax tree.
Example:
x = a + b;After annotation:
This helps in intermediate code generation
float x = 10.1;
float y = x * 30;
Steps: