CodeSampleX

Exemplo

golang.org/x/net v0.29.0: html.Parse

Amostra verificada para golang golang.org/x/net v0.29.0: html.Parse. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:4615c2c1f7fae1131aeb0622a74e563871fcee8ce173b6925ceb012fa545ffc4

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

Caso

HOW
Objetivo
verify golang.org/x/net/html.Parse in pkg:golang/golang.org/x/net@v0.29.0
Pacotes
Símbolos
  • golang.org/x/net/html.Parse
Criado
2026-09-03T05:10:23Z

Contrato

  1. html.Parse parses an HTML document into a DocumentNode with standard html, head, and body hierarchy
  2. html.Parse constructs ElementNode with expected tag Data, namespace, and Attribute key-value pairs
  3. html.Parse constructs TextNode containing inner text and CommentNode containing comments
  4. html.Parse handles fragment-like or unclosed HTML input by synthesizing a valid document tree without error
  5. html.Parse preserves sibling and parent pointers across all traversed child nodes

Arquivos

  • 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

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/net/html.Parse in pkg:golang/golang.org/x/net@v0.29.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.29.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/html.Parse

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:b9c6c8ee828eea62c8a081465b5e5ae1f6d7144fd01d5caf7c30d4bcecf9dc1e","contract":["html.Parse parses an HTML document into a DocumentNode with standard html, head, and body hierarchy","html.Parse constructs ElementNode with expected tag Data, namespace, and Attribute key-value pairs","html.Parse constructs TextNode containing inner text and CommentNode containing comments","html.Parse handles fragment-like or unclosed HTML input by synthesizing a valid document tree without error","html.Parse preserves sibling and parent pointers across all traversed child nodes"],"goal":"verify golang.org/x/net/html.Parse in pkg:golang/golang.org/x/net@v0.29.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.29.0"],"schemaVersion":1,"symbols":["golang.org/x/net/html.Parse"]},"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/net@v0.29.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.29.0","symbols":["golang.org/x/net/html.Parse"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.26.6

require golang.org/x/net v0.29.0
go.sum
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
main.go
package main

