ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Compiler Construction
    DC-322
    Progress0 / 14 topics
    Topics
    1. Introduction to Interpreter and Compiler2. Compiler Techniques and Methodology3. Organization of Compilers4. Lexical Analysis5. Syntax Analysis6. Parsing Techniques7. Types of Parsers8. Top-Down Parsing9. Bottom-Up Parsing10. Type Checking11. Semantic Analyser12. Object Code Generation13. Code Optimization14. Detection and Recovery from Errors
    DC-322›Semantic Analyser
    Compiler ConstructionTopic 11 of 14

    Semantic Analyser

    8 minread
    1,326words
    Intermediatelevel

    Semantic Analyzer in Compilers

    The Semantic Analyzer is a crucial component in a compiler that performs semantic analysis on the intermediate representation (IR) of the program after the syntax analysis phase. While the syntax analyzer (parser) ensures that the program follows the syntactic structure of the language (grammar), the semantic analyzer ensures that the program makes sense according to the meaning of the constructs in the language.

    In other words, semantic analysis ensures that the program follows the rules of the language's semantics, such as proper variable declarations, type correctness, function call matching, and correct use of operators. It operates over the abstract syntax tree (AST) or an intermediate representation (IR) produced by the parser.

    Key Responsibilities of the Semantic Analyzer

    1. Symbol Table Management:

      • The semantic analyzer uses the symbol table, a data structure that holds information about variables, functions, classes, objects, types, scopes, etc. The symbol table is crucial for managing the scope of variables and their types, checking for redeclarations, and ensuring correct usage of identifiers.
      • The analyzer checks whether an identifier has been declared before use and whether it is being used within its scope.
    2. Type Checking:

      • The semantic analyzer ensures that the operands of expressions are of compatible types. For example, it will ensure that an integer is added to another integer, not to a string, or that a function is called with the correct types and number of arguments.
      • Type errors are reported at this stage if incompatible types are used in operations or assignments.
    3. Scope Checking:

      • It checks whether variables and functions are used within their valid scope. For example, variables should not be used before being declared, and variables declared in one scope should not be accessible outside that scope.
      • Scope rules govern which identifiers are visible to different parts of the program. The semantic analyzer ensures that the program adheres to the scope rules defined by the language.
    4. Declaration Checking:

      • Ensures that all variables and functions are properly declared before use. For example, it checks whether a function is called before being declared, whether the right number of arguments are passed to a function, and whether variables are assigned values before being used.
      • It also ensures that variables or functions are not redeclared within the same scope.
    5. Control Flow Analysis:

      • The semantic analyzer may also check for certain logical errors in the control flow, such as unreachable code (code that can never be executed) or uninitialized variables.
    6. Array Bounds Checking:

      • In some compilers, the semantic analyzer also checks array bounds. For example, when accessing an array element, the index must fall within the valid range of indices. If an index is out of bounds, a semantic error is reported.
    7. Function and Method Checks:

      • It ensures that functions or methods are invoked with the correct number and types of arguments.
      • It also checks that the return type of a function matches the expected type as defined in the function's declaration.
    8. Checking for Undefined Behavior:

      • The semantic analyzer can also look for potential logical errors that are not syntactically incorrect but may lead to undefined behavior, such as using a pointer before initializing it or dividing by zero.

    Phases of Semantic Analysis

    1. Symbol Table Construction:

      • After parsing, the semantic analyzer constructs or updates the symbol table with information about variables, functions, types, constants, and their scopes. The symbol table ensures that the program's symbols are used consistently throughout the code.
      • During this phase, the compiler detects undeclared variables, variable redeclarations, and incorrect usage of symbols.
    2. Type Checking:

      • Type checking verifies that expressions, assignments, and function calls adhere to the rules of the language's type system. If an expression expects an integer but receives a string, a type error is raised.
      • The analyzer checks types for operations, such as verifying that the operands of arithmetic operations are of numeric types and that function calls match the function signatures.
    3. Scope Analysis:

      • The semantic analyzer checks the program's scope rules. It makes sure that variables are used within their declared scope and that shadowing (when a local variable hides a global variable) is handled appropriately.
      • It also ensures that variables are initialized before they are used.
    4. Control Flow and Reachability Analysis:

      • The analyzer performs checks on control flow, ensuring that code paths that are unreachable or redundant are flagged as errors.
      • It also verifies that variables are not accessed before being initialized.
    5. Error Reporting:

      • If any semantic error is found during the analysis (e.g., undeclared variable, incompatible types in an operation, invalid function arguments), the semantic analyzer generates error messages.
      • These messages help the programmer identify where the semantic errors are in the code.

    Example: Semantic Analysis in Action

    Consider the following C-like program:

    int x = 10;
    float y = 20.5;
    int z = x + y;
    
    1. Symbol Table Construction:

      • The symbol table will contain entries for x (type int), y (type float), and z (type int).
    2. Type Checking:

      • The operation x + y involves an integer and a float. Depending on the language's type system, either implicit type casting may occur (promoting x to a float) or a type error may be raised. If implicit conversion is not allowed, this would result in a type error.
    3. Scope Checking:

      • x, y, and z are all used within the correct scope since they are all declared in the global scope.
    4. Error Reporting:

      • If the program contained an undeclared variable, such as trying to use a variable a that was not declared earlier, the semantic analyzer would generate an error message like "Variable a is undeclared."

    Example of Semantic Errors

    Here are some common semantic errors that the semantic analyzer would catch:

    1. Undeclared Variable:

      int x = y + 10; // Error: 'y' is undeclared
      
      • The semantic analyzer would check that y has been declared before being used, resulting in an error if it has not.
    2. Type Mismatch:

      int x = "Hello"; // Error: Cannot assign a string to an integer
      
      • The semantic analyzer would ensure that the types match for assignments and raise an error if there is a mismatch.
    3. Function Call Errors:

      int sum(int a, int b) { return a + b; }
      sum(10, "Hello"); // Error: Argument 'b' should be an integer, not a string
      
      • The semantic analyzer would check that the arguments passed to sum() match the function's signature and types.
    4. Uninitialized Variable:

      int x;
      int y = x + 5; // Error: 'x' is used before being initialized
      
      • The semantic analyzer would detect that x is being used without being initialized first.
    5. Unreachable Code:

      return 0;
      int x = 10; // Error: Code after 'return' is unreachable
      
      • The semantic analyzer detects that the code after the return statement is unreachable.

    Data Structures Used in Semantic Analysis

    1. Symbol Table:

      • The symbol table stores information about variables, functions, types, and scopes. It is crucial for checking declarations, types, and scope rules.
    2. Abstract Syntax Tree (AST):

      • The AST, which is generated by the syntax analyzer, is used by the semantic analyzer to traverse the program's structure and perform checks on operations and expressions.
    3. Type System:

      • The type system defines the rules for how types interact (e.g., what types can be added together, what types can be passed as function arguments, etc.). The semantic analyzer refers to the type system to ensure that operations respect these rules.

    Conclusion

    The semantic analyzer plays a vital role in the compilation process by ensuring that the program is semantically correct. While the syntax analyzer ensures the program's structure is valid, the semantic analyzer makes sure the program's meaning aligns with the language's rules. By performing checks on types, scopes, declarations, and control flow, the semantic analyzer helps prevent logical and runtime errors, contributing to the overall correctness and reliability of the program.

    Previous topic 10
    Type Checking
    Next topic 12
    Object Code Generation

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,326
      Code examples0
      DifficultyIntermediate