]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/go/types/check_test.go
go/types, types2: add FileVersions map to test Info
[gostls13.git] / src / go / types / check_test.go
index a743d9d41d99d99549e8e15c45a7b8e100fd119d..fc9723a67fa5cf4569bb51e55dead7c0d0ed2d6a 100644 (file)
@@ -4,20 +4,27 @@
 
 // This file implements a typechecker test harness. The packages specified
 // in tests are typechecked. Error messages reported by the typechecker are
-// compared against the error messages expected in the test files.
+// compared against the errors expected in the test files.
 //
-// Expected errors are indicated in the test files by putting a comment
-// of the form /* ERROR "rx" */ immediately following an offending token.
-// The harness will verify that an error matching the regular expression
-// rx is reported at that source position. Consecutive comments may be
-// used to indicate multiple errors for the same token position.
+// Expected errors are indicated in the test files by putting comments
+// of the form /* ERROR pattern */ or /* ERRORx pattern */ (or a similar
+// //-style line comment) immediately following the tokens where errors
+// are reported. There must be exactly one blank before and after the
+// ERROR/ERRORx indicator, and the pattern must be a properly quoted Go
+// string.
 //
-// For instance, the following test file indicates that a "not declared"
+// The harness will verify that each ERROR pattern is a substring of the
+// error reported at that source position, and that each ERRORx pattern
+// is a regular expression matching the respective error.
+// Consecutive comments may be used to indicate multiple errors reported
+// at the same position.
+//
+// For instance, the following test source indicates that an "undeclared"
 // error should be reported for the undeclared variable x:
 //
 //     package p
 //     func f() {
-//             _ = x /* ERROR "not declared" */ + 1
+//             _ = x /* ERROR "undeclared" */ + 1
 //     }
 
 package types_test
