CodeSampleX

샘플

golang.org/x/tools v0.49.0: inspector.New

검증된 샘플 — golang golang.org/x/tools v0.49.0: inspector.New. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: inspector.New constructs an Inspector…

sha256:cf3b49b5d5c1634f01b6c31ecf087c5f6ab0408bbacf32170a3ddfcd46bc3878

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 go

검증 실행 환경

환경 컨트랙트 단계 실행일
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-02

케이스

HOW
목표
verify pkg:golang/golang.org/x/tools@v0.49.0
패키지
심벌
  • golang.org/x/tools/go/ast/inspector.New
생성일
2026-09-02T20:18:33Z

컨트랙트

  1. inspector.New constructs an Inspector from AST files for type-filtered syntax tree inspection
  2. inspector.Preorder visits specified AST node types in depth-first preorder traversal
  3. inspector.Nodes dispatches push and pop events for matching node types and supports subtree pruning
  4. inspector.WithStack maintains the ancestor node stack from root file to innermost node
  5. Inspector.Root returns a valid cursor enabling hierarchical AST node inspection

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • inspectutil.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 pkg:golang/golang.org/x/tools@v0.49.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/tools@v0.49.0
Demonstrate these symbols/APIs:
  - golang.org/x/tools/go/ast/inspector.New

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:d74fffaddba7899ee8f1815e4149d85ae3545186d727a53da35dd0460722a86f","contract":["inspector.New constructs an Inspector from AST files for type-filtered syntax tree inspection","inspector.Preorder visits specified AST node types in depth-first preorder traversal","inspector.Nodes dispatches push and pop events for matching node types and supports subtree pruning","inspector.WithStack maintains the ancestor node stack from root file to innermost node","Inspector.Root returns a valid cursor enabling hierarchical AST node inspection"],"goal":"verify pkg:golang/golang.org/x/tools@v0.49.0","kind":"HOW","packages":["pkg:golang/golang.org/x/tools@v0.49.0"],"schemaVersion":1,"symbols":["golang.org/x/tools/go/ast/inspector.New"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/tools@v0.49.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/tools@v0.49.0","symbols":["golang.org/x/tools/go/ast/inspector.New"],"verifierAdapter":"golang@1"}
go.mod
module example.com/ast-inspector

go 1.25.0

require golang.org/x/tools v0.49.0
go.sum
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
inspectutil.go
package inspectutil

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

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

// ParseSource parses Go source text into an AST file and token.FileSet.
func ParseSource(src string) (*token.FileSet, *ast.File, error) {
	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "src.go", src, 0)
	if err != nil {
		return nil, nil, fmt.Errorf("parsing source failed: %w", err)
	}
	return fset, file, nil
}

// NewInspector creates an Inspector for the provided AST files.
func NewInspector(files []*ast.File) *inspector.Inspector {
	return inspector.New(files)
}

// FindIdentifiers collects the names of all ast.Ident nodes using Preorder.
func FindIdentifiers(in *inspector.Inspector) []string {
	var names []string
	in.Preorder([]ast.Node{(*ast.Ident)(nil)}, func(n ast.Node) {
		if id, ok := n.(*ast.Ident); ok {
			names = append(names, id.Name)
		}
	})
	return names
}

// CollectCallNames collects function names from CallExpr nodes whose fun is an Ident.
func CollectCallNames(in *inspector.Inspector) []string {
	var names []string
	in.Preorder([]ast.Node{(*ast.CallExpr)(nil)}, func(n ast.Node) {
		if call, ok := n.(*ast.CallExpr); ok {
			if id, ok := call.Fun.(*ast.Ident); ok {
				names = append(names, id.Name)
			}
		}
	})
	return names
}

// TraverseWithPruning traverses matching nodes, skipping subtrees when prune returns true.
func TraverseWithPruning(in *inspector.Inspector, types []ast.Node, prune func(ast.Node) bool) (pushCount, popCount int) {
	in.Nodes(types, func(n ast.Node, push bool) bool {
		if push {
			pushCount++
			if prune != nil && prune(n) {
				return false
			}
		} else {
			popCount++
		}
		return true
	})
	return pushCount, popCount
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/tools@v0.49.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/tools@v0.49.0"
  ],
  "symbols": [
    "golang.org/x/tools/go/ast/inspector.New"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"go/ast"
	"os"

	inspectutil "example.com/ast-inspector"
	"golang.org/x/tools/go/ast/inspector"
)

