Semantic Analysis A Compiler must do more than

  • Slides: 7
Download presentation
Semantic Analysis A Compiler must do more than recognise whether a sentance belongs to

Semantic Analysis A Compiler must do more than recognise whether a sentance belongs to a langauge or not. ●It must do something useful with the sentance as it parses. ●We introduce semantic actions. ● Semantic Actions Each terminal and non-terminal may be associated with its own semantic value. ●For a rule A -> B C , the semantic action returned must be of the type associated with A. However the value returned is built up from the values of B and C. ●

Given the following grammar. . exp -> INT exp -> exp PLUS exp ->

Given the following grammar. . exp -> INT exp -> exp PLUS exp -> expt MINUS exp. . . add in semantic actions.

Tasks of Semantic Analysis: Type checking. ● Scope Checking. ● Uniqueness checking. ● Method

Tasks of Semantic Analysis: Type checking. ● Scope Checking. ● Uniqueness checking. ● Method invocation checks. ● We store information about all identifiers in a Symbol Table, which we consult when making these checks.

Semantic Analysis – Approaches 1) Perform analysis during the parse. Single Pass Compiler. 2)

Semantic Analysis – Approaches 1) Perform analysis during the parse. Single Pass Compiler. 2) Build an abstract Syntax Tree. This is done by using the semantic actions. When the tree is built, we walk the tree and populate the symbol table. We can walk the tree many times. Multi Pass Compiler.

Symbol Table We use a Hash Table to implement our symbol table. ●We map

Symbol Table We use a Hash Table to implement our symbol table. ●We map identifiers to their associated meaning. ●Identifiers can be mapped to methods, types, variables. . ● Scope Handling ● We need to cater for scope in a program

public class test. Scope{ private int x; private int y; public static void method

public class test. Scope{ private int x; private int y; public static void method 1(){ int z; boolean y; } public static void method 2(){ for(int x = 0; x<10; i++){. . . } } }

Course Overview of Compilation Lexical Syntax Semantic Analysis Lexical Analysis Regular Expressions RE's to

Course Overview of Compilation Lexical Syntax Semantic Analysis Lexical Analysis Regular Expressions RE's to DFA's Syntax Analysis CFG's Parsing and Parse Trees LL and LR Parsing. First and Follow Parse Tables Ambiguities and Conflicts Semantic Analysis Semantic Actions Scope Handling Symbol Table Type Checking etc.