Compiler Design and Construction - Old Questions

Question Answer Details

5.  What is semantic analysis? Why is it necessary to perform semantic analysis? Explain.

6 marks
Asked in 2074

Answer

AI Generated Answer

AI is thinking...

Official Answer

Semantic Analysis is the third phase of compiler. Semantic Analysis makes sure that declarations and statements of program are semantically correct. It is a collection of procedures which is called by parser as and when required by grammar. Both syntax tree of previous phase and symbol table are used to check the consistency of the given code.

Semantic analysis is necessary due to the following reasons:

1. In this phase, the semantic analyzer checks the source program for semantic errors and collects the type information for the code generation. Semantic analyzer checks whether they form a sensible set of instructions in the programming language or not.

2. Semantic analyzer recognizes following types of errors:

  • Type mismatch
  • Undeclared variables
  • Reserved identifier misuse
  • Multiple declaration of variable in a scope.
  • Accessing an out of scope variable.
  • Actual and formal parameter mismatch.

3. Semantic analysis performs the following function:

  • Type Checking : Ensures that data types are used in a way consistent with their definition.
  • Label Checking : A program should contain labels references.
  • Flow Control Check : Keeps a check that control structures are used in a proper manner.(example: no break statement outside a loop)

Example:

float x = 10.1;

float y = x*30;

In this example integer 30 will be typecasted to float 30.0 before multiplication, by semantic analyzer.