1 // Copyright 2015 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.
18 "honnef.co/go/tools/go/ir/irutil"
20 "golang.org/x/tools/go/packages"
23 const hello = `package main
28 fmt.Println("Hello, world")
32 func TestBuildPackage(t *testing.T) {
33 // There is a more substantial test of BuildPackage and the
34 // IR program it builds in ../ir/builder_test.go.
36 fset := token.NewFileSet()
37 f, err := parser.ParseFile(fset, "hello.go", hello, 0)
42 pkg := types.NewPackage("hello", "")
43 irpkg, _, err := irutil.BuildPackage(&types.Config{Importer: importer.Default()}, fset, pkg, []*ast.File{f}, 0)
47 if pkg.Name() != "main" {
48 t.Errorf("pkg.Name() = %s, want main", pkg.Name())
50 if irpkg.Func("main") == nil {
51 irpkg.WriteTo(os.Stderr)
52 t.Errorf("irpkg has no main function")
56 func TestPackages(t *testing.T) {
57 cfg := &packages.Config{Mode: packages.LoadSyntax}
58 initial, err := packages.Load(cfg, "bytes")
62 if packages.PrintErrors(initial) > 0 {
63 t.Fatal("there were errors")
66 prog, pkgs := irutil.Packages(initial, 0, nil)
67 bytesNewBuffer := pkgs[0].Func("NewBuffer")
68 bytesNewBuffer.Pkg.Build()
70 // We'll dump the IR of bytes.NewBuffer because it is small and stable.
71 out := new(bytes.Buffer)
72 bytesNewBuffer.WriteTo(out)
74 // For determinism, sanitize the location.
75 location := prog.Fset.Position(bytesNewBuffer.Pos()).String()
76 got := strings.Replace(out.String(), location, "$GOROOT/src/bytes/buffer.go:1", -1)
79 # Name: bytes.NewBuffer
81 # Location: $GOROOT/src/bytes/buffer.go:1
82 func NewBuffer(buf []byte) *Buffer:
84 t1 = Parameter <[]byte> {buf}
85 t2 = HeapAlloc <*Buffer>
86 t3 = FieldAddr <*[]byte> [0] (buf) t2
95 t.Errorf("bytes.NewBuffer IR = <<%s>>, want <<%s>>", got, want)
99 func TestBuildPackage_MissingImport(t *testing.T) {
100 fset := token.NewFileSet()
101 f, err := parser.ParseFile(fset, "bad.go", `package bad; import "missing"`, 0)
106 pkg := types.NewPackage("bad", "")
107 irpkg, _, err := irutil.BuildPackage(new(types.Config), fset, pkg, []*ast.File{f}, 0)
108 if err == nil || irpkg != nil {
109 t.Fatal("BuildPackage succeeded unexpectedly")
113 func TestIssue28106(t *testing.T) {
114 // In go1.10, go/packages loads all packages from source, not
115 // export data, but does not type check function bodies of
116 // imported packages. This test ensures that we do not attempt
117 // to run the IR builder on functions without type information.
118 cfg := &packages.Config{Mode: packages.LoadSyntax}
119 pkgs, err := packages.Load(cfg, "runtime")
123 prog, _ := irutil.Packages(pkgs, 0, nil)
124 prog.Build() // no crash