Commit c3a64c8be9 for golang

commit c3a64c8be989882e9f77d48cc0fc0ef8ab917ed2
Author: Mark Freeman <mark@golang.org>
Date:   Wed Dec 2 15:04:45 2026 -0500

    cmd/compile/internal/contraire: put another head on contraire

    This change puts a main.go with contraire so we can invoke it directly.
    This also makes the test a bit easier, since we don't need to deal with
    the flags.

    Most of this change is exporting symbols so main.go can use them.

    Change-Id: I88caf48ce90f4f6f10cca6b28d848aac309e5b89
    Reviewed-on: https://go-review.googlesource.com/c/go/+/868904
    Auto-Submit: Mark Freeman <mark@golang.org>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
    Reviewed-by: Robert Griesemer <gri@google.com>

diff --git a/src/cmd/compile/internal/contraire/cfg.go b/src/cmd/compile/internal/contraire/cfg.go
index 1d8aaf3677..fd28cb44a0 100644
--- a/src/cmd/compile/internal/contraire/cfg.go
+++ b/src/cmd/compile/internal/contraire/cfg.go
@@ -4,9 +4,9 @@

 package contraire

-// config defines the set of probabilities that Contraire will use while
+// Config defines the set of probabilities that Contraire will use while
 // generating an AST.
