• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 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
5package ld
6
7import (
8	"bytes"
9	"internal/testenv"
10	"path/filepath"
11	"testing"
12)
13
14func TestDeadcode(t *testing.T) {
15	testenv.MustHaveGoBuild(t)
16	t.Parallel()
17
18	tmpdir := t.TempDir()
19
20	tests := []struct {
21		src      string
22		pos, neg []string // positive and negative patterns
23	}{
24		{"reflectcall", nil, []string{"main.T.M"}},
25		{"typedesc", nil, []string{"type:main.T"}},
26		{"ifacemethod", nil, []string{"main.T.M"}},
27		{"ifacemethod2", []string{"main.T.M"}, nil},
28		{"ifacemethod3", []string{"main.S.M"}, nil},
29		{"ifacemethod4", nil, []string{"main.T.M"}},
30		{"ifacemethod5", []string{"main.S.M"}, nil},
31		{"ifacemethod6", []string{"main.S.M"}, []string{"main.S.N"}},
32		{"structof_funcof", []string{"main.S.M"}, []string{"main.S.N"}},
33		{"globalmap", []string{"main.small", "main.effect"},
34			[]string{"main.large"}},
35	}
36	for _, test := range tests {
37		test := test
38		t.Run(test.src, func(t *testing.T) {
39			t.Parallel()
40			src := filepath.Join("testdata", "deadcode", test.src+".go")
41			exe := filepath.Join(tmpdir, test.src+".exe")
42			cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-ldflags=-dumpdep", "-o", exe, src)
43			out, err := cmd.CombinedOutput()
44			if err != nil {
45				t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
46			}
47			for _, pos := range test.pos {
48				if !bytes.Contains(out, []byte(pos+"\n")) {
49					t.Errorf("%s should be reachable. Output:\n%s", pos, out)
50				}
51			}
52			for _, neg := range test.neg {
53				if bytes.Contains(out, []byte(neg+"\n")) {
54					t.Errorf("%s should not be reachable. Output:\n%s", neg, out)
55				}
56			}
57		})
58	}
59}
60