Table of Contents
hide
Introduction
- Semantic analysis is performed by the Semantic Analyzer.
Definition
- Semantic analysis is the third phase of a compiler that verifies the semantic errors (undeclared identifiers, type mismatches, duplicate declarations, etc.) of the valid parse tree generated during the syntax analysis phase to ensure it is logically correct.
Characteristics
- Semantic analysis takes a structured program [parse/abstract syntax tree and a symbol table (partial) generated by the syntax analyzer phase] as input and produces an annotated syntax tree (The syntax tree is enriched with extra or additional or semanic information such as data types, scope, and memory details in comparision to the original syntax tree to explain or describe it more clearly.)along with an updated symbol table (complete) and logical or semantic errors, if any, as output.
Original Syntax tree: shows only the structure
Annotated Syntax tree: shows structure + meaning
program statement: x=10+5
=
/ \
x + (Original Syntax Tree)
/ \
10 5
———————————————————
= (type: int)
/ \
x:int + (type: int) ( Annotated Syntax Tree)
/ \
10:int 5:int
- The code generator phase (after the semantic analysis phase) uses the annotated syntax tree as input.
- Semantic Analysis ensures the correct use of identifiers, correct data types, correct scope rules, correct function usage, etc.
- Semantic Analyser does –
- Type Checking – It ensures operations are performed on compatible data types. For example –
- int a = 10 + 5; (correct)
- int a = “hello India”; (incorrect)
- Type Conversion (Type Casting) – It ensures implicit or explicit type conversion. For example-
- Type Checking – It ensures operations are performed on compatible data types. For example –
int a; float b = 10.5;
a = b; // float → int (checked)
-
- Scope Resolution – It ensures variables are used within their declared scope. For example –
{
int x;
}
x = 5; // x out of scope, i.e. x is declared locally but used globally.
-
- Declaration Checking – It checks that variables/functions are declared before use. For example:
x = 10; // x not declared earlier/before
int a; int a; // Multiple declarations of a variable
-
- Function Checking- It verifies the correct number of arguments, the correct argument types, correct return type used in a function. For example –
int sum(int a, int b);
sum(5); // mismatch no. of argument
- Semantic analyzer also builds and updates the symbol table, which stores variable names, data type, scope, memory location(offset)/address, etc. For example –
Symbol Table of the above example
Identifier Type Scope Memory
x int local 200
sum function global 500
![]()
0 Comments