为什么在我的 flex lexer 中,行数在一种情况下增加而在另一种情况下不增加?

fla*_*urn 5 regex flex-lexer

我的作业(它没有评分,我从解决它中得不到任何东西)是编写一个词法分析器/扫描器/标记器(不管你想怎么称呼它)。flex 用于此类。词法分析器是为 Class Object Oriented Language 或 COOL 编写的。

在这种语言中,多行注释的开始和结束如下:

(* line 1
line 2
line 3 *)
Run Code Online (Sandbox Code Playgroud)

这些注释可以嵌套。换句话说,以下是有效的:

(* comment1 start (* comment 2 start (* comment 3 *) comemnt 2 end *) comment 1 end *)
Run Code Online (Sandbox Code Playgroud)

这种语言中的字符串是正则引用的字符串,就像在 C 中一样。这是一个例子:

"This is a string"
"This is another string"
Run Code Online (Sandbox Code Playgroud)

还有一个额外的规则是在注释或字符串中不能有 EOF。例如以下无效:

(* comment <EOF>
"My string <EOF>
Run Code Online (Sandbox Code Playgroud)

我写了一个词法分析器来处理它。它通过查找\n.

这是我遇到的问题:

当词法分析器在注释中遇到 EOF 时,它会将行数增加 1,但是当它在字符串中遇到 EOF 时,它不会这样做。

例如当词法分析器遇到以下代码时

Line 1: (* this is a comment <EOF>
Run Code Online (Sandbox Code Playgroud)

显示以下错误:

`#2 错误“注释中的 EOF”

但是,当它遇到此代码时:

Line 1: "This is a string <EOF>
Run Code Online (Sandbox Code Playgroud)

显示以下错误:

`#1 错误“字符串包含 EOF 字符”

我不明白为什么会发生这种情况(行号在一种情况下增加,而在另一种情况下不增加)。下面是我用来匹配注释和字符串的一些规则。如果您需要更多,请询问,我会发布它们。

    <BLOCK_COMMENT>{
  [^\n*)(]+ ; /* Eat the comment in chunks */
  ")" ; /* Eat a lonely right paren */
  "(" ; /* Eat a lonely left paren */
  "*" ; /* Eat a lonely star */
  \n curr_lineno++; /* increment the line count */
}

  /*
       Can't have EOF in the middle of a block comment
     */
<BLOCK_COMMENT><<EOF>>  {
    cool_yylval.error_msg = "EOF in comment";
  /*
     Need to return to INITIAL, otherwise the program will be stuck
     in the infinite loop. This was determined experimentally.
   */
  BEGIN(INITIAL);
  return ERROR;
}

  /* Match <back slash>\n or \n */
<STRING>\\\n|\n {
  curr_lineno++;
}
<STRING><<EOF>> {
    /* String may not have an EOF character */
  cool_yylval.error_msg = "String contains EOF character";

  /*
     Need to return to INITIAL, otherwise the program will be stuck
     in the infinite loop. This was determined experimentally.
   */
  BEGIN(INITIAL);
  return ERROR;
}
Run Code Online (Sandbox Code Playgroud)

所以问题是

为什么在注释的情况下行号增加而在字符串的情况下保持不变?

任何帮助表示赞赏。

cha*_*aos -1

因为注释模式不需要存在换行符来增加行号,而字符串模式则需要。