Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lex Program to check for comment lines

Tags:

lex

Could anyone please help me in writing a LEX program to check and count comment lines in a C program. I have searched for it everywhere and failed to get the complete code.

like image 561
Steve Avatar asked Dec 12 '25 06:12

Steve


1 Answers

comment lines are of the form

%% {START} {whatever symbols,alphanumerics and letters} {END} %%

  • START symbol can be // or /* in C.
  • END symbol is */
  • If it is "//" any other symbol can follow it in the LINE including a second occurances of // (which is ignored).
  • IF it is " /* " it will find the next immediate match for " */ " and all the rest of the patterns that appear in between is matched(This matching may include blank spaces,tabs ,"//" and " /* " in it)

Here is a sample code to do it

`   

%{
#include<stdio.h>
int c=0;
%}
START "/*"
END "*/"
SIMPLE [^*]
SPACE [ \t\n]
COMPLEX "*"[^/]
%s newstate
%%
"//"(.*[ \t]*.*)*[\n]+    {c++; fprintf(yyout," ");}
{START}                    {yymore();BEGIN newstate;}
 <newstate>{SIMPLE}        {yymore();BEGIN newstate;}
 <newstate>{COMPLEX}      {yymore();BEGIN newstate;}
 <newstate>{SPACE}        {yymore();BEGIN newstate;}
 <newstate>{END}  {c++;fprintf(yyout," ");BEGIN 0;}
%%
main()
{//program to remove comment lines
yyin=fopen("file4","r");
yyout=fopen("fileout4","w");system("cat file4");
yylex();system("cat fileout4");
printf("no.of comments=%d",c);
fclose(yyin);
fclose(yyout);
}
`

The input file "file4" is below

/* #include <stdlib.h>


    {}.@All nonsense symbols */
//another comment
int main{}
{/**/
 printf("hello");
 /* comment inside// comment is ignored */
 //how about//this?
 /* now we /* try this */ */
 printf("COOL!!");
 return (0);
}

It gives the following output which is stored in "fileout4" `

 int main{}
{


 printf("hello");
     */
 printf("COOL!!");
 return (0);
}

`

The number of comment lines in the above program is 6.

like image 85
kiran br Avatar answered Dec 16 '25 01:12

kiran br