CodeSampleX

샘플

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

검증된 샘플 — golang golang.org/x/tools v0.44.0: astutil.Cursor. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: Cursor.Node and Cursor.Parent return…

sha256:41699251adcd0eaade23b2ccf07262c8585cc98e9ed0e21c0ad3fffaa8c145e0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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")
}

오리진 시더

익명