import (
	"fmt"
	"log"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	htmlContent := `<!DOCTYPE html>
<html>
<head>
	<title>CodeSampleX Demonstration</title>
</head>
<body>
	<header>
		<h1>Welcome to HTML Parsing</h1>
	</header>
	<main>
		<p class="summary" id="lead">Parsing HTML documents into a DOM tree in Go.</p>
	</main>
</body>
</html>`

	doc, err := html.Parse(strings.NewReader(htmlContent))
	if err != nil {
		log.Fatalf("failed to parse HTML: %v", err)
	}

	fmt.Println("HTML parsed successfully into document tree.")

	var findNode func(*html.Node, string) *html.Node
	findNode = func(n *html.Node, tag string) *html.Node {
		if n.Type == html.ElementNode && n.Data == tag {
			return n
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			if res := findNode(c, tag); res != nil {
				return res
			}
		}
		return nil
	}

	titleNode := findNode(doc, "title")
	if titleNode != nil && titleNode.FirstChild != nil {
		fmt.Printf("Document Title: %s\n", titleNode.FirstChild.Data)
	}

	pNode := findNode(doc, "p")
	if pNode != nil {
		for _, attr := range pNode.Attr {
			fmt.Printf("Attribute %s=%q\n", attr.Key, attr.Val)
		}
		if pNode.FirstChild != nil {
			fmt.Printf("Paragraph text: %s\n", pNode.FirstChild.Data)
		}
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/html.Parse in pkg:golang/golang.org/x/net@v0.29.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.29.0"
  ],
  "symbols": [
    "golang.org/x/net/html.Parse"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	// 1. html.Parse parses an HTML document into a DocumentNode with standard html, head, and body hierarchy
	docHTML := `<!DOCTYPE html><html><head><title>Contract Test</title></head><body><h1>Heading</h1></body></html>`
	doc, err := html.Parse(strings.NewReader(docHTML))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: html.Parse returned error: %v\n", err)
		os.Exit(1)
	}
	if doc == nil || doc.Type != html.DocumentNode {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: expected DocumentNode root\n")
		os.Exit(1)
	}

	var htmlNode, headNode, bodyNode *html.Node
	for c := doc.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == html.ElementNode && c.Data == "html" {
			htmlNode = c
			break
		}
	}
	if htmlNode == nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: html element not found\n")
		os.Exit(1)
	}
	for c := htmlNode.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == html.ElementNode && c.Data == "head" {
			headNode = c
		} else if c.Type == html.ElementNode && c.Data == "body" {
			bodyNode = c
		}
	}
	if headNode == nil || bodyNode == nil {
		fmt.Fprintf(os.Stderr, "Assertion 1 failed: head or body element missing\n")
		os.Exit(1)
	}

	// 2. html.Parse constructs ElementNode with expected tag Data, namespace, and Attribute key-value pairs
	attrHTML := `<div id="main-card" class="card primary" data-count="42"><span>item</span></div>`
	attrDoc, err := html.Parse(strings.NewReader(attrHTML))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: html.Parse returned error: %v\n", err)
		os.Exit(1)
	}
	divNode := findFirstByTag(attrDoc, "div")
	if divNode == nil || divNode.Type != html.ElementNode {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: div element not found\n")
		os.Exit(1)
	}
	attrMap := make(map[string]string)
	for _, attr := range divNode.Attr {
		attrMap[attr.Key] = attr.Val
	}
	if attrMap["id"] != "main-card" || attrMap["class"] != "card primary" || attrMap["data-count"] != "42" {
		fmt.Fprintf(os.Stderr, "Assertion 2 failed: attributes mismatch: got %+v\n", attrMap)
		os.Exit(1)
	}

	// 3. html.Parse constructs TextNode containing inner text and CommentNode containing comments
	textCommentHTML := `<div><!-- initial comment -->Sample Text Content<!-- closing comment --></div>`
	tcDoc, err := html.Parse(strings.NewReader(textCommentHTML))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: html.Parse returned error: %v\n", err)
		os.Exit(1)
	}
	tcDiv := findFirstByTag(tcDoc, "div")
	if tcDiv == nil {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: div element not found\n")
		os.Exit(1)
	}
	var commentCount, textCount int
	var capturedText string
	for c := tcDiv.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == html.CommentNode {
			commentCount++
		} else if c.Type == html.TextNode {
			textCount++
			capturedText = c.Data
		}
	}
	if commentCount != 2 || textCount != 1 || capturedText != "Sample Text Content" {
		fmt.Fprintf(os.Stderr, "Assertion 3 failed: comments=%d (want 2), texts=%d (want 1), text=%q\n", commentCount, textCount, capturedText)
		os.Exit(1)
	}

	// 4. html.Parse handles fragment-like or unclosed HTML input by synthesizing a valid document tree without error
	unclosedHTML := `<section><p>Unclosed paragraph<span>Nested text`
	unclosedDoc, err := html.Parse(strings.NewReader(unclosedHTML))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: html.Parse returned unexpected error: %v\n", err)
		os.Exit(1)
	}
	pElement := findFirstByTag(unclosedDoc, "p")
	spanElement := findFirstByTag(unclosedDoc, "span")
	if pElement == nil || spanElement == nil {
		fmt.Fprintf(os.Stderr, "Assertion 4 failed: unclosed elements were not properly parsed\n")
		os.Exit(1)
	}

	// 5. html.Parse preserves sibling and parent pointers across all traversed child nodes
	if err := verifyPointers(doc); err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: doc pointer check failed: %v\n", err)
		os.Exit(1)
	}
	if err := verifyPointers(attrDoc); err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: attrDoc pointer check failed: %v\n", err)
		os.Exit(1)
	}
	if err := verifyPointers(unclosedDoc); err != nil {
		fmt.Fprintf(os.Stderr, "Assertion 5 failed: unclosedDoc pointer check failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("All contract assertions passed.")
}

func findFirstByTag(n *html.Node, tag string) *html.Node {
	if n.Type == html.ElementNode && n.Data == tag {
		return n
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if res := findFirstByTag(c, tag); res != nil {
			return res
		}
	}
	return nil
}

func verifyPointers(n *html.Node) error {
	var lastChild *html.Node
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if c.Parent != n {
			return fmt.Errorf("child node %p has parent %p, expected %p", c, c.Parent, n)
		}
		if c.NextSibling != nil && c.NextSibling.PrevSibling != c {
			return fmt.Errorf("node %p next sibling's prev sibling mismatch", c)
		}
		if c.PrevSibling != nil && c.PrevSibling.NextSibling != c {
			return fmt.Errorf("node %p prev sibling's next sibling mismatch", c)
		}
		lastChild = c
		if err := verifyPointers(c); err != nil {
			return err
		}
	}
	if n.FirstChild != nil && n.LastChild != lastChild {
		return fmt.Errorf("node %p LastChild mismatch: got %p, expected %p", n, n.LastChild, lastChild)
	}
	return nil
}

Seeder de origem

anônimo