0
0
Compiler Designknowledge~10 mins

Lex/Flex tool overview in Compiler Design - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lex/Flex tool overview
Write Lex/Flex rules
Run Lex/Flex tool
Generate C source code
Compile generated code
Use lexer in program
Input text scanned
Tokens produced for parser
The Lex/Flex tool reads rules, generates C code for a lexer, which is compiled and used to scan input text into tokens.
Execution Sample
Compiler Design
%{
#include <stdio.h>
%}
%%
[0-9]+  { printf("NUMBER\n"); }
%%
This Lex/Flex code matches numbers and prints 'NUMBER' when found.
Analysis Table
StepActionInputMatched PatternOutput/Result
1Start scanning123abcNone yetNo output
2Match digits123abc[0-9]+Print 'NUMBER'
3Advance inputabcNo matchNo output
4End scanningNo more inputStop
💡 Input fully scanned; no more tokens to produce.
State Tracker
VariableStartAfter Step 2After Step 3Final
Input Pointer0 (start)3 (after '123')6 (after 'abc')6 (end)
Current TokenNoneNUMBERNoneNone
Key Insights - 2 Insights
Why does the lexer print 'NUMBER' only after matching digits?
Because the pattern [0-9]+ matches one or more digits, as shown in execution_table step 2 where input '123' matches and triggers the action.
What happens when input characters do not match any pattern?
The lexer skips or stops scanning as in step 3, where 'abc' does not match the digit pattern, so no output is produced.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what pattern is matched?
A[A-Z]+
B[a-z]+
C[0-9]+
DNo pattern matched
💡 Hint
Check the 'Matched Pattern' column at step 2 in execution_table.
At which step does the input pointer reach the end of input?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at the 'Input Pointer' variable in variable_tracker and the 'Action' in execution_table.
If the input was '456xyz', what would be the output at step 2?
APrint 'WORD'
BPrint 'NUMBER'
CNo output
DError
💡 Hint
The pattern [0-9]+ matches digits at the start, as shown in execution_table step 2.
Concept Snapshot
Lex/Flex reads pattern-action rules.
Generates C code for a lexer.
Lexer scans input text.
Matches patterns produce tokens.
Tokens used by parser in compiler.
Full Transcript
Lex/Flex is a tool used in compiler design to create lexical analyzers. The process starts by writing rules that define patterns and actions. Running Lex/Flex generates C source code for a lexer. This code is compiled and used in a program to scan input text. The lexer reads the input, matches patterns like numbers or words, and produces tokens. These tokens are then passed to the parser for further processing. For example, a rule matching digits prints 'NUMBER' when digits are found. The lexer moves through the input, matching patterns step-by-step until all input is processed.