CodeSampleX

Exemple

golang.org/x/tools v0.1.12: intsets.Sparse, astutil.PathEnclosingInterval, inspector.New

Échantillon vérifié pour golang golang.org/x/tools v0.1.12: intsets.Sparse, astutil.PathEnclosingInterval, inspector.New. Le contrat s'est exécuté sur go…

sha256:8535c729bc741c2fc9fe2602d656bc3fb55ac7fc8d3631c55711509f6229bb73

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-28

Cas

HOW
Objectif
verify pkg:golang/golang.org/x/tools@v0.1.12
Paquets
Symboles
  • golang.org/x/tools/container/intsets.Sparse
  • golang.org/x/tools/go/ast/astutil.PathEnclosingInterval
  • golang.org/x/tools/go/ast/inspector.New
  • golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet
Créé
2026-08-28T09:13:26Z

Contrat

  1. intsets.Sparse stores non-negative integers and supports bitset operations including union, intersection, difference, and membership testing
  2. astutil.PathEnclosingInterval finds the path of AST nodes enclosing a specified source interval from innermost node to root file
  3. inspector.New constructs an AST inspector supporting type-filtered traversal with Preorder, Nodes, and WithStack methods
  4. typeutil.IntuitiveMethodSet computes all methods associated with a type including pointer receiver methods for value types

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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.1.12
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/tools@v0.1.12
Demonstrate these symbols/APIs:
  - golang.org/x/tools/container/intsets.Sparse
  - golang.org/x/tools/go/ast/astutil.PathEnclosingInterval
  - golang.org/x/tools/go/ast/inspector.New
  - golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet

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:838f7d03aecaf2a19958c8b9c83a6f9b9a5583a5b3a8cf0e7abc7eda9bf6a983","contract":["intsets.Sparse stores non-negative integers and supports bitset operations including union, intersection, difference, and membership testing","astutil.PathEnclosingInterval finds the path of AST nodes enclosing a specified source interval from innermost node to root file","inspector.New constructs an AST inspector supporting type-filtered traversal with Preorder, Nodes, and WithStack methods","typeutil.IntuitiveMethodSet computes all methods associated with a type including pointer receiver methods for value types"],"goal":"verify pkg:golang/golang.org/x/tools@v0.1.12","kind":"HOW","packages":["pkg:golang/golang.org/x/tools@v0.1.12"],"schemaVersion":1,"symbols":["golang.org/x/tools/container/intsets.Sparse","golang.org/x/tools/go/ast/astutil.PathEnclosingInterval","golang.org/x/tools/go/ast/inspector.New","golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet"]},"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.1.12"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/tools@v0.1.12","symbols":["golang.org/x/tools/container/intsets.Sparse","golang.org/x/tools/go/ast/astutil.PathEnclosingInterval","golang.org/x/tools/go/ast/inspector.New","golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet"],"verifierAdapter":"golang@1"}
go.mod
module sample-golang-tools

go 1.26.6

require golang.org/x/tools v0.1.12
go.sum
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
main.go
package main

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

	"golang.org/x/tools/container/intsets"
	"golang.org/x/tools/go/ast/astutil"
	"golang.org/x/tools/go/ast/inspector"
	"golang.org/x/tools/go/types/typeutil"
)

