From 28b92af2866ab2bc225795ba13f5a1ae765ffec5 Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Tue, 12 Dec 2023 13:27:10 -0500 Subject: [PATCH] internal/typeparams: eliminate remainining compatibility shims The nil checks in wrappers that had them were all redundant. Change-Id: Ide7296f2253610638b59dc4980b0487b9de72f0c Reviewed-on: https://go-review.googlesource.com/c/tools/+/549236 LUCI-TryBot-Result: Go LUCI Auto-Submit: Alan Donovan Reviewed-by: Robert Findley --- .../passes/ifaceassert/parameterized.go | 2 +- go/analysis/passes/tests/tests.go | 5 +- go/analysis/unitchecker/unitchecker.go | 3 +- go/ast/astutil/enclosing.go | 4 +- go/ast/astutil/rewrite.go | 6 +- go/callgraph/vta/graph.go | 2 +- go/loader/loader.go | 3 +- go/packages/packages.go | 3 +- go/ssa/builder_test.go | 5 +- go/ssa/const_test.go | 3 +- go/ssa/coretype.go | 2 +- go/ssa/create.go | 7 +- go/ssa/func.go | 4 +- go/ssa/instantiate.go | 2 +- go/ssa/parameterized.go | 4 +- go/ssa/ssautil/load.go | 3 +- go/ssa/ssautil/visit.go | 3 +- go/ssa/subst.go | 16 +-- go/ssa/subst_test.go | 4 +- go/ssa/util.go | 10 +- go/types/objectpath/objectpath.go | 4 +- go/types/typeutil/callee_test.go | 3 +- go/types/typeutil/map.go | 4 +- go/types/typeutil/map_test.go | 7 +- .../analysis/fillreturns/fillreturns.go | 3 +- .../analysis/infertypeargs/run_go118.go | 9 +- gopls/internal/analysis/useany/useany.go | 5 +- gopls/internal/lsp/cache/analysis.go | 5 +- gopls/internal/lsp/cache/check.go | 5 +- gopls/internal/lsp/cache/typerefs/refs.go | 9 +- .../lsp/source/completion/completion.go | 8 +- .../internal/lsp/source/completion/format.go | 3 +- .../internal/lsp/source/completion/literal.go | 11 +- gopls/internal/lsp/source/completion/util.go | 3 +- gopls/internal/lsp/source/hover.go | 3 +- gopls/internal/lsp/source/identifier.go | 4 +- gopls/internal/lsp/source/inlay_hint.go | 3 +- gopls/internal/lsp/source/stub.go | 3 +- gopls/internal/lsp/source/types_format.go | 6 +- gopls/internal/server/semantic.go | 3 +- internal/facts/imports.go | 10 +- internal/gcimporter/bexport_test.go | 15 +-- internal/gcimporter/iexport.go | 19 ++- internal/gcimporter/iimport.go | 19 ++- internal/typeparams/common.go | 16 +-- internal/typeparams/coretype.go | 2 +- .../typeparams/genericfeatures/features.go | 10 +- internal/typeparams/normalize.go | 2 +- internal/typeparams/normalize_test.go | 5 +- internal/typeparams/typeparams_go118.go | 126 ------------------ refactor/satisfy/find.go | 2 +- refactor/satisfy/find_test.go | 3 +- 52 files changed, 126 insertions(+), 295 deletions(-) delete mode 100644 internal/typeparams/typeparams_go118.go diff --git a/go/analysis/passes/ifaceassert/parameterized.go b/go/analysis/passes/ifaceassert/parameterized.go index 1fdd30c917a..12507f9967f 100644 --- a/go/analysis/passes/ifaceassert/parameterized.go +++ b/go/analysis/passes/ifaceassert/parameterized.go @@ -95,7 +95,7 @@ func (w *tpWalker) isParameterized(typ types.Type) (res bool) { return w.isParameterized(t.Elem()) case *types.Named: - list := typeparams.NamedTypeArgs(t) + list := t.TypeArgs() for i, n := 0, list.Len(); i < n; i++ { if w.isParameterized(list.At(i)) { return true diff --git a/go/analysis/passes/tests/tests.go b/go/analysis/passes/tests/tests.go index d0b0ebb1011..6db12f3cb9a 100644 --- a/go/analysis/passes/tests/tests.go +++ b/go/analysis/passes/tests/tests.go @@ -17,7 +17,6 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/internal/analysisutil" - "golang.org/x/tools/internal/typeparams" ) //go:embed doc.go @@ -391,7 +390,7 @@ func checkExampleName(pass *analysis.Pass, fn *ast.FuncDecl) { if results := fn.Type.Results; results != nil && len(results.List) != 0 { pass.Reportf(fn.Pos(), "%s should return nothing", fnName) } - if tparams := typeparams.ForFuncType(fn.Type); tparams != nil && len(tparams.List) > 0 { + if tparams := fn.Type.TypeParams; tparams != nil && len(tparams.List) > 0 { pass.Reportf(fn.Pos(), "%s should not have type params", fnName) } @@ -460,7 +459,7 @@ func checkTest(pass *analysis.Pass, fn *ast.FuncDecl, prefix string) { return } - if tparams := typeparams.ForFuncType(fn.Type); tparams != nil && len(tparams.List) > 0 { + if tparams := fn.Type.TypeParams; tparams != nil && len(tparams.List) > 0 { // Note: cmd/go/internal/load also errors about TestXXX and BenchmarkXXX functions with type parameters. // We have currently decided to also warn before compilation/package loading. This can help users in IDEs. // TODO(adonovan): use ReportRangef(tparams). diff --git a/go/analysis/unitchecker/unitchecker.go b/go/analysis/unitchecker/unitchecker.go index 36eed808d87..1fa0d1f68f9 100644 --- a/go/analysis/unitchecker/unitchecker.go +++ b/go/analysis/unitchecker/unitchecker.go @@ -50,7 +50,6 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/internal/analysisflags" "golang.org/x/tools/internal/facts" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" ) @@ -259,10 +258,10 @@ func run(fset *token.FileSet, cfg *Config, analyzers []*analysis.Analyzer) ([]re Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(info) versions.InitFileVersions(info) pkg, err := tc.Check(cfg.ImportPath, fset, files, info) diff --git a/go/ast/astutil/enclosing.go b/go/ast/astutil/enclosing.go index c05873a8b94..2c4c4e23289 100644 --- a/go/ast/astutil/enclosing.go +++ b/go/ast/astutil/enclosing.go @@ -11,8 +11,6 @@ import ( "go/ast" "go/token" "sort" - - "golang.org/x/tools/internal/typeparams" ) // PathEnclosingInterval returns the node that encloses the source @@ -322,7 +320,7 @@ func childrenOf(n ast.Node) []ast.Node { children = append(children, n.Recv) } children = append(children, n.Name) - if tparams := typeparams.ForFuncType(n.Type); tparams != nil { + if tparams := n.Type.TypeParams; tparams != nil { children = append(children, tparams) } if n.Type.Params != nil { diff --git a/go/ast/astutil/rewrite.go b/go/ast/astutil/rewrite.go index 94bc887dc20..58934f76633 100644 --- a/go/ast/astutil/rewrite.go +++ b/go/ast/astutil/rewrite.go @@ -9,8 +9,6 @@ import ( "go/ast" "reflect" "sort" - - "golang.org/x/tools/internal/typeparams" ) // An ApplyFunc is invoked by Apply for each node n, even if n is nil, @@ -293,7 +291,7 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. a.apply(n, "Fields", nil, n.Fields) case *ast.FuncType: - if tparams := typeparams.ForFuncType(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { a.apply(n, "TypeParams", nil, tparams) } a.apply(n, "Params", nil, n.Params) @@ -408,7 +406,7 @@ func (a *application) apply(parent ast.Node, name string, iter *iterator, n ast. case *ast.TypeSpec: a.apply(n, "Doc", nil, n.Doc) a.apply(n, "Name", nil, n.Name) - if tparams := typeparams.ForTypeSpec(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { a.apply(n, "TypeParams", nil, tparams) } a.apply(n, "Type", nil, n.Type) diff --git a/go/callgraph/vta/graph.go b/go/callgraph/vta/graph.go index 987859c023a..f68f4536e32 100644 --- a/go/callgraph/vta/graph.go +++ b/go/callgraph/vta/graph.go @@ -676,7 +676,7 @@ func (b *builder) multiconvert(c *ssa.MultiConvert) { // Common case. // Specializing the len=1 case to avoid a slice // had no measurable space/time benefit. - terms = []*types.Term{typeparams.NewTerm(false, typ)} + terms = []*types.Term{types.NewTerm(false, typ)} } if err != nil { diff --git a/go/loader/loader.go b/go/loader/loader.go index 41ee08b9b0a..013c0f505bb 100644 --- a/go/loader/loader.go +++ b/go/loader/loader.go @@ -23,7 +23,6 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/go/internal/cgo" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" ) @@ -1034,13 +1033,13 @@ func (imp *importer) newPackageInfo(path, dir string) *PackageInfo { Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), }, errorFunc: imp.conf.TypeChecker.Error, dir: dir, } - typeparams.InitInstanceInfo(&info.Info) versions.InitFileVersions(&info.Info) // Copy the types.Config so we can vary it across PackageInfos. diff --git a/go/packages/packages.go b/go/packages/packages.go index bd79efc1aaf..81e9e6a727d 100644 --- a/go/packages/packages.go +++ b/go/packages/packages.go @@ -27,7 +27,6 @@ import ( "golang.org/x/tools/go/gcexportdata" "golang.org/x/tools/internal/gocommand" "golang.org/x/tools/internal/packagesinternal" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/versions" ) @@ -1015,10 +1014,10 @@ func (ld *loader) loadPackage(lpkg *loaderPackage) { Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(lpkg.TypesInfo) versions.InitFileVersions(lpkg.TypesInfo) lpkg.TypesSizes = ld.sizes diff --git a/go/ssa/builder_test.go b/go/ssa/builder_test.go index 2186d2578a9..a15ab97aca9 100644 --- a/go/ssa/builder_test.go +++ b/go/ssa/builder_test.go @@ -26,7 +26,6 @@ import ( "golang.org/x/tools/go/ssa" "golang.org/x/tools/go/ssa/ssautil" "golang.org/x/tools/internal/testenv" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/txtar" ) @@ -689,10 +688,10 @@ func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer) p := prog.Package(lprog.Package("p").Pkg) p.Build() - if load := p.Func("Load"); typeparams.ForSignature(load.Signature).Len() != 1 { + if load := p.Func("Load"); load.Signature.TypeParams().Len() != 1 { t.Errorf("expected a single type param T for Load got %q", load.Signature) } - if ptr := p.Type("Pointer"); typeparams.ForNamed(ptr.Type().(*types.Named)).Len() != 1 { + if ptr := p.Type("Pointer"); ptr.Type().(*types.Named).TypeParams().Len() != 1 { t.Errorf("expected a single type param T for Pointer got %q", ptr.Type()) } } diff --git a/go/ssa/const_test.go b/go/ssa/const_test.go index d8e0c8a593a..c8ecadf7f0f 100644 --- a/go/ssa/const_test.go +++ b/go/ssa/const_test.go @@ -15,7 +15,6 @@ import ( "testing" "golang.org/x/tools/go/ssa" - "golang.org/x/tools/internal/typeparams" ) func TestConstString(t *testing.T) { @@ -93,7 +92,7 @@ func TestConstString(t *testing.T) { // Test type-param gen := pkg.Scope().Lookup("gen") - tp := typeparams.ForSignature(gen.Type().(*types.Signature)).At(0) + tp := gen.Type().(*types.Signature).TypeParams().At(0) if got, want := ssa.NewConst(nil, tp).String(), "0:T"; got != want { t.Errorf("ssa.NewConst(%v, %s).String() = %v, want %v", nil, tup, got, want) } diff --git a/go/ssa/coretype.go b/go/ssa/coretype.go index 957696bcdbd..88136b43842 100644 --- a/go/ssa/coretype.go +++ b/go/ssa/coretype.go @@ -60,7 +60,7 @@ func typeSetOf(typ types.Type) termList { // Common case. // Specializing the len=1 case to avoid a slice // had no measurable space/time benefit. - terms = []*types.Term{typeparams.NewTerm(false, typ)} + terms = []*types.Term{types.NewTerm(false, typ)} } if err != nil { diff --git a/go/ssa/create.go b/go/ssa/create.go index c5f952df399..c4da35d0b08 100644 --- a/go/ssa/create.go +++ b/go/ssa/create.go @@ -15,7 +15,6 @@ import ( "os" "sync" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" ) @@ -40,7 +39,7 @@ func NewProgram(fset *token.FileSet, mode BuilderMode) *Program { packages: make(map[*types.Package]*Package), mode: mode, canon: newCanonizer(), - ctxt: typeparams.NewContext(), + ctxt: types.NewContext(), parameterized: tpWalker{seen: make(map[types.Type]bool)}, } } @@ -118,9 +117,9 @@ func createFunction(prog *Program, obj *types.Func, name string, syntax ast.Node // Collect type parameters. var tparams *types.TypeParamList - if rtparams := typeparams.RecvTypeParams(sig); rtparams.Len() > 0 { + if rtparams := sig.RecvTypeParams(); rtparams.Len() > 0 { tparams = rtparams // method of generic type - } else if sigparams := typeparams.ForSignature(sig); sigparams.Len() > 0 { + } else if sigparams := sig.TypeParams(); sigparams.Len() > 0 { tparams = sigparams // generic function } diff --git a/go/ssa/func.go b/go/ssa/func.go index 65ed491bab6..22f878d4ed4 100644 --- a/go/ssa/func.go +++ b/go/ssa/func.go @@ -14,8 +14,6 @@ import ( "io" "os" "strings" - - "golang.org/x/tools/internal/typeparams" ) // Like ObjectOf, but panics instead of returning nil. @@ -45,7 +43,7 @@ func (f *Function) typ(T types.Type) types.Type { // If id is an Instance, returns info.Instances[id].Type. // Otherwise returns f.typeOf(id). func (f *Function) instanceType(id *ast.Ident) types.Type { - if t, ok := typeparams.GetInstances(f.info)[id]; ok { + if t, ok := f.info.Instances[id]; ok { return t.Type } return f.typeOf(id) diff --git a/go/ssa/instantiate.go b/go/ssa/instantiate.go index 370284ab72a..c155f6736af 100644 --- a/go/ssa/instantiate.go +++ b/go/ssa/instantiate.go @@ -59,7 +59,7 @@ func createInstance(fn *Function, targs []types.Type, cr *creator) *Function { sig = obj.Type().(*types.Signature) } else { // function - instSig, err := typeparams.Instantiate(prog.ctxt, fn.Signature, targs, false) + instSig, err := types.Instantiate(prog.ctxt, fn.Signature, targs, false) if err != nil { panic(err) } diff --git a/go/ssa/parameterized.go b/go/ssa/parameterized.go index 63160b4e49b..84db49d392f 100644 --- a/go/ssa/parameterized.go +++ b/go/ssa/parameterized.go @@ -105,9 +105,9 @@ func (w *tpWalker) isParameterizedLocked(typ types.Type) (res bool) { return w.isParameterizedLocked(t.Elem()) case *types.Named: - args := typeparams.NamedTypeArgs(t) + args := t.TypeArgs() // TODO(taking): this does not match go/types/infer.go. Check with rfindley. - if params := typeparams.ForNamed(t); params.Len() > args.Len() { + if params := t.TypeParams(); params.Len() > args.Len() { return true } for i, n := 0, args.Len(); i < n; i++ { diff --git a/go/ssa/ssautil/load.go b/go/ssa/ssautil/load.go index a1d4d74261f..3daa67a07e4 100644 --- a/go/ssa/ssautil/load.go +++ b/go/ssa/ssautil/load.go @@ -14,7 +14,6 @@ import ( "golang.org/x/tools/go/loader" "golang.org/x/tools/go/packages" "golang.org/x/tools/go/ssa" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" ) @@ -163,10 +162,10 @@ func BuildPackage(tc *types.Config, fset *token.FileSet, pkg *types.Package, fil Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(info) versions.InitFileVersions(info) if err := types.NewChecker(tc, fset, pkg, info).Files(files); err != nil { return nil, nil, err diff --git a/go/ssa/ssautil/visit.go b/go/ssa/ssautil/visit.go index 3cdd3462271..b4feb42cb3a 100644 --- a/go/ssa/ssautil/visit.go +++ b/go/ssa/ssautil/visit.go @@ -9,7 +9,6 @@ import ( "go/types" "golang.org/x/tools/go/ssa" - "golang.org/x/tools/internal/typeparams" _ "unsafe" // for linkname hack ) @@ -105,7 +104,7 @@ func AllFunctions(prog *ssa.Program) map[*ssa.Function]bool { // Consider only named types. // (Ignore aliases and unsafe.Pointer.) if named, ok := t.Type().(*types.Named); ok { - if typeparams.ForNamed(named) == nil { + if named.TypeParams() == nil { methodsOf(named) // T methodsOf(types.NewPointer(named)) // *T } diff --git a/go/ssa/subst.go b/go/ssa/subst.go index ae8718daee7..a9a6d41e813 100644 --- a/go/ssa/subst.go +++ b/go/ssa/subst.go @@ -6,8 +6,6 @@ package ssa import ( "go/types" - - "golang.org/x/tools/internal/typeparams" ) // Type substituter for a fixed set of replacement types. @@ -233,12 +231,12 @@ func (subst *subster) union(u *types.Union) *types.Union { } } if out != nil { - out[i] = typeparams.NewTerm(t.Tilde(), r) + out[i] = types.NewTerm(t.Tilde(), r) } } if out != nil { - return typeparams.NewUnion(out) + return types.NewUnion(out) } return u } @@ -310,7 +308,7 @@ func (subst *subster) named(t *types.Named) types.Type { // (2) locally scoped type, // (3) generic (type parameters but no type arguments), or // (4) instantiated (type parameters and type arguments). - tparams := typeparams.ForNamed(t) + tparams := t.TypeParams() if tparams.Len() == 0 { if subst.scope != nil && !subst.scope.Contains(t.Obj().Pos()) { // Outside the current function scope? @@ -344,7 +342,7 @@ func (subst *subster) named(t *types.Named) types.Type { n.SetUnderlying(subst.typ(t.Underlying())) return n } - targs := typeparams.NamedTypeArgs(t) + targs := t.TypeArgs() // insts are arguments to instantiate using. insts := make([]types.Type, tparams.Len()) @@ -367,13 +365,13 @@ func (subst *subster) named(t *types.Named) types.Type { inst := subst.typ(targs.At(i)) // TODO(generic): Check with rfindley for mutual recursion insts[i] = inst } - r, err := typeparams.Instantiate(subst.ctxt, typeparams.NamedTypeOrigin(t), insts, false) + r, err := types.Instantiate(subst.ctxt, t.Origin(), insts, false) assert(err == nil, "failed to Instantiate Named type") return r } func (subst *subster) signature(t *types.Signature) types.Type { - tparams := typeparams.ForSignature(t) + tparams := t.TypeParams() // We are choosing not to support tparams.Len() > 0 until a need has been observed in practice. // @@ -398,7 +396,7 @@ func (subst *subster) signature(t *types.Signature) types.Type { params := subst.tuple(t.Params()) results := subst.tuple(t.Results()) if recv != t.Recv() || params != t.Params() || results != t.Results() { - return typeparams.NewSignatureType(recv, nil, nil, params, results, t.Variadic()) + return types.NewSignatureType(recv, nil, nil, params, results, t.Variadic()) } return t } diff --git a/go/ssa/subst_test.go b/go/ssa/subst_test.go index e4aeaa1c312..6652b1a8e97 100644 --- a/go/ssa/subst_test.go +++ b/go/ssa/subst_test.go @@ -10,8 +10,6 @@ import ( "go/token" "go/types" "testing" - - "golang.org/x/tools/internal/typeparams" ) func TestSubst(t *testing.T) { @@ -96,7 +94,7 @@ var _ L[int] = Fn0[L[int]](nil) T := tv.Type.(*types.Named) - subst := makeSubster(typeparams.NewContext(), nil, typeparams.ForNamed(T), targs, true) + subst := makeSubster(types.NewContext(), nil, T.TypeParams(), targs, true) sub := subst.typ(T.Underlying()) if got := sub.String(); got != test.want { t.Errorf("subst{%v->%v}.typ(%s) = %v, want %v", test.expr, test.args, T.Underlying(), got, test.want) diff --git a/go/ssa/util.go b/go/ssa/util.go index dd6ff19da28..6e9f1282b1b 100644 --- a/go/ssa/util.go +++ b/go/ssa/util.go @@ -192,7 +192,7 @@ func receiverTypeArgs(obj *types.Func) []types.Type { if !ok { return nil } - ts := typeparams.NamedTypeArgs(named) + ts := named.TypeArgs() if ts.Len() == 0 { return nil } @@ -211,7 +211,7 @@ func recvAsFirstArg(sig *types.Signature) *types.Signature { for i := 0; i < sig.Params().Len(); i++ { params = append(params, sig.Params().At(i)) } - return typeparams.NewSignatureType(nil, nil, nil, types.NewTuple(params...), sig.Results(), sig.Variadic()) + return types.NewSignatureType(nil, nil, nil, types.NewTuple(params...), sig.Results(), sig.Variadic()) } // instance returns whether an expression is a simple or qualified identifier @@ -228,13 +228,13 @@ func instance(info *types.Info, expr ast.Expr) bool { default: return false } - _, ok := typeparams.GetInstances(info)[id] + _, ok := info.Instances[id] return ok } // instanceArgs returns the Instance[id].TypeArgs as a slice. func instanceArgs(info *types.Info, id *ast.Ident) []types.Type { - targList := typeparams.GetInstances(info)[id].TypeArgs + targList := info.Instances[id].TypeArgs if targList == nil { return nil } @@ -358,7 +358,7 @@ func (canon *canonizer) instantiateMethod(m *types.Func, targs []types.Type, ctx recv = p.Elem() } named := recv.(*types.Named) - inst, err := typeparams.Instantiate(ctxt, typeparams.NamedTypeOrigin(named), targs, false) + inst, err := types.Instantiate(ctxt, named.Origin(), targs, false) if err != nil { panic(err) } diff --git a/go/types/objectpath/objectpath.go b/go/types/objectpath/objectpath.go index 86f89836d80..11d5c8c3adf 100644 --- a/go/types/objectpath/objectpath.go +++ b/go/types/objectpath/objectpath.go @@ -283,7 +283,7 @@ func (enc *Encoder) For(obj types.Object) (Path, error) { } } else { if named, _ := T.(*types.Named); named != nil { - if r := findTypeParam(obj, typeparams.ForNamed(named), path, nil); r != nil { + if r := findTypeParam(obj, named.TypeParams(), path, nil); r != nil { // generic named type return Path(r), nil } @@ -462,7 +462,7 @@ func find(obj types.Object, T types.Type, path []byte, seen map[*types.TypeName] } return find(obj, T.Elem(), append(path, opElem), seen) case *types.Signature: - if r := findTypeParam(obj, typeparams.ForSignature(T), path, seen); r != nil { + if r := findTypeParam(obj, T.TypeParams(), path, seen); r != nil { return r } if r := find(obj, T.Params(), append(path, opParams), seen); r != nil { diff --git a/go/types/typeutil/callee_test.go b/go/types/typeutil/callee_test.go index 3ce6879ee5f..faee0f88721 100644 --- a/go/types/typeutil/callee_test.go +++ b/go/types/typeutil/callee_test.go @@ -14,7 +14,6 @@ import ( "testing" "golang.org/x/tools/go/types/typeutil" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" ) @@ -123,10 +122,10 @@ func testStaticCallee(t *testing.T, contents []string) { packages := make(map[string]*types.Package) cfg := &types.Config{Importer: closure(packages)} info := &types.Info{ + Instances: make(map[*ast.Ident]types.Instance), Uses: make(map[*ast.Ident]types.Object), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(info) versions.InitFileVersions(info) var files []*ast.File diff --git a/go/types/typeutil/map.go b/go/types/typeutil/map.go index 6b67ca882ec..544246dac1c 100644 --- a/go/types/typeutil/map.go +++ b/go/types/typeutil/map.go @@ -297,7 +297,7 @@ func (h Hasher) hashFor(t types.Type) uint32 { // We should never encounter a generic signature while hashing another // generic signature, but defensively set sigTParams only if h.mask is // unset. - tparams := typeparams.ForSignature(t) + tparams := t.TypeParams() if h.sigTParams == nil && tparams.Len() != 0 { h = Hasher{ // There may be something more efficient than discarding the existing @@ -354,7 +354,7 @@ func (h Hasher) hashFor(t types.Type) uint32 { case *types.Named: hash := h.hashPtr(t.Obj()) - targs := typeparams.NamedTypeArgs(t) + targs := t.TypeArgs() for i := 0; i < targs.Len(); i++ { targ := targs.At(i) hash += 2 * h.Hash(targ) diff --git a/go/types/typeutil/map_test.go b/go/types/typeutil/map_test.go index 5d875cecf9c..4891f7687d5 100644 --- a/go/types/typeutil/map_test.go +++ b/go/types/typeutil/map_test.go @@ -17,7 +17,6 @@ import ( "testing" "golang.org/x/tools/go/types/typeutil" - "golang.org/x/tools/internal/typeparams" ) var ( @@ -280,8 +279,8 @@ var Issue56048b = Issue56048_Ib.m U = CI.EmbeddedType(0).(*types.Union) Fa1 = scope.Lookup("Fa1").Type().(*types.Signature) Fa2 = scope.Lookup("Fa2").Type().(*types.Signature) - Fa1P = typeparams.ForSignature(Fa1).At(0) - Fa2Q = typeparams.ForSignature(Fa2).At(0) + Fa1P = Fa1.TypeParams().At(0) + Fa2Q = Fa2.TypeParams().At(0) Fb1 = scope.Lookup("Fb1").Type().(*types.Signature) Fb1x = Fb1.Params().At(0).Type() Fb1y = scope.Lookup("Fb1").(*types.Func).Scope().Lookup("y").Type() @@ -392,7 +391,7 @@ var Issue56048b = Issue56048_Ib.m } func instantiate(t *testing.T, origin types.Type, targs ...types.Type) types.Type { - inst, err := typeparams.Instantiate(nil, origin, targs, true) + inst, err := types.Instantiate(nil, origin, targs, true) if err != nil { t.Fatal(err) } diff --git a/gopls/internal/analysis/fillreturns/fillreturns.go b/gopls/internal/analysis/fillreturns/fillreturns.go index fb70c541eaa..cc584a70562 100644 --- a/gopls/internal/analysis/fillreturns/fillreturns.go +++ b/gopls/internal/analysis/fillreturns/fillreturns.go @@ -18,7 +18,6 @@ import ( "golang.org/x/tools/go/ast/astutil" "golang.org/x/tools/internal/analysisinternal" "golang.org/x/tools/internal/fuzzy" - "golang.org/x/tools/internal/typeparams" ) //go:embed doc.go @@ -108,7 +107,7 @@ outer: // have 0 values. // TODO(rfindley): We should be able to handle this if the return // values are all concrete types. - if tparams := typeparams.ForFuncType(enclosingFunc); tparams != nil && tparams.NumFields() > 0 { + if tparams := enclosingFunc.TypeParams; tparams != nil && tparams.NumFields() > 0 { return nil, nil } diff --git a/gopls/internal/analysis/infertypeargs/run_go118.go b/gopls/internal/analysis/infertypeargs/run_go118.go index e7317685abd..b3fff4e8408 100644 --- a/gopls/internal/analysis/infertypeargs/run_go118.go +++ b/gopls/internal/analysis/infertypeargs/run_go118.go @@ -40,7 +40,7 @@ func DiagnoseInferableTypeArgs(fset *token.FileSet, inspect *inspector.Inspector } // Confirm that instantiation actually occurred at this ident. - idata, ok := typeparams.GetInstances(info)[ident] + idata, ok := info.Instances[ident] if !ok { return // something went wrong, but fail open } @@ -64,14 +64,15 @@ func DiagnoseInferableTypeArgs(fset *token.FileSet, inspect *inspector.Inspector Ellipsis: call.Ellipsis, Rparen: call.Rparen, } - info := new(types.Info) - typeparams.InitInstanceInfo(info) + info := &types.Info{ + Instances: make(map[*ast.Ident]types.Instance), + } versions.InitFileVersions(info) if err := types.CheckExpr(fset, pkg, call.Pos(), newCall, info); err != nil { // Most likely inference failed. break } - newIData := typeparams.GetInstances(info)[ident] + newIData := info.Instances[ident] newInstance := newIData.Type if !types.Identical(instance, newInstance) { // The inferred result type does not match the original result type, so diff --git a/gopls/internal/analysis/useany/useany.go b/gopls/internal/analysis/useany/useany.go index 799b35fd538..ff25e5945d3 100644 --- a/gopls/internal/analysis/useany/useany.go +++ b/gopls/internal/analysis/useany/useany.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/go/analysis" "golang.org/x/tools/go/analysis/passes/inspect" "golang.org/x/tools/go/ast/inspector" - "golang.org/x/tools/internal/typeparams" ) const Doc = `check for constraints that could be simplified to "any"` @@ -42,9 +41,9 @@ func run(pass *analysis.Pass) (interface{}, error) { var tparams *ast.FieldList switch node := node.(type) { case *ast.TypeSpec: - tparams = typeparams.ForTypeSpec(node) + tparams = node.TypeParams case *ast.FuncType: - tparams = typeparams.ForFuncType(node) + tparams = node.TypeParams default: panic(fmt.Sprintf("unexpected node type %T", node)) } diff --git a/gopls/internal/lsp/cache/analysis.go b/gopls/internal/lsp/cache/analysis.go index c5c0004963c..dfbb9ef6c0e 100644 --- a/gopls/internal/lsp/cache/analysis.go +++ b/gopls/internal/lsp/cache/analysis.go @@ -45,7 +45,6 @@ import ( "golang.org/x/tools/internal/event/tag" "golang.org/x/tools/internal/facts" "golang.org/x/tools/internal/gcimporter" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/versions" ) @@ -928,14 +927,14 @@ func (an *analysisNode) typeCheck(parsed []*ParsedGoFile) *analysisPackage { typesInfo: &types.Info{ Types: make(map[ast.Expr]types.TypeAndValue), Defs: make(map[*ast.Ident]types.Object), - Uses: make(map[*ast.Ident]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Implicits: make(map[ast.Node]types.Object), Selections: make(map[*ast.SelectorExpr]*types.Selection), Scopes: make(map[ast.Node]*types.Scope), + Uses: make(map[*ast.Ident]types.Object), }, typesSizes: mp.TypesSizes, } - typeparams.InitInstanceInfo(pkg.typesInfo) versions.InitFileVersions(pkg.typesInfo) // Unsafe has no syntax. diff --git a/gopls/internal/lsp/cache/check.go b/gopls/internal/lsp/cache/check.go index 90d7b3804d9..9a48b4b346f 100644 --- a/gopls/internal/lsp/cache/check.go +++ b/gopls/internal/lsp/cache/check.go @@ -35,7 +35,6 @@ import ( "golang.org/x/tools/internal/gcimporter" "golang.org/x/tools/internal/packagesinternal" "golang.org/x/tools/internal/tokeninternal" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/typesinternal" "golang.org/x/tools/internal/versions" ) @@ -1441,11 +1440,11 @@ func (b *typeCheckBatch) checkPackage(ctx context.Context, ph *packageHandle) (* Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Selections: make(map[*ast.SelectorExpr]*types.Selection), Scopes: make(map[ast.Node]*types.Scope), }, } - typeparams.InitInstanceInfo(pkg.typesInfo) versions.InitFileVersions(pkg.typesInfo) // Collect parsed files from the type check pass, capturing parse errors from @@ -1524,7 +1523,7 @@ func (b *typeCheckBatch) checkPackage(ctx context.Context, ph *packageHandle) (* // Work around golang/go#61561: interface instances aren't concurrency-safe // as they are not completed by the type checker. - for _, inst := range typeparams.GetInstances(pkg.typesInfo) { + for _, inst := range pkg.typesInfo.Instances { if iface, _ := inst.Type.Underlying().(*types.Interface); iface != nil { iface.Complete() } diff --git a/gopls/internal/lsp/cache/typerefs/refs.go b/gopls/internal/lsp/cache/typerefs/refs.go index 878f53da86a..53dcd5e4359 100644 --- a/gopls/internal/lsp/cache/typerefs/refs.go +++ b/gopls/internal/lsp/cache/typerefs/refs.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/gopls/internal/lsp/cache/parsego" "golang.org/x/tools/gopls/internal/util/astutil" "golang.org/x/tools/gopls/internal/util/frob" - "golang.org/x/tools/internal/typeparams" ) // Encode analyzes the Go syntax trees of a package, constructs a @@ -365,7 +364,7 @@ func visitFile(file *ast.File, imports map[metadata.ImportPath]*metadata.Package case token.TYPE: for _, spec := range d.Specs { spec := spec.(*ast.TypeSpec) - tparams := tparamsMap(typeparams.ForTypeSpec(spec)) + tparams := tparamsMap(spec.TypeParams) visit(spec.Name, spec, tparams) } @@ -400,7 +399,7 @@ func visitFile(file *ast.File, imports map[metadata.ImportPath]*metadata.Package } } else { // Non-method. - tparams := tparamsMap(typeparams.ForFuncType(d.Type)) + tparams := tparamsMap(d.Type.TypeParams) visit(d.Name, d, tparams) } } @@ -450,7 +449,7 @@ func visitDeclOrSpec(node ast.Node, f refVisitor) { case *ast.TypeSpec: // Skip Doc, Name, and Comment, which do not affect the decl type. - if tparams := typeparams.ForTypeSpec(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { visitFieldList(tparams, f) } visitExpr(n.Type, f) @@ -563,7 +562,7 @@ func visitExpr(expr ast.Expr, f refVisitor) { visitFieldList(n.Fields, f) case *ast.FuncType: - if tparams := typeparams.ForFuncType(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { visitFieldList(tparams, f) } if n.Params != nil { diff --git a/gopls/internal/lsp/source/completion/completion.go b/gopls/internal/lsp/source/completion/completion.go index 6b1665fe7b1..d241cbdf31a 100644 --- a/gopls/internal/lsp/source/completion/completion.go +++ b/gopls/internal/lsp/source/completion/completion.go @@ -1651,7 +1651,7 @@ func (c *completer) injectType(ctx context.Context, t types.Type) { // considered via a lexical search, so we need to directly inject // them. Also allow generic types since lexical search does not // infer instantiated versions of them. - if named, _ := t.(*types.Named); named == nil || typeparams.ForNamed(named).Len() > 0 { + if named, _ := t.(*types.Named); named == nil || named.TypeParams().Len() > 0 { // If our expected type is "[]int", this will add a literal // candidate of "[]int{}". c.literal(ctx, t, nil) @@ -2244,7 +2244,7 @@ Nodes: sig, _ := c.pkg.GetTypesInfo().Types[node.Fun].Type.(*types.Signature) - if sig != nil && typeparams.ForSignature(sig).Len() > 0 { + if sig != nil && sig.TypeParams().Len() > 0 { // If we are completing a generic func call, re-check the call expression. // This allows type param inference to work in cases like: // @@ -2448,9 +2448,9 @@ func (c *completer) expectedCallParamType(inf candidateInference, node *ast.Call func expectedConstraint(t types.Type, idx int) types.Type { var tp *types.TypeParamList if named, _ := t.(*types.Named); named != nil { - tp = typeparams.ForNamed(named) + tp = named.TypeParams() } else if sig, _ := t.Underlying().(*types.Signature); sig != nil { - tp = typeparams.ForSignature(sig) + tp = sig.TypeParams() } if tp == nil || idx >= tp.Len() { return nil diff --git a/gopls/internal/lsp/source/completion/format.go b/gopls/internal/lsp/source/completion/format.go index d47c04564c6..0d47161c4d0 100644 --- a/gopls/internal/lsp/source/completion/format.go +++ b/gopls/internal/lsp/source/completion/format.go @@ -19,7 +19,6 @@ import ( "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/imports" - "golang.org/x/tools/internal/typeparams" ) var ( @@ -62,7 +61,7 @@ func (c *completer) item(ctx context.Context, cand candidate) (CompletionItem, e if isTypeName(obj) && c.wantTypeParams() { x := cand.obj.(*types.TypeName) if named, ok := x.Type().(*types.Named); ok { - tp := typeparams.ForNamed(named) + tp := named.TypeParams() label += source.FormatTypeParams(tp) insert = label // maintain invariant above (label == insert) } diff --git a/gopls/internal/lsp/source/completion/literal.go b/gopls/internal/lsp/source/completion/literal.go index fe97269baef..b48407b12e1 100644 --- a/gopls/internal/lsp/source/completion/literal.go +++ b/gopls/internal/lsp/source/completion/literal.go @@ -15,7 +15,6 @@ import ( "golang.org/x/tools/gopls/internal/lsp/source" "golang.org/x/tools/gopls/internal/lsp/source/completion/snippet" "golang.org/x/tools/internal/event" - "golang.org/x/tools/internal/typeparams" ) // literal generates composite literal, function literal, and make() @@ -513,7 +512,7 @@ func (c *completer) typeNameSnippet(literalType types.Type, qf types.Qualifier) named, _ = literalType.(*types.Named) ) - if named != nil && named.Obj() != nil && typeparams.ForNamed(named).Len() > 0 && !c.fullyInstantiated(named) { + if named != nil && named.Obj() != nil && named.TypeParams().Len() > 0 && !c.fullyInstantiated(named) { // We are not "fully instantiated" meaning we have type params that must be specified. if pkg := qf(named.Obj().Pkg()); pkg != "" { typeName = pkg + "." @@ -524,12 +523,12 @@ func (c *completer) typeNameSnippet(literalType types.Type, qf types.Qualifier) snip.WriteText(typeName + "[") if c.opts.placeholders { - for i := 0; i < typeparams.ForNamed(named).Len(); i++ { + for i := 0; i < named.TypeParams().Len(); i++ { if i > 0 { snip.WriteText(", ") } snip.WritePlaceholder(func(snip *snippet.Builder) { - snip.WriteText(types.TypeString(typeparams.ForNamed(named).At(i), qf)) + snip.WriteText(types.TypeString(named.TypeParams().At(i), qf)) }) } } else { @@ -549,8 +548,8 @@ func (c *completer) typeNameSnippet(literalType types.Type, qf types.Qualifier) // fullyInstantiated reports whether all of t's type params have // specified type args. func (c *completer) fullyInstantiated(t *types.Named) bool { - tps := typeparams.ForNamed(t) - tas := typeparams.NamedTypeArgs(t) + tps := t.TypeParams() + tas := t.TypeArgs() if tps.Len() != tas.Len() { return false diff --git a/gopls/internal/lsp/source/completion/util.go b/gopls/internal/lsp/source/completion/util.go index c2a693d4615..82c56e05775 100644 --- a/gopls/internal/lsp/source/completion/util.go +++ b/gopls/internal/lsp/source/completion/util.go @@ -14,7 +14,6 @@ import ( "golang.org/x/tools/gopls/internal/lsp/source" "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/diff" - "golang.org/x/tools/internal/typeparams" ) // exprAtPos returns the index of the expression containing pos. @@ -148,7 +147,7 @@ func isFunc(obj types.Object) bool { func isEmptyInterface(T types.Type) bool { intf, _ := T.(*types.Interface) - return intf != nil && intf.NumMethods() == 0 && typeparams.IsMethodSet(intf) + return intf != nil && intf.NumMethods() == 0 && intf.IsMethodSet() } func isUntyped(T types.Type) bool { diff --git a/gopls/internal/lsp/source/hover.go b/gopls/internal/lsp/source/hover.go index 4dc747dabdc..e9968a26b77 100644 --- a/gopls/internal/lsp/source/hover.go +++ b/gopls/internal/lsp/source/hover.go @@ -34,7 +34,6 @@ import ( "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/tokeninternal" - "golang.org/x/tools/internal/typeparams" ) // HoverJSON contains information used by hover. It is also the JSON returned @@ -682,7 +681,7 @@ func hoverEmbed(fh file.Handle, rng protocol.Range, pattern string) (protocol.Ra func inferredSignatureString(obj types.Object, qf types.Qualifier, inferred *types.Signature) string { // If the signature type was inferred, prefer the inferred signature with a // comment showing the generic signature. - if sig, _ := obj.Type().(*types.Signature); sig != nil && typeparams.ForSignature(sig).Len() > 0 && inferred != nil { + if sig, _ := obj.Type().(*types.Signature); sig != nil && sig.TypeParams().Len() > 0 && inferred != nil { obj2 := types.NewFunc(obj.Pos(), obj.Pkg(), obj.Name(), inferred) str := types.ObjectString(obj2, qf) // Try to avoid overly long lines. diff --git a/gopls/internal/lsp/source/identifier.go b/gopls/internal/lsp/source/identifier.go index 57001af930b..9e12e3fd222 100644 --- a/gopls/internal/lsp/source/identifier.go +++ b/gopls/internal/lsp/source/identifier.go @@ -8,8 +8,6 @@ import ( "errors" "go/ast" "go/types" - - "golang.org/x/tools/internal/typeparams" ) // ErrNoIdentFound is error returned when no identifier is found at a particular position @@ -20,7 +18,7 @@ var ErrNoIdentFound = errors.New("no identifier found") // // If no such signature exists, it returns nil. func inferredSignature(info *types.Info, id *ast.Ident) *types.Signature { - inst := typeparams.GetInstances(info)[id] + inst := info.Instances[id] sig, _ := inst.Type.(*types.Signature) return sig } diff --git a/gopls/internal/lsp/source/inlay_hint.go b/gopls/internal/lsp/source/inlay_hint.go index ae63277dd6f..41dd6709eb7 100644 --- a/gopls/internal/lsp/source/inlay_hint.go +++ b/gopls/internal/lsp/source/inlay_hint.go @@ -17,7 +17,6 @@ import ( "golang.org/x/tools/gopls/internal/lsp/cache" "golang.org/x/tools/gopls/internal/lsp/protocol" "golang.org/x/tools/internal/event" - "golang.org/x/tools/internal/typeparams" ) const ( @@ -188,7 +187,7 @@ func funcTypeParams(node ast.Node, m *protocol.Mapper, tf *token.File, info *typ if !ok { return nil } - inst := typeparams.GetInstances(info)[id] + inst := info.Instances[id] if inst.TypeArgs == nil { return nil } diff --git a/gopls/internal/lsp/source/stub.go b/gopls/internal/lsp/source/stub.go index d070d0a89c4..32c656ad44c 100644 --- a/gopls/internal/lsp/source/stub.go +++ b/gopls/internal/lsp/source/stub.go @@ -27,7 +27,6 @@ import ( "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/diff" "golang.org/x/tools/internal/tokeninternal" - "golang.org/x/tools/internal/typeparams" ) // stubSuggestedFixFunc returns a suggested fix to declare the missing @@ -185,7 +184,7 @@ func (%s%s%s) %s%s { iface, star, si.Concrete.Obj().Name(), - FormatTypeParams(typeparams.ForNamed(si.Concrete)), + FormatTypeParams(si.Concrete.TypeParams()), method.Name(), strings.TrimPrefix(types.TypeString(method.Type(), qual), "func")) } diff --git a/gopls/internal/lsp/source/types_format.go b/gopls/internal/lsp/source/types_format.go index ecb33c66612..b6306b98b8b 100644 --- a/gopls/internal/lsp/source/types_format.go +++ b/gopls/internal/lsp/source/types_format.go @@ -201,7 +201,7 @@ func FormatTypeParams(tparams *types.TypeParamList) string { // NewSignature returns formatted signature for a types.Signature struct. func NewSignature(ctx context.Context, s *cache.Snapshot, pkg *cache.Package, sig *types.Signature, comment *ast.CommentGroup, qf types.Qualifier, mq MetadataQualifier) (*signature, error) { var tparams []string - tpList := typeparams.ForSignature(sig) + tpList := sig.TypeParams() for i := 0; i < tpList.Len(); i++ { tparam := tpList.At(i) // TODO: is it possible to reuse the logic from FormatVarType here? @@ -310,7 +310,7 @@ func FormatVarType(ctx context.Context, snapshot *cache.Snapshot, srcpkg *cache. // We can't handle type parameters correctly, so we fall back on TypeString // for parameterized decls. if decl, _ := decl.(*ast.FuncDecl); decl != nil { - if typeparams.ForFuncType(decl.Type).NumFields() > 0 { + if decl.Type.TypeParams.NumFields() > 0 { return types.TypeString(obj.Type(), qf), nil // in generic function } if decl.Recv != nil && len(decl.Recv.List) > 0 { @@ -323,7 +323,7 @@ func FormatVarType(ctx context.Context, snapshot *cache.Snapshot, srcpkg *cache. } } } - if spec, _ := spec.(*ast.TypeSpec); spec != nil && typeparams.ForTypeSpec(spec).NumFields() > 0 { + if spec, _ := spec.(*ast.TypeSpec); spec != nil && spec.TypeParams.NumFields() > 0 { return types.TypeString(obj.Type(), qf), nil // in generic type decl } diff --git a/gopls/internal/server/semantic.go b/gopls/internal/server/semantic.go index 1421e9bda9c..b84279ca0c6 100644 --- a/gopls/internal/server/semantic.go +++ b/gopls/internal/server/semantic.go @@ -27,7 +27,6 @@ import ( "golang.org/x/tools/gopls/internal/util/safetoken" "golang.org/x/tools/internal/event" "golang.org/x/tools/internal/event/tag" - "golang.org/x/tools/internal/typeparams" ) // The LSP says that errors for the semantic token requests should only be returned @@ -789,7 +788,7 @@ func (e *encoded) definitionFor(x *ast.Ident, def types.Object) (tokenType, []st } func isTypeParam(x *ast.Ident, y *ast.FuncType) bool { - tp := typeparams.ForFuncType(y) + tp := y.TypeParams if tp == nil { return false } diff --git a/internal/facts/imports.go b/internal/facts/imports.go index 5c69b75072a..1fe63ca6b51 100644 --- a/internal/facts/imports.go +++ b/internal/facts/imports.go @@ -6,8 +6,6 @@ package facts import ( "go/types" - - "golang.org/x/tools/internal/typeparams" ) // importMap computes the import map for a package by traversing the @@ -55,7 +53,7 @@ func importMap(imports []*types.Package) map[string]*types.Package { // infinite expansions: // type N[T any] struct { F *N[N[T]] } // importMap() is called on such types when Analyzer.RunDespiteErrors is true. - T = typeparams.NamedTypeOrigin(T) + T = T.Origin() if !typs[T] { typs[T] = true addObj(T.Obj()) @@ -63,12 +61,12 @@ func importMap(imports []*types.Package) map[string]*types.Package { for i := 0; i < T.NumMethods(); i++ { addObj(T.Method(i)) } - if tparams := typeparams.ForNamed(T); tparams != nil { + if tparams := T.TypeParams(); tparams != nil { for i := 0; i < tparams.Len(); i++ { addType(tparams.At(i)) } } - if targs := typeparams.NamedTypeArgs(T); targs != nil { + if targs := T.TypeArgs(); targs != nil { for i := 0; i < targs.Len(); i++ { addType(targs.At(i)) } @@ -88,7 +86,7 @@ func importMap(imports []*types.Package) map[string]*types.Package { case *types.Signature: addType(T.Params()) addType(T.Results()) - if tparams := typeparams.ForSignature(T); tparams != nil { + if tparams := T.TypeParams(); tparams != nil { for i := 0; i < tparams.Len(); i++ { addType(tparams.At(i)) } diff --git a/internal/gcimporter/bexport_test.go b/internal/gcimporter/bexport_test.go index f722d0084c3..72fa8a2a31e 100644 --- a/internal/gcimporter/bexport_test.go +++ b/internal/gcimporter/bexport_test.go @@ -19,7 +19,6 @@ import ( "testing" "golang.org/x/tools/internal/gcimporter" - "golang.org/x/tools/internal/typeparams" ) var isRace = false @@ -143,10 +142,10 @@ func equalType(x, y types.Type) error { // return fmt.Errorf("receiver: %s", err) // } } - if err := equalTypeParams(typeparams.ForSignature(x), typeparams.ForSignature(y)); err != nil { + if err := equalTypeParams(x.TypeParams(), y.TypeParams()); err != nil { return fmt.Errorf("type params: %s", err) } - if err := equalTypeParams(typeparams.RecvTypeParams(x), typeparams.RecvTypeParams(y)); err != nil { + if err := equalTypeParams(x.RecvTypeParams(), y.RecvTypeParams()); err != nil { return fmt.Errorf("recv type params: %s", err) } case *types.Slice: @@ -209,15 +208,15 @@ func equalType(x, y types.Type) error { // cmpNamed compares two named types x and y, returning an error for any // discrepancies. It does not compare their underlying types. func cmpNamed(x, y *types.Named) error { - xOrig := typeparams.NamedTypeOrigin(x) - yOrig := typeparams.NamedTypeOrigin(y) + xOrig := x.Origin() + yOrig := y.Origin() if xOrig.String() != yOrig.String() { return fmt.Errorf("unequal named types: %s vs %s", x, y) } - if err := equalTypeParams(typeparams.ForNamed(x), typeparams.ForNamed(y)); err != nil { + if err := equalTypeParams(x.TypeParams(), y.TypeParams()); err != nil { return fmt.Errorf("type parameters: %s", err) } - if err := equalTypeArgs(typeparams.NamedTypeArgs(x), typeparams.NamedTypeArgs(y)); err != nil { + if err := equalTypeArgs(x.TypeArgs(), y.TypeArgs()); err != nil { return fmt.Errorf("type arguments: %s", err) } if x.NumMethods() != y.NumMethods() { @@ -252,7 +251,7 @@ func cmpNamed(x, y *types.Named) error { // makeExplicit returns an explicit version of typ, if typ is an implicit // interface. Otherwise it returns typ unmodified. func makeExplicit(typ types.Type) types.Type { - if iface, _ := typ.(*types.Interface); iface != nil && typeparams.IsImplicit(iface) { + if iface, _ := typ.(*types.Interface); iface != nil && iface.IsImplicit() { var methods []*types.Func for i := 0; i < iface.NumExplicitMethods(); i++ { methods = append(methods, iface.Method(i)) diff --git a/internal/gcimporter/iexport.go b/internal/gcimporter/iexport.go index 828f5550979..2ee8c70164f 100644 --- a/internal/gcimporter/iexport.go +++ b/internal/gcimporter/iexport.go @@ -24,7 +24,6 @@ import ( "golang.org/x/tools/go/types/objectpath" "golang.org/x/tools/internal/tokeninternal" - "golang.org/x/tools/internal/typeparams" ) // IExportShallow encodes "shallow" export data for the specified package. @@ -481,7 +480,7 @@ func (p *iexporter) doDecl(obj types.Object) { } // Function. - if typeparams.ForSignature(sig).Len() == 0 { + if sig.TypeParams().Len() == 0 { w.tag('F') } else { w.tag('G') @@ -494,7 +493,7 @@ func (p *iexporter) doDecl(obj types.Object) { // // While importing the type parameters, tparamList computes and records // their export name, so that it can be later used when writing the index. - if tparams := typeparams.ForSignature(sig); tparams.Len() > 0 { + if tparams := sig.TypeParams(); tparams.Len() > 0 { w.tparamList(obj.Name(), tparams, obj.Pkg()) } w.signature(sig) @@ -514,7 +513,7 @@ func (p *iexporter) doDecl(obj types.Object) { if p.version >= iexportVersionGo1_18 { implicit := false if iface, _ := constraint.(*types.Interface); iface != nil { - implicit = typeparams.IsImplicit(iface) + implicit = iface.IsImplicit() } w.bool(implicit) } @@ -535,17 +534,17 @@ func (p *iexporter) doDecl(obj types.Object) { panic(internalErrorf("%s is not a defined type", t)) } - if typeparams.ForNamed(named).Len() == 0 { + if named.TypeParams().Len() == 0 { w.tag('T') } else { w.tag('U') } w.pos(obj.Pos()) - if typeparams.ForNamed(named).Len() > 0 { + if named.TypeParams().Len() > 0 { // While importing the type parameters, tparamList computes and records // their export name, so that it can be later used when writing the index. - w.tparamList(obj.Name(), typeparams.ForNamed(named), obj.Pkg()) + w.tparamList(obj.Name(), named.TypeParams(), obj.Pkg()) } underlying := obj.Type().Underlying() @@ -565,7 +564,7 @@ func (p *iexporter) doDecl(obj types.Object) { // Receiver type parameters are type arguments of the receiver type, so // their name must be qualified before exporting recv. - if rparams := typeparams.RecvTypeParams(sig); rparams.Len() > 0 { + if rparams := sig.RecvTypeParams(); rparams.Len() > 0 { prefix := obj.Name() + "." + m.Name() for i := 0; i < rparams.Len(); i++ { rparam := rparams.At(i) @@ -740,13 +739,13 @@ func (w *exportWriter) doTyp(t types.Type, pkg *types.Package) { } switch t := t.(type) { case *types.Named: - if targs := typeparams.NamedTypeArgs(t); targs.Len() > 0 { + if targs := t.TypeArgs(); targs.Len() > 0 { w.startType(instanceType) // TODO(rfindley): investigate if this position is correct, and if it // matters. w.pos(t.Obj().Pos()) w.typeList(targs, pkg) - w.typ(typeparams.NamedTypeOrigin(t), pkg) + w.typ(t.Origin(), pkg) return } w.startType(definedType) diff --git a/internal/gcimporter/iimport.go b/internal/gcimporter/iimport.go index 391764f9ee2..9bde15e3bc6 100644 --- a/internal/gcimporter/iimport.go +++ b/internal/gcimporter/iimport.go @@ -22,7 +22,6 @@ import ( "strings" "golang.org/x/tools/go/types/objectpath" - "golang.org/x/tools/internal/typeparams" ) type intReader struct { @@ -321,7 +320,7 @@ func iimportCommon(fset *token.FileSet, getPackages GetPackagesFunc, data []byte // Therefore, we defer calling SetConstraint there, and call it here instead // after all types are complete. for _, d := range p.later { - typeparams.SetTypeParamConstraint(d.t, d.constraint) + d.t.SetConstraint(d.constraint) } for _, typ := range p.interfaceList { @@ -566,7 +565,7 @@ func (r *importReader) obj(name string) { r.declare(obj) if tag == 'U' { tparams := r.tparamList() - typeparams.SetForNamed(named, tparams) + named.SetTypeParams(tparams) } underlying := r.p.typAt(r.uint64(), named).Underlying() @@ -583,7 +582,7 @@ func (r *importReader) obj(name string) { // typeparams being used in the method sig/body). base := baseType(recv.Type()) assert(base != nil) - targs := typeparams.NamedTypeArgs(base) + targs := base.TypeArgs() var rparams []*types.TypeParam if targs.Len() > 0 { rparams = make([]*types.TypeParam, targs.Len()) @@ -606,7 +605,7 @@ func (r *importReader) obj(name string) { } name0 := tparamName(name) tn := types.NewTypeName(pos, r.currPkg, name0, nil) - t := typeparams.NewTypeParam(tn, nil) + t := types.NewTypeParam(tn, nil) // To handle recursive references to the typeparam within its // bound, save the partial type in tparamIndex before reading the bounds. @@ -622,7 +621,7 @@ func (r *importReader) obj(name string) { if iface == nil { errorf("non-interface constraint marked implicit") } - typeparams.MarkImplicit(iface) + iface.MarkImplicit() } // The constraint type may not be complete, if we // are in the middle of a type recursion involving type @@ -966,7 +965,7 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { // The imported instantiated type doesn't include any methods, so // we must always use the methods of the base (orig) type. // TODO provide a non-nil *Environment - t, _ := typeparams.Instantiate(nil, baseType, targs, false) + t, _ := types.Instantiate(nil, baseType, targs, false) // Workaround for golang/go#61561. See the doc for instanceList for details. r.p.instanceList = append(r.p.instanceList, t) @@ -978,9 +977,9 @@ func (r *importReader) doType(base *types.Named) (res types.Type) { } terms := make([]*types.Term, r.uint64()) for i := range terms { - terms[i] = typeparams.NewTerm(r.bool(), r.typ()) + terms[i] = types.NewTerm(r.bool(), r.typ()) } - return typeparams.NewUnion(terms) + return types.NewUnion(terms) } } @@ -1012,7 +1011,7 @@ func (r *importReader) signature(recv *types.Var, rparams []*types.TypeParam, tp params := r.paramList() results := r.paramList() variadic := params.Len() > 0 && r.bool() - return typeparams.NewSignatureType(recv, rparams, tparams, params, results, variadic) + return types.NewSignatureType(recv, rparams, tparams, params, results, variadic) } func (r *importReader) tparamList() []*types.TypeParam { diff --git a/internal/typeparams/common.go b/internal/typeparams/common.go index ae7e5c5c988..cdab9885314 100644 --- a/internal/typeparams/common.go +++ b/internal/typeparams/common.go @@ -100,11 +100,11 @@ func OriginMethod(fn *types.Func) *types.Func { // Receiver is a *types.Interface. return fn } - if ForNamed(named).Len() == 0 { + if named.TypeParams().Len() == 0 { // Receiver base has no type parameters, so we can avoid the lookup below. return fn } - orig := NamedTypeOrigin(named) + orig := named.Origin() gfn, _, _ := types.LookupFieldOrMethod(orig, true, fn.Pkg(), fn.Name()) // This is a fix for a gopls crash (#60628) due to a go/types bug (#60634). In: @@ -167,9 +167,9 @@ func GenericAssignableTo(ctxt *types.Context, V, T types.Type) bool { return types.AssignableTo(V, T) } - vtparams := ForNamed(VN) - ttparams := ForNamed(TN) - if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || NamedTypeArgs(VN).Len() != 0 || NamedTypeArgs(TN).Len() != 0 { + vtparams := VN.TypeParams() + ttparams := TN.TypeParams() + if vtparams.Len() == 0 || vtparams.Len() != ttparams.Len() || VN.TypeArgs().Len() != 0 || TN.TypeArgs().Len() != 0 { return types.AssignableTo(V, T) } @@ -182,7 +182,7 @@ func GenericAssignableTo(ctxt *types.Context, V, T types.Type) bool { // Minor optimization: ensure we share a context across the two // instantiations below. if ctxt == nil { - ctxt = NewContext() + ctxt = types.NewContext() } var targs []types.Type @@ -190,12 +190,12 @@ func GenericAssignableTo(ctxt *types.Context, V, T types.Type) bool { targs = append(targs, vtparams.At(i)) } - vinst, err := Instantiate(ctxt, V, targs, true) + vinst, err := types.Instantiate(ctxt, V, targs, true) if err != nil { panic("type parameters should satisfy their own constraints") } - tinst, err := Instantiate(ctxt, T, targs, true) + tinst, err := types.Instantiate(ctxt, T, targs, true) if err != nil { return false } diff --git a/internal/typeparams/coretype.go b/internal/typeparams/coretype.go index c2dc8e2982e..7ea8840eab7 100644 --- a/internal/typeparams/coretype.go +++ b/internal/typeparams/coretype.go @@ -117,6 +117,6 @@ func _NormalTerms(typ types.Type) ([]*types.Term, error) { case *types.Interface: return InterfaceTermSet(typ) default: - return []*types.Term{NewTerm(false, typ)}, nil + return []*types.Term{types.NewTerm(false, typ)}, nil } } diff --git a/internal/typeparams/genericfeatures/features.go b/internal/typeparams/genericfeatures/features.go index 8ceef867451..e307e677758 100644 --- a/internal/typeparams/genericfeatures/features.go +++ b/internal/typeparams/genericfeatures/features.go @@ -12,7 +12,6 @@ import ( "strings" "golang.org/x/tools/go/ast/inspector" - "golang.org/x/tools/internal/typeparams" ) // Features is a set of flags reporting which features of generic Go code a @@ -77,23 +76,22 @@ func ForPackage(inspect *inspector.Inspector, info *types.Info) Features { inspect.Preorder(nodeFilter, func(node ast.Node) { switch n := node.(type) { case *ast.FuncType: - if tparams := typeparams.ForFuncType(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { direct |= GenericFuncDecls } case *ast.InterfaceType: tv := info.Types[n] - if iface, _ := tv.Type.(*types.Interface); iface != nil && !typeparams.IsMethodSet(iface) { + if iface, _ := tv.Type.(*types.Interface); iface != nil && !iface.IsMethodSet() { direct |= EmbeddedTypeSets } case *ast.TypeSpec: - if tparams := typeparams.ForTypeSpec(n); tparams != nil { + if tparams := n.TypeParams; tparams != nil { direct |= GenericTypeDecls } } }) - instances := typeparams.GetInstances(info) - for _, inst := range instances { + for _, inst := range info.Instances { switch inst.Type.(type) { case *types.Named: direct |= TypeInstantiation diff --git a/internal/typeparams/normalize.go b/internal/typeparams/normalize.go index d88efa509a3..93c80fdc96c 100644 --- a/internal/typeparams/normalize.go +++ b/internal/typeparams/normalize.go @@ -105,7 +105,7 @@ func computeTermSet(typ types.Type) ([]*types.Term, error) { } var terms []*types.Term for _, term := range tset.terms { - terms = append(terms, NewTerm(term.tilde, term.typ)) + terms = append(terms, types.NewTerm(term.tilde, term.typ)) } return terms, nil } diff --git a/internal/typeparams/normalize_test.go b/internal/typeparams/normalize_test.go index a6253fa4dea..d2c678c90ff 100644 --- a/internal/typeparams/normalize_test.go +++ b/internal/typeparams/normalize_test.go @@ -13,7 +13,6 @@ import ( "strings" "testing" - "golang.org/x/tools/internal/typeparams" . "golang.org/x/tools/internal/typeparams" ) @@ -72,7 +71,7 @@ type T[P interface{ A|B; C }] int if obj == nil { t.Fatal("type T not found") } - T := typeparams.ForNamed(obj.Type().(*types.Named)).At(0) + T := obj.Type().(*types.Named).TypeParams().At(0) terms, err := StructuralTerms(T) if test.wantError != "" { if err == nil { @@ -91,7 +90,7 @@ type T[P interface{ A|B; C }] int got = "all" } else { qf := types.RelativeTo(pkg) - got = types.TypeString(NewUnion(terms), qf) + got = types.TypeString(types.NewUnion(terms), qf) } want := regexp.MustCompile(test.want) if !want.MatchString(got) { diff --git a/internal/typeparams/typeparams_go118.go b/internal/typeparams/typeparams_go118.go deleted file mode 100644 index 54e8e9711d9..00000000000 --- a/internal/typeparams/typeparams_go118.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2021 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package typeparams - -import ( - "go/ast" - "go/types" -) - -// TODO(adonovan): melt the trivial functions away. - -// ForTypeSpec returns n.TypeParams. -func ForTypeSpec(n *ast.TypeSpec) *ast.FieldList { - if n == nil { - return nil - } - return n.TypeParams -} - -// ForFuncType returns n.TypeParams. -func ForFuncType(n *ast.FuncType) *ast.FieldList { - if n == nil { - return nil - } - return n.TypeParams -} - -// NewTypeParam calls types.NewTypeParam. -func NewTypeParam(name *types.TypeName, constraint types.Type) *types.TypeParam { - return types.NewTypeParam(name, constraint) -} - -// SetTypeParamConstraint calls tparam.SetConstraint(constraint). -func SetTypeParamConstraint(tparam *types.TypeParam, constraint types.Type) { - tparam.SetConstraint(constraint) -} - -// NewSignatureType calls types.NewSignatureType. -func NewSignatureType(recv *types.Var, recvTypeParams, typeParams []*types.TypeParam, params, results *types.Tuple, variadic bool) *types.Signature { - return types.NewSignatureType(recv, recvTypeParams, typeParams, params, results, variadic) -} - -// ForSignature returns sig.TypeParams() -func ForSignature(sig *types.Signature) *types.TypeParamList { - return sig.TypeParams() -} - -// RecvTypeParams returns sig.RecvTypeParams(). -func RecvTypeParams(sig *types.Signature) *types.TypeParamList { - return sig.RecvTypeParams() -} - -// IsComparable calls iface.IsComparable(). -func IsComparable(iface *types.Interface) bool { - return iface.IsComparable() -} - -// IsMethodSet calls iface.IsMethodSet(). -func IsMethodSet(iface *types.Interface) bool { - return iface.IsMethodSet() -} - -// IsImplicit calls iface.IsImplicit(). -func IsImplicit(iface *types.Interface) bool { - return iface.IsImplicit() -} - -// MarkImplicit calls iface.MarkImplicit(). -func MarkImplicit(iface *types.Interface) { - iface.MarkImplicit() -} - -// ForNamed extracts the (possibly empty) type parameter object list from -// named. -func ForNamed(named *types.Named) *types.TypeParamList { - return named.TypeParams() -} - -// SetForNamed sets the type params tparams on n. Each tparam must be of -// dynamic type *types.TypeParam. -func SetForNamed(n *types.Named, tparams []*types.TypeParam) { - n.SetTypeParams(tparams) -} - -// NamedTypeArgs returns named.TypeArgs(). -func NamedTypeArgs(named *types.Named) *types.TypeList { - return named.TypeArgs() -} - -// NamedTypeOrigin returns named.Orig(). -func NamedTypeOrigin(named *types.Named) *types.Named { - return named.Origin() -} - -// NewTerm calls types.NewTerm. -func NewTerm(tilde bool, typ types.Type) *types.Term { - return types.NewTerm(tilde, typ) -} - -// NewUnion calls types.NewUnion. -func NewUnion(terms []*types.Term) *types.Union { - return types.NewUnion(terms) -} - -// InitInstanceInfo initializes info to record information about type and -// function instances. -func InitInstanceInfo(info *types.Info) { - info.Instances = make(map[*ast.Ident]types.Instance) -} - -// GetInstances returns info.Instances. -func GetInstances(info *types.Info) map[*ast.Ident]types.Instance { - return info.Instances -} - -// NewContext calls types.NewContext. -func NewContext() *types.Context { - return types.NewContext() -} - -// Instantiate calls types.Instantiate. -func Instantiate(ctxt *types.Context, typ types.Type, targs []types.Type, validate bool) (types.Type, error) { - return types.Instantiate(ctxt, typ, targs, validate) -} diff --git a/refactor/satisfy/find.go b/refactor/satisfy/find.go index 19cf4722c57..612f0a8e0f5 100644 --- a/refactor/satisfy/find.go +++ b/refactor/satisfy/find.go @@ -732,6 +732,6 @@ func instance(info *types.Info, expr ast.Expr) bool { default: return false } - _, ok := typeparams.GetInstances(info)[id] + _, ok := info.Instances[id] return ok } diff --git a/refactor/satisfy/find_test.go b/refactor/satisfy/find_test.go index e6ffa423686..daa8b219ef2 100644 --- a/refactor/satisfy/find_test.go +++ b/refactor/satisfy/find_test.go @@ -15,7 +15,6 @@ import ( "sort" "testing" - "golang.org/x/tools/internal/typeparams" "golang.org/x/tools/internal/versions" "golang.org/x/tools/refactor/satisfy" ) @@ -221,10 +220,10 @@ func constraints(t *testing.T, src string) []string { Defs: make(map[*ast.Ident]types.Object), Uses: make(map[*ast.Ident]types.Object), Implicits: make(map[ast.Node]types.Object), + Instances: make(map[*ast.Ident]types.Instance), Scopes: make(map[ast.Node]*types.Scope), Selections: make(map[*ast.SelectorExpr]*types.Selection), } - typeparams.InitInstanceInfo(info) versions.InitFileVersions(info) conf := types.Config{ Importer: importer.Default(),