robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 9a29622b3b00ddb601

master
121.8 KiB4224 linesraw
1// User defined function support
2
3#include <assert.h>
4#include <ctype.h>
5#include <inttypes.h>
6#include <lauxlib.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "nvim/api/private/defs.h"
12#include "nvim/ascii_defs.h"
13#include "nvim/autocmd.h"
14#include "nvim/autocmd_defs.h"
15#include "nvim/buffer_defs.h"
16#include "nvim/charset.h"
17#include "nvim/cmdexpand_defs.h"
18#include "nvim/debugger.h"
19#include "nvim/errors.h"
20#include "nvim/eval.h"
21#include "nvim/eval/encode.h"
22#include "nvim/eval/funcs.h"
23#include "nvim/eval/typval.h"
24#include "nvim/eval/userfunc.h"
25#include "nvim/eval/vars.h"
26#include "nvim/ex_cmds_defs.h"
27#include "nvim/ex_docmd.h"
28#include "nvim/ex_eval.h"
29#include "nvim/ex_eval_defs.h"
30#include "nvim/ex_getln.h"
31#include "nvim/garray.h"
32#include "nvim/garray_defs.h"
33#include "nvim/gettext_defs.h"
34#include "nvim/globals.h"
35#include "nvim/hashtab.h"
36#include "nvim/input.h"
37#include "nvim/input_defs.h"
38#include "nvim/insexpand.h"
39#include "nvim/keycodes.h"
40#include "nvim/lua/executor.h"
41#include "nvim/macros_defs.h"
42#include "nvim/mbyte.h"
43#include "nvim/memory.h"
44#include "nvim/message.h"
45#include "nvim/option_vars.h"
46#include "nvim/os/input.h"
47#include "nvim/path.h"
48#include "nvim/profile.h"
49#include "nvim/regexp.h"
50#include "nvim/regexp_defs.h"
51#include "nvim/runtime.h"
52#include "nvim/search.h"
53#include "nvim/strings.h"
54#include "nvim/types_defs.h"
55#include "nvim/ui.h"
56#include "nvim/ui_defs.h"
57#include "nvim/vim_defs.h"
58
59#include "eval/userfunc.c.generated.h"
60
61/// structure used as item in "fc_defer"
62typedef struct {
63  char *dr_name;  ///< function name, allocated
64  typval_T dr_argvars[MAX_FUNC_ARGS + 1];
65  int dr_argcount;
66} defer_T;
67
68static hashtab_T func_hashtab;
69
70// Used by get_func_tv()
71static garray_T funcargs = GA_EMPTY_INIT_VALUE;
72
73// pointer to funccal for currently active function
74static funccall_T *current_funccal = NULL;
75
76// Pointer to list of previously used funccal, still around because some
77// item in it is still being used.
78static funccall_T *previous_funccal = NULL;
79
80static const char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
81static const char *e_funcdict = N_("E717: Dictionary entry already exists");
82static const char *e_funcref = N_("E718: Funcref required");
83static const char *e_nofunc = N_("E130: Unknown function: %s");
84static const char e_function_list_was_modified[]
85  = N_("E454: Function list was modified");
86static const char e_function_nesting_too_deep[]
87  = N_("E1058: Function nesting too deep");
88static const char e_no_white_space_allowed_before_str_str[]
89  = N_("E1068: No white space allowed before '%s': %s");
90static const char e_missing_heredoc_end_marker_str[]
91  = N_("E1145: Missing heredoc end marker: %s");
92static const char e_cannot_use_partial_with_dictionary_for_defer[]
93  = N_("E1300: Cannot use a partial with dictionary for :defer");
94
95void func_init(void)
96{
97  hash_init(&func_hashtab);
98}
99
100/// Return the function hash table
101hashtab_T *func_tbl_get(void)
102{
103  return &func_hashtab;
104}
105
106/// Get one function argument.
107/// Return a pointer to after the type.
108/// When something is wrong return "arg".
109static char *one_function_arg(char *arg, garray_T *newargs, bool skip)
110{
111  char *p = arg;
112
113  while (ASCII_ISALNUM(*p) || *p == '_') {
114    p++;
115  }
116  if (arg == p || isdigit((uint8_t)(*arg))
117      || (p - arg == 9 && strncmp(arg, "firstline", 9) == 0)
118      || (p - arg == 8 && strncmp(arg, "lastline", 8) == 0)) {
119    if (!skip) {
120      semsg(_("E125: Illegal argument: %s"), arg);
121    }
122    return arg;
123  }
124
125  if (newargs != NULL) {
126    ga_grow(newargs, 1);
127    uint8_t c = (uint8_t)(*p);
128    *p = NUL;
129    char *arg_copy = xstrdup(arg);
130
131    // Check for duplicate argument name.
132    for (int i = 0; i < newargs->ga_len; i++) {
133      if (strcmp(((char **)(newargs->ga_data))[i], arg_copy) == 0) {
134        semsg(_("E853: Duplicate argument name: %s"), arg_copy);
135        xfree(arg_copy);
136        return arg;
137      }
138    }
139    ((char **)(newargs->ga_data))[newargs->ga_len] = arg_copy;
140    newargs->ga_len++;
141
142    *p = (char)c;
143  }
144
145  return p;
146}
147
148/// Get function arguments.
149static int get_function_args(char **argp, char endchar, garray_T *newargs, int *varargs,
150                             garray_T *default_args, bool skip)
151{
152  bool mustend = false;
153  char *arg = *argp;
154  char *p = arg;
155
156  if (newargs != NULL) {
157    ga_init(newargs, (int)sizeof(char *), 3);
158  }
159  if (default_args != NULL) {
160    ga_init(default_args, (int)sizeof(char *), 3);
161  }
162
163  if (varargs != NULL) {
164    *varargs = false;
165  }
166
167  // Isolate the arguments: "arg1, arg2, ...)"
168  bool any_default = false;
169  while (*p != endchar) {
170    if (p[0] == '.' && p[1] == '.' && p[2] == '.') {
171      if (varargs != NULL) {
172        *varargs = true;
173      }
174      p += 3;
175      mustend = true;
176    } else {
177      arg = p;
178      p = one_function_arg(p, newargs, skip);
179      if (p == arg) {
180        break;
181      }
182
183      if (*skipwhite(p) == '=' && default_args != NULL) {
184        typval_T rettv;
185
186        any_default = true;
187        p = skipwhite(p) + 1;
188        p = skipwhite(p);
189        char *expr = p;
190        if (eval1(&p, &rettv, NULL) != FAIL) {
191          ga_grow(default_args, 1);
192
193          // trim trailing whitespace
194          while (p > expr && ascii_iswhite(p[-1])) {
195            p--;
196          }
197          uint8_t c = (uint8_t)(*p);
198          *p = NUL;
199          expr = xstrdup(expr);
200          ((char **)(default_args->ga_data))[default_args->ga_len] = expr;
201          default_args->ga_len++;
202          *p = (char)c;
203        } else {
204          mustend = true;
205        }
206      } else if (any_default) {
207        emsg(_("E989: Non-default argument follows default argument"));
208        mustend = true;
209      }
210
211      if (ascii_iswhite(*p) && *skipwhite(p) == ',') {
212        // Be tolerant when skipping
213        if (!skip) {
214          semsg(_(e_no_white_space_allowed_before_str_str), ",", p);
215          goto err_ret;
216        }
217        p = skipwhite(p);
218      }
219      if (*p == ',') {
220        p++;
221      } else {
222        mustend = true;
223      }
224    }
225    p = skipwhite(p);
226    if (mustend && *p != endchar) {
227      if (!skip) {
228        semsg(_(e_invarg2), *argp);
229      }
230      break;
231    }
232  }
233  if (*p != endchar) {
234    goto err_ret;
235  }
236  p++;  // skip "endchar"
237
238  *argp = p;
239  return OK;
240
241err_ret:
242  if (newargs != NULL) {
243    ga_clear_strings(newargs);
244  }
245  if (default_args != NULL) {
246    ga_clear_strings(default_args);
247  }
248  return FAIL;
249}
250
251/// Register function "fp" as using "current_funccal" as its scope.
252static void register_closure(ufunc_T *fp)
253{
254  if (fp->uf_scoped == current_funccal) {
255    // no change
256    return;
257  }
258  funccal_unref(fp->uf_scoped, fp, false);
259  fp->uf_scoped = current_funccal;
260  current_funccal->fc_refcount++;
261  ga_grow(&current_funccal->fc_ufuncs, 1);
262  ((ufunc_T **)current_funccal->fc_ufuncs.ga_data)
263  [current_funccal->fc_ufuncs.ga_len++] = fp;
264}
265
266static char lambda_name[8 + NUMBUFLEN];
267
268/// @return  a name for a lambda.  Returned in static memory.
269static String get_lambda_name(void)
270{
271  static int lambda_no = 0;
272
273  int n = snprintf(lambda_name, sizeof(lambda_name), "<lambda>%d", ++lambda_no);
274
275  return cbuf_as_string(lambda_name,
276                        n < 1 ? 0 : (size_t)MIN(n, (int)sizeof(lambda_name) - 1));
277}
278
279/// Allocate a "ufunc_T" for a function called "name".
280static ufunc_T *alloc_ufunc(const char *name, size_t namelen)
281{
282  size_t len = offsetof(ufunc_T, uf_name) + namelen + 1;
283  ufunc_T *fp = xcalloc(1, len);
284  xmemcpyz(fp->uf_name, name, namelen);
285  fp->uf_namelen = namelen;
286
287  if ((uint8_t)name[0] == K_SPECIAL) {
288    len = namelen + 3;
289    fp->uf_name_exp = xmalloc(len);
290    snprintf(fp->uf_name_exp, len, "<SNR>%s", fp->uf_name + 3);
291  }
292
293  return fp;
294}
295
296/// Parse a lambda expression and get a Funcref from "*arg".
297///
298/// @return OK or FAIL.  Returns NOTDONE for dict or {expr}.
299int get_lambda_tv(char **arg, typval_T *rettv, evalarg_T *evalarg)
300{
301  const bool evaluate = evalarg != NULL && (evalarg->eval_flags & EVAL_EVALUATE);
302  garray_T newargs = GA_EMPTY_INIT_VALUE;
303  garray_T *pnewargs;
304  ufunc_T *fp = NULL;
305  partial_T *pt = NULL;
306  int varargs;
307  bool *old_eval_lavars = eval_lavars_used;
308  bool eval_lavars = false;
309  char *tofree = NULL;
310
311  // First, check if this is a lambda expression. "->" must exists.
312  char *s = skipwhite(*arg + 1);
313  int ret = get_function_args(&s, '-', NULL, NULL, NULL, true);
314  if (ret == FAIL || *s != '>') {
315    return NOTDONE;
316  }
317
318  // Parse the arguments again.
319  if (evaluate) {
320    pnewargs = &newargs;
321  } else {
322    pnewargs = NULL;
323  }
324  *arg = skipwhite(*arg + 1);
325  ret = get_function_args(arg, '-', pnewargs, &varargs, NULL, false);
326  if (ret == FAIL || **arg != '>') {
327    goto errret;
328  }
329
330  // Set up a flag for checking local variables and arguments.
331  if (evaluate) {
332    eval_lavars_used = &eval_lavars;
333  }
334
335  // Get the start and the end of the expression.
336  *arg = skipwhite((*arg) + 1);
337  char *start = *arg;
338  ret = skip_expr(arg, evalarg);
339  char *end = *arg;
340  if (ret == FAIL) {
341    goto errret;
342  }
343  if (evalarg != NULL) {
344    // avoid that the expression gets freed when another line break follows
345    tofree = evalarg->eval_tofree;
346    evalarg->eval_tofree = NULL;
347  }
348
349  *arg = skipwhite(*arg);
350  if (**arg != '}') {
351    semsg(_("E451: Expected }: %s"), *arg);
352    goto errret;
353  }
354  (*arg)++;
355
356  if (evaluate) {
357    int flags = 0;
358    garray_T newlines;
359
360    String name = get_lambda_name();
361    fp = alloc_ufunc(name.data, name.size);
362    pt = xcalloc(1, sizeof(partial_T));
363
364    ga_init(&newlines, (int)sizeof(char *), 1);
365    ga_grow(&newlines, 1);
366
367    // Add "return " before the expression.
368    size_t len = (size_t)(7 + end - start + 1);
369    char *p = xmalloc(len);
370    ((char **)(newlines.ga_data))[newlines.ga_len++] = p;
371    STRCPY(p, "return ");
372    xmemcpyz(p + 7, start, (size_t)(end - start));
373    if (strstr(p + 7, "a:") == NULL) {
374      // No a: variables are used for sure.
375      flags |= FC_NOARGS;
376    }
377
378    fp->uf_refcount = 1;
379    hash_add(&func_hashtab, UF2HIKEY(fp));
380    fp->uf_args = newargs;
381    ga_init(&fp->uf_def_args, (int)sizeof(char *), 1);
382    fp->uf_lines = newlines;
383    if (current_funccal != NULL && eval_lavars) {
384      flags |= FC_CLOSURE;
385      register_closure(fp);
386    } else {
387      fp->uf_scoped = NULL;
388    }
389
390    if (prof_def_func()) {
391      func_do_profile(fp);
392    }
393    if (sandbox) {
394      flags |= FC_SANDBOX;
395    }
396    fp->uf_varargs = true;
397    fp->uf_flags = flags;
398    fp->uf_calls = 0;
399    fp->uf_script_ctx = current_sctx;
400    fp->uf_script_ctx.sc_lnum += SOURCING_LNUM - newlines.ga_len;
401
402    pt->pt_func = fp;
403    pt->pt_refcount = 1;
404    rettv->vval.v_partial = pt;
405    rettv->v_type = VAR_PARTIAL;
406  }
407
408  eval_lavars_used = old_eval_lavars;
409  if (evalarg != NULL && evalarg->eval_tofree == NULL) {
410    evalarg->eval_tofree = tofree;
411  } else {
412    xfree(tofree);
413  }
414  return OK;
415
416errret:
417  ga_clear_strings(&newargs);
418  assert(fp == NULL);
419  xfree(pt);
420  if (evalarg != NULL && evalarg->eval_tofree == NULL) {
421    evalarg->eval_tofree = tofree;
422  } else {
423    xfree(tofree);
424  }
425  eval_lavars_used = old_eval_lavars;
426  return FAIL;
427}
428
429/// Return name of the function corresponding to `name`
430///
431/// If `name` points to variable that is either a function or partial then
432/// corresponding function name is returned. Otherwise it returns `name` itself.
433///
434/// @param[in]  name  Function name to check.
435/// @param[in,out]  lenp  Location where length of the returned name is stored.
436///                       Must be set to the length of the `name` argument.
437/// @param[out]  partialp  Location where partial will be stored if found
438///                        function appears to be a partial. May be NULL if this
439///                        is not needed.
440/// @param[in]  no_autoload  If true, do not source autoload scripts if function
441///                          was not found.
442/// @param[out]  found_var  If not NULL and a variable was found set it to true.
443///
444/// @return name of the function.
445char *deref_func_name(const char *name, int *lenp, partial_T **const partialp, bool no_autoload,
446                      bool *found_var)
447  FUNC_ATTR_NONNULL_ARG(1, 2)
448{
449  if (partialp != NULL) {
450    *partialp = NULL;
451  }
452
453  dictitem_T *const v = find_var(name, (size_t)(*lenp), NULL, no_autoload);
454  if (v == NULL) {
455    return (char *)name;
456  }
457  typval_T *const tv = &v->di_tv;
458  if (found_var != NULL) {
459    *found_var = true;
460  }
461
462  if (tv->v_type == VAR_FUNC) {
463    if (tv->vval.v_string == NULL) {  // just in case
464      *lenp = 0;
465      return "";
466    }
467    *lenp = (int)strlen(tv->vval.v_string);
468    return tv->vval.v_string;
469  }
470
471  if (tv->v_type == VAR_PARTIAL) {
472    partial_T *const pt = tv->vval.v_partial;
473    if (pt == NULL) {  // just in case
474      *lenp = 0;
475      return "";
476    }
477    if (partialp != NULL) {
478      *partialp = pt;
479    }
480    char *s = partial_name(pt);
481    *lenp = (int)strlen(s);
482    return s;
483  }
484
485  return (char *)name;
486}
487
488/// Give an error message with a function name.  Handle <SNR> things.
489///
490/// @param errmsg must be passed without translation (use N_() instead of _()).
491/// @param name function name
492void emsg_funcname(const char *errmsg, const char *name)
493{
494  char *p = (char *)name;
495
496  if ((uint8_t)name[0] == K_SPECIAL && name[1] != NUL && name[2] != NUL) {
497    p = concat_str("<SNR>", name + 3);
498  }
499
500  semsg(_(errmsg), p);
501
502  if (p != name) {
503    xfree(p);
504  }
505}
506
507/// Get function arguments at "*arg" and advance it.
508/// Return them in "*argvars[MAX_FUNC_ARGS + 1]" and the count in "argcount".
509/// On failure FAIL is returned but the "argvars[argcount]" are still set.
510static int get_func_arguments(char **arg, evalarg_T *const evalarg, int partial_argc,
511                              typval_T *argvars, int *argcount)
512{
513  char *argp = *arg;
514  int ret = OK;
515
516  // Get the arguments.
517  while (*argcount < MAX_FUNC_ARGS - partial_argc) {
518    argp = skipwhite(argp + 1);             // skip the '(' or ','
519
520    if (*argp == ')' || *argp == ',' || *argp == NUL) {
521      break;
522    }
523    if (eval1(&argp, &argvars[*argcount], evalarg) == FAIL) {
524      ret = FAIL;
525      break;
526    }
527    (*argcount)++;
528    if (*argp != ',') {
529      break;
530    }
531  }
532
533  argp = skipwhite(argp);
534  if (*argp == ')') {
535    argp++;
536  } else {
537    ret = FAIL;
538  }
539  *arg = argp;
540  return ret;
541}
542
543/// Call a function and put the result in "rettv".
544///
545/// @param name  name of the function
546/// @param len  length of "name" or -1 to use strlen()
547/// @param arg  argument, pointing to the '('
548/// @param funcexe  various values
549///
550/// @return  OK or FAIL.
551int get_func_tv(const char *name, int len, typval_T *rettv, char **arg, evalarg_T *const evalarg,
552                funcexe_T *funcexe)
553{
554  typval_T argvars[MAX_FUNC_ARGS + 1];          // vars for arguments
555  int argcount = 0;                     // number of arguments found
556  const bool evaluate = evalarg == NULL ? false : (evalarg->eval_flags & EVAL_EVALUATE);
557
558  char *argp = *arg;
559  int ret = get_func_arguments(&argp, evalarg,
560                               (funcexe->fe_partial == NULL
561                                ? 0
562                                : funcexe->fe_partial->pt_argc),
563                               argvars, &argcount);
564
565  assert(ret == OK || ret == FAIL);  // suppress clang false positive
566  if (ret == OK) {
567    int i = 0;
568
569    if (get_vim_var_nr(VV_TESTING)) {
570      // Prepare for calling test_garbagecollect_now(), need to know
571      // what variables are used on the call stack.
572      if (funcargs.ga_itemsize == 0) {
573        ga_init(&funcargs, (int)sizeof(typval_T *), 50);
574      }
575      for (i = 0; i < argcount; i++) {
576        ga_grow(&funcargs, 1);
577        ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] = &argvars[i];
578      }
579    }
580    ret = call_func(name, len, rettv, argcount, argvars, funcexe);
581
582    funcargs.ga_len -= i;
583  } else if (!aborting() && evaluate) {
584    if (argcount == MAX_FUNC_ARGS) {
585      emsg_funcname(N_("E740: Too many arguments for function %s"), name);
586    } else {
587      emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
588    }
589  }
590
591  while (--argcount >= 0) {
592    tv_clear(&argvars[argcount]);
593  }
594
595  *arg = skipwhite(argp);
596  return ret;
597}
598
599// fixed buffer length for fname_trans_sid()
600#define FLEN_FIXED 40
601
602/// Check whether function name starts with <SID> or s:
603///
604/// @warning Only works for names previously checked by eval_fname_script(), if
605///          it returned non-zero.
606///
607/// @param[in]  name  Name to check.
608///
609/// @return true if it starts with <SID> or s:, false otherwise.
610static inline bool eval_fname_sid(const char *const name)
611  FUNC_ATTR_PURE FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_WARN_UNUSED_RESULT
612  FUNC_ATTR_NONNULL_ALL
613{
614  return *name == 's' || TOUPPER_ASC(name[2]) == 'I';
615}
616
617/// In a script transform script-local names into actually used names
618///
619/// Transforms "<SID>" and "s:" prefixes to `K_SNR {N}` (e.g. K_SNR "123") and
620/// "<SNR>" prefix to `K_SNR`. Uses `fname_buf` buffer that is supposed to have
621/// #FLEN_FIXED + 1 length when it fits, otherwise it allocates memory.
622///
623/// @param[in]  name  Name to transform.
624/// @param  fname_buf  Buffer to save resulting function name to, if it fits.
625///                    Must have at least #FLEN_FIXED + 1 length.
626/// @param[out]  tofree  Location where pointer to an allocated memory is saved
627///                      in case result does not fit into fname_buf.
628/// @param[out]  error  Location where error type is saved, @see
629///                     FnameTransError.
630///
631/// @return transformed name: either `fname_buf` or a pointer to an allocated
632///         memory.
633static char *fname_trans_sid(const char *const name, char *const fname_buf, char **const tofree,
634                             int *const error)
635  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
636{
637  const char *script_name = name + eval_fname_script(name);
638  if (script_name == name) {
639    return (char *)name;  // no prefix
640  }
641
642  fname_buf[0] = (char)K_SPECIAL;
643  fname_buf[1] = (char)KS_EXTRA;
644  fname_buf[2] = KE_SNR;
645  size_t fname_buflen = 3;
646  if (!eval_fname_sid(name)) {  // "<SID>" or "s:"
647    fname_buf[fname_buflen] = NUL;
648  } else {
649    if (current_sctx.sc_sid <= 0) {
650      *error = FCERR_SCRIPT;
651    } else {
652      fname_buflen += (size_t)snprintf(fname_buf + fname_buflen,
653                                       FLEN_FIXED + 1 - fname_buflen,
654                                       "%" PRIdSCID "_",
655                                       current_sctx.sc_sid);
656    }
657  }
658  size_t fnamelen = fname_buflen + strlen(script_name);
659  char *fname;
660  if (fnamelen < FLEN_FIXED) {
661    STRCPY(fname_buf + fname_buflen, script_name);
662    fname = fname_buf;
663  } else {
664    fname = xmalloc(fnamelen + 1);
665    *tofree = fname;
666    snprintf(fname, fnamelen + 1, "%s%s", fname_buf, script_name);
667  }
668  return fname;
669}
670
671int get_func_arity(const char *name, int *required, int *optional, bool *varargs)
672{
673  int argcount = 0;
674  int min_argcount = 0;
675
676  const EvalFuncDef *fdef = find_internal_func(name);
677  if (fdef != NULL) {
678    argcount = fdef->max_argc;
679    min_argcount = fdef->min_argc;
680    *varargs = false;
681  } else {
682    char fname_buf[FLEN_FIXED + 1];
683    char *tofree = NULL;
684    int error = FCERR_NONE;
685
686    // May need to translate <SNR>123_ to K_SNR.
687    char *fname = fname_trans_sid(name, fname_buf, &tofree, &error);
688    ufunc_T *ufunc = NULL;
689    if (error == FCERR_NONE) {
690      ufunc = find_func(fname);
691    }
692    xfree(tofree);
693
694    if (ufunc == NULL) {
695      return FAIL;
696    }
697
698    argcount = ufunc->uf_args.ga_len;
699    min_argcount = ufunc->uf_args.ga_len - ufunc->uf_def_args.ga_len;
700    *varargs = ufunc->uf_varargs;
701  }
702
703  *required = min_argcount;
704  *optional = argcount - min_argcount;
705
706  return OK;
707}
708
709/// Find a function by name, return pointer to it in ufuncs.
710///
711/// @return  NULL for unknown function.
712ufunc_T *find_func(const char *name)
713{
714  hashitem_T *hi = hash_find(&func_hashtab, name);
715  if (!HASHITEM_EMPTY(hi)) {
716    return HI2UF(hi);
717  }
718  return NULL;
719}
720
721/// @return  true if "ufunc" is a global function.
722static bool func_is_global(const ufunc_T *ufunc)
723  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
724{
725  return (uint8_t)ufunc->uf_name[0] != K_SPECIAL;
726}
727
728/// Copy the function name of "fp" to buffer "buf".
729/// "buf" must be able to hold the function name plus three bytes.
730/// Takes care of script-local function names.
731static int cat_func_name(char *buf, size_t bufsize, const ufunc_T *fp)
732  FUNC_ATTR_NONNULL_ALL
733{
734  int len = -1;
735  size_t uflen = fp->uf_namelen;
736  assert(uflen > 0);
737
738  if (!func_is_global(fp) && uflen > 3) {
739    len = snprintf(buf, bufsize, "<SNR>%s", fp->uf_name + 3);
740  } else {
741    len = snprintf(buf, bufsize, "%s", fp->uf_name);
742  }
743
744  assert(len > 0);
745  return (len >= (int)bufsize) ? (int)bufsize - 1 : len;
746}
747
748/// Add a number variable "name" to dict "dp" with value "nr".
749static void add_nr_var(dict_T *dp, dictitem_T *v, char *name, varnumber_T nr)
750{
751  STRCPY(v->di_key, name);
752  v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
753  hash_add(&dp->dv_hashtab, v->di_key);
754  v->di_tv.v_type = VAR_NUMBER;
755  v->di_tv.v_lock = VAR_FIXED;
756  v->di_tv.vval.v_number = nr;
757}
758
759/// Free "fc"
760static void free_funccal(funccall_T *fc)
761{
762  for (int i = 0; i < fc->fc_ufuncs.ga_len; i++) {
763    ufunc_T *fp = ((ufunc_T **)(fc->fc_ufuncs.ga_data))[i];
764
765    // When garbage collecting a funccall_T may be freed before the
766    // function that references it, clear its uf_scoped field.
767    // The function may have been redefined and point to another
768    // funccal_T, don't clear it then.
769    if (fp != NULL && fp->uf_scoped == fc) {
770      fp->uf_scoped = NULL;
771    }
772  }
773  ga_clear(&fc->fc_ufuncs);
774
775  func_ptr_unref(fc->fc_func);
776  xfree(fc);
777}
778
779/// Free "fc" and what it contains.
780/// Can be called only when "fc" is kept beyond the period of it called,
781/// i.e. after cleanup_function_call(fc).
782static void free_funccal_contents(funccall_T *fc)
783{
784  // Free all l: variables.
785  vars_clear(&fc->fc_l_vars.dv_hashtab);
786
787  // Free all a: variables.
788  vars_clear(&fc->fc_l_avars.dv_hashtab);
789
790  // Free the a:000 variables.
791  TV_LIST_ITER(&fc->fc_l_varlist, li, {
792    tv_clear(TV_LIST_ITEM_TV(li));
793  });
794
795  free_funccal(fc);
796}
797
798/// Handle the last part of returning from a function: free the local hashtable.
799/// Unless it is still in use by a closure.
800static void cleanup_function_call(funccall_T *fc)
801{
802  bool may_free_fc = fc->fc_refcount <= 0;
803  bool free_fc = true;
804
805  current_funccal = fc->fc_caller;
806
807  // Free all l: variables if not referred.
808  if (may_free_fc && fc->fc_l_vars.dv_refcount == DO_NOT_FREE_CNT) {
809    vars_clear(&fc->fc_l_vars.dv_hashtab);
810  } else {
811    free_fc = false;
812  }
813
814  // If the a:000 list and the l: and a: dicts are not referenced and
815  // there is no closure using it, we can free the funccall_T and what's
816  // in it.
817  if (may_free_fc && fc->fc_l_avars.dv_refcount == DO_NOT_FREE_CNT) {
818    vars_clear_ext(&fc->fc_l_avars.dv_hashtab, false);
819  } else {
820    free_fc = false;
821
822    // Make a copy of the a: variables, since we didn't do that above.
823    TV_DICT_ITER(&fc->fc_l_avars, di, {
824      tv_copy(&di->di_tv, &di->di_tv);
825    });
826  }
827
828  if (may_free_fc && fc->fc_l_varlist.lv_refcount   // NOLINT(runtime/deprecated)
829      == DO_NOT_FREE_CNT) {
830    fc->fc_l_varlist.lv_first = NULL;  // NOLINT(runtime/deprecated)
831  } else {
832    free_fc = false;
833
834    // Make a copy of the a:000 items, since we didn't do that above.
835    TV_LIST_ITER(&fc->fc_l_varlist, li, {
836      tv_copy(TV_LIST_ITEM_TV(li), TV_LIST_ITEM_TV(li));
837    });
838  }
839
840  if (free_fc) {
841    free_funccal(fc);
842  } else {
843    static int made_copy = 0;
844
845    // "fc" is still in use.  This can happen when returning "a:000",
846    // assigning "l:" to a global variable or defining a closure.
847    // Link "fc" in the list for garbage collection later.
848    fc->fc_caller = previous_funccal;
849    previous_funccal = fc;
850
851    if (want_garbage_collect) {
852      // If garbage collector is ready, clear count.
853      made_copy = 0;
854    } else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc))) {
855      // We have made a lot of copies, worth 4 Mbyte.  This can happen
856      // when repetitively calling a function that creates a reference to
857      // itself somehow.  Call the garbage collector soon to avoid using
858      // too much memory.
859      made_copy = 0;
860      want_garbage_collect = true;
861    }
862  }
863}
864
865/// Unreference "fc": decrement the reference count and free it when it
866/// becomes zero.  "fp" is detached from "fc".
867///
868/// @param[in]   force   When true, we are exiting.
869static void funccal_unref(funccall_T *fc, ufunc_T *fp, bool force)
870{
871  if (fc == NULL) {
872    return;
873  }
874
875  fc->fc_refcount--;
876  if (force ? fc->fc_refcount <= 0 : !fc_referenced(fc)) {
877    for (funccall_T **pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->fc_caller) {
878      if (fc == *pfc) {
879        *pfc = fc->fc_caller;
880        free_funccal_contents(fc);
881        return;
882      }
883    }
884  }
885  for (int i = 0; i < fc->fc_ufuncs.ga_len; i++) {
886    if (((ufunc_T **)(fc->fc_ufuncs.ga_data))[i] == fp) {
887      ((ufunc_T **)(fc->fc_ufuncs.ga_data))[i] = NULL;
888    }
889  }
890}
891
892/// Remove the function from the function hashtable.  If the function was
893/// deleted while it still has references this was already done.
894///
895/// @return true if the entry was deleted, false if it wasn't found.
896static bool func_remove(ufunc_T *fp)
897{
898  hashitem_T *hi = hash_find(&func_hashtab, UF2HIKEY(fp));
899  if (HASHITEM_EMPTY(hi)) {
900    return false;
901  }
902
903  hash_remove(&func_hashtab, hi);
904  return true;
905}
906
907static void func_clear_items(ufunc_T *fp)
908{
909  ga_clear_strings(&(fp->uf_args));
910  ga_clear_strings(&(fp->uf_def_args));
911  ga_clear_strings(&(fp->uf_lines));
912
913  if (fp->uf_flags & FC_LUAREF) {
914    api_free_luaref(fp->uf_luaref);
915    fp->uf_luaref = LUA_NOREF;
916  }
917
918  XFREE_CLEAR(fp->uf_tml_count);
919  XFREE_CLEAR(fp->uf_tml_total);
920  XFREE_CLEAR(fp->uf_tml_self);
921}
922
923/// Free all things that a function contains. Does not free the function
924/// itself, use func_free() for that.
925///
926/// @param[in] force  When true, we are exiting.
927static void func_clear(ufunc_T *fp, bool force)
928{
929  if (fp->uf_cleared) {
930    return;
931  }
932  fp->uf_cleared = true;
933
934  // clear this function
935  func_clear_items(fp);
936  funccal_unref(fp->uf_scoped, fp, force);
937}
938
939/// Free a function and remove it from the list of functions. Does not free
940/// what a function contains, call func_clear() first.
941///
942/// @param[in] fp  The function to free.
943static void func_free(ufunc_T *fp)
944{
945  // only remove it when not done already, otherwise we would remove a newer
946  // version of the function
947  if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0) {
948    func_remove(fp);
949  }
950
951  XFREE_CLEAR(fp->uf_name_exp);
952  xfree(fp);
953}
954
955/// Free all things that a function contains and free the function itself.
956///
957/// @param[in] force  When true, we are exiting.
958static void func_clear_free(ufunc_T *fp, bool force)
959{
960  func_clear(fp, force);
961  func_free(fp);
962}
963
964/// Allocate a funccall_T, link it in current_funccal and fill in "fp" and "rettv".
965/// Must be followed by one call to remove_funccal() or cleanup_function_call().
966funccall_T *create_funccal(ufunc_T *fp, typval_T *rettv)
967{
968  funccall_T *fc = xcalloc(1, sizeof(funccall_T));
969  fc->fc_caller = current_funccal;
970  current_funccal = fc;
971  fc->fc_func = fp;
972  func_ptr_ref(fp);
973  fc->fc_rettv = rettv;
974  return fc;
975}
976
977/// Restore current_funccal.
978void remove_funccal(void)
979{
980  funccall_T *fc = current_funccal;
981  current_funccal = fc->fc_caller;
982  free_funccal(fc);
983}
984
985/// Call a user function
986///
987/// @param fp  Function to call.
988/// @param[in] argcount  Number of arguments.
989/// @param argvars  Arguments.
990/// @param[out] rettv  Return value.
991/// @param[in] firstline  First line of range.
992/// @param[in] lastline  Last line of range.
993/// @param selfdict  Dict for "self" for dictionary functions.
994void call_user_func(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv,
995                    linenr_T firstline, linenr_T lastline, dict_T *selfdict)
996  FUNC_ATTR_NONNULL_ARG(1, 3, 4)
997{
998  bool using_sandbox = false;
999  static int depth = 0;
1000  dictitem_T *v;
1001  int fixvar_idx = 0;           // index in fc_fixvar[]
1002  bool islambda = false;
1003  char numbuf[NUMBUFLEN];
1004  char *name;
1005  size_t namelen;
1006  typval_T *tv_to_free[MAX_FUNC_ARGS];
1007  int tv_to_free_len = 0;
1008  proftime_T wait_start;
1009  proftime_T call_start;
1010  bool started_profiling = false;
1011  bool did_save_redo = false;
1012  RedoState save_redo;
1013  ESTACK_CHECK_DECLARATION;
1014
1015  // If depth of calling is getting too high, don't execute the function
1016  if (depth >= p_mfd) {
1017    emsg(_("E132: Function call depth is higher than 'maxfuncdepth'"));
1018    rettv->v_type = VAR_NUMBER;
1019    rettv->vval.v_number = -1;
1020    return;
1021  }
1022  depth++;
1023  // Save search patterns and redo buffer.
1024  save_search_patterns();
1025  if (!ins_compl_active()) {
1026    save_redobuff(&save_redo);
1027    did_save_redo = true;
1028  }
1029  fp->uf_calls++;
1030  // check for CTRL-C hit
1031  line_breakcheck();
1032  // prepare the funccall_T structure
1033  funccall_T *fc = create_funccal(fp, rettv);
1034  fc->fc_level = ex_nesting_level;
1035  // Check if this function has a breakpoint.
1036  fc->fc_breakpoint = dbg_find_breakpoint(false, fp->uf_name, 0);
1037  fc->fc_dbg_tick = debug_tick;
1038  // Set up fields for closure.
1039  ga_init(&fc->fc_ufuncs, sizeof(ufunc_T *), 1);
1040
1041  if (strncmp(fp->uf_name, "<lambda>", 8) == 0) {
1042    islambda = true;
1043  }
1044
1045  // Note about using fc->fc_fixvar[]: This is an array of FIXVAR_CNT variables
1046  // with names up to VAR_SHORT_LEN long.  This avoids having to alloc/free
1047  // each argument variable and saves a lot of time.
1048  //
1049  // Init l: variables.
1050  init_var_dict(&fc->fc_l_vars, &fc->fc_l_vars_var, VAR_DEF_SCOPE);
1051  if (selfdict != NULL) {
1052    // Set l:self to "selfdict".  Use "name" to avoid a warning from
1053    // some compiler that checks the destination size.
1054    v = (dictitem_T *)&fc->fc_fixvar[fixvar_idx++];
1055    name = (char *)v->di_key;
1056    STRCPY(name, "self");
1057    v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
1058    hash_add(&fc->fc_l_vars.dv_hashtab, v->di_key);
1059    v->di_tv.v_type = VAR_DICT;
1060    v->di_tv.v_lock = VAR_UNLOCKED;
1061    v->di_tv.vval.v_dict = selfdict;
1062    selfdict->dv_refcount++;
1063  }
1064
1065  // Init a: variables, unless none found (in lambda).
1066  // Set a:0 to "argcount" less number of named arguments, if >= 0.
1067  // Set a:000 to a list with room for the "..." arguments.
1068  init_var_dict(&fc->fc_l_avars, &fc->fc_l_avars_var, VAR_SCOPE);
1069  if ((fp->uf_flags & FC_NOARGS) == 0) {
1070    add_nr_var(&fc->fc_l_avars, (dictitem_T *)&fc->fc_fixvar[fixvar_idx++], "0",
1071               (varnumber_T)(argcount >= fp->uf_args.ga_len
1072                             ? argcount - fp->uf_args.ga_len : 0));
1073  }
1074  fc->fc_l_avars.dv_lock = VAR_FIXED;
1075  if ((fp->uf_flags & FC_NOARGS) == 0) {
1076    // Use "name" to avoid a warning from some compiler that checks the
1077    // destination size.
1078    v = (dictitem_T *)&fc->fc_fixvar[fixvar_idx++];
1079    name = (char *)v->di_key;
1080    STRCPY(name, "000");
1081    v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
1082    hash_add(&fc->fc_l_avars.dv_hashtab, v->di_key);
1083    v->di_tv.v_type = VAR_LIST;
1084    v->di_tv.v_lock = VAR_FIXED;
1085    v->di_tv.vval.v_list = &fc->fc_l_varlist;
1086  }
1087  tv_list_init_static(&fc->fc_l_varlist);
1088  tv_list_set_lock(&fc->fc_l_varlist, VAR_FIXED);
1089
1090  // Set a:firstline to "firstline" and a:lastline to "lastline".
1091  // Set a:name to named arguments.
1092  // Set a:N to the "..." arguments.
1093  // Skipped when no a: variables used (in lambda).
1094  if ((fp->uf_flags & FC_NOARGS) == 0) {
1095    add_nr_var(&fc->fc_l_avars, (dictitem_T *)&fc->fc_fixvar[fixvar_idx++],
1096               "firstline", (varnumber_T)firstline);
1097    add_nr_var(&fc->fc_l_avars, (dictitem_T *)&fc->fc_fixvar[fixvar_idx++],
1098               "lastline", (varnumber_T)lastline);
1099  }
1100  bool default_arg_err = false;
1101  for (int i = 0; i < argcount || i < fp->uf_args.ga_len; i++) {
1102    bool addlocal = false;
1103    bool isdefault = false;
1104    typval_T def_rettv;
1105
1106    int ai = i - fp->uf_args.ga_len;
1107    if (ai < 0) {
1108      // named argument a:name
1109      name = FUNCARG(fp, i);
1110      if (islambda) {
1111        addlocal = true;
1112      }
1113
1114      // evaluate named argument default expression
1115      isdefault = ai + fp->uf_def_args.ga_len >= 0 && i >= argcount;
1116      if (isdefault) {
1117        char *default_expr = NULL;
1118        def_rettv.v_type = VAR_NUMBER;
1119        def_rettv.vval.v_number = -1;
1120
1121        default_expr = ((char **)(fp->uf_def_args.ga_data))
1122                       [ai + fp->uf_def_args.ga_len];
1123        if (eval1(&default_expr, &def_rettv, &EVALARG_EVALUATE) == FAIL) {
1124          default_arg_err = true;
1125          break;
1126        }
1127      }
1128
1129      namelen = strlen(name);
1130    } else {
1131      if ((fp->uf_flags & FC_NOARGS) != 0) {
1132        // Bail out if no a: arguments used (in lambda).
1133        break;
1134      }
1135      // "..." argument a:1, a:2, etc.
1136      namelen = (size_t)snprintf(numbuf, sizeof(numbuf), "%d", ai + 1);
1137      name = numbuf;
1138    }
1139    if (fixvar_idx < FIXVAR_CNT && namelen <= VAR_SHORT_LEN) {
1140      v = (dictitem_T *)&fc->fc_fixvar[fixvar_idx++];
1141      v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
1142      STRCPY(v->di_key, name);
1143    } else {
1144      v = tv_dict_item_alloc_len(name, namelen);
1145      v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX;
1146    }
1147
1148    // Note: the values are copied directly to avoid alloc/free.
1149    // "argvars" must have VAR_FIXED for v_lock.
1150    v->di_tv = isdefault ? def_rettv : argvars[i];
1151    v->di_tv.v_lock = VAR_FIXED;
1152
1153    if (isdefault) {
1154      // Need to free this later, no matter where it's stored.
1155      tv_to_free[tv_to_free_len++] = &v->di_tv;
1156    }
1157
1158    if (addlocal) {
1159      // Named arguments can be accessed without the "a:" prefix in lambda
1160      // expressions. Add to the l: dict.
1161      tv_copy(&v->di_tv, &v->di_tv);
1162      hash_add(&fc->fc_l_vars.dv_hashtab, v->di_key);
1163    } else {
1164      hash_add(&fc->fc_l_avars.dv_hashtab, v->di_key);
1165    }
1166
1167    if (ai >= 0 && ai < MAX_FUNC_ARGS) {
1168      listitem_T *li = &fc->fc_l_listitems[ai];
1169
1170      *TV_LIST_ITEM_TV(li) = argvars[i];
1171      TV_LIST_ITEM_TV(li)->v_lock = VAR_FIXED;
1172      tv_list_append(&fc->fc_l_varlist, li);
1173    }
1174  }
1175
1176  // Don't redraw while executing the function.
1177  RedrawingDisabled++;
1178
1179  if (fp->uf_flags & FC_SANDBOX) {
1180    using_sandbox = true;
1181    sandbox++;
1182  }
1183
1184  estack_push_ufunc(fp, 1);
1185  ESTACK_CHECK_SETUP;
1186  if (p_verbose >= 12) {
1187    no_wait_return++;
1188    verbose_enter_scroll();
1189
1190    smsg(0, _("calling %s"), SOURCING_NAME);
1191    if (p_verbose >= 14) {
1192      msg_puts("(");
1193      for (int i = 0; i < argcount; i++) {
1194        if (i > 0) {
1195          msg_puts(", ");
1196        }
1197        if (argvars[i].v_type == VAR_NUMBER) {
1198          msg_outnum((int)argvars[i].vval.v_number);
1199        } else {
1200          // Do not want errors such as E724 here.
1201          emsg_off++;
1202          char *tofree = encode_tv2string(&argvars[i], NULL);
1203          emsg_off--;
1204          if (tofree != NULL) {
1205            char *s = tofree;
1206            char buf[MSG_BUF_LEN];
1207            if (vim_strsize(s) > MSG_BUF_CLEN) {
1208              trunc_string(s, buf, MSG_BUF_CLEN, sizeof(buf));
1209              s = buf;
1210            }
1211            msg_puts(s);
1212            xfree(tofree);
1213          }
1214        }
1215      }
1216      msg_puts(")");
1217    }
1218    msg_puts("\n");  // don't overwrite this either
1219
1220    verbose_leave_scroll();
1221    no_wait_return--;
1222  }
1223
1224  const bool do_profiling_yes = do_profiling == PROF_YES;
1225
1226  bool func_not_yet_profiling_but_should =
1227    do_profiling_yes
1228    && !fp->uf_profiling && has_profiling(false, fp->uf_name, NULL);
1229
1230  if (func_not_yet_profiling_but_should) {
1231    started_profiling = true;
1232    func_do_profile(fp);
1233  }
1234
1235  bool func_or_func_caller_profiling =
1236    do_profiling_yes
1237    && (fp->uf_profiling
1238        || (fc->fc_caller != NULL && fc->fc_caller->fc_func->uf_profiling));
1239
1240  if (func_or_func_caller_profiling) {
1241    fp->uf_tm_count++;
1242    call_start = profile_start();
1243    fp->uf_tm_children = profile_zero();
1244  }
1245
1246  if (do_profiling_yes) {
1247    script_prof_save(&wait_start);
1248  }
1249
1250  const sctx_T save_current_sctx = current_sctx;
1251  current_sctx = fp->uf_script_ctx;
1252  int save_did_emsg = did_emsg;
1253  did_emsg = false;
1254
1255  if (default_arg_err && (fp->uf_flags & FC_ABORT || trylevel > 0)) {
1256    did_emsg = true;
1257  } else if (islambda) {
1258    char *p = *(char **)fp->uf_lines.ga_data + 7;
1259
1260    // A Lambda always has the command "return {expr}".  It is much faster
1261    // to evaluate {expr} directly.
1262    ex_nesting_level++;
1263    eval1(&p, rettv, &EVALARG_EVALUATE);
1264    ex_nesting_level--;
1265  } else {
1266    // call do_cmdline() to execute the lines
1267    do_cmdline(NULL, get_func_line, (void *)fc,
1268               DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
1269  }
1270
1271  // Invoke functions added with ":defer".
1272  handle_defer_one(current_funccal);
1273
1274  RedrawingDisabled--;
1275
1276  // when the function was aborted because of an error, return -1
1277  if ((did_emsg
1278       && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN) {
1279    tv_clear(rettv);
1280    rettv->v_type = VAR_NUMBER;
1281    rettv->vval.v_number = -1;
1282  }
1283
1284  if (func_or_func_caller_profiling) {
1285    call_start = profile_end(call_start);
1286    call_start = profile_sub_wait(wait_start, call_start);
1287    fp->uf_tm_total = profile_add(fp->uf_tm_total, call_start);
1288    fp->uf_tm_self = profile_self(fp->uf_tm_self, call_start,
1289                                  fp->uf_tm_children);
1290    if (fc->fc_caller != NULL && fc->fc_caller->fc_func->uf_profiling) {
1291      fc->fc_caller->fc_func->uf_tm_children =
1292        profile_add(fc->fc_caller->fc_func->uf_tm_children, call_start);
1293      fc->fc_caller->fc_func->uf_tml_children =
1294        profile_add(fc->fc_caller->fc_func->uf_tml_children, call_start);
1295    }
1296    if (started_profiling) {
1297      // make a ":profdel func" stop profiling the function
1298      fp->uf_profiling = false;
1299    }
1300  }
1301
1302  // when being verbose, mention the return value
1303  if (p_verbose >= 12) {
1304    no_wait_return++;
1305    verbose_enter_scroll();
1306
1307    if (aborting()) {
1308      smsg(0, _("%s aborted"), SOURCING_NAME);
1309    } else if (fc->fc_rettv->v_type == VAR_NUMBER) {
1310      smsg(0, _("%s returning #%" PRId64 ""),
1311           SOURCING_NAME, (int64_t)fc->fc_rettv->vval.v_number);
1312    } else {
1313      char buf[MSG_BUF_LEN];
1314
1315      // The value may be very long.  Skip the middle part, so that we
1316      // have some idea how it starts and ends. smsg() would always
1317      // truncate it at the end. Don't want errors such as E724 here.
1318      emsg_off++;
1319      char *s = encode_tv2string(fc->fc_rettv, NULL);
1320      char *tofree = s;
1321      emsg_off--;
1322      if (s != NULL) {
1323        if (vim_strsize(s) > MSG_BUF_CLEN) {
1324          trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
1325          s = buf;
1326        }
1327        smsg(0, _("%s returning %s"), SOURCING_NAME, s);
1328        xfree(tofree);
1329      }
1330    }
1331    msg_puts("\n");  // don't overwrite this either
1332
1333    verbose_leave_scroll();
1334    no_wait_return--;
1335  }
1336
1337  ESTACK_CHECK_NOW;
1338  estack_pop();
1339  current_sctx = save_current_sctx;
1340  if (do_profiling_yes) {
1341    script_prof_restore(&wait_start);
1342  }
1343  if (using_sandbox) {
1344    sandbox--;
1345  }
1346
1347  if (p_verbose >= 12 && SOURCING_NAME != NULL) {
1348    no_wait_return++;
1349    verbose_enter_scroll();
1350
1351    smsg(0, _("continuing in %s"), SOURCING_NAME);
1352    msg_puts("\n");  // don't overwrite this either
1353
1354    verbose_leave_scroll();
1355    no_wait_return--;
1356  }
1357
1358  did_emsg |= save_did_emsg;
1359  depth--;
1360  for (int i = 0; i < tv_to_free_len; i++) {
1361    tv_clear(tv_to_free[i]);
1362  }
1363  cleanup_function_call(fc);
1364
1365  if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) {
1366    // Function was unreferenced while being used, free it now.
1367    func_clear_free(fp, false);
1368  }
1369  // restore search patterns and redo buffer
1370  if (did_save_redo) {
1371    restore_redobuff(&save_redo);
1372  }
1373  restore_search_patterns();
1374}
1375
1376/// There are two kinds of function names:
1377/// 1. ordinary names, function defined with :function;
1378///    can start with "<SNR>123_" literally or with K_SPECIAL.
1379/// 2. Numbered functions and lambdas: "<lambda>123"
1380/// For the first we only count the name stored in func_hashtab as a reference,
1381/// using function() does not count as a reference, because the function is
1382/// looked up by name.
1383static bool func_name_refcount(const char *name)
1384  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
1385{
1386  return isdigit((uint8_t)(*name)) || (name[0] == '<' && name[1] == 'l');
1387}
1388
1389/// Check the argument count for user function "fp".
1390/// @return  FCERR_UNKNOWN if OK, FCERR_TOOFEW or FCERR_TOOMANY otherwise.
1391static int check_user_func_argcount(ufunc_T *fp, int argcount)
1392  FUNC_ATTR_NONNULL_ALL
1393{
1394  const int regular_args = fp->uf_args.ga_len;
1395
1396  if (argcount < regular_args - fp->uf_def_args.ga_len) {
1397    return FCERR_TOOFEW;
1398  } else if (!fp->uf_varargs && argcount > regular_args) {
1399    return FCERR_TOOMANY;
1400  }
1401  return FCERR_UNKNOWN;
1402}
1403
1404/// Call a user function after checking the arguments.
1405static int call_user_func_check(ufunc_T *fp, int argcount, typval_T *argvars, typval_T *rettv,
1406                                funcexe_T *funcexe, dict_T *selfdict)
1407  FUNC_ATTR_NONNULL_ARG(1, 3, 4, 5)
1408{
1409  if (fp->uf_flags & FC_LUAREF) {
1410    return nlua_exec_typval_callable(fp->uf_luaref, argcount, argvars, rettv);
1411  }
1412
1413  if ((fp->uf_flags & FC_RANGE) && funcexe->fe_doesrange != NULL) {
1414    *funcexe->fe_doesrange = true;
1415  }
1416  int error = check_user_func_argcount(fp, argcount);
1417  if (error != FCERR_UNKNOWN) {
1418    return error;
1419  }
1420  if ((fp->uf_flags & FC_DICT) && selfdict == NULL) {
1421    error = FCERR_DICT;
1422  } else {
1423    // Call the user function.
1424    call_user_func(fp, argcount, argvars, rettv, funcexe->fe_firstline, funcexe->fe_lastline,
1425                   (fp->uf_flags & FC_DICT) ? selfdict : NULL);
1426    error = FCERR_NONE;
1427  }
1428  return error;
1429}
1430
1431static funccal_entry_T *funccal_stack = NULL;
1432
1433/// Save the current function call pointer, and set it to NULL.
1434/// Used when executing autocommands and for ":source".
1435void save_funccal(funccal_entry_T *entry)
1436{
1437  entry->top_funccal = current_funccal;
1438  entry->next = funccal_stack;
1439  funccal_stack = entry;
1440  current_funccal = NULL;
1441}
1442
1443void restore_funccal(void)
1444{
1445  if (funccal_stack == NULL) {
1446    iemsg("INTERNAL: restore_funccal()");
1447  } else {
1448    current_funccal = funccal_stack->top_funccal;
1449    funccal_stack = funccal_stack->next;
1450  }
1451}
1452
1453funccall_T *get_current_funccal(void)
1454{
1455  return current_funccal;
1456}
1457
1458void set_current_funccal(funccall_T *fc)
1459{
1460  current_funccal = fc;
1461}
1462
1463#ifdef EXITFREE
1464void free_all_functions(void)
1465{
1466  hashitem_T *hi;
1467  ufunc_T *fp;
1468  uint64_t skipped = 0;
1469  uint64_t todo = 1;
1470  int changed;
1471
1472  // Clean up the current_funccal chain and the funccal stack.
1473  while (current_funccal != NULL) {
1474    tv_clear(current_funccal->fc_rettv);
1475    cleanup_function_call(current_funccal);
1476    if (current_funccal == NULL && funccal_stack != NULL) {
1477      restore_funccal();
1478    }
1479  }
1480
1481  // First clear what the functions contain. Since this may lower the
1482  // reference count of a function, it may also free a function and change
1483  // the hash table. Restart if that happens.
1484  while (todo > 0) {
1485    todo = func_hashtab.ht_used;
1486    for (hi = func_hashtab.ht_array; todo > 0; hi++) {
1487      if (!HASHITEM_EMPTY(hi)) {
1488        // Only free functions that are not refcounted, those are
1489        // supposed to be freed when no longer referenced.
1490        fp = HI2UF(hi);
1491        if (func_name_refcount(fp->uf_name)) {
1492          skipped++;
1493        } else {
1494          changed = func_hashtab.ht_changed;
1495          func_clear(fp, true);
1496          if (changed != func_hashtab.ht_changed) {
1497            skipped = 0;
1498            break;
1499          }
1500        }
1501        todo--;
1502      }
1503    }
1504  }
1505
1506  // Now actually free the functions. Need to start all over every time,
1507  // because func_free() may change the hash table.
1508  skipped = 0;
1509  while (func_hashtab.ht_used > skipped) {
1510    todo = func_hashtab.ht_used;
1511    for (hi = func_hashtab.ht_array; todo > 0; hi++) {
1512      if (!HASHITEM_EMPTY(hi)) {
1513        todo--;
1514        // Only free functions that are not refcounted, those are
1515        // supposed to be freed when no longer referenced.
1516        fp = HI2UF(hi);
1517        if (func_name_refcount(fp->uf_name)) {
1518          skipped++;
1519        } else {
1520          func_free(fp);
1521          skipped = 0;
1522          break;
1523        }
1524      }
1525    }
1526  }
1527  if (skipped == 0) {
1528    hash_clear(&func_hashtab);
1529  }
1530}
1531
1532#endif
1533
1534/// Checks if a builtin function with the given name exists.
1535///
1536/// @param[in]   name   name of the builtin function to check.
1537/// @param[in]   len    length of "name", or -1 for NUL terminated.
1538///
1539/// @return true if "name" looks like a builtin function name: starts with a
1540/// lower case letter and doesn't contain AUTOLOAD_CHAR or ':'.
1541static bool builtin_function(const char *name, int len)
1542{
1543  if (!ASCII_ISLOWER(name[0]) || name[1] == ':') {
1544    return false;
1545  }
1546
1547  const char *p = (len == -1
1548                   ? strchr(name, AUTOLOAD_CHAR)
1549                   : memchr(name, AUTOLOAD_CHAR, (size_t)len));
1550
1551  return p == NULL;
1552}
1553
1554int func_call(char *name, typval_T *args, partial_T *partial, dict_T *selfdict, typval_T *rettv)
1555{
1556  typval_T argv[MAX_FUNC_ARGS + 1];
1557  int argc = 0;
1558  int r = 0;
1559
1560  TV_LIST_ITER(args->vval.v_list, item, {
1561    if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc)) {
1562      emsg(_("E699: Too many arguments"));
1563      goto func_call_skip_call;
1564    }
1565    // Make a copy of each argument.  This is needed to be able to set
1566    // v_lock to VAR_FIXED in the copy without changing the original list.
1567    tv_copy(TV_LIST_ITEM_TV(item), &argv[argc++]);
1568  });
1569
1570  funcexe_T funcexe = FUNCEXE_INIT;
1571  funcexe.fe_firstline = curwin->w_cursor.lnum;
1572  funcexe.fe_lastline = curwin->w_cursor.lnum;
1573  funcexe.fe_evaluate = true;
1574  funcexe.fe_partial = partial;
1575  funcexe.fe_selfdict = selfdict;
1576  r = call_func(name, -1, rettv, argc, argv, &funcexe);
1577
1578func_call_skip_call:
1579  // Free the arguments.
1580  while (argc > 0) {
1581    tv_clear(&argv[--argc]);
1582  }
1583
1584  return r;
1585}
1586
1587/// call the 'callback' function and return the result as a number.
1588/// Returns -2 when calling the function fails.  Uses argv[0] to argv[argc - 1]
1589/// for the function arguments. argv[argc] should have type VAR_UNKNOWN.
1590///
1591/// @param argcount  number of "argvars"
1592/// @param argvars   vars for arguments, must have "argcount" PLUS ONE elements!
1593varnumber_T callback_call_retnr(Callback *callback, int argcount, typval_T *argvars)
1594{
1595  typval_T rettv;
1596  if (!callback_call(callback, argcount, argvars, &rettv)) {
1597    return -2;
1598  }
1599
1600  varnumber_T retval = tv_get_number_chk(&rettv, NULL);
1601  tv_clear(&rettv);
1602  return retval;
1603}
1604
1605/// Give an error message for the result of a function.
1606/// Nothing if "error" is FCERR_NONE.
1607static void user_func_error(int error, const char *name, bool found_var)
1608  FUNC_ATTR_NONNULL_ARG(2)
1609{
1610  switch (error) {
1611  case FCERR_UNKNOWN:
1612    if (found_var) {
1613      semsg(_(e_not_callable_type_str), name);
1614    } else {
1615      emsg_funcname(e_unknown_function_str, name);
1616    }
1617    break;
1618  case FCERR_NOTMETHOD:
1619    emsg_funcname(N_("E276: Cannot use function as a method: %s"), name);
1620    break;
1621  case FCERR_DELETED:
1622    emsg_funcname(N_("E933: Function was deleted: %s"), name);
1623    break;
1624  case FCERR_TOOMANY:
1625    emsg_funcname(_(e_toomanyarg), name);
1626    break;
1627  case FCERR_TOOFEW:
1628    emsg_funcname(_(e_toofewarg), name);
1629    break;
1630  case FCERR_SCRIPT:
1631    emsg_funcname(N_("E120: Using <SID> not in a script context: %s"), name);
1632    break;
1633  case FCERR_DICT:
1634    emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), name);
1635    break;
1636  }
1637}
1638
1639/// Used by call_func to add a method base (if any) to a function argument list
1640/// as the first argument. @see call_func
1641static void argv_add_base(typval_T *const basetv, typval_T **const argvars, int *const argcount,
1642                          typval_T *const new_argvars, int *const argv_base)
1643  FUNC_ATTR_NONNULL_ARG(2, 3, 4, 5)
1644{
1645  if (basetv != NULL) {
1646    // Method call: base->Method()
1647    memmove(&new_argvars[1], *argvars, sizeof(typval_T) * (size_t)(*argcount));
1648    new_argvars[0] = *basetv;
1649    (*argcount)++;
1650    *argvars = new_argvars;
1651    *argv_base = 1;
1652  }
1653}
1654
1655/// Call a function with its resolved parameters
1656///
1657/// @param funcname  name of the function
1658/// @param len  length of "name" or -1 to use strlen()
1659/// @param rettv  [out] value goes here
1660/// @param argcount_in  number of "argvars"
1661/// @param argvars_in  vars for arguments, must have "argcount" PLUS ONE elements!
1662/// @param funcexe  more arguments
1663///
1664/// @return FAIL if function cannot be called, else OK (even if an error
1665///         occurred while executing the function! Set `msg_list` to capture
1666///         the error, see do_cmdline()).
1667int call_func(const char *funcname, int len, typval_T *rettv, int argcount_in, typval_T *argvars_in,
1668              funcexe_T *funcexe)
1669  FUNC_ATTR_NONNULL_ARG(1, 3, 5, 6)
1670{
1671  int ret = FAIL;
1672  int error = FCERR_NONE;
1673  ufunc_T *fp = NULL;
1674  char fname_buf[FLEN_FIXED + 1];
1675  char *tofree = NULL;
1676  char *fname = NULL;
1677  char *name = NULL;
1678  int argcount = argcount_in;
1679  typval_T *argvars = argvars_in;
1680  dict_T *selfdict = funcexe->fe_selfdict;
1681  typval_T argv[MAX_FUNC_ARGS + 1];  // used when "partial" or
1682                                     // "funcexe->fe_basetv" is not NULL
1683  int argv_clear = 0;
1684  int argv_base = 0;
1685  partial_T *partial = funcexe->fe_partial;
1686
1687  // Initialize rettv so that it is safe for caller to invoke tv_clear(rettv)
1688  // even when call_func() returns FAIL.
1689  rettv->v_type = VAR_UNKNOWN;
1690
1691  if (len <= 0) {
1692    len = (int)strlen(funcname);
1693  }
1694  if (partial != NULL) {
1695    fp = partial->pt_func;
1696  }
1697  if (fp == NULL) {
1698    // Make a copy of the name, if it comes from a funcref variable it could
1699    // be changed or deleted in the called function.
1700    name = xmemdupz(funcname, (size_t)len);
1701    fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1702  }
1703
1704  if (funcexe->fe_doesrange != NULL) {
1705    *funcexe->fe_doesrange = false;
1706  }
1707
1708  if (partial != NULL) {
1709    // When the function has a partial with a dict and there is a dict
1710    // argument, use the dict argument. That is backwards compatible.
1711    // When the dict was bound explicitly use the one from the partial.
1712    if (partial->pt_dict != NULL && (selfdict == NULL || !partial->pt_auto)) {
1713      selfdict = partial->pt_dict;
1714    }
1715    if (error == FCERR_NONE && partial->pt_argc > 0) {
1716      for (argv_clear = 0; argv_clear < partial->pt_argc; argv_clear++) {
1717        if (argv_clear + argcount_in >= MAX_FUNC_ARGS) {
1718          error = FCERR_TOOMANY;
1719          goto theend;
1720        }
1721        tv_copy(&partial->pt_argv[argv_clear], &argv[argv_clear]);
1722      }
1723      for (int i = 0; i < argcount_in; i++) {
1724        argv[i + argv_clear] = argvars_in[i];
1725      }
1726      argvars = argv;
1727      argcount = partial->pt_argc + argcount_in;
1728    }
1729  }
1730
1731  if (error == FCERR_NONE && funcexe->fe_evaluate) {
1732    // Skip "g:" before a function name.
1733    bool is_global = fp == NULL && fname[0] == 'g' && fname[1] == ':';
1734    char *rfname = is_global ? fname + 2 : fname;
1735
1736    rettv->v_type = VAR_NUMBER;         // default rettv is number zero
1737    rettv->vval.v_number = 0;
1738    error = FCERR_UNKNOWN;
1739
1740    if (is_luafunc(partial)) {
1741      if (len > 0) {
1742        error = FCERR_NONE;
1743        argv_add_base(funcexe->fe_basetv, &argvars, &argcount, argv, &argv_base);
1744        nlua_call_vlua(funcname, (size_t)len, argvars, argcount, rettv);
1745      } else {
1746        // v:lua was called directly; show its name in the emsg
1747        XFREE_CLEAR(name);
1748        funcname = "v:lua";
1749      }
1750    } else if (fp != NULL || !builtin_function(rfname, -1)) {
1751      // User defined function.
1752      if (fp == NULL) {
1753        fp = find_func(rfname);
1754      }
1755
1756      // Trigger FuncUndefined event, may load the function.
1757      if (fp == NULL
1758          && apply_autocmds(EVENT_FUNCUNDEFINED, rfname, rfname, true, NULL)
1759          && !aborting()) {
1760        // executed an autocommand, search for the function again
1761        fp = find_func(rfname);
1762      }
1763      // Try loading a package.
1764      if (fp == NULL && script_autoload(rfname, strlen(rfname), true) && !aborting()) {
1765        // Loaded a package, search for the function again.
1766        fp = find_func(rfname);
1767      }
1768
1769      if (fp != NULL && (fp->uf_flags & FC_DELETED)) {
1770        error = FCERR_DELETED;
1771      } else if (fp != NULL) {
1772        if (funcexe->fe_argv_func != NULL) {
1773          // postponed filling in the arguments, do it now
1774          argcount = funcexe->fe_argv_func(argcount, argvars, argv_clear, fp);
1775        }
1776
1777        argv_add_base(funcexe->fe_basetv, &argvars, &argcount, argv, &argv_base);
1778
1779        error = call_user_func_check(fp, argcount, argvars, rettv, funcexe, selfdict);
1780      }
1781    } else if (funcexe->fe_basetv != NULL) {
1782      // expr->method(): Find the method name in the table, call its
1783      // implementation with the base as one of the arguments.
1784      error = call_internal_method(fname, argcount, argvars, rettv,
1785                                   funcexe->fe_basetv);
1786    } else {
1787      // Find the function name in the table, call its implementation.
1788      error = call_internal_func(fname, argcount, argvars, rettv);
1789    }
1790    // The function call (or "FuncUndefined" autocommand sequence) might
1791    // have been aborted by an error, an interrupt, or an explicitly thrown
1792    // exception that has not been caught so far.  This situation can be
1793    // tested for by calling aborting().  For an error in an internal
1794    // function or for the "E132" error in call_user_func(), however, the
1795    // throw point at which the "force_abort" flag (temporarily reset by
1796    // emsg()) is normally updated has not been reached yet. We need to
1797    // update that flag first to make aborting() reliable.
1798    update_force_abort();
1799  }
1800  if (error == FCERR_NONE) {
1801    ret = OK;
1802  }
1803
1804theend:
1805  // Report an error unless the argument evaluation or function call has been
1806  // cancelled due to an aborting error, an interrupt, or an exception.
1807  if (!aborting()) {
1808    user_func_error(error, (name != NULL) ? name : funcname, funcexe->fe_found_var);
1809  }
1810
1811  // clear the copies made from the partial
1812  while (argv_clear > 0) {
1813    tv_clear(&argv[--argv_clear + argv_base]);
1814  }
1815
1816  xfree(tofree);
1817  xfree(name);
1818
1819  return ret;
1820}
1821
1822int call_simple_luafunc(const char *funcname, size_t len, typval_T *rettv)
1823  FUNC_ATTR_NONNULL_ALL
1824{
1825  rettv->v_type = VAR_NUMBER;  // default rettv is number zero
1826  rettv->vval.v_number = 0;
1827
1828  typval_T argvars[1];
1829  argvars[0].v_type = VAR_UNKNOWN;
1830  nlua_call_vlua(funcname, len, argvars, 0, rettv);
1831  return OK;
1832}
1833
1834/// Call a function without arguments, partial or dict.
1835/// This is like call_func() when the call is only "FuncName()".
1836/// To be used by "expr" options.
1837/// Returns NOTDONE when the function could not be found.
1838///
1839/// @param funcname  name of the function
1840/// @param len       length of "name"
1841/// @param rettv     return value goes here
1842int call_simple_func(const char *funcname, size_t len, typval_T *rettv)
1843  FUNC_ATTR_NONNULL_ALL
1844{
1845  int ret = FAIL;
1846
1847  rettv->v_type = VAR_NUMBER;  // default rettv is number zero
1848  rettv->vval.v_number = 0;
1849
1850  // Make a copy of the name, an option can be changed in the function.
1851  char *name = xstrnsave(funcname, len);
1852
1853  int error = FCERR_NONE;
1854  char *tofree = NULL;
1855  char fname_buf[FLEN_FIXED + 1];
1856  char *fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1857
1858  // Skip "g:" before a function name.
1859  bool is_global = fname[0] == 'g' && fname[1] == ':';
1860  char *rfname = is_global ? fname + 2 : fname;
1861
1862  ufunc_T *fp = find_func(rfname);
1863  if (fp == NULL) {
1864    ret = NOTDONE;
1865  } else if (fp != NULL && (fp->uf_flags & FC_DELETED)) {
1866    error = FCERR_DELETED;
1867  } else if (fp != NULL) {
1868    typval_T argvars[1];
1869    argvars[0].v_type = VAR_UNKNOWN;
1870    funcexe_T funcexe = FUNCEXE_INIT;
1871    funcexe.fe_evaluate = true;
1872
1873    error = call_user_func_check(fp, 0, argvars, rettv, &funcexe, NULL);
1874    if (error == FCERR_NONE) {
1875      ret = OK;
1876    }
1877  }
1878
1879  user_func_error(error, name, false);
1880  xfree(tofree);
1881  xfree(name);
1882
1883  return ret;
1884}
1885
1886char *printable_func_name(ufunc_T *fp)
1887{
1888  return fp->uf_name_exp != NULL ? fp->uf_name_exp : fp->uf_name;
1889}
1890
1891/// When "prev_ht_changed" does not equal "ht_changed" give an error and return
1892/// true.  Otherwise return false.
1893static int function_list_modified(const int prev_ht_changed)
1894{
1895  if (prev_ht_changed != func_hashtab.ht_changed) {
1896    emsg(_(e_function_list_was_modified));
1897    return true;
1898  }
1899  return false;
1900}
1901
1902/// List the head of the function: "name(arg1, arg2)".
1903///
1904/// @param[in]  fp      Function pointer.
1905/// @param[in]  indent  Indent line.
1906/// @param[in]  force   Include bang "!" (i.e.: "function!").
1907static int list_func_head(ufunc_T *fp, bool indent, bool force)
1908{
1909  const int prev_ht_changed = func_hashtab.ht_changed;
1910
1911  msg_start();
1912
1913  // a callback at the more prompt may have deleted the function
1914  if (function_list_modified(prev_ht_changed)) {
1915    return FAIL;
1916  }
1917
1918  if (indent) {
1919    msg_puts("   ");
1920  }
1921  msg_puts(force ? "function! " : "function ");
1922  if (fp->uf_name_exp != NULL) {
1923    msg_puts(fp->uf_name_exp);
1924  } else {
1925    msg_puts(fp->uf_name);
1926  }
1927  msg_putchar('(');
1928  int j;
1929  for (j = 0; j < fp->uf_args.ga_len; j++) {
1930    if (j) {
1931      msg_puts(", ");
1932    }
1933    msg_puts(FUNCARG(fp, j));
1934    if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len) {
1935      msg_puts(" = ");
1936      msg_puts(((char **)(fp->uf_def_args.ga_data))
1937               [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]);
1938    }
1939  }
1940  if (fp->uf_varargs) {
1941    if (j) {
1942      msg_puts(", ");
1943    }
1944    msg_puts("...");
1945  }
1946  msg_putchar(')');
1947  if (fp->uf_flags & FC_ABORT) {
1948    msg_puts(" abort");
1949  }
1950  if (fp->uf_flags & FC_RANGE) {
1951    msg_puts(" range");
1952  }
1953  if (fp->uf_flags & FC_DICT) {
1954    msg_puts(" dict");
1955  }
1956  if (fp->uf_flags & FC_CLOSURE) {
1957    msg_puts(" closure");
1958  }
1959  msg_clr_eos();
1960  if (p_verbose > 0) {
1961    last_set_msg(fp->uf_script_ctx);
1962  }
1963
1964  return OK;
1965}
1966
1967/// Get a function name, translating "<SID>" and "<SNR>".
1968/// Also handles a Funcref in a List or Dict.
1969/// flags:
1970/// TFN_INT:         internal function name OK
1971/// TFN_QUIET:       be quiet
1972/// TFN_NO_AUTOLOAD: do not use script autoloading
1973/// TFN_NO_DEREF:    do not dereference a Funcref
1974/// Advances "pp" to just after the function name (if no error).
1975///
1976/// @param skip  only find the end, don't evaluate
1977/// @param fdp  return: info about dictionary used
1978/// @param partial  return: partial of a FuncRef
1979///
1980/// @return the function name in allocated memory, or NULL for failure.
1981char *trans_function_name(char **pp, bool skip, int flags, funcdict_T *fdp, partial_T **partial)
1982  FUNC_ATTR_NONNULL_ARG(1)
1983{
1984  char *name = NULL;
1985  int len;
1986  lval_T lv;
1987
1988  if (fdp != NULL) {
1989    CLEAR_POINTER(fdp);
1990  }
1991  const char *start = *pp;
1992
1993  // Check for hard coded <SNR>: already translated function ID (from a user
1994  // command).
1995  if ((uint8_t)(*pp)[0] == K_SPECIAL && (uint8_t)(*pp)[1] == KS_EXTRA && (*pp)[2] == KE_SNR) {
1996    *pp += 3;
1997    len = get_id_len((const char **)pp) + 3;
1998    return xmemdupz(start, (size_t)len);
1999  }
2000
2001  // A name starting with "<SID>" or "<SNR>" is local to a script.  But
2002  // don't skip over "s:", get_lval() needs it for "s:dict.func".
2003  int lead = eval_fname_script(start);
2004  if (lead > 2) {
2005    start += lead;
2006  }
2007
2008  // Note that TFN_ flags use the same values as GLV_ flags.
2009  const char *end = get_lval((char *)start, NULL, &lv, false, skip, flags | GLV_READ_ONLY,
2010                             lead > 2 ? 0 : FNE_CHECK_START);
2011  if (end == start) {
2012    if (!skip) {
2013      emsg(_("E129: Function name required"));
2014    }
2015    goto theend;
2016  }
2017  if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) {
2018    // Report an invalid expression in braces, unless the expression
2019    // evaluation has been cancelled due to an aborting error, an
2020    // interrupt, or an exception.
2021    if (!aborting()) {
2022      if (end != NULL) {
2023        semsg(_(e_invarg2), start);
2024      }
2025    } else {
2026      *pp = (char *)find_name_end(start, NULL, NULL, FNE_INCL_BR);
2027    }
2028    goto theend;
2029  }
2030
2031  if (lv.ll_tv != NULL) {
2032    if (fdp != NULL) {
2033      fdp->fd_dict = lv.ll_dict;
2034      fdp->fd_newkey = lv.ll_newkey;
2035      lv.ll_newkey = NULL;
2036      fdp->fd_di = lv.ll_di;
2037    }
2038    if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) {
2039      name = xstrdup(lv.ll_tv->vval.v_string);
2040      *pp = (char *)end;
2041    } else if (lv.ll_tv->v_type == VAR_PARTIAL
2042               && lv.ll_tv->vval.v_partial != NULL) {
2043      if (is_luafunc(lv.ll_tv->vval.v_partial) && *end == '.') {
2044        len = check_luafunc_name(end + 1, true);
2045        if (len == 0) {
2046          semsg(e_invexpr2, "v:lua");
2047          goto theend;
2048        }
2049        name = xmallocz((size_t)len);
2050        memcpy(name, end + 1, (size_t)len);
2051        *pp = (char *)end + 1 + len;
2052      } else {
2053        name = xstrdup(partial_name(lv.ll_tv->vval.v_partial));
2054        *pp = (char *)end;
2055      }
2056      if (partial != NULL) {
2057        *partial = lv.ll_tv->vval.v_partial;
2058      }
2059    } else {
2060      if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
2061                                            || lv.ll_dict == NULL
2062                                            || fdp->fd_newkey == NULL)) {
2063        emsg(_(e_funcref));
2064      } else {
2065        *pp = (char *)end;
2066      }
2067      name = NULL;
2068    }
2069    goto theend;
2070  }
2071
2072  if (lv.ll_name == NULL) {
2073    // Error found, but continue after the function name.
2074    *pp = (char *)end;
2075    goto theend;
2076  }
2077
2078  // Check if the name is a Funcref.  If so, use the value.
2079  if (lv.ll_exp_name != NULL) {
2080    len = (int)strlen(lv.ll_exp_name);
2081    name = deref_func_name(lv.ll_exp_name, &len, partial, flags & TFN_NO_AUTOLOAD, NULL);
2082    if (name == lv.ll_exp_name) {
2083      name = NULL;
2084    }
2085  } else if (!(flags & TFN_NO_DEREF)) {
2086    len = (int)(end - *pp);
2087    name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD, NULL);
2088    if (name == *pp) {
2089      name = NULL;
2090    }
2091  }
2092  if (name != NULL) {
2093    name = xstrdup(name);
2094    *pp = (char *)end;
2095    if (strncmp(name, "<SNR>", 5) == 0) {
2096      // Change "<SNR>" to the byte sequence.
2097      name[0] = (char)K_SPECIAL;
2098      name[1] = (char)KS_EXTRA;
2099      name[2] = KE_SNR;
2100      memmove(name + 3, name + 5, strlen(name + 5) + 1);
2101    }
2102    goto theend;
2103  }
2104
2105  if (lv.ll_exp_name != NULL) {
2106    len = (int)strlen(lv.ll_exp_name);
2107    if (lead <= 2 && lv.ll_name == lv.ll_exp_name
2108        && lv.ll_name_len >= 2 && memcmp(lv.ll_name, "s:", 2) == 0) {
2109      // When there was "s:" already or the name expanded to get a
2110      // leading "s:" then remove it.
2111      lv.ll_name += 2;
2112      lv.ll_name_len -= 2;
2113      len -= 2;
2114      lead = 2;
2115    }
2116  } else {
2117    // Skip over "s:" and "g:".
2118    if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) {
2119      lv.ll_name += 2;
2120      lv.ll_name_len -= 2;
2121    }
2122    len = (int)(end - lv.ll_name);
2123  }
2124
2125  size_t sid_buflen = 0;
2126  char sid_buf[20];
2127
2128  // Copy the function name to allocated memory.
2129  // Accept <SID>name() inside a script, translate into <SNR>123_name().
2130  // Accept <SNR>123_name() outside a script.
2131  if (skip) {
2132    lead = 0;  // do nothing
2133  } else if (lead > 0) {
2134    lead = 3;
2135    if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
2136        || eval_fname_sid(*pp)) {
2137      // It's "s:" or "<SID>".
2138      if (current_sctx.sc_sid <= 0) {
2139        emsg(_(e_usingsid));
2140        goto theend;
2141      }
2142      sid_buflen = (size_t)snprintf(sid_buf, sizeof(sid_buf), "%" PRIdSCID "_",
2143                                    current_sctx.sc_sid);
2144      lead += (int)sid_buflen;
2145    }
2146  } else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, (int)lv.ll_name_len)) {
2147    semsg(_("E128: Function name must start with a capital or \"s:\": %s"),
2148          start);
2149    goto theend;
2150  }
2151
2152  if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) {
2153    char *cp = xmemrchr(lv.ll_name, ':', lv.ll_name_len);
2154
2155    if (cp != NULL && cp < end) {
2156      semsg(_("E884: Function name cannot contain a colon: %s"), start);
2157      goto theend;
2158    }
2159  }
2160
2161  name = xmalloc((size_t)len + (size_t)lead + 1);
2162  if (!skip && lead > 0) {
2163    name[0] = (char)K_SPECIAL;
2164    name[1] = (char)KS_EXTRA;
2165    name[2] = KE_SNR;
2166    if (sid_buflen > 0) {  // If it's "<SID>"
2167      memcpy(name + 3, sid_buf, sid_buflen);
2168    }
2169  }
2170  memmove(name + lead, lv.ll_name, (size_t)len);
2171  name[lead + len] = NUL;
2172  *pp = (char *)end;
2173
2174theend:
2175  clear_lval(&lv);
2176  return name;
2177}
2178
2179/// If the "funcname" starts with "s:" or "<SID>", then expands it to the
2180/// current script ID and returns the expanded function name. The caller should
2181/// free the returned name. If not called from a script context or the function
2182/// name doesn't start with these prefixes, then returns NULL.
2183/// This doesn't check whether the script-local function exists or not.
2184char *get_scriptlocal_funcname(char *funcname)
2185{
2186  if (funcname == NULL) {
2187    return NULL;
2188  }
2189
2190  if (strncmp(funcname, "s:", 2) != 0
2191      && strncmp(funcname, "<SID>", 5) != 0) {
2192    // The function name does not have a script-local prefix.
2193    return NULL;
2194  }
2195
2196  if (!SCRIPT_ID_VALID(current_sctx.sc_sid)) {
2197    emsg(_(e_usingsid));
2198    return NULL;
2199  }
2200
2201  char sid_buf[25];
2202  // Expand s: and <SID> prefix into <SNR>nr_<name>
2203  size_t sid_buflen = (size_t)snprintf(sid_buf, sizeof(sid_buf), "<SNR>%" PRIdSCID "_",
2204                                       current_sctx.sc_sid);
2205  const int off = *funcname == 's' ? 2 : 5;
2206  size_t newnamesize = sid_buflen + strlen(funcname + off) + 1;
2207  char *newname = xmalloc(newnamesize);
2208  snprintf(newname, newnamesize, "%s%s", sid_buf, funcname + off);
2209
2210  return newname;
2211}
2212
2213/// Call trans_function_name(), except that a lambda is returned as-is.
2214/// Returns the name in allocated memory.
2215char *save_function_name(char **name, bool skip, int flags, funcdict_T *fudi)
2216{
2217  char *p = *name;
2218  char *saved;
2219
2220  if (strncmp(p, "<lambda>", 8) == 0) {
2221    p += 8;
2222    getdigits(&p, false, 0);
2223    saved = xmemdupz(*name, (size_t)(p - *name));
2224    if (fudi != NULL) {
2225      CLEAR_POINTER(fudi);
2226    }
2227  } else {
2228    saved = trans_function_name(&p, skip, flags, fudi, NULL);
2229  }
2230  *name = p;
2231  return saved;
2232}
2233
2234/// List functions.
2235///
2236/// @param regmatch  When NULL, all of them.
2237///                  Otherwise functions matching "regmatch".
2238static void list_functions(regmatch_T *regmatch)
2239{
2240  const int prev_ht_changed = func_hashtab.ht_changed;
2241  size_t todo = func_hashtab.ht_used;
2242  const hashitem_T *const ht_array = func_hashtab.ht_array;
2243
2244  msg_ext_set_kind("list_cmd");
2245  for (const hashitem_T *hi = ht_array; todo > 0 && !got_int; hi++) {
2246    if (!HASHITEM_EMPTY(hi)) {
2247      ufunc_T *fp = HI2UF(hi);
2248      todo--;
2249      if (regmatch == NULL
2250          ? (!message_filtered(fp->uf_name)
2251             && !func_name_refcount(fp->uf_name))
2252          : (!isdigit((uint8_t)(*fp->uf_name))
2253             && vim_regexec(regmatch, fp->uf_name, 0))) {
2254        if (list_func_head(fp, false, false) == FAIL) {
2255          return;
2256        }
2257        if (function_list_modified(prev_ht_changed)) {
2258          return;
2259        }
2260      }
2261    }
2262  }
2263}
2264
2265/// ":function /pat": list functions matching pattern.
2266static char *list_functions_matching_pat(exarg_T *eap)
2267{
2268  char *p = skip_regexp(eap->arg + 1, '/', true);
2269  if (!eap->skip) {
2270    regmatch_T regmatch;
2271
2272    char c = *p;
2273    *p = NUL;
2274    regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
2275    *p = c;
2276    if (regmatch.regprog != NULL) {
2277      regmatch.rm_ic = p_ic;
2278      list_functions(&regmatch);
2279      vim_regfree(regmatch.regprog);
2280    }
2281  }
2282  if (*p == '/') {
2283    p++;
2284  }
2285
2286  return p;
2287}
2288
2289/// List function "name".
2290/// If bang is given:
2291///  - include "!" in function head
2292///  - exclude line numbers from function body
2293/// Returns the function pointer or NULL on failure.
2294static ufunc_T *list_one_function(exarg_T *eap, char *name, char *p)
2295{
2296  if (!ends_excmd(*skipwhite(p))) {
2297    semsg(_(e_trailing_arg), p);
2298    return NULL;
2299  }
2300
2301  eap->nextcmd = check_nextcmd(p);
2302
2303  if (eap->nextcmd != NULL) {
2304    *p = NUL;
2305  }
2306
2307  if (eap->skip || got_int) {
2308    return NULL;
2309  }
2310
2311  ufunc_T *fp = find_func(name);
2312
2313  if (fp == NULL) {
2314    emsg_funcname(N_("E123: Undefined function: %s"), name);
2315    return NULL;
2316  }
2317
2318  // Check no function was added or removed from a callback, e.g. at
2319  // the more prompt.  "fp" may then be invalid.
2320  const int prev_ht_changed = func_hashtab.ht_changed;
2321
2322  msg_ext_set_kind("list_cmd");
2323  if (list_func_head(fp, !eap->forceit, eap->forceit) != OK) {
2324    return fp;
2325  }
2326
2327  for (int j = 0; j < fp->uf_lines.ga_len && !got_int; j++) {
2328    if (FUNCLINE(fp, j) == NULL) {
2329      continue;
2330    }
2331    msg_putchar('\n');
2332    if (!eap->forceit) {
2333      msg_outnum(j + 1);
2334      if (j < 9) {
2335        msg_putchar(' ');
2336      }
2337      if (j < 99) {
2338        msg_putchar(' ');
2339      }
2340      if (function_list_modified(prev_ht_changed)) {
2341        break;
2342      }
2343    }
2344    msg_prt_line(FUNCLINE(fp, j), false);
2345    line_breakcheck();  // show multiple lines at a time!
2346  }
2347
2348  if (!got_int) {
2349    msg_putchar('\n');
2350    if (!function_list_modified(prev_ht_changed)) {
2351      msg_puts(eap->forceit ? "endfunction" : "   endfunction");
2352    }
2353  }
2354
2355  return fp;
2356}
2357
2358#define MAX_FUNC_NESTING 50
2359
2360/// Read the body of a function, put every line in "newlines".
2361/// This stops at "endfunction".
2362/// "newlines" must already have been initialized.
2363static int get_function_body(exarg_T *eap, garray_T *newlines, char *line_arg_in,
2364                             char **line_to_free, bool show_block)
2365{
2366  bool saved_wait_return = need_wait_return;
2367  char *line_arg = line_arg_in;
2368  int indent = 2;
2369  int nesting = 0;
2370  char *skip_until = NULL;
2371  int ret = FAIL;
2372  bool is_heredoc = false;
2373  char *heredoc_trimmed = NULL;
2374  size_t heredoc_trimmedlen = 0;
2375  bool do_concat = true;
2376
2377  while (true) {
2378    if (KeyTyped) {
2379      msg_scroll = true;
2380      saved_wait_return = false;
2381    }
2382    need_wait_return = false;
2383
2384    char *theline;
2385    char *p;
2386    char *arg;
2387
2388    if (line_arg != NULL) {
2389      // Use eap->arg, split up in parts by line breaks.
2390      theline = line_arg;
2391      p = vim_strchr(theline, '\n');
2392      if (p == NULL) {
2393        line_arg += strlen(line_arg);
2394      } else {
2395        *p = NUL;
2396        line_arg = p + 1;
2397      }
2398    } else {
2399      xfree(*line_to_free);
2400      if (eap->ea_getline == NULL) {
2401        theline = getcmdline(':', 0, indent, do_concat);
2402      } else {
2403        theline = eap->ea_getline(':', eap->cookie, indent, do_concat);
2404      }
2405      *line_to_free = theline;
2406    }
2407    if (KeyTyped) {
2408      lines_left = Rows - 1;
2409    }
2410    if (theline == NULL) {
2411      if (skip_until != NULL) {
2412        semsg(_(e_missing_heredoc_end_marker_str), skip_until);
2413      } else {
2414        emsg(_("E126: Missing :endfunction"));
2415      }
2416      goto theend;
2417    }
2418    if (show_block) {
2419      assert(indent >= 0);
2420      ui_ext_cmdline_block_append((size_t)indent, theline);
2421    }
2422
2423    // Detect line continuation: SOURCING_LNUM increased more than one.
2424    linenr_T sourcing_lnum_off = get_sourced_lnum(eap->ea_getline, eap->cookie);
2425    if (SOURCING_LNUM < sourcing_lnum_off) {
2426      sourcing_lnum_off -= SOURCING_LNUM;
2427    } else {
2428      sourcing_lnum_off = 0;
2429    }
2430
2431    if (skip_until != NULL) {
2432      // Don't check for ":endfunc" between
2433      // * ":append" and "."
2434      // * ":python <<EOF" and "EOF"
2435      // * ":let {var-name} =<< [trim] {marker}" and "{marker}"
2436      if (heredoc_trimmed == NULL
2437          || (is_heredoc && skipwhite(theline) == theline)
2438          || strncmp(theline, heredoc_trimmed, heredoc_trimmedlen) == 0) {
2439        if (heredoc_trimmed == NULL) {
2440          p = theline;
2441        } else if (is_heredoc) {
2442          p = skipwhite(theline) == theline ? theline : theline + heredoc_trimmedlen;
2443        } else {
2444          p = theline + heredoc_trimmedlen;
2445        }
2446        if (strcmp(p, skip_until) == 0) {
2447          XFREE_CLEAR(skip_until);
2448          XFREE_CLEAR(heredoc_trimmed);
2449          heredoc_trimmedlen = 0;
2450          do_concat = true;
2451          is_heredoc = false;
2452        }
2453      }
2454    } else {
2455      // skip ':' and blanks
2456      for (p = theline; ascii_iswhite(*p) || *p == ':'; p++) {}
2457
2458      // Check for "endfunction".
2459      if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0) {
2460        if (*p == '!') {
2461          p++;
2462        }
2463        char *nextcmd = NULL;
2464        if (*p == '|') {
2465          nextcmd = p + 1;
2466        } else if (line_arg != NULL && *skipwhite(line_arg) != NUL) {
2467          nextcmd = line_arg;
2468        } else if (*p != NUL && *p != '"' && p_verbose > 0) {
2469          swmsg(true, _("W22: Text found after :endfunction: %s"), p);
2470        }
2471        if (nextcmd != NULL) {
2472          // Another command follows. If the line came from "eap" we
2473          // can simply point into it, otherwise we need to change
2474          // "eap->cmdlinep".
2475          eap->nextcmd = nextcmd;
2476          if (*line_to_free != NULL) {
2477            xfree(*eap->cmdlinep);
2478            *eap->cmdlinep = *line_to_free;
2479            *line_to_free = NULL;
2480          }
2481        }
2482        break;
2483      }
2484
2485      // Increase indent inside "if", "while", "for" and "try", decrease
2486      // at "end".
2487      if (indent > 2 && strncmp(p, "end", 3) == 0) {
2488        indent -= 2;
2489      } else if (strncmp(p, "if", 2) == 0
2490                 || strncmp(p, "wh", 2) == 0
2491                 || strncmp(p, "for", 3) == 0
2492                 || strncmp(p, "try", 3) == 0) {
2493        indent += 2;
2494      }
2495
2496      // Check for defining a function inside this function.
2497      if (checkforcmd(&p, "function", 2)) {
2498        if (*p == '!') {
2499          p = skipwhite(p + 1);
2500        }
2501        p += eval_fname_script(p);
2502        xfree(trans_function_name(&p, true, 0, NULL, NULL));
2503        if (*skipwhite(p) == '(') {
2504          if (nesting == MAX_FUNC_NESTING - 1) {
2505            emsg(_(e_function_nesting_too_deep));
2506          } else {
2507            nesting++;
2508            indent += 2;
2509          }
2510        }
2511      }
2512
2513      // Check for ":append", ":change", ":insert".
2514      char *const tp = p = skip_range(p, NULL);
2515      if ((checkforcmd(&p, "append", 1)
2516           || checkforcmd(&p, "change", 1)
2517           || checkforcmd(&p, "insert", 1))
2518          && (*p == '!' || *p == '|' || ascii_iswhite_nl_or_nul(*p))) {
2519        skip_until = xmemdupz(".", 1);
2520      } else {
2521        p = tp;
2522      }
2523
2524      // heredoc: Check for ":python <<EOF", ":lua <<EOF", etc.
2525      arg = skipwhite(skiptowhite(p));
2526      if (arg[0] == '<' && arg[1] == '<'
2527          && ((p[0] == 'p' && p[1] == 'y'
2528               && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2529                   || ((p[2] == '3' || p[2] == 'x')
2530                       && !ASCII_ISALPHA(p[3]))))
2531              || (p[0] == 'p' && p[1] == 'e'
2532                  && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2533              || (p[0] == 't' && p[1] == 'c'
2534                  && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2535              || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2536                  && !ASCII_ISALPHA(p[3]))
2537              || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2538                  && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2539              || (p[0] == 'm' && p[1] == 'z'
2540                  && (!ASCII_ISALPHA(p[2]) || p[2] == 's')))) {
2541        // ":python <<" continues until a dot, like ":append"
2542        p = skipwhite(arg + 2);
2543        if (strncmp(p, "trim", 4) == 0
2544            && (p[4] == NUL || ascii_iswhite(p[4]))) {
2545          // Ignore leading white space.
2546          p = skipwhite(p + 4);
2547          heredoc_trimmedlen = (size_t)(skipwhite(theline) - theline);
2548          heredoc_trimmed = xmemdupz(theline, heredoc_trimmedlen);
2549        }
2550        if (*p == NUL) {
2551          skip_until = xmemdupz(".", 1);
2552        } else {
2553          skip_until = xmemdupz(p, (size_t)(skiptowhite(p) - p));
2554        }
2555        do_concat = false;
2556        is_heredoc = true;
2557      }
2558
2559      if (!is_heredoc) {
2560        // Check for ":cmd v =<< [trim] EOF"
2561        //       and ":cmd [a, b] =<< [trim] EOF"
2562        // Where "cmd" can be "let" or "const".
2563        arg = p;
2564        if (checkforcmd(&arg, "let", 2) || checkforcmd(&p, "const", 5)) {
2565          int var_count = 0;
2566          int semicolon = 0;
2567          arg = (char *)skip_var_list(arg, &var_count, &semicolon, true);
2568          if (arg != NULL) {
2569            arg = skipwhite(arg);
2570          }
2571          if (arg != NULL && strncmp(arg, "=<<", 3) == 0) {
2572            p = skipwhite(arg + 3);
2573            bool has_trim = false;
2574            while (true) {
2575              if (strncmp(p, "trim", 4) == 0
2576                  && (p[4] == NUL || ascii_iswhite(p[4]))) {
2577                // Ignore leading white space.
2578                p = skipwhite(p + 4);
2579                has_trim = true;
2580                continue;
2581              }
2582              if (strncmp(p, "eval", 4) == 0
2583                  && (p[4] == NUL || ascii_iswhite(p[4]))) {
2584                // Ignore leading white space.
2585                p = skipwhite(p + 4);
2586                continue;
2587              }
2588              break;
2589            }
2590            if (has_trim) {
2591              heredoc_trimmedlen = (size_t)(skipwhite(theline) - theline);
2592              heredoc_trimmed = xmemdupz(theline, heredoc_trimmedlen);
2593            }
2594            XFREE_CLEAR(skip_until);
2595            skip_until = xmemdupz(p, (size_t)(skiptowhite(p) - p));
2596            do_concat = false;
2597            is_heredoc = true;
2598          }
2599        }
2600      }
2601    }
2602
2603    // Add the line to the function.
2604    ga_grow(newlines, 1 + (int)sourcing_lnum_off);
2605
2606    // Copy the line to newly allocated memory.  get_one_sourceline()
2607    // allocates 250 bytes per line, this saves 80% on average.  The cost
2608    // is an extra alloc/free.
2609    p = xstrdup(theline);
2610    ((char **)(newlines->ga_data))[newlines->ga_len++] = p;
2611
2612    // Add NULL lines for continuation lines, so that the line count is
2613    // equal to the index in the growarray.
2614    while (sourcing_lnum_off-- > 0) {
2615      ((char **)(newlines->ga_data))[newlines->ga_len++] = NULL;
2616    }
2617
2618    // Check for end of eap->arg.
2619    if (line_arg != NULL && *line_arg == NUL) {
2620      line_arg = NULL;
2621    }
2622  }
2623
2624  // Return OK when no error was detected.
2625  if (!did_emsg) {
2626    ret = OK;
2627  }
2628
2629theend:
2630  xfree(skip_until);
2631  xfree(heredoc_trimmed);
2632  need_wait_return |= saved_wait_return;
2633  return ret;
2634}
2635
2636/// ":function"
2637void ex_function(exarg_T *eap)
2638{
2639  char *line_to_free = NULL;
2640  char *arg;
2641  char *line_arg = NULL;
2642  garray_T newargs;
2643  garray_T default_args;
2644  garray_T newlines;
2645  int varargs = false;
2646  int flags = 0;
2647  ufunc_T *fp = NULL;
2648  bool free_fp = false;
2649  bool overwrite = false;
2650  funcdict_T fudi;
2651  static int func_nr = 0;           // number for nameless function
2652  hashtab_T *ht;
2653  bool show_block = false;
2654
2655  // ":function" without argument: list functions.
2656  if (ends_excmd(*eap->arg)) {
2657    if (!eap->skip) {
2658      list_functions(NULL);
2659    }
2660    eap->nextcmd = check_nextcmd(eap->arg);
2661    return;
2662  }
2663
2664  // ":function /pat": list functions matching pattern.
2665  if (*eap->arg == '/') {
2666    char *p = list_functions_matching_pat(eap);
2667    eap->nextcmd = check_nextcmd(p);
2668    return;
2669  }
2670
2671  // Get the function name.  There are these situations:
2672  // func        function name
2673  //             "name" == func, "fudi.fd_dict" == NULL
2674  // dict.func   new dictionary entry
2675  //             "name" == NULL, "fudi.fd_dict" set,
2676  //             "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
2677  // dict.func   existing dict entry with a Funcref
2678  //             "name" == func, "fudi.fd_dict" set,
2679  //             "fudi.fd_di" set, "fudi.fd_newkey" == NULL
2680  // dict.func   existing dict entry that's not a Funcref
2681  //             "name" == NULL, "fudi.fd_dict" set,
2682  //             "fudi.fd_di" set, "fudi.fd_newkey" == NULL
2683  // s:func      script-local function name
2684  // g:func      global function name, same as "func"
2685  char *p = eap->arg;
2686  char *name = save_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi);
2687  int paren = (vim_strchr(p, '(') != NULL);
2688  if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) {
2689    // Return on an invalid expression in braces, unless the expression
2690    // evaluation has been cancelled due to an aborting error, an
2691    // interrupt, or an exception.
2692    if (!aborting()) {
2693      if (fudi.fd_newkey != NULL) {
2694        semsg(_(e_dictkey), fudi.fd_newkey);
2695      }
2696      xfree(fudi.fd_newkey);
2697      return;
2698    }
2699    eap->skip = true;
2700  }
2701
2702  // An error in a function call during evaluation of an expression in magic
2703  // braces should not cause the function not to be defined.
2704  const int saved_did_emsg = did_emsg;
2705  did_emsg = false;
2706
2707  // ":function func" with only function name: list function.
2708  if (!paren) {
2709    fp = list_one_function(eap, name, p);
2710    goto ret_free;
2711  }
2712
2713  // ":function name(arg1, arg2)" Define function.
2714  p = skipwhite(p);
2715  if (*p != '(') {
2716    if (!eap->skip) {
2717      semsg(_("E124: Missing '(': %s"), eap->arg);
2718      goto ret_free;
2719    }
2720    // attempt to continue by skipping some text
2721    if (vim_strchr(p, '(') != NULL) {
2722      p = vim_strchr(p, '(');
2723    }
2724  }
2725  p = skipwhite(p + 1);
2726
2727  ga_init(&newargs, (int)sizeof(char *), 3);
2728  ga_init(&newlines, (int)sizeof(char *), 3);
2729
2730  if (!eap->skip) {
2731    // Check the name of the function.  Unless it's a dictionary function
2732    // (that we are overwriting).
2733    if (name != NULL) {
2734      arg = name;
2735    } else {
2736      arg = fudi.fd_newkey;
2737    }
2738    if (arg != NULL && (fudi.fd_di == NULL || !tv_is_func(fudi.fd_di->di_tv))) {
2739      char *name_base = arg;
2740      // When defining a dictionary function with bracket notation
2741      // (e.g. obj['foo-bar']()), the key is a dictionary key and is not
2742      // required to follow function naming rules.  Skip the identifier
2743      // check in that case.
2744      if (arg != fudi.fd_newkey) {
2745        if ((uint8_t)(*arg) == K_SPECIAL) {
2746          name_base = vim_strchr(arg, '_');
2747          if (name_base == NULL) {
2748            name_base = arg + 3;
2749          } else {
2750            name_base++;
2751          }
2752        }
2753        int i;
2754        for (i = 0; name_base[i] != NUL && (i == 0
2755                                            ? eval_isnamec1(name_base[i])
2756                                            : eval_isnamec(name_base[i])); i++) {}
2757        if (name_base[i] != NUL) {
2758          emsg_funcname(e_invarg2, arg);
2759          goto ret_free;
2760        }
2761      }
2762    }
2763    // Disallow using the g: dict.
2764    if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) {
2765      emsg(_("E862: Cannot use g: here"));
2766      goto ret_free;
2767    }
2768  }
2769
2770  if (get_function_args(&p, ')', &newargs, &varargs,
2771                        &default_args, eap->skip) == FAIL) {
2772    goto errret_2;
2773  }
2774
2775  if (KeyTyped && ui_has(kUICmdline)) {
2776    show_block = true;
2777    ui_ext_cmdline_block_append(0, eap->cmd);
2778  }
2779
2780  // find extra arguments "range", "dict", "abort" and "closure"
2781  while (true) {
2782    p = skipwhite(p);
2783    if (strncmp(p, "range", 5) == 0) {
2784      flags |= FC_RANGE;
2785      p += 5;
2786    } else if (strncmp(p, "dict", 4) == 0) {
2787      flags |= FC_DICT;
2788      p += 4;
2789    } else if (strncmp(p, "abort", 5) == 0) {
2790      flags |= FC_ABORT;
2791      p += 5;
2792    } else if (strncmp(p, "closure", 7) == 0) {
2793      flags |= FC_CLOSURE;
2794      p += 7;
2795      if (current_funccal == NULL) {
2796        emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
2797                      name == NULL ? "" : name);
2798        goto erret;
2799      }
2800    } else {
2801      break;
2802    }
2803  }
2804
2805  // When there is a line break use what follows for the function body.
2806  // Makes 'exe "func Test()\n...\nendfunc"' work.
2807  if (*p == '\n') {
2808    line_arg = p + 1;
2809  } else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) {
2810    semsg(_(e_trailing_arg), p);
2811  }
2812
2813  // Read the body of the function, until ":endfunction" is found.
2814  if (KeyTyped) {
2815    // Check if the function already exists, don't let the user type the
2816    // whole function before telling them it doesn't work!  For a script we
2817    // need to skip the body to be able to find what follows.
2818    if (!eap->skip && !eap->forceit) {
2819      if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) {
2820        emsg(_(e_funcdict));
2821      } else if (name != NULL && find_func(name) != NULL) {
2822        emsg_funcname(e_funcexts, name);
2823      }
2824    }
2825
2826    if (!eap->skip && did_emsg) {
2827      goto erret;
2828    }
2829
2830    if (!ui_has(kUICmdline)) {
2831      msg_putchar('\n');              // don't overwrite the function name
2832    }
2833    cmdline_row = msg_row;
2834  }
2835
2836  // Save the starting line number.
2837  linenr_T sourcing_lnum_top = SOURCING_LNUM;
2838
2839  // Do not define the function when getting the body fails and when skipping.
2840  if (get_function_body(eap, &newlines, line_arg, &line_to_free, show_block) == FAIL
2841      || eap->skip) {
2842    goto erret;
2843  }
2844
2845  // If there are no errors, add the function
2846  size_t namelen = 0;
2847  if (fudi.fd_dict == NULL) {
2848    dictitem_T *v = find_var(name, strlen(name), &ht, false);
2849    if (v != NULL && v->di_tv.v_type == VAR_FUNC) {
2850      emsg_funcname(N_("E707: Function name conflicts with variable: %s"), name);
2851      goto erret;
2852    }
2853
2854    fp = find_func(name);
2855    if (fp != NULL) {
2856      // Function can be replaced with "function!" and when sourcing the
2857      // same script again, but only once.
2858      if (!eap->forceit
2859          && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid
2860              || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) {
2861        emsg_funcname(e_funcexts, name);
2862        goto errret_keep;
2863      }
2864      if (fp->uf_calls > 0) {
2865        emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), name);
2866        goto errret_keep;
2867      }
2868      if (fp->uf_refcount > 1) {
2869        // This function is referenced somewhere, don't redefine it but
2870        // create a new one.
2871        (fp->uf_refcount)--;
2872        fp->uf_flags |= FC_REMOVED;
2873        fp = NULL;
2874        overwrite = true;
2875      } else {
2876        char *exp_name = fp->uf_name_exp;
2877        // redefine existing function, keep the expanded name
2878        XFREE_CLEAR(name);
2879        fp->uf_name_exp = NULL;
2880        func_clear_items(fp);
2881        fp->uf_name_exp = exp_name;
2882        fp->uf_profiling = false;
2883        fp->uf_prof_initialized = false;
2884      }
2885    }
2886  } else {
2887    char numbuf[NUMBUFLEN];
2888
2889    fp = NULL;
2890    if (fudi.fd_newkey == NULL && !eap->forceit) {
2891      emsg(_(e_funcdict));
2892      goto erret;
2893    }
2894    if (fudi.fd_di == NULL) {
2895      if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, TV_CSTRING)) {
2896        // Can't add a function to a locked dictionary
2897        goto erret;
2898      }
2899    } else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, TV_CSTRING)) {
2900      // Can't change an existing function if it is locked
2901      goto erret;
2902    }
2903
2904    // Give the function a sequential number.  Can only be used with a
2905    // Funcref!
2906    xfree(name);
2907    namelen = (size_t)snprintf(numbuf, sizeof(numbuf), "%d", ++func_nr);
2908    name = xmemdupz(numbuf, namelen);
2909  }
2910
2911  if (fp == NULL) {
2912    if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) {
2913      // Check that the autoload name matches the script name.
2914      int j = FAIL;
2915      if (SOURCING_NAME != NULL) {
2916        char *scriptname = autoload_name(name, strlen(name));
2917        p = vim_strchr(scriptname, '/');
2918        int plen = (int)strlen(p);
2919        int slen = (int)strlen(SOURCING_NAME);
2920        if (slen > plen && path_equal(p, SOURCING_NAME + slen - plen, kPathCmpLiteral)) {
2921          j = OK;
2922        }
2923        xfree(scriptname);
2924      }
2925      if (j == FAIL) {
2926        semsg(_("E746: Function name does not match script file name: %s"),
2927              name);
2928        goto erret;
2929      }
2930    }
2931
2932    if (namelen == 0) {
2933      namelen = strlen(name);
2934    }
2935    fp = alloc_ufunc(name, namelen);
2936
2937    if (fudi.fd_dict != NULL) {
2938      char *func_name = xmemdupz(name, namelen);
2939
2940      if (fudi.fd_di == NULL) {
2941        // Add new dict entry
2942        fudi.fd_di = tv_dict_item_alloc(fudi.fd_newkey);
2943        if (tv_dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) {
2944          xfree(fudi.fd_di);
2945          xfree(func_name);
2946          XFREE_CLEAR(fp);
2947          goto erret;
2948        }
2949      } else {
2950        // Overwrite existing dict entry.
2951        tv_clear(&fudi.fd_di->di_tv);
2952      }
2953      fudi.fd_di->di_tv.v_type = VAR_FUNC;
2954      fudi.fd_di->di_tv.vval.v_string = func_name;
2955
2956      // behave like "dict" was used
2957      flags |= FC_DICT;
2958    }
2959
2960    // insert the new function in the function list
2961    if (overwrite) {
2962      hashitem_T *hi = hash_find(&func_hashtab, name);
2963      hi->hi_key = UF2HIKEY(fp);
2964    } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) {
2965      free_fp = true;
2966      goto erret;
2967    }
2968    fp->uf_refcount = 1;
2969  }
2970  fp->uf_args = newargs;
2971  fp->uf_def_args = default_args;
2972  fp->uf_lines = newlines;
2973  if ((flags & FC_CLOSURE) != 0) {
2974    register_closure(fp);
2975  } else {
2976    fp->uf_scoped = NULL;
2977  }
2978  if (prof_def_func()) {
2979    func_do_profile(fp);
2980  }
2981  fp->uf_varargs = varargs;
2982  if (sandbox) {
2983    flags |= FC_SANDBOX;
2984  }
2985  fp->uf_flags = flags;
2986  fp->uf_calls = 0;
2987  fp->uf_script_ctx = current_sctx;
2988  fp->uf_script_ctx.sc_lnum += sourcing_lnum_top;
2989  nlua_set_sctx(&fp->uf_script_ctx);
2990
2991  goto ret_free;
2992
2993erret:
2994  if (fp != NULL) {
2995    // these were set to "newargs" and "default_args", which are cleared below
2996    ga_init(&fp->uf_args, (int)sizeof(char *), 1);
2997    ga_init(&fp->uf_def_args, (int)sizeof(char *), 1);
2998  }
2999errret_2:
3000  if (fp != NULL) {
3001    XFREE_CLEAR(fp->uf_name_exp);
3002  }
3003  if (free_fp) {
3004    XFREE_CLEAR(fp);
3005  }
3006errret_keep:
3007  ga_clear_strings(&newargs);
3008  ga_clear_strings(&default_args);
3009  ga_clear_strings(&newlines);
3010ret_free:
3011  xfree(line_to_free);
3012  xfree(fudi.fd_newkey);
3013  xfree(name);
3014  did_emsg |= saved_did_emsg;
3015  if (show_block) {
3016    ui_ext_cmdline_block_leave();
3017  }
3018}
3019
3020/// @return  5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
3021///          2 if "p" starts with "s:".
3022///          0 otherwise.
3023int eval_fname_script(const char *const p)
3024{
3025  // Use mb_strnicmp() because in Turkish comparing the "I" may not work with
3026  // the standard library function.
3027  if (p[0] == '<'
3028      && (mb_strnicmp(p + 1, "SID>", 4) == 0
3029          || mb_strnicmp(p + 1, "SNR>", 4) == 0)) {
3030    return 5;
3031  }
3032  if (p[0] == 's' && p[1] == ':') {
3033    return 2;
3034  }
3035  return 0;
3036}
3037
3038bool translated_function_exists(const char *name)
3039{
3040  if (builtin_function(name, -1)) {
3041    return find_internal_func(name) != NULL;
3042  }
3043  return find_func(name) != NULL;
3044}
3045
3046/// Check whether function with the given name exists
3047///
3048/// @param[in] name  Function name.
3049/// @param[in] no_deref  Whether to dereference a Funcref.
3050///
3051/// @return  true if it exists, false otherwise.
3052bool function_exists(const char *const name, bool no_deref)
3053{
3054  const char *nm = name;
3055  bool n = false;
3056  int flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
3057
3058  if (no_deref) {
3059    flag |= TFN_NO_DEREF;
3060  }
3061  char *const p = trans_function_name((char **)&nm, false, flag, NULL, NULL);
3062  nm = skipwhite(nm);
3063
3064  // Only accept "funcname", "funcname ", "funcname (..." and
3065  // "funcname(...", not "funcname!...".
3066  if (p != NULL && (*nm == NUL || *nm == '(')) {
3067    n = translated_function_exists(p);
3068  }
3069  xfree(p);
3070  return n;
3071}
3072
3073/// Function given to ExpandGeneric() to obtain the list of user defined
3074/// function names.
3075char *get_user_func_name(expand_T *xp, int idx)
3076{
3077  static size_t done;
3078  static int changed;
3079  static hashitem_T *hi;
3080
3081  if (idx == 0) {
3082    done = 0;
3083    hi = func_hashtab.ht_array;
3084    changed = func_hashtab.ht_changed;
3085  }
3086  assert(hi);
3087  if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) {
3088    if (done++ > 0) {
3089      hi++;
3090    }
3091    while (HASHITEM_EMPTY(hi)) {
3092      hi++;
3093    }
3094    ufunc_T *fp = HI2UF(hi);
3095
3096    if ((fp->uf_flags & FC_DICT)
3097        || strncmp(fp->uf_name, "<lambda>", 8) == 0) {
3098      return "";       // don't show dict and lambda functions
3099    }
3100
3101    if (fp->uf_namelen + 4 >= IOSIZE) {
3102      return fp->uf_name;  // Prevent overflow.
3103    }
3104
3105    int len = cat_func_name(IObuff, IOSIZE, fp);
3106    if (xp->xp_context != EXPAND_USER_FUNC) {
3107      xstrlcpy(IObuff + len, "(", IOSIZE - (size_t)len);
3108      if (!fp->uf_varargs && GA_EMPTY(&fp->uf_args)) {
3109        len++;
3110        xstrlcpy(IObuff + len, ")", IOSIZE - (size_t)len);
3111      }
3112    }
3113    return IObuff;
3114  }
3115  return NULL;
3116}
3117
3118/// ":delfunction {name}"
3119void ex_delfunction(exarg_T *eap)
3120{
3121  ufunc_T *fp = NULL;
3122  funcdict_T fudi;
3123
3124  char *p = eap->arg;
3125  char *name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
3126  xfree(fudi.fd_newkey);
3127  if (name == NULL) {
3128    if (fudi.fd_dict != NULL && !eap->skip) {
3129      emsg(_(e_funcref));
3130    }
3131    return;
3132  }
3133  if (!ends_excmd(*skipwhite(p))) {
3134    xfree(name);
3135    semsg(_(e_trailing_arg), p);
3136    return;
3137  }
3138  eap->nextcmd = check_nextcmd(p);
3139  if (eap->nextcmd != NULL) {
3140    *p = NUL;
3141  }
3142
3143  if (isdigit((uint8_t)(*name)) && fudi.fd_dict == NULL) {
3144    if (!eap->skip) {
3145      semsg(_(e_invarg2), eap->arg);
3146    }
3147    xfree(name);
3148    return;
3149  }
3150  if (!eap->skip) {
3151    fp = find_func(name);
3152  }
3153  xfree(name);
3154
3155  if (!eap->skip) {
3156    if (fp == NULL) {
3157      if (!eap->forceit) {
3158        semsg(_(e_nofunc), eap->arg);
3159      }
3160      return;
3161    }
3162    if (fp->uf_calls > 0) {
3163      semsg(_("E131: Cannot delete function %s: It is in use"), eap->arg);
3164      return;
3165    }
3166    // check `uf_refcount > 2` because deleting a function should also reduce
3167    // the reference count, and 1 is the initial refcount.
3168    if (fp->uf_refcount > 2) {
3169      semsg(_("Cannot delete function %s: It is being used internally"),
3170            eap->arg);
3171      return;
3172    }
3173
3174    if (fudi.fd_dict != NULL) {
3175      // Delete the dict item that refers to the function, it will
3176      // invoke func_unref() and possibly delete the function.
3177      tv_dict_item_remove(fudi.fd_dict, fudi.fd_di);
3178    } else {
3179      // A normal function (not a numbered function or lambda) has a
3180      // refcount of 1 for the entry in the hashtable.  When deleting
3181      // it and the refcount is more than one, it should be kept.
3182      // A numbered function or lambda should be kept if the refcount is
3183      // one or more.
3184      if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) {
3185        // Function is still referenced somewhere. Don't free it but
3186        // do remove it from the hashtable.
3187        if (func_remove(fp)) {
3188          fp->uf_refcount--;
3189        }
3190        fp->uf_flags |= FC_DELETED;
3191      } else {
3192        func_clear_free(fp, false);
3193      }
3194    }
3195  }
3196}
3197
3198/// Unreference a Function: decrement the reference count and free it when it
3199/// becomes zero.
3200void func_unref(char *name)
3201{
3202  if (name == NULL || !func_name_refcount(name)) {
3203    return;
3204  }
3205
3206  ufunc_T *fp = find_func(name);
3207  if (fp == NULL && isdigit((uint8_t)(*name))) {
3208#ifdef EXITFREE
3209    if (!entered_free_all_mem) {
3210      internal_error("func_unref()");
3211      abort();
3212    }
3213#else
3214    internal_error("func_unref()");
3215    abort();
3216#endif
3217  }
3218  func_ptr_unref(fp);
3219}
3220
3221/// Unreference a Function: decrement the reference count and free it when it
3222/// becomes zero.
3223/// Unreference user function, freeing it if needed
3224///
3225/// Decrements the reference count and frees when it becomes zero.
3226///
3227/// @param  fp  Function to unreference.
3228void func_ptr_unref(ufunc_T *fp)
3229{
3230  if (fp != NULL && --fp->uf_refcount <= 0) {
3231    // Only delete it when it's not being used. Otherwise it's done
3232    // when "uf_calls" becomes zero.
3233    if (fp->uf_calls == 0) {
3234      func_clear_free(fp, false);
3235    }
3236  }
3237}
3238
3239/// Count a reference to a Function.
3240void func_ref(char *name)
3241{
3242  if (name == NULL || !func_name_refcount(name)) {
3243    return;
3244  }
3245  ufunc_T *fp = find_func(name);
3246  if (fp != NULL) {
3247    (fp->uf_refcount)++;
3248  } else if (isdigit((uint8_t)(*name))) {
3249    // Only give an error for a numbered function.
3250    // Fail silently, when named or lambda function isn't found.
3251    internal_error("func_ref()");
3252  }
3253}
3254
3255/// Count a reference to a Function.
3256void func_ptr_ref(ufunc_T *fp)
3257{
3258  if (fp != NULL) {
3259    (fp->uf_refcount)++;
3260  }
3261}
3262
3263/// Check whether funccall is still referenced outside
3264///
3265/// It is supposed to be referenced if either it is referenced itself or if l:,
3266/// a: or a:000 are referenced as all these are statically allocated within
3267/// funccall structure.
3268static inline bool fc_referenced(const funccall_T *const fc)
3269  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
3270  FUNC_ATTR_NONNULL_ALL
3271{
3272  return ((fc->fc_l_varlist.lv_refcount  // NOLINT(runtime/deprecated)
3273           != DO_NOT_FREE_CNT)
3274          || fc->fc_l_vars.dv_refcount != DO_NOT_FREE_CNT
3275          || fc->fc_l_avars.dv_refcount != DO_NOT_FREE_CNT
3276          || fc->fc_refcount > 0);
3277}
3278
3279/// @return true if items in "fc" do not have "copyID".  That means they are not
3280/// referenced from anywhere that is in use.
3281static bool can_free_funccal(funccall_T *fc, int copyID)
3282{
3283  return fc->fc_l_varlist.lv_copyID != copyID
3284         && fc->fc_l_vars.dv_copyID != copyID
3285         && fc->fc_l_avars.dv_copyID != copyID
3286         && fc->fc_copyID != copyID;
3287}
3288
3289/// ":return [expr]"
3290void ex_return(exarg_T *eap)
3291{
3292  char *arg = eap->arg;
3293  typval_T rettv;
3294  bool returning = false;
3295
3296  if (current_funccal == NULL) {
3297    emsg(_("E133: :return not inside a function"));
3298    return;
3299  }
3300
3301  evalarg_T evalarg = { .eval_flags = eap->skip ? 0 : EVAL_EVALUATE };
3302
3303  if (eap->skip) {
3304    emsg_skip++;
3305  }
3306
3307  eap->nextcmd = NULL;
3308  if ((*arg != NUL && *arg != '|' && *arg != '\n')
3309      && eval0(arg, &rettv, eap, &evalarg) != FAIL) {
3310    if (!eap->skip) {
3311      returning = do_return(eap, false, true, &rettv);
3312    } else {
3313      tv_clear(&rettv);
3314    }
3315  } else if (!eap->skip) {  // It's safer to return also on error.
3316    // In return statement, cause_abort should be force_abort.
3317    update_force_abort();
3318
3319    // Return unless the expression evaluation has been cancelled due to an
3320    // aborting error, an interrupt, or an exception.
3321    if (!aborting()) {
3322      returning = do_return(eap, false, true, NULL);
3323    }
3324  }
3325
3326  // When skipping or the return gets pending, advance to the next command
3327  // in this line (!returning).  Otherwise, ignore the rest of the line.
3328  // Following lines will be ignored by get_func_line().
3329  if (returning) {
3330    eap->nextcmd = NULL;
3331  } else if (eap->nextcmd == NULL) {          // no argument
3332    eap->nextcmd = check_nextcmd(arg);
3333  }
3334
3335  if (eap->skip) {
3336    emsg_skip--;
3337  }
3338  clear_evalarg(&evalarg, eap);
3339}
3340
3341/// Lower level implementation of "call".  Only called when not skipping.
3342static int ex_call_inner(exarg_T *eap, char *name, char **arg, char *startarg,
3343                         const funcexe_T *const funcexe_init, evalarg_T *const evalarg)
3344{
3345  bool doesrange;
3346  bool failed = false;
3347
3348  for (linenr_T lnum = eap->line1; lnum <= eap->line2; lnum++) {
3349    if (eap->addr_count > 0) {
3350      if (lnum > curbuf->b_ml.ml_line_count) {
3351        // If the function deleted lines or switched to another buffer
3352        // the line number may become invalid.
3353        emsg(_(e_invrange));
3354        break;
3355      }
3356      curwin->w_cursor.lnum = lnum;
3357      curwin->w_cursor.col = 0;
3358      curwin->w_cursor.coladd = 0;
3359    }
3360    *arg = startarg;
3361
3362    funcexe_T funcexe = *funcexe_init;
3363    funcexe.fe_doesrange = &doesrange;
3364    typval_T rettv;
3365    rettv.v_type = VAR_UNKNOWN;  // tv_clear() uses this
3366    if (get_func_tv(name, -1, &rettv, arg, evalarg, &funcexe) == FAIL) {
3367      failed = true;
3368      break;
3369    }
3370
3371    // Handle a function returning a Funcref, Dict or List.
3372    if (handle_subscript((const char **)arg, &rettv, &EVALARG_EVALUATE, true) == FAIL) {
3373      failed = true;
3374      break;
3375    }
3376
3377    tv_clear(&rettv);
3378    if (doesrange) {
3379      break;
3380    }
3381
3382    // Stop when immediately aborting on error, or when an interrupt
3383    // occurred or an exception was thrown but not caught.
3384    // get_func_tv() returned OK, so that the check for trailing
3385    // characters below is executed.
3386    if (aborting()) {
3387      break;
3388    }
3389  }
3390
3391  return failed;
3392}
3393
3394/// Core part of ":defer func(arg)".  "arg" points to the "(" and is advanced.
3395///
3396/// @return  FAIL or OK.
3397static int ex_defer_inner(char *name, char **arg, const partial_T *const partial,
3398                          evalarg_T *const evalarg)
3399{
3400  typval_T argvars[MAX_FUNC_ARGS + 1];  // vars for arguments
3401  int partial_argc = 0;  // number of partial arguments
3402  int argcount = 0;  // number of arguments found
3403
3404  if (current_funccal == NULL) {
3405    semsg(_(e_str_not_inside_function), "defer");
3406    return FAIL;
3407  }
3408  if (partial != NULL) {
3409    if (partial->pt_dict != NULL) {
3410      emsg(_(e_cannot_use_partial_with_dictionary_for_defer));
3411      return FAIL;
3412    }
3413    if (partial->pt_argc > 0) {
3414      partial_argc = partial->pt_argc;
3415      for (int i = 0; i < partial_argc; i++) {
3416        tv_copy(&partial->pt_argv[i], &argvars[i]);
3417      }
3418    }
3419  }
3420  int r = get_func_arguments(arg, evalarg, false, argvars + partial_argc, &argcount);
3421  argcount += partial_argc;
3422
3423  if (r == OK) {
3424    if (builtin_function(name, -1)) {
3425      const EvalFuncDef *const fdef = find_internal_func(name);
3426      if (fdef == NULL) {
3427        emsg_funcname(e_unknown_function_str, name);
3428        r = FAIL;
3429      } else if (check_internal_func(fdef, argcount) == -1) {
3430        r = FAIL;
3431      }
3432    } else {
3433      ufunc_T *ufunc = find_func(name);
3434      // we tolerate an unknown function here, it might be defined later
3435      if (ufunc != NULL) {
3436        int error = check_user_func_argcount(ufunc, argcount);
3437        if (error != FCERR_UNKNOWN) {
3438          user_func_error(error, name, false);
3439          r = FAIL;
3440        }
3441      }
3442    }
3443  }
3444
3445  if (r == FAIL) {
3446    while (--argcount >= 0) {
3447      tv_clear(&argvars[argcount]);
3448    }
3449    return FAIL;
3450  }
3451  add_defer(name, argcount, argvars);
3452  return OK;
3453}
3454
3455/// Return true if currently inside a function call.
3456/// Give an error message and return false when not.
3457bool can_add_defer(void)
3458{
3459  if (get_current_funccal() == NULL) {
3460    semsg(_(e_str_not_inside_function), "defer");
3461    return false;
3462  }
3463  return true;
3464}
3465
3466/// Add a deferred call for "name" with arguments "argvars[argcount]".
3467/// Consumes "argvars[]".
3468/// Caller must check that current_funccal is not NULL.
3469void add_defer(char *name, int argcount_arg, typval_T *argvars)
3470{
3471  char *saved_name = xstrdup(name);
3472  int argcount = argcount_arg;
3473
3474  if (current_funccal->fc_defer.ga_itemsize == 0) {
3475    ga_init(&current_funccal->fc_defer, sizeof(defer_T), 10);
3476  }
3477  defer_T *dr = GA_APPEND_VIA_PTR(defer_T, &current_funccal->fc_defer);
3478  dr->dr_name = saved_name;
3479  dr->dr_argcount = argcount;
3480  while (argcount > 0) {
3481    argcount--;
3482    dr->dr_argvars[argcount] = argvars[argcount];
3483  }
3484}
3485
3486/// Invoked after a function has finished: invoke ":defer" functions.
3487static void handle_defer_one(funccall_T *funccal)
3488{
3489  for (int idx = funccal->fc_defer.ga_len - 1; idx >= 0; idx--) {
3490    defer_T *dr = ((defer_T *)funccal->fc_defer.ga_data) + idx;
3491
3492    if (dr->dr_name == NULL) {
3493      // already being called, can happen if function does ":qa"
3494      continue;
3495    }
3496
3497    funcexe_T funcexe = { .fe_evaluate = true };
3498
3499    typval_T rettv;
3500    rettv.v_type = VAR_UNKNOWN;     // tv_clear() uses this
3501
3502    char *name = dr->dr_name;
3503    dr->dr_name = NULL;
3504
3505    // If the deferred function is called after an exception, then only the
3506    // first statement in the function will be executed (because of the
3507    // exception).  So save and restore the try/catch/throw exception
3508    // state.
3509    exception_state_T estate;
3510    exception_state_save(&estate);
3511    exception_state_clear();
3512
3513    call_func(name, -1, &rettv, dr->dr_argcount, dr->dr_argvars, &funcexe);
3514
3515    exception_state_restore(&estate);
3516
3517    tv_clear(&rettv);
3518    xfree(name);
3519    for (int i = dr->dr_argcount - 1; i >= 0; i--) {
3520      tv_clear(&dr->dr_argvars[i]);
3521    }
3522  }
3523  ga_clear(&funccal->fc_defer);
3524}
3525
3526/// When exiting: call all ":defer" functions.
3527void invoke_all_defer(void)
3528{
3529  for (funccall_T *fc = current_funccal; fc != NULL; fc = fc->fc_caller) {
3530    handle_defer_one(fc);
3531  }
3532
3533  for (funccal_entry_T *fce = funccal_stack; fce != NULL; fce = fce->next) {
3534    for (funccall_T *fc = fce->top_funccal; fc != NULL; fc = fc->fc_caller) {
3535      handle_defer_one(fc);
3536    }
3537  }
3538}
3539
3540/// ":1,25call func(arg1, arg2)" function call.
3541/// ":defer func(arg1, arg2)"    deferred function call.
3542void ex_call(exarg_T *eap)
3543{
3544  char *arg = eap->arg;
3545  bool failed = false;
3546  funcdict_T fudi;
3547  partial_T *partial = NULL;
3548  evalarg_T evalarg;
3549
3550  fill_evalarg_from_eap(&evalarg, eap, eap->skip);
3551  if (eap->skip) {
3552    typval_T rettv;
3553    // trans_function_name() doesn't work well when skipping, use eval0()
3554    // instead to skip to any following command, e.g. for:
3555    //   :if 0 | call dict.foo().bar() | endif.
3556    emsg_skip++;
3557    if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) {
3558      tv_clear(&rettv);
3559    }
3560    emsg_skip--;
3561    clear_evalarg(&evalarg, eap);
3562    return;
3563  }
3564
3565  char *tofree = trans_function_name(&arg, false, TFN_INT, &fudi, &partial);
3566  if (fudi.fd_newkey != NULL) {
3567    // Still need to give an error message for missing key.
3568    semsg(_(e_dictkey), fudi.fd_newkey);
3569    xfree(fudi.fd_newkey);
3570  }
3571  if (tofree == NULL) {
3572    return;
3573  }
3574
3575  // Increase refcount on dictionary, it could get deleted when evaluating
3576  // the arguments.
3577  if (fudi.fd_dict != NULL) {
3578    fudi.fd_dict->dv_refcount++;
3579  }
3580
3581  // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3582  // contents. For VAR_PARTIAL get its partial, unless we already have one
3583  // from trans_function_name().
3584  int len = (int)strlen(tofree);
3585  bool found_var = false;
3586  char *name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, false, &found_var);
3587
3588  // Skip white space to allow ":call func ()".  Not good, but required for
3589  // backward compatibility.
3590  char *startarg = skipwhite(arg);
3591
3592  if (*startarg != '(') {
3593    semsg(_(e_missingparen), eap->arg);
3594    goto end;
3595  }
3596
3597  if (eap->cmdidx == CMD_defer) {
3598    arg = startarg;
3599    failed = ex_defer_inner(name, &arg, partial, &evalarg) == FAIL;
3600  } else {
3601    funcexe_T funcexe = FUNCEXE_INIT;
3602    funcexe.fe_partial = partial;
3603    funcexe.fe_selfdict = fudi.fd_dict;
3604    funcexe.fe_firstline = eap->line1;
3605    funcexe.fe_lastline = eap->line2;
3606    funcexe.fe_found_var = found_var;
3607    funcexe.fe_evaluate = true;
3608    failed = ex_call_inner(eap, name, &arg, startarg, &funcexe, &evalarg);
3609  }
3610
3611  // When inside :try we need to check for following "| catch" or "| endtry".
3612  // Not when there was an error, but do check if an exception was thrown.
3613  if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) {
3614    // Check for trailing illegal characters and a following command.
3615    if (!ends_excmd(*arg)) {
3616      if (!failed && !aborting()) {
3617        emsg_severe = true;
3618        semsg(_(e_trailing_arg), arg);
3619      }
3620    } else {
3621      eap->nextcmd = check_nextcmd(arg);
3622    }
3623  }
3624  clear_evalarg(&evalarg, eap);
3625
3626end:
3627  tv_dict_unref(fudi.fd_dict);
3628  xfree(tofree);
3629}
3630
3631/// Return from a function.  Possibly makes the return pending.  Also called
3632/// for a pending return at the ":endtry" or after returning from an extra
3633/// do_cmdline().  "reanimate" is used in the latter case.
3634///
3635/// @param reanimate  used after returning from an extra do_cmdline().
3636/// @param is_cmd     set when called due to a ":return" command.
3637/// @param rettv      may point to a typval_T with the return rettv.
3638///
3639/// @return  true when the return can be carried out,
3640///          false when the return gets pending.
3641bool do_return(exarg_T *eap, bool reanimate, bool is_cmd, void *rettv)
3642{
3643  cstack_T *const cstack = eap->cstack;
3644
3645  if (reanimate) {
3646    // Undo the return.
3647    current_funccal->fc_returned = false;
3648  }
3649
3650  // Cleanup (and deactivate) conditionals, but stop when a try conditional
3651  // not in its finally clause (which then is to be executed next) is found.
3652  // In this case, make the ":return" pending for execution at the ":endtry".
3653  // Otherwise, return normally.
3654  int idx = cleanup_conditionals(eap->cstack, 0, true);
3655  if (idx >= 0) {
3656    cstack->cs_pending[idx] = CSTP_RETURN;
3657
3658    if (!is_cmd && !reanimate) {
3659      // A pending return again gets pending.  "rettv" points to an
3660      // allocated variable with the rettv of the original ":return"'s
3661      // argument if present or is NULL else.
3662      cstack->cs_rettv[idx] = rettv;
3663    } else {
3664      // When undoing a return in order to make it pending, get the stored
3665      // return rettv.
3666      if (reanimate) {
3667        assert(current_funccal->fc_rettv);
3668        rettv = current_funccal->fc_rettv;
3669      }
3670
3671      if (rettv != NULL) {
3672        // Store the value of the pending return.
3673        cstack->cs_rettv[idx] = xcalloc(1, sizeof(typval_T));
3674        *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3675      } else {
3676        cstack->cs_rettv[idx] = NULL;
3677      }
3678
3679      if (reanimate) {
3680        // The pending return value could be overwritten by a ":return"
3681        // without argument in a finally clause; reset the default
3682        // return value.
3683        current_funccal->fc_rettv->v_type = VAR_NUMBER;
3684        current_funccal->fc_rettv->vval.v_number = 0;
3685      }
3686    }
3687    report_make_pending(CSTP_RETURN, rettv);
3688  } else {
3689    current_funccal->fc_returned = true;
3690
3691    // If the return is carried out now, store the return value.  For
3692    // a return immediately after reanimation, the value is already
3693    // there.
3694    if (!reanimate && rettv != NULL) {
3695      tv_clear(current_funccal->fc_rettv);
3696      *current_funccal->fc_rettv = *(typval_T *)rettv;
3697      if (!is_cmd) {
3698        xfree(rettv);
3699      }
3700    }
3701  }
3702
3703  return idx < 0;
3704}
3705
3706/// Generate a return command for producing the value of "rettv".  The result
3707/// is an allocated string.  Used by report_pending() for verbose messages.
3708char *get_return_cmd(void *rettv)
3709{
3710  char *s = NULL;
3711  char *tofree = NULL;
3712  size_t slen = 0;
3713
3714  if (rettv != NULL) {
3715    tofree = s = encode_tv2echo((typval_T *)rettv, NULL);
3716  }
3717  if (s == NULL) {
3718    s = "";
3719  } else {
3720    slen = strlen(s);
3721  }
3722
3723  xstrlcpy(IObuff, ":return ", IOSIZE);
3724  xstrlcpy(IObuff + 8, s, IOSIZE - 8);
3725  size_t IObufflen = 8 + slen;
3726  if (IObufflen >= IOSIZE) {
3727    STRCPY(IObuff + IOSIZE - 4, "...");
3728    IObufflen = IOSIZE - 1;
3729  }
3730  xfree(tofree);
3731  return xstrnsave(IObuff, IObufflen);
3732}
3733
3734/// Get next function line.
3735/// Called by do_cmdline() to get the next line.
3736///
3737/// @return  allocated string, or NULL for end of function.
3738char *get_func_line(int c, void *cookie, int indent, bool do_concat)
3739{
3740  funccall_T *fcp = (funccall_T *)cookie;
3741  ufunc_T *fp = fcp->fc_func;
3742  char *retval;
3743
3744  // If breakpoints have been added/deleted need to check for it.
3745  if (fcp->fc_dbg_tick != debug_tick) {
3746    fcp->fc_breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM);
3747    fcp->fc_dbg_tick = debug_tick;
3748  }
3749  if (do_profiling == PROF_YES) {
3750    func_line_end(cookie);
3751  }
3752
3753  garray_T *gap = &fp->uf_lines;  // growarray with function lines
3754  if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3755      || fcp->fc_returned) {
3756    retval = NULL;
3757  } else {
3758    // Skip NULL lines (continuation lines).
3759    while (fcp->fc_linenr < gap->ga_len
3760           && ((char **)(gap->ga_data))[fcp->fc_linenr] == NULL) {
3761      fcp->fc_linenr++;
3762    }
3763    if (fcp->fc_linenr >= gap->ga_len) {
3764      retval = NULL;
3765    } else {
3766      retval = xstrdup(((char **)(gap->ga_data))[fcp->fc_linenr++]);
3767      SOURCING_LNUM = fcp->fc_linenr;
3768      if (do_profiling == PROF_YES) {
3769        func_line_start(cookie);
3770      }
3771    }
3772  }
3773
3774  // Did we encounter a breakpoint?
3775  if (fcp->fc_breakpoint != 0 && fcp->fc_breakpoint <= SOURCING_LNUM) {
3776    dbg_breakpoint(fp->uf_name, SOURCING_LNUM);
3777    // Find next breakpoint.
3778    fcp->fc_breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM);
3779    fcp->fc_dbg_tick = debug_tick;
3780  }
3781
3782  return retval;
3783}
3784
3785/// @return  true if the currently active function should be ended, because a
3786///          return was encountered or an error occurred.  Used inside a ":while".
3787int func_has_ended(void *cookie)
3788{
3789  funccall_T *fcp = (funccall_T *)cookie;
3790
3791  // Ignore the "abort" flag if the abortion behavior has been changed due to
3792  // an error inside a try conditional.
3793  return ((fcp->fc_func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3794         || fcp->fc_returned;
3795}
3796
3797/// @return  true if cookie indicates a function which "abort"s on errors.
3798int func_has_abort(void *cookie)
3799{
3800  return ((funccall_T *)cookie)->fc_func->uf_flags & FC_ABORT;
3801}
3802
3803/// Turn "dict.Func" into a partial for "Func" bound to "dict".
3804/// Changes "rettv" in-place.
3805void make_partial(dict_T *const selfdict, typval_T *const rettv)
3806{
3807  ufunc_T *fp = NULL;
3808  char fname_buf[FLEN_FIXED + 1];
3809  int error;
3810
3811  if (rettv->v_type == VAR_PARTIAL
3812      && rettv->vval.v_partial != NULL
3813      && rettv->vval.v_partial->pt_func != NULL) {
3814    fp = rettv->vval.v_partial->pt_func;
3815  } else {
3816    char *fname = rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING
3817                  ? rettv->vval.v_string
3818                  : rettv->vval.v_partial == NULL
3819                  ? NULL
3820                  : rettv->vval.v_partial->pt_name;
3821    if (fname == NULL) {
3822      // There is no point binding a dict to a NULL function, just create
3823      // a function reference.
3824      rettv->v_type = VAR_FUNC;
3825      rettv->vval.v_string = NULL;
3826    } else {
3827      char *tofree = NULL;
3828
3829      // Translate "s:func" to the stored function name.
3830      fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3831      fp = find_func(fname);
3832      xfree(tofree);
3833    }
3834  }
3835
3836  // Turn "dict.Func" into a partial for "Func" with "dict".
3837  if (fp != NULL && (fp->uf_flags & FC_DICT)) {
3838    partial_T *pt = (partial_T *)xcalloc(1, sizeof(partial_T));
3839    pt->pt_refcount = 1;
3840    pt->pt_dict = selfdict;
3841    (selfdict->dv_refcount)++;
3842    pt->pt_auto = true;
3843    if (rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING) {
3844      // Just a function: Take over the function name and use selfdict.
3845      pt->pt_name = rettv->vval.v_string;
3846    } else {
3847      partial_T *ret_pt = rettv->vval.v_partial;
3848
3849      // Partial: copy the function name, use selfdict and copy
3850      // args. Can't take over name or args, the partial might
3851      // be referenced elsewhere.
3852      if (ret_pt->pt_name != NULL) {
3853        pt->pt_name = xstrdup(ret_pt->pt_name);
3854        func_ref(pt->pt_name);
3855      } else {
3856        pt->pt_func = ret_pt->pt_func;
3857        func_ptr_ref(pt->pt_func);
3858      }
3859      if (ret_pt->pt_argc > 0) {
3860        size_t arg_size = sizeof(typval_T) * (size_t)ret_pt->pt_argc;
3861        pt->pt_argv = (typval_T *)xmalloc(arg_size);
3862        pt->pt_argc = ret_pt->pt_argc;
3863        for (int i = 0; i < pt->pt_argc; i++) {
3864          tv_copy(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3865        }
3866      }
3867      partial_unref(ret_pt);
3868    }
3869    rettv->v_type = VAR_PARTIAL;
3870    rettv->vval.v_partial = pt;
3871  }
3872}
3873
3874/// @return  the name of the executed function.
3875char *func_name(void *cookie)
3876{
3877  return ((funccall_T *)cookie)->fc_func->uf_name;
3878}
3879
3880/// @return  the address holding the next breakpoint line for a funccall cookie.
3881linenr_T *func_breakpoint(void *cookie)
3882{
3883  return &((funccall_T *)cookie)->fc_breakpoint;
3884}
3885
3886/// @return  the address holding the debug tick for a funccall cookie.
3887int *func_dbg_tick(void *cookie)
3888{
3889  return &((funccall_T *)cookie)->fc_dbg_tick;
3890}
3891
3892/// @return  the nesting level for a funccall cookie.
3893int func_level(void *cookie)
3894{
3895  return ((funccall_T *)cookie)->fc_level;
3896}
3897
3898/// @return  true when a function was ended by a ":return" command.
3899int current_func_returned(void)
3900{
3901  return current_funccal->fc_returned;
3902}
3903
3904bool free_unref_funccal(int copyID, int testing)
3905{
3906  bool did_free = false;
3907  bool did_free_funccal = false;
3908
3909  for (funccall_T **pfc = &previous_funccal; *pfc != NULL;) {
3910    if (can_free_funccal(*pfc, copyID)) {
3911      funccall_T *fc = *pfc;
3912      *pfc = fc->fc_caller;
3913      free_funccal_contents(fc);
3914      did_free = true;
3915      did_free_funccal = true;
3916    } else {
3917      pfc = &(*pfc)->fc_caller;
3918    }
3919  }
3920  if (did_free_funccal) {
3921    // When a funccal was freed some more items might be garbage
3922    // collected, so run again.
3923    garbage_collect(testing);
3924  }
3925  return did_free;
3926}
3927
3928// Get function call environment based on backtrace debug level
3929funccall_T *get_funccal(void)
3930{
3931  funccall_T *funccal = current_funccal;
3932  if (debug_backtrace_level > 0) {
3933    for (int i = 0; i < debug_backtrace_level; i++) {
3934      funccall_T *temp_funccal = funccal->fc_caller;
3935      if (temp_funccal) {
3936        funccal = temp_funccal;
3937      } else {
3938        // backtrace level overflow. reset to max
3939        debug_backtrace_level = i;
3940      }
3941    }
3942  }
3943
3944  return funccal;
3945}
3946
3947/// Get the function call environment to use for the l: and a: variables, based
3948/// on the backtrace debug level.
3949/// Returns NULL if there is no current funccal.
3950static funccall_T *get_funccal_for_vars(void)
3951{
3952  funccall_T *funccal = NULL;
3953
3954  if (current_funccal == NULL) {
3955    return NULL;
3956  }
3957  funccal = get_funccal();
3958  if (funccal == NULL || funccal->fc_l_vars.dv_refcount == 0) {
3959    return NULL;
3960  }
3961  return funccal;
3962}
3963
3964/// @return  dict used for local variables in the current funccal or
3965///          NULL if there is no current funccal.
3966dict_T *get_funccal_local_dict(void)
3967{
3968  funccall_T *funccal = get_funccal_for_vars();
3969  return funccal == NULL ? NULL : &funccal->fc_l_vars;
3970}
3971
3972/// @return  hashtable used for local variables in the current funccal or
3973///          NULL if there is no current funccal.
3974hashtab_T *get_funccal_local_ht(void)
3975{
3976  dict_T *d = get_funccal_local_dict();
3977  return d != NULL ? &d->dv_hashtab : NULL;
3978}
3979
3980/// @return   the l: scope variable or
3981///           NULL if there is no current funccal.
3982dictitem_T *get_funccal_local_var(void)
3983{
3984  funccall_T *funccal = get_funccal_for_vars();
3985  return funccal == NULL ? NULL : (dictitem_T *)&funccal->fc_l_vars_var;
3986}
3987
3988/// @return  the dict used for argument in the current funccal or
3989///          NULL if there is no current funccal.
3990dict_T *get_funccal_args_dict(void)
3991{
3992  funccall_T *funccal = get_funccal_for_vars();
3993  return funccal == NULL ? NULL : &funccal->fc_l_avars;
3994}
3995
3996/// @return  the hashtable used for argument in the current funccal or
3997///          NULL if there is no current funccal.
3998hashtab_T *get_funccal_args_ht(void)
3999{
4000  dict_T *d = get_funccal_args_dict();
4001  return d != NULL ? &d->dv_hashtab : NULL;
4002}
4003
4004/// @return  the a: scope variable or
4005///          NULL if there is no current funccal.
4006dictitem_T *get_funccal_args_var(void)
4007{
4008  funccall_T *funccal = get_funccal_for_vars();
4009  return funccal == NULL ? NULL : (dictitem_T *)&funccal->fc_l_avars_var;
4010}
4011
4012/// List function variables, if there is a function.
4013void list_func_vars(int *first)
4014{
4015  if (current_funccal != NULL && current_funccal->fc_l_vars.dv_refcount > 0) {
4016    list_hashtable_vars(&current_funccal->fc_l_vars.dv_hashtab, "l:", false,
4017                        first);
4018  }
4019}
4020
4021/// @return  if "ht" is the hashtable for local variables in the current
4022///          funccal, return the dict that contains it. Otherwise return NULL.
4023dict_T *get_current_funccal_dict(hashtab_T *ht)
4024{
4025  if (current_funccal != NULL && ht == &current_funccal->fc_l_vars.dv_hashtab) {
4026    return &current_funccal->fc_l_vars;
4027  }
4028  return NULL;
4029}
4030
4031/// Search hashitem in parent scope.
4032hashitem_T *find_hi_in_scoped_ht(const char *name, hashtab_T **pht)
4033{
4034  if (current_funccal == NULL || current_funccal->fc_func->uf_scoped == NULL) {
4035    return NULL;
4036  }
4037
4038  funccall_T *old_current_funccal = current_funccal;
4039  hashitem_T *hi = NULL;
4040  const size_t namelen = strlen(name);
4041  const char *varname;
4042
4043  // Search in parent scope which is possible to reference from lambda
4044  current_funccal = current_funccal->fc_func->uf_scoped;
4045  while (current_funccal != NULL) {
4046    hashtab_T *ht = find_var_ht(name, namelen, &varname);
4047    if (ht != NULL && *varname != NUL) {
4048      hi = hash_find_len(ht, varname, namelen - (size_t)(varname - name));
4049      if (!HASHITEM_EMPTY(hi)) {
4050        *pht = ht;
4051        break;
4052      }
4053    }
4054    if (current_funccal == current_funccal->fc_func->uf_scoped) {
4055      break;
4056    }
4057    current_funccal = current_funccal->fc_func->uf_scoped;
4058  }
4059  current_funccal = old_current_funccal;
4060
4061  return hi;
4062}
4063
4064/// Search variable in parent scope.
4065dictitem_T *find_var_in_scoped_ht(const char *name, const size_t namelen, int no_autoload)
4066{
4067  if (current_funccal == NULL || current_funccal->fc_func->uf_scoped == NULL) {
4068    return NULL;
4069  }
4070
4071  dictitem_T *v = NULL;
4072  funccall_T *old_current_funccal = current_funccal;
4073  const char *varname;
4074
4075  // Search in parent scope which is possible to reference from lambda
4076  current_funccal = current_funccal->fc_func->uf_scoped;
4077  while (current_funccal) {
4078    hashtab_T *ht = find_var_ht(name, namelen, &varname);
4079    if (ht != NULL && *varname != NUL) {
4080      v = find_var_in_ht(ht, *name, varname,
4081                         namelen - (size_t)(varname - name), no_autoload);
4082      if (v != NULL) {
4083        break;
4084      }
4085    }
4086    if (current_funccal == current_funccal->fc_func->uf_scoped) {
4087      break;
4088    }
4089    current_funccal = current_funccal->fc_func->uf_scoped;
4090  }
4091  current_funccal = old_current_funccal;
4092
4093  return v;
4094}
4095
4096/// Set "copyID + 1" in previous_funccal and callers.
4097bool set_ref_in_previous_funccal(int copyID)
4098{
4099  for (funccall_T *fc = previous_funccal; fc != NULL;
4100       fc = fc->fc_caller) {
4101    fc->fc_copyID = copyID + 1;
4102    if (set_ref_in_ht(&fc->fc_l_vars.dv_hashtab, copyID + 1, NULL)
4103        || set_ref_in_ht(&fc->fc_l_avars.dv_hashtab, copyID + 1, NULL)
4104        || set_ref_in_list_items(&fc->fc_l_varlist, copyID + 1, NULL)) {
4105      return true;
4106    }
4107  }
4108  return false;
4109}
4110
4111static bool set_ref_in_funccal(funccall_T *fc, int copyID)
4112{
4113  if (fc->fc_copyID != copyID) {
4114    fc->fc_copyID = copyID;
4115    if (set_ref_in_ht(&fc->fc_l_vars.dv_hashtab, copyID, NULL)
4116        || set_ref_in_ht(&fc->fc_l_avars.dv_hashtab, copyID, NULL)
4117        || set_ref_in_list_items(&fc->fc_l_varlist, copyID, NULL)
4118        || set_ref_in_func(NULL, fc->fc_func, copyID)) {
4119      return true;
4120    }
4121  }
4122  return false;
4123}
4124
4125/// Set "copyID" in all local vars and arguments in the call stack.
4126bool set_ref_in_call_stack(int copyID)
4127{
4128  for (funccall_T *fc = current_funccal; fc != NULL;
4129       fc = fc->fc_caller) {
4130    if (set_ref_in_funccal(fc, copyID)) {
4131      return true;
4132    }
4133  }
4134
4135  // Also go through the funccal_stack.
4136  for (funccal_entry_T *entry = funccal_stack; entry != NULL;
4137       entry = entry->next) {
4138    for (funccall_T *fc = entry->top_funccal; fc != NULL;
4139         fc = fc->fc_caller) {
4140      if (set_ref_in_funccal(fc, copyID)) {
4141        return true;
4142      }
4143    }
4144  }
4145
4146  return false;
4147}
4148
4149/// Set "copyID" in all functions available by name.
4150bool set_ref_in_functions(int copyID)
4151{
4152  int todo = (int)func_hashtab.ht_used;
4153  for (hashitem_T *hi = func_hashtab.ht_array; todo > 0 && !got_int; hi++) {
4154    if (!HASHITEM_EMPTY(hi)) {
4155      todo--;
4156      ufunc_T *fp = HI2UF(hi);
4157      if (!func_name_refcount(fp->uf_name)
4158          && set_ref_in_func(NULL, fp, copyID)) {
4159        return true;
4160      }
4161    }
4162  }
4163  return false;
4164}
4165
4166/// Set "copyID" in all function arguments.
4167bool set_ref_in_func_args(int copyID)
4168{
4169  for (int i = 0; i < funcargs.ga_len; i++) {
4170    if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
4171                        copyID, NULL, NULL)) {
4172      return true;
4173    }
4174  }
4175  return false;
4176}
4177
4178/// Mark all lists and dicts referenced through function "name" with "copyID".
4179/// "list_stack" is used to add lists to be marked.  Can be NULL.
4180/// "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
4181///
4182/// @return  true if setting references failed somehow.
4183bool set_ref_in_func(char *name, ufunc_T *fp_in, int copyID)
4184{
4185  ufunc_T *fp = fp_in;
4186  int error = FCERR_NONE;
4187  char fname_buf[FLEN_FIXED + 1];
4188  char *tofree = NULL;
4189  bool abort = false;
4190  if (name == NULL && fp_in == NULL) {
4191    return false;
4192  }
4193
4194  if (fp_in == NULL) {
4195    char *fname = fname_trans_sid(name, fname_buf, &tofree, &error);
4196    fp = find_func(fname);
4197  }
4198  if (fp != NULL) {
4199    for (funccall_T *fc = fp->uf_scoped; fc != NULL; fc = fc->fc_func->uf_scoped) {
4200      abort = abort || set_ref_in_funccal(fc, copyID);
4201    }
4202  }
4203  xfree(tofree);
4204  return abort;
4205}
4206
4207/// Registers a luaref as a lambda.
4208char *register_luafunc(LuaRef ref)
4209{
4210  String name = get_lambda_name();
4211  ufunc_T *fp = alloc_ufunc(name.data, name.size);
4212
4213  fp->uf_refcount = 1;
4214  fp->uf_varargs = true;
4215  fp->uf_flags = FC_LUAREF;
4216  fp->uf_calls = 0;
4217  fp->uf_script_ctx = current_sctx;
4218  fp->uf_luaref = ref;
4219
4220  hash_add(&func_hashtab, UF2HIKEY(fp));
4221
4222  // coverity[leaked_storage]
4223  return fp->uf_name;
4224}