Lecture 4
Lecture 4
Part 3
/* Input */ /* Output */
wewevWEUFWIGhHkkH WEUFWIG
sdcwehSDWEhTkFLksewT H
H
SDWE
T
FL
T - Part
Lexical Analysis
Definitions
Section
/* Input */ /* Output */
wewevWEUFWIGhHkkH WEUFWIG
sdcwehSDWEhTkFLksewT H
H
SDWE
T
FL
T
Lexical Analysis - Part
LEX Example 2: EX-
2.lex
%%
^[ ]*\n
\n {ECHO; yylineno++;}
.* {printf("%d\t%s",yylineno,yytext);}
%%
yywrap(){}
main(){ yylineno = 1; yylex(); }
1234
5678
9
euhoyo854
shacg345845nkfg
===============
=========
1 kurtrtotr
2 dvure
3
Lexical Analysis - Part
LEX Example 3: EX-
3.lex
%{
FILE *declfile;
%}
blanks [ \t]*
letter [a-
z] digit [0-
9]
id ({letter}|_)({letter}|{digit}|
_)* number {digit}+
arraydeclpart {id}"["{number}"]"
declpart ({arraydeclpart}|{id})
decllist ({declpart}
{blanks}","{blanks})*
Lexical Analysis - Part
LEX Example 3
(contd.)
%%
{declaration} fprintf(declfile,"%s\n",yytext);
%%
yywrap()
{ fclose(declfil
e);
}
main(){
declfile = fopen("declfile","w");
yylex();
}
ewl2efo24hg2jhrto;ty;
sdkvbwrkb;
sdvjkjkw
Lexical Analysis - Part
LEX Example 4: Identifiers, Reserved
Words, and Constants (id-hex-oct-int-1.lex)
%{
int hex = 0; int oct = 0; int regular =0;
%}
letter [a-zA-Z_]
digit [0-9]
digits {digit}+
digit_oct [0-7]
[0-9A-F]
digit_hex [uUlL]
int_qualifier [ \t]+
blanks {letter}
identifier ({letter
integer }|
hex_const {digit})
oct_const
*
Lexical Analysis - Part
LEX Example 4:
(contd.)
%%
if {printf("reserved word:%s\n",yytext);}
else {printf("reserved word:%s\n",yytext);}
while {printf("reserved word:%s\n",yytext);}
switch {printf("reserved word:%s\n",yytext);}
{identifier} {printf("identifier :%s\n",yytext);}
{hex_const} {sscanf(yytext,"%i",&hex);
printf("hex constant: %s = %i\n",yytext,hex);}
{oct_const} {sscanf(yytext,"%i",&oct);
printf("oct constant: %s = %i\n",yytext,oct);}
{integer} {sscanf(yytext,"%i",®ular);
printf("integer : %s = %i\n",yytext, regular);}
.|\n ;
%%
yywrap(){}
int main(){yylex();}
Lexical Analysis - Part
LEX Example 4: Input and
Output
uorme while
0345LA 456UB 0x786lHABC
b0x34
========================
identifier :uorme
reserved word:while
oct constant: 0345L = 229
identifier :A
integer : 456U = 456
identifier :B
hex constant: 0x786l = 1926
identifier :HABC
identifier :b0x34
number [0-9]+\.?|[0-9]*\.[0-9]+
name [A-Za-z][A-Za-z0-9]*
%%
[ ] {/* skip blanks */}
{number} {sscanf(yytext,"%lf",&yylval.dval);
return NUMBER;}
{name} {struct symtab *sp =symlook(yytext);
yylval.symp = sp; return NAME;}
"++" {return POSTPLUS;}
"--" {return POSTMINUS;}
\n|. {return yytext[0];}
"$" {return 0;}