// Copyright (c) 2024 Celestino Amoroso (celestino.amoroso@gmail.com). // All rights reserved. // operand-func.go package expr import ( "errors" ) // -------- 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 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 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, parent: nil, children: args, // arg[0]=formal-param-list, arg[1]=*ast 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 }