Skip to content

Lecture No. 11

Dated: 17-03-2025

Semantic Analysis

Consider the English sentence "He wrote the computer". This sentence is syntactically correct but semantically wrong.
Consider the following code example which is syntactically correct but has semantic errors

int* foo(int i, int j) {
    for (k = 0; i < j; j++ )
        if(i < j - 2)
            sum = sum + i;

    return sum;
}

The errors are

  • Sum was not declared
  • Function is supposed to return a pointer1 but returns an int.

Role of Parser2

Parsing is the process of discovering a derivation for some sentence of a language.3
The mathematical model of a syntax is represented by a grammer \(G\). The language3 generated by the grammar is indicated by \(L(G)\). Syntax of most programming languages can be represented by Context Free Grammar (CFG).

The syntax of C, C++ and Java is derived heavily from Algol-60.
The notation was developed by John Backus and adapted by Peter Naur for the Algol-60 language report; thus the term Backus-Naur Form (BNF).

There are 2 derivations of interest

  • Left most where we replace the left most non terminal at each step.
  • Right most where we replace the right most non terminal at each step.

Both these derivations produce different parse trees2 which implies different order of evaluations.

References


  1. Read more about pointers

  2. Read more about parsers

  3. Read more about fundamentals