Compiler Construction Final
Compiler Construction Final
A parser is a component of a compiler that processes the source code to check its structure according to
the grammar of the programming language. It ensures the code follows the rules and produces a
structured representation, usually in the form of a parse tree or syntax tree.
Types of Parsers
1. Top-Down Parsers: Start analyzing from the root of the parse tree and move toward the leaves.
2. Bottom-Up Parsers: Start analyzing from the leaves of the parse tree and move toward the root.
Simple Example
Consider the grammar for a simple arithmetic expression:
E→E+T|T
T→T*F|F
F → a|b|c | id
1. Input Code: a + b * c
/|\
E + T
| /\
T T F
| | |
F F c
| |
a b
Types of Tokens
1. Keywords: Reserved words in a language (e.g., if, else, while).
2. Identifiers: Names for variables, functions, etc. (e.g., x, sum).
3. Operators: Symbols for operations (e.g., +, -, *).
4. Literals: Constant values (e.g., 10, 'hello').
5. Punctuation: Symbols like ;, ,, (), {}.
Example
For the code:
int x = 10 + 20;
Tokens:
1. int → Keyword
2. x → Identifier
3. = → Operator
4. 10 → Literal
5. + → Operator
6. 20 → Literal
7. ; → Punctuation
Example:
2. Scope Rule:
Ensure variables/functions are declared before use.
Example:
Identifier → VariableName
Semantic Check: Confirm VariableName is in the current scope.
Example:
4. Operator Rule:
Ensure operators are applied to valid types.
Example:
Steps
1. Parser Rules (Syntax Check):
Match declarations:
Match assignments:
4) Code Generation
Code generation is the final phase in a compiler where the intermediate representation (IR) of a
program is translated into machine code or assembly code that can be executed by a computer.
Example:
For the statement: x = a + b;
5) Symbol Table
In compiler construction, a symbol table is a data structure that stores information about variables,
functions, and other symbols used in the source code during compilation.
Purpose:
1. Track identifiers: Keeps track of variables, functions, and other symbols in the program.
2. Store information: Stores details like type, scope, memory location, and usage of each symbol.
Static Binding
Occurs at compile-time: The memory address and type of variables or methods are determined during
compilation.
Dynamic Binding
Occurs at runtime: Memory address and type are determined during execution.
Example:
Expression: id1 = id2 + id3 * 60
TAC Steps:
1. Convert constant:
Temp1 = inttoreal(60)
2. Multiply:
3. Add:
4. Assign:
id1 = Temp3
Final TAC:
Temp1 = inttoreal(60)
Temp2 = id3 * Temp1
Temp3 = id2 + Temp2
id1 = Temp3