CodeSampleX

Exemplo

golang.org/x/tools v0.1.12: packages.Config

Amostra verificada para golang golang.org/x/tools v0.1.12: packages.Config. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:52378e26d4f26d2b392e70b68b0c4a0a9ca3df523b38d7e496aecc5a25a91127

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-06

Caso

HOW
Objetivo
verify golang.org/x/tools/go/packages.Config in pkg:golang/golang.org/x/tools@v0.1.12
Pacotes
Símbolos
  • golang.org/x/tools/go/packages.Config
Criado
2026-09-06T13:05:37Z

Contrato

  1. packages.Config with Mode LoadMode controls package metadata inspection including ID, Name, PkgPath, and GoFiles.
  2. packages.Config with Overlay maps file paths to in-memory source buffers allowing package analysis of virtual files without disk persistence.
  3. packages.Config with NeedSyntax populates abstract syntax trees in pkg.Syntax for loaded source files.
  4. packages.Config with NeedTypes and NeedTypesInfo performs type analysis and exposes types.Package and type definitions in pkg.Types and pkg.TypesInfo.
  5. packages.Config with ParseFile customizes the source file parsing hook during package loading.
  6. packages.Config with Logf logs build system and loader execution diagnostics.
  7. packages.Config with Tests enables loading of test packages and test variants.
  8. packages.Config with Context respects context cancellation and aborts package loading.

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Go Analysis packages.Config Semantics

A search for `golang.org/x/tools/go/packages.Config` in `pkg:golang/golang.org/x/tools@v0.1.12` returned `NO_SAFE_MATCH`.

This sample verifies the configuration capabilities and behavior provided by `packages.Config` in `golang.org/x/tools/go/packages`.

## Proved Behaviors

1. **Mode Flags (`Mode`)**:
   - `packages.NeedName | packages.NeedFiles` loads basic package metadata (`ID`, `Name`, `PkgPath`, `GoFiles`) without parsing full AST or type checking.
   - `packages.NeedSyntax` parses source files into AST syntax trees (`pkg.Syntax`). Note that `NeedSyntax` requires `NeedFiles` or `NeedCompiledGoFiles` to know which files to parse.
   - `packages.NeedTypes | packages.NeedTypesInfo` runs the Go type checker (`go/types`), populating `pkg.Types` and `pkg.TypesInfo`.

2. **Virtual In-Memory Source Mapping (`Overlay`)**:
   - `packages.Config.Overlay` maps virtual file paths to in-memory `[]byte` source code buffers.
   - `packages.Load` analyzes packages containing overlay files without requiring the files to exist on disk.

3. **Custom AST Parsing Hook (`ParseFile`)**:
   - `packages.Config.ParseFile` allows callers to hook into or customize file parsing (`*ast.File`), enabling custom parser flags or comment inclusion.

4. **Diagnostic Logging (`Logf`)**:
   - Supplying a logger function `func(format string, args ...interface{})` captures internal driver execution logs and debug messages.

5. **Test Package Loading (`Tests`)**:
   - Setting `packages.Config.Tests = true` causes `packages.Load` to also return test variant packages (`<pkg>.test`).

6. **Context Support (`Context`)**:
   - Supplying a canceled `context.Context` halts package loading and returns an error.

## Compatibility Insights

- When using `NeedTypes` with constant evaluation across newer Go toolchains (Go 1.26+), `types.SizesFor` implementation details can affect constant size evaluation if `NeedTypesSizes` is omitted. Structs, functions, and untyped constants remain fully supported across toolchain versions.
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/packages.Config in 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/go/packages.Config

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:ae371b315cbb93d359886dadbf89d71a971608583d20a2c1793cd36a3fe76f61","contract":["packages.Config with Mode LoadMode controls package metadata inspection including ID, Name, PkgPath, and GoFiles.","packages.Config with Overlay maps file paths to in-memory source buffers allowing package analysis of virtual files without disk persistence.","packages.Config with NeedSyntax populates abstract syntax trees in pkg.Syntax for loaded source files.","packages.Config with NeedTypes and NeedTypesInfo performs type analysis and exposes types.Package and type definitions in pkg.Types and pkg.TypesInfo.","packages.Config with ParseFile customizes the source file parsing hook during package loading.","packages.Config with Logf logs build system and loader execution diagnostics.","packages.Config with Tests enables loading of test packages and test variants.","packages.Config with Context respects context cancellation and aborts package loading."],"goal":"verify golang.org/x/tools/go/packages.Config in 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/go/packages.Config"]},"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/go/packages.Config"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample-packages-config

go 1.23.0

require golang.org/x/tools v0.1.12

