// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com). // All rights reserved. // operand-func.go package expr import ( "errors" "fmt" ) // -------- function call term func newFuncCallTerm(tk *Token, args []*term) *term { return &term{ tk: *tk, parent: nil, children: args, position: posLeaf, priority: priValue, evalFunc: evalFuncCall, } } // -------- eval func call func checkFunctionCall(ctx ExprContext, name string, params []any) (err error) { if info, exists, owner := GetFuncInfo(ctx, name); exists { if info.MinArgs() > len(params) { if info.MaxArgs() < 0 { err = fmt.Errorf("too few params -- expected %d or more, got %d", info.MinArgs(), len(params)) } else { err = fmt.Errorf("too few params -- expected %d, got %d", info.MinArgs(), len(params)) } } if err == nil && info.MaxArgs() >= 0 && info.MaxArgs() < len(params) { err = fmt.Errorf("too much params -- expected %d, got %d", info.MaxArgs(), len(params)) } if err == nil && owner != ctx { ctx.RegisterFunc(name, info.Functor(), info.MinArgs(), info.MaxArgs()) } } else { err = fmt.Errorf("unknown function %s()", name) } return } func evalFuncCall(parentCtx ExprContext, self *term) (v any, err error) { ctx := cloneContext(parentCtx) name, _ := self.tk.Value.(string) // fmt.Printf("Call %s(), context: %p\n", name, ctx) params := make([]any, len(self.children)) for i, tree := range self.children { var param any if param, err = tree.compute(ctx); err != nil { break } params[i] = param } if err == nil { if err = checkFunctionCall(ctx, name, params); err == nil { if v, err = ctx.Call(name, params); err == nil { exportObjects(parentCtx, ctx) } } } return } // -------- function definition term func newFuncDefTerm(tk *Token, args []*term) *term { return &term{ tk: *tk, // value is the expression body parent: nil, children: args, // function params position: posLeaf, priority: priValue, evalFunc: evalFuncDef, } } // -------- eval func def // TODO type funcDefFunctor struct { params []string expr Expr } func (functor *funcDefFunctor) Invoke(ctx ExprContext, name string, args []any) (result any, err error) { for i, p := range functor.params { if i < len(args) { arg := args[i] if functor, ok := arg.(Functor); ok { ctx.RegisterFunc(p, functor, 0, -1) } else { ctx.setVar(p, arg) } } else { ctx.setVar(p, nil) } } result, err = functor.expr.eval(ctx, false) return } func evalFuncDef(ctx ExprContext, self *term) (v any, err error) { bodySpec := self.value() if expr, ok := bodySpec.(*ast); ok { paramList := make([]string, 0, len(self.children)) for _, param := range self.children { paramList = append(paramList, param.source()) } v = &funcDefFunctor{ params: paramList, expr: expr, } } else { err = errors.New("invalid function definition: the body specification must be an expression") } return }