github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/compiler/internal/typeparams/utils.go (about)

     1  package typeparams
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"go/types"
     7  )
     8  
     9  // SignatureTypeParams returns receiver type params for methods, or function
    10  // type params for standalone functions, or nil for non-generic functions and
    11  // methods.
    12  func SignatureTypeParams(sig *types.Signature) *types.TypeParamList {
    13  	if tp := sig.RecvTypeParams(); tp != nil {
    14  		return tp
    15  	} else if tp := sig.TypeParams(); tp != nil {
    16  		return tp
    17  	} else {
    18  		return nil
    19  	}
    20  }
    21  
    22  var (
    23  	errInstantiatesGenerics = errors.New("instantiates generic type or function")
    24  	errDefinesGenerics      = errors.New("defines generic type or function")
    25  )
    26  
    27  // RequiresGenericsSupport returns an error if the type-checked code depends on
    28  // generics support.
    29  func RequiresGenericsSupport(info *types.Info) error {
    30  	type withTypeParams interface{ TypeParams() *types.TypeParamList }
    31  
    32  	for ident := range info.Instances {
    33  		// Any instantiation means dependency on generics.
    34  		return fmt.Errorf("%w: %v", errInstantiatesGenerics, info.ObjectOf(ident))
    35  	}
    36  
    37  	for _, obj := range info.Defs {
    38  		if obj == nil {
    39  			continue
    40  		}
    41  		typ, ok := obj.Type().(withTypeParams)
    42  		if ok && typ.TypeParams().Len() > 0 {
    43  			return fmt.Errorf("%w: %v", errDefinesGenerics, obj)
    44  		}
    45  	}
    46  
    47  	return nil
    48  }