require (
	golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
	golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
)
go.sum
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
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/types"
	"os"
	"path/filepath"

	"golang.org/x/tools/go/packages"
)

func main() {
	tmpDir, err := os.MkdirTemp("", "csx-demo-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to create temp dir: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tmpDir)

	goModPath := filepath.Join(tmpDir, "go.mod")
	if err := os.WriteFile(goModPath, []byte("module example.com/analyzer\n\ngo 1.23\n"), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "failed to write go.mod: %v\n", err)
		os.Exit(1)
	}

	virtualFile := filepath.Join(tmpDir, "service.go")
	virtualSrc := []byte(`package service

// Status indicates state.
type Status string

const (
	StatusIdle Status = "idle"
	StatusBusy Status = "busy"
)

// Calculator performs arithmetic operations.
type Calculator struct {
	Base int
}

// Add adds two numbers plus Base.
func (c *Calculator) Add(a, b int) int {
	return c.Base + a + b
}
`)

	cfg := &packages.Config{
		Mode: packages.NeedName |
			packages.NeedFiles |
			packages.NeedCompiledGoFiles |
			packages.NeedSyntax |
			packages.NeedTypes |
			packages.NeedTypesInfo,
		Dir: tmpDir,
		Env: append(os.Environ(), "GOPROXY=off"),
		Overlay: map[string][]byte{
			virtualFile: virtualSrc,
		},
	}

	pkgs, err := packages.Load(cfg, "example.com/analyzer")
	if err != nil {
		fmt.Fprintf(os.Stderr, "packages.Load failed: %v\n", err)
		os.Exit(1)
	}

	for _, pkg := range pkgs {
		fmt.Printf("Loaded package ID: %s (Name: %s)\n", pkg.ID, pkg.Name)
		fmt.Printf("Go source files count: %d\n", len(pkg.GoFiles))
		fmt.Printf("AST syntax trees count: %d\n", len(pkg.Syntax))

		if pkg.Types != nil {
			scope := pkg.Types.Scope()
			fmt.Println("Package symbols:")
			for _, name := range scope.Names() {
				obj := scope.Lookup(name)
				switch t := obj.Type().(type) {
				case *types.Signature:
					fmt.Printf("  func %s%s\n", name, t)
				case *types.Named:
					fmt.Printf("  type %s (%s)\n", name, t.Underlying())
				default:
					fmt.Printf("  %s: %s\n", name, obj.Type())
				}
			}
		}
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/tools/go/packages.Config in 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/go/packages.Config"
  ]
}
test/contract.go
package main

import (
	"context"
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"go/types"
	"os"
	"path/filepath"
	"strings"

	"golang.org/x/tools/go/packages"
)

