Source file src/go/types/check_test.go

     1  // Copyright 2011 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  // This file implements a typechecker test harness. The packages specified
     6  // in tests are typechecked. Error messages reported by the typechecker are
     7  // compared against the errors expected in the test files.
     8  //
     9  // Expected errors are indicated in the test files by putting comments
    10  // of the form /* ERROR pattern */ or /* ERRORx pattern */ (or a similar
    11  // //-style line comment) immediately following the tokens where errors
    12  // are reported. There must be exactly one blank before and after the
    13  // ERROR/ERRORx indicator, and the pattern must be a properly quoted Go
    14  // string.
    15  //
    16  // The harness will verify that each ERROR pattern is a substring of the
    17  // error reported at that source position, and that each ERRORx pattern
    18  // is a regular expression matching the respective error.
    19  // Consecutive comments may be used to indicate multiple errors reported
    20  // at the same position.
    21  //
    22  // For instance, the following test source indicates that an "undeclared"
    23  // error should be reported for the undeclared variable x:
    24  //
    25  //	package p
    26  //	func f() {
    27  //		_ = x /* ERROR "undeclared" */ + 1
    28  //	}
    29  
    30  package types_test
    31  
    32  import (
    33  	"bytes"
    34  	"flag"
    35  	"fmt"
    36  	"go/ast"
    37  	"go/build"
    38  	"go/build/constraint"
    39  	"go/parser"
    40  	"go/scanner"
    41  	"go/token"
    42  	"internal/buildcfg"
    43  	"internal/testenv"
    44  	"internal/types/errors"
    45  	"os"
    46  	"path/filepath"
    47  	"reflect"
    48  	"regexp"
    49  	"runtime"
    50  	"slices"
    51  	"strconv"
    52  	"strings"
    53  	"testing"
    54  
    55  	. "go/types"
    56  )
    57  
    58  var (
    59  	haltOnError  = flag.Bool("halt", false, "halt on error")
    60  	verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
    61  )
    62  
    63  var fset = token.NewFileSet()
    64  
    65  func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
    66  	var files []*ast.File
    67  	var errlist []error
    68  	for i, filename := range filenames {
    69  		file, err := parser.ParseFile(fset, filename, srcs[i], mode)
    70  		if file == nil {
    71  			t.Fatalf("%s: %s", filename, err)
    72  		}
    73  		files = append(files, file)
    74  		if err != nil {
    75  			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
    76  				for _, err := range list {
    77  					errlist = append(errlist, err)
    78  				}
    79  			} else {
    80  				errlist = append(errlist, err)
    81  			}
    82  		}
    83  	}
    84  	return files, errlist
    85  }
    86  
    87  func unpackError(fset *token.FileSet, err error) (token.Position, string) {
    88  	switch err := err.(type) {
    89  	case *scanner.Error:
    90  		return err.Pos, err.Msg
    91  	case Error:
    92  		return fset.Position(err.Pos), err.Msg
    93  	}
    94  	panic("unreachable")
    95  }
    96  
    97  // absDiff returns the absolute difference between x and y.
    98  func absDiff(x, y int) int {
    99  	if x < y {
   100  		return y - x
   101  	}
   102  	return x - y
   103  }
   104  
   105  // parseFlags parses flags from the first line of the given source if the line
   106  // starts with "//" (line comment) followed by "-" (possibly with spaces
   107  // between). Otherwise the line is ignored.
   108  func parseFlags(src []byte, flags *flag.FlagSet) error {
   109  	// we must have a line comment that starts with a "-"
   110  	const prefix = "//"
   111  	if !bytes.HasPrefix(src, []byte(prefix)) {
   112  		return nil // first line is not a line comment
   113  	}
   114  	src = src[len(prefix):]
   115  	if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
   116  		return nil // comment doesn't start with a "-"
   117  	}
   118  	end := bytes.Index(src, []byte("\n"))
   119  	const maxLen = 256
   120  	if end < 0 || end > maxLen {
   121  		return fmt.Errorf("flags comment line too long")
   122  	}
   123  
   124  	return flags.Parse(strings.Fields(string(src[:end])))
   125  }
   126  
   127  // testFiles type-checks the package consisting of the given files, and
   128  // compares the resulting errors with the ERROR annotations in the source.
   129  //
   130  // The srcs slice contains the file content for the files named in the
   131  // filenames slice. The colDelta parameter specifies the tolerance for position
   132  // mismatch when comparing errors. The manual parameter specifies whether this
   133  // is a 'manual' test.
   134  //
   135  // If provided, opts may be used to mutate the Config before type-checking.
   136  func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
   137  	if len(filenames) == 0 {
   138  		t.Fatal("no source files")
   139  	}
   140  
   141  	// parse files
   142  	files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors|parser.SkipObjectResolution)
   143  	pkgName := "<no package>"
   144  	if len(files) > 0 {
   145  		pkgName = files[0].Name.Name
   146  	}
   147  	listErrors := manual && !*verifyErrors
   148  	if listErrors && len(errlist) > 0 {
   149  		t.Errorf("--- %s:", pkgName)
   150  		for _, err := range errlist {
   151  			t.Error(err)
   152  		}
   153  	}
   154  
   155  	// set up typechecker
   156  	var conf Config
   157  	*boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
   158  	conf.Importer = defaultImporter(fset)
   159  	conf.Error = func(err error) {
   160  		if *haltOnError {
   161  			defer panic(err)
   162  		}
   163  		if listErrors {
   164  			t.Error(err)
   165  			return
   166  		}
   167  		// Ignore secondary error messages starting with "\t";
   168  		// they are clarifying messages for a primary error.
   169  		if !strings.Contains(err.Error(), ": \t") {
   170  			errlist = append(errlist, err)
   171  		}
   172  	}
   173  
   174  	// apply custom configuration
   175  	for _, opt := range opts {
   176  		opt(&conf)
   177  	}
   178  
   179  	// apply flag setting (overrides custom configuration)
   180  	var goexperiment string
   181  	flags := flag.NewFlagSet("", flag.PanicOnError)
   182  	flags.StringVar(&conf.GoVersion, "lang", "", "")
   183  	flags.StringVar(&goexperiment, "goexperiment", "", "")
   184  	flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
   185  	if err := parseFlags(srcs[0], flags); err != nil {
   186  		t.Fatal(err)
   187  	}
   188  
   189  	if goexperiment != "" {
   190  		revert := setGOEXPERIMENT(goexperiment)
   191  		defer revert()
   192  	}
   193  
   194  	// Provide Config.Info with all maps so that info recording is tested.
   195  	info := Info{
   196  		Types:        make(map[ast.Expr]TypeAndValue),
   197  		Instances:    make(map[*ast.Ident]Instance),
   198  		Defs:         make(map[*ast.Ident]Object),
   199  		Uses:         make(map[*ast.Ident]Object),
   200  		Implicits:    make(map[ast.Node]Object),
   201  		Selections:   make(map[*ast.SelectorExpr]*Selection),
   202  		Scopes:       make(map[ast.Node]*Scope),
   203  		FileVersions: make(map[*ast.File]string),
   204  	}
   205  
   206  	// typecheck
   207  	conf.Check(pkgName, fset, files, &info)
   208  	if listErrors {
   209  		return
   210  	}
   211  
   212  	// collect expected errors
   213  	errmap := make(map[string]map[int][]comment)
   214  	for i, filename := range filenames {
   215  		if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
   216  			errmap[filename] = m
   217  		}
   218  	}
   219  
   220  	// match against found errors
   221  	var indices []int // list indices of matching errors, reused for each error
   222  	for _, err := range errlist {
   223  		gotPos, gotMsg := unpackError(fset, err)
   224  
   225  		// find list of errors for the respective error line
   226  		filename := gotPos.Filename
   227  		filemap := errmap[filename]
   228  		line := gotPos.Line
   229  		var errList []comment
   230  		if filemap != nil {
   231  			errList = filemap[line]
   232  		}
   233  
   234  		// At least one of the errors in errList should match the current error.
   235  		indices = indices[:0]
   236  		for i, want := range errList {
   237  			pattern, substr := strings.CutPrefix(want.text, " ERROR ")
   238  			if !substr {
   239  				var found bool
   240  				pattern, found = strings.CutPrefix(want.text, " ERRORx ")
   241  				if !found {
   242  					panic("unreachable")
   243  				}
   244  			}
   245  			unquoted, err := strconv.Unquote(strings.TrimSpace(pattern))
   246  			if err != nil {
   247  				t.Errorf("%s:%d:%d: invalid ERROR pattern (cannot unquote %s)", filename, line, want.col, pattern)
   248  				continue
   249  			}
   250  			if substr {
   251  				if !strings.Contains(gotMsg, unquoted) {
   252  					continue
   253  				}
   254  			} else {
   255  				rx, err := regexp.Compile(unquoted)
   256  				if err != nil {
   257  					t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
   258  					continue
   259  				}
   260  				if !rx.MatchString(gotMsg) {
   261  					continue
   262  				}
   263  			}
   264  			indices = append(indices, i)
   265  		}
   266  		if len(indices) == 0 {
   267  			t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
   268  			continue
   269  		}
   270  		// len(indices) > 0
   271  
   272  		// If there are multiple matching errors, select the one with the closest column position.
   273  		index := -1 // index of matching error
   274  		var delta int
   275  		for _, i := range indices {
   276  			if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
   277  				index, delta = i, d
   278  			}
   279  		}
   280  
   281  		// The closest column position must be within expected colDelta.
   282  		const colDelta = 0 // go/types errors are positioned correctly
   283  		if delta > colDelta {
   284  			t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
   285  		}
   286  
   287  		// eliminate from errList
   288  		if n := len(errList) - 1; n > 0 {
   289  			// not the last entry - slide entries down (don't reorder)
   290  			copy(errList[index:], errList[index+1:])
   291  			filemap[line] = errList[:n]
   292  		} else {
   293  			// last entry - remove errList from filemap
   294  			delete(filemap, line)
   295  		}
   296  
   297  		// if filemap is empty, eliminate from errmap
   298  		if len(filemap) == 0 {
   299  			delete(errmap, filename)
   300  		}
   301  	}
   302  
   303  	// there should be no expected errors left
   304  	if len(errmap) > 0 {
   305  		t.Errorf("--- %s: unreported errors:", pkgName)
   306  		for filename, filemap := range errmap {
   307  			for line, errList := range filemap {
   308  				for _, err := range errList {
   309  					t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
   310  				}
   311  			}
   312  		}
   313  	}
   314  }
   315  
   316  func readCode(err Error) errors.Code {
   317  	v := reflect.ValueOf(err)
   318  	return errors.Code(v.FieldByName("go116code").Int())
   319  }
   320  
   321  // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
   322  // For accessing unexported fields.
   323  func boolFieldAddr(conf *Config, name string) *bool {
   324  	v := reflect.Indirect(reflect.ValueOf(conf))
   325  	return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
   326  }
   327  
   328  // stringFieldAddr(conf, name) returns the address of the string field conf.<name>.
   329  // For accessing unexported fields.
   330  func stringFieldAddr(conf *Config, name string) *string {
   331  	v := reflect.Indirect(reflect.ValueOf(conf))
   332  	return (*string)(v.FieldByName(name).Addr().UnsafePointer())
   333  }
   334  
   335  // setGOEXPERIMENT overwrites the existing buildcfg.Experiment with a new one
   336  // based on the provided goexperiment string. Calling the result function
   337  // (typically via defer), reverts buildcfg.Experiment to the prior value.
   338  // For testing use, only.
   339  func setGOEXPERIMENT(goexperiment string) func() {
   340  	exp, err := buildcfg.ParseGOEXPERIMENT(runtime.GOOS, runtime.GOARCH, goexperiment)
   341  	if err != nil {
   342  		panic(err)
   343  	}
   344  	old := buildcfg.Experiment
   345  	buildcfg.Experiment = *exp
   346  	return func() { buildcfg.Experiment = old }
   347  }
   348  
   349  // TestManual is for manual testing of a package - either provided
   350  // as a list of filenames belonging to the package, or a directory
   351  // name containing the package files - after the test arguments
   352  // (and a separating "--"). For instance, to test the package made
   353  // of the files foo.go and bar.go, use:
   354  //
   355  //	go test -run Manual -- foo.go bar.go
   356  //
   357  // If no source arguments are provided, the file testdata/manual.go
   358  // is used instead.
   359  // Provide the -verify flag to verify errors against ERROR comments
   360  // in the input files rather than having a list of errors reported.
   361  // The accepted Go language version can be controlled with the -lang
   362  // flag.
   363  func TestManual(t *testing.T) {
   364  	testenv.MustHaveGoBuild(t)
   365  
   366  	filenames := flag.Args()
   367  	if len(filenames) == 0 {
   368  		filenames = []string{filepath.FromSlash("testdata/manual.go")}
   369  	}
   370  
   371  	info, err := os.Stat(filenames[0])
   372  	if err != nil {
   373  		t.Fatalf("TestManual: %v", err)
   374  	}
   375  
   376  	DefPredeclaredTestFuncs()
   377  	if info.IsDir() {
   378  		if len(filenames) > 1 {
   379  			t.Fatal("TestManual: must have only one directory argument")
   380  		}
   381  		testDir(t, filenames[0], true)
   382  	} else {
   383  		testPkg(t, filenames, true)
   384  	}
   385  }
   386  
   387  func TestLongConstants(t *testing.T) {
   388  	format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
   389  	src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
   390  	testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
   391  }
   392  
   393  func withSizes(sizes Sizes) func(*Config) {
   394  	return func(cfg *Config) {
   395  		cfg.Sizes = sizes
   396  	}
   397  }
   398  
   399  // TestIndexRepresentability tests that constant index operands must
   400  // be representable as int even if they already have a type that can
   401  // represent larger values.
   402  func TestIndexRepresentability(t *testing.T) {
   403  	const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
   404  	testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
   405  }
   406  
   407  func TestIssue47243_TypedRHS(t *testing.T) {
   408  	// The RHS of the shift expression below overflows uint on 32bit platforms,
   409  	// but this is OK as it is explicitly typed.
   410  	const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
   411  	testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
   412  }
   413  
   414  func TestCheck(t *testing.T) {
   415  	DefPredeclaredTestFuncs()
   416  	testDirFiles(t, "../../internal/types/testdata/check", false)
   417  }
   418  func TestSpec(t *testing.T)      { testDirFiles(t, "../../internal/types/testdata/spec", false) }
   419  func TestExamples(t *testing.T)  { testDirFiles(t, "../../internal/types/testdata/examples", false) }
   420  func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
   421  func TestLocal(t *testing.T)     { testDirFiles(t, "testdata/local", false) }
   422  
   423  func testDirFiles(t *testing.T, dir string, manual bool) {
   424  	testenv.MustHaveGoBuild(t)
   425  	dir = filepath.FromSlash(dir)
   426  
   427  	fis, err := os.ReadDir(dir)
   428  	if err != nil {
   429  		t.Error(err)
   430  		return
   431  	}
   432  
   433  	for _, fi := range fis {
   434  		path := filepath.Join(dir, fi.Name())
   435  
   436  		// If fi is a directory, its files make up a single package.
   437  		if fi.IsDir() {
   438  			testDir(t, path, manual)
   439  		} else {
   440  			t.Run(filepath.Base(path), func(t *testing.T) {
   441  				testPkg(t, []string{path}, manual)
   442  			})
   443  		}
   444  	}
   445  }
   446  
   447  func testDir(t *testing.T, dir string, manual bool) {
   448  	testenv.MustHaveGoBuild(t)
   449  
   450  	fis, err := os.ReadDir(dir)
   451  	if err != nil {
   452  		t.Error(err)
   453  		return
   454  	}
   455  
   456  	var filenames []string
   457  	for _, fi := range fis {
   458  		filenames = append(filenames, filepath.Join(dir, fi.Name()))
   459  	}
   460  
   461  	t.Run(filepath.Base(dir), func(t *testing.T) {
   462  		testPkg(t, filenames, manual)
   463  	})
   464  }
   465  
   466  func testPkg(t *testing.T, filenames []string, manual bool) {
   467  	fs := filenames[:0]
   468  	srcs := make([][]byte, 0, len(filenames))
   469  	for _, filename := range filenames {
   470  		src, err := os.ReadFile(filename)
   471  		if err != nil {
   472  			t.Fatalf("could not read %s: %v", filename, err)
   473  		}
   474  		if !shouldTest(src) {
   475  			continue
   476  		}
   477  		fs = append(fs, filename)
   478  		srcs = append(srcs, src)
   479  	}
   480  	if len(fs) == 0 {
   481  		t.Skip("all files skipped by build tags")
   482  	}
   483  	testFiles(t, fs, srcs, manual)
   484  }
   485  
   486  // shouldTest checks build tags in src and returns whether the file
   487  // should be tested according to the tags.
   488  func shouldTest(src []byte) bool {
   489  	match := func(tag string) bool {
   490  		// We only care GOOS, GOARCH, and go version tags.
   491  		if slices.Contains(build.Default.ReleaseTags, tag) {
   492  			return true
   493  		}
   494  		return tag == runtime.GOOS || tag == runtime.GOARCH
   495  	}
   496  	for line := range strings.SplitSeq(string(src), "\n") {
   497  		if strings.HasPrefix(line, "package ") {
   498  			break
   499  		}
   500  		if expr, err := constraint.Parse(line); err == nil {
   501  			return expr.Eval(match)
   502  		}
   503  	}
   504  	return true
   505  }
   506  

View as plain text