Source file test/fixedbugs/issue22662b.go

     1  // run
     2  
     3  //go:build !js && !wasip1 && gc
     4  
     5  // Copyright 2018 The Go Authors. All rights reserved.
     6  // Use of this source code is governed by a BSD-style
     7  // license that can be found in the LICENSE file.
     8  
     9  // Verify the impact of line directives on error positions and position formatting.
    10  
    11  package main
    12  
    13  import (
    14  	"log"
    15  	"os"
    16  	"os/exec"
    17  	"path/filepath"
    18  	"strings"
    19  )
    20  
    21  // Each of these tests is expected to fail (missing package clause)
    22  // at the position determined by the preceding line directive.
    23  var tests = []struct {
    24  	src, pos string
    25  }{
    26  	{"//line :10\n", ":10:"},                   // no filename means no filename
    27  	{"//line :10:4\n", "filename:10:4"},        // no filename means use existing filename
    28  	{"//line foo.go:10\n", "foo.go:10:"},       // no column means don't print a column
    29  	{"//line foo.go:10:4\n", "foo.go:10:4:"},   // column means print a column
    30  	{"//line foo.go:10:4\n\n", "foo.go:11:1:"}, // relative columns start at 1 after newline
    31  
    32  	{"/*line :10*/", ":10:"},
    33  	{"/*line :10:4*/", "filename:10:4"},
    34  	{"/*line foo.go:10*/", "foo.go:10:"},
    35  	{"/*line foo.go:10:4*/", "foo.go:10:4:"},
    36  	{"/*line foo.go:10:4*/\n", "foo.go:11:1:"},
    37  }
    38  
    39  func main() {
    40  	f, err := os.CreateTemp("", "issue22662b.go")
    41  	if err != nil {
    42  		log.Fatal(err)
    43  	}
    44  	f.Close()
    45  	defer os.Remove(f.Name())
    46  
    47  	for _, test := range tests {
    48  		if err := os.WriteFile(f.Name(), []byte(test.src), 0660); err != nil {
    49  			log.Fatal(err)
    50  		}
    51  
    52  		out, err := exec.Command("go", "tool", "compile", "-p=p", f.Name()).CombinedOutput()
    53  		if err == nil {
    54  			log.Fatalf("expected compiling\n---\n%s\n---\nto fail", test.src)
    55  		}
    56  
    57  		// Replace the temp filename (used when the line directive inherits
    58  		// it via the empty-filename form), and strip the temp directory
    59  		// prefix that is now joined onto relative line-directive filenames
    60  		// since go.dev/issue/70478.
    61  		errmsg := strings.Replace(string(out), f.Name(), "filename", -1)
    62  		errmsg = strings.Replace(errmsg, filepath.Dir(f.Name())+string(filepath.Separator), "", -1)
    63  		if !strings.HasPrefix(errmsg, test.pos) {
    64  			log.Fatalf("%q: got %q; want position %q", test.src, errmsg, test.pos)
    65  		}
    66  	}
    67  }
    68  

View as plain text