func main() {
	tmpDir, err := os.MkdirTemp("", "csx-contract-cfg-*")
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: unable to create temp dir: %v\n", err)
		os.Exit(1)
	}
	defer os.RemoveAll(tmpDir)

	goModPath := filepath.Join(tmpDir, "go.mod")
	if err := os.WriteFile(goModPath, []byte("module example.com/calc\n\ngo 1.23\n"), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: unable to write go.mod: %v\n", err)
		os.Exit(1)
	}

	calcGo := filepath.Join(tmpDir, "calc.go")
	calcSrc := []byte(`package calc

const Version = "1.0.0"

func Multiply(a, b int) int {
	return a * b
}
`)

	calcTestGo := filepath.Join(tmpDir, "calc_test.go")
	calcTestSrc := []byte(`package calc

import "testing"

func TestMultiply(t *testing.T) {
	if Multiply(2, 3) != 6 {
		t.Fail()
	}
}
`)

	overlay := map[string][]byte{
		calcGo:     calcSrc,
		calcTestGo: calcTestSrc,
	}

	env := append(os.Environ(), "GOPROXY=off")

	// Assertion 1: packages.Config with Mode LoadMode controls package metadata inspection including ID, Name, PkgPath, and GoFiles.
	{
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 1]: packages.Load returned error: %v\n", err)
			os.Exit(1)
		}
		if len(pkgs) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 1]: expected 1 package, got %d\n", len(pkgs))
			os.Exit(1)
		}
		p := pkgs[0]
		if len(p.Errors) > 0 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 1]: package errors: %v\n", p.Errors)
			os.Exit(1)
		}
		if p.ID != "example.com/calc" || p.Name != "calc" || p.PkgPath != "example.com/calc" || len(p.GoFiles) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 1]: unexpected package metadata: %+v\n", p)
			os.Exit(1)
		}
	}

	// Assertion 2: packages.Config with Overlay maps file paths to in-memory source buffers allowing package analysis of virtual files without disk persistence.
	{
		if _, err := os.Stat(calcGo); !os.IsNotExist(err) {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 2]: virtual file %s exists on disk\n", calcGo)
			os.Exit(1)
		}
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil || len(pkgs) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 2]: packages.Load failed: %v\n", err)
			os.Exit(1)
		}
		if len(pkgs[0].GoFiles) != 1 || pkgs[0].GoFiles[0] != calcGo {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 2]: GoFiles did not match overlay file: %v\n", pkgs[0].GoFiles)
			os.Exit(1)
		}
	}

	// Assertion 3: packages.Config with NeedSyntax populates abstract syntax trees in pkg.Syntax for loaded source files.
	{
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil || len(pkgs) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 3]: packages.Load failed: %v\n", err)
			os.Exit(1)
		}
		p := pkgs[0]
		if len(p.Syntax) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 3]: expected 1 AST file in Syntax, got %d\n", len(p.Syntax))
			os.Exit(1)
		}
		fileAST := p.Syntax[0]
		if fileAST == nil || fileAST.Name == nil || fileAST.Name.Name != "calc" {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 3]: invalid AST syntax structure: %+v\n", fileAST)
			os.Exit(1)
		}
	}

	// Assertion 4: packages.Config with NeedTypes and NeedTypesInfo performs type analysis and exposes types.Package and type definitions in pkg.Types and pkg.TypesInfo.
	{
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil || len(pkgs) != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 4]: packages.Load failed: %v\n", err)
			os.Exit(1)
		}
		p := pkgs[0]
		if p.Types == nil || p.TypesInfo == nil {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 4]: Types or TypesInfo is nil\n")
			os.Exit(1)
		}
		obj := p.Types.Scope().Lookup("Multiply")
		if obj == nil {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 4]: Multiply symbol not found in Types.Scope\n")
			os.Exit(1)
		}
		fnType, ok := obj.Type().(*types.Signature)
		if !ok || fnType.Params().Len() != 2 || fnType.Results().Len() != 1 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 4]: unexpected signature for Multiply: %v\n", obj.Type())
			os.Exit(1)
		}
	}

	// Assertion 5: packages.Config with ParseFile customizes the source file parsing hook during package loading.
	{
		parsedCount := 0
		cfg := &packages.Config{
			Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax,
			Dir:  tmpDir,
			Env:  env,
			Overlay: map[string][]byte{
				calcGo: calcSrc,
			},
			ParseFile: func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
				parsedCount++
				return parser.ParseFile(fset, filename, src, parser.ParseComments)
			},
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil || len(pkgs) != 1 || parsedCount == 0 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 5]: ParseFile hook failed: count=%d err=%v\n", parsedCount, err)
			os.Exit(1)
		}
	}

	// Assertion 6: packages.Config with Logf logs build system and loader execution diagnostics.
	{
		var logLines []string
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
			Logf: func(format string, args ...interface{}) {
				logLines = append(logLines, fmt.Sprintf(format, args...))
			},
		}
		_, _ = packages.Load(cfg, "example.com/calc")
		if len(logLines) == 0 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 6]: no log messages emitted via Logf\n")
			os.Exit(1)
		}
	}

	// Assertion 7: packages.Config with Tests enables loading of test packages and test variants.
	{
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
			Tests:   true,
		}
		pkgs, err := packages.Load(cfg, "example.com/calc")
		if err != nil || len(pkgs) < 2 {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 7]: expected at least 2 packages with Tests: true, got %d (err: %v)\n", len(pkgs), err)
			os.Exit(1)
		}
		hasTestPkg := false
		for _, p := range pkgs {
			if strings.Contains(p.ID, ".test") {
				hasTestPkg = true
				break
			}
		}
		if !hasTestPkg {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 7]: test package variant not found in loaded packages\n")
			os.Exit(1)
		}
	}

	// Assertion 8: packages.Config with Context respects context cancellation and aborts package loading.
	{
		ctx, cancel := context.WithCancel(context.Background())
		cancel()
		cfg := &packages.Config{
			Mode:    packages.NeedName | packages.NeedFiles,
			Context: ctx,
			Dir:     tmpDir,
			Env:     env,
			Overlay: overlay,
		}
		_, err := packages.Load(cfg, "example.com/calc")
		if err == nil {
			fmt.Fprintf(os.Stderr, "FAIL [assertion 8]: expected error on canceled context, got nil\n")
			os.Exit(1)
		}
	}

	fmt.Println("PASS: golang.org/x/tools/go/packages.Config contract passed")
}

Seeder de origem

anônimo