Lex program to identify Well formedness of brackets

  1. Lex program contains three sections: definitions, rules, and user subroutines. Each section must be separated from the others by a line containing only the delimiter, %%.
The format is as follows: definitions %% rules %% user_subroutines
  1. In definition section, the variables make up the left column, and their definitions make up the right column. Any C statements should be enclosed in %{..}%. Identifier is defined such that the first letter of an identifier is alphabet and remaining letters are alphanumeric.
  2. In rules section, the left column contains the pattern to be recognized in an input file to yylex(). The right column contains the C program fragment executed when that pattern is recognized. The various patterns are keywords, operators, new line character, number, string, identifier, beginning and end of block, comment statements, preprocessor directive statements etc.
  3. Each pattern may have a corresponding action, that is, a fragment of C source code to execute when the pattern is matched.
  4. When yylex() matches a string in the input stream, it copies the matched text to an external character array, yytext, before it executes any actions in the rules section.
  5. In user subroutine section, main routine calls yylex(). yywrap() is used to get more input.
The lex command uses the rules and actions contained in file to generate a program, lex.yy.c, which can be compiled with the cc command. That program can then receive input, break the input into the logical pieces defined by the rules in file, and run program fragments contained in the actions in file.
				
					%{
/*input is b.c*/
#include<stdio.h>
#include<string.h>
char temp[10];
int i=0,openbracket=0,closebracket=0;
extern FILE *yyin;
%}

%%
"("[()]*")"";"{
strcpy(temp,yytext);
printf("%s\n",temp);
i=0;
while(temp[i]!=';')
{
if(temp[i]=='(')
openbracket++;
if(temp[i]==')')
closebracket++;
else ;
i++;
}

if(openbracket=closebracket)
printf("Well formed input!\n");
else
printf("not well formed!\n");
}
%%

main(int argc,char *argv[])
{
FILE *fp=fopen(argv[1],"r");
yyin=fp;
yylex();
fclose(fp);
}


          
				
			
[CSE@localhost ~]$ lex lex2.l

[CSE@localhost ~]$ gcc lex.yy.c -ll

[CSE@localhost ~]$. /a.out b.c

(());

Well formed input

[CSE@localhost ~]$ lex lex2.l

[CSE@localhost ~]$ gcc lex.yy.c -ll

[CSE@localhost ~]$. /a.out b.c

());

Not well formed

Leave a Reply