compiler construction Lecture 8
compiler construction Lecture 8
COMPILER CONSTRUCTION(CS-636)
______________________________________________________
GIMS- PMAS Arid Agriculture University, Gujrat Campus
2
Specification File lex.l 3
%{
#include “tokdefs.h”
%}
D [0-9]
L [a-zA-Z_]
id {L}({L}|{D})*
%%
"void" {return(TOK_VOID);}
"int" {return(TOK_INT);}
"if" {return(TOK_IF);}
Specification File lex.l 4
"else" {return(TOK_ELSE);}
"while"{return(TOK_WHILE)};
"<=" {return(TOK_LE);}
">=" {return(TOK_GE);}
"==" {return(TOK_EQ);}
"!=" {return(TOK_NE);}
{D}+ {return(TOK_INT);}
{id} {return(TOK_ID);}
[\n]|[\t]|[ ] ;
%%
File tokdefs.h 5
#define TOK_VOID 1
#define TOK_INT 2
#define TOK_IF 3
#define TOK_ELSE 4
#define TOK_WHILE 5
#define TOK_LE 6
#define TOK_GE 7
#define TOK_EQ 8
#define TOK_NE 9
#define TOK_INT 10
#define TOK_ID 111
Invoking Flex 6
flex lex.l
g++ –c lex.cpp
g++ –c main.cpp
g++ –o lex.exe lex.o main.o
lex <main.cpp
Using Generated Scanner 9
void main()
{
FlexLexer lex;
int tc = lex.yylex();
while(tc != 0)
cout << tc << “,”
<<lex.YYText() << endl;
tc = lex.yylex();
}
Input Tokenized 10
258,tc
266,=
258,lex
291,.
258,yylex
283,(
284,)
290,;
263,while
Input Tokenized 12
283,(
258,tc
276,!=
257,0
284,)
258,cout
279,<<
258,tc
Input Tokenized 13
279,<<
292,","
279,<<
258,lex
291,.
258,YYText
283,(
284,)
279,<<
Input Tokenized 14
258,endl
290,;
258,tc
266,=
258,lex
291,.
258,yylex
283,(
284,)
290,;
286,}
Flex Input for C++ 15
/*
* ISO C++ lexical analyzer.
* Based on the ISO C++ draft standard of December
'96.
*/
%{
#include <ctype.h>
#include <stdio.h>
#include “tokdefs.h"
int lineno;
"/*" { skip_comment(); }
"//" { skip_until_eol(); }
[a-zA-Z_][a-zA-Z_0-9]*
{ return check_identifier(yytext); }
%%
static int
yywrap(void)
{
return 1;
}
static void
27
skip_comment(void)
{
int c1, c2;
c1 = input();
c2 = input();