modernc.org/gc@v1.0.1-0.20240304020402-f0dba7c97c2b/testdata/errchk/test/fixedbugs/issue11771.go (about)

     1  // +build !nacl
     2  // run
     3  
     4  // Copyright 2015 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // Issue 11771: Magic comments should ignore carriage returns.
     9  
    10  package main
    11  
    12  import (
    13  	"bytes"
    14  	"fmt"
    15  	"io/ioutil"
    16  	"log"
    17  	"os"
    18  	"os/exec"
    19  	"path/filepath"
    20  	"runtime"
    21  )
    22  
    23  func main() {
    24  	if runtime.Compiler != "gc" {
    25  		return
    26  	}
    27  
    28  	dir, err := ioutil.TempDir("", "go-issue11771")
    29  	if err != nil {
    30  		log.Fatalf("creating temp dir: %v\n", err)
    31  	}
    32  	defer os.RemoveAll(dir)
    33  
    34  	// The go:nowritebarrier magic comment is only permitted in
    35  	// the runtime package.  So we confirm that the compilation
    36  	// fails.
    37  
    38  	var buf bytes.Buffer
    39  	fmt.Fprintln(&buf, `
    40  package main
    41  
    42  func main() {
    43  }
    44  `)
    45  	fmt.Fprintln(&buf, "//go:nowritebarrier\r")
    46  	fmt.Fprintln(&buf, `
    47  func x() {
    48  }
    49  `)
    50  
    51  	if err := ioutil.WriteFile(filepath.Join(dir, "x.go"), buf.Bytes(), 0666); err != nil {
    52  		log.Fatal(err)
    53  	}
    54  
    55  	cmd := exec.Command("go", "tool", "compile", "x.go")
    56  	cmd.Dir = dir
    57  	output, err := cmd.CombinedOutput()
    58  	if err == nil {
    59  		log.Fatal("compile succeeded unexpectedly")
    60  	}
    61  	if !bytes.Contains(output, []byte("only allowed in runtime")) {
    62  		log.Fatalf("wrong error message from compiler; got:\n%s\n", output)
    63  	}
    64  }