Source file src/cmd/compile/internal/contraire/worker.go

     1  // Copyright 2026 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build darwin || linux
     6  
     7  package contraire
     8  
     9  import (
    10  	"cmd/compile/internal/syntax"
    11  	"cmd/compile/internal/types2"
    12  	"encoding/json"
    13  	"fmt"
    14  	"go/ast"
    15  	"go/parser"
    16  	"go/token"
    17  	"go/types"
    18  	"os"
    19  	"strings"
    20  	"syscall"
    21  )
    22  
    23  // runWorker executes a shard of trials sequentially.
    24  func runWorker(trials int, cfgPath, outPath, lockPath string, std bool) error {
    25  	if trials < 1 {
    26  		return fmt.Errorf("trials %d must be positive", trials)
    27  	}
    28  
    29  	// Load config if provided; otherwise use the default.
    30  	c := cfg
    31  	if cfgPath != "" {
    32  		data, err := os.ReadFile(cfgPath)
    33  		if err != nil {
    34  			return fmt.Errorf("couldn't read config %q: %v", cfgPath, err)
    35  		}
    36  		c = new(config)
    37  		if err := json.Unmarshal(data, c); err != nil {
    38  			return fmt.Errorf("couldn't decode config %q: %v", cfgPath, err)
    39  		}
    40  	}
    41  
    42  	// The driver must have created the lock file.
    43  	f, err := os.Open(lockPath)
    44  	if err != nil {
    45  		return fmt.Errorf("couldn't open lock file %q: %v", lockPath, err)
    46  	}
    47  	defer f.Close()
    48  	fd := int(f.Fd())
    49  
    50  	write := func(out *output) error {
    51  		data, err := json.Marshal(out)
    52  		if err != nil {
    53  			return fmt.Errorf("couldn't marshal output: %v", err)
    54  		}
    55  		// Hold the lock while writing so the driver never observes a partial write.
    56  		if err := syscall.Flock(fd, syscall.LOCK_EX); err != nil {
    57  			return fmt.Errorf("couldn't acquire lock file %q: %v", lockPath, err)
    58  		}
    59  		if err := os.WriteFile(outPath, data, 0o644); err != nil {
    60  			return fmt.Errorf("couldn't write output to %q: %v", outPath, err)
    61  		}
    62  		if err := syscall.Flock(fd, syscall.LOCK_UN); err != nil {
    63  			return fmt.Errorf("couldn't release lock file %q: %v", lockPath, err)
    64  		}
    65  		return nil
    66  	}
    67  
    68  	g := newGenerator(c)
    69  	var (
    70  		sc scorer
    71  		pr printer
    72  	)
    73  	genNext := func() *scoredProg {
    74  		p := g.genProg()
    75  		return &scoredProg{Source: pr.print(p), Score: sc.score(p)}
    76  	}
    77  	next := genNext()
    78  
    79  	// Populate the WAL to signal to the driver that startup is complete.
    80  	// We are about to enter the main loop and the driver can begin to
    81  	// monitor the worker's progress. The driver should have ensured
    82  	// that outPath doesn't exist yet.
    83  	if err := write(&output{Next: next}); err != nil {
    84  		return err
    85  	}
    86  
    87  	var (
    88  		trialsDone  int
    89  		parseErrors int
    90  		typeErrors  int
    91  		successes   int
    92  		minPanic    *scoredProg
    93  	)
    94  	for trialsDone < trials {
    95  		// Type-check the in-hand program.
    96  		switch check(next.Source, std) {
    97  		case parseErr:
    98  			parseErrors++
    99  		case typeErr:
   100  			typeErrors++
   101  		case success:
   102  			successes++
   103  		case panik:
   104  			minPanic = min(minPanic, next)
   105  		}
   106  		trialsDone++
   107  
   108  		// Prepare the next program if needed.
   109  		if trialsDone < trials {
   110  			next = genNext()
   111  		} else {
   112  			next = nil
   113  		}
   114  
   115  		// Report progress back to the driver.
   116  		if err := write(&output{
   117  			TrialsDone:  trialsDone,
   118  			Next:        next,
   119  			ParseErrors: parseErrors,
   120  			TypeErrors:  typeErrors,
   121  			Successes:   successes,
   122  			Panic:       minPanic,
   123  		}); err != nil {
   124  			return err
   125  		}
   126  	}
   127  	return nil
   128  }
   129  
   130  // A tcOutcome is the result of type-checking a program. The outcomes form a
   131  // partition.
   132  type tcOutcome int
   133  
   134  const (
   135  	parseErr tcOutcome = iota
   136  	typeErr
   137  	success
   138  	panik
   139  )
   140  
   141  // check parses and type-checks src.
   142  func check(src string, std bool) (out tcOutcome) {
   143  	defer func() {
   144  		if r := recover(); r != nil {
   145  			out = panik
   146  		}
   147  	}()
   148  
   149  	if std {
   150  		return checkStd(src)
   151  	}
   152  	return checkGC(src)
   153  }
   154  
   155  // checkStd parses and type-checks src using the standard library's facilities.
   156  func checkStd(src string) tcOutcome {
   157  	fset := token.NewFileSet()
   158  	f, err := parser.ParseFile(fset, "p.go", src, 0)
   159  	if err != nil {
   160  		return parseErr
   161  	}
   162  	conf := types.Config{Error: func(error) {}}
   163  	if _, err := conf.Check("p", fset, []*ast.File{f}, nil); err != nil {
   164  		return typeErr
   165  	}
   166  	return success
   167  }
   168  
   169  // checkGC parses and type-checks src using the compiler's facilities.
   170  func checkGC(src string) tcOutcome {
   171  	f, err := syntax.Parse(syntax.NewFileBase("p.go"), strings.NewReader(src), nil, nil, 0)
   172  	if err != nil {
   173  		return parseErr
   174  	}
   175  	conf := types2.Config{Error: func(error) {}}
   176  	if _, err := conf.Check("p", []*syntax.File{f}, nil); err != nil {
   177  		return typeErr
   178  	}
   179  	return success
   180  }
   181  

View as plain text