ANTLR4 Golang语法文件

huangapple go评论71阅读模式
英文:

ANTLR4 Golang grammar file

问题

我正在尝试从golang代码创建AST树时遇到一个警告。
第6行第1列的输入无法识别:'sMap, lMap map[int32]string\r\n\tif'
我尝试的代码如下:

package dum
func mergeIntStrMap(map1 map[int32]string, map2 map[int32]string) string {

	var sMap, lMap map[int32]string
    return lMap
}

我从[github](https://github.com/antlr/grammars-v4/blob/master/golang/)下载了语法文件。语法文件是否有问题或者有没有修复方法?
我使用以下代码生成AST(python代码):

from antlr4 import *
from GoParser import GoParser
from GoLexer import GoLexer
file = FileStream(f,encoding = 'utf-8')
lexer = GoLexer(file)
token = CommonTokenStream(lexer)
parse = GoParser(token)
trees = parse.sourceFile()

这里的GoParser和GoLexer文件是从语法文件生成的。

提前感谢。

英文:

I'm getting a warning while trying to create AST tree from golang code
line 6:1 no viable alternative at input 'sMap, lMap map[int32]string\r\n\tif'
The code I tried,

package dum
func mergeIntStrMap(map1 map[int32]string, map2 map[int32]string) string {

	var sMap, lMap map[int32]string
    return lMap
}

Grammar file I downloaded from [github]<https://github.com/antlr/grammars-v4/blob/master/golang/>. Is there any issue in the grammar file or any fix for this.
Used code to generate AST(python code),

from antlr4 import *
from GoParser import GoParser
from GoLexer import GoLexer
file = FileStream(f,encoding = &#39;utf-8&#39;)
lexer = GoLexer(file)
token = CommonTokenStream(lexer)
parse = GoParser(token)
trees = parse.sourceFile()

here GoParser and GoLexer files are generated from grammar file.

Thanks in Advance

答案1

得分: 1

你要翻译的内容如下:

你要么在语法文件中做了一些更改,要么没有正确实现GoParserBase.py,因为在没有做任何更改的情况下,你的示例Go代码被正确解析了:

从评论中,@kaby76提到了这个:

> 我还没有进行移植,但代码很简单GoParserBase.py
>
> py &gt; from antlr4 import * &gt; &gt; class GoParserBase(Parser): &gt; def closingBracket(self) -&gt; bool: &gt; la = self._input.LA(1) &gt; return la == self.R_PAREN or la == self.R_CURLY &gt;
>
> 你需要修补语法文件,使其调用self.closingBracket()
>
> 解析你的示例没有问题。

英文:

You either changed something in the grammar file(s), or you did not implement GoParserBase.py correctly, because without changing anything, your example Go code is correctly parsed:

ANTLR4 Golang语法文件

From the comments, @kaby76 mentions this:

> I haven't done the port yet, but the code is easy GoParserBase.py:
>
> py
&gt; from antlr4 import *
&gt;
&gt; class GoParserBase(Parser):
&gt; def closingBracket(self) -&gt; bool:
&gt; la = self._input.LA(1)
&gt; return la == self.R_PAREN or la == self.R_CURLY
&gt;

>
> You'll have to patch the grammar so that it calls self.closingBracket().
>
> Parses your example just fine.

huangapple
  • 本文由 发表于 2022年7月20日 19:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/73050657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定