Saturday, December 4, 2010

Some Words On LEX

Lex

Lex stands for Lexical Analyzer. Lex is a tool for generating scanners. Scanners are programs that recognize lexical patterns in text. These lexical patterns (or regular expressions) are defined in a particular syntax. A matched regular expression may have an associated action. This action may also include returning a token. When Lex receives input in the form of a file or text, it attempts to match the text with the regular expression. It takes input one character at a time and continues until a pattern is matched. If a pattern can be matched, then Lex performs the associated action (which may include returning a token). If, on the other hand, no regular expression can be matched, further processing stops and Lex displays an error message.

Lex and C are tightly coupled. A .lex file (files in Lex have the extension .lex) is passed through the lex utility, and produces output files in C. These file(s) are compiled to produce an executable version of the lexical analyzer.

Regular expressions in Lex
A regular expression is a pattern description using a meta language. An expression is made up of symbols. Normal symbols are characters and numbers, but there are other symbols that have special meaning in Lex. The following two tables define some of the symbols used in Lex and give a few typical examples.

Defining regular expressions in Lex
Character Meaning
A-Z, 0-9, a-z Characters and numbers that form part of the pattern.
. Matches any character except \n.
- Used to denote range. Example: A-Z implies all characters from A to Z.
[ ] A character class. Matches any character in the brackets. If the first character is ^ then it indicates a negation pattern. Example: [abC] matches either of a, b, and C.
* Match zero or more occurrences of the preceding pattern.
+ Matches one or more occurrences of the preceding pattern.
? Matches zero or one occurrences of the preceding pattern.
$ Matches end of line as the last character of the pattern.
{ } Indicates how many times a pattern can be present. Example: A{1,3} implies one or three occurrences of A may be present.
\ Used to escape meta characters. Also used to remove the special meaning of characters as defined in this table.
^ Negation.
| Logical OR between expressions.
"" Literal meanings of characters. Meta characters hold.
/ Look ahead. Matches the preceding pattern only if followed by the succeeding expression. Example: A0/1 matches A0 only if A01 is the input.
( ) Groups a series of regular expressions.

Examples of regular expressions
Regular expression Meaning
joke[rs] Matches either jokes or joker.
A{1,2}shis+ Matches AAshis, Ashis, AAshi, Ashi.
(A[b-e])+ Matches zero or one occurrences of A followed by any character from b to e.
Tokens in Lex are declared like variable names in C. Every token has an associated expression. (Examples of tokens and expression are given in the following table.) Using the examples in our tables, we'll build a word-counting program. Our first task will be to show how tokens are declared.

Examples of token declarations
Token
Associated expression Meaning
number ([0-9])+ 1 or more occurrences of a digit
chars [A-Za-z] Any character
blank " " A blank space
word (chars)+ 1 or more occurrences of chars
variable (chars)+(number)*(chars)*( number)*

Programming in Lex
Programming in Lex can be divided into three steps:
1. Specify the pattern-associated actions in a form that Lex can understand.
2. Run Lex over this file to generate C code for the scanner.
3. Compile and link the C code to produce the executable scanner.
Note: If the scanner is part of a parser developed using Yacc, only steps 1 and 2 should be performed.
Now let's look at the kind of program format that Lex understands. A Lex program is divided into three sections: the first section has global C and Lex declarations, the second section has the patterns (coded in C), and the third section has supplemental C functions. main(), for example, would typically be found in the third section. These sections are delimited by %%. So, to get back to the word-counting Lex program, let's look at the composition of the various program sections.


Global C and Lex declarations
In this section we can add C variable declarations. We will declare an integer variable here for our word-counting program that holds the number of words counted by the program. We'll also perform token declarations of Lex.

Declarations for the word-counting program
%{
int wordCount = 0;
%}
chars [A-za-z\_\'\.\"]
numbers ([0-9])+
delim [" "\n\t]
whitespace {delim}+
words {chars}+
%%
The double percent sign implies the end of this section and the beginning of the second of the three sections in Lex programming.

Lex rules for matching patterns
Let's look at the Lex rules for describing the token that we want to match. (We'll use C to define what to do when a token is matched.) Continuing with our word-counting program, here are the rules for matching tokens.

Lex rules for the word-counting program
{words} { wordCount++; /*
increase the word count by one*/ }
{whitespace} { /* do
nothing*/ }
{numbers} { /* one may
want to add some processing here*/ }
%%

C code
The third and final section of programming in Lex covers C function declarations (and occasionally the main function) Note that this section has to include the yywrap() function. Lex has a set of functions and variables that are available to the user. One of them is yywrap. Typically, yywrap() is defined as shown in the example below.

C code section for the word-counting program
void main()
{
yylex(); /* start the analysis*/
printf(" No of words:
%d\n", wordCount);
}
int yywrap()
{
return 1;
}
In the preceding sections we've discussed the basic elements of Lex programming, which should help you in writing simple lexical analysis programs.

Putting it all together
The .lex file is Lex's scanner. It is presented to the Lex program as:
$ lex
This produces the lex.yy.c file, which can be compiled using a C compiler. It can also be used with a parser to produce an executable, or you can include the Lex library in the link step with the option –ll.
Here are some of Lex's flags:
• -c Indicates C actions and is the default.
• -t Causes the lex.yy.c program to be written instead to standard output.
• -v Provides a two-line summary of statistics.
• -n Will not print out the -v summary.


Advanced Lex
Lex has several functions and variables that provide different information and can be used to build programs that can perform complex functions. Some of these variables and functions, along with their uses, are listed in the following tables.

Lex variables
yyin Of the type FILE*. This points to the current file being parsed by the lexer.
yyout Of the type FILE*. This points to the location where the output of the lexer will be written. By default, both yyin and yyout point to standard input and output.
yytext The text of the matched pattern is stored in this variable (char*).
yyleng Gives the length of the matched pattern.
yylineno Provides current line number information. (May or may not be supported by the lexer.)

Lex functions
yylex() The function that starts the analysis. It is automatically generated by Lex.
yywrap() This function is called when end of file (or input) is encountered. If this function returns 1, the parsing stops. So, this can be used to parse multiple files. Code can be written in the third section, which will allow multiple files to be parsed. The strategy is to make yyin file pointer (see the preceding table) point to a different file until all the files are parsed. At the end, yywrap() can return 1 to indicate end of parsing.
yyless(int n) This function can be used to push back all but first ‘n’ characters of the read token.
yymore() This function tells the lexer to append the next token to the current token.

SHIFT REDUCE PARSER(in C)

#include
#include
#include
char stack[20];
char input[30];
int curr;
int stacktop=-1;
int len;
void pop()
{
stacktop-=2;
}
void printstack()
{ int i;
printf("\n");
for(i=0;i<=stacktop;i++)
printf("%c",stack[i]);
}
void printinput()
{
int j;
printf("\t\t");
for(j=curr+1;j printf("%c",input[j]);
}
int isnum(char c)
{
switch(c)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':return 1;
break;
default:return 0;

}
}
int isoper(char c)
{
switch(c)
{
case '+':return 2;
break;
case '-':return 3;
break;
case '*':return 4;
break;
case '/':return 5;
break;
default:return 0;

}
}
void shift(char in)
{
stacktop++;
stack[stacktop]=in;
printstack();
printinput();
printf("\t\tShift\n");
}
void reduce(int id)
{
printf("\t\t");
if(id==1)
{
stack[stacktop]='E';
printf("Reduced by E->id");
}
if(id==2)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E+E");
}
if(id==3)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E-E");
}
if(id==4)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E*E");
}
if(id==5)
{
pop();
stack[stacktop]='E';
printf("Reduced by E->E/E");
}
printf("\n");
}
int main()
{
int op;
printf("\nEnter the string to be tested:");
scanf("%s",input);
printf("\n%s\n",input);
curr=0;
len=strlen(input);
if(isoper(input[curr]))
{
printf("\n\nERROR REJECTED");
exit(1);
}
printf("\n\nSTACK\t\tINPUT\t\tCOMMENT\n");
do{
if(isnum(input[curr]))
{
shift(input[curr]);
reduce(1);
curr++;
}
op=isoper(input[curr]);
if(op>0)
{
shift(input[curr]);
curr++;
shift(input[curr]);
curr++;
if(isnum(stack[stacktop]))
{
reduce(op);
}
else
{
printf("\n\nERROR!! STIRNG REJECTED\n");
}
}
}while(curr if(stacktop==0&&stack[stacktop]=='E')
printf("\nString ACCEPTED\n");
}

Recognization of IF ELSE/WHILE/DO WHILE Statements

LEX PROGRAM

%{
%}
ID [A-Za-z][A-Za-z0-9]*
DIGIT [0-9]+
%%
"if" {return IF;}
"else" {return ELSE;}
"while" {return WHILE;}
"do" {return DO;}
{ID} {return ID;}
{DIGIT} {return DIGIT;}
"+"|"-"|"*"|"/"|"<"|">"|"<="|">="|"||"|"&&"|"=="|"%"|"!=" {return OPERATOR;}
"}" {return *yytext;}
"{" {return *yytext;}
")" {return *yytext;}
"(" {return *yytext;}
";" {return *yytext;}
[\t\n] { ;}
%%
int yywrap()
{
return 1;
}



YACC PROGRAM



%{
#include
%}
%token DIGIT
%token OPERATOR
%token IF
%token ELSE
%token WHILE
%token ID
%token DO
%%
START :while_stmt{printf("success");}
|if_stmt{printf("success");}
|dowhile_stmt{printf("success");}
|error {printf("not correct");}
;
dowhile_stmt:DO'{'stmt_list'}'WHILE'('E')'';'
|DO E';'WHILE'('E')'';'
;
while_stmt:WHILE'('E')''{'stmt_list'}'
|WHILE'('E')'';'
|WHILE'('E')'E';'
;
if_stmt:IF'('E')''{'stmt_list'}'
|IF'('E')''{'stmt_list'}'ELSE'{'stmt_list'}'
|IF'('E')'';'
|IF'('E')'E';'
|IF'('E')'';'ELSE';'
|IF'('E')'E';'ELSE';'
;
stmt_list:stmt_list E';'
|E ';'
|if_stmt
|while_stmt
|dowhile_stmt
|
;
E:E OPERATOR E
|ID
|DIGIT
|'('E')'
;
%%
#include "lex.yy.c"
int yyerror(char *s)
{
fprintf(stderr,"%s is error\n",s);
return 1;
}
int main()
{
yyin=fopen("input","r");
yyparse();
fclose(yyin);
return 0;
}

INFIX EXPRESSION TO POSTFIX EXPRESSION

LEX PROGRAM

%{



%}

dig [0-9]+
%%

{dig} {
yylval.no = atoi(yytext);
return DIGIT;
}
[a-zA-Z][a-zA-Z0-9]* {
strcpy(yylval.str,yytext);
return ID;
}

"+" {return *yytext;}
"-" {return *yytext;}
"*" {return *yytext;}
"/" {return *yytext;}
"^" {return *yytext;}
"(" {return *yytext;}
")" {return *yytext;}
"\n" {return 0;}



%%

int yywrap()
{
return 1;
}


YACC PROGRAM


%{
#include
#include
#include
#include
%}

%union
{
int no;
char str[10];
}

%token DIGIT
%token ID
%left '+''-'
%left '*''/'
%right '^'
%left '(' ')'

%%
STMT:EXPR {printf("\n");}
;
EXPR:EXPR'+'EXPR { printf("+");}
|EXPR'-'EXPR { printf("-");}
|EXPR'*'EXPR { printf("*");}
|EXPR'/'EXPR { printf("/");}
|EXPR'^'EXPR { printf("^");}
|'('EXPR')'
|DIGIT { printf("\n%d",yylval.no);}
|ID { printf("\n%s",yylval.str);}
;
%%

yyerror()
{
printf("\n error");
}


#include "lex.yy.c"

int main()
{
yyparse();
return 0;
}

IDENTIFICATION OF Switch Case Statements!

LEX PROGRAM

%{
%}
ID [a-zA-Z][a-zA-Z0-9]*
NUMBER ([0-9]+)|([0-9]+\.[0-9]+)
OP "+"|"-"|"*"|"/"|"--"|"&&"|"||"|">"|"<"|"=="|">="|"<="|"="
%%
SWITCH {/*printf("It is switch\n");*/ return SWITCH; }
CASE {/*printf("It is case\n");*/ return CASE; }
BREAK {/*printf("It is case\n");*/ return BREAK; }
DEFAULT {/*printf("It is case\n");*/ return DEFAULT; }
{ID} {/*printf("It is id\n");*/ return ID; }
{NUMBER} {/*printf("It is number\n");*/ return NUMBER; }
{OP} {/*printf("It is operator\n");*/ return OP; }
"(" {return *yytext;}
")" {return *yytext;}
"{" {return *yytext;}
"}" {return *yytext;}
";" {return *yytext;}
":" {return *yytext;}
"\n" {return *yytext;}
[ \t] {}
. {return *yytext;}
%%
/*
int main()
{
yyin = fopen("test","r");
yylex();
}
*/
int yywrap()
{
return 1;
}

YACC PROGRAM

%token NUMBER
%token SWITCH
%token CASE
%token BREAK
%token DEFAULT
%token OP
%token '\n'
%token ID
%{
#include
int lineno=1;
%}
%%
STMT_LIST : STMT_LIST SWITCH_STMT '\n' {printf("VALID STATEMENT...\n"); lineno++; }
| error '\n' {printf("INVALID...\n"); lineno++; }
|
;
SWITCH_STMT : SWITCH'('EXPR')''{'CASE EXPR':'STMTS'}'
| SWITCH'('EXPR')''{'CASE EXPR':'STMTS BREAK';''}'
| SWITCH'('EXPR')''{'CASE EXPR':'STMTS BREAK';'DEFAULT':'STMTS'}'
|
;
STMTS : EXPR';'
|
;
EXPR : EXPR OP EXPR
| ID
| NUMBER
|
;
%%
#include "lex.yy.c"
int main()
{
yyin = fopen("test","r");
yyparse();
}
int yyerror(char *s)
{
fprintf(stderr," %s at line no %d. ",s,lineno);
}

IDENTIFYING DECLARATION STATEMENTS

LEX PROGRAM

%{
%}
VAR [a-zA-Z][a-zA-Z0-9]*
INT "INT"|"int"
%%
{INT} { return INT; }
"FLOAT" { return FLOAT; }
"CHAR" { return CHAR; }
{VAR} { return VAR; }
";" { return *yytext; }
"," { return *yytext; }
"\n" { return *yytext; }
[ \t] {}
%%
int yywrap()
{
return 1;
}



YACC PROGRAM


%token INT
%token FLOAT
%token CHAR
%token VAR
%{
%}
%%
line:line dec '\n' { printf("\nACCEPTED..\n"); }
|error '\n' { printf("\nINVALID...\n"); }
|
;
dec:keyword idef';'
|
;
keyword:INT
|FLOAT
|CHAR
;
idef:VAR','VAR
|VAR
;
%%
#include "lex.yy.c"
#include
void yyerror(char *s)
{
fprintf(stderr,"\n%s...\n",s);
}
int main()
{
yyparse();
exit(50);
}

LexicalAnalyser for data types(using LEX)

%{
int nreal=0;
int nint=0;
int ndec=0;
int nimg=0;
%}
int [\+|\-]?[0-9]+
dec [\+|\-]?[0-9]+[\.][0-9]+
real [\+|\-]?[0-9]+[\.][0-9]*e[\+|\-]?[0-9]+
imag [\+|\-]?[0-9]+[i|j]*[\+|\-]?[0-9]+
%%
{int} {nint++;printf("\n%s is integr",yytext);}
{dec} {ndec++;printf("\n%s is decimal",yytext);}
{real} {nreal++;printf("\n%s is real",yytext);}
{imag} {nimg++;printf("\n%s is img",yytext);}
%%
int main()
{
yyin = fopen("d.txt","r");
yylex();
printf("\nno of integers is %d",nint);
printf("\nno of decimals is %d",ndec);
printf("\nno of real is %d",nreal+ndec+nint);
printf("\nno of imaginay is %d\n",nimg);
fclose(yyin);
return 0;
}
int yywrap(void)
{
return 1;
}