示例
github.com/antlr4-go/antlr/v4 v4.13.0: Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy
已验证示例 — golang github.com/antlr4-go/antlr/v4 v4.13.0: Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy. contract…
sha256:e0c389e227e903a7a4820d91ebacddd9661e474430d5c86fb192e062a8838935
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 2
- 构建过它的签名密钥
- 1
声明的环境
go linux 24 · ubuntu · glibc 2.39 x64 go go go
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-08-26 |
| go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a… |
2026-09-07 |
案例
HOW- 目标
- Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy
- 符号
-
- antlr.BaseParseTreeListener
- antlr.NewBailErrorStrategy
- antlr.NewParseTreeWalker
- antlr.TreesStringTree
- 环境
- go
- 创建时间
- 2026-08-26T07:04:50Z
契约
- antlr.NewParseTreeWalker traverses parse trees in depth-first order triggering EnterEveryRule, VisitTerminal, and ExitEveryRule events on custom listeners embedding antlr.BaseParseTreeListener.
- antlr.TreesStringTree converts parse tree rule contexts and terminal nodes into a LISP-style S-expression string representation using the provided rule names.
- antlr.NewBailErrorStrategy cancels parse execution upon encountering syntax errors by setting a ParseCancellationException on the parser and recording the error on active rule contexts.
文件
- NOTES.md
- PROMPT.md
- csx.json
- go.mod
- go.sum
- parser_tree_test.go
- spec.json
源代码
# antlr4-go AST Traversal and Bail Error Strategy Notes
## Search Results
An initial search via `search_known_solution` for `pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0` with AST traversal and bail error handling symbols yielded `NO_SAFE_MATCH`.
## Pinned Version
- Package: `github.com/antlr4-go/antlr/v4`
- Release: `v4.13.0` (in `go.mod` / `go.sum`)
## Observed Behavior
1. **Parse Tree Traversal (`antlr.NewParseTreeWalker` and `antlr.BaseParseTreeListener`)**:
- `antlr.NewParseTreeWalker().Walk(listener, tree)` traverses tree nodes depth-first.
- Embeds `*antlr.BaseParseTreeListener` to intercept `EnterEveryRule`, `ExitEveryRule`, and `VisitTerminal` events.
2. **LISP Tree Formatting (`antlr.TreesStringTree`)**:
- `antlr.TreesStringTree(tree, ruleNames, recognizer)` produces an S-expression representation `(ruleName ...)` for parse tree verification and debugging.
3. **Strict Syntax Error Handling (`antlr.NewBailErrorStrategy`)**:
- `antlr.NewBailErrorStrategy()` attaches to parsers to fail immediately upon encountering syntax errors.
- Calling `strategy.Recover(parser, exception)` sets a `*antlr.ParseCancellationException` on the parser and marks the exception across enclosing `ParserRuleContext` nodes.
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0
Demonstrate these symbols/APIs:
- antlr.BaseParseTreeListener
- antlr.NewBailErrorStrategy
- antlr.NewParseTreeWalker
- antlr.TreesStringTree
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:ab8db31fa70e44bf0f80e675ba1c04c27e0528c57ea08812b7eca254c1557c9d","contract":["antlr.NewParseTreeWalker traverses parse trees in depth-first order triggering EnterEveryRule, VisitTerminal, and ExitEveryRule events on custom listeners embedding antlr.BaseParseTreeListener.","antlr.TreesStringTree converts parse tree rule contexts and terminal nodes into a LISP-style S-expression string representation using the provided rule names.","antlr.NewBailErrorStrategy cancels parse execution upon encountering syntax errors by setting a ParseCancellationException on the parser and recording the error on active rule contexts."],"goal":"Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy","kind":"HOW","packages":["pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0"],"schemaVersion":1,"symbols":["antlr.BaseParseTreeListener","antlr.NewBailErrorStrategy","antlr.NewParseTreeWalker","antlr.TreesStringTree"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0","symbols":["antlr.BaseParseTreeListener","antlr.NewBailErrorStrategy","antlr.NewParseTreeWalker","antlr.TreesStringTree"],"verifierAdapter":"golang@1"}
module example.com/antlrsample
go 1.26.6
require github.com/antlr4-go/antlr/v4 v4.13.1
require golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=
package antlrsample_test
import (
"testing"
"unicode"
"github.com/antlr4-go/antlr/v4"
)
// CustomListener tracks entered rules and visited terminals.
type CustomListener struct {
*antlr.BaseParseTreeListener
EnteredRules []int
ExitedRules []int
Terminals []string
}
func NewCustomListener() *CustomListener {
return &CustomListener{
BaseParseTreeListener: &antlr.BaseParseTreeListener{},
EnteredRules: make([]int, 0),
ExitedRules: make([]int, 0),
Terminals: make([]string, 0),
}
}
func (l *CustomListener) EnterEveryRule(ctx antlr.ParserRuleContext) {
l.EnteredRules = append(l.EnteredRules, ctx.GetRuleIndex())
}
func (l *CustomListener) ExitEveryRule(ctx antlr.ParserRuleContext) {
l.ExitedRules = append(l.ExitedRules, ctx.GetRuleIndex())
}
func (l *CustomListener) VisitTerminal(node antlr.TerminalNode) {
l.Terminals = append(l.Terminals, node.GetText())
}
const (
RuleExpression = 0
RuleTerm = 1
)
var ruleNames = []string{
"expression",
"term",
}
// SimpleLexer is a minimal Lexer that tokenizes identifiers, numbers, and symbols.
type SimpleLexer struct {
*antlr.BaseLexer
}
func NewSimpleLexer(input antlr.CharStream) *SimpleLexer {
l := &SimpleLexer{
BaseLexer: antlr.NewBaseLexer(input),
}
l.Virt = l
l.Interpreter = &antlr.LexerATNSimulator{
Line: 1,
CharPositionInLine: 0,
}
return l
}
func (l *SimpleLexer) NextToken() antlr.Token {
input := l.GetInputStream()
sim := l.Interpreter.(*antlr.LexerATNSimulator)
for {
ch := input.LA(1)
if ch == antlr.TokenEOF {
return l.GetTokenFactory().Create(
l.GetTokenSourceCharStreamPair(),
antlr.TokenEOF,
"",
antlr.TokenDefaultChannel,
input.Index(),
input.Index(),
sim.Line,
sim.CharPositionInLine,
)
}
start := input.Index()
line := sim.Line
col := sim.CharPositionInLine
r := rune(ch)
input.Consume()
sim.CharPositionInLine++
if unicode.IsSpace(r) {
continue
}
token := l.GetTokenFactory().Create(
l.GetTokenSourceCharStreamPair(),
1,
string(r),
antlr.TokenDefaultChannel,
start,
start,
line,
col,
)
return token
}
}
func createToken(tokenType int, text string) antlr.Token {
return antlr.CommonTokenFactoryDEFAULT.Create(
&antlr.TokenSourceCharStreamPair{},
tokenType,
text,
antlr.TokenDefaultChannel,
0,
len(text)-1,
1,
0,
)
}
// buildSampleTree creates a tree: expression -> [term("42"), "+", term("58")]
func buildSampleTree() antlr.Tree {
rootCtx := antlr.NewBaseParserRuleContext(nil, -1)
rootCtx.RuleIndex = RuleExpression
leftTerm := antlr.NewBaseParserRuleContext(rootCtx, -1)
leftTerm.RuleIndex = RuleTerm
leftTerm.AddTokenNode(createToken(1, "42"))
rootCtx.AddChild(leftTerm)
rootCtx.AddTokenNode(createToken(2, "+"))
rightTerm := antlr.NewBaseParserRuleContext(rootCtx, -1)
rightTerm.RuleIndex = RuleTerm
rightTerm.AddTokenNode(createToken(1, "58"))
rootCtx.AddChild(rightTerm)
return rootCtx
}
func TestParseTreeWalkerAndBaseListener(t *testing.T) {
tree := buildSampleTree()
walker := antlr.NewParseTreeWalker()
listener := NewCustomListener()
walker.Walk(listener, tree)
// Verify entered rules: root (RuleExpression), left (RuleTerm), right (RuleTerm)
expectedEntered := []int{RuleExpression, RuleTerm, RuleTerm}
if len(listener.EnteredRules) != len(expectedEntered) {
t.Fatalf("expected %d entered rules, got %d", len(expectedEntered), len(listener.EnteredRules))
}
for i, r := range expectedEntered {
if listener.EnteredRules[i] != r {
t.Errorf("at entered rule index %d: expected rule %d, got %d", i, r, listener.EnteredRules[i])
}
}
// Verify exited rules: left (RuleTerm), right (RuleTerm), root (RuleExpression)
expectedExited := []int{RuleTerm, RuleTerm, RuleExpression}
if len(listener.ExitedRules) != len(expectedExited) {
t.Fatalf("expected %d exited rules, got %d", len(expectedExited), len(listener.ExitedRules))
}
for i, r := range expectedExited {
if listener.ExitedRules[i] != r {
t.Errorf("at exited rule index %d: expected rule %d, got %d", i, r, listener.ExitedRules[i])
}
}
// Verify terminals visited in order: "42", "+", "58"
expectedTerminals := []string{"42", "+", "58"}
if len(listener.Terminals) != len(expectedTerminals) {
t.Fatalf("expected %d terminals, got %d", len(expectedTerminals), len(listener.Terminals))
}
for i, term := range expectedTerminals {
if listener.Terminals[i] != term {
t.Errorf("at terminal %d: expected %q, got %q", i, term, listener.Terminals[i])
}
}
}
func TestTreesStringTree(t *testing.T) {
tree := buildSampleTree()
treeStr := antlr.TreesStringTree(tree, ruleNames, nil)
expected := "(expression (term 42) + (term 58))"
if treeStr != expected {
t.Fatalf("expected string tree %q, got %q", expected, treeStr)
}
}
func TestBailErrorStrategySetsParseCancellationException(t *testing.T) {
strategy := antlr.NewBailErrorStrategy()
lexer := NewSimpleLexer(antlr.NewInputStream("bad_input"))
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
parser := antlr.NewBaseParser(stream)
parser.SetErrorHandler(strategy)
ctx := antlr.NewBaseParserRuleContext(nil, -1)
parser.SetParserRuleContext(ctx)
mismatched := antlr.NewInputMisMatchException(parser)
strategy.Recover(parser, mismatched)
if !parser.HasError() {
t.Fatalf("expected parser to have error after BailErrorStrategy.Recover")
}
err := parser.GetError()
if _, ok := err.(*antlr.ParseCancellationException); !ok {
t.Fatalf("expected *antlr.ParseCancellationException, got %T: %v", err, err)
}
}
{
"schemaVersion": 1,
"goal": "Traverse parse tree with antlr.ParseTreeWalker and handle errors with antlr.BailErrorStrategy",
"kind": "HOW",
"packages": [
"pkg:golang/github.com/antlr4-go/antlr/v4@v4.13.0"
],
"symbols": [
"antlr.BaseParseTreeListener",
"antlr.NewBailErrorStrategy",
"antlr.NewParseTreeWalker",
"antlr.TreesStringTree"
]
}
原始种子者
匿名