Premier exercice
This commit is contained in:
29
lexical/example.l
Normal file
29
lexical/example.l
Normal file
@ -0,0 +1,29 @@
|
||||
%option noyywrap
|
||||
|
||||
%{
|
||||
int lines = 1; // On compte la première ligne
|
||||
%}
|
||||
|
||||
DIG [0-9]
|
||||
HEX 0x[0-9A-Fa-f]+
|
||||
|
||||
%%
|
||||
|
||||
{HEX} { printf("hex(%d)", strtol(yytext, NULL, 16)); }
|
||||
{DIG}+ { printf("int(%d)", atoi(yytext)); }
|
||||
"if" { printf("IF"); }
|
||||
"then" { printf("THEN"); }
|
||||
"else" { printf("ELSE"); }
|
||||
\n { lines++; }
|
||||
. { /* Pour tous les autres caractères, on ne fait rien */ }
|
||||
|
||||
%%
|
||||
|
||||
int main (int argc, char **argv)
|
||||
{
|
||||
if (argc > 1) yyin = fopen(argv[1], "r");
|
||||
yylex();
|
||||
puts("");
|
||||
printf("%d lignes\n", lines);
|
||||
return 0;
|
||||
}
|
34
lexical/flux.l
Normal file
34
lexical/flux.l
Normal file
@ -0,0 +1,34 @@
|
||||
%option noyywrap
|
||||
|
||||
%{
|
||||
enum { T_INT = 1, T_CHAR = 2 };
|
||||
union {
|
||||
int i;
|
||||
char c;
|
||||
} data;
|
||||
%}
|
||||
|
||||
DIG [0-9]
|
||||
|
||||
%%
|
||||
|
||||
{DIG}+ { data.i = atoi(yytext); return T_INT; }
|
||||
[+*()] { data.c = *yytext; return T_CHAR; }
|
||||
[ \n] { /* ignore */ }
|
||||
|
||||
%%
|
||||
|
||||
int main (int argc, char **argv)
|
||||
{
|
||||
int token;
|
||||
if (argc > 1) yyin = fopen(argv[1],"r");
|
||||
while (token = yylex())
|
||||
{
|
||||
switch(token)
|
||||
{
|
||||
case T_INT: printf("int(%d) ",data.i); break;
|
||||
case T_CHAR: printf("'%c' ",data.c); break;
|
||||
}
|
||||
}
|
||||
puts("");
|
||||
}
|
26
lexical/string.l
Normal file
26
lexical/string.l
Normal file
@ -0,0 +1,26 @@
|
||||
%option noyywrap
|
||||
|
||||
DIG [0-9]
|
||||
|
||||
%%
|
||||
|
||||
{DIG}+ { printf("int(%d) ",atoi(yytext)); }
|
||||
[+*()] { printf("'%c' ",*yytext); }
|
||||
[ \n] { /* ignore */ }
|
||||
|
||||
%%
|
||||
|
||||
int main (int argc, char **argv)
|
||||
{
|
||||
YY_BUFFER_STATE buffer;
|
||||
|
||||
buffer = yy_scan_string("100+5*2");
|
||||
yylex();
|
||||
yy_delete_buffer(buffer);
|
||||
|
||||
buffer = yy_scan_string("20+30");
|
||||
yylex();
|
||||
yy_delete_buffer(buffer);
|
||||
|
||||
puts("");
|
||||
}
|
Reference in New Issue
Block a user