CodeSampleX

示例

golang.org/x/tools v0.44.0: astutil.Cursor

已验证示例 — golang golang.org/x/tools v0.44.0: astutil.Cursor. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: Cursor.Node and Cursor.Parent return the…

sha256:41699251adcd0eaade23b2ccf07262c8585cc98e9ed0e21c0ad3fffaa8c145e0

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

验证运行环境

环境 契约 阶段 运行日期
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-04

案例

HOW
目标
verify golang.org/x/tools/go/ast/astutil.Cursor in pkg:golang/golang.org/x/tools@v0.44.0
符号
  • golang.org/x/tools/go/ast/astutil.Cursor
环境
go 1.26.6
创建时间
2026-09-04T13:30:41Z

契约

  1. Cursor.Node and Cursor.Parent return the current AST node and its enclosing parent node during traversal
  2. Cursor.Name and Cursor.Index report the parent AST field name and slice element index
  3. Cursor.Replace replaces an AST node with another node during AST traversal
  4. Cursor.Delete removes an AST node from a slice of statements in a block
  5. Cursor.InsertBefore and Cursor.InsertAfter insert sibling statements into an AST block

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

下载源代码构件 (tar.gz)

源代码

PROMPT.md
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: verify golang.org/x/tools/go/ast/astutil.Cursor in pkg:golang/golang.org/x/tools@v0.44.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/tools@v0.44.0
Demonstrate these symbols/APIs:
  - golang.org/x/tools/go/ast/astutil.Cursor
