Debian Codegraph @

go/ssa/example_test.go

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