Understanding Semantic Analysis

In this class, We discuss Understanding Semantic Analysis

For Complete YouTube Video: Click Here

The reader should have prior knowledge of syntax analysis. Click Here.

We discuss the basic understanding of semantic analysis here. These basics will help readers understand the next classes.

The below diagram shows the part of the compiler phases.

We refresh the previous concepts once and go with semantic analysis.

Take the source program and input it to the lexical analysis phase.

The lexical analysis phase program will convert the source code into tokens.

The tokens are input to the syntax analysis phase.

The syntax analysis phase program checks for syntax and generates a syntax tree.

The syntax tree is input for the semantic analysis phase.

The semantic phase will check the conditions required for the programming language.

Example:

Take C Programming language.

a= b + c

1) In ‘C’ language variable should be declared before assigning value to a variable.

2) When we evaluate expressions Type of variables should match.

The above two are some of the conditions in the semantic analysis phase.

The semantic conditions changes from one programming language to another.

One way to check semantic conditions.

Take the syntax tree and write a program to check for semantic conditions.

Most of the compilers do not follow this way.

Second Way:

During the execution of the syntax analysis program, add the extra logic to check for semantic conditions.

The example below helps you understand how to write the semantic logic in the syntax analysis program?

The below example is our expression grammar.

Assume we are using a top-down approach for syntax analysis.

We can take recursive descent or LL(1) parsing.

The below program is the code using recursive descent parsing.

In recursive descent parsing, we write a function for each non-terminal.

The below program shows the function for non-terminal E.

the function E will call the function E.

After completing function E., it checks for input symbol ‘+’ and then calls the function T.

The top-down approach generates the leftmost derivation tree.

The below diagram shows the derivation tree.

After completing the production E – E + T evaluation, we add the semantic condition checking logic in the same function.

The below program shows the semantic checking typecasting in the function E.

We can write the semantic condition logic anywhere required in the program.

Similarly, we write the semantic condition in bottom-up parsing when we reduce action.