]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/go/types/check.go
go/types: export Info.FileVersions
[gostls13.git] / src / go / types / check.go
index 76be49804248f675020bb9d45db7e30dc86acd5f..89b8ee07a25d9f71049a7be0281a3cdce61e56c7 100644 (file)
@@ -12,9 +12,13 @@ import (
        "go/ast"
        "go/constant"
        "go/token"
+       "internal/goversion"
        . "internal/types/errors"
 )
 
+// nopos indicates an unknown position
+var nopos token.Pos
+
 // debugging/development support
 const debug = false // leave on during development
 
@@ -86,7 +90,7 @@ type actionDesc struct {
 }
 
 // A Checker maintains the state of the type checker.
-// It must be created with NewChecker.
+// It must be created with [NewChecker].
 type Checker struct {
        // package information
        // (initialized by NewChecker, valid for the life-time of checker)
@@ -96,6 +100,7 @@ type Checker struct {
        pkg  *Package
        *Info
        version version                // accepted language version
+       posVers map[token.Pos]version  // maps file start positions to versions (may be nil)
        nextID  uint64                 // unique Id for type parameters (first valid Id is 1)
        objMap  map[Object]*declInfo   // maps package-level objects and (non-interface) methods to declaration info
        impMap  map[importKey]*Package // maps (import path, source directory) to (complete or fake) package
@@ -167,7 +172,7 @@ func (check *Checker) validAlias(alias *TypeName, typ Type) {
 
 // isBrokenAlias reports whether alias doesn't have a determined type yet.
 func (check *Checker) isBrokenAlias(alias *TypeName) bool {
-       return alias.typ == Typ[Invalid] && check.brokenAliases[alias]
+       return !isValid(alias.typ) && check.brokenAliases[alias]
 }
 
 func (check *Checker) rememberUntyped(e ast.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
@@ -216,8 +221,8 @@ func (check *Checker) needsCleanup(c cleaner) {
        check.cleaners = append(check.cleaners, c)
 }
 
-// NewChecker returns a new Checker instance for a given package.
-// Package files may be added incrementally via checker.Files.
+// NewChecker returns a new [Checker] instance for a given package.
+// [Package] files may be added incrementally via checker.Files.
 func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Checker {
        // make sure we have a configuration
        if conf == nil {
@@ -229,20 +234,20 @@ func NewChecker(conf *Config, fset *token.FileSet, pkg *Package, info *Info) *Ch
                info = new(Info)
        }
 
-       version, err := parseGoVersion(conf.GoVersion)
-       if err != nil {
-               panic(fmt.Sprintf("invalid Go version %q (%v)", conf.GoVersion, err))
-       }
+       // Note: clients may call NewChecker with the Unsafe package, which is
+       // globally shared and must not be mutated. Therefore NewChecker must not
+       // mutate *pkg.
+       //
+       // (previously, pkg.goVersion was mutated here: go.dev/issue/61212)
 
        return &Checker{
-               conf:    conf,
-               ctxt:    conf.Context,
-               fset:    fset,
-               pkg:     pkg,
-               Info:    info,
-               version: version,
-               objMap:  make(map[Object]*declInfo),
-               impMap:  make(map[importKey]*Package),
+               conf:   conf,
+               ctxt:   conf.Context,
+               fset:   fset,
+               pkg:    pkg,
+               Info:   info,
+               objMap: make(map[Object]*declInfo),
+               impMap: make(map[importKey]*Package),
        }
 }
 
@@ -281,6 +286,37 @@ func (check *Checker) initFiles(files []*ast.File) {
                        // ignore this file
                }
        }
+
+       // collect file versions
+       for _, file := range check.files {
+               check.recordFileVersion(file, check.conf.GoVersion)
+               if v, _ := parseGoVersion(file.GoVersion); v.major > 0 {
+                       if v.equal(check.version) {
+                               continue
+                       }
+                       // Go 1.21 introduced the feature of setting the go.mod
+                       // go line to an early version of Go and allowing //go:build lines
+                       // to “upgrade” the Go version in a given file.
+                       // We can do that backwards compatibly.
+                       // Go 1.21 also introduced the feature of allowing //go:build lines
+                       // to “downgrade” the Go version in a given file.
+                       // That can't be done compatibly in general, since before the
+                       // build lines were ignored and code got the module's Go version.
+                       // To work around this, downgrades are only allowed when the
+                       // module's Go version is Go 1.21 or later.
+                       // If there is no check.version, then we don't really know what Go version to apply.
+                       // Legacy tools may do this, and they historically have accepted everything.
+                       // Preserve that behavior by ignoring //go:build constraints entirely in that case.
+                       if (v.before(check.version) && check.version.before(go1_21)) || check.version.equal(go0_0) {
+                               continue
+                       }
+                       if check.posVers == nil {
+                               check.posVers = make(map[token.Pos]version)
+                       }
+                       check.posVers[file.FileStart] = v
+                       check.recordFileVersion(file, file.GoVersion) // overwrite package version
+               }
+       }
 }
 
 // A bailout panic is used for early termination.
@@ -303,6 +339,24 @@ func (check *Checker) Files(files []*ast.File) error { return check.checkFiles(f
 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
 
 func (check *Checker) checkFiles(files []*ast.File) (err error) {
+       if check.pkg == Unsafe {
+               // Defensive handling for Unsafe, which cannot be type checked, and must
+               // not be mutated. See https://go.dev/issue/61212 for an example of where
+               // Unsafe is passed to NewChecker.
+               return nil
+       }
+
+       // Note: parseGoVersion and the subsequent checks should happen once,
+       //       when we create a new Checker, not for each batch of files.
+       //       We can't change it at this point because NewChecker doesn't
+       //       return an error.
+       check.version, err = parseGoVersion(check.conf.GoVersion)
+       if err != nil {
+               return err
+       }
+       if check.version.after(version{1, goversion.Version}) {
+               return fmt.Errorf("package requires newer Go version %v", check.version)
+       }
        if check.conf.FakeImportC && check.conf.go115UsesCgo {
                return errBadCgo
        }
@@ -310,7 +364,7 @@ func (check *Checker) checkFiles(files []*ast.File) (err error) {
        defer check.handleBailout(&err)
 
        print := func(msg string) {
-               if check.conf.trace {
+               if check.conf._Trace {
                        fmt.Println()
                        fmt.Println(msg)
                }
@@ -347,6 +401,7 @@ func (check *Checker) checkFiles(files []*ast.File) (err error) {
                check.monomorph()
        }
 
+       check.pkg.goVersion = check.conf.GoVersion
        check.pkg.complete = true
 
        // no longer needed - release memory
@@ -374,15 +429,15 @@ func (check *Checker) processDelayed(top int) {
        // this is a sufficiently bounded process.
        for i := top; i < len(check.delayed); i++ {
                a := &check.delayed[i]
-               if check.conf.trace {
+               if check.conf._Trace {
                        if a.desc != nil {
                                check.trace(a.desc.pos.Pos(), "-- "+a.desc.format, a.desc.args...)
                        } else {
-                               check.trace(token.NoPos, "-- delayed %p", a.f)
+                               check.trace(nopos, "-- delayed %p", a.f)
                        }
                }
                a.f() // may append to check.delayed
-               if check.conf.trace {
+               if check.conf._Trace {
                        fmt.Println()
                }
        }
@@ -450,7 +505,7 @@ func (check *Checker) recordTypeAndValue(x ast.Expr, mode operandMode, typ Type,
                assert(val != nil)
                // We check allBasic(typ, IsConstType) here as constant expressions may be
                // recorded as type parameters.
-               assert(typ == Typ[Invalid] || allBasic(typ, IsConstType))
+               assert(!isValid(typ) || allBasic(typ, IsConstType))
        }
        if m := check.Types; m != nil {
                m[x] = TypeAndValue{mode, typ, val}
@@ -475,20 +530,24 @@ func (check *Checker) recordBuiltinType(f ast.Expr, sig *Signature) {
        }
 }
 
-func (check *Checker) recordCommaOkTypes(x ast.Expr, a [2]Type) {
+// recordCommaOkTypes updates recorded types to reflect that x is used in a commaOk context
+// (and therefore has tuple type).
+func (check *Checker) recordCommaOkTypes(x ast.Expr, a []*operand) {
        assert(x != nil)
-       if a[0] == nil || a[1] == nil {
+       assert(len(a) == 2)
+       if a[0].mode == invalid {
                return
        }
-       assert(isTyped(a[0]) && isTyped(a[1]) && (isBoolean(a[1]) || a[1] == universeError))
+       t0, t1 := a[0].typ, a[1].typ
+       assert(isTyped(t0) && isTyped(t1) && (isBoolean(t1) || t1 == universeError))
        if m := check.Types; m != nil {
                for {
                        tv := m[x]
                        assert(tv.Type != nil) // should have been recorded already
                        pos := x.Pos()
                        tv.Type = NewTuple(
-                               NewVar(pos, check.pkg, "", a[0]),
-                               NewVar(pos, check.pkg, "", a[1]),
+                               NewVar(pos, check.pkg, "", t0),
+                               NewVar(pos, check.pkg, "", t1),
                        )
                        m[x] = tv
                        // if x is a parenthesized expression (p.X), update p.X
@@ -573,3 +632,9 @@ func (check *Checker) recordScope(node ast.Node, scope *Scope) {
                m[node] = scope
        }
 }
+
+func (check *Checker) recordFileVersion(file *ast.File, version string) {
+       if m := check.FileVersions; m != nil {
+               m[file] = version
+       }
+}