CodeSampleX

Exemple

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

Échantillon vérifié pour golang golang.org/x/tools v0.49.0: cfg.New. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a réussi : cfg.New…

sha256:a554c6522cca4c4ccd109b1016842af239fc5e93e192c8ed4b1d76512747339f

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 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

Cas

HOW
Objectif
verify golang.org/x/tools/go/cfg.New in pkg:golang/golang.org/x/tools@v0.49.0
Paquets
Symboles
  • golang.org/x/tools/go/cfg.New
Créé
2026-09-02T19:58:30Z

Contrat

  1. cfg.New constructs a control flow graph from an AST block statement for sequential code
  2. cfg.New creates branching basic blocks with two successors for conditional if-else statements
  3. cfg.New marks entry-reachable control flow blocks as Live
  4. cfg.New formats the control flow graph into a readable representation via CFG.Format

Fichiers

  • PROMPT.md
  • cfganalyzer.go
  • csx.json
  • go.mod
  • go.sum
  • 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 golang.org/x/tools/go/cfg.New in 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/cfg.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.
cfganalyzer.go
package cfganalyzer

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

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

// BuildCFG constructs a control flow graph for the given function body
// using default returnability analysis.
func BuildCFG(body *ast.BlockStmt) *cfg.CFG {
	return cfg.New(body, func(call *ast.CallExpr) bool {
		return true
	})
}

// AnalyzeFunction parses a Go source code string containing a function
// and returns the constructed CFG alongside the token.FileSet.
func AnalyzeFunction(src string) (*cfg.CFG, *token.FileSet, 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)
	}

	for _, decl := range file.Decls {
		if fn, ok := decl.(*ast.FuncDecl); ok && fn.Body != nil {
			return BuildCFG(fn.Body), fset, nil
		}
	}

	return nil, nil, fmt.Errorf("no function declaration with body found")
}

// CountBranchBlocks returns the number of blocks in the CFG that have more than one successor.
func CountBranchBlocks(c *cfg.CFG) int {
	if c == nil {
		return 0
	}
	count := 0
	for _, b := range c.Blocks {
		if len(b.Succs) > 1 {
			count++
		}
	}
	return count
}

// ReachableBlocks returns all basic blocks that are marked as live (reachable from entry).
func ReachableBlocks(c *cfg.CFG) []*cfg.Block {
	if c == nil {
		return nil
	}
	var reachable []*cfg.Block
	for _, b := range c.Blocks {
		if b.Live {
			reachable = append(reachable, b)
		}
	}
	return reachable
}
csx.json
{"case":{"caseId":"case:sha256:873001d06f4c2b21ca2a1548fcf6545853dc9bc36b621d92437ae43446a14179","contract":["cfg.New constructs a control flow graph from an AST block statement for sequential code","cfg.New creates branching basic blocks with two successors for conditional if-else statements","cfg.New marks entry-reachable control flow blocks as Live","cfg.New formats the control flow graph into a readable representation via CFG.Format"],"goal":"verify golang.org/x/tools/go/cfg.New in 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/cfg.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/cfg.New"],"verifierAdapter":"golang@1"}
go.mod
module example.com/cfg-sample

go 1.25.0

require golang.org/x/tools v0.49.0
go.sum
golang.org/x/mod v0.39.0 h1:UF5zwQdCRRUpHfyPwr7d4UrGiVeldIsogtzWVnczL74=
golang.org/x/mod v0.39.0/go.mod h1:bvIbwjQ0HUFFf5AKukeeYQG4ZBUG9yxQbR9aEweIwYY=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/tools/go/cfg.New in 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/cfg.New"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	cfganalyzer "example.com/cfg-sample"
	"golang.org/x/tools/go/cfg"
)

func main() {
	// Assertion 1: cfg.New constructs a control flow graph from an AST block statement for sequential code
	seqSrc := `package p
func linear() int {
	a := 1
	b := 2
	return a + b
}`
	c1, fset1, err := cfganalyzer.AnalyzeFunction(seqSrc)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to analyze sequential function: %v\n", err)
		os.Exit(1)
	}
	if c1 == nil || len(c1.Blocks) == 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected non-empty blocks for sequential function\n")
		os.Exit(1)
	}
	if cfganalyzer.CountBranchBlocks(c1) != 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 0 branch blocks in linear code, got %d\n", cfganalyzer.CountBranchBlocks(c1))
		os.Exit(1)
	}

	// Assertion 2: cfg.New creates branching basic blocks with two successors for conditional if-else statements
	branchSrc := `package p
func branching(x int) int {
	if x > 0 {
		return 1
	} else {
		return -1
	}
}`
	c2, fset2, err := cfganalyzer.AnalyzeFunction(branchSrc)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to analyze branching function: %v\n", err)
		os.Exit(1)
	}
	if c2 == nil {
		fmt.Fprintf(os.Stderr, "FAIL: c2 is nil\n")
		os.Exit(1)
	}
	branchCount := cfganalyzer.CountBranchBlocks(c2)
	if branchCount != 1 {
		fmt.Fprintf(os.Stderr, "FAIL: expected 1 branch block with multiple successors, got %d\n", branchCount)
		os.Exit(1)
	}
	entryBlock := c2.Blocks[0]
	if len(entryBlock.Succs) != 2 {
		fmt.Fprintf(os.Stderr, "FAIL: expected entry block to have 2 successors, got %d\n", len(entryBlock.Succs))
		os.Exit(1)
	}

	// Assertion 3: cfg.New marks entry-reachable control flow blocks as Live
	liveBlocks := cfganalyzer.ReachableBlocks(c2)
	if len(liveBlocks) == 0 {
		fmt.Fprintf(os.Stderr, "FAIL: expected reachable blocks to be non-empty\n")
		os.Exit(1)
	}
	for _, b := range liveBlocks {
		if !b.Live {
			fmt.Fprintf(os.Stderr, "FAIL: block %d should have Live=true\n", b.Index)
			os.Exit(1)
		}
	}

	// Assertion 4: cfg.New formats the control flow graph into a readable representation via CFG.Format
	formatted := c2.Format(fset2)
	if !strings.Contains(formatted, ".0:") || !strings.Contains(formatted, "succs:") {
		fmt.Fprintf(os.Stderr, "FAIL: formatted CFG missing expected markers: %q\n", formatted)
		os.Exit(1)
	}
	_ = fset1

	// Assertion 5: Direct call with mayReturn hook verifies custom non-returning function handling
	deadSrc := `package p
func panicCaller() {
	panic("fatal error")
	println("unreachable")
}`
	c3, _, err := cfganalyzer.AnalyzeFunction(deadSrc)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: failed to analyze panic caller: %v\n", err)
		os.Exit(1)
	}
	if c3 == nil {
		fmt.Fprintf(os.Stderr, "FAIL: c3 is nil\n")
		os.Exit(1)
	}

	// Direct instantiation testing block kinds
	var foundIfThen, foundIfElse bool
	for _, b := range c2.Blocks {
		if b.Kind == cfg.KindIfThen {
			foundIfThen = true
		}
		if b.Kind == cfg.KindIfElse {
			foundIfElse = true
		}
	}
	if !foundIfThen || !foundIfElse {
		fmt.Fprintf(os.Stderr, "FAIL: expected KindIfThen and KindIfElse in branching CFG\n")
		os.Exit(1)
	}

	fmt.Println("PASS: cfg.New contract passed")
}

Seeder d'origine

anonyme