Reputation: 3465
I'm trying to describe grammar for toy language. Here is the contents of tokens.lex
:
/* Simple scanner for a toy language */
%{
/* need this for the call to atof() below */
#include <string.h>
#include <math.h>
%}
IDENTIFIER [a-z][a-z0-9]*
DIGIT [0-9]
%%
{DIGIT}+ {
printf("int: %s (%d)\n", yytext, atoi(yytext));
yylval.string = new std::string(yytext, yyleng);
} /* define int type */
{DIGIT}+"."{DIGIT}+ {
printf("float: %s (%d)\n", yytext, atof(yytext));
yylval.string = new std::string(yytext, yyleng);
} /* define float type */
b[\'\"]{IDENTIFIER}[\'\"] {
printf("bstream: %s\n", yytext);
yylval.string = new std::string(yytext, yyleng);
} /* define bstream type */
u[\'\"]{IDENTIFIER}[\'\"] {
printf("ustream: %s\n", yytext);
yylval.string = new std::string(yytext, yyleng);
} /* define ustream type */
if|then|begin|end|procedure|function {
printf( "A keyword: %s\n", yytext );
}
{IDENTIFIER} printf( "identifier: %s\n", yytext );
"+"|"-"|"*"|"/" printf( "operator: %s\n", yytext );
"{"[^}\n]*"}" /* Remove one-line comments */
[ \t\n]+ /* Remove whitespace */
. printf( "Unrecognized character: %s\n", yytext );
%%
int argc;
char **argv;
int main(argc, argv);
{
if ( argc > 0 )
yyin = fopen( argv[0], "r" );
else
yyin = stdin;
yylex();
}
Then I try to compile it:
lex tokens.lex && g++ -lfl lex.yy.c
Compiler returns a couple of errors:
tokens.lex:51:20: error: expression list treated as compound expression in initializer [-fpermissive]
tokens.lex:51:20: error: invalid conversion from ‘char**’ to ‘int’ [-fpermissive]
tokens.lex:52:3: error: expected unqualified-id before ‘{’ token
What can be wrong here? I'm not very strong in C/C++, so I can't find out what happens here. Could you help me, please? THanks!
Upvotes: 0
Views: 2982
Reputation: 310913
Your main() argument declarations are incorrect 'C' syntax as noted in another answer, but this is all wrong anyway. Your lexer has to return tokens, not just print them. The main() function for lex/flex must call yylex() until it returns zero or -1 or whatever the EOS indication is. That's what the one in the lex library does.
Upvotes: 0
Reputation: 523294
The correct way to write the main function is:
int main(int argc, char** argv)
{
if (argc > 1)
yyin = fopen(argv[1], "r");
else
yyin = stdin;
return yylex();
}
Upvotes: 1