Debian Codegraph @

go/ir/example_test.go

raw
1 // Copyright 2013 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 //go:build !android && !ios && (unix || aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || plan9 || windows)
6
7 package ir_test
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/importer"
13 "go/parser"
14 "go/token"
15 "go/types"
16 "log"
17 "os"
18
19 "honnef.co/go/tools/go/ir"
20 "honnef.co/go/tools/go/ir/irutil"
21
22 "golang.org/x/tools/go/packages"
23 )
24
25 const hello = `
26 package main
27
28 import "fmt"
29
30 const message = "Hello, World!"
31
32 func main() {
33 fmt.Println(message)
34 }
35 `
36
37 // This program demonstrates how to run the IR builder on a single
38 // package of one or more already-parsed files. Its dependencies are
39 // loaded from compiler export data. This is what you'd typically use
40 // for a compiler; it does not depend on the obsolete
41 // [golang.org/x/tools/go/loader].
42 //
43 // It shows the printed representation of packages, functions, and
44 // instructions. Within the function listing, the name of each
45 // BasicBlock such as ".0.entry" is printed left-aligned, followed by
46 // the block's Instructions.
47 //
48 // For each instruction that defines an IR virtual register
49 // (i.e. implements Value), the type of that value is shown in the
50 // right column.
51 //
52 // Build and run the irdump.go program if you want a standalone tool
53 // with similar functionality. It is located at
54 // honnef.co/go/tools/internal/cmd/irdump.
55 //
56 // Use irutil.BuildPackage only if you have parsed--but not
57 // type-checked--syntax trees. Typically, clients already have typed
58 // syntax, perhaps obtained from golang.org/x/tools/go/packages.
59 // In that case, see the other examples for simpler approaches.
60 func Example_buildPackage() {
61 // Parse the source files.
62 fset := token.NewFileSet()
63 f, err := parser.ParseFile(fset, "hello.go", hello, parser.ParseComments|parser.SkipObjectResolution)
64 if err != nil {
65 fmt.Print(err) // parse error
66 return
67 }
68 files := []*ast.File{f}
69
70 // Create the type-checker's package.
71 pkg := types.NewPackage("hello", "")
72
73 // Type-check the package, load dependencies.
74 // Create and build the IR program.
75 hello, _, err := irutil.BuildPackage(
76 &types.Config{Importer: importer.Default()}, fset, pkg, files, ir.SanityCheckFunctions)
77 if err != nil {
78 fmt.Print(err) // type error in some package
79 return
80 }
81
82 // Print out the package.
83 hello.WriteTo(os.Stdout)
84
85 // Print out the package-level functions.
86 hello.Func("init").WriteTo(os.Stdout)
87 hello.Func("main").WriteTo(os.Stdout)
88
89 // Output:
90 //
91 // package hello:
92 // func init func()
93 // var init$guard bool
94 // func main func()
95 // const message message = "Hello, World!":untyped string
96 //
97 // # Name: hello.init
98 // # Package: hello
99 // # Synthetic: package initializer
100 // func init():
101 // 0: entry P:0 S:2
102 // t1 = *init$guard bool
103 // if t1 goto 2 else 1
104 // 1: init.start P:1 S:1 idom:0
105 // *init$guard = true:bool
106 // t4 = fmt.init() ()
107 // jump 2
108 // 2: init.done P:2 S:0 idom:0
109 // return
110 //
111 // # Name: hello.main
112 // # Package: hello
113 // # Location: hello.go:8:6
114 // func main():
115 // 0: entry P:0 S:0
116 // t1 = new [1]any (varargs) *[1]any
117 // t2 = &t1[0:int] *any
118 // t3 = make any <- string ("Hello, World!":string) any
119 // *t2 = t3
120 // t5 = slice t1[:] []any
121 // t6 = fmt.Println(t5...) (n int, err error)
122 // return
123 }
124
125 // This example builds IR code for a set of packages using the
126 // [golang.org/x/tools/go/packages] API. This is what you would typically use for a
127 // analysis capable of operating on a single package.
128 func Example_loadPackages() {
129 // Load, parse, and type-check the initial packages.
130 cfg := &packages.Config{Mode: packages.LoadSyntax}
131 initial, err := packages.Load(cfg, "fmt", "net/http")
132 if err != nil {
133 log.Fatal(err)
134 }
135
136 // Stop if any package had errors.
137 // This step is optional; without it, the next step
138 // will create IR for only a subset of packages.
139 if packages.PrintErrors(initial) > 0 {
140 log.Fatalf("packages contain errors")
141 }
142
143 // Create IR packages for all well-typed packages.
144 prog, pkgs := irutil.Packages(initial, ir.PrintPackages)
145 _ = prog
146
147 // Build IR code for the well-typed initial packages.
148 for _, p := range pkgs {
149 if p != nil {
150 p.Build()
151 }
152 }
153 }
154
155 // This example builds IR code for a set of packages plus all their dependencies,
156 // using the [golang.org/x/tools/go/packages] API.
157 // This is what you'd typically use for a whole-program analysis.
158 func Example_loadWholeProgram() {
159 // Load, parse, and type-check the whole program.
160 cfg := packages.Config{Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedDeps}
161 initial, err := packages.Load(&cfg, "fmt", "net/http")
162 if err != nil {
163 log.Fatal(err)
164 }
165
166 // Create IR packages for well-typed packages and their dependencies.
167 prog, pkgs := irutil.AllPackages(initial, ir.PrintPackages|ir.InstantiateGenerics)
168 _ = pkgs
169
170 // Build IR code for the whole program.
171 prog.Build()
172 }