Source file src/go/types/example_test.go

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

View as plain text