Required runtime conditions:
  - ecosystem: golang
  - language: go
  - packageManager: go@1.26.6
  - runtime: go@1.26.6

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.
csx.json
{"case":{"caseId":"case:sha256:04fbfc811a8e3a60079abcf03aac8a8068a84416f209361be50f8feefa747c91","contract":["Cursor.Node and Cursor.Parent return the current AST node and its enclosing parent node during traversal","Cursor.Name and Cursor.Index report the parent AST field name and slice element index","Cursor.Replace replaces an AST node with another node during AST traversal","Cursor.Delete removes an AST node from a slice of statements in a block","Cursor.InsertBefore and Cursor.InsertAfter insert sibling statements into an AST block"],"goal":"verify golang.org/x/tools/go/ast/astutil.Cursor in pkg:golang/golang.org/x/tools@v0.44.0","kind":"HOW","packages":["pkg:golang/golang.org/x/tools@v0.44.0"],"schemaVersion":1,"symbols":["golang.org/x/tools/go/ast/astutil.Cursor"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/tools@v0.44.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/tools@v0.44.0","symbols":["golang.org/x/tools/go/ast/astutil.Cursor"],"verifierAdapter":"golang@1"}
go.mod
module sample-astutil-cursor

go 1.26.6

require golang.org/x/tools v0.44.0
go.sum
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
main.go
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"

	"golang.org/x/tools/go/ast/astutil"
)

func main() {
	src := `package main

func greet() {
	msg := "hello"
	_ = msg
}
`
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "example.go", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	// Use astutil.Apply and astutil.Cursor to replace identifier "msg" with "greeting"
	astutil.Apply(file, func(c *astutil.Cursor) bool {
		n := c.Node()
		if ident, ok := n.(*ast.Ident); ok && ident.Name == "msg" {
			c.Replace(ast.NewIdent("greeting"))
		}
		return true
	}, nil)

	var buf bytes.Buffer
	if err := format.Node(&buf, fset, file); err != nil {
		panic(err)
	}

	fmt.Println("Transformed code:")
	fmt.Println(buf.String())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/tools/go/ast/astutil.Cursor in pkg:golang/golang.org/x/tools@v0.44.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/tools@v0.44.0"
  ],
  "symbols": [
    "golang.org/x/tools/go/ast/astutil.Cursor"
  ],
  "runtimeConditions": {
    "ecosystem": "golang",
    "language": "go",
    "packageManager": "go@1.26.6",
    "runtime": "go@1.26.6"
  }
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/format"
	"go/parser"
	"go/token"
	"os"
	"strings"

	"golang.org/x/tools/go/ast/astutil"
)

func main() {
	// Assertion 1: Cursor.Node and Cursor.Parent return the current AST node and its enclosing parent node during traversal
	{
		src := `package main
func targetFunc() {
	x := 42
	_ = x
}`
		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, "src.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		foundFunc := false
		foundBlock := false

		astutil.Apply(file, func(c *astutil.Cursor) bool {
			if fn, ok := c.Node().(*ast.FuncDecl); ok {
				if fn.Name.Name == "targetFunc" {
					foundFunc = true
					if c.Parent() != file {
						fmt.Fprintf(os.Stderr, "FAIL: FuncDecl parent is not *ast.File\n")
						os.Exit(1)
					}
				}
			}
			if blk, ok := c.Node().(*ast.BlockStmt); ok {
				if fn, ok := c.Parent().(*ast.FuncDecl); ok && fn.Name.Name == "targetFunc" {
					foundBlock = true
					if c.Node() != blk {
						fmt.Fprintf(os.Stderr, "FAIL: BlockStmt Cursor.Node mismatch\n")
						os.Exit(1)
					}
				}
			}
			return true
		}, nil)

		if !foundFunc || !foundBlock {
			fmt.Fprintf(os.Stderr, "FAIL: did not find targetFunc (%v) or its block (%v)\n", foundFunc, foundBlock)
			os.Exit(1)
		}
	}

	// Assertion 2: Cursor.Name and Cursor.Index report the parent AST field name and slice element index
	{
		src := `package main
func first() {}
func second() {}`
		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, "src.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		checkedFirst := false
		checkedSecond := false

		astutil.Apply(file, func(c *astutil.Cursor) bool {
			if fn, ok := c.Node().(*ast.FuncDecl); ok {
				if fn.Name.Name == "first" {
					checkedFirst = true
					if c.Name() != "Decls" || c.Index() != 0 {
						fmt.Fprintf(os.Stderr, "FAIL: first() name=%q index=%d, expected Decls/0\n", c.Name(), c.Index())
						os.Exit(1)
					}
				} else if fn.Name.Name == "second" {
					checkedSecond = true
					if c.Name() != "Decls" || c.Index() != 1 {
						fmt.Fprintf(os.Stderr, "FAIL: second() name=%q index=%d, expected Decls/1\n", c.Name(), c.Index())
						os.Exit(1)
					}
				}
			}
			return true
		}, nil)

		if !checkedFirst || !checkedSecond {
			fmt.Fprintf(os.Stderr, "FAIL: did not check first (%v) or second (%v)\n", checkedFirst, checkedSecond)
			os.Exit(1)
		}
	}

	// Assertion 3: Cursor.Replace replaces an AST node with another node during AST traversal
	{
		src := `package main
func run() {
	oldVar := 100
	_ = oldVar
}`
		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, "src.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		replaceCount := 0
		astutil.Apply(file, func(c *astutil.Cursor) bool {
			if ident, ok := c.Node().(*ast.Ident); ok && ident.Name == "oldVar" {
				c.Replace(ast.NewIdent("newVar"))
				replaceCount++
			}
			return true
		}, nil)

		if replaceCount != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: expected 2 replacements, got %d\n", replaceCount)
			os.Exit(1)
		}

		var buf bytes.Buffer
		if err := format.Node(&buf, fset, file); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: format.Node failed: %v\n", err)
			os.Exit(1)
		}
		res := buf.String()
		if strings.Contains(res, "oldVar") || !strings.Contains(res, "newVar") {
			fmt.Fprintf(os.Stderr, "FAIL: replacement not reflected in formatted code:\n%s\n", res)
			os.Exit(1)
		}
	}

	// Assertion 4: Cursor.Delete removes an AST node from a slice of statements in a block
	{
		src := `package main
func run() {
	keepFirst := 1
	removeThis := 2
	keepSecond := 3
	_, _ = keepFirst, keepSecond
}`
		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, "src.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		deleted := false
		astutil.Apply(file, func(c *astutil.Cursor) bool {
			if assign, ok := c.Node().(*ast.AssignStmt); ok {
				for _, lhs := range assign.Lhs {
					if id, ok := lhs.(*ast.Ident); ok && id.Name == "removeThis" {
						c.Delete()
						deleted = true
						break
					}
				}
			}
			return true
		}, nil)

		if !deleted {
			fmt.Fprintf(os.Stderr, "FAIL: removeThis assign statement was not deleted\n")
			os.Exit(1)
		}

		var buf bytes.Buffer
		if err := format.Node(&buf, fset, file); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: format.Node failed: %v\n", err)
			os.Exit(1)
		}
		res := buf.String()
		if strings.Contains(res, "removeThis") {
			fmt.Fprintf(os.Stderr, "FAIL: removeThis still found in output:\n%s\n", res)
			os.Exit(1)
		}
	}

	// Assertion 5: Cursor.InsertBefore and Cursor.InsertAfter insert sibling statements into an AST block
	{
		src := `package main
func run() {
	pivot := 0
	_ = pivot
}`
		fset := token.NewFileSet()
		file, err := parser.ParseFile(fset, "src.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		inserted := false
		astutil.Apply(file, func(c *astutil.Cursor) bool {
			if assign, ok := c.Node().(*ast.AssignStmt); ok {
				for _, lhs := range assign.Lhs {
					if id, ok := lhs.(*ast.Ident); ok && id.Name == "pivot" {
						beforeStmt := &ast.AssignStmt{
							Lhs: []ast.Expr{ast.NewIdent("beforePivot")},
							Tok: token.DEFINE,
							Rhs: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: "-1"}},
						}
						afterStmt := &ast.AssignStmt{
							Lhs: []ast.Expr{ast.NewIdent("afterPivot")},
							Tok: token.DEFINE,
							Rhs: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: "1"}},
						}
						c.InsertBefore(beforeStmt)
						c.InsertAfter(afterStmt)
						inserted = true
						break
					}
				}
			}
			return true
		}, nil)

		if !inserted {
			fmt.Fprintf(os.Stderr, "FAIL: pivot statement not found for insert\n")
			os.Exit(1)
		}

		var buf bytes.Buffer
		if err := format.Node(&buf, fset, file); err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: format.Node failed: %v\n", err)
			os.Exit(1)
		}
		res := buf.String()
		if !strings.Contains(res, "beforePivot := -1") || !strings.Contains(res, "afterPivot := 1") {
			fmt.Fprintf(os.Stderr, "FAIL: inserted statements not found in output:\n%s\n", res)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: Cursor contract passed")
}

原始种子者

匿名