CodeSampleX

Exemplo

modernc.org/cc/v4 v4.28.1: cc.Builtin, cc.FunctionType, cc.NewABI

Amostra verificada para golang modernc.org/cc/v4 v4.28.1: cc.Builtin, cc.FunctionType, cc.NewABI. O contrato rodou em go 1.26 · linux debian/x64 · docker e…

sha256:7fc37c5c1a9a4f040e92a446f0a405407ca7f01248749c53e34af3406630bd19

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

Caso

HOW
Objetivo
verify pkg:golang/modernc.org/cc/v4@v4.28.1
Pacotes
Símbolos
  • cc.Builtin
  • cc.FunctionType
  • cc.NewABI
  • cc.StructType
  • cc.Translate
Criado
2026-11-29T03:00:24Z

Contrato

  1. cc.NewABI("linux", "amd64") constructs the target ABI without a host C compiler, and cc.NewABI with an unsupported OS/arch returns a non-nil error
  2. cc.Translate with predefined integer type macros, cc.Builtin, and Config.EvalAllMacros=true evaluates object-like arithmetic macros to cc.Int64Value in AST.Macros
  3. Typedef struct declarations in AST.Scope.Nodes resolve to *cc.StructType with ABI-computed Size(), Align(), and per-field Offset() values, and function declarations resolve to *cc.FunctionType with Result(), Parameters(), IsVariadic(), and Declarator.IsFuncDef()
  4. cc.Translate returns an error mentioning __predefined_declarator when cc.Builtin is omitted, and returns non-nil errors for invalid C syntax or undeclared identifiers

Arquivos

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

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

Código-fonte

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/modernc.org/cc/v4@v4.28.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/modernc.org/cc/v4@v4.28.1
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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.
cccheck.go
package sample

import (
	"fmt"

	"modernc.org/cc/v4"
)

const linuxAMD64Predefined = `
#define __SIZE_TYPE__ long unsigned int
#define __UINT16_TYPE__ unsigned short
#define __UINT32_TYPE__ unsigned int
#define __UINT64_TYPE__ long unsigned int
`

// FuncInfo summarizes a parsed C function declaration or definition.
type FuncInfo struct {
	Name       string
	ReturnKind cc.Kind
	ParamCount int
	IsVariadic bool
	IsFuncDef  bool
}

// RecordInfo summarizes an ABI-computed C struct layout.
type RecordInfo struct {
	Size         int64
	Align        int
	FieldOffsets map[string]int64
}

// ParseReport holds key AST results extracted from a translated C unit.
type ParseReport struct {
	IntMacros map[string]int64
	Functions map[string]FuncInfo
	Records   map[string]RecordInfo
}

