Basics of Compiler Design
Introduction
When we have learnt different programming languages like C, C++ or Java we got familiar with the term compiler. As an example, for C and C++ we have found Turbo C compiler, for Java we have seen Java compiler and so on. Most of the students have a wrong idea that compilation is required only to check the errors. But this is not the only job for a compiler, its job is much wider than error checking. Compiler is basically built on the knowledge of Automata. To learn different phases of compiler we need the knowledge of Finite Automata, Regular Expression, Context Free Grammar etc. Compiler needs a vast discussion, but in this section we shall discuss only those parts which are directly related to Automata.
13.1 Definition
Compiler is a program that takes a program written in a source language and translates it into an equivalent program in a target language. In relation to compiler the source language is human readable language called High Level Language and target language is machine readable code called machine level language. In the operational process of a compiler it reports the programmer the presence of errors in the source program. The block diagram of compiler is shown in Fig. 13.1 .
Fig. 13.1 Block Diagram of Compiler
13.2 Types of Compiler
Compilers are classified mainly into three types according to their operational process.
-
Single pass: In computer programming, a single pass or one-pass compiler is a compiler that scans through the source code of each compilation unit only once. In other words, a single-pass compiler does not ‘look back’ the code it has previously processed. Sometimes single pass compiler is called narrow compiler, which points to the limited scope of a one-pass compiler. Some programming languages have been designed specifically to be compiled with one-pass compilers. As an example of such a construct is the forward declaration in Pascal. Normally Pascal requires that procedures to be fully defined before use. This helps a single-pass compiler with its type checking—calling a procedure that has not been defined is a clear error. However, this requirement makes mutually recursive procedures impossible to implement.
-
Multi-pass: A multi-pass compiler is a type of compiler that processes the source code or abstract syntax tree constructed from the program several times. This is in contrast to a one-pass compiler, which traverses the program only once. In multipass compiler each pass takes the result of the previous pass as the input, and creates an intermediate output. In this way, the intermediate code is improved pass by pass, and in the final pass the final code is produced.
Referring to the greater scope of the passes multi-pass compilers are sometimes called wide compilers as they can ‘see’ the entire program being compiled, instead of just a small portion of it. This type of compilers allows better code generation which is smaller in size, and faster to execute by the computer hardware, compared to the output of one-pass compilers. But the main disadvantage is the higher compilation time and memory consumption. In addition, some languages cannot be compiled in a single pass, as a result of their design.
-
Load and go: A load and go compiler generates machine code and then immediately executes it.
Compilers usually produce either absolute code that is executed immediately upon conclusion of the compilation or object code that is transformed by a linking loader into absolute code. These compiler organizations will be called Load & Go and Link/Load. Both Load & Go and Link/Load compilers use a number of passes to translate the source program into absolute code. A pass reads some form of the source program, transforms it into another form, and normally outputs this form to an intermediate file which may be the input of a later pass.
13.2.1 Difference Between Single Pass and Multi-Pass Compiler
- A one-pass compiler (narrow compiler) is a compiler that passes through the source code of each compilation unit only once whereas a multi-pass compiler (wide compiler) is a type of compiler that processes the source code several times.
- A one-pass compiler is faster than multi-pass compilers as it traverse the source code only once.
- Multi-pass compiler produces smaller targets and faster to execute target code than single-pass compiler.
- Many programming languages like Pascal can only be represented with a single pass compiler, whereas some languages like Java require a multi-pass compiler.
13.3 Major Parts of Compiler
The working process of a compiler is divided into two parts—analysis and synthesis. Analysis phase scan the program and breaks it into constituent pieces. From the pieces an intermediate representation of the source program is created. Synthesis phase takes the intermediate representation and construct the target code for the source program. The phases of a compiler are shown in Fig. 13.2 .
Fig. 13.2 Different Phases of Compiler
Analysis part can be divided into three parts:
- Linear or lexical analysis
- Hierarchical analysis or syntax analysis
- Semantic analysis
Synthesis part is also divided into three parts:
- Intermediate code generator
- Code optimizer
- Code generator
Lexical Analysis: This is the initial phase of compiler. The dictionary meaning of lexical is pertaining into words. In this phase the source program is read from left to right and divided into tokens. Tokens are the sequence of characters having a collective meaning. In relation to programming languages tokens are objects like variable name, number, keywords and so on. This phase also performs some secondary tasks like, removing source program’s comments, white spaces in the form of blank, tab and newline character and so on.
Syntax Analysis: Syntax analyzer sometimes called parser. This phase takes the list of tokens produced by lexical analysis and arranges these in a tree-structure. Parser checks the input with a generated Context Free Grammar (CFG). If the parser determines the input to be valid one, it represents the input in the form of a parse tree. But if it is grammatically incorrect, the parser declares the presence of syntax error in the input. In this case no parse tree can be produced.
Semantic Analysis: Once a program is found to be syntactically correct—that is grammatically—the next task is to check for semantic correctness. A major job of semantic analysis is type checking where the match between operator and operand is checked. As an example, let an array is declared as integer. So all the elements within the array must be integer. If a float number is used to index the array, error will be reported.
Intermediate Code Generation: This phase is the first phase of synthesis part. Here the tree generated and modifies in syntax or semantic analysis phase is converted into a low level or machine like intermediate representation. This intermediate representation makes the target code easy to produce.
Code Optimization: This phase takes the intermediate representation as input and optimizes it to reduce its time and space complexity. By this the intermediate code is improved and better target code is produced.
Code Generation: Produces the target language in a specific architecture. The target program is normally is a object file containing the machine codes.
Symbol Table: In different phases of compiler the variables are needed. The values of the variables are changed from time to time in different operational phases of the compiler. To keep record of the variables or identifiers memory storage is needed. Symbol table is that storage. A symbol table is a data structure which keeps the record for each identifier, with fields for the attribute of the identifier. This data structure allows us to find the record for each identifier quickly and to store or retrieve data from that record quickly.
Upon detecting the identifiers in the source program by the lexical analyzer, those are entered into the symbol table. The remaining phases enter information about identifiers into the symbol table and then use this information in various ways.
Error Detection and Reporting: Errors can be produced in each phase of the compiler. After detecting an error, a phase may deal with those errors, so that the compilation can proceed and further errors in the source program are detected or simply reports the errors.
The syntax and semantic analysis phase usually handle a large fraction of the errors detectable by the compiler.
Among these phases, lexical analysis and syntax analysis have direct connection with automata theory. Lexical analysis phase deals with regular expression and finite automata whereas syntax analysis needs context free grammar. For this reason these two phases need some of discussion with automata. In this section we shall discuss the parts of lexical and syntax analysis which has connection with automata.
13.3.1 Lexical Analysis
Lexical analysis is the first phase of compiler design. In this phase the source program is read from left to right, character by character and generates token. Lexical analysis does not work single and not return a list of tokens at one shot, it returns a token when the parser asks a token from it. Getting a get next token command from parser, lexical analysis scans the source program and upon finding a token it returns it to the parser. The working principle of lexical analysis is shown in Fig. 13.3 .
Though token generation process is not so simple, it uses a technique called double buffering which makes the scanning process faster. But that is beyond our discussion.
Fig. 13.3 Working Principle of Lexical Analysis
13.3.1.1 Major Terms of Lexical Analysis
It is already discussed that lexical analyzer returns tokens. But how a lexical analyzer decides a string of characters and/or numbers as token? For this we have to know the definitions of token, pattern and lexemes.
Token: Sequence of characters having a collective meaning. Token can be differentiated as type token (integer number, real number), punctuation token (void, return) and alphabetic token (keywords).
Comment, macros, whitespace characters (blank, tab, new line) are treated as non tokens.
Pattern: Pattern is the set of rules which characterizes a string as a token. If a scanned string is matched with the set of rules; it is declared as token. As an example the pattern of identifier is id → letter (letter | digit)*. According to this int A2 is a valid identifier but 2A is not.
Lexeme: It is the actual string that fulfills the rules of pattern as classified by a token.
Example: int principal1 is characterized by the pattern that id → letter (letter | digit)*. Thus it is a valid identifier and it is a type token. The actual string is principal1, thus it is a lexeme.
13.3.2 Syntax Analysis
Syntax analyzer creates the syntactic structure of the given source program. The mostly used syntactic structure is parse tree. For this reason syntax analysis is known as parser. What is the syntax? The syntax of a programming language is the rules described by a context free grammar associated with it. In syntax analysis phase it is checked whether a given source program satisfies the rules of the underlying context free grammar or not. If a valid parse tree is created for the given source program then the program is syntactically correct, otherwise it gives the error message known as syntax error. As an example a = b + c is a valid C statement but b + c = a is not. Because for the second one a valid parse tree can not be generated. Compiler generates an error L value required for this type of C statement.
The rules or grammar related to syntax analysis is context free grammar. Therefore, the grammar may me ambiguous. A very common case of ambiguity occurs in if-else statement in C or Java. Let us take the following example.
Now consider the following C statement
This can be derived by the following ways.
or
The parse trees for the previous two derivations are given in Fig. 13.4 .
Fig. 13.4 Nested If-Else Problem
Now the ‘else’ part is for which if ?—the first or the second. Attaching ‘else’ with each of two results different. So, ambiguity must be removed. Here the ambiguity is removed by the following rule— ‘Match each else with the closest previous unmatched if’.
In context free grammar section another common case of ambiguity has already been described for the grammar.
E → E + E/E – E/E * E/id
In this case the ambiguity is removed by putting precedence of operators.
13.3.3 Parser
The syntax analyzer checks whether a given source program satisfies the rules implied by a context-free grammar or not by constructing a parse tree for a given statement. For this reason syntax analyzer is sometimes known as parser. Parser is of mainly two types—top down parser and bottom up parser. In this chapter we shall discuss LL(1) parsing as an example of top down parsing and LR parsing, as an example of bottom up parsing.
Top down parsing technique can not handle left recursive grammar. A grammar is called left recursive if it has a non-terminal ‘A’ such that there is a derivation.
The process of the removal of left recursion is described in context free grammar chapter.
Backtracking is also a problem related to parsing.
Let a grammar is in the form.
And the string to be generated is abbc. Compiler can scan one symbol at a time. As aBC and aB both are started with the symbol ‘a’; compiler can take any of the productions to generate abbc. Let it take A → aBC and the derivations are as follows.
The string abbc is already generated but a non-terminal ‘C’ still remains. So, the parser has to backtrack to choose the alternative production A → aB, and the following derivations are
It succeeds in generating the string. For backtracking the parser wastes a lot of lime. Hence the backtracking must be removed. Left factoting of the grammar is a process to remove backtracking. Actually top-down parsing technique insists that the grammar must be left factored. The process of left factoring a grammar is described in Context free grammar chapter.
13.3.3.1 Top-down Parsing
In top down parsing a parse is created from root to leaf. Top down parsing corresponds to a preorder traversal of the parse tree. In this parsing a left most derivation is applied at each derivation step. There are mainly two types of top-down parsing—recursive decent parsing and predictive parsing.
Recursive Decent Parsing: Recursive decent parsing is most straight forward form of parsing. In this type of top down parsing the parser attempts to verify the input string read from left to right with the grammar underlying. A basic operation of recursive decent parsing involves reading characters from the input stream one at a time, and matching it with terminals from the production rule of the grammar that describes the syntax of the input. In recursive decent parsing backtracking occurs. This backtracking is caused because in recursive decent parsing left recursion is not removed. Due to this it is not efficient and not widely used.
Predictive Parsing: This is a type of top down parsing which never backtracks. To prevent the occurrence of backtracking from the grammar left recursion is removed and the grammar is left factored. Non recursive predictive parsing is a mixture of recursive decent parsing and predictive parsing, which never backtracks.
13.3.3.2 LL(1) Parsing
LL(1) parsing is an example of predictive parsing. The first ‘L’ in LL(1) denotes that input string is scanned from left to right. Second ‘L’ denotes that by left most derivation the input string is constructed. ‘1’ denotes that only one symbol of the input string is used as a look-head symbol to determine parser action. LL(1) is a table driven parser as the parser consults with a parsing table for its actions. A LL(1) parser consists of a input tape, a stack and a parsing table. The block diagram of a LL(1) parser is given in Fig. 13.5 .
Fig. 13.5 LL(1) Parser
Different Components of LL(1) Parser
- Input buffer: Input buffer contains the input string to be parsed. It contains a $ as the end marker of the input string.
- Stack: Stack contains the terminal and non-terminal symbols. In brief it can be said that Stack contains grammar symbols. Bottom of the stack contains a special symbol $ ∉ (V N ∪ Σ). At the beginning of parsing the stack contains $S, where S is the start symbol.
- Parsing table: It is most important part of a LL(1) parser. It is a two dimensional array whose left most column contains the non-terminal symbols ∈ V N and top most row contains the terminal symbol ∈ Σ ∪ $. Some entries of the parsing table contain the production rules of the grammar and remaining contains error.
How LL(1) Parser Works? As described in earlier section, the input buffer contains the input string to be parsed ended by a $ and stack contains the grammar symbols including $. The symbols in the input buffer are terminal symbols. As it is LL(1) parser, therefore one symbol of the input buffer is scanned at a time. The parser action is determined by the top of the stack symbol let T Stack and the current scanned input symbol from the input buffer let I i/p . Four types actions are possible for a LL(1) parser.
- T Stack and I i/p are same terminal symbol: Parser pops T Stack from the top of the stack and points next symbol in the input buffer.
- T Stack is a non-terminal: Parser consults with the corresponding entries for T Stack and I i/p in the parsing table. The top of the stack is replaced by the right hand side of the production in reverse. [Parsing table entries is a production rule of the grammar]
- T Stack is $ and I i/p is $: parsing successful. Declare accept.
- None of the above three: Error.
Let take an example to describe it in detail.
Example 13.1
Consider the following parsing table.
Parse the string (int * int) + int using the following parsing table.
Solution:
Hence the string (int *int) + int is acepted by the given LL(1) parser.
Example 13.2
Consider the following parsing table.
Check whether the string (id–id) + id is accepted by the parser or not.
Solution:
Hence the string is accepted by the given LL(1) parser.
Construction of LL(1) Parsing Table: LL(1) parsing is a table driven parsing. The parsing table is an important part of the parser. In this section we shall learn how to construct the LL(1) parsing table. Before going into the construction process of LL(1) parsing table, two important topics are needed to be discussed—First and Follow.
- FIRST: For a given string α ∈ {V N ∪ Σ}, First(α) is the set of terminal symbols that begin the strings derivable from ε. If ε is derived from α then ε is also included in First(α). First can be calculated for terminal, non-terminal and string of terminal and/or non-terminal.
-
FOLLOW: Follow is calculated for non-terminal symbols. Follow (NT) is the set of the terminals which occur immediately after (follow) the non-terminal NT in the strings derived from the starting symbol. A terminal t is in Follow(NT) S
. . . . t . . . . . In the blank space there is non-terminal or terminal symbols.
Rules of Constructing FIRST
-
First of ε is ε.
-
First of a terminal symbol is that terminal symbol, i.e. if a is a terminal symbol then FIRST (a) = {a}
-
First of a string XY is
- FIRST(X) ∪ FIRST(Y) if FIRST(X) contains ε
- FIRST(X) if FIRST(X) does not contains ε
-
If there are productions NT → α 1 /α 2 / . . . . . . /α n
Example 13.3
Construct FIRST of the non-terminal symbols of the given grammar.
[This is the grammar Here i is for ‘if’, E is for ‘Expression’, t is for ‘then’ , S is for ‘statement’ and e is for ‘Else’. ]
Solution: The terminal symbols in the grammar are ‘i’, ‘t’, ‘a’, ‘e’ and ‘b’.
Now calculate the FIRST of the Non-Terminal symbols.
FIRST(S) = FIRST (iEtSS′) ∪ FIRST(a)
FIRST (iEtSS′) =
-
FIRST(i) ∪ FIRST(EtSS′) if FIRST(i) contains ε.
-
FIRST(i) if FIRST(i) does not contain ε.
Hence FIRST(S) = {i, a}.
Hence FIRST(S′) = {e,( }.
FIRST(E) = FIRST(b) = {b}
Example 13.4
Construct FIRST of the non-terminal symbols of the given grammar.
Solution: The terminal symbols in the grammar are +, –, (, ), id.
Now calculate the FIRST of the non-terminal symbols.
FIRST(E) = FIRST(TE′)
-
FIRST(T) ∪ FIRST(E′) if FIRST(T) contains ε.
-
FIRST(T) if FIRST(T) does not contain ε.
-
FIRST(F) ∪ FIRST(T′) if FIRST(F) contains ε.
-
FIRST(F) if FIRST(F) does not contain ε.
As FIRST(F) does not contain ε, therefore
FIRST(T) = FIRST(F) = {(, id}
As FIRST(T) does not contain ε, therefore
FIRST(E) = FIRST(T) = {(, id}
Example 13.5
Construct FIRST of the non-terminal symbols of the given grammar.
Solution : The terminal symbols in the grammar are ‘(‘, ‘)’,int, +, *.
The non-terminal of the grammar are E, T, X and Y.
FIRST(E) = FIRST(TX)
- FIRST(T) ∪ FIRST(X) if FIRST(T) contains ε.
- FIRST(T) if FIRST(T) does not contain ε.
Rules of Constructing FOLLOW
- FOLLOW of a start symbol contains $.
- If there is a production rule in the form A → αBβ then everything in FIRST(β) is included in FOLLOW(B) except ε.
- If (there is a production rule in the form A → αB) OR (a production rule in the form A → αBβ and ε is in FIRST(β)) then everything in FOLLOW(A) is included in FOLLOW(B).
Example 13.6
Construct FOLLOW of the non-terminal symbols of the given grammar.
Solution: S is the start symbol of the grammar. So, FOLLOW(S) contains $.
S → iEtSS′ is in the form A → αBβ, where
-
Case 1: α is i, B is E and β is tSS′. FOLLOW(E) = FIRST(tSS′)−ε.
-
Case 2: α is iEt, B is S and β is S′. FOLLOW(S)= FIRST(S′) −ε.
FIRST(S′) = {e, ε}, therefore FOLLOW(S) = {e}
S → iEtSS′ is in the form A → αB, where iEtS is α and S′ is B. So, FOLLOW(S) is a subset of FOLLOW(S′).
S′ → eS is in the form A → αB. Therefore FOLLOW(S′) is a subset of FOLLOW(S).
Hence FOLLOW(S) = FOLLOW(S′)
Example 13.7
Construct FOLLOW of the non-terminal symbols of the given grammar.
Solution: E is the start symbol. Hence FOLLOW(E) = {$}.
There is a production E → TE′ [in the form A → αB]. So FOLLOW(E) is a subset of FOLLOW(E′).
There is a production E′ → +TE′ [in the form A → αBβ]. Everything FIRST(E′) is included in FOLLOW(T) except ε. FIRST(E′) = {+, ε}, so FOLLOW(T) = {+}.
As ε is in FIRST(E′), so FOLLOW(E′) is a subset of FOLLOW(T).
There is a production T → FT′ [in the form A → αB]. FOLLOW(T) is a subset of FOLLOW(T′).
There is a production T′ → −FT′ [in the form A → αBβ ]. Everything FIRST(T′) is included in FOLLOW(F) except ε. FIRST(T′) = {−, ε} , so FOLLOW(F) = {+}.
As ε is in FIRST(T′), so FOLLOW(T′) is a subset of FOLLOW(F).
Consider the production F → (E). It is in the form A → αBβ. So everything in FIRST(‘)’) except ∈ is in FOLLOW(E). Hence FOLLOW(E) ={‘)’}
Finally
Rules for LL(1) Parsing Table Construction: We know that the parsing table is a table whose top most row contains the terminal symbols including $ and left most column contains the non-terminal symbols.
Let the parsing table is M[NT, T], where NT denotes non-terminals and T denotes terminals. The rules for constructing the parsing table are given below.
For each production rule in the form A → α of the given grammar G
{
-
for each terminal T i in FIRST(α) add A → α to M[A, T i ]
-
- If FIRST(α) contains ε then for each terminal T in FOLLOW(A) the production rule A → α is added to M[A,T]
- If FIRST(α) contains ε and FOLLOW(A) contains $ then the production rule A → α is added to M[A, $].
}
-
All other undefined entries of the parsing table are ERROR.
Example 13.8
Construct LL(1) parsing table for the grammar.
Solution: The FIRST of the Terminals and Non-Terminals and FOLLOW of the Non-Terminals are already calculated. These are given below.
- S → iEtSS′ is in the form A → α. FIRST(iEtSS′) = {i}. The production rule S → iEtSS′ is added in the parsing table label [S, i].
- S→ a is added in the parsing table label [S, a] as FIRST(a) = {a}.
- S′ → eS is added in the parsing table label [S′, e] as FIRST(eS) = {e}.
- For the production S′ → $ as FIRST(ε) = {ε} look for FOLLOW(S′). It is {e, $}. Hence S′ → ε is added in the parsing table label [S′, e] and [S′, $].
- E → b is added in the parsing table label [E, b] as FIRST(b) = {b}.
Therefore the constructed parsing table is
Example 13.9
Construct LL(1) parsing table for the grammar.
Solution: The FIRST of the terminals and non-terminals and FOLLOW of the non-terminals are already calculated. These are given below.
- E→ TE′ is in the form A → α. FIRST(TE′) = {(, id}. E→ TE′ is added in the parsing table label [E, (] and [E, id].
- E′ → +TE′ is added in the parsing table label {E′, +}.
- FIRST(ε) = {ε} in E′ → ε. FOLLOW(E′) = {$, )}. Therefore E′ → ε is added in the parsing table label [E′, )]. As FOLLOW(E′) contains $, so E′ → ε is added in the parsing table label [E′, $].
- FIRST(F) = {(, id} in T (FT′. Therefore the production T → FT′ is added in the parsing table label [F,( ] and [F, id].
- The production rule T′ → −FT′ is added in the parsing table label [T′, −].
- FIRST(ε) = {ε} in T′ → ε. FOLLOW(T′) = {+, ), $}. Therefore T′ → ε is added in the parsing table label [T′, +] and [T′, )]. As FOLLOW(T′) contains $, so T′ → ε is added in the parsing table label [T′, $].
- The production rule F → (E) is added in the parsing table label [F, ( ].
- The production rule F→ id is added in the parsing table label [F, id].
Therefore the constructed parsing table is
Checking Whether a Grammar is LL(1) or Not: A grammar is LL(1) if parsing table of it does not contain multiple entry in a single label [NT, T]. Look the parsing table for the grammar for If-Else statement. It contains two production rules S′ → eS and S′ → ε in the parsing table label [S′, e]. Hence the grammar is not LL(1).
But it become difficult to say whether a grammar is LL(1) or not by constructing its parsing table. If we are able to mark those conditions for which multiple entry appears in a single label [NT, T] of the parsing table, then it becomes easy to check whether a grammar is LL(1) or not. The conditions are as follows.
-
A grammar which is left recursive is not LL(1).
Explanation: Let a grammar contains a production rule A → Aα/β, where α and β are string of terminal and/or non terminals.
Hence FIRST(Aα) contains all the terminal symbols those appear in FIRST(β). Therefore the parsing table block label [A, T ∈ FIRST(β)] contains the productions A → Aα and A → β.
-
A grammar which is not left factored is not LL(1).
Explanation: Let a grammar contains a productions A → αS 1 /αS 2 , where α is a terminal and S 1 , S 2 are string of terminal and/or non terminals. FIRST(A) contains the terminal α. Therefore the parsing table block label [A, α] contains the productions A → αS 1 and A → αS 2 .
-
An ambiguous grammar is not LL(1) grammar.
-
If a grammar contain productions A → a and A → β.
– If both of α and β generate ε, the grammar is not LL(1).
Explanation: The parsing table block label [A, ε] contain A → α and A → β.
– If β produce ε and α derive any string starting with a terminal belongs to FOLLOW(A), the grammar is not LL(1).
Explanation: Let there is a production NT i → T i <String>/ε and FOLLOW(NT i ) contains T i . For the production NT i → T i <String> the parsing table block label [NT i , T i ] contains the production NT i → T i <String>, as FIRST(T i <String>) contains T i .
Now consider the production NT i → ε. As FOLLOW(NT i ) contains T i , the production rule NT i → ε is place in parsing table block label [NT i , T i ].
It means parsing table block label [NT i , T i ] contains two productions NT i → T i <String> and NT i → ε, thus the grammar is not LL(1).
Example 13.10
Check whether the grammar is LL(1) or not.
Solution:
- The grammar is not left recursive. There is no option to make it left factored.
- The production rule S → iEtSS′/a and S′ → eS/ε contain two productions in a group. Any of the first group of productions do not produce ε. The production S′ → eS do not generate ε.
- For the group of production S′ → eS/ε, S′ → ε produce ε. FOLLOW(S′) = {e, $}. But the production S′ → eS starts with e ∈ FOLLOW(S′).
Therefore the grammar is not LL(1).
13.3.3.3 Bottom Up Parsing
Operation of bottom up parsing is the reverse of top down parsing. A bottom-up parsing starts traversing with the string of terminals from the leaves and by applying the productions in reverse it moves upward until it gets the start symbol. In this process, a bottom-up parser searches for substrings of the working string that match the right side of some production. When such a substring is found, parser reduces it i.e. the parser substitutes the left side non-terminal of the matching production rule with the substring (Which is the right hand side of the production rule). By this process at the last stage a substring is replaced by the start symbol reporting successful parsing. There are different types of bottom up parsing. Among them we shall discuss mainly shift reduce parsing and LR parsing.
Shift Reduce Parsing: A shift reduce parser is one type of bottom up parsing. It means the parser starts traversing a string from the string itself and reaches to the start symbol. A shift reduce parser consists of an input tape and a stack. The bottom of the stack is marked by $, the stack bottom symbol. The end of the string in the input tape is marked by $ as end marker.
The block diagram of a shift reduces parser is shown in Fig. 13.6 .
Fig. 13.6 Shift Reduce Parser
As the name suggests, the two operations attached with this parsing are shift and reduce.
- Shift: This operation traverses the input alphabets from input tape to the stack one by one in each step.
- Reduce: This operation reduces the handle by some non-terminal. A handle is a right sentential sequence of terminal and/or non-terminal within the string being parsed and same as the rightmost derivation of a production rule of the grammar.
The following are some examples of shift reduce parsing.
Example 13.11
Parse the string (a + b)*c using shift reduce parsing from the given grammar.
Solution:
| Stack
|
Input Tape
|
Action
| | --- | --- | --- | | $ | (a + b)*c $ | Shift ‘(’ | | $ ( | a + b)*c $ | Shift ‘a’ | | $ ( a | + b)*c $ | Reduce by E → a | | $ (E | b)*c $ | Shift + | | $ (E + | )*c $ | Shift ‘b’ | | $ (E + b | )*c $ | Reduce by E → b | | $ ( E + E ) | )*c $ | Reduce by E → E + E | | $ (E) | )*c $ | Shift ‘(’ | | $ ( E ) | *c $ | Reduce by E → (E) | | $ E | * c $ | Shift * | | $ E* | c $ | Shift c | | $ E* c | $ | Reduce by E → c | | $ E*E | $ | Reduce by E *E | | $ E | $ | Accept |
Example 13.12
Parse the string ibtictaeac using shift reduce parsing from the given grammar.
Solution:
| Stack
|
Input Tape
|
Action
| | --- | --- | --- | | $ | ibtictaeac$ | Shift i | | $i | btictaeac$ | Shift ‘b’ | | $ib | tictaeac$ | Reduce by E → b | | $iE | tictaeac$ | Shift t | | $iEt | ictaeac$ | Shift i | | $iEti | ctaeac$ | Shift c | | $iEtic | taeac$ | Shift t | | $iEtict | aeac$ | Shift a | | $iEticta | aeac$ | Reduce by S → a | | $iEtictS | eac$ | Shift e | | $iEtictSe | ac$ | Shift a | | $iEtictSea | c$ | Reduce by S → a | | $iEtictSeS | c$ | Reduce by E → eS | | $iEtictSE | c$ | Reduce by E → iEtSE | | $iEtS | c$ | Shift c | | $iEtSc | $ | Reduce by E → c | | $iEtSE | $ | Reduce by E → iEtSE | | $E | $ | accept |
Two types of problems that found in a shift reduce parsing are shift reduce conflict and reduce reduce conflict. There is no scope of discussing them details in this chapter.
LR Parsing: LR parsing is one type of bottom up parsing. It is also shift reduce parsing. LR parsing is a backtrack-free deterministic parsing technique performed in linear time. LR recognizes virtually all programming languages. For this reason LR is widely used parsing technique. In LR, L represents left to right scanning of the input string, R represents rightmost derivation in reverse. In LR(1) , the number ‘1’ represents one symbol look ahead.
LR parsing is also a table driven parsing like LL(1) parsing. Here the parser table is divided into two parts—Action and Goto. The parser is attached with an input tape and a stack. The input tape contains the string to be parsed ended by a $ as end marker and the stack contains the grammar symbols (terminal and non-terminal both). The rows of the LR parsing table are marked by state number. The columns of the ACTION part are marked by the terminal symbol of the grammar and the GOTO part are marked by the non-terminal symbols of the grammar. Already it is discussed that LR parser is nothing but a shift reduce parser. The fields [State and Terminal] of the ACTION part contains SHIFT (the states) and REDUCE (by the given productions). The field [State and Non-Terminal] of the GOTO part contains the next state number to go. The block diagram of a LR parser is given in Fig. 13.7 .
Fig. 13.7 Block Diagram of LR Parser
13.3.3.4 Parsing Algorithm
Input: Grammar with n number of productions, A LR parsing table.
A LR parser works as follows.
-
It checks the state S i currently on the top of the stack and the current input symbol I i in the input tape.
-
The parser consults in the Action part of the parsing table with label [S i , I i ]. This returns one of the following.
– Shift S j . This places the current input in the stack followed by S j as the top of the stack
– Reduce by production number k. k = 1 to n. [Let the production k is A → B. The parser pushes A by popping 2*| B | elements from the stack, consult with the goto part with label (A, previous input) and places state S l on the top of the stack. S l is the entry in (A, previous input) in the goto part of the parsing table.]
– Accept
– Error
Example 13.13
Parse the string id + id * id by the following grammar and the LR parsing table.
Solution:
| Stack
|
Input
|
Action
|
| --- | --- | --- |
| 0 | id + id * id$ | Shift 5 |
| 0id5 | + id * id$ | Reduce by production no 6
(| id | = 1, so 2 symbols are popped from the stack, F is placed. For [0, F] there is g 3 , thus 3 is top of the stack ) |
| 0F3 | + id * id$ | Reduce by production no 4
(| F | = 1, so 2 symbols are popped from the stack, T is placed. For [0, T] there is g 2 , thus 2 is top of the stack) |
| 0T2 | + id * id$ | Reduce by production no 2, then g 1 . Top of the stack is 1. |
| 0E1 | + id * id$ | Shift 6 |
| 0E1 | + 6id * id$ | Shift 5 |
| 0E1 | + 6id5*id$ | Reduce by production no 6, then g 3 . Top of the stack is 3. |
| 0E1 | + 6F3*id$ | Reduce by production no 4, then g 9 . Top of the stack is 9. |
| 0E1 | + 6T9*id$ | Shift 7 |
| 0E1 | + 6T9*7id$ | Shift 5 |
| 0E1 + 6T9*7 | id5$ | Reduce by production no 6, then g 10 . Top of the stack is 10. |
| 0E1 + 6T9*7F10 | $ | Reduce by production no 3. | T * F | = 3. Six symbols are popped. T is placed. Entry for [6, T] = g 9 , thus 9 is the top of the stack. |
| 0E1 + 6T9 | $ | Reduce by production number 1. Then g 1 , thus 1 is top of the stack. |
| 0E1 | $ | accept |
LR Parsing Table Construction: LR parsing is an efficient parsing technique in compiler design. Whole parsing technique is dependent on the parsing table. But the most difficult part is the LR parsing table construction. In this section we shall discuss the construction process of Simple LR parsing table. The construction process consists of several steps as follows.
- Augmented grammar formation
- State construction of FA using item grammar and closure operation from the augmented grammar:
Item Grammar Construction: This is done by item grammar construction. An item of a grammar G is a production rule in G with a dot at some position of the right hand side of the production. Item (The presence of . [dot]) indicates how much of the production is parsed so far.
As an example If E → E + T is a production rule of a grammar, then the items of the grammar are
E → .E + T
E → E. + T
E → E + .T
E → E + T.
If there is a production T → ε in the grammar then T → . is an item of the grammar.
Closure Operation: If I is the set of items of a grammar G then Closure of I is a set of item constructed by the following rules.
- Closure(I) contains every item in I.
- If A → α . B β exist in Closure(I) and B → γ is a production, then B → .γ is also added in the Closure(I).
Goto Operation: If a set of item is I and B is a grammar symbol, the operation goto(I, B) is constructed as
-
In FA if goto(I i , T ) → I j then Action[I i , T] = S j . If goto(I i , NT) → I j then Goto[I i , NT] = g j
-
To construct the reduce operations in Action table formulate the FOLLOW of the non-terminals.
If I i contains a production in the form NT → α . , and FOLLOW(NT) = {T j }, then Action [I i , T j ] = r k . [Where k is the production number of the production NT → α] If I i contains a production S → α . , where S is the new start symbol and FOLLOW(S) = $, then Action[I i , $] = Accept.
The process is described by the following example.
Example 13.14
Construct SLR parsing table for the following grammar
Solution:
-
The augmented grammar is
-
Construction of state of NFA: This is done by two steps
-
Item grammar construction: Let take E′ → . E in I. The closure(I) is the set as follow.
Mark it I 0 .
I 3 = {T → F.} i.e. {T → id.}. So I 3 is the final state.
I 5 is also final state.
I 9 is final state as the parse ends at E → E + T.
I 10 is final state as the parse ends at T → T * F.
I 11 is also final state.
For I 10 and I 11 all are null.
The final FA is
-
-
Shift in the Action part and Goto Table is as follow.
-
FOLLOW(E′) = {$}
FOLLOW(E) = {+, ), $}
FOLLOW(T) = {+, ), *, $}
FOLLOW(F) = {+, ), *, $}
I 1 contains a production E′ → E., and FOLLOW(E′ ) = {$}. Thus Action [I 1 , $] = Accept.
I 2 contains a production E → T. , and FOLLOW(E ) = {+, ), $}. Hence
For I 3 : Action[I 3 , +] = r 4 , Action[I 3 , )] = r 4 , Action[I 3 , *] = r 4 , Action[I 3 , $] = r 4 ,
By this process the final table is
What We Have Learned So Far
- Compiler is a program that takes a program written in a source language and translates it into an equivalent program in a target language.
- The knowledge of automata theory is required in different phases of compiler design.
- Compiler are of three types—single pass, multi-pass and load and go.
- Single pass compiler is known as narrow compiler and multi-pass is known as wide compiler.
- Phases of Compiler are divided into two phases—analysis and synthesis phase.
- Analysis part can be divided into three parts—linear or lexical analysis, hierarchical analysis or syntax analysis and semantic analysis.
- Synthesis part is divided into three parts—intermediate code generator, code optimizer and code generator.
- In lexical analysis the source program is read from left to right, character by character and generates token.
- In syntax analysis the rules associated with the context free grammar for the programming language are checked.
- Parsing is of two types—top down and bottom up parsing.
- Recursive decent parsing is a top down parsing and it is most straight forward form of parsing. The major drawback of it is backtracking.
- LL(1) parsing is a backtrack free table driven parsing.
- LL(1) parsing table is constructed by FIRST and FOLLOW operation.
- If any cell of the table constructed from a grammar contains multiple entry then the grammar is not LL(1).
- Shift reduce and LR are bottom up parsing where the parsing starts from the leaf nodes and ends on the root.
- LR parsing table consists of two parts Action and Goto.
- LR parsing table is constructed by item grammar construction, closure operation, finite automata construction etc.
Multiple Choice Questions
-
Choose the role of compiler
- Converting high level language to machine level language
- Converting low level language to high level language
- Converting a source language to a target language
- Only checking the errors in the written program.
-
Compiler is a
- Software
- Operating system
- Program
- Translator
-
Symbol table keeps record of
- Keywords
- Identifier
- Constant
- Loop
-
Which is true for lexical analysis?
- It removes comments and white spaces from the source program.
- It breaks the source program into tokens
- Its operation is dependent on syntax analysis
- All of these
-
Pattern of an identifier is
- letter (letter | digit)*-
- digit (letter | digit)*
- (letter | digit)* letter
- (letter | digit)*digit
-
Which is not included in LL(1) parsing
- Input buffer
- Queue
- Parsing table
- Stack
-
Which may be a cause for a grammar not to be LL(1) ?
- Grammar is left recursive
- Grammar is left factored
- Parsing table does not contain multiple entry
- Grammar is not ambiguous.
-
Identify the invalid drawback of Shift Reduce conflict
- Shift-Reduce Conflict
- Reduce-Reduce Conflict
- Shift-shift Conflict
- Shift-Reduce-Shift Conflict
Answers:
- c
- d
- b
- d
- a
- b
- a
- c
GATE Questions
(Common for Question 1 and 2)
For the grammar below, a partial LL(1) parsing table is also presented along with grammar. Entries that need to be filled are indicated as E 1 , E 2 , E 3 . ε is the empty string, $ indicates the end of input, and, | separates alternate right hand side productions.
-
The FIRST and FOLLOW sets for the non-terminals A and B are
-
FIRST (A) = {a, b, ε} = FIRST(B)
FOLLOW(A) = {a, b}
FOLLOW (B) = {a, b, $}
-
FIRST (A) = {a, b, $}
FIRST(B) = {a, b, ε}
FOLLOW(A) = {a, b}
FOLLOW (B) = {$}
-
FIRST (A) = {a, b, ε} = FIRST(B)
FOLLOW(A) = {a, b}
FOLLOW (B) = Ø
-
FIRST (A) = {a, b} = FIRST(B)
FOLLOW(A) = {a, b}
FOLLOW (B) = {a, b}
-
-
The appropriate entries for E 1 , E 2 and E 3 are
-
E 1 : S → aAbB, A → S
E 2 : S → bAaB, B → S
E 3 : B → S
-
E 1 : S → aAbB, S → ε
E 2 : S → bAaB, S → ε
E 3 : S → ε
-
E 1 : S → aAbB, S → ε
E 2 : S → bAaB, S → ε
E 3 : B →S
-
E 1 : A → S, S → ε
E 2 : B → S, S → ε
E 3 : B → S
-
-
In compiler keywords of a language are recognized during
- parsing of a program
- the code generation
- the lexical analysis of the program
- dataflow analysis
-
The grammar S → aSa | bS | c is
- LL(1) but not LR(1)
- LR(1) but not LL(1)
- both LL(1) and LR(1)
- neither LL(1) nor LR(1)
Answers:
- a
- b
- c
- c
Hints:
-
FIRST (S) = {a, b, ε} = FIRST(A) = FIRST(B)
FOLLOW(S) = {$}
FIRST(bB) – ε is included in included in FOLLOW(A)
FOLLOW(A) = {b}
From S → bAab considering ab as β using same rule FOLLOW(A) = {a}.
FOLLOW(A) = {a, b}
Consider A → S and B → S. These two productions are in the form A → αB, where α is null.
FOLLOW(A) ⊂ FOLLOW(S)
FOLLOW(B) ⊂FOLLOW(S)
Consider S → aAbB, with aAb as α. Using the rule A → αB, we get
FOLLOW(S) ⊂ FOLLOW(B).
Thus FOLLOW(S) = {a, b, $} = FOLLOW(B)
FOLLOW(A) = {a, b}
Exercise
-
Parse the string S = abbfgg using the following LL(1) parsing table.
-
Construct LL(1) parsing table for the following grammar.
-
Check whether the following languages are LL(1) or not.
- L = a n b n , n ≥ 1
- L = {a m b n , n, m ≥ 1 }
-
Parse the string S = abbfgg using the following grammar by shift reduce parsing
-
Parse the string id/id + id * id ↑ id by the following grammar using shift reduce parsing.
In this relation describe shift-reduce and reduce-reduce conflict.
-
Construct LR parsing table for the grammar