Resolve symbol identity with go/types
Resolve symbol identity with go/types
Two identifiers with identical text may refer to different declarations. A refactoring needs object identity, not spelling. Populate types.Info.Defs and Uses before calling Config.Check. The keys are AST identifier pointers, and the values are types.Object values representing declarations. Check the returned error before using semantic results.
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func main() { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", "package p; var n=1; func work(){n:=2;_=n}; var copy=n", 0) if e != nil { panic(e) } info := types.Info{Defs: map[*ast.Ident]types.Object{}, Uses: map[*ast.Ident]types.Object{}} pkg, e := new(types.Config).Check("example/p", fs, []*ast.File{f}, &info) if e != nil { panic(e) } global := pkg.Scope().Lookup("n") ast.Inspect(f, func(node ast.Node) bool { if id, ok := node.(*ast.Ident); ok && id.Name == "n" && info.Uses[id] != nil { fmt.Println(info.Uses[id] == global) } return true })}The use inside work resolves to the local declaration. The final initializer resolves to the package variable. Traversal order is source order here; ranging over the maps would not guarantee it. For imports, package loading must respect the build environment; a one-file parser is not enough for full modules.
Expected output:
falsetrueInspect expression types and reject invalid code
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func main() { fs := token.NewFileSet() f, e := parser.ParseFile(fs, "p.go", "package p; var n=1+2", 0) if e != nil { panic(e) } info := types.Info{Types: map[ast.Expr]types.TypeAndValue{}} _, e = new(types.Config).Check("p", fs, []*ast.File{f}, &info) if e != nil { panic(e) } ast.Inspect(f, func(n ast.Node) bool { if x, ok := n.(*ast.BinaryExpr); ok { fmt.Println(info.TypeOf(x)) } return true }) bad, e := parser.ParseFile(fs, "bad.go", `package q; var x int = "s"`, 0) if e != nil { panic(e) } _, e = new(types.Config).Check("q", fs, []*ast.File{bad}, nil) fmt.Println(e != nil)}The variable initializer is contextually converted to int. A string assigned to an int is grammatically valid but fails type checking. For general tools request Types, Selections and Instances as needed; a missing entry is not a proof of an invalid program.
Expected output:
inttrueTry it locally
Type-check package p; var n int64 = 3; var copy = n and print the type of the object copy.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Developer tooling 03: Resolve symbol identity with go/types
Check the lesson objective before moving on.
What distinguishes two shadowed names?
Why allocate Info.Uses before checking?