UNIT-1
Introduction to Compilers
A compiler is a translator
software program that takes its input in the form of a program written in one
particular programming language and produces the output in the form of a
program in another language.
Features of Compilers:
- A compiler is a translator that converts the
high-level language into machine language.
- High-level language is written by a developer, and
machine language can be understood by the processor.
- A compiler is used to show errors to the programmer.
- A compiler executes a program in two parts:
- The source program is compiled into an object
program.
- The object program is translated into the target
program.
Compiler Structure:
A compiler operates in phases. A
phase is a logically interrelated operation that takes a source program in one
representation and produces output in another representation. There are two
phases of compilation:
1. Analysis Phase:
In the analysis part, an
intermediate representation is created from the given source program. This part
is called the front end of the compiler. This part consists of four phases:
i) Lexical
Analysis:
Lexical analysis or scanning is
the process where the source program is read from left to right and grouped
into tokens. Tokens are sequences of characters with a collective meaning. In
any programming language, tokens may be constants, operators, reserved words,
etc. The lexical analyzer takes a source program as input and produces a stream
of tokens as output.
Example:
Input string: c = a + b * 3
Tokens: id1 = id2 + id3 * 3
ii)
Syntax Analysis:
In this phase, the syntax analyzer takes the tokens produced by the lexical analyzer as input and generates a parse tree as output. During the syntax analysis phase, the parser checks whether the expression made by the tokens is syntactically correct according to the rules that define the syntax of the source language.
Example:
iii) Semantic Analysis:
In this phase, the semantic analyzer checks the source program for semantic errors and collects the type information for code generation. The semantic analyzer ensures the instructions form a sensible set in the programming language. Type-checking is a crucial part of the semantic analysis.
Example: