Unit 1
Unit 1
INRODUCTION TO COMPILERS
Translator:
It is a program that translates one language to another.
Types of Translator:
1.Interpreter
2.Compiler
3.Assembler
1.Interpreter:
It is one of the translators that translate high level language to low level language.
2.Assembler:
It translates assembly level language to machine code.
3.Compiler:
It is a program that translates one language(source code) to another language (target
code).
Compiler Interpreter
It is a translator that translates high level to It is a translator that translates high level to low
low level language level language
It displays the errors after the whole program
is It checks line by line for errors.
executed.
Examples: C, C++, Cobol, higher version of
Examples: Basic, lower version of Pascal.
Pascal.
LANGUAGE PROCESSORS:
Preprocessor
A preprocessor produce input to compilers. They may perform the following
functions.
1. Macro processing: A preprocessor may allow a user to define macros that
are short hands for longer constructs.
2. File inclusion: A preprocessor may include header files into the
program text.
3. Rational preprocessor: these preprocessors augment older languages with
more modern flow-of-control and data structuring facilities.
4. Language Extensions: These preprocessor attempts to add capabilities to the
language by certain amounts to build-in macro
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 a compiler is error showing to the programmer.
Languages such as BASIC, SNOBOL, LISP can be translated using interpreters. JAVA also
uses interpreter. The process of interpretation can be carried out in following phases.
1. Lexical analysis
2. Synatx analysis
3. Semantic analysis
4. Direct Execution
Advantages:
Modification of user program can be easily made and implemented as execution
proceeds.
Type of object that denotes a various may change dynamically.
Debugging a program and finding errors is simplified task for a program used for
interpretation.
The interpreter for the language makes it machine independent.
Disadvantages:
1) Structure editor:
Takes as input a sequence of commands to build a source program.
The structure editor not only performs the text-creation and modification functions of
an ordinary text editor, but it also analyzes the program text, putting an appropriate
hierarchical structure on the source program.
For example , it can supply key words automatically - while …. do and begin….. end.
2) Pretty printers :
A pretty printer analyzes a program and prints it in such a way that the structure of
the program becomes clearly visible.
For example, comments may appear in a special font.
3) Static checkers :
A static checker reads a program, analyzes it, and attempts to discover potential
bugs without running the program.
For example, a static checker may detect that parts of the source program can never
be executed.
4) Interpreters :
Translates from high level language ( BASIC, FORTRAN, etc..) into machine language.
An interpreter might build a syntax tree and then carry out the operations at the nodes
as it walks the tree.
Interpreters are frequently used to execute command language since each operator
executed in a command language is usually an invocation of a complex routine such as
an
editor or complier.
ANALYSIS OF THE SOURCE PROGRAM
Linear/Lexical Analysis :
It is also called scanning. It is the process of reading the characters from left to right
and grouping into tokens having a collective meaning.
For example, in the assignment statement a=b+c*2, the characters would be grouped
into the following tokens:
i) The identifier1 ‘a’
ii) The assignment symbol (=)
iii) The identifier2 ‘b’
iv) The plus sign (+)
v) The identifier3 ‘c’
vi) The multiplication sign (*)
vii) The constant ‘2’
Syntax Analysis :
a +
b *
c 2
A syntax tree is the tree generated as a result of syntax analysis in which the
interior nodes are the operators and the exterior nodes are the operands.
Semantic Analysis :
It checks the source programs for semantic errors and gathers type information for the
subsequent code generation phase. It uses the syntax tree to identify the operators
and operands of statements.
A Compiler operates in phases, each of which transforms the source program from
one representation into another. The following are the phases of the compiler:
Main phases:
1) Lexical analysis
2) Syntax analysis
3) Semantic analysis
4) Intermediate code generation
5) Code optimization
6) Code generation
Sub-Phases:
1) Symbol table management
2) Error handling
LEXICAL ANALYSIS:
It is the first phase of the compiler. It gets input from the source program and
produces tokens as output.
It reads the characters one by one, starting from left to right and forms the tokens.
Token : It represents a logically cohesive sequence of characters such as
keywords, operators, identifiers, special symbols etc.
Example: a + b = 20
Here, a,b,+,=,20 are all separate tokens.
Group of characters forming a token is called the Lexeme.
The lexical analyser not only generates a token but also enters the lexeme into the
symbol table if it is not already there.
SYNTAX ANALYSIS:
a +
b *
c 2
SEMANTIC ANALYSIS:
CODE OPTIMIZATION:
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.
Whenever an identifier is detected in any of the phases, it is stored in the symbol table.
ERROR HANDLING:
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.
To illustrate the translation of source code through each phase, consider the statement
a=b+c*2. The figure shows the representation of this statement after each phase:
a=b+c*2
Lexical analyser
id1=id2+id3*2
Syntax analyser
=
Symbol Table
id1 +
a id1
b id2 id2 *
c id3
id3 2
Semantic analyser =
id1 +
id2 *
id3 inttoreal
2
Intermediate code generator
temp1=inttoreal(2)
temp2=id3*temp1
temp3=id2+temp2
id1=temp3
Code optimizer
temp1=id3*2.0
id1=id2+temp1
Code generator
MOVF id3,R2
MULF #2.0,R2
MOVF id2,R1
ADDF R2,R1
MOVF R1,id1
GROUPING OF PHASES:
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.
These are specialized tools that have been developed for helping implement
various phases of a compiler. The following are the compiler construction tools:
1) Parser Generators:
-These produce syntax analyzers, normally from input that is based on a context-free
grammar.
-It consumes a large fraction of the running time of a compiler.
-Example-YACC (Yet Another Compiler-Compiler).
2) Scanner Generator:
-These generate lexical analyzers, normally from a specification based on regular
expressions.
-The basic organization of lexical analyzers is based on finite automation.
3) Syntax-Directed Translation:
-These produce routines that walk the parse tree and as a result generate intermediate code.
-Each translation is defined in terms of translations at its neighbour nodes in the tree.
5) Data-Flow Engines:
-It does code optimization using data-flow analysis, that is, the gathering of information
about
how values are transmitted from one part of a program to each other part.
ERRORS ENCOUNTERED IN DIFFERENT PHASES:
Compiler Errors
In Different Phases:
A parser should be able to detect and report any error in the program. It is expected that
when an error is encountered, the parser should be able to handle it and carry on parsing the rest
of the input. Mostly it is expected from the parser to check for errors but errors may be
encountered at various stages of the compilation process. A program may have the following
kinds of errors at various stages:
There are four common error-recovery strategies that can be implemented in the parser to
deal with errors in the code.
Panic mode
When a parser encounters an error anywhere in the statement, it ignores the rest of the
statement by not processing input from erroneous input to delimiter, such as semi-colon. This is
the easiest way of error-recovery and also, it prevents the parser from developing infinite loops.
Statement mode
When a parser encounters an error, it tries to take corrective measures so that the rest of
inputs of statement allow the parser to parse ahead. For example, inserting a missing semicolon,
replacing comma with a semicolon etc. Parser designers have to be careful here because one
wrong correction may lead to an infinite loop.
Error productions
Some common errors are known to the compiler designers that may occur in the code. In
addition, the designers can create augmented grammar to be used, as productions that generate
erroneous constructs when these errors are encountered.
Global correction
The parser considers the program in hand as a whole and tries to figure out what the
program is intended to do and tries to find out a closest match for it, which is error-free. When
an erroneous input (statement) X is fed, it creates a parse tree for some closest error-free
statement Y. This may allow the parser to make minimal changes in the source code, but due to
the complexity (time and space) of this strategy, it has not been implemented in practice yet.
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
TOKENS
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.
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.
Lexical Errors:
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 aheads safely. We then
consider an improvement involving "sentinels" that saves time checking for the ends of
buffers.
BUFFER PAIRS
::E::=::M:* C:*::*:2:
eof
lexeme_beginning
forwa
rd
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.
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 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.
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:
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.
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
alphabet. A language is any countable set of strings over some fixed alphabet.
In language theory, the terms "sentence" and "word" are often used as synonyms for
"string." The length of a string s, usually written |s|, is the number of occurrences of symbols
in s. For example, banana is a string of length six. The empty string, denoted ε, is the string of
length zero.
Operations on strings
1. A prefix of string s is any string obtained by removing zero or more symbols from the end
of string s.
For example, ban is a prefix of banana.
2. A suffix of string s is any string obtained by removing zero or more symbols from
the beginning of s.
For example, nana is a suffix of banana.
4. The proper prefixes, suffixes, and substrings of a string s are those prefixes, suffixes,
and substrings, respectively of s that are not ε or not equal to s itself.
Operations on languages:
1.Union
2.Concatenation
3.Kleene closure
4.Positive closure
Regular Expressions
Here are the rules that define the regular expressions over some alphabet Σ and the
languages that those expressions denote:
1. ε is a regular expression, and L(ε) is { ε }, that is, the language whose sole member is
the empty string.
2. If ‘a’ is a symbol in Σ, then ‘a’ is a regular expression, and L(a) = {a}, that is, the
language with one string, of length one, with ‘a’ in its one position.
3. Suppose r and s are regular expressions denoting the languages L(r) and L(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
Example: Identifiers is the set of strings of letters and digits beginning with a letter. Regular
definition for this set:
letter → A | B | …. | Z | a | b | …. | z |
digit → 0 | 1 | …. | 9
id → letter ( letter | digit ) *
Shorthands
Certain constructs occur so frequently in regular expressions that it is convenient to
introduce notational shorthands for them.
1. One or more instances (+):
- If ‘r’ is a regular expression, then ( r )? is a regular expression that denotes the language
L( r ) U { ε
}.
3. Character Classes:
- The notation [abc] where a, b and c are alphabet symbols denotes the regular
expression a | b | c.
Non-regular Set
RECOGNITION OF TOKENS
Consider the following grammar fragment:
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 → num →
<|<=|=|<>|>|>=
*
letter(letter|digit)
+ + +
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.
Transition diagram for Identifiers:
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.
a b c
r5 : r 3 r4
r12 : r11 a c
r10
2 a 3
st 0 1 6 7 a 8 b 9
b
5
ar
4 b 1
t 0
b C b
sta a b b
rt A B D E
a
a
a
DFA Minimization
a
C b
A B D E
a
C b
A B D E
A B Dab E
Followpos :
Syntax tree of (a
the position i in the strings generated by
the augmented regular expression.
For example, ( a | b) * a #
1 2 3 4
followpos(1) = {1,2,3}
followpos(2) = {1,2,3} each symbol is at a le
followpos(3) = {4}
followpos(4) = {}
firstpos, lastpos, nullable
inner nodes are oper
To evaluate followpos, three more functions are to be defined for the nodes (not just for leaves)
of the syntax tree.
firstpos(n) -- the set of the positions of the first symbols of strings generated by the
sub-expression rooted at n.
lastpos(n) -- the set of the positions of the last symbols of strings generated by the
sub-expression rooted at n.
nullable(n) -- true if the empty string is a member of strings generated by the sub-
expression rooted by n false otherwise
Evaluation of followpos
{1,2,3} {4
}
red –
firstpo
{4} #{4}
{1,2,3} {3} 4
{1,2} {1 ,2} {3} a{3}
*
3
p o s (1 ) = { s1,2,3}
Algorithm (RE è DFA) {1,2}
follo w
3e}–
{1,2}
|
{2}
o s ( 2 ) =
wp lastpos, nullable { b
1 l
,2u ,
{1} a{1} {2} b
follofirstpos,
Create the syntax tree of (r) #
r E xp r e ss
1
2
Calculate the functions: followpos,
ll o w p o s (3
u c d 4
{lfa
) t=estate. }
o s
r o
thpe Rs e gu la
n ow be f o
Put firstpos(root) into the states of DFA
co n
as
s
an
tr
unmarked
The DF A c a n wp os (4 ) {}
while (there is an unmarked state S in the states of DFA) do
=
o mark S
fo ll o
o for each input symbol a do
let s1,...,sn are positions in S and symbols in those positions are a
S’ ç followpos(s1) È ... È followpos(sn)
move(S,a) ç S’
if (S’ is not empty and not in the states of DFA)
put S’ into the states of DFA as an unmarked state.
the start state of DFA is firstpos(root)
the accepting states of DFA are all states containing the position of #
Example -- ( a | b) * a #
A LANGUAGE FOR SPECIFYING LEXICAL ANALYZER:
LEX
Lex is a computer program that generates lexical analyzers. Lex is commonly used with
the yacc parser generator.
Lex Specification
{ definitions }
%%
{ rules }
%%
{ user subroutines }
User subroutines are auxiliary procedures needed by the actions. These can be
compiled separately and loaded with the lexical analyzer.
(a | b) (a | h) denotes (aa, ab. ba, bb), the set of an strings of a's and b's of length two.
Another regular expression for this same set is aa | ab | ba | bb
(a b)* denotes the set of all strings containing zero or more instances of an a or b, that is
the set of all strings of a's and b's.
X | X'YZ denotes the set containing the string X and all strings consisting of zero or
more X's followed by YZ.
Given a familiarity with Lex and C, a lexical analyzer for almost any programming language can
be written in a very short time. Lex does not have application solely in the generator of lexical
analysers. It can also be used to assist in the implementation of almost any text pattern matching
application, such as text editing, code conversion and so on.