Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: go/internal/typeparams

     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  //go:build typeparams
     6  // +build typeparams
     7  
     8  package typeparams
     9  
    10  import (
    11  	"fmt"
    12  	"go/ast"
    13  )
    14  
    15  const Enabled = true
    16  
    17  func PackExpr(list []ast.Expr) ast.Expr {
    18  	switch len(list) {
    19  	case 0:
    20  		// Return an empty ListExpr here, rather than nil, as IndexExpr.Index must
    21  		// never be nil.
    22  		// TODO(rFindley) would a BadExpr be more appropriate here?
    23  		return &ast.ListExpr{}
    24  	case 1:
    25  		return list[0]
    26  	default:
    27  		return &ast.ListExpr{ElemList: list}
    28  	}
    29  }
    30  
    31  // TODO(gri) Should find a more efficient solution that doesn't
    32  //           require introduction of a new slice for simple
    33  //           expressions.
    34  func UnpackExpr(x ast.Expr) []ast.Expr {
    35  	if x, _ := x.(*ast.ListExpr); x != nil {
    36  		return x.ElemList
    37  	}
    38  	if x != nil {
    39  		return []ast.Expr{x}
    40  	}
    41  	return nil
    42  }
    43  
    44  func IsListExpr(n ast.Node) bool {
    45  	_, ok := n.(*ast.ListExpr)
    46  	return ok
    47  }
    48  
    49  func Get(n ast.Node) *ast.FieldList {
    50  	switch n := n.(type) {
    51  	case *ast.TypeSpec:
    52  		return n.TParams
    53  	case *ast.FuncType:
    54  		return n.TParams
    55  	default:
    56  		panic(fmt.Sprintf("node type %T has no type parameters", n))
    57  	}
    58  }
    59  
    60  func Set(n ast.Node, params *ast.FieldList) {
    61  	switch n := n.(type) {
    62  	case *ast.TypeSpec:
    63  		n.TParams = params
    64  	case *ast.FuncType:
    65  		n.TParams = params
    66  	default:
    67  		panic(fmt.Sprintf("node type %T has no type parameters", n))
    68  	}
    69  }
    70  

View as plain text