【问题标题】:Removing comments with JFlex, but keeping line terminators使用 JFlex 删除注释,但保留行终止符
【发布时间】:2012-10-13 19:58:37
【问题描述】:

我正在为 JFlex 编写词法规范(它类似于 flex,但用于 Java)。我对 TraditionalComment (/* */) 和 DocumentationComment (/** */) 有疑问。到目前为止,我有这个,取自JFlex User's Manual

LineTerminator = \r|\n|\r\n
InputCharacter = [^\r\n]
WhiteSpace     = {LineTerminator} | [ \t\f]

/* comments */
Comment = {TraditionalComment} | {EndOfLineComment} | {DocumentationComment}

TraditionalComment   = "/*" [^*] ~"*/" | "/*" "*"+ "/"
EndOfLineComment     = "//" {InputCharacter}* {LineTerminator}
DocumentationComment = "/**" {CommentContent} "*"+ "/"
CommentContent       = ( [^*] | \*+ [^/*] )*

{Comment}           { /* Ignore comments */ }
{LineTerminator}    { return LexerToken.PASS; }

LexerToken.PASS 表示稍后我将在输出中传递行终止符。现在,我想做的是:

忽略注释中的所有内容,换行符除外

例如,考虑这样的输入:

/* Some
 * quite long comment. */

其实是/* Some\n * quite long comment. */\n。使用当前的词法分析器,它将被转换为单行。输出将是单个 '\n'。但我想要两行,'\n\n'。一般来说,我希望我的输出始终具有与输入相同的行数。怎么办?

【问题讨论】:

    标签: lex flex-lexer lexer jflex


    【解决方案1】:

    几天后,我找到了解决方案。我会在这里发布,也许有人会遇到同样的问题。

    诀窍是,在识别出您在评论中之后 - 再次检查其正文,如果您发现换行符 - 传递它们,而不是忽略:

    %{
    public StringBuilder newLines;
    %}
    
    // ...
    
    {Comment}           { 
                            char[] ch; 
                            ch = yytext().toCharArray(); 
                            newLines = new StringBuilder();
                            for (char c : ch)
                            {
                                if (c == '\n')
                                {
                                    newLines.append(c);
                                }
                            } 
                            return LexerToken.NEW_LINES;
                        }
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 2021-11-11
      • 2012-12-08
      • 2023-04-08
      • 2019-10-27
      相关资源
      最近更新 更多