aliases.go 1.4 KB

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