@@ -31,10 +38,15 @@ import (
        "go/parser"
        "go/scanner"
        "go/token"
+       "internal/buildcfg"
        "internal/testenv"
+       "internal/types/errors"
        "os"
        "path/filepath"
+       "reflect"
        "regexp"
+       "runtime"
+       "strconv"
        "strings"
        "testing"
 
@@ -44,26 +56,10 @@ import (
 var (
        haltOnError  = flag.Bool("halt", false, "halt on error")
        verifyErrors = flag.Bool("verify", false, "verify errors (rather than list them) in TestManual")
-       goVersion    = flag.String("lang", "", "Go language version (e.g. \"go1.12\") for TestManual")
 )
 
 var fset = token.NewFileSet()
 
-// Positioned errors are of the form filename:line:column: message .
-var posMsgRx = regexp.MustCompile(`^(.*:[0-9]+:[0-9]+): *(?s)(.*)`)
-
-// splitError splits an error's error message into a position string
-// and the actual error message. If there's no position information,
-// pos is the empty string, and msg is the entire error message.
-func splitError(err error) (pos, msg string) {
-       msg = err.Error()
-       if m := posMsgRx.FindStringSubmatch(msg); len(m) == 3 {
-               pos = m[1]
-               msg = m[2]
-       }
-       return
-}
-
 func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mode) ([]*ast.File, []error) {
        var files []*ast.File
        var errlist []error
@@ -86,110 +82,28 @@ func parseFiles(t *testing.T, filenames []string, srcs [][]byte, mode parser.Mod
        return files, errlist
 }
 
-// ERROR comments must start with text `ERROR "rx"` or `ERROR rx` where
-// rx is a regular expression that matches the expected error message.
-// Space around "rx" or rx is ignored.
-var errRx = regexp.MustCompile(`^ *ERROR *"?([^"]*)"?`)
-
-// errMap collects the regular expressions of ERROR comments found
-// in files and returns them as a map of error positions to error messages.
-//
-// srcs must be a slice of the same length as files, containing the original
-// source for the parsed AST.
-func errMap(t *testing.T, files []*ast.File, srcs [][]byte) map[string][]string {
-       // map of position strings to lists of error message patterns
-       errmap := make(map[string][]string)
-
-       for i, file := range files {
-               tok := fset.File(file.Package)
-               src := srcs[i]
-               var s scanner.Scanner
-               s.Init(tok, src, nil, scanner.ScanComments)
-               var prev token.Pos // position of last non-comment, non-semicolon token
-
-       scanFile:
-               for {
-                       pos, tok, lit := s.Scan()
-                       switch tok {
-                       case token.EOF:
-                               break scanFile
-                       case token.COMMENT:
-                               if lit[1] == '*' {
-                                       lit = lit[:len(lit)-2] // strip trailing */
-                               }
-                               if s := errRx.FindStringSubmatch(lit[2:]); len(s) == 2 {
-                                       p := fset.Position(prev).String()
-                                       errmap[p] = append(errmap[p], strings.TrimSpace(s[1]))
-                               }
-                       case token.SEMICOLON:
-                               // ignore automatically inserted semicolon
-                               if lit == "\n" {
-                                       continue scanFile
-                               }
-                               fallthrough
-                       default:
-                               prev = pos
-                       }
-               }
+func unpackError(fset *token.FileSet, err error) (token.Position, string) {
+       switch err := err.(type) {
+       case *scanner.Error:
+               return err.Pos, err.Msg
+       case Error:
+               return fset.Position(err.Pos), err.Msg
        }
-
-       return errmap
+       panic("unreachable")
 }
 
-func eliminate(t *testing.T, errmap map[string][]string, errlist []error) {
-       for _, err := range errlist {
-               pos, gotMsg := splitError(err)
-               list := errmap[pos]
-               index := -1 // list index of matching message, if any
-               // we expect one of the messages in list to match the error at pos
-               for i, wantRx := range list {
-                       rx, err := regexp.Compile(wantRx)
-                       if err != nil {
-                               t.Errorf("%s: %v", pos, err)
-                               continue
-                       }
-                       if rx.MatchString(gotMsg) {
-                               index = i
-                               break
-                       }
-               }
-               if index >= 0 {
-                       // eliminate from list
-                       if n := len(list) - 1; n > 0 {
-                               // not the last entry - swap in last element and shorten list by 1
-                               list[index] = list[n]
-                               errmap[pos] = list[:n]
-                       } else {
-                               // last entry - remove list from map
-                               delete(errmap, pos)
-                       }
-               } else {
-                       t.Errorf("%s: no error expected: %q", pos, gotMsg)
-               }
+// absDiff returns the absolute difference between x and y.
+func absDiff(x, y int) int {
+       if x < y {
+               return y - x
        }
+       return x - y
 }
 
-// parseFlags parses flags from the first line of the given source
-// (from src if present, or by reading from the file) if the line
-// starts with "//" (line comment) followed by "-" (possibly with
-// spaces between). Otherwise the line is ignored.
-func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
-       // If there is no src, read from the file.
-       const maxLen = 256
-       if len(src) == 0 {
-               f, err := os.Open(filename)
-               if err != nil {
-                       return err
-               }
-
-               var buf [maxLen]byte
-               n, err := f.Read(buf[:])
-               if err != nil {
-                       return err
-               }
-               src = buf[:n]
-       }
-
+// parseFlags parses flags from the first line of the given source if the line
+// starts with "//" (line comment) followed by "-" (possibly with spaces
+// between). Otherwise the line is ignored.
+func parseFlags(src []byte, flags *flag.FlagSet) error {
        // we must have a line comment that starts with a "-"
        const prefix = "//"
        if !bytes.HasPrefix(src, []byte(prefix)) {
@@ -200,6 +114,7 @@ func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
                return nil // comment doesn't start with a "-"
        }
        end := bytes.Index(src, []byte("\n"))
+       const maxLen = 256
        if end < 0 || end > maxLen {
                return fmt.Errorf("flags comment line too long")
        }
@@ -207,38 +122,37 @@ func parseFlags(filename string, src []byte, flags *flag.FlagSet) error {
        return flags.Parse(strings.Fields(string(src[:end])))
 }
 
-func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, manual bool, imp Importer) {
-       if len(filenames) == 0 {
-               t.Fatal("no source files")
-       }
-
-       var conf Config
-       conf.Sizes = sizes
-       flags := flag.NewFlagSet("", flag.PanicOnError)
-       flags.StringVar(&conf.GoVersion, "lang", "", "")
-       flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
-       if err := parseFlags(filenames[0], srcs[0], flags); err != nil {
-               t.Fatal(err)
-       }
-
-       if manual && *goVersion != "" {
-               // goVersion overrides -lang for manual tests.
-               conf.GoVersion = *goVersion
+// testFiles type-checks the package consisting of the given files, and
+// compares the resulting errors with the ERROR annotations in the source.
+// Except for manual tests, each package is type-checked twice, once without
+// use of Alias types, and once with Alias types.
+//
+// The srcs slice contains the file content for the files named in the
+// filenames slice. The colDelta parameter specifies the tolerance for position
+// mismatch when comparing errors. The manual parameter specifies whether this
+// is a 'manual' test.
+//
+// If provided, opts may be used to mutate the Config before type-checking.
+func testFiles(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
+       // Alias types are disabled by default
+       testFilesImpl(t, filenames, srcs, manual, opts...)
+       if !manual {
+               t.Setenv("GODEBUG", "gotypesalias=1")
+               testFilesImpl(t, filenames, srcs, manual, opts...)
        }
+}
 
-       // TODO(gri) remove this or use flag mechanism to set mode if still needed
-       if strings.HasSuffix(filenames[0], ".go1") {
-               // TODO(rfindley): re-enable this test by using GoVersion.
-               t.Skip("type params are enabled")
+func testFilesImpl(t *testing.T, filenames []string, srcs [][]byte, manual bool, opts ...func(*Config)) {
+       if len(filenames) == 0 {
+               t.Fatal("no source files")
        }
 
+       // parse files
        files, errlist := parseFiles(t, filenames, srcs, parser.AllErrors)
-
        pkgName := "<no package>"
        if len(files) > 0 {
                pkgName = files[0].Name.Name
        }
-
        listErrors := manual && !*verifyErrors
        if listErrors && len(errlist) > 0 {
                t.Errorf("--- %s:", pkgName)
@@ -247,11 +161,10 @@ func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, man
                }
        }
 
-       // typecheck and collect typechecker errors
-       if imp == nil {
-               imp = importer.Default()
-       }
-       conf.Importer = imp
+       // set up typechecker
+       var conf Config
+       *boolFieldAddr(&conf, "_Trace") = manual && testing.Verbose()
+       conf.Importer = importer.Default()
        conf.Error = func(err error) {
                if *haltOnError {
                        defer panic(err)
@@ -266,39 +179,179 @@ func testFiles(t *testing.T, sizes Sizes, filenames []string, srcs [][]byte, man
                        errlist = append(errlist, err)
                }
        }
-       conf.Check(pkgName, fset, files, nil)
 
+       // apply custom configuration
+       for _, opt := range opts {
+               opt(&conf)
+       }
+
+       // apply flag setting (overrides custom configuration)
+       var goexperiment, gotypesalias string
+       flags := flag.NewFlagSet("", flag.PanicOnError)
+       flags.StringVar(&conf.GoVersion, "lang", "", "")
+       flags.StringVar(&goexperiment, "goexperiment", "", "")
+       flags.BoolVar(&conf.FakeImportC, "fakeImportC", false, "")
+       flags.StringVar(&gotypesalias, "gotypesalias", "", "")
+       if err := parseFlags(srcs[0], flags); err != nil {
+               t.Fatal(err)
+       }
+
+       exp, err := buildcfg.ParseGOEXPERIMENT(runtime.GOOS, runtime.GOARCH, goexperiment)
+       if err != nil {
+               t.Fatal(err)
+       }
+       old := buildcfg.Experiment
+       defer func() {
+               buildcfg.Experiment = old
+       }()
+       buildcfg.Experiment = *exp
+
+       // By default, gotypesalias is not set.
+       if gotypesalias != "" {
+               t.Setenv("GODEBUG", "gotypesalias="+gotypesalias)
+       }
+
+       // Provide Config.Info with all maps so that info recording is tested.
+       info := Info{
+               Types:        make(map[ast.Expr]TypeAndValue),
+               Instances:    make(map[*ast.Ident]Instance),
+               Defs:         make(map[*ast.Ident]Object),
+               Uses:         make(map[*ast.Ident]Object),
+               Implicits:    make(map[ast.Node]Object),
+               Selections:   make(map[*ast.SelectorExpr]*Selection),
+               Scopes:       make(map[ast.Node]*Scope),
+               FileVersions: make(map[*ast.File]string),
+       }
+
+       // typecheck
+       conf.Check(pkgName, fset, files, &info)
        if listErrors {
                return
        }
 
+       // collect expected errors
+       errmap := make(map[string]map[int][]comment)
+       for i, filename := range filenames {
+               if m := commentMap(srcs[i], regexp.MustCompile("^ ERRORx? ")); len(m) > 0 {
+                       errmap[filename] = m
+               }
+       }
+
+       // match against found errors
+       var indices []int // list indices of matching errors, reused for each error
        for _, err := range errlist {
-               err, ok := err.(Error)
-               if !ok {
+               gotPos, gotMsg := unpackError(fset, err)
+
+               // find list of errors for the respective error line
+               filename := gotPos.Filename
+               filemap := errmap[filename]
+               line := gotPos.Line
+               var errList []comment
+               if filemap != nil {
+                       errList = filemap[line]
+               }
+
+               // At least one of the errors in errList should match the current error.
+               indices = indices[:0]
+               for i, want := range errList {
+                       pattern, substr := strings.CutPrefix(want.text, " ERROR ")
+                       if !substr {
+                               var found bool
+                               pattern, found = strings.CutPrefix(want.text, " ERRORx ")
+                               if !found {
+                                       panic("unreachable")
+                               }
+                       }
+                       pattern, err := strconv.Unquote(strings.TrimSpace(pattern))
+                       if err != nil {
+                               t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
+                               continue
+                       }
+                       if substr {
+                               if !strings.Contains(gotMsg, pattern) {
+                                       continue
+                               }
+                       } else {
+                               rx, err := regexp.Compile(pattern)
+                               if err != nil {
+                                       t.Errorf("%s:%d:%d: %v", filename, line, want.col, err)
+                                       continue
+                               }
+                               if !rx.MatchString(gotMsg) {
+                                       continue
+                               }
+                       }
+                       indices = append(indices, i)
+               }
+               if len(indices) == 0 {
+                       t.Errorf("%s: no error expected: %q", gotPos, gotMsg)
                        continue
                }
-               code := readCode(err)
-               if code == 0 {
-                       t.Errorf("missing error code: %v", err)
+               // len(indices) > 0
+
+               // If there are multiple matching errors, select the one with the closest column position.
+               index := -1 // index of matching error
+               var delta int
+               for _, i := range indices {
+                       if d := absDiff(gotPos.Column, errList[i].col); index < 0 || d < delta {
+                               index, delta = i, d
+                       }
                }
-       }
 
-       // match and eliminate errors;
-       // we are expecting the following errors
-       errmap := errMap(t, files, srcs)
-       eliminate(t, errmap, errlist)
+               // The closest column position must be within expected colDelta.
+               const colDelta = 0 // go/types errors are positioned correctly
+               if delta > colDelta {
+                       t.Errorf("%s: got col = %d; want %d", gotPos, gotPos.Column, errList[index].col)
+               }
+
+               // eliminate from errList
+               if n := len(errList) - 1; n > 0 {
+                       // not the last entry - slide entries down (don't reorder)
+                       copy(errList[index:], errList[index+1:])
+                       filemap[line] = errList[:n]
+               } else {
+                       // last entry - remove errList from filemap
+                       delete(filemap, line)
+               }
+
+               // if filemap is empty, eliminate from errmap
+               if len(filemap) == 0 {
+                       delete(errmap, filename)
+               }
+       }
 
        // there should be no expected errors left
        if len(errmap) > 0 {
-               t.Errorf("--- %s: %d source positions with expected (but not reported) errors:", pkgName, len(errmap))
-               for pos, list := range errmap {
-                       for _, rx := range list {
-                               t.Errorf("%s: %q", pos, rx)
+               t.Errorf("--- %s: unreported errors:", pkgName)
+               for filename, filemap := range errmap {
+                       for line, errList := range filemap {
+                               for _, err := range errList {
+                                       t.Errorf("%s:%d:%d: %s", filename, line, err.col, err.text)
+                               }
                        }
                }
        }
 }
 
+func readCode(err Error) errors.Code {
+       v := reflect.ValueOf(err)
+       return errors.Code(v.FieldByName("go116code").Int())
+}
+
+// boolFieldAddr(conf, name) returns the address of the boolean field conf.<name>.
+// For accessing unexported fields.
+func boolFieldAddr(conf *Config, name string) *bool {
+       v := reflect.Indirect(reflect.ValueOf(conf))
+       return (*bool)(v.FieldByName(name).Addr().UnsafePointer())
+}
+
+// stringFieldAddr(conf, name) returns the address of the string field conf.<name>.
+// For accessing unexported fields.
+func stringFieldAddr(conf *Config, name string) *string {
+       v := reflect.Indirect(reflect.ValueOf(conf))
+       return (*string)(v.FieldByName(name).Addr().UnsafePointer())
+}
+
 // TestManual is for manual testing of a package - either provided
 // as a list of filenames belonging to the package, or a directory
 // name containing the package files - after the test arguments
@@ -338,27 +391,39 @@ func TestManual(t *testing.T) {
 }
 
 func TestLongConstants(t *testing.T) {
-       format := "package longconst\n\nconst _ = %s /* ERROR constant overflow */ \nconst _ = %s // ERROR excessively long constant"
+       format := `package longconst; const _ = %s /* ERROR "constant overflow" */; const _ = %s // ERROR "excessively long constant"`
        src := fmt.Sprintf(format, strings.Repeat("1", 9999), strings.Repeat("1", 10001))
-       testFiles(t, nil, []string{"longconst.go"}, [][]byte{[]byte(src)}, false, nil)
+       testFiles(t, []string{"longconst.go"}, [][]byte{[]byte(src)}, false)
+}
+
+func withSizes(sizes Sizes) func(*Config) {
+       return func(cfg *Config) {
+               cfg.Sizes = sizes
+       }
 }
 
 // TestIndexRepresentability tests that constant index operands must
 // be representable as int even if they already have a type that can
 // represent larger values.
 func TestIndexRepresentability(t *testing.T) {
-       const src = "package index\n\nvar s []byte\nvar _ = s[int64 /* ERROR \"int64\\(1\\) << 40 \\(.*\\) overflows int\" */ (1) << 40]"
-       testFiles(t, &StdSizes{4, 4}, []string{"index.go"}, [][]byte{[]byte(src)}, false, nil)
+       const src = `package index; var s []byte; var _ = s[int64 /* ERRORx "int64\\(1\\) << 40 \\(.*\\) overflows int" */ (1) << 40]`
+       testFiles(t, []string{"index.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
 }
 
 func TestIssue47243_TypedRHS(t *testing.T) {
        // The RHS of the shift expression below overflows uint on 32bit platforms,
        // but this is OK as it is explicitly typed.
-       const src = "package issue47243\n\nvar a uint64; var _ = a << uint64(4294967296)" // uint64(1<<32)
-       testFiles(t, &StdSizes{4, 4}, []string{"p.go"}, [][]byte{[]byte(src)}, false, nil)
+       const src = `package issue47243; var a uint64; var _ = a << uint64(4294967296)` // uint64(1<<32)
+       testFiles(t, []string{"p.go"}, [][]byte{[]byte(src)}, false, withSizes(&StdSizes{4, 4}))
 }
 
 func TestCheck(t *testing.T) {
+       old := buildcfg.Experiment.RangeFunc
+       defer func() {
+               buildcfg.Experiment.RangeFunc = old
+       }()
+       buildcfg.Experiment.RangeFunc = true
+
        DefPredeclaredTestFuncs()
        testDirFiles(t, "../../internal/types/testdata/check", false)
 }
@@ -410,7 +475,6 @@ func testDir(t *testing.T, dir string, manual bool) {
        })
 }
 
-// TODO(rFindley) reconcile the different test setup in go/types with types2.
 func testPkg(t *testing.T, filenames []string, manual bool) {
        srcs := make([][]byte, len(filenames))
        for i, filename := range filenames {
@@ -420,5 +484,5 @@ func testPkg(t *testing.T, filenames []string, manual bool) {
                }
                srcs[i] = src
        }
-       testFiles(t, nil, filenames, srcs, manual, nil)
+       testFiles(t, filenames, srcs, manual)
 }