Source file src/go/internal/typeparams/typeparams.go

     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
     6  
     7  import (
     8  	"go/ast"
     9  	"go/token"
    10  )
    11  
    12  func PackIndexExpr(x ast.Expr, lbrack token.Pos, exprs []ast.Expr, rbrack token.Pos) ast.Expr {
    13  	switch len(exprs) {
    14  	case 0:
    15  		panic("internal error: PackIndexExpr with empty expr slice")
    16  	case 1:
    17  		return &ast.IndexExpr{
    18  			X:      x,
    19  			Lbrack: lbrack,
    20  			Index:  exprs[0],
    21  			Rbrack: rbrack,
    22  		}
    23  	default:
    24  		return &ast.IndexListExpr{
    25  			X:       x,
    26  			Lbrack:  lbrack,
    27  			Indices: exprs,
    28  			Rbrack:  rbrack,
    29  		}
    30  	}
    31  }
    32  
    33  // IndexExpr wraps an ast.IndexExpr or ast.IndexListExpr.
    34  //
    35  // Orig holds the original ast.Expr from which this IndexExpr was derived.
    36  type IndexExpr struct {
    37  	Orig ast.Expr // the wrapped expr, which may be distinct from the IndexListExpr below.
    38  	*ast.IndexListExpr
    39  }
    40  
    41  func UnpackIndexExpr(n ast.Node) *IndexExpr {
    42  	switch e := n.(type) {
    43  	case *ast.IndexExpr:
    44  		return &IndexExpr{e, &ast.IndexListExpr{
    45  			X:       e.X,
    46  			Lbrack:  e.Lbrack,
    47  			Indices: []ast.Expr{e.Index},
    48  			Rbrack:  e.Rbrack,
    49  		}}
    50  	case *ast.IndexListExpr:
    51  		return &IndexExpr{e, e}
    52  	}
    53  	return nil
    54  }
    55  

View as plain text