Trace AST name resolution and type checking
Trace AST name resolution and type checking
An abstract syntax tree (AST) describes syntactic structure. Name resolution connects uses of identifiers to declarations in lexical scopes, including shadowing. Type checking validates assignments, calls and operators. The public go/types package records facts in types.Info maps when requested; the compiler uses its internal types2 checker and constructs Unified IR from checked code. These APIs support analyzers, not execution of source code.
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func main() { fs := token.NewFileSet() f, err := parser.ParseFile(fs, "p.go", `package p; var n=1; func f(){n:="local"; _=n}; var v=n`, 0) if err != nil { panic(err) } info := types.Info{Uses: map[*ast.Ident]types.Object{}} conf := types.Config{} _, err = conf.Check("p", fs, []*ast.File{f}, &info) if err != nil { panic(err) } ast.Inspect(f, func(n ast.Node) bool { if id, ok := n.(*ast.Ident); ok && id.Name == "n" && info.Uses[id] != nil { fmt.Println(info.Uses[id].Type()) } return true })}The two uses of n refer to different declarations. Local shadowing changes the binding, not the package variable. AST traversal gives source order; ranging over the Uses map would not guarantee that order. Request Defs, Uses, Types or Scopes only when needed. Check errors before treating type information as complete.
Expected output:
stringintValid syntax can have invalid types
package main
import ( "fmt" "go/ast" "go/parser" "go/token" "go/types")
func main() { fs := token.NewFileSet() f, err := parser.ParseFile(fs, "p.go", `package p; var n int = "wrong"`, 0) fmt.Println(err == nil) conf := types.Config{} _, err = conf.Check("p", fs, []*ast.File{f}, nil) fmt.Println(err != nil)}The declaration parses but the string cannot be assigned to int. A checker with Config.Error can collect multiple errors; do not generate code from invalid types. For a package importing dependencies, configure an appropriate Importer and respect build constraints; checking one snippet is not a full package build.
Expected output:
truetrueTry it locally
Check package p; var a = 2; var b = a + 3 and print the type of b from the checked package scope. Then check package p; var b = missing and print whether an error occurred.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler pipeline 02: Trace AST name resolution and type checking
Check the lesson objective before moving on.
What can distinguish two shadowed identifiers?
Can a parsed AST still fail type checking?