// AnalyzeC translates C source for the given target OS/arch using modernc.org/cc/v4
// without invoking an external C compiler.
func AnalyzeC(targetOS, targetArch, source string) (*ParseReport, error) {
	abi, err := cc.NewABI(targetOS, targetArch)
	if err != nil {
		return nil, fmt.Errorf("create abi: %w", err)
	}

	cfg := &cc.Config{
		ABI:           abi,
		EvalAllMacros: true,
	}
	sources := []cc.Source{
		{Name: "<predefined>", Value: linuxAMD64Predefined},
		{Name: "<builtin>", Value: cc.Builtin},
		{Name: "unit.c", Value: source},
	}

	ast, err := cc.Translate(cfg, sources)
	if err != nil {
		return nil, err
	}

	report := &ParseReport{
		IntMacros: make(map[string]int64),
		Functions: make(map[string]FuncInfo),
		Records:   make(map[string]RecordInfo),
	}

	for name, m := range ast.Macros {
		if val, ok := m.Value().(cc.Int64Value); ok {
			report.IntMacros[name] = int64(val)
		}
	}

	for name, nodes := range ast.Scope.Nodes {
		for _, n := range nodes {
			d, ok := n.(*cc.Declarator)
			if !ok {
				continue
			}

			if ft, ok := d.Type().(*cc.FunctionType); ok {
				report.Functions[name] = FuncInfo{
					Name:       name,
					ReturnKind: ft.Result().Kind(),
					ParamCount: len(ft.Parameters()),
					IsVariadic: ft.IsVariadic(),
					IsFuncDef:  d.IsFuncDef(),
				}
			}

			if d.IsTypename() {
				if st, ok := d.Type().(*cc.StructType); ok {
					offsets := make(map[string]int64, st.NumFields())
					for i := 0; i < st.NumFields(); i++ {
						field := st.FieldByIndex(i)
						offsets[field.Name()] = field.Offset()
					}
					report.Records[name] = RecordInfo{
						Size:         st.Size(),
						Align:        st.Align(),
						FieldOffsets: offsets,
					}
				}
			}
		}
	}

	return report, nil
}
csx.json
{"case":{"caseId":"case:sha256:0125c45d7a8834f865f2002bbe158a99a55962a3ba8fcf9b46b4df5684205e0e","contract":["cc.NewABI(\"linux\", \"amd64\") constructs the target ABI without a host C compiler, and cc.NewABI with an unsupported OS/arch returns a non-nil error","cc.Translate with predefined integer type macros, cc.Builtin, and Config.EvalAllMacros=true evaluates object-like arithmetic macros to cc.Int64Value in AST.Macros","Typedef struct declarations in AST.Scope.Nodes resolve to *cc.StructType with ABI-computed Size(), Align(), and per-field Offset() values, and function declarations resolve to *cc.FunctionType with Result(), Parameters(), IsVariadic(), and Declarator.IsFuncDef()","cc.Translate returns an error mentioning __predefined_declarator when cc.Builtin is omitted, and returns non-nil errors for invalid C syntax or undeclared identifiers"],"goal":"verify pkg:golang/modernc.org/cc/v4@v4.28.1","kind":"HOW","packages":["pkg:golang/modernc.org/cc/v4@v4.28.1"],"schemaVersion":1,"symbols":["cc.Builtin","cc.FunctionType","cc.NewABI","cc.StructType","cc.Translate"]},"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/modernc.org/cc/v4@v4.28.1"],"schemaVersion":1,"subject":"pkg:golang/modernc.org/cc/v4@v4.28.1","symbols":["cc.Builtin","cc.FunctionType","cc.NewABI","cc.StructType","cc.Translate"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.25

require modernc.org/cc/v4 v4.28.1

require (
	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
	modernc.org/mathutil v1.7.1 // indirect
	modernc.org/opt v0.2.0 // indirect
	modernc.org/sortutil v1.2.1 // indirect
	modernc.org/strutil v1.2.1 // indirect
	modernc.org/token v1.1.0 // indirect
)
go.sum
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=
github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
modernc.org/cc/v4 v4.28.1 h1:XpLbkYVQ24E8tX5u8+yWGvaxerxkR/S4zqxI8ZoSBuc=
modernc.org/cc/v4 v4.28.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
modernc.org/ccorpus2 v1.6.0 h1:JODbahvmixwZDoF1kZs/9Rj6aHA2vAPP7HKiNDq//xo=
modernc.org/ccorpus2 v1.6.0/go.mod h1:Wifvo4Q/qS/h1aRoC2TffcHsnxwTikmi1AuLANuucJQ=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/modernc.org/cc/v4@v4.28.1",
  "kind": "HOW",
  "packages": [
    "pkg:golang/modernc.org/cc/v4@v4.28.1"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	"modernc.org/cc/v4"
	"sample"
)

func fail(format string, args ...any) {
	fmt.Fprintf(os.Stderr, format+"\n", args...)
	os.Exit(1)
}

func main() {
	const cUnit = `
#define BASE_PORT 8000
#define PORT_OFFSET 80
#define SERVICE_PORT (BASE_PORT + PORT_OFFSET)

typedef struct Header {
	unsigned char version;
	unsigned int length;
	unsigned long checksum;
} Header;

int verify_header(const Header *hdr, int flags) {
	return hdr != 0 && flags >= 0;
}

int log_event(const char *fmt, ...);
`

	report, err := sample.AnalyzeC("linux", "amd64", cUnit)
	if err != nil {
		fail("AnalyzeC failed on valid C unit: %v", err)
	}

	if got := report.IntMacros["SERVICE_PORT"]; got != 8080 {
		fail("expected SERVICE_PORT=8080, got %d", got)
	}

	hdr, ok := report.Records["Header"]
	if !ok {
		fail("expected Header struct in report")
	}
	if hdr.Size != 16 || hdr.Align != 8 {
		fail("expected Header size=16 align=8, got size=%d align=%d", hdr.Size, hdr.Align)
	}
	if hdr.FieldOffsets["version"] != 0 || hdr.FieldOffsets["length"] != 4 || hdr.FieldOffsets["checksum"] != 8 {
		fail("unexpected Header field offsets: %+v", hdr.FieldOffsets)
	}

	fn, ok := report.Functions["verify_header"]
	if !ok {
		fail("expected verify_header in report")
	}
	if !fn.IsFuncDef || fn.ReturnKind != cc.Int || fn.ParamCount != 2 || fn.IsVariadic {
		fail("unexpected verify_header info: %+v", fn)
	}

	varFn, ok := report.Functions["log_event"]
	if !ok {
		fail("expected log_event in report")
	}
	if varFn.IsFuncDef || varFn.ReturnKind != cc.Int || varFn.ParamCount != 1 || !varFn.IsVariadic {
		fail("unexpected log_event info: %+v", varFn)
	}

	// Unsupported target returns an error from cc.NewABI.
	if _, err := cc.NewABI("unsupported-os", "unsupported-arch"); err == nil {
		fail("expected error for unsupported ABI target")
	}

	// Missing cc.Builtin fails because __predefined_declarator is not declared.
	abi, err := cc.NewABI("linux", "amd64")
	if err != nil {
		fail("unexpected NewABI error: %v", err)
	}
	if _, err := cc.Translate(&cc.Config{ABI: abi}, []cc.Source{{Name: "minimal.c", Value: "int v = 42;"}}); err == nil || !strings.Contains(err.Error(), "__predefined_declarator") {
		fail("expected __predefined_declarator error when cc.Builtin is omitted, got: %v", err)
	}

	// Syntax error returns a non-nil error.
	if _, err := sample.AnalyzeC("linux", "amd64", "int bad_fn( { return 1; }"); err == nil {
		fail("expected error for invalid C syntax")
	}

	// Semantic type error returns a non-nil error in Translate.
	if _, err := sample.AnalyzeC("linux", "amd64", "int f(void) { return missing_symbol; }"); err == nil {
		fail("expected error for undeclared identifier")
	}
}

Seeder de origem

anônimo