Error while parsing comments in lex

☆樱花仙子☆ 提交于 2019-12-12 00:39:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!