如何标记块(注释,字符串,...)以及块间(块外的任何字符)?

时间:2015-08-18 11:37:18

标签: antlr antlr4 lexer

我需要将所有内容都标记为"外部"任何评论,直到最后。例如:

take me */ and me /* but not me! */ I'm in! // I'm not...

标记为(STR是"外部"字符串,BC是块注释,LC是单行注释:

{
    STR: "take me */ and me ", // note the "*/" in the string!
    BC : " but not me! ",
    STR: " I'm in! ",
    LC : " I'm not..."
}

/* starting with don't take me */ ...take me...

标记为:

{
    BC : " starting with don't take me ",
    STR: " ...take me..."
}

问题是STR可以是除了注释之外的任何内容,并且因为注释开头不是单个字符标记,所以我不能使用{{1的否定规则}}

我想也许可以这样做:

STR

但我不知道如何在词法分析器行动中预测字符

甚至可以用ANTLR4词法分析器完成,如果是,那么如何?

2 个答案:

答案 0 :(得分:2)

是的,可以执行您正在尝试的标记化。

根据上面所描述的内容,您需要嵌套注释。这些只能在没有Action,Predicate或任何代码的词法分析器中实现。为了获得嵌套注释,如果不使用贪婪/非贪婪的ANTLR选项,则更容易。您需要在lexer语法中指定/编码。以下是您需要的三个词法规则......使用STR定义。

我添加了一个用于测试的解析器规则。我没有测试过这个,但它应该做你提到的一切。此外,它不仅限于“线路末端”。如果需要,你可以进行修改。

/*
    All 3 COMMENTS are Mutually Exclusive
 */
DOC_COMMENT
        : '/**'
          ( [*]* ~[*/]         // Cannot START/END Comment
            ( DOC_COMMENT
            | BLK_COMMENT
            | INL_COMMENT
            | .
            )*?
          )?
          '*'+ '/' -> channel( DOC_COMMENT )
        ;
BLK_COMMENT
        : '/*'
          (
            ( /* Must never match an '*' in position 3 here, otherwise
                 there is a conflict with the definition of DOC_COMMENT
               */
              [/]? ~[*/]       // No START/END Comment
            | DOC_COMMENT
            | BLK_COMMENT
            | INL_COMMENT
            )
            ( DOC_COMMENT
            | BLK_COMMENT
            | INL_COMMENT
            | .
            )*?
          )?
          '*/' -> channel( BLK_COMMENT )
        ;
INL_COMMENT
        : '//'
          ( ~[\n\r*/]          // No NEW_LINE
          | INL_COMMENT        // Nested Inline Comment
          )* -> channel( INL_COMMENT )
        ;
STR       // Consume everthing up to the start of a COMMENT
        : ( ~'/'      // Any Char not used to START a Comment
          | '/' ~[*/] // Cannot START a Comment
          )+
        ;

start
        : DOC_COMMENT
        | BLK_COMMENT
        | INL_COMMENT
        | STR
        ;

答案 1 :(得分:1)

尝试这样的事情:

grammar T;

@lexer::members {

  // Returns true iff either "//" or "/*"  is ahead in the char stream.
  boolean startCommentAhead() {
    return _input.LA(1) == '/' && (_input.LA(2) == '/' || _input.LA(2) == '*');
  }
}

// other rules

STR
 : ( {!startCommentAhead()}? . )+
 ;