| 1 |
// Copyright 2024 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package aliases |
| 6 |
|
| 7 |
import ( |
| 8 |
"go/token" |
| 9 |
"go/types" |
| 10 |
) |
| 11 |
|
| 12 |
// Package aliases defines backward compatible shims |
| 13 |
// for the types.Alias type representation added in 1.22. |
| 14 |
// This defines placeholders for x/tools until 1.26. |
| 15 |
|
| 16 |
// NewAlias creates a new TypeName in Package pkg that |
| 17 |
// is an alias for the type rhs. |
| 18 |
// |
| 19 |
// The enabled parameter determines whether the resulting [TypeName]'s |
| 20 |
// type is an [types.Alias]. Its value must be the result of a call to |
| 21 |
// [Enabled], which computes the effective value of |
| 22 |
// GODEBUG=gotypesalias=... by invoking the type checker. The Enabled |
| 23 |
// function is expensive and should be called once per task (e.g. |
| 24 |
// package import), not once per call to NewAlias. |
| 25 |
// |
| 26 |
// Precondition: enabled || len(tparams)==0. |
| 27 |
// If materialized aliases are disabled, there must not be any type parameters. |
| 28 |
func NewAlias(enabled bool, pos token.Pos, pkg *types.Package, name string, rhs types.Type, tparams []*types.TypeParam) *types.TypeName { |
| 29 |
if enabled { |
| 30 |
tname := types.NewTypeName(pos, pkg, name, nil) |
| 31 |
SetTypeParams(types.NewAlias(tname, rhs), tparams) |
| 32 |
return tname |
| 33 |
} |
| 34 |
if len(tparams) > 0 { |
| 35 |
panic("cannot create an alias with type parameters when gotypesalias is not enabled") |
| 36 |
} |
| 37 |
return types.NewTypeName(pos, pkg, name, rhs) |
| 38 |
} |