ExampleScope prints the tree of Scopes of a package created from a set of parsed files.
()
| 31 | // ExampleScope prints the tree of Scopes of a package created from a |
| 32 | // set of parsed files. |
| 33 | func ExampleScope() { |
| 34 | // Parse the source files for a package. |
| 35 | var files []*File |
| 36 | for _, file := range []struct{ name, input string }{ |
| 37 | {"main.go", ` |
| 38 | package main |
| 39 | import "fmt" |
| 40 | func main() { |
| 41 | freezing := FToC(-18) |
| 42 | fmt.Println(freezing, Boiling) } |
| 43 | `}, |
| 44 | {"celsius.go", ` |
| 45 | package main |
| 46 | import "fmt" |
| 47 | type Celsius float64 |
| 48 | func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) } |
| 49 | func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) } |
| 50 | const Boiling Celsius = 100 |
| 51 | func 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 { |