-type config struct {
+type Config struct {
 	ConstDeclMaxCount int // [1, N]
 	TypeDeclMaxCount  int // [1, N]

@@ -22,7 +22,7 @@ type config struct {
 }

 // cfg is a reasonable default config.
-var cfg = &config{
+var cfg = &Config{
 	ConstDeclMaxCount: 4,
 	TypeDeclMaxCount:  4,

diff --git a/src/cmd/compile/internal/contraire/contraire_test.go b/src/cmd/compile/internal/contraire/contraire_test.go
index 0ddfb6cf35..518b9294ed 100644
--- a/src/cmd/compile/internal/contraire/contraire_test.go
+++ b/src/cmd/compile/internal/contraire/contraire_test.go
@@ -7,42 +7,30 @@
 package contraire

 import (
-	"flag"
-	"fmt"
-	"os"
+	"internal/testenv"
+	"path/filepath"
 	"runtime"
 	"testing"
 )

-var (
-	workerFlag = flag.Bool("worker", false, "run in worker mode")
-	trialsFlag = flag.Int("trials", 0, "number of trials to run")
-	cfgFlag    = flag.String("cfg", "", "path to config JSON file")
-	outFlag    = flag.String("out", "", "path to output JSON file")
-	lckFlag    = flag.String("lock", "", "path to lock file")
-	stdFlag    = flag.Bool("std", false, "use go/types instead of types2")
-)
-
-func TestMain(m *testing.M) {
-	flag.Parse()
-	if *workerFlag {
-		if err := runWorker(*trialsFlag, *cfgFlag, *outFlag, *lckFlag, *stdFlag); err != nil {
-			fmt.Fprintln(os.Stderr, err)
-			os.Exit(1)
-		}
-		os.Exit(0)
-	}
-	os.Exit(m.Run())
-}
-
 func TestContraire(t *testing.T) {
 	if testing.Short() {
 		t.Skip("skipping in short mode")
 	}
+	testenv.MustHaveGoBuild(t)
+
+	dir := t.TempDir()
+
+	// Build the binary for workers.
+	exe := filepath.Join(dir, "exe")
+	cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-o", exe, "main.go")
+	if out, err := cmd.CombinedOutput(); err != nil {
+		t.Fatalf("couldn't build worker binary: %v\n%s", err, out)
+	}

 	const trials = 1_000_000
 	for _, std := range [...]bool{false, true} {
-		out, err := runDriver(t.TempDir(), trials, runtime.GOMAXPROCS(0), nil, std)
+		out, err := RunDriver(exe, dir, trials, runtime.GOMAXPROCS(0), nil, std)
 		if err != nil {
 			t.Fatal(err)
 		}
diff --git a/src/cmd/compile/internal/contraire/driver.go b/src/cmd/compile/internal/contraire/driver.go
index b2cbdf7004..3d7a10d536 100644
--- a/src/cmd/compile/internal/contraire/driver.go
+++ b/src/cmd/compile/internal/contraire/driver.go
@@ -18,9 +18,9 @@ import (
 	"time"
 )

-// runDriver manages workers that generate and type-check programs. It returns a
+// RunDriver manages workers that generate and type-check programs. It returns a
 // summary of the workers' outputs (or an error).
-func runDriver(workDir string, trials, workers int, cfg *config, std bool) (*output, error) {
+func RunDriver(workerExe, workDir string, trials, workers int, cfg *Config, std bool) (*Output, error) {
 	if trials < 1 {
 		return nil, errors.New("trials must be positive")
 	}
@@ -29,12 +29,6 @@ func runDriver(workDir string, trials, workers int, cfg *config, std bool) (*out
 	}
 	workers = min(workers, trials)

-	// The worker uses the same binary as the driver.
-	exe, err := os.Executable()
-	if err != nil {
-		return nil, fmt.Errorf("couldn't find executable: %v", err)
-	}
-
 	// Recreate the driver directory in case a prior run didn't exit cleanly.
 	driverDir := filepath.Join(workDir, "contraire")
 	if err := recreateDir(driverDir); err != nil {
@@ -57,7 +51,7 @@ func runDriver(workDir string, trials, workers int, cfg *config, std bool) (*out
 	// Create workers and assign initial shards to them.
 	active := make(map[int]*worker, workers)
 	for i := range workers {
-		active[i] = newWorker(i, driverDir, exe)
+		active[i] = newWorker(i, driverDir, workerExe)
 	}
 	shardSize := trials / workers
 	remainder := trials % workers
@@ -75,7 +69,7 @@ func runDriver(workDir string, trials, workers int, cfg *config, std bool) (*out
 	ticker := time.NewTicker(100 * time.Millisecond)
 	defer ticker.Stop()

-	acc := &output{}
+	acc := &Output{}
 	for len(active) > 0 {
 		<-ticker.C
 		for i, w := range active {
@@ -118,7 +112,7 @@ func (w *worker) initDir() error {
 		return err
 	}
 	w.outPath = filepath.Join(workerDir, "out.json")
-	data, err := json.Marshal(&output{})
+	data, err := json.Marshal(&Output{})
 	if err != nil {
 		return fmt.Errorf("couldn't encode output: %v", err)
 	}
@@ -183,7 +177,7 @@ const (
 	shardHanging
 )

-func (w *worker) poll() (*output, error) {
+func (w *worker) poll() (*Output, error) {
 	state, out, err := w.shard.poll()
 	if err != nil {
 		return nil, err
@@ -205,7 +199,7 @@ func (w *worker) poll() (*output, error) {
 	return out, nil
 }

-func (s *shard) poll() (shardState, *output, error) {
+func (s *shard) poll() (shardState, *Output, error) {
 	f, err := os.Open(s.lockPath)
 	if err != nil {
 		return 0, nil, fmt.Errorf("couldn't open lock file %q: %v", s.lockPath, err)
@@ -220,7 +214,7 @@ func (s *shard) poll() (shardState, *output, error) {
 	if err != nil {
 		return 0, nil, fmt.Errorf("couldn't read output %q: %v", s.outPath, err)
 	}
-	out := &output{}
+	out := &Output{}
 	if err := json.Unmarshal(data, out); err != nil {
 		return 0, nil, fmt.Errorf("couldn't decode output %q: %v", s.outPath, err)
 	}
diff --git a/src/cmd/compile/internal/contraire/gen.go b/src/cmd/compile/internal/contraire/gen.go
index 7bfbc2cb69..af0e02254b 100644
--- a/src/cmd/compile/internal/contraire/gen.go
+++ b/src/cmd/compile/internal/contraire/gen.go
@@ -7,13 +7,13 @@ package contraire
 import "fmt"

 // newGenerator returns a new generator.
-func newGenerator(cfg *config) *generator {
+func newGenerator(cfg *Config) *generator {
 	return &generator{cfg: cfg}
 }

 // A generator generates Contraire ASTs.
 type generator struct {
-	cfg *config // immutable
+	cfg *Config // immutable
 	s   *state  // mutable
 }

diff --git a/src/cmd/compile/internal/contraire/main.go b/src/cmd/compile/internal/contraire/main.go
new file mode 100644
index 0000000000..a9619078b7
--- /dev/null
+++ b/src/cmd/compile/internal/contraire/main.go
@@ -0,0 +1,113 @@
+// Copyright 2026 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+//go:build ignore
+
+package main
+
+import (
+	"cmd/compile/internal/contraire"
+	"encoding/json"
+	"flag"
+	"fmt"
+	"log"
+	"os"
+	"runtime"
+)
+
+var (
+	// ============================= Driver Flags =============================
+
+	// (Optional) Sets the number of workers that will generate programs in
+	// parallel; each worker gets a process.
+	workers = flag.Int("workers", runtime.GOMAXPROCS(0), "number of worker processes")
+
+	// ============================= Shared Flags =============================
+
+	// (Required) Sets the number of programs to generate.
+	//
+	// To a driver, this means the sum of programs across all workers.
+	// To a worker, this means the number of programs for this worker.
+	trials = flag.Int("trials", 0, "number of trials to run")
+
+	// (Optional) Sets the configuration controlling program generation
+	// parameters.
+	cfgPath = flag.String("cfg", "", "path to config JSON file")
+
+	// (Optional) Write output to a file; otherwise print a summary.
+	outPath = flag.String("out", "", "path to output JSON file")
+
+	// (Optional) Sets type-checking to use go/parser and go/types.
+	std = flag.Bool("std", false, "use go/types")
+
+	// ============================= Worker Flags =============================
+
+	// Instructs the binary to execute in worker mode. If true, trials, outPath,
+	// and lockPath are required.
+	worker   = flag.Bool("worker", false, "run in worker mode")
+	lockPath = flag.String("lock", "", "path to lock file")
+)
+
+func main() {
+	log.SetFlags(0)
+	log.SetPrefix("contraire: ")
+
+	flag.Parse()
+
+	if *worker {
+		if err := contraire.RunWorker(*trials, *cfgPath, *outPath, *lockPath, *std); err != nil {
+			log.Fatal(err)
+		}
+		return
+	}
+
+	// Forward binary to workers.
+	exe, err := os.Executable()
+	if err != nil {
+		log.Fatalf("couldn't find executable: %v", err)
+	}
+
+	// Load config (if provided).
+	var cfg *contraire.Config
+	if *cfgPath != "" {
+		data, err := os.ReadFile(*cfgPath)
+		if err != nil {
+			log.Fatalf("couldn't read config %q: %v", *cfgPath, err)
+		}
+		cfg = new(contraire.Config)
+		if err := json.Unmarshal(data, cfg); err != nil {
+			log.Fatalf("couldn't decode config %q: %v", *cfgPath, err)
+		}
+	}
+
+	out, err := contraire.RunDriver(exe, os.TempDir(), *trials, *workers, cfg, *std)
+	if err != nil {
+		log.Fatal(err)
+	}
+
+	// Write output (if provided).
+	if *outPath != "" {
+		data, err := json.MarshalIndent(out, "", "\t")
+		if err != nil {
+			log.Fatalf("couldn't encode output: %v", err)
+		}
+		if err := os.WriteFile(*outPath, data, 0644); err != nil {
+			log.Fatalf("couldn't write output to %q: %v", *outPath, err)
+		}
+	} else {
+		fmt.Printf("trials:       %d\n", out.TrialsDone)
+		fmt.Printf("parse errors: %d\n", out.ParseErrors)
+		fmt.Printf("type errors:  %d\n", out.TypeErrors)
+		fmt.Printf("successes:    %d\n", out.Successes)
+		if out.Panic != nil {
+			fmt.Printf("panic:\n%s\n", out.Panic.Source)
+		}
+		if out.Crash != nil {
+			fmt.Printf("crash:\n%s\n", out.Crash.Source)
+		}
+		if out.Hang != nil {
+			fmt.Printf("hang:\n%s\n", out.Hang.Source)
+		}
+	}
+}
diff --git a/src/cmd/compile/internal/contraire/shared.go b/src/cmd/compile/internal/contraire/shared.go
index c3ad5893cc..36dd10014f 100644
--- a/src/cmd/compile/internal/contraire/shared.go
+++ b/src/cmd/compile/internal/contraire/shared.go
@@ -4,24 +4,24 @@

 package contraire

-// JSON encoding of messages emitted from both workers and the driver.
-type output struct {
+// Output is the JSON encoding of messages emitted from both workers and the driver.
+type Output struct {
 	TrialsDone  int         // The number of trials completed.
-	Next        *scoredProg // A write-ahead of the program about to be type-checked.
+	Next        *ScoredProg // A write-ahead of the program about to be type-checked.
 	ParseErrors int         // The number of generated programs with parse errors.
 	TypeErrors  int         // The number of generated programs with type errors.
 	Successes   int         // The number of generated programs without errors.
-	Panic       *scoredProg // The lowest-score program with a panic failure.
-	Crash       *scoredProg // The lowest-score program with a crash failure.
-	Hang        *scoredProg // The lowest-score program with a hang failure.
+	Panic       *ScoredProg // The lowest-score program with a panic failure.
+	Crash       *ScoredProg // The lowest-score program with a crash failure.
+	Hang        *ScoredProg // The lowest-score program with a hang failure.
 }

-type scoredProg struct {
+type ScoredProg struct {
 	Source string
 	Score  int
 }

-func (a *output) merge(b *output) {
+func (a *Output) merge(b *Output) {
 	a.TrialsDone += b.TrialsDone
 	if a.Next != nil || b.Next != nil {
 		panic("unexpected Next field")
@@ -34,7 +34,7 @@ func (a *output) merge(b *output) {
 	a.Hang = minProg(a.Hang, b.Hang)
 }

-func minProg(a *scoredProg, b *scoredProg) *scoredProg {
+func minProg(a *ScoredProg, b *ScoredProg) *ScoredProg {
 	switch {
 	case a == nil:
 		return b
diff --git a/src/cmd/compile/internal/contraire/worker.go b/src/cmd/compile/internal/contraire/worker.go
index 9bf646820a..8969982204 100644
--- a/src/cmd/compile/internal/contraire/worker.go
+++ b/src/cmd/compile/internal/contraire/worker.go
@@ -20,8 +20,8 @@ import (
 	"syscall"
 )

-// runWorker executes a shard of trials sequentially.
-func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
+// RunWorker executes a shard of trials sequentially.
+func RunWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 	if trials < 1 {
 		return fmt.Errorf("trials %d must be positive", trials)
 	}
@@ -33,7 +33,7 @@ func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 		if err != nil {
 			return fmt.Errorf("couldn't read config %q: %v", cfgPath, err)
 		}
-		c = new(config)
+		c = new(Config)
 		if err := json.Unmarshal(data, c); err != nil {
 			return fmt.Errorf("couldn't decode config %q: %v", cfgPath, err)
 		}
@@ -47,7 +47,7 @@ func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 	defer f.Close()
 	fd := int(f.Fd())

-	write := func(out *output) error {
+	write := func(out *Output) error {
 		data, err := json.Marshal(out)
 		if err != nil {
 			return fmt.Errorf("couldn't encode output: %v", err)
@@ -68,16 +68,16 @@ func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 		sc scorer
 		pr printer
 	)
-	genNext := func() *scoredProg {
+	genNext := func() *ScoredProg {
 		p := g.genProg()
-		return &scoredProg{Source: pr.print(p), Score: sc.score(p)}
+		return &ScoredProg{Source: pr.print(p), Score: sc.score(p)}
 	}
 	next := genNext()

 	// Populate the WAL to signal to the driver that startup is complete.
 	// We are about to enter the main loop and the driver can begin to
 	// monitor the worker's progress.
-	if err := write(&output{Next: next}); err != nil {
+	if err := write(&Output{Next: next}); err != nil {
 		return err
 	}

@@ -86,7 +86,7 @@ func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 		parseErrors int
 		typeErrors  int
 		successes   int
-		minPanic    *scoredProg
+		minPanic    *ScoredProg
 	)
 	for trialsDone < trials {
 		// Type-check the in-hand program.
@@ -110,7 +110,7 @@ func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
 		}

 		// Report progress back to the driver.
-		if err := write(&output{
+		if err := write(&Output{
 			TrialsDone:  trialsDone,
 			Next:        next,
 			ParseErrors: parseErrors,