]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/cmd/compile/internal/types2/check.go
cmd/compile/internal/types2: mark gotypesalias as undocumented
[gostls13.git] / src / cmd / compile / internal / types2 / check.go
index 5cf8454aa44049f21b917ea5d47ec425f3a94048..381ccd8dcfae81cafba5863181925576596a7f72 100644 (file)
@@ -11,13 +11,20 @@ import (
        "errors"
        "fmt"
        "go/constant"
+       "internal/godebug"
+       "internal/goversion"
+       . "internal/types/errors"
 )
 
+// nopos indicates an unknown position
 var nopos syntax.Pos
 
 // debugging/development support
 const debug = false // leave on during development
 
+// gotypesalias controls the use of Alias types.
+var gotypesalias = godebug.New("#gotypesalias")
+
 // exprInfo stores information about an untyped expression.
 type exprInfo struct {
        isLhs bool // expression is lhs operand of a shift with delayed type-check
@@ -90,15 +97,22 @@ type actionDesc struct {
 type Checker struct {
        // package information
        // (initialized by NewChecker, valid for the life-time of checker)
+
+       // If enableAlias is set, alias declarations produce an Alias type.
+       // Otherwise the alias information is only in the type name, which
+       // points directly to the actual (aliased) type.
+       enableAlias bool
+
        conf *Config
        ctxt *Context // context for de-duplicating instances
        pkg  *Package
        *Info
-       version version                // accepted language version
-       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
-       infoMap map[*Named]typeInfo    // maps named types to their associated type info (for cycle detection)
+       version version                     // accepted language version
+       posVers map[*syntax.PosBase]version // maps file PosBases 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
+       valids  instanceLookup              // valid *Named (incl. instantiated) types per the validType check
 
        // pkgPathMap maps package names to the set of distinct import paths we've
        // seen for that name, anywhere in the import graph. It is used for
@@ -148,9 +162,14 @@ func (check *Checker) addDeclDep(to Object) {
        from.addDep(to)
 }
 
+// Note: The following three alias-related functions are only used
+//       when Alias types are not enabled.
+
 // brokenAlias records that alias doesn't have a determined type yet.
 // It also sets alias.typ to Typ[Invalid].
+// Not used if check.enableAlias is set.
 func (check *Checker) brokenAlias(alias *TypeName) {
+       assert(!check.enableAlias)
        if check.brokenAliases == nil {
                check.brokenAliases = make(map[*TypeName]bool)
        }
@@ -160,13 +179,15 @@ func (check *Checker) brokenAlias(alias *TypeName) {
 
 // validAlias records that alias has the valid type typ (possibly Typ[Invalid]).
 func (check *Checker) validAlias(alias *TypeName, typ Type) {
+       assert(!check.enableAlias)
        delete(check.brokenAliases, alias)
        alias.typ = typ
 }
 
 // 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]
+       assert(!check.enableAlias)
+       return check.brokenAliases[alias]
 }
 
 func (check *Checker) rememberUntyped(e syntax.Expr, lhs bool, mode operandMode, typ *Basic, val constant.Value) {
@@ -228,20 +249,20 @@ func NewChecker(conf *Config, pkg *Package, info *Info) *Checker {
                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,
-               pkg:     pkg,
-               Info:    info,
-               version: version,
-               objMap:  make(map[Object]*declInfo),
-               impMap:  make(map[importKey]*Package),
-               infoMap: make(map[*Named]typeInfo),
+               enableAlias: gotypesalias.Value() == "1",
+               conf:        conf,
+               ctxt:        conf.Context,
+               pkg:         pkg,
+               Info:        info,
+               objMap:      make(map[Object]*declInfo),
+               impMap:      make(map[importKey]*Package),
        }
 }
 
@@ -268,7 +289,7 @@ func (check *Checker) initFiles(files []*syntax.File) {
                        if name != "_" {
                                pkg.name = name
                        } else {
-                               check.error(file.PkgName, "invalid package name _")
+                               check.error(file.PkgName, BlankPkgName, "invalid package name _")
                        }
                        fallthrough
 
@@ -276,10 +297,42 @@ func (check *Checker) initFiles(files []*syntax.File) {
                        check.files = append(check.files, file)
 
                default:
-                       check.errorf(file, "package %s; expected %s", name, pkg.name)
+                       check.errorf(file, MismatchedPkgName, "package %s; expected %s", name, pkg.name)
                        // ignore this file
                }
        }
+
+       for _, file := range check.files {
+               fbase := base(file.Pos())                            // fbase may be nil for tests
+               check.recordFileVersion(fbase, check.conf.GoVersion) // record package version (possibly zero version)
+               v, _ := parseGoVersion(file.GoVersion)
+               if 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[*syntax.PosBase]version)
+                       }
+                       check.posVers[fbase] = v
+                       check.recordFileVersion(fbase, file.GoVersion) // overwrite package version
+               }
+       }
 }
 
 // A bailout panic is used for early termination.
