github.com/AndrienkoAleksandr/go@v0.0.19/src/go/types/check_test.go (about)

     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/importer"
    38  	"go/parser"
    39  	"go/scanner"
    40  	"go/token"
    41  	"internal/testenv"
    42  	"internal/types/errors"
    43  	"os"
    44  	"path/filepath"
    45  	"reflect"
    46  	"regexp"
    47  	"strconv"
    48  	"strings"
    49  	"testing"
    50  
    51  	. "go/types"
    52  )
    53  
    54  var (
    55  	haltOnError  = flag.Bool("halt", false, "halt on error")
    56  	verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
    57  )
    58  
    59  var fset = token.NewFileSet()
    60  
    61  func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
    62  	var files []*ast.File
    63  	var errlist []error
    64  	for i, filename := range filenames {
    65  		file, err := parser.ParseFile(fset, filename, srcs[i], mode)
    66  		if file == nil {
    67  			t.Fatalf("%s: %s", filename, err)
    68  		}
    69  		files = append(files, file)
    70  		if err != nil {
    71  			if list, _ := err.(scanner.ErrorList); len(list) > 0 {
    72  				for _, err := range list {
    73  					errlist = append(errlist, err)
    74  				}
    75  			} else {
    76  				errlist = append(errlist, err)
    77  			}
    78  		}
    79  	}
    80  	return files, errlist
    81  }
    82  
    83  func unpackError(fset *token.FileSet, err error) (token.Position, string) {
    84  	switch err := err.(type) {
    85  	case *scanner.Error:
    86  		return err.Pos, err.Msg
    87  	case Error:
    88  		return fset.Position(err.Pos), err.Msg
    89  	}
    90  	panic("unreachable")
    91  }
    92  
    93  // absDiff returns the absolute difference between x and y.
    94  func absDiff(x, y int) int {
    95  	if x < y {
    96  		return y - x
    97  	}
    98  	return x - y
    99  }
   100  
   101  // parseFlags parses flags from the first line of the given source if the line
   102  // starts with "//" (line comment) followed by "-" (possibly with spaces
   103  // between). Otherwise the line is ignored.
   104  func parseFlags(src []byte, flags *flag.FlagSet) error {
   105  	// we must have a line comment that starts with a "-"
   106  	const prefix = "//"
   107  	if !bytes.HasPrefix(src, []byte(prefix)) {
   108  		return nil // first line is not a line comment
   109  	}
   110  	src = src[len(prefix):]
   111  	if i := bytes.Index(src, []byte("-")); i < 0 || len(bytes.TrimSpace(src[:i])) != 0 {
   112  		return nil // comment doesn't start with a "-"
   113  	}
   114  	end := bytes.Index(src, []byte("\n"))
   115  	const maxLen = 256
   116  	if end < 0 || end > maxLen {
   117  		return fmt.Errorf("flags comment line too long")
   118  	}
   119  
   120  	return flags.Parse(strings.Fields(string(src[:end])))
   121  }
   122  
   123  // testFiles type-checks the package consisting of the given files, and
   124  // compares the resulting errors with the ERROR annotations in the source.
   125  //
   126  // The srcs slice contains the file content for the files named in the
   127  // filenames slice. The manual parameter specifies whether this is a 'manual'
   128  // test.
   129  //
   130  // If provided, opts may be used to mutate the Config before type-checking.
   131  func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
   132  	if len(filenames) == 0 {
   133  		t.Fatal("no source files")
   134  	}
   135  
   136  	var conf Config
   137  	flags := flag.NewFlagSet("", flag.PanicOnError)
   138  	flags.StringVar(&conf.GoVersion, "lang", "", "")
   139  	flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
   140  	if err := parseFlags(srcs[0], flags); err != nil {
   141  		t.Fatal(err)
   142  	}
   143  
   144  	files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
   145  
   146  	pkgName := "<no package>"
   147  	if len(files) > 0 {
   148  		pkgName = files[0].Name.Name
   149  	}
   150  
   151  	listErrors := manual && !*verifyErrors
   152  	if listErrors && len(errlist) > 0 {
   153  		t.Errorf("--- %s:", pkgName)
   154  		for _, err := range errlist {
   155  			t.Error(err)
   156  		}
   157  	}
   158  
   159  	// typecheck and collect typechecker errors
   160  	*boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
   161  	conf.Importer = importer.Default()
   162  	conf.Error = func(err error) {
   163  		if *haltOnError {
   164  			defer panic(err)
   165  		}
   166  		if listErrors {
   167  			t.Error(err)
   168  			return
   169  		}
   170  		// Ignore secondary error messages starting with "\t";
   171  		// they are clarifying messages for a primary error.
   172  		if !strings.Contains(err.Error(), ": \t") {
   173  			errlist = append(errlist, err)
   174  		}
   175  	}
   176  
   177  	for _, opt := range opts {
   178  		opt(&conf)
   179  	}
   180  
   181  	conf.Check(pkgName, fset, files, nil)
   182  
   183  	if listErrors {
   184  		return
   185  	}
   186  
   187  	// collect expected errors
   188  	errmap := make(map[string]map[int][]comment)
   189  	for i, filename := range filenames {
   190  		if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
   191  			errmap[filename] = m
   192  		}
   193  	}
   194  
   195  	// match against found errors
   196  	var indices []int // list indices of matching errors, reused for each error
   197  	for _, err := range errlist {
   198  		gotPos, gotMsg := unpackError(fset, err)
   199  
   200  		// find list of errors for the respective error line
   201  		filename := gotPos.Filename
   202  		filemap := errmap[filename]
   203  		line := gotPos.Line
   204  		var errList []comment
   205  		if filemap != nil {
   206  			errList = filemap[line]
   207  		}
   208  
   209  		// At least one of the errors in errList should match the current error.
   210  		indices = indices[:0]
   211  		for i, want := range errList {
   212  			pattern, substr := strings.CutPrefix(want.text, " ERROR ")
   213  			if !substr {
   214  				var found bool
   215  				pattern, found = strings.CutPrefix(want.text, " ERRORx ")
   216  				if !found {
   217  					panic("unreachable")
   218  				}
   219  			}
   220  			pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
   221  			if err != nil {
   222  				t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
   223  				continue
   224  			}
   225  			if substr {
   226  				if !strings.Contains(gotMsg, pattern) {
   227  					continue
   228  				}
   229  			} else {
   230  				rx, err := regexp.Compile(pattern)
   231  				if err != nil {
   232  					t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
   233  					continue
   234  				}
   235  				if !rx.MatchString(gotMsg) {
   236  					continue
   237  				}
   238  			}
   239  			indices = append(indices, i)
   240  		}
   241  		if len(indices) == 0 {
   242  			t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
   243  			continue
   244  		}
   245  		// len(indices) > 0
   246  
   247  		// If there are multiple matching errors, select the one with the closest column position.
   248  		index := -1 // index of matching error
   249  		var delta int
   250  		for _, i := range indices {
   251  			if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
   252  				index, delta = i, d
   253  			}
   254  		}
   255  
   256  		// The closest column position must be within expected colDelta.
   257  		const colDelta = 0 // go/types errors are positioned correctly
   258  		if delta > colDelta {
   259  			t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
   260  		}
   261  
   262  		// eliminate from errList
   263  		if n := len(errList) - 1; n > 0 {
   264  			// not the last entry - slide entries down (don't reorder)
   265  			copy(errList[index:], errList[index+1:])
   266  			filemap[line] = errList[:n]
   267  		} else {
   268  			// last entry - remove errList from filemap
   269  			delete(filemap, line)
   270  		}
   271  
   272  		// if filemap is empty, eliminate from errmap
   273  		if len(filemap) == 0 {
   274  			delete(errmap, filename)
   275  		}
   276  	}
   277  
   278  	// there should be no expected errors left
   279  	if len(errmap) > 0 {
   280  		t.Errorf("--- %s: unreported errors:", pkgName)
   281  		for filename, filemap := range errmap {
   282  			for line, errList := range filemap {
   283  				for _, err := range errList {
   284  					t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
   285  				}
   286  			}
   287  		}
   288  	}
   289  }
   290  
   291  func readCode(err Error) errors.Code {
   292  	v := reflect.ValueOf(err)
   293  	return errors.Code(v.FieldByName("go116code").Int())
   294  }
   295  
   296  // boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
   297  // For accessing unexported fields.
   298  func boolFieldAddr(conf *Config, name string) *bool {
   299  	v := reflect.Indirect(reflect.ValueOf(conf))
   300  	return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
   301  }
   302  
   303  // stringFieldAddr(conf, name) returns the address of the string field conf.<name>.
   304  // For accessing unexported fields.
   305  func stringFieldAddr(conf *Config, name string) *string {
   306  	v := reflect.Indirect(reflect.ValueOf(conf))
   307  	return (*string)(v.FieldByName(name).Addr().UnsafePointer())
   308  }
   309  
   310  // TestManual is for manual testing of a package - either provided
   311  // as a list of filenames belonging to the package, or a directory
   312  // name containing the package files - after the test arguments
   313  // (and a separating "--"). For instance, to test the package made
   314  // of the files foo.go and bar.go, use:
   315  //
   316  //	go test -run Manual -- foo.go bar.go
   317  //
   318  // If no source arguments are provided, the file testdata/manual.go
   319  // is used instead.
   320  // Provide the -verify flag to verify errors against ERROR comments
   321  // in the input files rather than having a list of errors reported.
   322  // The accepted Go language version can be controlled with the -lang
   323  // flag.
   324  func TestManual(t *testing.T) {
   325  	testenv.MustHaveGoBuild(t)
   326  
   327  	filenames := flag.Args()
   328  	if len(filenames) == 0 {
   329  		filenames = []string{filepath.FromSlash("testdata/manual.go")}
   330  	}
   331  
   332  	info, err := os.Stat(filenames[0])
   333  	if err != nil {
   334  		t.Fatalf("TestManual: %v", err)
   335  	}
   336  
   337  	DefPredeclaredTestFuncs()
   338  	if info.IsDir() {
   339  		if len(filenames) > 1 {
   340  			t.Fatal("TestManual: must have only one directory argument")
   341  		}
   342  		testDir(t, filenames[0], true)
   343  	} else {
   344  		testPkg(t, filenames, true)
   345  	}
   346  }
   347  
   348  func TestLongConstants(t *testing.T) {
   349  	format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
   350  	src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
   351  	testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
   352  }
   353  
   354  func withSizes(sizes Sizes) func(*Config) {
   355  	return func(cfg *Config) {
   356  		cfg.Sizes = sizes
   357  	}
   358  }
   359  
   360  // TestIndexRepresentability tests that constant index operands must
   361  // be representable as int even if they already have a type that can
   362  // represent larger values.
   363  func TestIndexRepresentability(t *testing.T) {
   364  	const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
   365  	testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
   366  }
   367  
   368  func TestIssue47243_TypedRHS(t *testing.T) {
   369  	// The RHS of the shift expression below overflows uint on 32bit platforms,
   370  	// but this is OK as it is explicitly typed.
   371  	const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
   372  	testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
   373  }
   374  
   375  func TestCheck(t *testing.T) {
   376  	DefPredeclaredTestFuncs()
   377  	testDirFiles(t, "../../internal/types/testdata/check", false)
   378  }
   379  func TestSpec(t *testing.T)      { testDirFiles(t, "../../internal/types/testdata/spec", false) }
   380  func TestExamples(t *testing.T)  { testDirFiles(t, "../../internal/types/testdata/examples", false) }
   381  func TestFixedbugs(t *testing.T) { testDirFiles(t, "../../internal/types/testdata/fixedbugs", false) }
   382  func TestLocal(t *testing.T)     { testDirFiles(t, "testdata/local", false) }
   383  
   384  func testDirFiles(t *testing.T, dir string, manual bool) {
   385  	testenv.MustHaveGoBuild(t)
   386  	dir = filepath.FromSlash(dir)
   387  
   388  	fis, err := os.ReadDir(dir)
   389  	if err != nil {
   390  		t.Error(err)
   391  		return
   392  	}
   393  
   394  	for _, fi := range fis {
   395  		path := filepath.Join(dir, fi.Name())
   396  
   397  		// If fi is a directory, its files make up a single package.
   398  		if fi.IsDir() {
   399  			testDir(t, path, manual)
   400  		} else {
   401  			t.Run(filepath.Base(path), func(t *testing.T) {
   402  				testPkg(t, []string{path}, manual)
   403  			})
   404  		}
   405  	}
   406  }
   407  
   408  func testDir(t *testing.T, dir string, manual bool) {
   409  	testenv.MustHaveGoBuild(t)
   410  
   411  	fis, err := os.ReadDir(dir)
   412  	if err != nil {
   413  		t.Error(err)
   414  		return
   415  	}
   416  
   417  	var filenames []string
   418  	for _, fi := range fis {
   419  		filenames = append(filenames, filepath.Join(dir, fi.Name()))
   420  	}
   421  
   422  	t.Run(filepath.Base(dir), func(t *testing.T) {
   423  		testPkg(t, filenames, manual)
   424  	})
   425  }
   426  
   427  func testPkg(t *testing.T, filenames []string, manual bool) {
   428  	srcs := make([][]byte, len(filenames))
   429  	for i, filename := range filenames {
   430  		src, err := os.ReadFile(filename)
   431  		if err != nil {
   432  			t.Fatalf("could not read %s: %v", filename, err)
   433  		}
   434  		srcs[i] = src
   435  	}
   436  	testFiles(t, filenames, srcs, manual)
   437  }