Introduction of Lexical Analysis
Last Updated :
18 Oct, 2024
Lexical Analysis is the first phase of a compiler that takes the input as a source code written in a high-level language. The purpose of lexical analysis is that it aims to read the input code and break it down into meaningful elements called tokens. Those tokens are turned into building blocks for other phases of compilation.
What is Lexical Analysis?
Lexical analysis is the process of breaking down the source code of the program into smaller parts, called tokens, such that a computer can easily understand. These tokens can be individual words or symbols in a sentence, such as keywords, variable names, numbers, and punctuation. It is also known as a scanner. Lexical Analysis can be implemented with the Deterministic Finite Automata. The output generated from Lexical Analysis are a sequence of tokens sent to the parser for syntax analysis.
What is a Token?
A lexical token is a sequence of characters that can be treated as a unit in the grammar of the programming languages.
Example of tokens
- Type token (id, number, real, . . . )
- Punctuation tokens (IF, void, return, . . . )
- Alphabetic tokens (keywords)
Keywords; Examples - for, while, if etc.
Identifier; Examples - Variable name, function name, etc.
Operators; Examples '+', '++', '-' etc.
Separators; Examples ',' ';' etc
Example of Non-Tokens
- Comments, preprocessor directive, macros, blanks, tabs, newline, etc.
What is a Lexeme?
The sequence of characters matched by a pattern to form the corresponding token or a sequence of input characters that comprises a single token is called a lexeme. eg- “float”, “abs_zero_Kelvin”, “=”, “-”, “273”, “;” .
How Lexical Analyzer Works?
- Input preprocessing: This stage involves cleaning up the input text and preparing it for lexical analysis. This may include removing comments, whitespace, and other non-essential characters from the input text.
- Tokenization: This is the process of breaking the input text into a sequence of tokens. This is usually done by matching the characters in the input text against a set of patterns or regular expressions that define the different types of tokens.
- Token classification: In this stage, the lexer determines the type of each token. For example, in a programming language, the lexer might classify keywords, identifiers, operators, and punctuation symbols as separate token types.
- Token validation: In this stage, the lexer checks that each token is valid according to the rules of the programming language. For example, it might check that a variable name is a valid identifier, or that an operator has the correct syntax.
- Output generation: In this final stage, the lexer generates the output of the lexical analysis process, which is typically a list of tokens. This list of tokens can then be passed to the next stage of compilation or interpretation.

