]> Cypherpunks.ru repositories - gostls13.git/blob - test/run.go
cmd/compile: fix mknode script
[gostls13.git] / test / run.go
1 // skip
2
3 // Copyright 2012 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 // Run runs tests in the test directory.
8 package main
9
10 import (
11         "bytes"
12         "encoding/json"
13         "errors"
14         "flag"
15         "fmt"
16         "go/build"
17         "go/build/constraint"
18         "hash/fnv"
19         "io"
20         "io/fs"
21         "io/ioutil"
22         "log"
23         "os"
24         "os/exec"
25         "path"
26         "path/filepath"
27         "regexp"
28         "runtime"
29         "sort"
30         "strconv"
31         "strings"
32         "time"
33         "unicode"
34 )
35
36 var (
37         verbose        = flag.Bool("v", false, "verbose. if set, parallelism is set to 1.")
38         keep           = flag.Bool("k", false, "keep. keep temporary directory.")
39         numParallel    = flag.Int("n", runtime.NumCPU(), "number of parallel tests to run")
40         summary        = flag.Bool("summary", false, "show summary of results")
41         allCodegen     = flag.Bool("all_codegen", defaultAllCodeGen(), "run all goos/goarch for codegen")
42         showSkips      = flag.Bool("show_skips", false, "show skipped tests")
43         runSkips       = flag.Bool("run_skips", false, "run skipped tests (ignore skip and build tags)")
44         linkshared     = flag.Bool("linkshared", false, "")
45         updateErrors   = flag.Bool("update_errors", false, "update error messages in test file based on compiler output")
46         runoutputLimit = flag.Int("l", defaultRunOutputLimit(), "number of parallel runoutput tests to run")
47         force          = flag.Bool("f", false, "ignore expected-failure test lists")
48
49         shard  = flag.Int("shard", 0, "shard index to run. Only applicable if -shards is non-zero.")
50         shards = flag.Int("shards", 0, "number of shards. If 0, all tests are run. This is used by the continuous build.")
51 )
52
53 type envVars struct {
54         GOOS         string
55         GOARCH       string
56         GOEXPERIMENT string
57         CGO_ENABLED  string
58 }
59
60 var env = func() (res envVars) {
61         cmd := exec.Command("go", "env", "-json")
62         stdout, err := cmd.StdoutPipe()
63         if err != nil {
64                 log.Fatal("StdoutPipe:", err)
65         }
66         if err := cmd.Start(); err != nil {
67                 log.Fatal("Start:", err)
68         }
69         if err := json.NewDecoder(stdout).Decode(&res); err != nil {
70                 log.Fatal("Decode:", err)
71         }
72         if err := cmd.Wait(); err != nil {
73                 log.Fatal("Wait:", err)
74         }
75         return
76 }()
77
78 // TODO(mdempsky): This will give false negatives if the unified
79 // experiment is enabled by default, but presumably at that point we
80 // won't need to disable tests for it anymore anyway.
81 var unifiedEnabled = strings.Contains(","+env.GOEXPERIMENT+",", ",unified,")
82
83 // defaultAllCodeGen returns the default value of the -all_codegen
84 // flag. By default, we prefer to be fast (returning false), except on
85 // the linux-amd64 builder that's already very fast, so we get more
86 // test coverage on trybots. See https://golang.org/issue/34297.
87 func defaultAllCodeGen() bool {
88         return os.Getenv("GO_BUILDER_NAME") == "linux-amd64"
89 }
90
91 var (
92         goos          = env.GOOS
93         goarch        = env.GOARCH
94         cgoEnabled, _ = strconv.ParseBool(env.CGO_ENABLED)
95
96         // dirs are the directories to look for *.go files in.
97         // TODO(bradfitz): just use all directories?
98         dirs = []string{".", "ken", "chan", "interface", "syntax", "dwarf", "fixedbugs", "codegen", "runtime", "abi", "typeparam", "typeparam/mdempsky"}
99
100         // ratec controls the max number of tests running at a time.
101         ratec chan bool
102
103         // toRun is the channel of tests to run.
104         // It is nil until the first test is started.
105         toRun chan *test
106
107         // rungatec controls the max number of runoutput tests
108         // executed in parallel as they can each consume a lot of memory.
109         rungatec chan bool
110 )
111
112 // maxTests is an upper bound on the total number of tests.
113 // It is used as a channel buffer size to make sure sends don't block.
114 const maxTests = 5000
115
116 func main() {
117         flag.Parse()
118
119         findExecCmd()
120
121         // Disable parallelism if printing or if using a simulator.
122         if *verbose || len(findExecCmd()) > 0 {
123                 *numParallel = 1
124                 *runoutputLimit = 1
125         }
126
127         ratec = make(chan bool, *numParallel)
128         rungatec = make(chan bool, *runoutputLimit)
129
130         var tests []*test
131         if flag.NArg() > 0 {
132                 for _, arg := range flag.Args() {
133                         if arg == "-" || arg == "--" {
134                                 // Permit running:
135                                 // $ go run run.go - env.go
136                                 // $ go run run.go -- env.go
137                                 // $ go run run.go - ./fixedbugs
138                                 // $ go run run.go -- ./fixedbugs
139                                 continue
140                         }
141                         if fi, err := os.Stat(arg); err == nil && fi.IsDir() {
142                                 for _, baseGoFile := range goFiles(arg) {
143                                         tests = append(tests, startTest(arg, baseGoFile))
144                                 }
145                         } else if strings.HasSuffix(arg, ".go") {
146                                 dir, file := filepath.Split(arg)
147                                 tests = append(tests, startTest(dir, file))
148                         } else {
149                                 log.Fatalf("can't yet deal with non-directory and non-go file %q", arg)
150                         }
151                 }
152         } else {
153                 for _, dir := range dirs {
154                         for _, baseGoFile := range goFiles(dir) {
155                                 tests = append(tests, startTest(dir, baseGoFile))
156                         }
157                 }
158         }
159
160         failed := false
161         resCount := map[string]int{}
162         for _, test := range tests {
163                 <-test.donec
164                 status := "ok  "
165                 errStr := ""
166                 if e, isSkip := test.err.(skipError); isSkip {
167                         test.err = nil
168                         errStr = "unexpected skip for " + path.Join(test.dir, test.gofile) + ": " + string(e)
169                         status = "FAIL"
170                 }
171                 if test.err != nil {
172                         errStr = test.err.Error()
173                         if test.expectFail {
174                                 errStr += " (expected)"
175                         } else {
176                                 status = "FAIL"
177                         }
178                 } else if test.expectFail {
179                         status = "FAIL"
180                         errStr = "unexpected success"
181                 }
182                 if status == "FAIL" {
183                         failed = true
184                 }
185                 resCount[status]++
186                 dt := fmt.Sprintf("%.3fs", test.dt.Seconds())
187                 if status == "FAIL" {
188                         fmt.Printf("# go run run.go -- %s\n%s\nFAIL\t%s\t%s\n",
189                                 path.Join(test.dir, test.gofile),
190                                 errStr, test.goFileName(), dt)
191                         continue
192                 }
193                 if !*verbose {
194                         continue
195                 }
196                 fmt.Printf("%s\t%s\t%s\n", status, test.goFileName(), dt)
197         }
198
199         if *summary {
200                 for k, v := range resCount {
201                         fmt.Printf("%5d %s\n", v, k)
202                 }
203         }
204
205         if failed {
206                 os.Exit(1)
207         }
208 }
209
210 // goTool reports the path of the go tool to use to run the tests.
211 // If possible, use the same Go used to run run.go, otherwise
212 // fallback to the go version found in the PATH.
213 func goTool() string {
214         var exeSuffix string
215         if runtime.GOOS == "windows" {
216                 exeSuffix = ".exe"
217         }
218         path := filepath.Join(runtime.GOROOT(), "bin", "go"+exeSuffix)
219         if _, err := os.Stat(path); err == nil {
220                 return path
221         }
222         // Just run "go" from PATH
223         return "go"
224 }
225
226 func shardMatch(name string) bool {
227         if *shards == 0 {
228                 return true
229         }
230         h := fnv.New32()
231         io.WriteString(h, name)
232         return int(h.Sum32()%uint32(*shards)) == *shard
233 }
234
235 func goFiles(dir string) []string {
236         f, err := os.Open(dir)
237         if err != nil {
238                 log.Fatal(err)
239         }
240         dirnames, err := f.Readdirnames(-1)
241         f.Close()
242         if err != nil {
243                 log.Fatal(err)
244         }
245         names := []string{}
246         for _, name := range dirnames {
247                 if !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && shardMatch(name) {
248                         names = append(names, name)
249                 }
250         }
251         sort.Strings(names)
252         return names
253 }
254
255 type runCmd func(...string) ([]byte, error)
256
257 func compileFile(runcmd runCmd, longname string, flags []string) (out []byte, err error) {
258         cmd := []string{goTool(), "tool", "compile", "-e", "-p=p"}
259         cmd = append(cmd, flags...)
260         if *linkshared {
261                 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
262         }
263         cmd = append(cmd, longname)
264         return runcmd(cmd...)
265 }
266
267 func compileInDir(runcmd runCmd, dir string, flags []string, pkgname string, names ...string) (out []byte, err error) {
268         cmd := []string{goTool(), "tool", "compile", "-e", "-D", "test", "-I", "."}
269         if pkgname == "main" {
270                 cmd = append(cmd, "-p=main")
271         } else {
272                 pkgname = path.Join("test", strings.TrimSuffix(names[0], ".go"))
273                 cmd = append(cmd, "-o", pkgname+".a", "-p", pkgname)
274         }
275         cmd = append(cmd, flags...)
276         if *linkshared {
277                 cmd = append(cmd, "-dynlink", "-installsuffix=dynlink")
278         }
279         for _, name := range names {
280                 cmd = append(cmd, filepath.Join(dir, name))
281         }
282         return runcmd(cmd...)
283 }
284
285 func linkFile(runcmd runCmd, goname string, ldflags []string) (err error) {
286         pfile := strings.Replace(goname, ".go", ".o", -1)
287         cmd := []string{goTool(), "tool", "link", "-w", "-o", "a.exe", "-L", "."}
288         if *linkshared {
289                 cmd = append(cmd, "-linkshared", "-installsuffix=dynlink")
290         }
291         if ldflags != nil {
292                 cmd = append(cmd, ldflags...)
293         }
294         cmd = append(cmd, pfile)
295         _, err = runcmd(cmd...)
296         return
297 }
298
299 // skipError describes why a test was skipped.
300 type skipError string
301
302 func (s skipError) Error() string { return string(s) }
303
304 // test holds the state of a test.
305 type test struct {
306         dir, gofile string
307         donec       chan bool // closed when done
308         dt          time.Duration
309
310         src string
311
312         tempDir string
313         err     error
314
315         // expectFail indicates whether the (overall) test recipe is
316         // expected to fail under the current test configuration (e.g.,
317         // GOEXPERIMENT=unified).
318         expectFail bool
319 }
320
321 // initExpectFail initializes t.expectFail based on the build+test
322 // configuration.
323 func (t *test) initExpectFail() {
324         if *force {
325                 return
326         }
327
328         failureSets := []map[string]bool{types2Failures}
329
330         // Note: gccgo supports more 32-bit architectures than this, but
331         // hopefully the 32-bit failures are fixed before this matters.
332         switch goarch {
333         case "386", "arm", "mips", "mipsle":
334                 failureSets = append(failureSets, types2Failures32Bit)
335         }
336
337         if unifiedEnabled {
338                 failureSets = append(failureSets, unifiedFailures)
339         } else {
340                 failureSets = append(failureSets, go118Failures)
341         }
342
343         filename := strings.Replace(t.goFileName(), "\\", "/", -1) // goFileName() uses \ on Windows
344
345         for _, set := range failureSets {
346                 if set[filename] {
347                         t.expectFail = true
348                         return
349                 }
350         }
351 }
352
353 func startTest(dir, gofile string) *test {
354         t := &test{
355                 dir:    dir,
356                 gofile: gofile,
357                 donec:  make(chan bool, 1),
358         }
359         if toRun == nil {
360                 toRun = make(chan *test, maxTests)
361                 go runTests()
362         }
363         select {
364         case toRun <- t:
365         default:
366                 panic("toRun buffer size (maxTests) is too small")
367         }
368         return t
369 }
370
371 // runTests runs tests in parallel, but respecting the order they
372 // were enqueued on the toRun channel.
373 func runTests() {
374         for {
375                 ratec <- true
376                 t := <-toRun
377                 go func() {
378                         t.run()
379                         <-ratec
380                 }()
381         }
382 }
383
384 var cwd, _ = os.Getwd()
385
386 func (t *test) goFileName() string {
387         return filepath.Join(t.dir, t.gofile)
388 }
389
390 func (t *test) goDirName() string {
391         return filepath.Join(t.dir, strings.Replace(t.gofile, ".go", ".dir", -1))
392 }
393
394 func goDirFiles(longdir string) (filter []os.FileInfo, err error) {
395         files, dirErr := ioutil.ReadDir(longdir)
396         if dirErr != nil {
397                 return nil, dirErr
398         }
399         for _, gofile := range files {
400                 if filepath.Ext(gofile.Name()) == ".go" {
401                         filter = append(filter, gofile)
402                 }
403         }
404         return
405 }
406
407 var packageRE = regexp.MustCompile(`(?m)^package ([\p{Lu}\p{Ll}\w]+)`)
408
409 func getPackageNameFromSource(fn string) (string, error) {
410         data, err := ioutil.ReadFile(fn)
411         if err != nil {
412                 return "", err
413         }
414         pkgname := packageRE.FindStringSubmatch(string(data))
415         if pkgname == nil {
416                 return "", fmt.Errorf("cannot find package name in %s", fn)
417         }
418         return pkgname[1], nil
419 }
420
421 type goDirPkg struct {
422         name  string
423         files []string
424 }
425
426 // If singlefilepkgs is set, each file is considered a separate package
427 // even if the package names are the same.
428 func goDirPackages(longdir string, singlefilepkgs bool) ([]*goDirPkg, error) {
429         files, err := goDirFiles(longdir)
430         if err != nil {
431                 return nil, err
432         }
433         var pkgs []*goDirPkg
434         m := make(map[string]*goDirPkg)
435         for _, file := range files {
436                 name := file.Name()
437                 pkgname, err := getPackageNameFromSource(filepath.Join(longdir, name))
438                 if err != nil {
439                         log.Fatal(err)
440                 }
441                 p, ok := m[pkgname]
442                 if singlefilepkgs || !ok {
443                         p = &goDirPkg{name: pkgname}
444                         pkgs = append(pkgs, p)
445                         m[pkgname] = p
446                 }
447                 p.files = append(p.files, name)
448         }
449         return pkgs, nil
450 }
451
452 type context struct {
453         GOOS       string
454         GOARCH     string
455         cgoEnabled bool
456         noOptEnv   bool
457 }
458
459 // shouldTest looks for build tags in a source file and returns
460 // whether the file should be used according to the tags.
461 func shouldTest(src string, goos, goarch string) (ok bool, whyNot string) {
462         if *runSkips {
463                 return true, ""
464         }
465         for _, line := range strings.Split(src, "\n") {
466                 if strings.HasPrefix(line, "package ") {
467                         break
468                 }
469
470                 if expr, err := constraint.Parse(line); err == nil {
471                         gcFlags := os.Getenv("GO_GCFLAGS")
472                         ctxt := &context{
473                                 GOOS:       goos,
474                                 GOARCH:     goarch,
475                                 cgoEnabled: cgoEnabled,
476                                 noOptEnv:   strings.Contains(gcFlags, "-N") || strings.Contains(gcFlags, "-l"),
477                         }
478
479                         if !expr.Eval(ctxt.match) {
480                                 return false, line
481                         }
482                 }
483         }
484         return true, ""
485 }
486
487 func (ctxt *context) match(name string) bool {
488         if name == "" {
489                 return false
490         }
491
492         // Tags must be letters, digits, underscores or dots.
493         // Unlike in Go identifiers, all digits are fine (e.g., "386").
494         for _, c := range name {
495                 if !unicode.IsLetter(c) && !unicode.IsDigit(c) && c != '_' && c != '.' {
496                         return false
497                 }
498         }
499
500         if strings.HasPrefix(name, "goexperiment.") {
501                 for _, tag := range build.Default.ToolTags {
502                         if tag == name {
503                                 return true
504                         }
505                 }
506                 return false
507         }
508
509         if name == "cgo" && ctxt.cgoEnabled {
510                 return true
511         }
512
513         if name == ctxt.GOOS || name == ctxt.GOARCH || name == "gc" {
514                 return true
515         }
516
517         if ctxt.noOptEnv && name == "gcflags_noopt" {
518                 return true
519         }
520
521         if name == "test_run" {
522                 return true
523         }
524
525         return false
526 }
527
528 func init() { checkShouldTest() }
529
530 // goGcflags returns the -gcflags argument to use with go build / go run.
531 // This must match the flags used for building the standard library,
532 // or else the commands will rebuild any needed packages (like runtime)
533 // over and over.
534 func (t *test) goGcflags() string {
535         return "-gcflags=all=" + os.Getenv("GO_GCFLAGS")
536 }
537
538 func (t *test) goGcflagsIsEmpty() bool {
539         return "" == os.Getenv("GO_GCFLAGS")
540 }
541
542 var errTimeout = errors.New("command exceeded time limit")
543
544 // run runs a test.
545 func (t *test) run() {
546         start := time.Now()
547         defer func() {
548                 t.dt = time.Since(start)
549                 close(t.donec)
550         }()
551
552         srcBytes, err := ioutil.ReadFile(t.goFileName())
553         if err != nil {
554                 t.err = err
555                 return
556         }
557         t.src = string(srcBytes)
558         if t.src[0] == '\n' {
559                 t.err = skipError("starts with newline")
560                 return
561         }
562
563         // Execution recipe stops at first blank line.
564         action, _, ok := strings.Cut(t.src, "\n\n")
565         if !ok {
566                 t.err = fmt.Errorf("double newline ending execution recipe not found in %s", t.goFileName())
567                 return
568         }
569         if firstLine, rest, ok := strings.Cut(action, "\n"); ok && strings.Contains(firstLine, "+build") {
570                 // skip first line
571                 action = rest
572         }
573         action = strings.TrimPrefix(action, "//")
574
575         // Check for build constraints only up to the actual code.
576         header, _, ok := strings.Cut(t.src, "\npackage")
577         if !ok {
578                 header = action // some files are intentionally malformed
579         }
580         if ok, why := shouldTest(header, goos, goarch); !ok {
581                 if *showSkips {
582                         fmt.Printf("%-20s %-20s: %s\n", "skip", t.goFileName(), why)
583                 }
584                 return
585         }
586
587         var args, flags, runenv []string
588         var tim int
589         wantError := false
590         wantAuto := false
591         singlefilepkgs := false
592         f, err := splitQuoted(action)
593         if err != nil {
594                 t.err = fmt.Errorf("invalid test recipe: %v", err)
595                 return
596         }
597         if len(f) > 0 {
598                 action = f[0]
599                 args = f[1:]
600         }
601
602         // TODO: Clean up/simplify this switch statement.
603         switch action {
604         case "compile", "compiledir", "build", "builddir", "buildrundir", "run", "buildrun", "runoutput", "rundir", "runindir", "asmcheck":
605                 // nothing to do
606         case "errorcheckandrundir":
607                 wantError = false // should be no error if also will run
608         case "errorcheckwithauto":
609                 action = "errorcheck"
610                 wantAuto = true
611                 wantError = true
612         case "errorcheck", "errorcheckdir", "errorcheckoutput":
613                 wantError = true
614         case "skip":
615                 if *runSkips {
616                         break
617                 }
618                 return
619         default:
620                 t.err = skipError("skipped; unknown pattern: " + action)
621                 return
622         }
623
624         goexp := env.GOEXPERIMENT
625
626         // collect flags
627         for len(args) > 0 && strings.HasPrefix(args[0], "-") {
628                 switch args[0] {
629                 case "-1":
630                         wantError = true
631                 case "-0":
632                         wantError = false
633                 case "-s":
634                         singlefilepkgs = true
635                 case "-t": // timeout in seconds
636                         args = args[1:]
637                         var err error
638                         tim, err = strconv.Atoi(args[0])
639                         if err != nil {
640                                 t.err = fmt.Errorf("need number of seconds for -t timeout, got %s instead", args[0])
641                         }
642                         if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
643                                 timeoutScale, err := strconv.Atoi(s)
644                                 if err != nil {
645                                         log.Fatalf("failed to parse $GO_TEST_TIMEOUT_SCALE = %q as integer: %v", s, err)
646                                 }
647                                 tim *= timeoutScale
648                         }
649                 case "-goexperiment": // set GOEXPERIMENT environment
650                         args = args[1:]
651                         if goexp != "" {
652                                 goexp += ","
653                         }
654                         goexp += args[0]
655                         runenv = append(runenv, "GOEXPERIMENT="+goexp)
656
657                 default:
658                         flags = append(flags, args[0])
659                 }
660                 args = args[1:]
661         }
662         if action == "errorcheck" {
663                 found := false
664                 for i, f := range flags {
665                         if strings.HasPrefix(f, "-d=") {
666                                 flags[i] = f + ",ssa/check/on"
667                                 found = true
668                                 break
669                         }
670                 }
671                 if !found {
672                         flags = append(flags, "-d=ssa/check/on")
673                 }
674         }
675
676         t.initExpectFail()
677         t.makeTempDir()
678         if !*keep {
679                 defer os.RemoveAll(t.tempDir)
680         }
681
682         err = ioutil.WriteFile(filepath.Join(t.tempDir, t.gofile), srcBytes, 0644)
683         if err != nil {
684                 log.Fatal(err)
685         }
686
687         // A few tests (of things like the environment) require these to be set.
688         if os.Getenv("GOOS") == "" {
689                 os.Setenv("GOOS", runtime.GOOS)
690         }
691         if os.Getenv("GOARCH") == "" {
692                 os.Setenv("GOARCH", runtime.GOARCH)
693         }
694
695         var (
696                 runInDir        = t.tempDir
697                 tempDirIsGOPATH = false
698         )
699         runcmd := func(args ...string) ([]byte, error) {
700                 cmd := exec.Command(args[0], args[1:]...)
701                 var buf bytes.Buffer
702                 cmd.Stdout = &buf
703                 cmd.Stderr = &buf
704                 cmd.Env = append(os.Environ(), "GOENV=off", "GOFLAGS=")
705                 if runInDir != "" {
706                         cmd.Dir = runInDir
707                         // Set PWD to match Dir to speed up os.Getwd in the child process.
708                         cmd.Env = append(cmd.Env, "PWD="+cmd.Dir)
709                 }
710                 if tempDirIsGOPATH {
711                         cmd.Env = append(cmd.Env, "GOPATH="+t.tempDir)
712                 }
713                 cmd.Env = append(cmd.Env, runenv...)
714
715                 var err error
716
717                 if tim != 0 {
718                         err = cmd.Start()
719                         // This command-timeout code adapted from cmd/go/test.go
720                         // Note: the Go command uses a more sophisticated timeout
721                         // strategy, first sending SIGQUIT (if appropriate for the
722                         // OS in question) to try to trigger a stack trace, then
723                         // finally much later SIGKILL. If timeouts prove to be a
724                         // common problem here, it would be worth porting over
725                         // that code as well. See https://do.dev/issue/50973
726                         // for more discussion.
727                         if err == nil {
728                                 tick := time.NewTimer(time.Duration(tim) * time.Second)
729                                 done := make(chan error)
730                                 go func() {
731                                         done <- cmd.Wait()
732                                 }()
733                                 select {
734                                 case err = <-done:
735                                         // ok
736                                 case <-tick.C:
737                                         cmd.Process.Signal(os.Interrupt)
738                                         time.Sleep(1 * time.Second)
739                                         cmd.Process.Kill()
740                                         <-done
741                                         err = errTimeout
742                                 }
743                                 tick.Stop()
744                         }
745                 } else {
746                         err = cmd.Run()
747                 }
748                 if err != nil && err != errTimeout {
749                         err = fmt.Errorf("%s\n%s", err, buf.Bytes())
750                 }
751                 return buf.Bytes(), err
752         }
753
754         long := filepath.Join(cwd, t.goFileName())
755         switch action {
756         default:
757                 t.err = fmt.Errorf("unimplemented action %q", action)
758
759         case "asmcheck":
760                 // Compile Go file and match the generated assembly
761                 // against a set of regexps in comments.
762                 ops := t.wantedAsmOpcodes(long)
763                 self := runtime.GOOS + "/" + runtime.GOARCH
764                 for _, env := range ops.Envs() {
765                         // Only run checks relevant to the current GOOS/GOARCH,
766                         // to avoid triggering a cross-compile of the runtime.
767                         if string(env) != self && !strings.HasPrefix(string(env), self+"/") && !*allCodegen {
768                                 continue
769                         }
770                         // -S=2 forces outermost line numbers when disassembling inlined code.
771                         cmdline := []string{"build", "-gcflags", "-S=2"}
772
773                         // Append flags, but don't override -gcflags=-S=2; add to it instead.
774                         for i := 0; i < len(flags); i++ {
775                                 flag := flags[i]
776                                 switch {
777                                 case strings.HasPrefix(flag, "-gcflags="):
778                                         cmdline[2] += " " + strings.TrimPrefix(flag, "-gcflags=")
779                                 case strings.HasPrefix(flag, "--gcflags="):
780                                         cmdline[2] += " " + strings.TrimPrefix(flag, "--gcflags=")
781                                 case flag == "-gcflags", flag == "--gcflags":
782                                         i++
783                                         if i < len(flags) {
784                                                 cmdline[2] += " " + flags[i]
785                                         }
786                                 default:
787                                         cmdline = append(cmdline, flag)
788                                 }
789                         }
790
791                         cmdline = append(cmdline, long)
792                         cmd := exec.Command(goTool(), cmdline...)
793                         cmd.Env = append(os.Environ(), env.Environ()...)
794                         if len(flags) > 0 && flags[0] == "-race" {
795                                 cmd.Env = append(cmd.Env, "CGO_ENABLED=1")
796                         }
797
798                         var buf bytes.Buffer
799                         cmd.Stdout, cmd.Stderr = &buf, &buf
800                         if err := cmd.Run(); err != nil {
801                                 fmt.Println(env, "\n", cmd.Stderr)
802                                 t.err = err
803                                 return
804                         }
805
806                         t.err = t.asmCheck(buf.String(), long, env, ops[env])
807                         if t.err != nil {
808                                 return
809                         }
810                 }
811                 return
812
813         case "errorcheck":
814                 // Compile Go file.
815                 // Fail if wantError is true and compilation was successful and vice versa.
816                 // Match errors produced by gc against errors in comments.
817                 // TODO(gri) remove need for -C (disable printing of columns in error messages)
818                 cmdline := []string{goTool(), "tool", "compile", "-p=p", "-d=panic", "-C", "-e", "-o", "a.o"}
819                 // No need to add -dynlink even if linkshared if we're just checking for errors...
820                 cmdline = append(cmdline, flags...)
821                 cmdline = append(cmdline, long)
822                 out, err := runcmd(cmdline...)
823                 if wantError {
824                         if err == nil {
825                                 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
826                                 return
827                         }
828                         if err == errTimeout {
829                                 t.err = fmt.Errorf("compilation timed out")
830                                 return
831                         }
832                 } else {
833                         if err != nil {
834                                 t.err = err
835                                 return
836                         }
837                 }
838                 if *updateErrors {
839                         t.updateErrors(string(out), long)
840                 }
841                 t.err = t.errorCheck(string(out), wantAuto, long, t.gofile)
842
843         case "compile":
844                 // Compile Go file.
845                 _, t.err = compileFile(runcmd, long, flags)
846
847         case "compiledir":
848                 // Compile all files in the directory as packages in lexicographic order.
849                 longdir := filepath.Join(cwd, t.goDirName())
850                 pkgs, err := goDirPackages(longdir, singlefilepkgs)
851                 if err != nil {
852                         t.err = err
853                         return
854                 }
855                 for _, pkg := range pkgs {
856                         _, t.err = compileInDir(runcmd, longdir, flags, pkg.name, pkg.files...)
857                         if t.err != nil {
858                                 return
859                         }
860                 }
861
862         case "errorcheckdir", "errorcheckandrundir":
863                 flags = append(flags, "-d=panic")
864                 // Compile and errorCheck all files in the directory as packages in lexicographic order.
865                 // If errorcheckdir and wantError, compilation of the last package must fail.
866                 // If errorcheckandrundir and wantError, compilation of the package prior the last must fail.
867                 longdir := filepath.Join(cwd, t.goDirName())
868                 pkgs, err := goDirPackages(longdir, singlefilepkgs)
869                 if err != nil {
870                         t.err = err
871                         return
872                 }
873                 errPkg := len(pkgs) - 1
874                 if wantError && action == "errorcheckandrundir" {
875                         // The last pkg should compiled successfully and will be run in next case.
876                         // Preceding pkg must return an error from compileInDir.
877                         errPkg--
878                 }
879                 for i, pkg := range pkgs {
880                         out, err := compileInDir(runcmd, longdir, flags, pkg.name, pkg.files...)
881                         if i == errPkg {
882                                 if wantError && err == nil {
883                                         t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
884                                         return
885                                 } else if !wantError && err != nil {
886                                         t.err = err
887                                         return
888                                 }
889                         } else if err != nil {
890                                 t.err = err
891                                 return
892                         }
893                         var fullshort []string
894                         for _, name := range pkg.files {
895                                 fullshort = append(fullshort, filepath.Join(longdir, name), name)
896                         }
897                         t.err = t.errorCheck(string(out), wantAuto, fullshort...)
898                         if t.err != nil {
899                                 break
900                         }
901                 }
902                 if action == "errorcheckdir" {
903                         return
904                 }
905                 fallthrough
906
907         case "rundir":
908                 // Compile all files in the directory as packages in lexicographic order.
909                 // In case of errorcheckandrundir, ignore failed compilation of the package before the last.
910                 // Link as if the last file is the main package, run it.
911                 // Verify the expected output.
912                 longdir := filepath.Join(cwd, t.goDirName())
913                 pkgs, err := goDirPackages(longdir, singlefilepkgs)
914                 if err != nil {
915                         t.err = err
916                         return
917                 }
918                 // Split flags into gcflags and ldflags
919                 ldflags := []string{}
920                 for i, fl := range flags {
921                         if fl == "-ldflags" {
922                                 ldflags = flags[i+1:]
923                                 flags = flags[0:i]
924                                 break
925                         }
926                 }
927
928                 for i, pkg := range pkgs {
929                         _, err := compileInDir(runcmd, longdir, flags, pkg.name, pkg.files...)
930                         // Allow this package compilation fail based on conditions below;
931                         // its errors were checked in previous case.
932                         if err != nil && !(wantError && action == "errorcheckandrundir" && i == len(pkgs)-2) {
933                                 t.err = err
934                                 return
935                         }
936                         if i == len(pkgs)-1 {
937                                 err = linkFile(runcmd, pkg.files[0], ldflags)
938                                 if err != nil {
939                                         t.err = err
940                                         return
941                                 }
942                                 var cmd []string
943                                 cmd = append(cmd, findExecCmd()...)
944                                 cmd = append(cmd, filepath.Join(t.tempDir, "a.exe"))
945                                 cmd = append(cmd, args...)
946                                 out, err := runcmd(cmd...)
947                                 if err != nil {
948                                         t.err = err
949                                         return
950                                 }
951                                 t.checkExpectedOutput(out)
952                         }
953                 }
954
955         case "runindir":
956                 // Make a shallow copy of t.goDirName() in its own module and GOPATH, and
957                 // run "go run ." in it. The module path (and hence import path prefix) of
958                 // the copy is equal to the basename of the source directory.
959                 //
960                 // It's used when test a requires a full 'go build' in order to compile
961                 // the sources, such as when importing multiple packages (issue29612.dir)
962                 // or compiling a package containing assembly files (see issue15609.dir),
963                 // but still needs to be run to verify the expected output.
964                 tempDirIsGOPATH = true
965                 srcDir := t.goDirName()
966                 modName := filepath.Base(srcDir)
967                 gopathSrcDir := filepath.Join(t.tempDir, "src", modName)
968                 runInDir = gopathSrcDir
969
970                 if err := overlayDir(gopathSrcDir, srcDir); err != nil {
971                         t.err = err
972                         return
973                 }
974
975                 modFile := fmt.Sprintf("module %s\ngo 1.14\n", modName)
976                 if err := ioutil.WriteFile(filepath.Join(gopathSrcDir, "go.mod"), []byte(modFile), 0666); err != nil {
977                         t.err = err
978                         return
979                 }
980
981                 cmd := []string{goTool(), "run", t.goGcflags()}
982                 if *linkshared {
983                         cmd = append(cmd, "-linkshared")
984                 }
985                 cmd = append(cmd, flags...)
986                 cmd = append(cmd, ".")
987                 out, err := runcmd(cmd...)
988                 if err != nil {
989                         t.err = err
990                         return
991                 }
992                 t.checkExpectedOutput(out)
993
994         case "build":
995                 // Build Go file.
996                 cmd := []string{goTool(), "build", t.goGcflags()}
997                 cmd = append(cmd, flags...)
998                 cmd = append(cmd, "-o", "a.exe", long)
999                 _, err := runcmd(cmd...)
1000                 if err != nil {
1001                         t.err = err
1002                 }
1003
1004         case "builddir", "buildrundir":
1005                 // Build an executable from all the .go and .s files in a subdirectory.
1006                 // Run it and verify its output in the buildrundir case.
1007                 longdir := filepath.Join(cwd, t.goDirName())
1008                 files, dirErr := ioutil.ReadDir(longdir)
1009                 if dirErr != nil {
1010                         t.err = dirErr
1011                         break
1012                 }
1013                 var gos []string
1014                 var asms []string
1015                 for _, file := range files {
1016                         switch filepath.Ext(file.Name()) {
1017                         case ".go":
1018                                 gos = append(gos, filepath.Join(longdir, file.Name()))
1019                         case ".s":
1020                                 asms = append(asms, filepath.Join(longdir, file.Name()))
1021                         }
1022
1023                 }
1024                 if len(asms) > 0 {
1025                         emptyHdrFile := filepath.Join(t.tempDir, "go_asm.h")
1026                         if err := ioutil.WriteFile(emptyHdrFile, nil, 0666); err != nil {
1027                                 t.err = fmt.Errorf("write empty go_asm.h: %s", err)
1028                                 return
1029                         }
1030                         cmd := []string{goTool(), "tool", "asm", "-p=main", "-gensymabis", "-o", "symabis"}
1031                         cmd = append(cmd, asms...)
1032                         _, err = runcmd(cmd...)
1033                         if err != nil {
1034                                 t.err = err
1035                                 break
1036                         }
1037                 }
1038                 var objs []string
1039                 cmd := []string{goTool(), "tool", "compile", "-p=main", "-e", "-D", ".", "-I", ".", "-o", "go.o"}
1040                 if len(asms) > 0 {
1041                         cmd = append(cmd, "-asmhdr", "go_asm.h", "-symabis", "symabis")
1042                 }
1043                 cmd = append(cmd, gos...)
1044                 _, err := runcmd(cmd...)
1045                 if err != nil {
1046                         t.err = err
1047                         break
1048                 }
1049                 objs = append(objs, "go.o")
1050                 if len(asms) > 0 {
1051                         cmd = []string{goTool(), "tool", "asm", "-p=main", "-e", "-I", ".", "-o", "asm.o"}
1052                         cmd = append(cmd, asms...)
1053                         _, err = runcmd(cmd...)
1054                         if err != nil {
1055                                 t.err = err
1056                                 break
1057                         }
1058                         objs = append(objs, "asm.o")
1059                 }
1060                 cmd = []string{goTool(), "tool", "pack", "c", "all.a"}
1061                 cmd = append(cmd, objs...)
1062                 _, err = runcmd(cmd...)
1063                 if err != nil {
1064                         t.err = err
1065                         break
1066                 }
1067                 cmd = []string{goTool(), "tool", "link", "-o", "a.exe", "all.a"}
1068                 _, err = runcmd(cmd...)
1069                 if err != nil {
1070                         t.err = err
1071                         break
1072                 }
1073                 if action == "buildrundir" {
1074                         cmd = append(findExecCmd(), filepath.Join(t.tempDir, "a.exe"))
1075                         out, err := runcmd(cmd...)
1076                         if err != nil {
1077                                 t.err = err
1078                                 break
1079                         }
1080                         t.checkExpectedOutput(out)
1081                 }
1082
1083         case "buildrun":
1084                 // Build an executable from Go file, then run it, verify its output.
1085                 // Useful for timeout tests where failure mode is infinite loop.
1086                 // TODO: not supported on NaCl
1087                 cmd := []string{goTool(), "build", t.goGcflags(), "-o", "a.exe"}
1088                 if *linkshared {
1089                         cmd = append(cmd, "-linkshared")
1090                 }
1091                 longdirgofile := filepath.Join(filepath.Join(cwd, t.dir), t.gofile)
1092                 cmd = append(cmd, flags...)
1093                 cmd = append(cmd, longdirgofile)
1094                 _, err := runcmd(cmd...)
1095                 if err != nil {
1096                         t.err = err
1097                         return
1098                 }
1099                 cmd = []string{"./a.exe"}
1100                 out, err := runcmd(append(cmd, args...)...)
1101                 if err != nil {
1102                         t.err = err
1103                         return
1104                 }
1105
1106                 t.checkExpectedOutput(out)
1107
1108         case "run":
1109                 // Run Go file if no special go command flags are provided;
1110                 // otherwise build an executable and run it.
1111                 // Verify the output.
1112                 runInDir = ""
1113                 var out []byte
1114                 var err error
1115                 if len(flags)+len(args) == 0 && t.goGcflagsIsEmpty() && !*linkshared && goarch == runtime.GOARCH && goos == runtime.GOOS && goexp == env.GOEXPERIMENT {
1116                         // If we're not using special go command flags,
1117                         // skip all the go command machinery.
1118                         // This avoids any time the go command would
1119                         // spend checking whether, for example, the installed
1120                         // package runtime is up to date.
1121                         // Because we run lots of trivial test programs,
1122                         // the time adds up.
1123                         pkg := filepath.Join(t.tempDir, "pkg.a")
1124                         if _, err := runcmd(goTool(), "tool", "compile", "-p=main", "-o", pkg, t.goFileName()); err != nil {
1125                                 t.err = err
1126                                 return
1127                         }
1128                         exe := filepath.Join(t.tempDir, "test.exe")
1129                         cmd := []string{goTool(), "tool", "link", "-s", "-w"}
1130                         cmd = append(cmd, "-o", exe, pkg)
1131                         if _, err := runcmd(cmd...); err != nil {
1132                                 t.err = err
1133                                 return
1134                         }
1135                         out, err = runcmd(append([]string{exe}, args...)...)
1136                 } else {
1137                         cmd := []string{goTool(), "run", t.goGcflags()}
1138                         if *linkshared {
1139                                 cmd = append(cmd, "-linkshared")
1140                         }
1141                         cmd = append(cmd, flags...)
1142                         cmd = append(cmd, t.goFileName())
1143                         out, err = runcmd(append(cmd, args...)...)
1144                 }
1145                 if err != nil {
1146                         t.err = err
1147                         return
1148                 }
1149                 t.checkExpectedOutput(out)
1150
1151         case "runoutput":
1152                 // Run Go file and write its output into temporary Go file.
1153                 // Run generated Go file and verify its output.
1154                 rungatec <- true
1155                 defer func() {
1156                         <-rungatec
1157                 }()
1158                 runInDir = ""
1159                 cmd := []string{goTool(), "run", t.goGcflags()}
1160                 if *linkshared {
1161                         cmd = append(cmd, "-linkshared")
1162                 }
1163                 cmd = append(cmd, t.goFileName())
1164                 out, err := runcmd(append(cmd, args...)...)
1165                 if err != nil {
1166                         t.err = err
1167                         return
1168                 }
1169                 tfile := filepath.Join(t.tempDir, "tmp__.go")
1170                 if err := ioutil.WriteFile(tfile, out, 0666); err != nil {
1171                         t.err = fmt.Errorf("write tempfile:%s", err)
1172                         return
1173                 }
1174                 cmd = []string{goTool(), "run", t.goGcflags()}
1175                 if *linkshared {
1176                         cmd = append(cmd, "-linkshared")
1177                 }
1178                 cmd = append(cmd, tfile)
1179                 out, err = runcmd(cmd...)
1180                 if err != nil {
1181                         t.err = err
1182                         return
1183                 }
1184                 t.checkExpectedOutput(out)
1185
1186         case "errorcheckoutput":
1187                 // Run Go file and write its output into temporary Go file.
1188                 // Compile and errorCheck generated Go file.
1189                 runInDir = ""
1190                 cmd := []string{goTool(), "run", t.goGcflags()}
1191                 if *linkshared {
1192                         cmd = append(cmd, "-linkshared")
1193                 }
1194                 cmd = append(cmd, t.goFileName())
1195                 out, err := runcmd(append(cmd, args...)...)
1196                 if err != nil {
1197                         t.err = err
1198                         return
1199                 }
1200                 tfile := filepath.Join(t.tempDir, "tmp__.go")
1201                 err = ioutil.WriteFile(tfile, out, 0666)
1202                 if err != nil {
1203                         t.err = fmt.Errorf("write tempfile:%s", err)
1204                         return
1205                 }
1206                 cmdline := []string{goTool(), "tool", "compile", "-p=p", "-d=panic", "-e", "-o", "a.o"}
1207                 cmdline = append(cmdline, flags...)
1208                 cmdline = append(cmdline, tfile)
1209                 out, err = runcmd(cmdline...)
1210                 if wantError {
1211                         if err == nil {
1212                                 t.err = fmt.Errorf("compilation succeeded unexpectedly\n%s", out)
1213                                 return
1214                         }
1215                 } else {
1216                         if err != nil {
1217                                 t.err = err
1218                                 return
1219                         }
1220                 }
1221                 t.err = t.errorCheck(string(out), false, tfile, "tmp__.go")
1222                 return
1223         }
1224 }
1225
1226 var execCmd []string
1227
1228 func findExecCmd() []string {
1229         if execCmd != nil {
1230                 return execCmd
1231         }
1232         execCmd = []string{} // avoid work the second time
1233         if goos == runtime.GOOS && goarch == runtime.GOARCH {
1234                 return execCmd
1235         }
1236         path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch))
1237         if err == nil {
1238                 execCmd = []string{path}
1239         }
1240         return execCmd
1241 }
1242
1243 func (t *test) String() string {
1244         return filepath.Join(t.dir, t.gofile)
1245 }
1246
1247 func (t *test) makeTempDir() {
1248         var err error
1249         t.tempDir, err = ioutil.TempDir("", "")
1250         if err != nil {
1251                 log.Fatal(err)
1252         }
1253         if *keep {
1254                 log.Printf("Temporary directory is %s", t.tempDir)
1255         }
1256         err = os.Mkdir(filepath.Join(t.tempDir, "test"), 0o755)
1257         if err != nil {
1258                 log.Fatal(err)
1259         }
1260 }
1261
1262 // checkExpectedOutput compares the output from compiling and/or running with the contents
1263 // of the corresponding reference output file, if any (replace ".go" with ".out").
1264 // If they don't match, fail with an informative message.
1265 func (t *test) checkExpectedOutput(gotBytes []byte) {
1266         got := string(gotBytes)
1267         filename := filepath.Join(t.dir, t.gofile)
1268         filename = filename[:len(filename)-len(".go")]
1269         filename += ".out"
1270         b, err := ioutil.ReadFile(filename)
1271         // File is allowed to be missing (err != nil) in which case output should be empty.
1272         got = strings.Replace(got, "\r\n", "\n", -1)
1273         if got != string(b) {
1274                 if err == nil {
1275                         t.err = fmt.Errorf("output does not match expected in %s. Instead saw\n%s", filename, got)
1276                 } else {
1277                         t.err = fmt.Errorf("output should be empty when (optional) expected-output file %s is not present. Instead saw\n%s", filename, got)
1278                 }
1279         }
1280 }
1281
1282 func splitOutput(out string, wantAuto bool) []string {
1283         // gc error messages continue onto additional lines with leading tabs.
1284         // Split the output at the beginning of each line that doesn't begin with a tab.
1285         // <autogenerated> lines are impossible to match so those are filtered out.
1286         var res []string
1287         for _, line := range strings.Split(out, "\n") {
1288                 if strings.HasSuffix(line, "\r") { // remove '\r', output by compiler on windows
1289                         line = line[:len(line)-1]
1290                 }
1291                 if strings.HasPrefix(line, "\t") {
1292                         res[len(res)-1] += "\n" + line
1293                 } else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
1294                         continue
1295                 } else if strings.TrimSpace(line) != "" {
1296                         res = append(res, line)
1297                 }
1298         }
1299         return res
1300 }
1301
1302 // errorCheck matches errors in outStr against comments in source files.
1303 // For each line of the source files which should generate an error,
1304 // there should be a comment of the form // ERROR "regexp".
1305 // If outStr has an error for a line which has no such comment,
1306 // this function will report an error.
1307 // Likewise if outStr does not have an error for a line which has a comment,
1308 // or if the error message does not match the <regexp>.
1309 // The <regexp> syntax is Perl but it's best to stick to egrep.
1310 //
1311 // Sources files are supplied as fullshort slice.
1312 // It consists of pairs: full path to source file and its base name.
1313 func (t *test) errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
1314         defer func() {
1315                 if *verbose && err != nil {
1316                         log.Printf("%s gc output:\n%s", t, outStr)
1317                 }
1318         }()
1319         var errs []error
1320         out := splitOutput(outStr, wantAuto)
1321
1322         // Cut directory name.
1323         for i := range out {
1324                 for j := 0; j < len(fullshort); j += 2 {
1325                         full, short := fullshort[j], fullshort[j+1]
1326                         out[i] = strings.Replace(out[i], full, short, -1)
1327                 }
1328         }
1329
1330         var want []wantedError
1331         for j := 0; j < len(fullshort); j += 2 {
1332                 full, short := fullshort[j], fullshort[j+1]
1333                 want = append(want, t.wantedErrors(full, short)...)
1334         }
1335
1336         for _, we := range want {
1337                 var errmsgs []string
1338                 if we.auto {
1339                         errmsgs, out = partitionStrings("<autogenerated>", out)
1340                 } else {
1341                         errmsgs, out = partitionStrings(we.prefix, out)
1342                 }
1343                 if len(errmsgs) == 0 {
1344                         errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
1345                         continue
1346                 }
1347                 matched := false
1348                 n := len(out)
1349                 for _, errmsg := range errmsgs {
1350                         // Assume errmsg says "file:line: foo".
1351                         // Cut leading "file:line: " to avoid accidental matching of file name instead of message.
1352                         text := errmsg
1353                         if _, suffix, ok := strings.Cut(text, " "); ok {
1354                                 text = suffix
1355                         }
1356                         if we.re.MatchString(text) {
1357                                 matched = true
1358                         } else {
1359                                 out = append(out, errmsg)
1360                         }
1361                 }
1362                 if !matched {
1363                         errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t")))
1364                         continue
1365                 }
1366         }
1367
1368         if len(out) > 0 {
1369                 errs = append(errs, fmt.Errorf("Unmatched Errors:"))
1370                 for _, errLine := range out {
1371                         errs = append(errs, fmt.Errorf("%s", errLine))
1372                 }
1373         }
1374
1375         if len(errs) == 0 {
1376                 return nil
1377         }
1378         if len(errs) == 1 {
1379                 return errs[0]
1380         }
1381         var buf bytes.Buffer
1382         fmt.Fprintf(&buf, "\n")
1383         for _, err := range errs {
1384                 fmt.Fprintf(&buf, "%s\n", err.Error())
1385         }
1386         return errors.New(buf.String())
1387 }
1388
1389 func (t *test) updateErrors(out, file string) {
1390         base := path.Base(file)
1391         // Read in source file.
1392         src, err := ioutil.ReadFile(file)
1393         if err != nil {
1394                 fmt.Fprintln(os.Stderr, err)
1395                 return
1396         }
1397         lines := strings.Split(string(src), "\n")
1398         // Remove old errors.
1399         for i := range lines {
1400                 lines[i], _, _ = strings.Cut(lines[i], " // ERROR ")
1401         }
1402         // Parse new errors.
1403         errors := make(map[int]map[string]bool)
1404         tmpRe := regexp.MustCompile(`autotmp_[0-9]+`)
1405         for _, errStr := range splitOutput(out, false) {
1406                 errFile, rest, ok := strings.Cut(errStr, ":")
1407                 if !ok || errFile != file {
1408                         continue
1409                 }
1410                 lineStr, msg, ok := strings.Cut(rest, ":")
1411                 if !ok {
1412                         continue
1413                 }
1414                 line, err := strconv.Atoi(lineStr)
1415                 line--
1416                 if err != nil || line < 0 || line >= len(lines) {
1417                         continue
1418                 }
1419                 msg = strings.Replace(msg, file, base, -1) // normalize file mentions in error itself
1420                 msg = strings.TrimLeft(msg, " \t")
1421                 for _, r := range []string{`\`, `*`, `+`, `?`, `[`, `]`, `(`, `)`} {
1422                         msg = strings.Replace(msg, r, `\`+r, -1)
1423                 }
1424                 msg = strings.Replace(msg, `"`, `.`, -1)
1425                 msg = tmpRe.ReplaceAllLiteralString(msg, `autotmp_[0-9]+`)
1426                 if errors[line] == nil {
1427                         errors[line] = make(map[string]bool)
1428                 }
1429                 errors[line][msg] = true
1430         }
1431         // Add new errors.
1432         for line, errs := range errors {
1433                 var sorted []string
1434                 for e := range errs {
1435                         sorted = append(sorted, e)
1436                 }
1437                 sort.Strings(sorted)
1438                 lines[line] += " // ERROR"
1439                 for _, e := range sorted {
1440                         lines[line] += fmt.Sprintf(` "%s$"`, e)
1441                 }
1442         }
1443         // Write new file.
1444         err = ioutil.WriteFile(file, []byte(strings.Join(lines, "\n")), 0640)
1445         if err != nil {
1446                 fmt.Fprintln(os.Stderr, err)
1447                 return
1448         }
1449         // Polish.
1450         exec.Command(goTool(), "fmt", file).CombinedOutput()
1451 }
1452
1453 // matchPrefix reports whether s is of the form ^(.*/)?prefix(:|[),
1454 // That is, it needs the file name prefix followed by a : or a [,
1455 // and possibly preceded by a directory name.
1456 func matchPrefix(s, prefix string) bool {
1457         i := strings.Index(s, ":")
1458         if i < 0 {
1459                 return false
1460         }
1461         j := strings.LastIndex(s[:i], "/")
1462         s = s[j+1:]
1463         if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
1464                 return false
1465         }
1466         switch s[len(prefix)] {
1467         case '[', ':':
1468                 return true
1469         }
1470         return false
1471 }
1472
1473 func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
1474         for _, s := range strs {
1475                 if matchPrefix(s, prefix) {
1476                         matched = append(matched, s)
1477                 } else {
1478                         unmatched = append(unmatched, s)
1479                 }
1480         }
1481         return
1482 }
1483
1484 type wantedError struct {
1485         reStr   string
1486         re      *regexp.Regexp
1487         lineNum int
1488         auto    bool // match <autogenerated> line
1489         file    string
1490         prefix  string
1491 }
1492
1493 var (
1494         errRx       = regexp.MustCompile(`// (?:GC_)?ERROR (.*)`)
1495         errAutoRx   = regexp.MustCompile(`// (?:GC_)?ERRORAUTO (.*)`)
1496         errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
1497         lineRx      = regexp.MustCompile(`LINE(([+-])([0-9]+))?`)
1498 )
1499
1500 func (t *test) wantedErrors(file, short string) (errs []wantedError) {
1501         cache := make(map[string]*regexp.Regexp)
1502
1503         src, _ := ioutil.ReadFile(file)
1504         for i, line := range strings.Split(string(src), "\n") {
1505                 lineNum := i + 1
1506                 if strings.Contains(line, "////") {
1507                         // double comment disables ERROR
1508                         continue
1509                 }
1510                 var auto bool
1511                 m := errAutoRx.FindStringSubmatch(line)
1512                 if m != nil {
1513                         auto = true
1514                 } else {
1515                         m = errRx.FindStringSubmatch(line)
1516                 }
1517                 if m == nil {
1518                         continue
1519                 }
1520                 all := m[1]
1521                 mm := errQuotesRx.FindAllStringSubmatch(all, -1)
1522                 if mm == nil {
1523                         log.Fatalf("%s:%d: invalid errchk line: %s", t.goFileName(), lineNum, line)
1524                 }
1525                 for _, m := range mm {
1526                         rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
1527                                 n := lineNum
1528                                 if strings.HasPrefix(m, "LINE+") {
1529                                         delta, _ := strconv.Atoi(m[5:])
1530                                         n += delta
1531                                 } else if strings.HasPrefix(m, "LINE-") {
1532                                         delta, _ := strconv.Atoi(m[5:])
1533                                         n -= delta
1534                                 }
1535                                 return fmt.Sprintf("%s:%d", short, n)
1536                         })
1537                         re := cache[rx]
1538                         if re == nil {
1539                                 var err error
1540                                 re, err = regexp.Compile(rx)
1541                                 if err != nil {
1542                                         log.Fatalf("%s:%d: invalid regexp \"%s\" in ERROR line: %v", t.goFileName(), lineNum, rx, err)
1543                                 }
1544                                 cache[rx] = re
1545                         }
1546                         prefix := fmt.Sprintf("%s:%d", short, lineNum)
1547                         errs = append(errs, wantedError{
1548                                 reStr:   rx,
1549                                 re:      re,
1550                                 prefix:  prefix,
1551                                 auto:    auto,
1552                                 lineNum: lineNum,
1553                                 file:    short,
1554                         })
1555                 }
1556         }
1557
1558         return
1559 }
1560
1561 const (
1562         // Regexp to match a single opcode check: optionally begin with "-" (to indicate
1563         // a negative check), followed by a string literal enclosed in "" or ``. For "",
1564         // backslashes must be handled.
1565         reMatchCheck = `-?(?:\x60[^\x60]*\x60|"(?:[^"\\]|\\.)*")`
1566 )
1567
1568 var (
1569         // Regexp to split a line in code and comment, trimming spaces
1570         rxAsmComment = regexp.MustCompile(`^\s*(.*?)\s*(?://\s*(.+)\s*)?$`)
1571
1572         // Regexp to extract an architecture check: architecture name (or triplet),
1573         // followed by semi-colon, followed by a comma-separated list of opcode checks.
1574         // Extraneous spaces are ignored.
1575         rxAsmPlatform = regexp.MustCompile(`(\w+)(/\w+)?(/\w*)?\s*:\s*(` + reMatchCheck + `(?:\s*,\s*` + reMatchCheck + `)*)`)
1576
1577         // Regexp to extract a single opcoded check
1578         rxAsmCheck = regexp.MustCompile(reMatchCheck)
1579
1580         // List of all architecture variants. Key is the GOARCH architecture,
1581         // value[0] is the variant-changing environment variable, and values[1:]
1582         // are the supported variants.
1583         archVariants = map[string][]string{
1584                 "386":     {"GO386", "sse2", "softfloat"},
1585                 "amd64":   {"GOAMD64", "v1", "v2", "v3", "v4"},
1586                 "arm":     {"GOARM", "5", "6", "7"},
1587                 "arm64":   {},
1588                 "loong64": {},
1589                 "mips":    {"GOMIPS", "hardfloat", "softfloat"},
1590                 "mips64":  {"GOMIPS64", "hardfloat", "softfloat"},
1591                 "ppc64":   {"GOPPC64", "power8", "power9"},
1592                 "ppc64le": {"GOPPC64", "power8", "power9"},
1593                 "s390x":   {},
1594                 "wasm":    {},
1595                 "riscv64": {},
1596         }
1597 )
1598
1599 // wantedAsmOpcode is a single asmcheck check
1600 type wantedAsmOpcode struct {
1601         fileline string         // original source file/line (eg: "/path/foo.go:45")
1602         line     int            // original source line
1603         opcode   *regexp.Regexp // opcode check to be performed on assembly output
1604         negative bool           // true if the check is supposed to fail rather than pass
1605         found    bool           // true if the opcode check matched at least one in the output
1606 }
1607
1608 // A build environment triplet separated by slashes (eg: linux/386/sse2).
1609 // The third field can be empty if the arch does not support variants (eg: "plan9/amd64/")
1610 type buildEnv string
1611
1612 // Environ returns the environment it represents in cmd.Environ() "key=val" format
1613 // For instance, "linux/386/sse2".Environ() returns {"GOOS=linux", "GOARCH=386", "GO386=sse2"}
1614 func (b buildEnv) Environ() []string {
1615         fields := strings.Split(string(b), "/")
1616         if len(fields) != 3 {
1617                 panic("invalid buildEnv string: " + string(b))
1618         }
1619         env := []string{"GOOS=" + fields[0], "GOARCH=" + fields[1]}
1620         if fields[2] != "" {
1621                 env = append(env, archVariants[fields[1]][0]+"="+fields[2])
1622         }
1623         return env
1624 }
1625
1626 // asmChecks represents all the asmcheck checks present in a test file
1627 // The outer map key is the build triplet in which the checks must be performed.
1628 // The inner map key represent the source file line ("filename.go:1234") at which the
1629 // checks must be performed.
1630 type asmChecks map[buildEnv]map[string][]wantedAsmOpcode
1631
1632 // Envs returns all the buildEnv in which at least one check is present
1633 func (a asmChecks) Envs() []buildEnv {
1634         var envs []buildEnv
1635         for e := range a {
1636                 envs = append(envs, e)
1637         }
1638         sort.Slice(envs, func(i, j int) bool {
1639                 return string(envs[i]) < string(envs[j])
1640         })
1641         return envs
1642 }
1643
1644 func (t *test) wantedAsmOpcodes(fn string) asmChecks {
1645         ops := make(asmChecks)
1646
1647         comment := ""
1648         src, _ := ioutil.ReadFile(fn)
1649         for i, line := range strings.Split(string(src), "\n") {
1650                 matches := rxAsmComment.FindStringSubmatch(line)
1651                 code, cmt := matches[1], matches[2]
1652
1653                 // Keep comments pending in the comment variable until
1654                 // we find a line that contains some code.
1655                 comment += " " + cmt
1656                 if code == "" {
1657                         continue
1658                 }
1659
1660                 // Parse and extract any architecture check from comments,
1661                 // made by one architecture name and multiple checks.
1662                 lnum := fn + ":" + strconv.Itoa(i+1)
1663                 for _, ac := range rxAsmPlatform.FindAllStringSubmatch(comment, -1) {
1664                         archspec, allchecks := ac[1:4], ac[4]
1665
1666                         var arch, subarch, os string
1667                         switch {
1668                         case archspec[2] != "": // 3 components: "linux/386/sse2"
1669                                 os, arch, subarch = archspec[0], archspec[1][1:], archspec[2][1:]
1670                         case archspec[1] != "": // 2 components: "386/sse2"
1671                                 os, arch, subarch = "linux", archspec[0], archspec[1][1:]
1672                         default: // 1 component: "386"
1673                                 os, arch, subarch = "linux", archspec[0], ""
1674                                 if arch == "wasm" {
1675                                         os = "js"
1676                                 }
1677                         }
1678
1679                         if _, ok := archVariants[arch]; !ok {
1680                                 log.Fatalf("%s:%d: unsupported architecture: %v", t.goFileName(), i+1, arch)
1681                         }
1682
1683                         // Create the build environments corresponding the above specifiers
1684                         envs := make([]buildEnv, 0, 4)
1685                         if subarch != "" {
1686                                 envs = append(envs, buildEnv(os+"/"+arch+"/"+subarch))
1687                         } else {
1688                                 subarchs := archVariants[arch]
1689                                 if len(subarchs) == 0 {
1690                                         envs = append(envs, buildEnv(os+"/"+arch+"/"))
1691                                 } else {
1692                                         for _, sa := range archVariants[arch][1:] {
1693                                                 envs = append(envs, buildEnv(os+"/"+arch+"/"+sa))
1694                                         }
1695                                 }
1696                         }
1697
1698                         for _, m := range rxAsmCheck.FindAllString(allchecks, -1) {
1699                                 negative := false
1700                                 if m[0] == '-' {
1701                                         negative = true
1702                                         m = m[1:]
1703                                 }
1704
1705                                 rxsrc, err := strconv.Unquote(m)
1706                                 if err != nil {
1707                                         log.Fatalf("%s:%d: error unquoting string: %v", t.goFileName(), i+1, err)
1708                                 }
1709
1710                                 // Compile the checks as regular expressions. Notice that we
1711                                 // consider checks as matching from the beginning of the actual
1712                                 // assembler source (that is, what is left on each line of the
1713                                 // compile -S output after we strip file/line info) to avoid
1714                                 // trivial bugs such as "ADD" matching "FADD". This
1715                                 // doesn't remove genericity: it's still possible to write
1716                                 // something like "F?ADD", but we make common cases simpler
1717                                 // to get right.
1718                                 oprx, err := regexp.Compile("^" + rxsrc)
1719                                 if err != nil {
1720                                         log.Fatalf("%s:%d: %v", t.goFileName(), i+1, err)
1721                                 }
1722
1723                                 for _, env := range envs {
1724                                         if ops[env] == nil {
1725                                                 ops[env] = make(map[string][]wantedAsmOpcode)
1726                                         }
1727                                         ops[env][lnum] = append(ops[env][lnum], wantedAsmOpcode{
1728                                                 negative: negative,
1729                                                 fileline: lnum,
1730                                                 line:     i + 1,
1731                                                 opcode:   oprx,
1732                                         })
1733                                 }
1734                         }
1735                 }
1736                 comment = ""
1737         }
1738
1739         return ops
1740 }
1741
1742 func (t *test) asmCheck(outStr string, fn string, env buildEnv, fullops map[string][]wantedAsmOpcode) (err error) {
1743         // The assembly output contains the concatenated dump of multiple functions.
1744         // the first line of each function begins at column 0, while the rest is
1745         // indented by a tabulation. These data structures help us index the
1746         // output by function.
1747         functionMarkers := make([]int, 1)
1748         lineFuncMap := make(map[string]int)
1749
1750         lines := strings.Split(outStr, "\n")
1751         rxLine := regexp.MustCompile(fmt.Sprintf(`\((%s:\d+)\)\s+(.*)`, regexp.QuoteMeta(fn)))
1752
1753         for nl, line := range lines {
1754                 // Check if this line begins a function
1755                 if len(line) > 0 && line[0] != '\t' {
1756                         functionMarkers = append(functionMarkers, nl)
1757                 }
1758
1759                 // Search if this line contains a assembly opcode (which is prefixed by the
1760                 // original source file/line in parenthesis)
1761                 matches := rxLine.FindStringSubmatch(line)
1762                 if len(matches) == 0 {
1763                         continue
1764                 }
1765                 srcFileLine, asm := matches[1], matches[2]
1766
1767                 // Associate the original file/line information to the current
1768                 // function in the output; it will be useful to dump it in case
1769                 // of error.
1770                 lineFuncMap[srcFileLine] = len(functionMarkers) - 1
1771
1772                 // If there are opcode checks associated to this source file/line,
1773                 // run the checks.
1774                 if ops, found := fullops[srcFileLine]; found {
1775                         for i := range ops {
1776                                 if !ops[i].found && ops[i].opcode.FindString(asm) != "" {
1777                                         ops[i].found = true
1778                                 }
1779                         }
1780                 }
1781         }
1782         functionMarkers = append(functionMarkers, len(lines))
1783
1784         var failed []wantedAsmOpcode
1785         for _, ops := range fullops {
1786                 for _, o := range ops {
1787                         // There's a failure if a negative match was found,
1788                         // or a positive match was not found.
1789                         if o.negative == o.found {
1790                                 failed = append(failed, o)
1791                         }
1792                 }
1793         }
1794         if len(failed) == 0 {
1795                 return
1796         }
1797
1798         // At least one asmcheck failed; report them
1799         sort.Slice(failed, func(i, j int) bool {
1800                 return failed[i].line < failed[j].line
1801         })
1802
1803         lastFunction := -1
1804         var errbuf bytes.Buffer
1805         fmt.Fprintln(&errbuf)
1806         for _, o := range failed {
1807                 // Dump the function in which this opcode check was supposed to
1808                 // pass but failed.
1809                 funcIdx := lineFuncMap[o.fileline]
1810                 if funcIdx != 0 && funcIdx != lastFunction {
1811                         funcLines := lines[functionMarkers[funcIdx]:functionMarkers[funcIdx+1]]
1812                         log.Println(strings.Join(funcLines, "\n"))
1813                         lastFunction = funcIdx // avoid printing same function twice
1814                 }
1815
1816                 if o.negative {
1817                         fmt.Fprintf(&errbuf, "%s:%d: %s: wrong opcode found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1818                 } else {
1819                         fmt.Fprintf(&errbuf, "%s:%d: %s: opcode not found: %q\n", t.goFileName(), o.line, env, o.opcode.String())
1820                 }
1821         }
1822         err = errors.New(errbuf.String())
1823         return
1824 }
1825
1826 // defaultRunOutputLimit returns the number of runoutput tests that
1827 // can be executed in parallel.
1828 func defaultRunOutputLimit() int {
1829         const maxArmCPU = 2
1830
1831         cpu := runtime.NumCPU()
1832         if runtime.GOARCH == "arm" && cpu > maxArmCPU {
1833                 cpu = maxArmCPU
1834         }
1835         return cpu
1836 }
1837
1838 // checkShouldTest runs sanity checks on the shouldTest function.
1839 func checkShouldTest() {
1840         assert := func(ok bool, _ string) {
1841                 if !ok {
1842                         panic("fail")
1843                 }
1844         }
1845         assertNot := func(ok bool, _ string) { assert(!ok, "") }
1846
1847         // Simple tests.
1848         assert(shouldTest("// +build linux", "linux", "arm"))
1849         assert(shouldTest("// +build !windows", "linux", "arm"))
1850         assertNot(shouldTest("// +build !windows", "windows", "amd64"))
1851
1852         // A file with no build tags will always be tested.
1853         assert(shouldTest("// This is a test.", "os", "arch"))
1854
1855         // Build tags separated by a space are OR-ed together.
1856         assertNot(shouldTest("// +build arm 386", "linux", "amd64"))
1857
1858         // Build tags separated by a comma are AND-ed together.
1859         assertNot(shouldTest("// +build !windows,!plan9", "windows", "amd64"))
1860         assertNot(shouldTest("// +build !windows,!plan9", "plan9", "386"))
1861
1862         // Build tags on multiple lines are AND-ed together.
1863         assert(shouldTest("// +build !windows\n// +build amd64", "linux", "amd64"))
1864         assertNot(shouldTest("// +build !windows\n// +build amd64", "windows", "amd64"))
1865
1866         // Test that (!a OR !b) matches anything.
1867         assert(shouldTest("// +build !windows !plan9", "windows", "amd64"))
1868 }
1869
1870 func getenv(key, def string) string {
1871         value := os.Getenv(key)
1872         if value != "" {
1873                 return value
1874         }
1875         return def
1876 }
1877
1878 // overlayDir makes a minimal-overhead copy of srcRoot in which new files may be added.
1879 func overlayDir(dstRoot, srcRoot string) error {
1880         dstRoot = filepath.Clean(dstRoot)
1881         if err := os.MkdirAll(dstRoot, 0777); err != nil {
1882                 return err
1883         }
1884
1885         srcRoot, err := filepath.Abs(srcRoot)
1886         if err != nil {
1887                 return err
1888         }
1889
1890         return filepath.WalkDir(srcRoot, func(srcPath string, d fs.DirEntry, err error) error {
1891                 if err != nil || srcPath == srcRoot {
1892                         return err
1893                 }
1894
1895                 suffix := strings.TrimPrefix(srcPath, srcRoot)
1896                 for len(suffix) > 0 && suffix[0] == filepath.Separator {
1897                         suffix = suffix[1:]
1898                 }
1899                 dstPath := filepath.Join(dstRoot, suffix)
1900
1901                 var info fs.FileInfo
1902                 if d.Type()&os.ModeSymlink != 0 {
1903                         info, err = os.Stat(srcPath)
1904                 } else {
1905                         info, err = d.Info()
1906                 }
1907                 if err != nil {
1908                         return err
1909                 }
1910                 perm := info.Mode() & os.ModePerm
1911
1912                 // Always copy directories (don't symlink them).
1913                 // If we add a file in the overlay, we don't want to add it in the original.
1914                 if info.IsDir() {
1915                         return os.MkdirAll(dstPath, perm|0200)
1916                 }
1917
1918                 // If the OS supports symlinks, use them instead of copying bytes.
1919                 if err := os.Symlink(srcPath, dstPath); err == nil {
1920                         return nil
1921                 }
1922
1923                 // Otherwise, copy the bytes.
1924                 src, err := os.Open(srcPath)
1925                 if err != nil {
1926                         return err
1927                 }
1928                 defer src.Close()
1929
1930                 dst, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
1931                 if err != nil {
1932                         return err
1933                 }
1934
1935                 _, err = io.Copy(dst, src)
1936                 if closeErr := dst.Close(); err == nil {
1937                         err = closeErr
1938                 }
1939                 return err
1940         })
1941 }
1942
1943 // The following sets of files are excluded from testing depending on configuration.
1944 // The types2Failures(32Bit) files pass with the 1.17 compiler but don't pass with
1945 // the 1.18 compiler using the new types2 type checker, or pass with sub-optimal
1946 // error(s).
1947
1948 // List of files that the compiler cannot errorcheck with the new typechecker (types2).
1949 var types2Failures = setOf(
1950         "notinheap.go",            // types2 doesn't report errors about conversions that are invalid due to //go:notinheap
1951         "shift1.go",               // types2 reports two new errors which are probably not right
1952         "fixedbugs/issue10700.go", // types2 should give hint about ptr to interface
1953         "fixedbugs/issue18331.go", // missing error about misuse of //go:noescape (irgen needs code from noder)
1954         "fixedbugs/issue18419.go", // types2 reports no field or method member, but should say unexported
1955         "fixedbugs/issue20233.go", // types2 reports two instead of one error (preference: 1.17 compiler)
1956         "fixedbugs/issue20245.go", // types2 reports two instead of one error (preference: 1.17 compiler)
1957         "fixedbugs/issue31053.go", // types2 reports "unknown field" instead of "cannot refer to unexported field"
1958 )
1959
1960 var types2Failures32Bit = setOf(
1961         "printbig.go",             // large untyped int passed to print (32-bit)
1962         "fixedbugs/bug114.go",     // large untyped int passed to println (32-bit)
1963         "fixedbugs/issue23305.go", // large untyped int passed to println (32-bit)
1964 )
1965
1966 var go118Failures = setOf(
1967         "typeparam/nested.go",     // 1.18 compiler doesn't support function-local types with generics
1968         "typeparam/issue51521.go", // 1.18 compiler produces bad panic message and link error
1969 )
1970
1971 // In all of these cases, the 1.17 compiler reports reasonable errors, but either the
1972 // 1.17 or 1.18 compiler report extra errors, so we can't match correctly on both. We
1973 // now set the patterns to match correctly on all the 1.18 errors.
1974 // This list remains here just as a reference and for comparison - these files all pass.
1975 var _ = setOf(
1976         "import1.go",      // types2 reports extra errors
1977         "initializerr.go", // types2 reports extra error
1978         "typecheck.go",    // types2 reports extra error at function call
1979
1980         "fixedbugs/bug176.go", // types2 reports all errors (pref: types2)
1981         "fixedbugs/bug195.go", // types2 reports slight different errors, and an extra error
1982         "fixedbugs/bug412.go", // types2 produces a follow-on error
1983
1984         "fixedbugs/issue11614.go", // types2 reports an extra error
1985         "fixedbugs/issue17038.go", // types2 doesn't report a follow-on error (pref: types2)
1986         "fixedbugs/issue23732.go", // types2 reports different (but ok) line numbers
1987         "fixedbugs/issue4510.go",  // types2 reports different (but ok) line numbers
1988         "fixedbugs/issue7525b.go", // types2 reports init cycle error on different line - ok otherwise
1989         "fixedbugs/issue7525c.go", // types2 reports init cycle error on different line - ok otherwise
1990         "fixedbugs/issue7525d.go", // types2 reports init cycle error on different line - ok otherwise
1991         "fixedbugs/issue7525e.go", // types2 reports init cycle error on different line - ok otherwise
1992         "fixedbugs/issue7525.go",  // types2 reports init cycle error on different line - ok otherwise
1993 )
1994
1995 var unifiedFailures = setOf(
1996         "closure3.go",  // unified IR numbers closures differently than -d=inlfuncswithclosures
1997         "escape4.go",   // unified IR can inline f5 and f6; test doesn't expect this
1998         "inline.go",    // unified IR reports function literal diagnostics on different lines than -d=inlfuncswithclosures
1999         "linkname3.go", // unified IR is missing some linkname errors
2000
2001         "fixedbugs/issue42284.go",  // prints "T(0) does not escape", but test expects "a.I(a.T(0)) does not escape"
2002         "fixedbugs/issue7921.go",   // prints "… escapes to heap", but test expects "string(…) escapes to heap"
2003         "typeparam/issue47631.go",  // unified IR can handle local type declarations
2004         "fixedbugs/issue42058a.go", // unified IR doesn't report channel element too large
2005         "fixedbugs/issue42058b.go", // unified IR doesn't report channel element too large
2006         "fixedbugs/issue49767.go",  // unified IR doesn't report channel element too large
2007         "fixedbugs/issue49814.go",  // unified IR doesn't report array type too large
2008 )
2009
2010 func setOf(keys ...string) map[string]bool {
2011         m := make(map[string]bool, len(keys))
2012         for _, key := range keys {
2013                 m[key] = true
2014         }
2015         return m
2016 }
2017
2018 // splitQuoted splits the string s around each instance of one or more consecutive
2019 // white space characters while taking into account quotes and escaping, and
2020 // returns an array of substrings of s or an empty list if s contains only white space.
2021 // Single quotes and double quotes are recognized to prevent splitting within the
2022 // quoted region, and are removed from the resulting substrings. If a quote in s
2023 // isn't closed err will be set and r will have the unclosed argument as the
2024 // last element. The backslash is used for escaping.
2025 //
2026 // For example, the following string:
2027 //
2028 //      a b:"c d" 'e''f'  "g\""
2029 //
2030 // Would be parsed as:
2031 //
2032 //      []string{"a", "b:c d", "ef", `g"`}
2033 //
2034 // [copied from src/go/build/build.go]
2035 func splitQuoted(s string) (r []string, err error) {
2036         var args []string
2037         arg := make([]rune, len(s))
2038         escaped := false
2039         quoted := false
2040         quote := '\x00'
2041         i := 0
2042         for _, rune := range s {
2043                 switch {
2044                 case escaped:
2045                         escaped = false
2046                 case rune == '\\':
2047                         escaped = true
2048                         continue
2049                 case quote != '\x00':
2050                         if rune == quote {
2051                                 quote = '\x00'
2052                                 continue
2053                         }
2054                 case rune == '"' || rune == '\'':
2055                         quoted = true
2056                         quote = rune
2057                         continue
2058                 case unicode.IsSpace(rune):
2059                         if quoted || i > 0 {
2060                                 quoted = false
2061                                 args = append(args, string(arg[:i]))
2062                                 i = 0
2063                         }
2064                         continue
2065                 }
2066                 arg[i] = rune
2067                 i++
2068         }
2069         if quoted || i > 0 {
2070                 args = append(args, string(arg[:i]))
2071         }
2072         if quote != 0 {
2073                 err = errors.New("unclosed quote")
2074         } else if escaped {
2075                 err = errors.New("unfinished escaping")
2076         }
2077         return args, err
2078 }