Source file src/cmd/compile/internal/test/inst_test.go

     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  	"internal/goexperiment"
     9  	"internal/testenv"
    10  	"io/ioutil"
    11  	"os"
    12  	"os/exec"
    13  	"path/filepath"
    14  	"regexp"
    15  	"testing"
    16  )
    17  
    18  // TestInst tests that only one instantiation of Sort is created, even though generic
    19  // Sort is used for multiple pointer types across two packages.
    20  func TestInst(t *testing.T) {
    21  	if goexperiment.Unified {
    22  		t.Skip("unified currently does stenciling, not dictionaries")
    23  	}
    24  	testenv.MustHaveGoBuild(t)
    25  	testenv.MustHaveGoRun(t)
    26  
    27  	var tmpdir string
    28  	var err error
    29  	tmpdir, err = ioutil.TempDir("", "TestDict")
    30  	if err != nil {
    31  		t.Fatalf("Failed to create temporary directory: %v", err)
    32  	}
    33  	defer os.RemoveAll(tmpdir)
    34  
    35  	// Build ptrsort.go, which uses package mysort.
    36  	var output []byte
    37  	filename := "ptrsort.go"
    38  	exename := "ptrsort"
    39  	outname := "ptrsort.out"
    40  	gotool := testenv.GoToolPath(t)
    41  	dest := filepath.Join(tmpdir, exename)
    42  	cmd := exec.Command(gotool, "build", "-o", dest, filepath.Join("testdata", filename))
    43  	if output, err = cmd.CombinedOutput(); err != nil {
    44  		t.Fatalf("Failed: %v:\nOutput: %s\n", err, output)
    45  	}
    46  
    47  	// Test that there is exactly one shape-based instantiation of Sort in
    48  	// the executable.
    49  	cmd = exec.Command(gotool, "tool", "nm", dest)
    50  	if output, err = cmd.CombinedOutput(); err != nil {
    51  		t.Fatalf("Failed: %v:\nOut: %s\n", err, output)
    52  	}
    53  	// Look for shape-based instantiation of Sort, but ignore any extra wrapper
    54  	// ending in "-tramp" (which are created on riscv).
    55  	re := regexp.MustCompile(`\bSort\[.*shape.*\][^-]`)
    56  	r := re.FindAllIndex(output, -1)
    57  	if len(r) != 1 {
    58  		t.Fatalf("Wanted 1 instantiations of Sort function, got %d\n", len(r))
    59  	}
    60  
    61  	// Actually run the test and make sure output is correct.
    62  	cmd = exec.Command(gotool, "run", filepath.Join("testdata", filename))
    63  	if output, err = cmd.CombinedOutput(); err != nil {
    64  		t.Fatalf("Failed: %v:\nOut: %s\n", err, output)
    65  	}
    66  	out, err := ioutil.ReadFile(filepath.Join("testdata", outname))
    67  	if err != nil {
    68  		t.Fatalf("Could not find %s\n", outname)
    69  	}
    70  	if string(out) != string(output) {
    71  		t.Fatalf("Wanted output %v, got %v\n", string(out), string(output))
    72  	}
    73  }
    74  

View as plain text