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