github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/func_call.go (about)

     1  package expressions
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/runtime/core"
     7  	"github.com/MontFerret/ferret/pkg/runtime/values"
     8  )
     9  
    10  type FunctionCallExpression struct {
    11  	src  core.SourceMap
    12  	fun  core.Function
    13  	args []core.Expression
    14  }
    15  
    16  func NewFunctionCallExpression(
    17  	src core.SourceMap,
    18  	fun core.Function,
    19  	args []core.Expression,
    20  ) (*FunctionCallExpression, error) {
    21  	if fun == nil {
    22  		return nil, core.Error(core.ErrMissedArgument, "function")
    23  	}
    24  
    25  	return &FunctionCallExpression{src, fun, args}, nil
    26  }
    27  
    28  func NewFunctionCallExpressionWith(
    29  	src core.SourceMap,
    30  	fun core.Function,
    31  	args ...core.Expression,
    32  ) (*FunctionCallExpression, error) {
    33  	return NewFunctionCallExpression(src, fun, args)
    34  }
    35  
    36  func (e *FunctionCallExpression) Arguments() []core.Expression {
    37  	return e.args
    38  }
    39  
    40  func (e *FunctionCallExpression) Function() core.Function {
    41  	return e.fun
    42  }
    43  
    44  func (e *FunctionCallExpression) Exec(ctx context.Context, scope *core.Scope) (core.Value, error) {
    45  	select {
    46  	case <-ctx.Done():
    47  		return values.None, core.ErrTerminated
    48  	default:
    49  		var out core.Value
    50  		var err error
    51  
    52  		if len(e.args) == 0 {
    53  			out, err = e.fun(ctx)
    54  		} else {
    55  			args := make([]core.Value, len(e.args))
    56  
    57  			for idx, arg := range e.args {
    58  				out, err := arg.Exec(ctx, scope)
    59  
    60  				if err != nil {
    61  					return values.None, core.SourceError(e.src, err)
    62  				}
    63  
    64  				args[idx] = out
    65  			}
    66  
    67  			out, err = e.fun(ctx, args...)
    68  		}
    69  
    70  		if err != nil {
    71  			return values.None, core.SourceError(e.src, err)
    72  		}
    73  
    74  		return out, nil
    75  	}
    76  }