The lexical analyzer identifies the error with the help of the automation machine and the grammar of the given language on which it is based like C, C++, and gives row number and column number of the error.
Suppose we pass a statement through lexical analyzer: a = b + c;
It will generate token sequence like this: id=id+id;
Where each id refers to it’s variable in the symbol table referencing all details For example, consider the program
int main()
{
// 2 variables
int a, b;
a = 10;
return 0;
}
All the valid tokens are:
'int' 'main' '(' ')' '{' 'int' 'a' ',' 'b' ';'
'a' '=' '10' ';' 'return' '0' ';' '}'
Above are the valid tokens. You can observe that we have omitted comments. As another example, consider below printf statement.
There are 5 valid token in this printf statement.
Exercise 1: Count number of tokens:
int main()
{
int a = 10, b = 20;
printf("sum is:%d",a+b);
return 0;
}
Answer: Total number of token: 27.
Exercise 2: Count number of tokens: int max(int i);
- Lexical analyzer first read int and finds it to be valid and accepts as token.
- max is read by it and found to be a valid function name after reading (
- int is also a token , then again I as another token and finally ;
Answer: Total number of tokens 7:
int, max, ( ,int, i, ), ;
We can represent in the form of lexemes and tokens as under
| Lexemes |
Tokens |
Lexemes |
Tokens |
|
| while |
WHILE |
a |
IDENTIEFIER |
|
| ( |
LAPREN |
= |
ASSIGNMENT |
|
| a |
IDENTIFIER |
a |
IDENTIFIER |
|
| >= |
COMPARISON |
– |
ARITHMETIC |
|
| b |
IDENTIFIER |
2 |
INTEGER |
|
| ) |
RPAREN |
; |
SEMICOLON |
|
Advantages
- Simplifies Parsing:Breaking down the source code into tokens makes it easier for computers to understand and work with the code. This helps programs like compilers or interpreters to figure out what the code is supposed to do. It’s like breaking down a big puzzle into smaller pieces, which makes it easier to put together and solve.
- Error Detection: Lexical analysis will detect lexical errors such as misspelled keywords or undefined symbols early in the compilation process. This helps in improving the overall efficiency of the compiler or interpreter by identifying errors sooner rather than later.
- Efficiency: Once the source code is converted into tokens, subsequent phases of compilation or interpretation can operate more efficiently. Parsing and semantic analysis become faster and more streamlined when working with tokenized input.
Disadvantages
- Limited Context: Lexical analysis operates based on individual tokens and does not consider the overall context of the code. This can sometimes lead to ambiguity or misinterpretation of the code’s intended meaning especially in languages with complex syntax or semantics.
- Overhead: Although lexical analysis is necessary for the compilation or interpretation process, it adds an extra layer of overhead. Tokenizing the source code requires additional computational resources which can impact the overall performance of the compiler or interpreter.
- Debugging Challenges: Lexical errors detected during the analysis phase may not always provide clear indications of their origins in the original source code. Debugging such errors can be challenging especially if they result from subtle mistakes in the lexical analysis process.
For Previous Year Questions on Lexical Analysis, refer to https://www.geeksforgeeks.org/lexical-analysis-gq/.
Conclusion
Lexical Analysis is the first phase of compilation which breaks source code into meaningful tokens. The raw code is being transformed into structured tokens as eliminating all redundant information like white space and comments. Hence, the code is prepared for syntactic and further semantic analysis before actual interpretation. In addition to this, lexical errors are also identified at this stage as well, which makes the compiler process the code more efficiently. It essentially acts as a bridge between human-understandable code and machine-understandable structure.
Introduction of Lexical Analysis – FAQs
What is the purpose of lexical analysis in a compiler?
Lexical analysis converts source code into tokens. Those are the atomic units of meaning, keywords, operators, identifiers, etc., which are extracted with lexical analysis. Unwanted elements include white space and comments.
What is a token in lexical analysis?
A token is a classified unit of code, or a keyword such as int and if, an identifier such as x or y, an operator like + or =, or a literal such as constants, 10, “hello”.
What does a lexical analyzer do?
Tokenization, removes comments and white space, and error detection for unmng terms or strings.
How does lexical analysis handle errors?
It detects and outputs lexical errors including illegal characters or malformed tokens, which are then corrected by the developer for further processing.
What does lexical analysis pass on to the next phase?
After lexical analysis, tokens are passed on to the syntax analysis phase. The syntax analysis checks whether the code structure complies with the grammar of the chosen programming language.
Similar Reads
Compiler Design Tutorial
A compiler is software that translates or converts a program written in a high-level language (Source Language) into a low-level language (Machine Language or Assembly Language). Compiler design is the process of developing a compiler. It involves many stages like lexical analysis, syntax analysis (
3 min read
Introduction
Introduction of Compiler Design
Compiler design is design of a software that translates the source code written in a high-level programming language (Like C, C++, Java or Python) into the low level language like Machine code, Assembly code or Byte code. It comprises a number of phases where the code is pre-processed, and parsed, i
12 min read
Compiler construction tools
The compiler writer can use some specialized tools that help in implementing various phases of a compiler. These tools assist in the creation of an entire compiler or its parts. Some commonly used compiler construction tools include: Parser Generator - It produces syntax analyzers (parsers) from the
4 min read
Phases of a Compiler
Prerequisite - Introduction of Compiler design We basically have two phases of compilers, namely the Analysis phase and Synthesis phase. The analysis phase creates an intermediate representation from the given source code. The synthesis phase creates an equivalent target program from the intermediat
7 min read
Symbol Table in Compiler
Every compiler uses a major tool called the symbol table to keep track of all the variables, functions, and other identifiers a program may have. The symbol table will store the name, its type, and perhaps its memory locations to support the compiler in error checking, scope management, and the opti
10 min read
Error detection and Recovery in Compiler
In this phase of compilation, all possible errors made by the user are detected and reported to the user in form of error messages. This process of locating errors and reporting them to users is called the Error Handling process. Functions of an Error handler. DetectionReportingRecoveryClassificatio
6 min read
Error Handling in Compiler Design
The tasks of the Error Handling process are to detect each error, report it to the user, and then make some recovery strategy and implement them to handle the error. During this whole process processing time of the program should not be slow. Functions of Error Handler: Error DetectionError ReportEr
7 min read
Language Processors: Assembler, Compiler and Interpreter
Computer programs are generally written in high-level languages (like C++, Python, and Java). A language processor, or language translator, is a computer program that convert source code from one programming language to another language or to machine code (also known as object code). They also find
5 min read
Generation of Programming Languages
Programming languages have evolved significantly over time, moving from fundamental machine-specific code to complex languages that are simpler to write and understand. Each new generation of programming languages has improved, allowing developers to create more efficient, human-readable, and adapta
6 min read
Parsers
Parsing | Set 1 (Introduction, Ambiguity and Parsers)
Parsing, also known as syntactic analysis, refers to the process of performing token order analysis to determine the syntactic structure of tokens. In parsing, the token stream (generated by the word parser) is processed, and the parser constructs a parse tree or syntax tree. This tree provides a hi
4 min read
Classification of Top Down Parsers
Parsing is classified into two categories, i.e. Top-Down Parsing, and Bottom-Up Parsing. Top-Down Parsing is based on Left Most Derivation whereas Bottom-Up Parsing is dependent on Reverse Right Most Derivation. The process of constructing the parse tree which starts from the root and goes down to
5 min read
Bottom-up or Shift Reduce Parsers | Set 2
In this article, we are discussing the Bottom Up parser. Bottom-up Parsers / Shift Reduce Parsers Build the parse tree from leaves to root. Bottom-up parsing can be defined as an attempt to reduce the input string w to the start symbol of grammar by tracing out the rightmost derivations of w in reve
6 min read
Shift Reduce Parser in Compiler
Prerequisite – Parsing | Set 2 (Bottom Up or Shift Reduce Parsers) Shift Reduce parser attempts for the construction of parse in a similar manner as done in bottom-up parsing i.e. the parse tree is constructed from leaves(bottom) to the root(up). A more general form of the shift-reduce parser is the
8 min read
SLR Parser (with Examples)
LR parsers is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for left-to-right scanningR stands for rightmost derivation in reversek is several input symbols. when k is omitted k is assumed to be 1. A
4 min read
CLR Parser (with Examples)
LR parsers :It is an efficient bottom-up syntax analysis technique that can be used to parse large classes of context-free grammar is called LR(k) parsing. L stands for the left to right scanningR stands for rightmost derivation in reversek stands for no. of input symbols of lookahead Advantages of
7 min read
Construction of LL(1) Parsing Table
Parsing is an essential part of computer science, especially in compilers and interpreters. From the various parsing techniques, LL(1) parsing is best. It uses a predictive, top-down approach. This allows efficient parsing without backtracking. This article will explore parsing and LL(1) parsing. It
7 min read
LALR Parser (with Examples)
LALR Parser :LALR Parser is lookahead LR parser. It is the most powerful parser which can handle large classes of grammar. The size of CLR parsing table is quite large as compared to other parsing table. LALR reduces the size of this table.LALR works similar to CLR. The only difference is , it combi
6 min read
Syntax Directed Translation
Code Generation and Optimization
Code Optimization in Compiler Design
Code optimization is a crucial phase in compiler design aimed at enhancing the performance and efficiency of the executable code. By improving the quality of the generated machine code optimizations can reduce execution time, minimize resource usage, and improve overall system performance. This proc
9 min read
Intermediate Code Generation in Compiler Design
In the analysis-synthesis model of a compiler, the front end of a compiler translates a source program into an independent intermediate code, then the back end of the compiler uses this intermediate code to generate the target code (which can be understood by the machine). The benefits of using mach
6 min read
Issues in the design of a code generator
A code generator is a crucial part of a compiler that converts the intermediate representation of source code into machine-readable instructions. Its main task is to produce the correct and efficient code that can be executed by a computer. The design of the code generator should ensure that it is e
7 min read
Three address code in Compiler
TAC is an intermediate representation of three-address code utilized by compilers to ease the process of code generation. Complex expressions are, therefore, decomposed into simple steps comprising, at most, three addresses: two operands and one result using this code. The results from TAC are alway
6 min read
Data flow analysis in Compiler
Data flow is analysis that determines the information regarding the definition and use of data in program. With the help of this analysis, optimization can be done. In general, its process in which values are computed using data flow analysis. The data flow property represents information that can b
6 min read
Compiler Design | Detection of a Loop in Three Address Code
Prerequisite - Three address code in Compiler Loop optimization is the phase after the Intermediate Code Generation. The main intention of this phase is to reduce the number of lines in a program. In any program majority of the time is spent actually inside the loop for an iterative program. In the
3 min read
Introduction of Object Code in Compiler Design
Let assume that, you have a c program, then you give the C program to compiler and compiler will produce the output in assembly code. Now, that assembly language code will give to the assembler and assembler is going to produce you some code. That is known as Object Code. In the context of compiler
7 min read
Data flow analysis in Compiler
Data flow is analysis that determines the information regarding the definition and use of data in program. With the help of this analysis, optimization can be done. In general, its process in which values are computed using data flow analysis. The data flow property represents information that can b
6 min read
Compiler Design GATE PYQ's and MCQs