COMPILER DESIGN ASSIGNMENT
QUESTION 1
Explain the different phases of a compiler with a diagram and detailed explanation.
Introduction
A compiler is a system software that translates high-level programming languages into
machine code. This process occurs in several phases, each transforming the program closer
to executable form.
Phases of a Compiler
1. Lexical Analysis: Converts source code into tokens such as keywords, identifiers, and
constants.
2. Syntax Analysis: Ensures the tokens follow grammatical rules and builds a parse tree.
3. Semantic Analysis: Checks for logical errors such as type mismatches and undeclared
variables.
4. Intermediate Code Generation: Produces a machine-independent representation.
5. Code Optimization: Improves performance by eliminating redundant code.
6. Code Generation: Converts optimized code into machine or assembly language.
Conclusion for Question 1
Each compiler phase plays a critical role in transforming high-level code into efficient
machine code.
QUESTION 2
Discuss the role of lexical analysis and design a simple lexical analyzer.
Role of Lexical Analysis
Lexical analysis is the first stage of compilation. It reads the source program and converts it
into tokens, removing unnecessary characters such as whitespace and comments.
Functions of Lexical Analyzer
- Tokenization
- Removal of whitespace and comments
- Error detection
- Symbol table interaction
Simple Lexical Analyzer (Python Example)
keywords = {"int", "if", "else", "while", "return"}
operators = {"+", "-", "*", "/", "="}
separators = {";", "(", ")", ","}
def lexical_analyzer(code):
for word in [Link]():
if word in keywords:
print(word, "-> Keyword")
elif word in operators:
print(word, "-> Operator")
elif [Link]():
print(word, "-> Constant")
elif word in separators:
print(word, "-> Separator")
else:
print(word, "-> Identifier")
code = "int x = 25 + y;"
lexical_analyzer(code)
Conclusion for Question 2
Lexical analysis simplifies compiler design by converting raw input into manageable tokens.