func main() {
	// 1. Demonstrate intsets.Sparse
	var s1, s2 intsets.Sparse
	s1.Insert(10)
	s1.Insert(20)
	s2.Insert(20)
	s2.Insert(30)

	var union intsets.Sparse
	union.Copy(&s1)
	union.UnionWith(&s2)
	fmt.Printf("intsets.Sparse Union: %s (len: %d)\n", union.String(), union.Len())

	// 2. Demonstrate astutil.PathEnclosingInterval
	fset := token.NewFileSet()
	code := `package main
func add(x, y int) int {
	sum := x + y
	return sum
}`
	file, err := parser.ParseFile(fset, "calc.go", code, 0)
	if err != nil {
		panic(err)
	}

	var retIdent *ast.Ident
	ast.Inspect(file, func(n ast.Node) bool {
		if ret, ok := n.(*ast.ReturnStmt); ok && len(ret.Results) > 0 {
			if id, ok := ret.Results[0].(*ast.Ident); ok {
				retIdent = id
			}
		}
		return true
	})

	if retIdent != nil {
		path, exact := astutil.PathEnclosingInterval(file, retIdent.Pos(), retIdent.End())
		fmt.Printf("astutil.PathEnclosingInterval path depth: %d, exact: %v\n", len(path), exact)
	}

	// 3. Demonstrate inspector.New
	inspect := inspector.New([]*ast.File{file})
	var funcCount int
	inspect.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(n ast.Node) {
		funcCount++
	})
	fmt.Printf("inspector found %d function declaration(s)\n", funcCount)

	// 4. Demonstrate typeutil.IntuitiveMethodSet
	typeSrc := `package demo
type Buffer struct {
	data []byte
}
func (b Buffer) Len() int { return len(b.data) }
func (b *Buffer) Reset() { b.data = nil }
`
	typeFile, err := parser.ParseFile(fset, "demo.go", typeSrc, 0)
	if err != nil {
		panic(err)
	}

	conf := types.Config{Importer: importer.Default()}
	info := &types.Info{Defs: make(map[*ast.Ident]types.Object)}
	pkg, err := conf.Check("demo", fset, []*ast.File{typeFile}, info)
	if err != nil {
		panic(err)
	}

	bufType := pkg.Scope().Lookup("Buffer").Type()
	var mcache typeutil.MethodSetCache
	mset := typeutil.IntuitiveMethodSet(bufType, &mcache)
	fmt.Printf("typeutil.IntuitiveMethodSet found %d methods for Buffer\n", len(mset))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/tools@v0.1.12",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/tools@v0.1.12"
  ],
  "symbols": [
    "golang.org/x/tools/container/intsets.Sparse",
    "golang.org/x/tools/go/ast/astutil.PathEnclosingInterval",
    "golang.org/x/tools/go/ast/inspector.New",
    "golang.org/x/tools/go/types/typeutil.IntuitiveMethodSet"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"go/ast"
	"go/importer"
	"go/parser"
	"go/token"
	"go/types"
	"os"

	"golang.org/x/tools/container/intsets"
	"golang.org/x/tools/go/ast/astutil"
	"golang.org/x/tools/go/ast/inspector"
	"golang.org/x/tools/go/types/typeutil"
)

