问题
Lex code:
identifier [\._a-zA-Z0-9\/]+
comment "//"
<*>{comment} {
cout<<"Comment\n";
char c;
while((c= yyinput()) != '\n')
{
}
}
<INITIAL>{s}{e}{t} {
BEGIN(SAMPLE_STATE);
return SET;
}
<SAMPLE_STATE>{identifier} {
strncpy(yylval.str, yytext,1023);
yylval.str[1023] = '\0';
return IDENTIFIER;
}
In the above lex code, there is no error when "// set name" is parsed. Please notice the space after "//" in the sentence parsed. However, when "//set name" is parsed, there is an error reported. Could you point to where I am going wrong? Thanks.
The error is caught by yyerror and reports
SampleParser.y:43: int CMTSTapTestSeq_yyerror(char*): Assertion `0 && "Error parsing Sample file\n"' failed.
This assertion is added by me.
回答1:
I think you have made a mistake in simplifying your example, as the code you supplied works fine and does not have the fault you indicated. I coded it up and tested it (I used C instead of C++ for convenience). However, I see you posted a later question with more code that explained the problem better. I answered that one also.
s s
e e
t t
identifier [\._a-zA-Z0-9\/]+
comment "//"
%s SAMPLE_STATE
%{
//#include <iostream>
//using namespace std;
#include <stdio.h>
#define SET 1
#define IDENTIFIER 2
#define yyinput input
%}
%%
<*>{comment} {
// cout<<"Comment\n";
printf("Comment\n");
char c;
while((c= yyinput()) != '\n')
{
}
}
<INITIAL>{s}{e}{t} {
BEGIN(SAMPLE_STATE);
//return SET;
printf("SET\n");
}
<SAMPLE_STATE>{identifier} {
//strncpy(yylval.str, yytext,1023);
//yylval.str[1023] = '\0';
//return IDENTIFIER;
printf("identifier");
}
The accepts both:
//set name
// set name
来源:https://stackoverflow.com/questions/18317948/error-while-parsing-comments-in-lex