github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/compile/test/inst_test.go (about)

     1  // Copyright 2021 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package test
     6  
     7  import (
     8  	"os"
     9  	"path/filepath"
    10  	"regexp"
    11  	"testing"
    12  
    13  	"github.com/go-asm/go/testenv"
    14  )
    15  
    16  // TestInst tests that only one instantiation of Sort is created, even though generic
    17  // Sort is used for multiple pointer types across two packages.
    18  func TestInst(t *testing.T) {
    19  	testenv.MustHaveGoBuild(t)
    20  	testenv.MustHaveGoRun(t)
    21  
    22  	// Build ptrsort.go, which uses package mysort.
    23  	var output []byte
    24  	var err error
    25  	filename := "ptrsort.go"
    26  	exename := "ptrsort"
    27  	outname := "ptrsort.out"
    28  	gotool := testenv.GoToolPath(t)
    29  	dest := filepath.Join(t.TempDir(), exename)
    30  	cmd := testenv.Command(t, gotool, "build", "-o", dest, filepath.Join("testdata", filename))
    31  	if output, err = cmd.CombinedOutput(); err != nil {
    32  		t.Fatalf("Failed: %v:\nOutput: %s\n", err, output)
    33  	}
    34  
    35  	// Test that there is exactly one shape-based instantiation of Sort in
    36  	// the executable.
    37  	cmd = testenv.Command(t, gotool, "tool", "nm", dest)
    38  	if output, err = cmd.CombinedOutput(); err != nil {
    39  		t.Fatalf("Failed: %v:\nOut: %s\n", err, output)
    40  	}
    41  	// Look for shape-based instantiation of Sort, but ignore any extra wrapper
    42  	// ending in "-tramp" (which are created on riscv).
    43  	re := regexp.MustCompile(`\bSort\[.*shape.*\][^-]`)
    44  	r := re.FindAllIndex(output, -1)
    45  	if len(r) != 1 {
    46  		t.Fatalf("Wanted 1 instantiations of Sort function, got %d\n", len(r))
    47  	}
    48  
    49  	// Actually run the test and make sure output is correct.
    50  	cmd = testenv.Command(t, gotool, "run", filepath.Join("testdata", filename))
    51  	if output, err = cmd.CombinedOutput(); err != nil {
    52  		t.Fatalf("Failed: %v:\nOut: %s\n", err, output)
    53  	}
    54  	out, err := os.ReadFile(filepath.Join("testdata", outname))
    55  	if err != nil {
    56  		t.Fatalf("Could not find %s\n", outname)
    57  	}
    58  	if string(out) != string(output) {
    59  		t.Fatalf("Wanted output %v, got %v\n", string(out), string(output))
    60  	}
    61  }