ExampleInfo prints various facts recorded by the type checker in a types.Info struct: definitions of and references to each named object, and the type, value, and mode of every expression in the package.
()
| 112 | // types.Info struct: definitions of and references to each named object, |
| 113 | // and the type, value, and mode of every expression in the package. |
| 114 | func ExampleInfo() { |
| 115 | // Parse a single source file. |
| 116 | const input = ` |
| 117 | package fib |
| 118 | |
| 119 | type S string |
| 120 | |
| 121 | var a, b, c = len(b), S(c), "hello" |
| 122 | |
| 123 | func fib(x int) int { |
| 124 | if x < 2 { |
| 125 | return x |
| 126 | } |
| 127 | return fib(x-1) - fib(x-2) |
| 128 | }` |
| 129 | f, err := parseSrc("fib.go", input) |
| 130 | if err != nil { |
| 131 | log.Fatal(err) |
| 132 | } |
| 133 | |
| 134 | // Type-check the package. |
| 135 | // We create an empty map for each kind of input |
| 136 | // we're interested in, and Check populates them. |
| 137 | info := types.Info{ |
| 138 | Types: make(map[Expr]types.TypeAndValue), |
| 139 | Defs: make(map[*Name]types.Object), |
| 140 | Uses: make(map[*Name]types.Object), |
| 141 | } |
| 142 | var conf types.Config |
| 143 | pkg, err := conf.Check("fib", []*File{f}, &info) |
| 144 | if err != nil { |
| 145 | log.Fatal(err) |
| 146 | } |
| 147 | |
| 148 | // Print package-level variables in initialization order. |
| 149 | fmt.Printf("InitOrder: %v\n\n", info.InitOrder) |
| 150 | |
| 151 | // For each named object, print the line and |
| 152 | // column of its definition and each of its uses. |
| 153 | fmt.Println("Defs and Uses of each named object:") |
| 154 | usesByObj := make(map[types.Object][]string) |
| 155 | for id, obj := range info.Uses { |
| 156 | posn := id.Pos() |
| 157 | lineCol := fmt.Sprintf("%d:%d", posn.Line(), posn.Col()) |
| 158 | usesByObj[obj] = append(usesByObj[obj], lineCol) |
| 159 | } |
| 160 | var items []string |
| 161 | for obj, uses := range usesByObj { |
| 162 | sort.Strings(uses) |
| 163 | item := fmt.Sprintf("%s:\n defined at %s\n used at %s", |
| 164 | types.ObjectString(obj, types.RelativeTo(pkg)), |
| 165 | obj.Pos(), |
| 166 | strings.Join(uses, ", ")) |
| 167 | items = append(items, item) |
| 168 | } |
| 169 | sort.Strings(items) // sort by line:col, in effect |
| 170 | fmt.Println(strings.Join(items, "\n")) |
| 171 | fmt.Println() |
nothing calls this directly
no test coverage detected