Files
2025-02-Compiler/notes/4.md
2025-10-27 17:19:12 +09:00

2.3 KiB

Semantic Analysis

Even after passing the lexical and syntax analysis, there are still erros: correct usage of variables, objects, functions. Semantic Analysis ensures that the program satisfies a set of rules regarding the usage of programming constructs.

There are two main categories of semantic analysis:

  • Scopes
  • Types

Scope

Lexical scope is textual region in the program. Scope of an identifier is the lexical scope its declaration refers to

Symbol Tables

Symantic checks refer to properties of identifier in the program; it need an environment to store identifier info: symbol table.

In symbol tables each entry contains name of an identifier and additional info.

Implementing Symbol Tables

Five operations:

  • Insert Scope
  • Exit Scope
  • Find Symbol(x)
  • Add Symbol(x)
  • Check Scope(x)

We can build the symbol tables during parsing or after constructing the AST. The symbol tables should be generated before semantic analysis.

Function Declaration and Usage Types

  • Declare the functions before usage(cminus)
  • Can use functions before declaration(py)
  • Separate body declaration(C)

Scope Analysis

  • Generate Symbol Table and do Scope Analysis
  • Simultaneously

Types

  • Type Checking: A set of rules which ensures the type consistency of different construct in the program.
  • Type inferencing: fill missing type info.

Type Checking

Semantic checking to enforce the type safety of the program.

There are three types of types.

  • Statically typed
  • Dynamically typed
  • Untyped

Static Type Checking does not require additional type checking instructions at runtime. It guarantees that the executions are safe at compile time. But modern languages require both static and dynamic type checking (union, void pointer).

A type is a description of a set of values and a set of allowed operations on those values. Type expression is the description the possible types in the program. Type System defines types for language construct like nodes in AST.

Language usually have basic types aka primitive types. Using these types to build type expressions.

Type Comparison Implementation

There are two options:

  1. Implement a method Equals(T1, T2). It must compare type trees of T1 and T2. For OOP languages also need sub-types