github.com/grailbio/bigslice@v0.0.0-20230519005545-30c4c12152ad/typecheck/func.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache 2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package typecheck
     6  
     7  import (
     8  	"github.com/grailbio/bigslice/slicefunc"
     9  	"github.com/grailbio/bigslice/slicetype"
    10  )
    11  
    12  // CanApply returns whether fn can be applied to arg.
    13  func CanApply(fn slicefunc.Func, arg slicetype.Type) bool {
    14  	if fn.IsVariadic {
    15  		if arg.NumOut() < fn.In.NumOut()-1 {
    16  			// Not enough arguments.
    17  			return false
    18  		}
    19  		for i := 0; i < fn.In.NumOut()-1; i++ {
    20  			if !arg.Out(i).AssignableTo(fn.In.Out(i)) {
    21  				// Non-variadic mismatch.
    22  				return false
    23  			}
    24  		}
    25  		variadicType := fn.In.Out(fn.In.NumOut() - 1).Elem()
    26  		for i := fn.In.NumOut() - 1; i < arg.NumOut(); i++ {
    27  			if !arg.Out(i).AssignableTo(variadicType) {
    28  				// Variadic mismatch.
    29  				return false
    30  			}
    31  		}
    32  		return true
    33  	}
    34  	if arg.NumOut() != fn.In.NumOut() {
    35  		return false
    36  	}
    37  	for i := 0; i < fn.In.NumOut(); i++ {
    38  		if !arg.Out(i).AssignableTo(fn.In.Out(i)) {
    39  			return false
    40  		}
    41  	}
    42  	return true
    43  }