Unit - I Lexical Analysis Translator
Unit - I Lexical Analysis Translator
Unit - I Lexical Analysis Translator
UNIT – I
LEXICAL ANALYSIS
Translator:
It is a program that translates one language to another Language.
COMPILER:
Compiler is a translator, program that translates a program written in (HLL) - the source
program and translate it into an equivalent program in (MLL) - the target program. As an important
part of the compiler is error showing to the programmer.
ASSEMBLER:
Programmers found it difficult to write or read programs in machine language. They begin to
use a mnemonic (symbols) for each machine instruction, which they would subsequently translate into
machine language. Such a mnemonic machine language is now called an assembly language.
Programs known as assembler were written to automate the translation of assembly language in
to machine language. The input to an assembler program is called source program, the output is a
machine language translation (object program)
Assembly Machine
Assembler
Language Language
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
INTERPRETER:
It is one of the translators that translate high level language to low level language.
High Level Low Level
Interpreter
Language Language
During execution, it checks the line by line for error(s).
No Compiler Interpreter
Program need not be compiled every Every time higher level program is
5
time converted into lower level program
Errors are displayed after entire Errors are displayed for every
6
program is checked instruction interpreted (if any)
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
a +
b *
c 2
Semantic Analysis:-
It is the third phase of the compiler.
It gets input from the syntax analysis as parse tree and checks whether the given
syntax is correct or not.
It performs type conversion of all the data types into real data types.
Intermediate Code Generations:-
It is the fourth phase of the compiler.
It gets input from the semantic analysis and converts the input into output as
intermediate code such as three-address code.
The three-address code consists of a sequence of instructions, each of which has
atmost three operands. Example: t1=t2+t3
Code Optimization:-
It is the fifth phase of the compiler.
It gets the intermediate code as input and produces optimized intermediate code
as output.
This phase reduces the redundant code and attempts to improve the intermediate code
so that faster-running machine code will result.
During the code optimization, the result of the program is not affected.
To improve the code generation, the optimization involves
- deduction and removal of dead code (unreachable code).
- calculation of constants in expressions and terms.
- collapsing of repeated expression into temporary string.
- loop unrolling.
- moving code outside the loop.
- removal of unwanted temporary variables.
Code Generation:-
It is the final phase of the compiler.
It gets input from code optimization phase and produces the target code or object code
as result.
Intermediate instructions are translated into a sequence of machine instructions
that perform the same task.
The code generation involves
- allocation of register and memory
- generation of correct references
- generation of correct data types
-generation of missing code.
Table Management (or) Book-keeping:-
Symbol table is used to store all the information about identifiers used in the program.
It is a data structure containing a record for each identifier, with fields for the attributes
of the identifier.
It allows to find the record for each identifier quickly and to store or retrieve data
from that record.
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
Whenever an identifier is detected in any of the phases, it is stored in the symbol table.
Error Handlers:-
Each phase can encounter errors. After detecting an error, a phase must handle the
error so that compilation can proceed.
In lexical analysis, errors occur in separation of tokens.
In syntax analysis, errors occur during construction of syntax tree.
In semantic analysis, errors occur when the compiler detects constructs with
right syntactic structure but no meaning and during type conversion.
In code optimization, errors occur when the result is affected by the optimization.
In code generation, it shows error when code is missing etc.
Example: To illustrate the translation of source code through each phase, consider the statement
position := initial + rate * 60. The figure shows the representation of this statement after each
phase.
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
Compiler passes
A collection of phases is done only once (single pass) or multiple times (multi pass)
Single pass: usually requires everything to be defined before being used in
source program.
Multi pass: compiler may have to keep entire program representation in memory.
Several phases can be grouped into one single pass and the activities of these phases are
interleaved during the pass. For example, lexical analysis, syntax analysis, semantic analysis and
intermediate code generation might be grouped into one pass.
3) LEXICAL ANALYSIS
Lexical analysis is the process of converting a sequence of characters into a sequence of
tokens. A program or function which performs lexical analysis is called a lexical analyzer or
scanner. A lexer often exists as a single function which is called by a parser or another function.
3.1) Role of The Lexical Analyzer:
The lexical analyzer is the first phase of a compiler.
Its main task is to read the input characters and produce as output a sequence of tokens
that the parser uses for syntax analysis.
token
source lexical parser
program analyser
get next token
symbol
table
Upon receiving a “get next token” command from the parser, the lexical analyzer reads
input characters until it can identify the next token.
Issues of Lexical Analyzer
There are three issues in lexical analysis:
To make the design simpler.
To improve the efficiency of the compiler.
To enhance the computer portability.
Tokens
A token is a string of characters, categorized according to the rules as a symbol (e.g.,
IDENTIFIER, NUMBER, and COMMA). The process of forming tokens from an input
stream of characters is called tokenization.
A token can look like anything that is useful for processing an input text stream or text
file. Consider this expression in the C programming language: sum=3+2;
sum Identifier
= Assignment operator
3 Number
+ Addition operator
2 Number
; End of statement
LEXEME:
Collection or group of characters forming tokens is called Lexeme.
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
Pattern:
A pattern is a description of the form that the lexemes of a token may take.
In the case of a keyword as a token, the pattern is just the sequence of characters that
form the keyword. For identifiers and some other tokens, the pattern is a more complex structure
that is matched by many strings.
Attributes for Tokens
Some tokens have attributes that can be passed back to the parser. The lexical analyzer
collects information about tokens into their associated attributes. The attributes influence the
translation of tokens.
i) Constant : value of the constant
ii) Identifiers: pointer to the corresponding symbol table entry.
Error Recovery Strategies in Lexical Analysis:
The following are the error-recovery actions in lexical analysis:
1) Deleting an extraneous character.
2) Inserting a missing character.
3) Replacing an incorrect character by a correct character.
4) Transforming two adjacent characters.
5) Panic mode recovery: Deletion of successive characters from the token until error
is resolved.
INPUT BUFFERING
We often have to look one or more characters beyond the next lexeme before we can be
sure we have the right lexeme. As characters are read from left to right, each character is stored
in the buffer to form a meaningful token as shown below:
Forward pointer
A = B + C
We introduce a two-buffer scheme that handles large look ahead safely. We then consider
an improvement involving "sentinels" that saves time checking for the ends of buffers.
Buffer Pairs
A buffer is divided into two N-character halves, as shown below
: : E : : = : : M : * C : * : : * : 2 : eof
lexeme_beginning
forwar
d
Each buffer is of the same size N, and N is usually the number of characters on one
disk block. E.g., 1024 or 4096 bytes.
Using one system read command we can read N characters into a buffer.
If fewer than N characters remain in the input file, then a special character,
represented by eof, marks the end of the source file.
Two pointers to the input are maintained:
1. Pointer lexeme_beginning, marks the beginning of the current
lexeme, whose extent we are attempting to determine.
2. Pointer forward scans ahead until a pattern match is found.
blog – anilkumarprathipati.wordpress.com/
jntuk396.blogspot.com
UNIT-I COMPILER DESIGN
Once the next lexeme is determined, forward is set to the character at its
right end.
The string of characters between the two pointers is the current lexeme.
After the lexeme is recorded as an attribute value of a token returned to the parser,
lexeme_beginning is set to the character immediately after the lexeme just found.
Advancing forward pointer:
Advancing forward pointer requires that we first test whether we have reached the end of
one of the buffers, and if so, we must reload the other buffer from the input, and move forward
to the beginning of the newly loaded buffer. If the end of second buffer is reached, we must
again reload the first buffer with input and the pointer wraps to the beginning of the buffer.
Code to advance forward pointer:
if forward at end of first half then
begin reload second half;
forward := forward + 1
end
else if forward at end of second half then
begin reload second half;
move forward to beginning of first half
end
else forward := forward + 1;
Sentinels
For each character read, we make two tests: one for the end of the buffer, and one to
determine what character is read. We can combine the buffer-end test with the test for
the current character if we extend each buffer to hold a sentinel character at the end.
The sentinel is a special character that cannot be part of the source program, and a
natural choice is the character eof. The sentinel arrangement is as shown below:
: : E : : = : : M : * : eofC : * : : * : 2 : eof : : : eof
lexeme_beginning
forwar
d
Note that eof retains its use as a marker for the end of the entire input. Any eof
that appears other than at the end of a buffer means that the input is at an end.
Code to advance forward pointer:
forward : = forward + 1;
if forward ↑ = eof then begin
if forward at end of first half then
begin reload second half;
forward := forward + 1
end
else if forward at end of second half then
begin reload first half;
move forward to beginning of first
half end
else /* eof within a buffer signifying end of input
*/ terminate lexical analysis
end
SPECIFICATION OF TOKENS
There are 3 specifications of tokens:
1) Strings
2) Languageand 3) Regular expression
blog – anilkumarprathipati.wordpress.com/
jntuk396.blogspot.com
UNIT-I COMPILER DESIGN
blog – anilkumarprathipati.wordpress.com/
jntuk396.blogspot.com
UNIT-I COMPILER DESIGN
Regular set
A language that can be defined by a regular expression is called a regular set.
If two regular expressions r and s denote the same regular set, we say they are equivalent and
write r = s.
There are a number of algebraic laws for regular expressions that can be used to
manipulate into equivalent forms.
For instance, r|s = s|r is commutative; r|(s|t)=(r|s)|t is associative.
Regular Definitions
Giving names to regular expressions is referred to as a Regular definition. If Σ is an
alphabet of basic symbols, then a regular definition is a sequence of definitions of the form
dl → r 1 d2
→ r2
………
dn → rn
Non-regular Set
A language which cannot be described by any regular expression is a non-regular set.
Example: The set of all strings of balanced parentheses and repeating strings cannot be
described by a regular expression. This set can be specified by a context-free grammar.
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
RECOGNITION OF TOKENS
Consider the following grammar fragment:
stmt → if expr then stmt
| if expr then stmt else
stmt | ε
expr → term relop
term | term
term → id |
num
where the terminals if , then, else, relop, id and num generate sets of strings given by
the following regular definitions:
if → if
then → then
else → else
relop → <|<=|=|<>|>|>=
*
id → letter(letter|digit)
+ + +
num → digit (.digit )?(E(+|-)?digit )?
For this language fragment the lexical analyzer will recognize the keywords if, then,
else, as well as the lexemes denoted by relop, id, and num. To simplify matters, we assume
keywords are reserved; that is, they cannot be used as identifiers.Transition diagrams
It is a diagrammatic representation to depict the action that will take place when a lexical
analyzer is called by the parser to get the next token. It is used to keep track of information
about the characters that are seen as the forward pointer scans the input.
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
UNIT-I COMPILER DESIGN
Lex
lex.l lex.yy.c
compiler
Lex Specification
A Lex program consists of three parts:
{ definitions }
%%
{ rules }
%%
{ user subroutines }
blog – anilkumarprathipati.wordpress.com/
jntuk396.blogspot.com
UNIT-I COMPILER DESIGN
FINITE AUTOMATA
Finite Automata is one of the mathematical models that consist of a number of states and
edges. It is a transition diagram that recognizes a regular expression or grammar.
The following steps are involved in the construction of DFA from regular expression:
i) Convert RE to NFA using Thomson’s rules
ii) Convert NFA to DFA
iii) Construct minimized DFA
jntuk396.blogspot.com
blog – anilkumarprathipati.wordpress.com/
jntuk396