@@ -302,6 +355,24 @@ func (check *Checker) Files(files []*syntax.File) error { return check.checkFile
 var errBadCgo = errors.New("cannot use FakeImportC and go115UsesCgo together")
 
 func (check *Checker) checkFiles(files []*syntax.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
        }
@@ -346,6 +417,7 @@ func (check *Checker) checkFiles(files []*syntax.File) (err error) {
                check.monomorph()
        }
 
+       check.pkg.goVersion = check.conf.GoVersion
        check.pkg.complete = true
 
        // no longer needed - release memory
@@ -426,13 +498,13 @@ func (check *Checker) record(x *operand) {
 }
 
 func (check *Checker) recordUntyped() {
-       if !debug && check.Types == nil {
+       if !debug && !check.recordTypes() {
                return // nothing to do
        }
 
        for x, info := range check.untyped {
                if debug && isTyped(info.typ) {
-                       check.dump("%v: %s (type %s) is typed", posFor(x), x, info.typ)
+                       check.dump("%v: %s (type %s) is typed", atPos(x), x, info.typ)
                        unreachable()
                }
                check.recordTypeAndValue(x, info.mode, info.typ, info.val)
@@ -449,11 +521,40 @@ func (check *Checker) recordTypeAndValue(x syntax.Expr, mode operandMode, typ Ty
                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}
        }
+       if check.StoreTypesInSyntax {
+               tv := TypeAndValue{mode, typ, val}
+               stv := syntax.TypeAndValue{Type: typ, Value: val}
+               if tv.IsVoid() {
+                       stv.SetIsVoid()
+               }
+               if tv.IsType() {
+                       stv.SetIsType()
+               }
+               if tv.IsBuiltin() {
+                       stv.SetIsBuiltin()
+               }
+               if tv.IsValue() {
+                       stv.SetIsValue()
+               }
+               if tv.IsNil() {
+                       stv.SetIsNil()
+               }
+               if tv.Addressable() {
+                       stv.SetAddressable()
+               }
+               if tv.Assignable() {
+                       stv.SetAssignable()
+               }
+               if tv.HasOk() {
+                       stv.SetHasOk()
+               }
+               x.SetTypeInfo(stv)
+       }
 }
 
 func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
@@ -474,20 +575,24 @@ func (check *Checker) recordBuiltinType(f syntax.Expr, sig *Signature) {
        }
 }
 
-func (check *Checker) recordCommaOkTypes(x syntax.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 syntax.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
@@ -498,6 +603,25 @@ func (check *Checker) recordCommaOkTypes(x syntax.Expr, a [2]Type) {
                        x = p.X
                }
        }
+       if check.StoreTypesInSyntax {
+               // Note: this loop is duplicated because the type of tv is different.
+               // Above it is types2.TypeAndValue, here it is syntax.TypeAndValue.
+               for {
+                       tv := x.GetTypeInfo()
+                       assert(tv.Type != nil) // should have been recorded already
+                       pos := x.Pos()
+                       tv.Type = NewTuple(
+                               NewVar(pos, check.pkg, "", t0),
+                               NewVar(pos, check.pkg, "", t1),
+                       )
+                       x.SetTypeInfo(tv)
+                       p, _ := x.(*syntax.ParenExpr)
+                       if p == nil {
+                               break
+                       }
+                       x = p.X
+               }
+       }
 }
 
 // recordInstance records instantiation information into check.Info, if the
@@ -570,3 +694,9 @@ func (check *Checker) recordScope(node syntax.Node, scope *Scope) {
                m[node] = scope
        }
 }
+
+func (check *Checker) recordFileVersion(fbase *syntax.PosBase, version string) {
+       if m := check.FileVersions; m != nil {
+               m[fbase] = version
+       }
+}