Phase 1: Lexical Analysis: Example
Phase 1: Lexical Analysis: Example
Phase 1: Lexical Analysis: Example
Lexical Analysis is the first phase when compiler scans the source code.
This process can be left to right, character by character, and group these
characters into tokens.
Example:
x = y + 10
Tokens
X identifier
= Assignment operator
Y identifier
+ Addition operator
10 Number
Example
Any identifier/number is an expression
(a+b)*c
In Parse Tree
Interior node: record with an operator filed and two files for children
Leaf: records with 2/more fields; one for token and other information
about the token
Ensure that the components of the program fit together meaningfully
Gathers type information and checks for type compatibility
Checks operands are permitted by the source language
Example
float x = 20.2;
float y = x*30;
In the above code, the semantic analyzer will typecast the integer 30 to float
30.0 before multiplication
Example
For example,
t1 := int_to_float(5)
t2 := rate * t1
t3 := count + t2
total := t3
Example:
a = intofloat(10)
b=c*a
d=e+b
f=d
Can become
b =c * 10.0
f = e+b
It also allocates memory locations for the variable. The instructions in the
intermediate code are converted into machine instructions. This phase
coverts the optimize or intermediate code into the target language.
The target language is the machine code. Therefore, all the memory
locations and registers are also selected and allotted during this phase. The
code generated by this phase is executed to take inputs and generate
expected outputs.
Example:
a = b + 60.0
MOVF a, R1
MULF #60.0, R2
ADDF R1, R2
The error may be encountered in any of the above phases. After finding
errors, the phase needs to deal with the errors to continue with the
compilation process. These errors need to be reported to the error handler
which handles the error to perform the compilation process. Generally, the
errors are reported in the form of message.
Summary
Compiler operates in various phases each phase transforms the source
program from one representation to another
Six phases of compiler design are 1) Lexical analysis 2) Syntax
analysis 3) Semantic analysis 4) Intermediate code generator 5) Code
optimizer 6) Code Generator
Lexical Analysis is the first phase when compiler scans the source
code
Syntax analysis is all about discovering structure in text
Semantic analysis checks the semantic consistency of the code
Once the semantic analysis phase is over the compiler, generate
intermediate code for the target machine
Code optimization phase removes unnecessary code line and arranges
the sequence of statements
Code generation phase gets inputs from code optimization phase and
produces the page code or object code as a result
A symbol table contains a record for each identifier with fields for the
attributes of the identifier
Error handling routine handles error and reports during many phases