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

时间:2015-07-25 19:49:13

标签: regex flex-lexer

我的作业(没有评分,我没有得到任何解决方法)就是写一个词法分析器/扫描器/标记器(但是你想调用它)。 flex用于此类。词法分析器是为类面向对象语言或COOL编写的。

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

(* line 1
line 2
line 3 *)

这些评论可以嵌套。换句话说,以下内容有效:

(* comment1 start (* comment 2 start (* comment 3 *) comemnt 2 end *) comment 1 end *)

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

"This is a string"
"This is another string"

还有一条额外的规则,即评论或字符串中不能有EOF。例如,以下内容无效:

(* comment <EOF>
"My string <EOF>

我写了一个lexer来处理它。它通过查找\n来跟踪行数。

以下是我遇到的问题:

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

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

Line 1: (* this is a comment <EOF>

显示以下错误:

  

`#2 ERROR“评论中的EOF”

然而,当它遇到这段代码时:

Line 1: "This is a string <EOF>

显示以下错误:

  

`#1 ERROR“字符串包含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;
}

所以问题是

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

感谢任何帮助。

1 个答案:

答案 0 :(得分:-1)

因为注释的图案不需要换行就可以增加行号,而字符串的图案则需要换行。

相关问题