4-Intro To Flex and Bison-09!09!2024
4-Intro To Flex and Bison-09!09!2024
Symbol Table
4
Attributes of Tokens
<id, “y”> <assign, > <num, 31> <+, > <num, 28> <*, > <id, “x”>
token
tokenval
(token attribute) Parser
5
s0 =
si = si-1s for i > 0
note that s = s = s
8
letter AB…Zab…z
digit 01…9
id letter ( letterdigit )*
r+ = rr*
r? = r
[a-z] = abc…z
• Examples:
digit [0-9]
num digit+ (. digit+)? ( E (+-)? digit+ )?
13
lex.yy.c
C a.out
compiler
input sequence
stream a.out of tokens
18
{ definitions }
%%
{ rules }
%%
{ user subroutines }
How to run:
Compile:lex Programname.l
Run: cc lex.yy.c -lfl
Output: ./a.out
19
Lex Specification
• A lex specification consists of three parts:
regular definitions, C declarations in %{ %}
%%
translation rules
%%
user-defined auxiliary procedures
• The translation rules are of the form:
p1 { action1 }
p2 { action2 }
…
pn { actionn }
20
/* DESCRIPTION/DEFINITION SECTION */
%{
#include<stdio.h>
int lc=0,sc=0,tc=0,ch=0,wc=0; // GLOBAL VARIABLES
%}
// RULE SECTION
%%
[\n] { lc++; ch+=yyleng;}
[ \t] { sc++; ch+=yyleng;}
[^\t] { tc++; ch+=yyleng;}
[^\t\n ]+ { wc++; ch+=yyleng;}
%%
// MAIN FUNCTION
int main(){
printf("Enter the Sentence : ");
yylex();
printf("Number of lines : %d\n",lc);
printf("Number of spaces : %d\n",sc);
printf("Number of tabs, words, charc : %d , %d , %d\n",tc,wc,ch);
return 0;
}
22
Number
/*lex program to count number of words*/
of words
%{
#include<stdio.h>
#include<string.h>
int i = 0;
%}
/* Rules Section*/
%%
([a-zA-Z0-9])* {i++;} /* Rule for counting number of words*/
"\n" {printf("%d\n", i); i = 0;}
%%
int yywrap(void){}
int main()
{ // The function that starts the analysis
yylex();
return 0; }
23
Mobile Number
/* Lex Program to check valid Mobile Number */
%{
/* Definition section */
%}
/* Rule Section */
%%
[1-9][0-9]{9} {printf("\nMobile Number Valid\n");}
.+ {printf("\nMobile Number Invalid\n");}
%%
// driver code
int main()
{ printf("\nEnter Mobile Number : ");
yylex();
printf("\n");
return 0;
}
24
lex spec.l
gcc lex.yy.c -ll
./a.out < spec.l
26
%{
#include<stdio.h>
#include<string.h>
int i = 0;
%}
%%
([a-zA-Z0-9])* {i++;} /* Rule for counting
number of words*/
"\n" {printf("%d\n", i); i = 0;}
%%
int yywrap(void){}
int main()
{
yylex();
return 0;
}