You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Golang结合ANTLR4解析Python时缺失Python3LexerBase.go文件求助

解决Golang+ANTLR4解析Python时缺失Python3LexerBase.go的方案
  • 该文件是Python3词法解析器的基础依赖类,ANTLR官方提供的Python3语法模板默认仅提供Java版本的Base实现,Go版本需要自行实现,你可以直接使用以下通用实现:
// 修改为你自己的解析文件所在包名
package parser

import (
	"github.com/antlr/antlr4/runtime/Go/antlr/v4"
)

type Python3LexerBase struct {
	*antlr.BaseLexer
	indentStack []int
}

func NewPython3LexerBase(input antlr.CharStream) *Python3LexerBase {
	return &Python3LexerBase{
		BaseLexer:   antlr.NewBaseLexer(input),
		indentStack: []int{0},
	}
}

func (l *Python3LexerBase) atStartOfInput() bool {
	return l.GetCharPositionInLine() == 0 && l.GetLine() == 1
}

func (l *Python3LexerBase) getIndentationCount(spaces string) int {
	count := 0
	for _, ch := range spaces {
		if ch == ' ' {
			count++
		} else {
			count += 8 - (count % 8)
		}
	}
	return count
}

func (l *Python3LexerBase) pushIndent(indent int) {
	l.indentStack = append(l.indentStack, indent)
}

func (l *Python3LexerBase) popIndent() int {
	if len(l.indentStack) == 0 {
		return 0
	}
	res := l.indentStack[len(l.indentStack)-1]
	l.indentStack = l.indentStack[:len(l.indentStack)-1]
	return res
}

func (l *Python3LexerBase) getLastIndent() int {
	if len(l.indentStack) == 0 {
		return 0
	}
	return l.indentStack[len(l.indentStack)-1]
}
  • 将上述代码保存为Python3LexerBase.go,和ANTLR4生成的Python3Lexer.go、Python3Parser.go放在同一个目录下,修改首行的package声明和生成的文件包名一致即可正常使用。
  • 如果你是直接用ANTLR命令生成代码,需要确保语法文件里的superClass配置正确指向这个基础类。

内容的提问来源于stack exchange,提问作者rickdamon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:27:00