func main() {
	src := `package sample

func compute(a, b int) int {
	if a > 0 {
		return a + b
	}
	println("non-positive")
	return 0
}
`

	fset, file, err := inspectutil.ParseSource(src)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to parse sample source: %v\n", err)
		os.Exit(1)
	}
	_ = fset

	// Assertion 1: inspector.New constructs an Inspector from AST files for type-filtered syntax tree inspection
	in := inspector.New([]*ast.File{file})
	if in == nil {
		fmt.Fprintf(os.Stderr, "FAIL 1: inspector.New returned nil\n")
		os.Exit(1)
	}

	// Assertion 2: inspector.Preorder visits specified AST node types in depth-first preorder traversal
	{
		var idents []string
		in.Preorder([]ast.Node{(*ast.Ident)(nil)}, func(n ast.Node) {
			id, ok := n.(*ast.Ident)
			if !ok {
				fmt.Fprintf(os.Stderr, "FAIL 2: expected *ast.Ident, got %T\n", n)
				os.Exit(1)
			}
			idents = append(idents, id.Name)
		})

		if len(idents) == 0 {
			fmt.Fprintf(os.Stderr, "FAIL 2: Preorder found no identifiers\n")
			os.Exit(1)
		}
		if idents[0] != "sample" || idents[1] != "compute" {
			fmt.Fprintf(os.Stderr, "FAIL 2: unexpected identifier prefix: %v\n", idents)
			os.Exit(1)
		}

		calls := inspectutil.CollectCallNames(in)
		if len(calls) != 1 || calls[0] != "println" {
			fmt.Fprintf(os.Stderr, "FAIL 2: expected [println] call, got %v\n", calls)
			os.Exit(1)
		}
	}

	// Assertion 3: inspector.Nodes dispatches push and pop events for matching node types and supports subtree pruning
	{
		var pushEvents, popEvents int
		in.Nodes([]ast.Node{(*ast.IfStmt)(nil)}, func(n ast.Node, push bool) bool {
			if _, ok := n.(*ast.IfStmt); !ok {
				fmt.Fprintf(os.Stderr, "FAIL 3: expected *ast.IfStmt, got %T\n", n)
				os.Exit(1)
			}
			if push {
				pushEvents++
			} else {
				popEvents++
			}
			return true
		})

		if pushEvents != 1 || popEvents != 1 {
			fmt.Fprintf(os.Stderr, "FAIL 3: expected 1 push and 1 pop for single IfStmt, got push=%d pop=%d\n", pushEvents, popEvents)
			os.Exit(1)
		}

		var visitedInIf bool
		in.Nodes(nil, func(n ast.Node, push bool) bool {
			if push {
				if _, ok := n.(*ast.IfStmt); ok {
					return false // prune children of IfStmt
				}
				if _, ok := n.(*ast.BinaryExpr); ok {
					visitedInIf = true
				}
			}
			return true
		})

		if visitedInIf {
			fmt.Fprintf(os.Stderr, "FAIL 3: expected BinaryExpr inside IfStmt to be pruned\n")
			os.Exit(1)
		}
	}

	// Assertion 4: inspector.WithStack maintains the ancestor node stack from root file to innermost node
	{
		var stackVerified bool
		in.WithStack([]ast.Node{(*ast.ReturnStmt)(nil)}, func(n ast.Node, push bool, stack []ast.Node) bool {
			if push {
				if len(stack) < 3 {
					fmt.Fprintf(os.Stderr, "FAIL 4: stack depth too shallow: %d\n", len(stack))
					os.Exit(1)
				}
				if rootFile, ok := stack[0].(*ast.File); !ok || rootFile != file {
					fmt.Fprintf(os.Stderr, "FAIL 4: stack root is not the parsed file: %T\n", stack[0])
					os.Exit(1)
				}
				if current := stack[len(stack)-1]; current != n {
					fmt.Fprintf(os.Stderr, "FAIL 4: top of stack does not match current node\n")
					os.Exit(1)
				}
				stackVerified = true
			}
			return true
		})

		if !stackVerified {
			fmt.Fprintf(os.Stderr, "FAIL 4: ReturnStmt stack was not verified\n")
			os.Exit(1)
		}
	}

	// Assertion 5: Inspector.Root returns a valid cursor enabling hierarchical AST node inspection
	{
		root := in.Root()
		if !root.Valid() {
			fmt.Fprintf(os.Stderr, "FAIL 5: root cursor is invalid\n")
			os.Exit(1)
		}
		if root.Node() != nil {
			fmt.Fprintf(os.Stderr, "FAIL 5: root.Node() expected nil, got %T\n", root.Node())
			os.Exit(1)
		}

		first := in.At(0)
		if !first.Valid() {
			fmt.Fprintf(os.Stderr, "FAIL 5: cursor at index 0 is invalid\n")
			os.Exit(1)
		}
		if first.Node() != file {
			fmt.Fprintf(os.Stderr, "FAIL 5: expected first node to be *ast.File, got %T\n", first.Node())
			os.Exit(1)
		}
		if first.Parent() != root {
			fmt.Fprintf(os.Stderr, "FAIL 5: expected first node's parent to be root\n")
			os.Exit(1)
		}
	}

	fmt.Println("PASS: all inspector.New contract assertions verified")
}

오리진 시더

익명