...

Source file src/go/types/example_test.go

Documentation: go/types

     1  // Copyright 2015 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Only run where builders (build.golang.org) have
     6  // access to compiled packages for import.
     7  //
     8  //go:build !android && !ios && !js && !wasip1
     9  
    10  package types_test
    11  
    12  // This file shows examples of basic usage of the go/types API.
    13  //
    14  // To locate a Go package, use (*go/build.Context).Import.
    15  // To load, parse, and type-check a complete Go program
    16  // from source, use golang.org/x/tools/go/loader.
    17  
    18  import (
    19  	"fmt"
    20  	"go/ast"
    21  	"go/format"
    22  	"go/token"
    23  	"go/types"
    24  	"log"
    25  	"regexp"
    26  	"slices"
    27  	"strings"
    28  )
    29  
    30  // ExampleScope prints the tree of Scopes of a package created from a
    31  // set of parsed files.
    32  func ExampleScope() {
    33  	// Parse the source files for a package.
    34  	fset := token.NewFileSet()
    35  	var files []*ast.File
    36  	for _, src := range []string{
    37  		`package main
    38  import "fmt"
    39  func main() {
    40  	freezing := FToC(-18)
    41  	fmt.Println(freezing, Boiling) }
    42  `,
    43  		`package main
    44  import "fmt"
    45  type Celsius float64
    46  func (c Celsius) String() string { return fmt.Sprintf("%g°C", c) }
    47  func FToC(f float64) Celsius { return Celsius(f - 32 / 9 * 5) }
    48  const Boiling Celsius = 100
    49  func Unused() { {}; {{ var x int; _ = x }} } // make sure empty block scopes get printed
    50  `,
    51  	} {
    52  		files = append(files, mustParse(fset, src))
    53  	}
    54  
    55  	// Type-check a package consisting of these files.
    56  	// Type information for the imported "fmt" package
    57  	// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
    58  	conf := types.Config{Importer: defaultImporter(fset)}
    59  	pkg, err := conf.Check("temperature", fset, files, nil)
    60  	if err != nil {
    61  		log.Fatal(err)
    62  	}
    63  
    64  	// Print the tree of scopes.
    65  	// For determinism, we redact addresses.
    66  	var buf strings.Builder
    67  	pkg.Scope().WriteTo(&buf, 0, true)
    68  	rx := regexp.MustCompile(` 0x[a-fA-F\d]*`)
    69  	fmt.Println(rx.ReplaceAllString(buf.String(), ""))
    70  
    71  	// Output:
    72  	// package "temperature" scope {
    73  	// .  const temperature.Boiling temperature.Celsius
    74  	// .  type temperature.Celsius float64
    75  	// .  func temperature.FToC(f float64) temperature.Celsius
    76  	// .  func temperature.Unused()
    77  	// .  func temperature.main()
    78  	// .  main scope {
    79  	// .  .  package fmt
    80  	// .  .  function scope {
    81  	// .  .  .  var freezing temperature.Celsius
    82  	// .  .  }
    83  	// .  }
    84  	// .  main scope {
    85  	// .  .  package fmt
    86  	// .  .  function scope {
    87  	// .  .  .  var c temperature.Celsius
    88  	// .  .  }
    89  	// .  .  function scope {
    90  	// .  .  .  var f float64
    91  	// .  .  }
    92  	// .  .  function scope {
    93  	// .  .  .  block scope {
    94  	// .  .  .  }
    95  	// .  .  .  block scope {
    96  	// .  .  .  .  block scope {
    97  	// .  .  .  .  .  var x int
    98  	// .  .  .  .  }
    99  	// .  .  .  }
   100  	// .  .  }
   101  	// .  }
   102  	// }
   103  }
   104  
   105  // ExampleMethodSet prints the method sets of various types.
   106  func ExampleMethodSet() {
   107  	// Parse a single source file.
   108  	const input = `
   109  package temperature
   110  import "fmt"
   111  type Celsius float64
   112  func (c Celsius) String() string  { return fmt.Sprintf("%g°C", c) }
   113  func (c *Celsius) SetF(f float64) { *c = Celsius(f - 32 / 9 * 5) }
   114  
   115  type S struct { I; m int }
   116  type I interface { m() byte }
   117  `
   118  	fset := token.NewFileSet()
   119  	f := mustParse(fset, input)
   120  
   121  	// Type-check a package consisting of this file.
   122  	// Type information for the imported packages
   123  	// comes from $GOROOT/pkg/$GOOS_$GOOARCH/fmt.a.
   124  	conf := types.Config{Importer: defaultImporter(fset)}
   125  	pkg, err := conf.Check("temperature", fset, []*ast.File{f}, nil)
   126  	if err != nil {
   127  		log.Fatal(err)
   128  	}
   129  
   130  	// Print the method sets of Celsius and *Celsius.
   131  	celsius := pkg.Scope().Lookup("Celsius").Type()
   132  	for _, t := range []types.Type{celsius, types.NewPointer(celsius)} {
   133  		fmt.Printf("Method set of %s:\n", t)
   134  		for m := range types.NewMethodSet(t).Methods() {
   135  			fmt.Println(m)
   136  		}
   137  		fmt.Println()
   138  	}
   139  
   140  	// Print the method set of S.
   141  	styp := pkg.Scope().Lookup("S").Type()
   142  	fmt.Printf("Method set of %s:\n", styp)
   143  	fmt.Println(types.NewMethodSet(styp))
   144  
   145  	// Output:
   146  	// Method set of temperature.Celsius:
   147  	// method (temperature.Celsius) String() string
   148  	//
   149  	// Method set of *temperature.Celsius:
   150  	// method (*temperature.Celsius) SetF(f float64)
   151  	// method (*temperature.Celsius) String() string
   152  	//
   153  	// Method set of temperature.S:
   154  	// MethodSet {}
   155  }
   156  
   157  // ExampleInfo prints various facts recorded by the type checker in a
   158  // types.Info struct: definitions of and references to each named object,
   159  // and the type, value, and mode of every expression in the package.
   160  func ExampleInfo() {
   161  	// Parse a single source file.
   162  	const input = `
   163  package fib
   164  
   165  type S string
   166  
   167  var a, b, c = len(b), S(c), "hello"
   168  
   169  func fib(x int) int {
   170  	if x < 2 {
   171  		return x
   172  	}
   173  	return fib(x-1) - fib(x-2)
   174  }`
   175  	// We need a specific fileset in this test below for positions.
   176  	// Cannot use typecheck helper.
   177  	fset := token.NewFileSet()
   178  	f := mustParse(fset, input)
   179  
   180  	// Type-check the package.
   181  	// We create an empty map for each kind of input
   182  	// we're interested in, and Check populates them.
   183  	info := types.Info{
   184  		Types: make(map[ast.Expr]types.TypeAndValue),
   185  		Defs:  make(map[*ast.Ident]types.Object),
   186  		Uses:  make(map[*ast.Ident]types.Object),
   187  	}
   188  	var conf types.Config
   189  	pkg, err := conf.Check("fib", fset, []*ast.File{f}, &info)
   190  	if err != nil {
   191  		log.Fatal(err)
   192  	}
   193  
   194  	// Print package-level variables in initialization order.
   195  	fmt.Printf("InitOrder: %v\n\n", info.InitOrder)
   196  
   197  	// For each named object, print the line and
   198  	// column of its definition and each of its uses.
   199  	fmt.Println("Defs and Uses of each named object:")
   200  	usesByObj := make(map[types.Object][]string)
   201  	for id, obj := range info.Uses {
   202  		posn := fset.Position(id.Pos())
   203  		lineCol := fmt.Sprintf("%d:%d", posn.Line, posn.Column)
   204  		usesByObj[obj] = append(usesByObj[obj], lineCol)
   205  	}
   206  	var items []string
   207  	for obj, uses := range usesByObj {
   208  		slices.Sort(uses)
   209  		item := fmt.Sprintf("%s:\n  defined at %s\n  used at %s",
   210  			types.ObjectString(obj, types.RelativeTo(pkg)),
   211  			fset.Position(obj.Pos()),
   212  			strings.Join(uses, ", "))
   213  		items = append(items, item)
   214  	}
   215  	slices.Sort(items) // sort by line:col, in effect
   216  	fmt.Println(strings.Join(items, "\n"))
   217  	fmt.Println()
   218  
   219  	fmt.Println("Types and Values of each expression:")
   220  	items = nil
   221  	for expr, tv := range info.Types {
   222  		var buf strings.Builder
   223  		posn := fset.Position(expr.Pos())
   224  		tvstr := tv.Type.String()
   225  		if tv.Value != nil {
   226  			tvstr += " = " + tv.Value.String()
   227  		}
   228  		// line:col | expr | mode : type = value
   229  		fmt.Fprintf(&buf, "%2d:%2d | %-19s | %-7s : %s",
   230  			posn.Line, posn.Column, exprString(fset, expr),
   231  			mode(tv), tvstr)
   232  		items = append(items, buf.String())
   233  	}
   234  	slices.Sort(items)
   235  	fmt.Println(strings.Join(items, "\n"))
   236  
   237  	// Output:
   238  	// InitOrder: [c = "hello" b = S(c) a = len(b)]
   239  	//
   240  	// Defs and Uses of each named object:
   241  	// builtin len:
   242  	//   defined at -
   243  	//   used at 6:15
   244  	// func fib(x int) int:
   245  	//   defined at fib:8:6
   246  	//   used at 12:20, 12:9
   247  	// type S string:
   248  	//   defined at fib:4:6
   249  	//   used at 6:23
   250  	// type int:
   251  	//   defined at -
   252  	//   used at 8:12, 8:17
   253  	// type string:
   254  	//   defined at -
   255  	//   used at 4:8
   256  	// var b S:
   257  	//   defined at fib:6:8
   258  	//   used at 6:19
   259  	// var c string:
   260  	//   defined at fib:6:11
   261  	//   used at 6:25
   262  	// var x int:
   263  	//   defined at fib:8:10
   264  	//   used at 10:10, 12:13, 12:24, 9:5
   265  	//
   266  	// Types and Values of each expression:
   267  	//  4: 8 | string              | type    : string
   268  	//  6:15 | len                 | builtin : func(fib.S) int
   269  	//  6:15 | len(b)              | value   : int
   270  	//  6:19 | b                   | var     : fib.S
   271  	//  6:23 | S                   | type    : fib.S
   272  	//  6:23 | S(c)                | value   : fib.S
   273  	//  6:25 | c                   | var     : string
   274  	//  6:29 | "hello"             | value   : string = "hello"
   275  	//  8:12 | int                 | type    : int
   276  	//  8:17 | int                 | type    : int
   277  	//  9: 5 | x                   | var     : int
   278  	//  9: 5 | x < 2               | value   : untyped bool
   279  	//  9: 9 | 2                   | value   : int = 2
   280  	// 10:10 | x                   | var     : int
   281  	// 12: 9 | fib                 | value   : func(x int) int
   282  	// 12: 9 | fib(x - 1)          | value   : int
   283  	// 12: 9 | fib(x-1) - fib(x-2) | value   : int
   284  	// 12:13 | x                   | var     : int
   285  	// 12:13 | x - 1               | value   : int
   286  	// 12:15 | 1                   | value   : int = 1
   287  	// 12:20 | fib                 | value   : func(x int) int
   288  	// 12:20 | fib(x - 2)          | value   : int
   289  	// 12:24 | x                   | var     : int
   290  	// 12:24 | x - 2               | value   : int
   291  	// 12:26 | 2                   | value   : int = 2
   292  }
   293  
   294  func mode(tv types.TypeAndValue) string {
   295  	switch {
   296  	case tv.IsVoid():
   297  		return "void"
   298  	case tv.IsType():
   299  		return "type"
   300  	case tv.IsBuiltin():
   301  		return "builtin"
   302  	case tv.IsNil():
   303  		return "nil"
   304  	case tv.Assignable():
   305  		if tv.Addressable() {
   306  			return "var"
   307  		}
   308  		return "mapindex"
   309  	case tv.IsValue():
   310  		return "value"
   311  	default:
   312  		return "unknown"
   313  	}
   314  }
   315  
   316  func exprString(fset *token.FileSet, expr ast.Expr) string {
   317  	var buf strings.Builder
   318  	format.Node(&buf, fset, expr)
   319  	return buf.String()
   320  }
   321  

View as plain text