如何在 Java ANTLR4 VisitTerminal 重写函数中包含 Python 注释?

问题描述 投票:0回答:1

背景

我自动生成了:

  • Python3Lexer.java
  • Python3ParserBase.java
  • Python3ParserListener.java
  • PythonDocstringModifierListener.java
  • Python3Parser.java 根据this答案提交文件。然后我修改了该问题中的 MWE 以包括:
public class SomePythonListener extends Python3ParserBaseListener {
  public SomePythonListener
      Python3Parser parser, String someValue) {
    this.parser = parser;
    this.someValue = someValue;
  }

  @Override
  public void visitTerminal(TerminalNode node) {
    Token token = node.getSymbol();
    System.out.println("token.getType()=" + token.getType());
    System.out.println("getText:" + token.getText() + "XXXX\n\n");
  } 
}

我向它提供源代码:

"""A file docstring.
With a multiline starting docstring.
That spans the first 3 lines."""
# Some Comment.

# Another comment
"""Some string."""
def foo():
    """Some docstring."""
    print('hello world')
    def bar():
        """Another docstring."""
        print('hello world')
def baz():
        """Third docstring."""
        print('hello universe')

然后输出:

token.getType()=3
getText:"""A file docstring.
With a multiline starting docstring.
That spans the first 3 lines."""END

token.getType()=44
getText:
END

token.getType()=3
getText:"""Some string."""END

token.getType()=44
getText:
END

token.getType()=15
getText:defEND

token.getType()=45
getText:fooEND

token.getType()=57
getText:(END

token.getType()=58
getText:)END

token.getType()=60
getText::END

token.getType()=44
getText: END

token.getType()=1
getText:    ENDtoken.getType()=3

为了完整起见,

44
代表新行字符,可以看到包含第一个文档字符串,后跟一个新行,然后是第二个文档字符串
"""Some string."""
,但是两个注释:
# Some Comment.
# Another comment 
被忽略/未访问/未显示。

问题

TerminalNode node
visitTerminal
对象不包含注释。

问题

如何将评论包含在访客中?

尝试

基于这些答案看来我应该从隐藏渠道获取这些。我还不知道该怎么做。为了完整起见,自动生成的

Python3Lexer.java
文件包含:

public static String[] channelNames = {"DEFAULT_TOKEN_CHANNEL", "HIDDEN"};

  public static String[] modeNames = {"DEFAULT_MODE"};
java python-3.x comments antlr4 concrete-syntax-tree
1个回答
0
投票

visitTerminal 的 TerminalNode 节点对象不包含注释。

这是正确的:这些标记在词法分析器中被跳过。您还可以通过将

-> skip
替换为
-> channel(HIDDEN)
,将这些标记放在另一个通道上(因此不要跳过它们)。但这仍然不会导致它们出现在
visitTerminal(...)
方法中。毕竟:只有解析器规则中定义的标记才会出现在那里。

© www.soinside.com 2019 - 2024. All rights reserved.