CodeSampleX

Ejemplo

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

Muestra verificada para golang golang.org/x/tools v0.49.0: inspector.New. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó: inspector.New…

sha256:cf3b49b5d5c1634f01b6c31ecf087c5f6ab0408bbacf32170a3ddfcd46bc3878

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify pkg:golang/golang.org/x/tools@v0.49.0
Paquetes
Símbolos
  • golang.org/x/tools/go/ast/inspector.New
Creado
2026-09-02T20:18:33Z

Contrato

  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

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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")
}

Seeder de origen

anónimo