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  //
    37  // Note: IndexExpr (intentionally) does not wrap ast.Expr, as that leads to
    38  // accidental misuse such as encountered in golang/go#63933.
    39  //
    40  // TODO(rfindley): remove this helper, in favor of just having a helper
    41  // function that returns indices.
    42  type IndexExpr struct {
    43  	Orig    ast.Expr   // the wrapped expr, which may be distinct from the IndexListExpr below.
    44  	X       ast.Expr   // expression
    45  	Lbrack  token.Pos  // position of "["
    46  	Indices []ast.Expr // index expressions
    47  	Rbrack  token.Pos  // position of "]"
    48  }
    49  
    50  func (x *IndexExpr) Pos() token.Pos {
    51  	return x.Orig.Pos()
    52  }
    53  
    54  func UnpackIndexExpr(n ast.Node) *IndexExpr {
    55  	switch e := n.(type) {
    56  	case *ast.IndexExpr:
    57  		return &IndexExpr{
    58  			Orig:    e,
    59  			X:       e.X,
    60  			Lbrack:  e.Lbrack,
    61  			Indices: []ast.Expr{e.Index},
    62  			Rbrack:  e.Rbrack,
    63  		}
    64  	case *ast.IndexListExpr:
    65  		return &IndexExpr{
    66  			Orig:    e,
    67  			X:       e.X,
    68  			Lbrack:  e.Lbrack,
    69  			Indices: e.Indices,
    70  			Rbrack:  e.Rbrack,
    71  		}
    72  	}
    73  	return nil
    74  }
    75  

View as plain text