| 1 |
// Copyright 2021 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 typeparams contains common utilities for writing tools that |
| 6 |
// interact with generic Go code, as introduced with Go 1.18. It |
| 7 |
// supplements the standard library APIs. Notably, the StructuralTerms |
| 8 |
// API computes a minimal representation of the structural |
| 9 |
// restrictions on a type parameter. |
| 10 |
// |
| 11 |
// An external version of these APIs is available in the |
| 12 |
// golang.org/x/exp/typeparams module. |
| 13 |
package typeparams |
| 14 |
|
| 15 |
import ( |
| 16 |
"go/ast" |
| 17 |
"go/token" |
| 18 |
"go/types" |
| 19 |
) |
| 20 |
|
| 21 |
// UnpackIndexExpr extracts data from AST nodes that represent index |
| 22 |
// expressions. |
| 23 |
// |
| 24 |
// For an ast.IndexExpr, the resulting indices slice will contain exactly one |
| 25 |
// index expression. For an ast.IndexListExpr (go1.18+), it may have a variable |
| 26 |
// number of index expressions. |
| 27 |
// |
| 28 |
// For nodes that don't represent index expressions, the first return value of |
| 29 |
// UnpackIndexExpr will be nil. |
| 30 |
func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) { |
| 31 |
switch e := n.(type) { |
| 32 |
case *ast.IndexExpr: |
| 33 |
return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack |
| 34 |
case *ast.IndexListExpr: |
| 35 |
return e.X, e.Lbrack, e.Indices, e.Rbrack |
| 36 |
} |
| 37 |
return nil, token.NoPos, nil, token.NoPos |
| 38 |
} |
| 39 |
|
| 40 |
// PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on |
| 41 |
// the cardinality of indices. Calling PackIndexExpr with len(indices) == 0 |
| 42 |
// will panic. |
| 43 |
func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr { |
| 44 |
switch len(indices) { |
| 45 |
case 0: |
| 46 |
panic("empty indices") |
| 47 |
case 1: |
| 48 |
return &ast.IndexExpr{ |
| 49 |
X: x, |
| 50 |
Lbrack: lbrack, |
| 51 |
Index: indices[0], |
| 52 |
Rbrack: rbrack, |
| 53 |
} |
| 54 |
default: |
| 55 |
return &ast.IndexListExpr{ |
| 56 |
X: x, |
| 57 |
Lbrack: lbrack, |
| 58 |
Indices: indices, |
| 59 |
Rbrack: rbrack, |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
// IsTypeParam reports whether t is a type parameter (or an alias of one). |
| 65 |
func IsTypeParam(t types.Type) bool { |
| 66 |
_, ok := types.Unalias(t).(*types.TypeParam) |
| 67 |
return ok |
| 68 |
} |