func main() {
	// Assertion 1: intsets.Sparse stores non-negative integers and supports bitset operations including union, intersection, difference, and membership testing
	{
		var s1, s2 intsets.Sparse
		s1.Insert(1)
		s1.Insert(10)
		s1.Insert(100)

		s2.Insert(10)
		s2.Insert(100)
		s2.Insert(1000)

		if s1.Len() != 3 {
			fmt.Fprintf(os.Stderr, "FAIL: s1.Len() expected 3, got %d\n", s1.Len())
			os.Exit(1)
		}
		if !s1.Has(1) || !s1.Has(10) || !s1.Has(100) || s1.Has(1000) {
			fmt.Fprintf(os.Stderr, "FAIL: s1 membership test failed\n")
			os.Exit(1)
		}

		var union intsets.Sparse
		union.Copy(&s1)
		union.UnionWith(&s2)
		if union.Len() != 4 || !union.Has(1) || !union.Has(10) || !union.Has(100) || !union.Has(1000) {
			fmt.Fprintf(os.Stderr, "FAIL: union failed, got len=%d, string=%s\n", union.Len(), union.String())
			os.Exit(1)
		}

		var inter intsets.Sparse
		inter.Copy(&s1)
		inter.IntersectionWith(&s2)
		if inter.Len() != 2 || !inter.Has(10) || !inter.Has(100) || inter.Has(1) || inter.Has(1000) {
			fmt.Fprintf(os.Stderr, "FAIL: intersection failed, got len=%d, string=%s\n", inter.Len(), inter.String())
			os.Exit(1)
		}

		var diff intsets.Sparse
		diff.Copy(&s1)
		diff.DifferenceWith(&s2)
		if diff.Len() != 1 || !diff.Has(1) || diff.Has(10) {
			fmt.Fprintf(os.Stderr, "FAIL: difference failed, got len=%d, string=%s\n", diff.Len(), diff.String())
			os.Exit(1)
		}

		removed := s1.Remove(10)
		if !removed || s1.Has(10) || s1.Len() != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: remove failed\n")
			os.Exit(1)
		}
	}

	// Assertion 2: astutil.PathEnclosingInterval finds the path of AST nodes enclosing a specified source interval from innermost node to root file
	{
		fset := token.NewFileSet()
		src := `package main

func process(input int) int {
	result := input + 1
	return result
}
`
		file, err := parser.ParseFile(fset, "example.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: parser.ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		var retIdent *ast.Ident
		ast.Inspect(file, func(n ast.Node) bool {
			if ret, ok := n.(*ast.ReturnStmt); ok && len(ret.Results) > 0 {
				if id, ok := ret.Results[0].(*ast.Ident); ok {
					retIdent = id
				}
			}
			return true
		})

		if retIdent == nil {
			fmt.Fprintf(os.Stderr, "FAIL: could not locate return identifier in AST\n")
			os.Exit(1)
		}

		path, exact := astutil.PathEnclosingInterval(file, retIdent.Pos(), retIdent.End())
		if !exact {
			fmt.Fprintf(os.Stderr, "FAIL: expected exact=true for return identifier interval\n")
			os.Exit(1)
		}

		// Innermost node must be *ast.Ident, outermost node must be *ast.File
		if len(path) < 4 {
			fmt.Fprintf(os.Stderr, "FAIL: expected path length >= 4, got %d\n", len(path))
			os.Exit(1)
		}
		if _, ok := path[0].(*ast.Ident); !ok {
			fmt.Fprintf(os.Stderr, "FAIL: path[0] expected *ast.Ident, got %T\n", path[0])
			os.Exit(1)
		}
		if _, ok := path[len(path)-1].(*ast.File); !ok {
			fmt.Fprintf(os.Stderr, "FAIL: path[last] expected *ast.File, got %T\n", path[len(path)-1])
			os.Exit(1)
		}
	}

	// Assertion 3: inspector.New constructs an AST inspector supporting type-filtered traversal with Preorder, Nodes, and WithStack methods
	{
		fset := token.NewFileSet()
		src := `package main
func first() int { return 10 }
func second() int { return 20 }
`
		file, err := parser.ParseFile(fset, "funcs.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: parser.ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		inspect := inspector.New([]*ast.File{file})

		// Preorder filtering for FuncDecl
		var funcNames []string
		inspect.Preorder([]ast.Node{(*ast.FuncDecl)(nil)}, func(n ast.Node) {
			if fn, ok := n.(*ast.FuncDecl); ok {
				funcNames = append(funcNames, fn.Name.Name)
			}
		})
		if len(funcNames) != 2 || funcNames[0] != "first" || funcNames[1] != "second" {
			fmt.Fprintf(os.Stderr, "FAIL: Preorder FuncDecl expected [first second], got %v\n", funcNames)
			os.Exit(1)
		}

		// Nodes filtering for ReturnStmt
		var returnCount int
		inspect.Nodes([]ast.Node{(*ast.ReturnStmt)(nil)}, func(n ast.Node, push bool) bool {
			if push {
				returnCount++
			}
			return true
		})
		if returnCount != 2 {
			fmt.Fprintf(os.Stderr, "FAIL: Nodes ReturnStmt expected 2, got %d\n", returnCount)
			os.Exit(1)
		}

		// WithStack verifying ancestor stack
		var maxStackDepth int
		inspect.WithStack([]ast.Node{(*ast.ReturnStmt)(nil)}, func(n ast.Node, push bool, stack []ast.Node) bool {
			if push && len(stack) > maxStackDepth {
				maxStackDepth = len(stack)
			}
			return true
		})
		if maxStackDepth == 0 {
			fmt.Fprintf(os.Stderr, "FAIL: WithStack did not record stack depth\n")
			os.Exit(1)
		}
	}

	// Assertion 4: typeutil.IntuitiveMethodSet computes all methods associated with a type including pointer receiver methods for value types
	{
		fset := token.NewFileSet()
		src := `package mypkg

type Counter struct {
	val int
}

func (c Counter) Value() int {
	return c.val
}

func (c *Counter) Increment() {
	c.val++
}
`
		file, err := parser.ParseFile(fset, "counter.go", src, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: parser.ParseFile failed: %v\n", err)
			os.Exit(1)
		}

		conf := types.Config{Importer: importer.Default()}
		info := &types.Info{Defs: make(map[*ast.Ident]types.Object)}
		pkg, err := conf.Check("mypkg", fset, []*ast.File{file}, info)
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL: types.Config.Check failed: %v\n", err)
			os.Exit(1)
		}

		counterType := pkg.Scope().Lookup("Counter").Type()
		var mcache typeutil.MethodSetCache
		mset := typeutil.IntuitiveMethodSet(counterType, &mcache)

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

		methodNames := make(map[string]bool)
		for _, sel := range mset {
			methodNames[sel.Obj().Name()] = true
		}

		if !methodNames["Value"] || !methodNames["Increment"] {
			fmt.Fprintf(os.Stderr, "FAIL: expected Value and Increment in method set, got %v\n", methodNames)
			os.Exit(1)
		}
	}

	fmt.Println("PASS: pkg:golang/golang.org/x/tools@v0.1.12 contract passed")
}

Seeder d'origine

anonyme