SEMANTIC ANALYSIS

ADLAWAN VILLANUEVA SESCON MANGAWANG



SEMANTIC ANALYSIS

•se-man-tic: of or relating to meaning in language (Webster’s Dictionary)

•we have already tackled:

Lexical analysis: Source code to tokens. Parsing: Validate token conformity with grammar.

•Now we need to check if the code makes sense or (have correct meaning).



NEED FOR SEMANTIC ANALYSIS

• Lexically and syntactically correct programs may still contain __other errors.

• Lexical and syntax analyses are not powerful enough to ensure __the correct usage of variables, objects, functions, ...

• Semantic analysis: Ensure that the program satisfies a set of rules __regarding the usage of programming constructs (variables, __ __ __objects, expressions, statements)



SEMANTIC ANALYSIS PHASE

• The semantic analysis phase of a compiler:

○ connects variable definitions to their uses,

○ checks that each expression has a correct type,

○ translates the abstract syntax into a simpler representation suitable for generating machine code,

○ adds semantic information to the parse tree and builds the symbol table.



SEMANTIC RULES

• Examples of semantic rules:

○ Variables must be defined before being used,

○ A variable should not be defined multiple times,

○ In an assignment statement, the variable and the expression must have the same type,

○ The test expr. of an if statement must have boolean type,

○ Class definitions and inheritance relationship.



CATEGORIES OF SEMANTIC ANALYSIS

• 2 MAJOR CATEGORIES:

○ Semantic rules regarding types.

○ Semantic rules regarding scopes.



TYPES

• What is a type?:

○ The notion varies from language to language.

• Consensus.

○ A set of values.

○ A set of operation on those values.

• Classes are one instantiation of the modern notion of type.



TYPES AND OPERATIONS

• Certain operations are legal for values of each type.

○ It doesn’t make sense to add a function pointer and an integer in C.

○ It does make sense to add two integers.

○ But both have the same assembly language implementation!



TYPE SYSTEMS

• A language’s type system specifies which operations are valid for which types.

• The goal of type checking is to ensure that operations are used with the correct types.

○ Enforces intended interpretation of values, because nothing else will!



TYPE INFORMATION AND TYPE CHECKING

• Type Information: Describes what kind of values correspond to different constructs: variables, statements, expressions, functions, etc.

○ variables: int a; integer

○ expressions: (a+1) == 2 boolean

○ statements: a = 1.0; floating-point

○ functions: int pow(int n, int m) int = int, int

• Type Checking: Set of rules which ensures the type consistency of different constructs in the program.