MCPcopy Create free account
hub / github.com/despiteallobjections/amigo / ExampleScope

Function ExampleScope

types/example_test.go:33–109  ·  view source on GitHub ↗

ExampleScope prints the tree of Scopes of a package created from a set of parsed files.

()

Source from the content-addressed store, hash-verified

31// ExampleScope prints the tree of Scopes of a package created from a
32// set of parsed files.
33func ExampleScope() {
34 // Parse the source files for a package.
35 var files []*File
36 for _, file := range []struct{ name, input string }{
37 {"main.go", `
38package main
39import "fmt"
40func main() {
41 freezing := FToC(-18)
42 fmt.Println(freezing, Boiling) }
43`},
44 {"celsius.go", `
45package main
46import "fmt"
47type Celsius float64
48func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
49func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
50const Boiling Celsius = 100
51func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
52`},
53 } {
54 f, err := parseSrc(file.name, file.input)
55 if err != nil {
56 log.Fatal(err)
57 }
58 files = append(files, f)
59 }
60
61 // Type-check a package consisting of these files.
62 // Type information for the imported "fmt" package
63 // comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
64 conf := types.Config{Importer: defaultImporter()}
65 pkg, err := conf.Check("temperature", files, nil)
66 if err != nil {
67 log.Fatal(err)
68 }
69
70 // Print the tree of scopes.
71 // For determinism, we redact addresses.
72 var buf bytes.Buffer
73 pkg.Scope().WriteTo(&buf, 0, true)
74 rx := regexp.MustCompile(` 0x[a-fA-F0-9]*`)
75 fmt.Println(rx.ReplaceAllString(buf.String(), ""))
76
77 // Output:
78 // package "temperature" scope {
79 // . const temperature.Boiling temperature.Celsius
80 // . type temperature.Celsius float64
81 // . func temperature.FToC(f float64) temperature.Celsius
82 // . func temperature.Unused()
83 // . func temperature.main()
84 // . main.go scope {
85 // . . package fmt
86 // . . function scope {
87 // . . . var freezing temperature.Celsius
88 // . . }
89 // . }
90 // . celsius.go scope {

Callers

nothing calls this directly

Calls 6

CheckMethod · 0.95
StringMethod · 0.95
parseSrcFunction · 0.85
appendFunction · 0.50
WriteToMethod · 0.45
ScopeMethod · 0.45

Tested by

no test coverage detected