Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Semantic Analysis

Analysis

The provided information describes the semantic analysis phase of a compiler for a language with
classes, functions, and variables. The semantic analysis focuses on ensuring the program adheres
to the language's rules and identifying any errors related to variable types, function calls, and
class inheritance.

Key Semantic Rules:

Symbol Tables:
A symbol table is used to store information about identifiers (variables, functions, classes) such
as their type and scope.
Separate symbol tables are created for the global scope, each class, and each function.
Inheriting classes use the symbol table of their parent class.
Type Checking:
Expressions, assignments, and return statements must involve compatible data types.
Function calls must use the correct number and type of arguments according to the function's
declaration.
Array accesses must use integer expressions as indices.
Circular Class Dependencies:**
Inheritance hierarchies cannot form circular dependencies (e.g., class A inherits from B, class B
inherits from A).
Member Access:
The dot operator (.) can only be applied to variables of a class type.
The right operand of the dot operator must be a member of the class on the left.

Design

The semantic analysis is typically implemented in two phases:

1. Symbol Table Creation:


During AST traversal, semantic actions are triggered to:
Create a symbol table for the global scope.
Create symbol table entries for classes, functions, and variables.
Link inherited class symbol tables.
Check for multiply declared identifiers within the same scope.
Ensure all declared member functions have corresponding definitions.

2. Type Checking and Semantic Checks:


AST traversal triggers further semantic actions to perform checks like:
Verifying type compatibility in expressions, assignments, and return statements.
Ensuring identifiers are defined in the appropriate scope.
Validating function calls with argument numbers and types.
Checking array access with integer indices.
Detecting circular class dependencies.
Confirming the dot operator is used on class variables with valid members.

Implementation Tools

Common tools and libraries used for semantic analysis include:

Programming Languages: C++, Java, Python


Parser Generators: Bison, ANTLR
Symbol Table Libraries: Coco, Gnu Libavl

Example Symbol Table

The image depicts an example symbol table structure. It likely shows entries for various classes,
functions, and variables along with their types and scope information. This helps visualize how
the symbol table stores information for the compiler to perform semantic analysis.

You might also like