簡體   English   中英

使用ANTLR 4在Python 3中生成Java解析器

[英]Generating a Java Parser in Python 3 using ANTLR 4

從此處使用Lexer和解析器:

https://raw.githubusercontent.com/antlr/grammars-v4/master/java/JavaLexer.g4

https://raw.githubusercontent.com/antlr/grammars-v4/master/java/JavaParser.g4

用antlr-4.6生成Python3目標

java -jar ./antlr-4.6-complete.jar -Dlanguage = Python3 ./JavaLexer.g4

java -jar ./antlr-4.6-complete.jar -Dlanguage = Python3 ./JavaParser.g4

但是,im無法在生成的解析器上運行compilationUnit()方法。 說錯了

ipdb> parser.compilationUnit()

File "/home/sviyer/onmt-fresh/java/JavaParser.py", line 1063, in compilationUnit
    localctx = JavaParser.CompilationUnitContext(self, self._ctx, self.state)
  File "/home/sviyer/.conda/envs/allennlp/lib/python3.6/site-packages/antlr4/error/ErrorStrategy.py", line 223, in sync
    raise InputMismatchException(recognizer)
antlr4.error.Errors.InputMismatchException: None

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "TestAntlr.py", line 13, in <module>
    parser.compilationUnit()
  File "/home/sviyer/onmt-fresh/java/JavaParser.py", line 1063, in compilationUnit
    localctx = JavaParser.CompilationUnitContext(self, self._ctx, self.state)
  File "/home/sviyer/.conda/envs/allennlp/lib/python3.6/site-packages/antlr4/error/ErrorStrategy.py", line 126, in reportError
    self.reportInputMismatch(recognizer, e)
  File "/home/sviyer/.conda/envs/allennlp/lib/python3.6/site-packages/antlr4/error/ErrorStrategy.py", line 266, in reportInputMismatch
    + " expecting " + e.getExpectedTokens().toString(recognizer.literalNames, recognizer.symbolicNames)
  File "/home/sviyer/.conda/envs/allennlp/lib/python3.6/site-packages/antlr4/error/ErrorStrategy.py", line 522, in getTokenErrorDisplay
    s = t.text
AttributeError: 'int' object has no attribute 'text'

詞法分析器工作正常,但解析器對其進行了解析。 我的代碼是:

流= antlr4.InputStream(代碼)

lexer = JavaLexer(流)

托克斯= antlr4.CommonTokenStream(lexer)

解析器= JavaParser(流)

您的代碼不正確。 試試這個:

code = open('sample.java', 'r').read()
codeStream = InputStream(code)
lexer = JavaLexer(codeStream)

# First lexing way
tokensStream = CommonTokenStream(lexer)
parser = JavaParser(tokensStream)

# Second lexing way
'''tokens = lexer.getAllTokens()
tokensSource = ListTokenSource(tokens)
tokensStream = CommonTokenStream(tokensSource)
parser = JavaParser(tokensStream)'''

tree = parser.compilationUnit()
print "Tree " + tree.toStringTree(recog=parser);

另外,請使用最新的穩定ANTLR版本(4.7)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM