-3

I am making C compiler using flex on RED HAT LINUX . But its not going well , please help. Its not showing any of these. Why its not showing the output in the printf statement. How to create check of libraries and the pre defined directrives ?

keywords auto | break | default | case | for | char | malloc |int |const |continue |do |double |if |else | enum | extern |float | goto |long |void |return |short |static | sizeof|switch| typedef |union|unsigned| signed | volatile| while | do | struct



%%

{keywords}*
{
    printf ( "\n\n\nThese are keywords:" ) ; printf( "'%s'\n" , yytext ) ;
}


"#include define"
{
    printf ( "\n\n\nThese are predefined directives:" ); 
    printf( "'%s'\n",yytext );
}


"#include <"|"#include \" "
{
    printf ( "\n\n\nThese are libraries:");
    printf ( "'%s'\n",yytext);
}


""|,|;|:|!
{
    printf ("\n\n\n These are puctuation :") ; 
printf("'%s'\n",yytext);
}


"<<"|">>"|"<"|">"|"<="|">="|"+"|"-"|"*"|"/"|"{"|"}"|"["|"]"|"&&"|"||"
{
    printf("\n\n\nThese are operators:");
printf("'%s'\n",yytext);
}


"//"|"/*"|"*/"
{
    printf("\n\n\nThese are comments:");
printf("'%s'\n",yytext);
}
%%

int yywrap(void)
{
return 1;
}
int main (void)
{
yylex();
return 0;
}
Brian
  • 3,850
  • 3
  • 21
  • 37
MHS
  • 1
  • 5

1 Answers1

2

Your flex input is pretty broken, and won't actually generate a scanner, just a bunch of (probably very confusing) error messages.

The first issue is that spaces and newline are very important syntaxtically for flex -- spaces separate patterns from actions, and newlines end actions. So all the spaces in your keyword pattern are causing problems; you need to get rid of them:

keywords  auto|break|default|case|for|char|malloc|int|const|continue|do|double|if|else|enum|extern|float|goto|long|void|return|short|static|sizeof|switch|typedef|union|unsigned|signed|volatile|while|do|struct

Then, you can't have a newline between the pattern and action in a rule (otherwise you end up with two patterns and no actions). So you need:

{keywords}* { 
    printf ( "\n\n\nThese are keywords:" ) ; printf( "'%s'\n" , yytext ) ;
}

and likewise for the rest of the rules.

Once you do that, you can get your code to run through flex and produce a scanner. Now you can give it input and see what it does.

Anything that matches one of the rules will trigger that rule. For example, break will trigger the "keywords" rule, but so will things like casecharswitch or any other string of keywords mashed together. That's because you used a * on that rule.

Anything that doesn't match any of the rules will simply be echoed to the output. Since that probably isn't what you want, you need to make sure that you have rules that match . and \n at the end of the rules, so that every possible input will match some rule.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226