neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

userfunc.c (124056B)


      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/getchar.h"
     34 #include "nvim/getchar_defs.h"
     35 #include "nvim/gettext_defs.h"
     36 #include "nvim/globals.h"
     37 #include "nvim/hashtab.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"
     62 typedef 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 
     68 static hashtab_T func_hashtab;
     69 
     70 // Used by get_func_tv()
     71 static garray_T funcargs = GA_EMPTY_INIT_VALUE;
     72 
     73 // pointer to funccal for currently active function
     74 static 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.
     78 static funccall_T *previous_funccal = NULL;
     79 
     80 static const char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
     81 static const char *e_funcdict = N_("E717: Dictionary entry already exists");
     82 static const char *e_funcref = N_("E718: Funcref required");
     83 static const char *e_nofunc = N_("E130: Unknown function: %s");
     84 static const char e_function_list_was_modified[]
     85  = N_("E454: Function list was modified");
     86 static const char e_function_nesting_too_deep[]
     87  = N_("E1058: Function nesting too deep");
     88 static const char e_no_white_space_allowed_before_str_str[]
     89  = N_("E1068: No white space allowed before '%s': %s");
     90 static const char e_missing_heredoc_end_marker_str[]
     91  = N_("E1145: Missing heredoc end marker: %s");
     92 static const char e_cannot_use_partial_with_dictionary_for_defer[]
     93  = N_("E1300: Cannot use a partial with dictionary for :defer");
     94 
     95 void func_init(void)
     96 {
     97  hash_init(&func_hashtab);
     98 }
     99 
    100 /// Return the function hash table
    101 hashtab_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".
    109 static 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.
    149 static 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 
    241 err_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.
    252 static 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 
    266 static char lambda_name[8 + NUMBUFLEN];
    267 
    268 /// @return  a name for a lambda.  Returned in static memory.
    269 static 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".
    280 static 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}.
    299 int 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 
    416 errret:
    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.
    445 char *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
    492 void 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.
    510 static 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.
    551 int 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.
    610 static 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.
    633 static 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 
    671 int 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.
    712 ufunc_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.
    722 static 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.
    731 static 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".
    749 static 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"
    760 static 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).
    782 static 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.
    800 static 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.
    869 static 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.
    896 static 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 
    907 static 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.
    927 static 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.
    943 static 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.
    958 static 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().
    966 funccall_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.
    978 void 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.
    994 void 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  save_redo_T 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    saveRedobuff(&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    restoreRedobuff(&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.
   1383 static 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.
   1391 static 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.
   1405 static 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 typval_exec_lua_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 
   1431 static 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".
   1435 void 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 
   1443 void 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 
   1453 funccall_T *get_current_funccal(void)
   1454 {
   1455  return current_funccal;
   1456 }
   1457 
   1458 void set_current_funccal(funccall_T *fc)
   1459 {
   1460  current_funccal = fc;
   1461 }
   1462 
   1463 #if defined(EXITFREE)
   1464 void 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 ':'.
   1541 static 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 
   1554 int 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 
   1578 func_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!
   1593 varnumber_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.
   1607 static 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
   1641 static 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()).
   1667 int 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_typval_call(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 
   1804 theend:
   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 
   1822 int 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_typval_call(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
   1842 int 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 
   1886 char *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.
   1893 static 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!").
   1907 static 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.
   1981 char *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 
   2174 theend:
   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.
   2184 char *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.
   2215 char *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".
   2238 static 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.
   2266 static 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.
   2294 static 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.
   2363 static 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 
   2629 theend:
   2630  xfree(skip_until);
   2631  xfree(heredoc_trimmed);
   2632  need_wait_return |= saved_wait_return;
   2633  return ret;
   2634 }
   2635 
   2636 /// ":function"
   2637 void 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      if ((uint8_t)(*arg) == K_SPECIAL) {
   2741        name_base = vim_strchr(arg, '_');
   2742        if (name_base == NULL) {
   2743          name_base = arg + 3;
   2744        } else {
   2745          name_base++;
   2746        }
   2747      }
   2748      int i;
   2749      for (i = 0; name_base[i] != NUL && (i == 0
   2750                                          ? eval_isnamec1(name_base[i])
   2751                                          : eval_isnamec(name_base[i])); i++) {}
   2752      if (name_base[i] != NUL) {
   2753        emsg_funcname(e_invarg2, arg);
   2754        goto ret_free;
   2755      }
   2756    }
   2757    // Disallow using the g: dict.
   2758    if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) {
   2759      emsg(_("E862: Cannot use g: here"));
   2760      goto ret_free;
   2761    }
   2762  }
   2763 
   2764  if (get_function_args(&p, ')', &newargs, &varargs,
   2765                        &default_args, eap->skip) == FAIL) {
   2766    goto errret_2;
   2767  }
   2768 
   2769  if (KeyTyped && ui_has(kUICmdline)) {
   2770    show_block = true;
   2771    ui_ext_cmdline_block_append(0, eap->cmd);
   2772  }
   2773 
   2774  // find extra arguments "range", "dict", "abort" and "closure"
   2775  while (true) {
   2776    p = skipwhite(p);
   2777    if (strncmp(p, "range", 5) == 0) {
   2778      flags |= FC_RANGE;
   2779      p += 5;
   2780    } else if (strncmp(p, "dict", 4) == 0) {
   2781      flags |= FC_DICT;
   2782      p += 4;
   2783    } else if (strncmp(p, "abort", 5) == 0) {
   2784      flags |= FC_ABORT;
   2785      p += 5;
   2786    } else if (strncmp(p, "closure", 7) == 0) {
   2787      flags |= FC_CLOSURE;
   2788      p += 7;
   2789      if (current_funccal == NULL) {
   2790        emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
   2791                      name == NULL ? "" : name);
   2792        goto erret;
   2793      }
   2794    } else {
   2795      break;
   2796    }
   2797  }
   2798 
   2799  // When there is a line break use what follows for the function body.
   2800  // Makes 'exe "func Test()\n...\nendfunc"' work.
   2801  if (*p == '\n') {
   2802    line_arg = p + 1;
   2803  } else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) {
   2804    semsg(_(e_trailing_arg), p);
   2805  }
   2806 
   2807  // Read the body of the function, until ":endfunction" is found.
   2808  if (KeyTyped) {
   2809    // Check if the function already exists, don't let the user type the
   2810    // whole function before telling them it doesn't work!  For a script we
   2811    // need to skip the body to be able to find what follows.
   2812    if (!eap->skip && !eap->forceit) {
   2813      if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) {
   2814        emsg(_(e_funcdict));
   2815      } else if (name != NULL && find_func(name) != NULL) {
   2816        emsg_funcname(e_funcexts, name);
   2817      }
   2818    }
   2819 
   2820    if (!eap->skip && did_emsg) {
   2821      goto erret;
   2822    }
   2823 
   2824    if (!ui_has(kUICmdline)) {
   2825      msg_putchar('\n');              // don't overwrite the function name
   2826    }
   2827    cmdline_row = msg_row;
   2828  }
   2829 
   2830  // Save the starting line number.
   2831  linenr_T sourcing_lnum_top = SOURCING_LNUM;
   2832 
   2833  // Do not define the function when getting the body fails and when skipping.
   2834  if (get_function_body(eap, &newlines, line_arg, &line_to_free, show_block) == FAIL
   2835      || eap->skip) {
   2836    goto erret;
   2837  }
   2838 
   2839  // If there are no errors, add the function
   2840  size_t namelen = 0;
   2841  if (fudi.fd_dict == NULL) {
   2842    dictitem_T *v = find_var(name, strlen(name), &ht, false);
   2843    if (v != NULL && v->di_tv.v_type == VAR_FUNC) {
   2844      emsg_funcname(N_("E707: Function name conflicts with variable: %s"), name);
   2845      goto erret;
   2846    }
   2847 
   2848    fp = find_func(name);
   2849    if (fp != NULL) {
   2850      // Function can be replaced with "function!" and when sourcing the
   2851      // same script again, but only once.
   2852      if (!eap->forceit
   2853          && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid
   2854              || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq)) {
   2855        emsg_funcname(e_funcexts, name);
   2856        goto errret_keep;
   2857      }
   2858      if (fp->uf_calls > 0) {
   2859        emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), name);
   2860        goto errret_keep;
   2861      }
   2862      if (fp->uf_refcount > 1) {
   2863        // This function is referenced somewhere, don't redefine it but
   2864        // create a new one.
   2865        (fp->uf_refcount)--;
   2866        fp->uf_flags |= FC_REMOVED;
   2867        fp = NULL;
   2868        overwrite = true;
   2869      } else {
   2870        char *exp_name = fp->uf_name_exp;
   2871        // redefine existing function, keep the expanded name
   2872        XFREE_CLEAR(name);
   2873        fp->uf_name_exp = NULL;
   2874        func_clear_items(fp);
   2875        fp->uf_name_exp = exp_name;
   2876        fp->uf_profiling = false;
   2877        fp->uf_prof_initialized = false;
   2878      }
   2879    }
   2880  } else {
   2881    char numbuf[NUMBUFLEN];
   2882 
   2883    fp = NULL;
   2884    if (fudi.fd_newkey == NULL && !eap->forceit) {
   2885      emsg(_(e_funcdict));
   2886      goto erret;
   2887    }
   2888    if (fudi.fd_di == NULL) {
   2889      if (value_check_lock(fudi.fd_dict->dv_lock, eap->arg, TV_CSTRING)) {
   2890        // Can't add a function to a locked dictionary
   2891        goto erret;
   2892      }
   2893    } else if (value_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, TV_CSTRING)) {
   2894      // Can't change an existing function if it is locked
   2895      goto erret;
   2896    }
   2897 
   2898    // Give the function a sequential number.  Can only be used with a
   2899    // Funcref!
   2900    xfree(name);
   2901    namelen = (size_t)snprintf(numbuf, sizeof(numbuf), "%d", ++func_nr);
   2902    name = xmemdupz(numbuf, namelen);
   2903  }
   2904 
   2905  if (fp == NULL) {
   2906    if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) {
   2907      // Check that the autoload name matches the script name.
   2908      int j = FAIL;
   2909      if (SOURCING_NAME != NULL) {
   2910        char *scriptname = autoload_name(name, strlen(name));
   2911        p = vim_strchr(scriptname, '/');
   2912        int plen = (int)strlen(p);
   2913        int slen = (int)strlen(SOURCING_NAME);
   2914        if (slen > plen && path_fnamecmp(p, SOURCING_NAME + slen - plen) == 0) {
   2915          j = OK;
   2916        }
   2917        xfree(scriptname);
   2918      }
   2919      if (j == FAIL) {
   2920        semsg(_("E746: Function name does not match script file name: %s"),
   2921              name);
   2922        goto erret;
   2923      }
   2924    }
   2925 
   2926    if (namelen == 0) {
   2927      namelen = strlen(name);
   2928    }
   2929    fp = alloc_ufunc(name, namelen);
   2930 
   2931    if (fudi.fd_dict != NULL) {
   2932      if (fudi.fd_di == NULL) {
   2933        // Add new dict entry
   2934        fudi.fd_di = tv_dict_item_alloc(fudi.fd_newkey);
   2935        if (tv_dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) {
   2936          xfree(fudi.fd_di);
   2937          XFREE_CLEAR(fp);
   2938          goto erret;
   2939        }
   2940      } else {
   2941        // Overwrite existing dict entry.
   2942        tv_clear(&fudi.fd_di->di_tv);
   2943      }
   2944      fudi.fd_di->di_tv.v_type = VAR_FUNC;
   2945      fudi.fd_di->di_tv.vval.v_string = xmemdupz(name, namelen);
   2946 
   2947      // behave like "dict" was used
   2948      flags |= FC_DICT;
   2949    }
   2950 
   2951    // insert the new function in the function list
   2952    if (overwrite) {
   2953      hashitem_T *hi = hash_find(&func_hashtab, name);
   2954      hi->hi_key = UF2HIKEY(fp);
   2955    } else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) {
   2956      free_fp = true;
   2957      goto erret;
   2958    }
   2959    fp->uf_refcount = 1;
   2960  }
   2961  fp->uf_args = newargs;
   2962  fp->uf_def_args = default_args;
   2963  fp->uf_lines = newlines;
   2964  if ((flags & FC_CLOSURE) != 0) {
   2965    register_closure(fp);
   2966  } else {
   2967    fp->uf_scoped = NULL;
   2968  }
   2969  if (prof_def_func()) {
   2970    func_do_profile(fp);
   2971  }
   2972  fp->uf_varargs = varargs;
   2973  if (sandbox) {
   2974    flags |= FC_SANDBOX;
   2975  }
   2976  fp->uf_flags = flags;
   2977  fp->uf_calls = 0;
   2978  fp->uf_script_ctx = current_sctx;
   2979  fp->uf_script_ctx.sc_lnum += sourcing_lnum_top;
   2980  nlua_set_sctx(&fp->uf_script_ctx);
   2981 
   2982  goto ret_free;
   2983 
   2984 erret:
   2985  if (fp != NULL) {
   2986    // these were set to "newargs" and "default_args", which are cleared below
   2987    ga_init(&fp->uf_args, (int)sizeof(char *), 1);
   2988    ga_init(&fp->uf_def_args, (int)sizeof(char *), 1);
   2989  }
   2990 errret_2:
   2991  if (fp != NULL) {
   2992    XFREE_CLEAR(fp->uf_name_exp);
   2993  }
   2994  if (free_fp) {
   2995    XFREE_CLEAR(fp);
   2996  }
   2997 errret_keep:
   2998  ga_clear_strings(&newargs);
   2999  ga_clear_strings(&default_args);
   3000  ga_clear_strings(&newlines);
   3001 ret_free:
   3002  xfree(line_to_free);
   3003  xfree(fudi.fd_newkey);
   3004  xfree(name);
   3005  did_emsg |= saved_did_emsg;
   3006  if (show_block) {
   3007    ui_ext_cmdline_block_leave();
   3008  }
   3009 }
   3010 
   3011 /// @return  5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
   3012 ///          2 if "p" starts with "s:".
   3013 ///          0 otherwise.
   3014 int eval_fname_script(const char *const p)
   3015 {
   3016  // Use mb_strnicmp() because in Turkish comparing the "I" may not work with
   3017  // the standard library function.
   3018  if (p[0] == '<'
   3019      && (mb_strnicmp(p + 1, "SID>", 4) == 0
   3020          || mb_strnicmp(p + 1, "SNR>", 4) == 0)) {
   3021    return 5;
   3022  }
   3023  if (p[0] == 's' && p[1] == ':') {
   3024    return 2;
   3025  }
   3026  return 0;
   3027 }
   3028 
   3029 bool translated_function_exists(const char *name)
   3030 {
   3031  if (builtin_function(name, -1)) {
   3032    return find_internal_func(name) != NULL;
   3033  }
   3034  return find_func(name) != NULL;
   3035 }
   3036 
   3037 /// Check whether function with the given name exists
   3038 ///
   3039 /// @param[in] name  Function name.
   3040 /// @param[in] no_deref  Whether to dereference a Funcref.
   3041 ///
   3042 /// @return  true if it exists, false otherwise.
   3043 bool function_exists(const char *const name, bool no_deref)
   3044 {
   3045  const char *nm = name;
   3046  bool n = false;
   3047  int flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
   3048 
   3049  if (no_deref) {
   3050    flag |= TFN_NO_DEREF;
   3051  }
   3052  char *const p = trans_function_name((char **)&nm, false, flag, NULL, NULL);
   3053  nm = skipwhite(nm);
   3054 
   3055  // Only accept "funcname", "funcname ", "funcname (..." and
   3056  // "funcname(...", not "funcname!...".
   3057  if (p != NULL && (*nm == NUL || *nm == '(')) {
   3058    n = translated_function_exists(p);
   3059  }
   3060  xfree(p);
   3061  return n;
   3062 }
   3063 
   3064 /// Function given to ExpandGeneric() to obtain the list of user defined
   3065 /// function names.
   3066 char *get_user_func_name(expand_T *xp, int idx)
   3067 {
   3068  static size_t done;
   3069  static int changed;
   3070  static hashitem_T *hi;
   3071 
   3072  if (idx == 0) {
   3073    done = 0;
   3074    hi = func_hashtab.ht_array;
   3075    changed = func_hashtab.ht_changed;
   3076  }
   3077  assert(hi);
   3078  if (changed == func_hashtab.ht_changed && done < func_hashtab.ht_used) {
   3079    if (done++ > 0) {
   3080      hi++;
   3081    }
   3082    while (HASHITEM_EMPTY(hi)) {
   3083      hi++;
   3084    }
   3085    ufunc_T *fp = HI2UF(hi);
   3086 
   3087    if ((fp->uf_flags & FC_DICT)
   3088        || strncmp(fp->uf_name, "<lambda>", 8) == 0) {
   3089      return "";       // don't show dict and lambda functions
   3090    }
   3091 
   3092    if (fp->uf_namelen + 4 >= IOSIZE) {
   3093      return fp->uf_name;  // Prevent overflow.
   3094    }
   3095 
   3096    int len = cat_func_name(IObuff, IOSIZE, fp);
   3097    if (xp->xp_context != EXPAND_USER_FUNC) {
   3098      xstrlcpy(IObuff + len, "(", IOSIZE - (size_t)len);
   3099      if (!fp->uf_varargs && GA_EMPTY(&fp->uf_args)) {
   3100        len++;
   3101        xstrlcpy(IObuff + len, ")", IOSIZE - (size_t)len);
   3102      }
   3103    }
   3104    return IObuff;
   3105  }
   3106  return NULL;
   3107 }
   3108 
   3109 /// ":delfunction {name}"
   3110 void ex_delfunction(exarg_T *eap)
   3111 {
   3112  ufunc_T *fp = NULL;
   3113  funcdict_T fudi;
   3114 
   3115  char *p = eap->arg;
   3116  char *name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
   3117  xfree(fudi.fd_newkey);
   3118  if (name == NULL) {
   3119    if (fudi.fd_dict != NULL && !eap->skip) {
   3120      emsg(_(e_funcref));
   3121    }
   3122    return;
   3123  }
   3124  if (!ends_excmd(*skipwhite(p))) {
   3125    xfree(name);
   3126    semsg(_(e_trailing_arg), p);
   3127    return;
   3128  }
   3129  eap->nextcmd = check_nextcmd(p);
   3130  if (eap->nextcmd != NULL) {
   3131    *p = NUL;
   3132  }
   3133 
   3134  if (isdigit((uint8_t)(*name)) && fudi.fd_dict == NULL) {
   3135    if (!eap->skip) {
   3136      semsg(_(e_invarg2), eap->arg);
   3137    }
   3138    xfree(name);
   3139    return;
   3140  }
   3141  if (!eap->skip) {
   3142    fp = find_func(name);
   3143  }
   3144  xfree(name);
   3145 
   3146  if (!eap->skip) {
   3147    if (fp == NULL) {
   3148      if (!eap->forceit) {
   3149        semsg(_(e_nofunc), eap->arg);
   3150      }
   3151      return;
   3152    }
   3153    if (fp->uf_calls > 0) {
   3154      semsg(_("E131: Cannot delete function %s: It is in use"), eap->arg);
   3155      return;
   3156    }
   3157    // check `uf_refcount > 2` because deleting a function should also reduce
   3158    // the reference count, and 1 is the initial refcount.
   3159    if (fp->uf_refcount > 2) {
   3160      semsg(_("Cannot delete function %s: It is being used internally"),
   3161            eap->arg);
   3162      return;
   3163    }
   3164 
   3165    if (fudi.fd_dict != NULL) {
   3166      // Delete the dict item that refers to the function, it will
   3167      // invoke func_unref() and possibly delete the function.
   3168      tv_dict_item_remove(fudi.fd_dict, fudi.fd_di);
   3169    } else {
   3170      // A normal function (not a numbered function or lambda) has a
   3171      // refcount of 1 for the entry in the hashtable.  When deleting
   3172      // it and the refcount is more than one, it should be kept.
   3173      // A numbered function or lambda should be kept if the refcount is
   3174      // one or more.
   3175      if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) {
   3176        // Function is still referenced somewhere. Don't free it but
   3177        // do remove it from the hashtable.
   3178        if (func_remove(fp)) {
   3179          fp->uf_refcount--;
   3180        }
   3181        fp->uf_flags |= FC_DELETED;
   3182      } else {
   3183        func_clear_free(fp, false);
   3184      }
   3185    }
   3186  }
   3187 }
   3188 
   3189 /// Unreference a Function: decrement the reference count and free it when it
   3190 /// becomes zero.
   3191 void func_unref(char *name)
   3192 {
   3193  if (name == NULL || !func_name_refcount(name)) {
   3194    return;
   3195  }
   3196 
   3197  ufunc_T *fp = find_func(name);
   3198  if (fp == NULL && isdigit((uint8_t)(*name))) {
   3199 #ifdef EXITFREE
   3200    if (!entered_free_all_mem) {
   3201      internal_error("func_unref()");
   3202      abort();
   3203    }
   3204 #else
   3205    internal_error("func_unref()");
   3206    abort();
   3207 #endif
   3208  }
   3209  func_ptr_unref(fp);
   3210 }
   3211 
   3212 /// Unreference a Function: decrement the reference count and free it when it
   3213 /// becomes zero.
   3214 /// Unreference user function, freeing it if needed
   3215 ///
   3216 /// Decrements the reference count and frees when it becomes zero.
   3217 ///
   3218 /// @param  fp  Function to unreference.
   3219 void func_ptr_unref(ufunc_T *fp)
   3220 {
   3221  if (fp != NULL && --fp->uf_refcount <= 0) {
   3222    // Only delete it when it's not being used. Otherwise it's done
   3223    // when "uf_calls" becomes zero.
   3224    if (fp->uf_calls == 0) {
   3225      func_clear_free(fp, false);
   3226    }
   3227  }
   3228 }
   3229 
   3230 /// Count a reference to a Function.
   3231 void func_ref(char *name)
   3232 {
   3233  if (name == NULL || !func_name_refcount(name)) {
   3234    return;
   3235  }
   3236  ufunc_T *fp = find_func(name);
   3237  if (fp != NULL) {
   3238    (fp->uf_refcount)++;
   3239  } else if (isdigit((uint8_t)(*name))) {
   3240    // Only give an error for a numbered function.
   3241    // Fail silently, when named or lambda function isn't found.
   3242    internal_error("func_ref()");
   3243  }
   3244 }
   3245 
   3246 /// Count a reference to a Function.
   3247 void func_ptr_ref(ufunc_T *fp)
   3248 {
   3249  if (fp != NULL) {
   3250    (fp->uf_refcount)++;
   3251  }
   3252 }
   3253 
   3254 /// Check whether funccall is still referenced outside
   3255 ///
   3256 /// It is supposed to be referenced if either it is referenced itself or if l:,
   3257 /// a: or a:000 are referenced as all these are statically allocated within
   3258 /// funccall structure.
   3259 static inline bool fc_referenced(const funccall_T *const fc)
   3260  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
   3261  FUNC_ATTR_NONNULL_ALL
   3262 {
   3263  return ((fc->fc_l_varlist.lv_refcount  // NOLINT(runtime/deprecated)
   3264           != DO_NOT_FREE_CNT)
   3265          || fc->fc_l_vars.dv_refcount != DO_NOT_FREE_CNT
   3266          || fc->fc_l_avars.dv_refcount != DO_NOT_FREE_CNT
   3267          || fc->fc_refcount > 0);
   3268 }
   3269 
   3270 /// @return true if items in "fc" do not have "copyID".  That means they are not
   3271 /// referenced from anywhere that is in use.
   3272 static bool can_free_funccal(funccall_T *fc, int copyID)
   3273 {
   3274  return fc->fc_l_varlist.lv_copyID != copyID
   3275         && fc->fc_l_vars.dv_copyID != copyID
   3276         && fc->fc_l_avars.dv_copyID != copyID
   3277         && fc->fc_copyID != copyID;
   3278 }
   3279 
   3280 /// ":return [expr]"
   3281 void ex_return(exarg_T *eap)
   3282 {
   3283  char *arg = eap->arg;
   3284  typval_T rettv;
   3285  bool returning = false;
   3286 
   3287  if (current_funccal == NULL) {
   3288    emsg(_("E133: :return not inside a function"));
   3289    return;
   3290  }
   3291 
   3292  evalarg_T evalarg = { .eval_flags = eap->skip ? 0 : EVAL_EVALUATE };
   3293 
   3294  if (eap->skip) {
   3295    emsg_skip++;
   3296  }
   3297 
   3298  eap->nextcmd = NULL;
   3299  if ((*arg != NUL && *arg != '|' && *arg != '\n')
   3300      && eval0(arg, &rettv, eap, &evalarg) != FAIL) {
   3301    if (!eap->skip) {
   3302      returning = do_return(eap, false, true, &rettv);
   3303    } else {
   3304      tv_clear(&rettv);
   3305    }
   3306  } else if (!eap->skip) {  // It's safer to return also on error.
   3307    // In return statement, cause_abort should be force_abort.
   3308    update_force_abort();
   3309 
   3310    // Return unless the expression evaluation has been cancelled due to an
   3311    // aborting error, an interrupt, or an exception.
   3312    if (!aborting()) {
   3313      returning = do_return(eap, false, true, NULL);
   3314    }
   3315  }
   3316 
   3317  // When skipping or the return gets pending, advance to the next command
   3318  // in this line (!returning).  Otherwise, ignore the rest of the line.
   3319  // Following lines will be ignored by get_func_line().
   3320  if (returning) {
   3321    eap->nextcmd = NULL;
   3322  } else if (eap->nextcmd == NULL) {          // no argument
   3323    eap->nextcmd = check_nextcmd(arg);
   3324  }
   3325 
   3326  if (eap->skip) {
   3327    emsg_skip--;
   3328  }
   3329  clear_evalarg(&evalarg, eap);
   3330 }
   3331 
   3332 /// Lower level implementation of "call".  Only called when not skipping.
   3333 static int ex_call_inner(exarg_T *eap, char *name, char **arg, char *startarg,
   3334                         const funcexe_T *const funcexe_init, evalarg_T *const evalarg)
   3335 {
   3336  bool doesrange;
   3337  bool failed = false;
   3338 
   3339  for (linenr_T lnum = eap->line1; lnum <= eap->line2; lnum++) {
   3340    if (eap->addr_count > 0) {
   3341      if (lnum > curbuf->b_ml.ml_line_count) {
   3342        // If the function deleted lines or switched to another buffer
   3343        // the line number may become invalid.
   3344        emsg(_(e_invrange));
   3345        break;
   3346      }
   3347      curwin->w_cursor.lnum = lnum;
   3348      curwin->w_cursor.col = 0;
   3349      curwin->w_cursor.coladd = 0;
   3350    }
   3351    *arg = startarg;
   3352 
   3353    funcexe_T funcexe = *funcexe_init;
   3354    funcexe.fe_doesrange = &doesrange;
   3355    typval_T rettv;
   3356    rettv.v_type = VAR_UNKNOWN;  // tv_clear() uses this
   3357    if (get_func_tv(name, -1, &rettv, arg, evalarg, &funcexe) == FAIL) {
   3358      failed = true;
   3359      break;
   3360    }
   3361 
   3362    // Handle a function returning a Funcref, Dict or List.
   3363    if (handle_subscript((const char **)arg, &rettv, &EVALARG_EVALUATE, true) == FAIL) {
   3364      failed = true;
   3365      break;
   3366    }
   3367 
   3368    tv_clear(&rettv);
   3369    if (doesrange) {
   3370      break;
   3371    }
   3372 
   3373    // Stop when immediately aborting on error, or when an interrupt
   3374    // occurred or an exception was thrown but not caught.
   3375    // get_func_tv() returned OK, so that the check for trailing
   3376    // characters below is executed.
   3377    if (aborting()) {
   3378      break;
   3379    }
   3380  }
   3381 
   3382  return failed;
   3383 }
   3384 
   3385 /// Core part of ":defer func(arg)".  "arg" points to the "(" and is advanced.
   3386 ///
   3387 /// @return  FAIL or OK.
   3388 static int ex_defer_inner(char *name, char **arg, const partial_T *const partial,
   3389                          evalarg_T *const evalarg)
   3390 {
   3391  typval_T argvars[MAX_FUNC_ARGS + 1];  // vars for arguments
   3392  int partial_argc = 0;  // number of partial arguments
   3393  int argcount = 0;  // number of arguments found
   3394 
   3395  if (current_funccal == NULL) {
   3396    semsg(_(e_str_not_inside_function), "defer");
   3397    return FAIL;
   3398  }
   3399  if (partial != NULL) {
   3400    if (partial->pt_dict != NULL) {
   3401      emsg(_(e_cannot_use_partial_with_dictionary_for_defer));
   3402      return FAIL;
   3403    }
   3404    if (partial->pt_argc > 0) {
   3405      partial_argc = partial->pt_argc;
   3406      for (int i = 0; i < partial_argc; i++) {
   3407        tv_copy(&partial->pt_argv[i], &argvars[i]);
   3408      }
   3409    }
   3410  }
   3411  int r = get_func_arguments(arg, evalarg, false, argvars + partial_argc, &argcount);
   3412  argcount += partial_argc;
   3413 
   3414  if (r == OK) {
   3415    if (builtin_function(name, -1)) {
   3416      const EvalFuncDef *const fdef = find_internal_func(name);
   3417      if (fdef == NULL) {
   3418        emsg_funcname(e_unknown_function_str, name);
   3419        r = FAIL;
   3420      } else if (check_internal_func(fdef, argcount) == -1) {
   3421        r = FAIL;
   3422      }
   3423    } else {
   3424      ufunc_T *ufunc = find_func(name);
   3425      // we tolerate an unknown function here, it might be defined later
   3426      if (ufunc != NULL) {
   3427        int error = check_user_func_argcount(ufunc, argcount);
   3428        if (error != FCERR_UNKNOWN) {
   3429          user_func_error(error, name, false);
   3430          r = FAIL;
   3431        }
   3432      }
   3433    }
   3434  }
   3435 
   3436  if (r == FAIL) {
   3437    while (--argcount >= 0) {
   3438      tv_clear(&argvars[argcount]);
   3439    }
   3440    return FAIL;
   3441  }
   3442  add_defer(name, argcount, argvars);
   3443  return OK;
   3444 }
   3445 
   3446 /// Return true if currently inside a function call.
   3447 /// Give an error message and return false when not.
   3448 bool can_add_defer(void)
   3449 {
   3450  if (get_current_funccal() == NULL) {
   3451    semsg(_(e_str_not_inside_function), "defer");
   3452    return false;
   3453  }
   3454  return true;
   3455 }
   3456 
   3457 /// Add a deferred call for "name" with arguments "argvars[argcount]".
   3458 /// Consumes "argvars[]".
   3459 /// Caller must check that current_funccal is not NULL.
   3460 void add_defer(char *name, int argcount_arg, typval_T *argvars)
   3461 {
   3462  char *saved_name = xstrdup(name);
   3463  int argcount = argcount_arg;
   3464 
   3465  if (current_funccal->fc_defer.ga_itemsize == 0) {
   3466    ga_init(&current_funccal->fc_defer, sizeof(defer_T), 10);
   3467  }
   3468  defer_T *dr = GA_APPEND_VIA_PTR(defer_T, &current_funccal->fc_defer);
   3469  dr->dr_name = saved_name;
   3470  dr->dr_argcount = argcount;
   3471  while (argcount > 0) {
   3472    argcount--;
   3473    dr->dr_argvars[argcount] = argvars[argcount];
   3474  }
   3475 }
   3476 
   3477 /// Invoked after a function has finished: invoke ":defer" functions.
   3478 static void handle_defer_one(funccall_T *funccal)
   3479 {
   3480  for (int idx = funccal->fc_defer.ga_len - 1; idx >= 0; idx--) {
   3481    defer_T *dr = ((defer_T *)funccal->fc_defer.ga_data) + idx;
   3482 
   3483    if (dr->dr_name == NULL) {
   3484      // already being called, can happen if function does ":qa"
   3485      continue;
   3486    }
   3487 
   3488    funcexe_T funcexe = { .fe_evaluate = true };
   3489 
   3490    typval_T rettv;
   3491    rettv.v_type = VAR_UNKNOWN;     // tv_clear() uses this
   3492 
   3493    char *name = dr->dr_name;
   3494    dr->dr_name = NULL;
   3495 
   3496    // If the deferred function is called after an exception, then only the
   3497    // first statement in the function will be executed (because of the
   3498    // exception).  So save and restore the try/catch/throw exception
   3499    // state.
   3500    exception_state_T estate;
   3501    exception_state_save(&estate);
   3502    exception_state_clear();
   3503 
   3504    call_func(name, -1, &rettv, dr->dr_argcount, dr->dr_argvars, &funcexe);
   3505 
   3506    exception_state_restore(&estate);
   3507 
   3508    tv_clear(&rettv);
   3509    xfree(name);
   3510    for (int i = dr->dr_argcount - 1; i >= 0; i--) {
   3511      tv_clear(&dr->dr_argvars[i]);
   3512    }
   3513  }
   3514  ga_clear(&funccal->fc_defer);
   3515 }
   3516 
   3517 /// Called when exiting: call all defer functions.
   3518 void invoke_all_defer(void)
   3519 {
   3520  for (funccall_T *fc = current_funccal; fc != NULL; fc = fc->fc_caller) {
   3521    handle_defer_one(fc);
   3522  }
   3523 
   3524  for (funccal_entry_T *fce = funccal_stack; fce != NULL; fce = fce->next) {
   3525    for (funccall_T *fc = fce->top_funccal; fc != NULL; fc = fc->fc_caller) {
   3526      handle_defer_one(fc);
   3527    }
   3528  }
   3529 }
   3530 
   3531 /// ":1,25call func(arg1, arg2)" function call.
   3532 /// ":defer func(arg1, arg2)"    deferred function call.
   3533 void ex_call(exarg_T *eap)
   3534 {
   3535  char *arg = eap->arg;
   3536  bool failed = false;
   3537  funcdict_T fudi;
   3538  partial_T *partial = NULL;
   3539  evalarg_T evalarg;
   3540 
   3541  fill_evalarg_from_eap(&evalarg, eap, eap->skip);
   3542  if (eap->skip) {
   3543    typval_T rettv;
   3544    // trans_function_name() doesn't work well when skipping, use eval0()
   3545    // instead to skip to any following command, e.g. for:
   3546    //   :if 0 | call dict.foo().bar() | endif.
   3547    emsg_skip++;
   3548    if (eval0(eap->arg, &rettv, eap, &evalarg) != FAIL) {
   3549      tv_clear(&rettv);
   3550    }
   3551    emsg_skip--;
   3552    clear_evalarg(&evalarg, eap);
   3553    return;
   3554  }
   3555 
   3556  char *tofree = trans_function_name(&arg, false, TFN_INT, &fudi, &partial);
   3557  if (fudi.fd_newkey != NULL) {
   3558    // Still need to give an error message for missing key.
   3559    semsg(_(e_dictkey), fudi.fd_newkey);
   3560    xfree(fudi.fd_newkey);
   3561  }
   3562  if (tofree == NULL) {
   3563    return;
   3564  }
   3565 
   3566  // Increase refcount on dictionary, it could get deleted when evaluating
   3567  // the arguments.
   3568  if (fudi.fd_dict != NULL) {
   3569    fudi.fd_dict->dv_refcount++;
   3570  }
   3571 
   3572  // If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
   3573  // contents. For VAR_PARTIAL get its partial, unless we already have one
   3574  // from trans_function_name().
   3575  int len = (int)strlen(tofree);
   3576  bool found_var = false;
   3577  char *name = deref_func_name(tofree, &len, partial != NULL ? NULL : &partial, false, &found_var);
   3578 
   3579  // Skip white space to allow ":call func ()".  Not good, but required for
   3580  // backward compatibility.
   3581  char *startarg = skipwhite(arg);
   3582 
   3583  if (*startarg != '(') {
   3584    semsg(_(e_missingparen), eap->arg);
   3585    goto end;
   3586  }
   3587 
   3588  if (eap->cmdidx == CMD_defer) {
   3589    arg = startarg;
   3590    failed = ex_defer_inner(name, &arg, partial, &evalarg) == FAIL;
   3591  } else {
   3592    funcexe_T funcexe = FUNCEXE_INIT;
   3593    funcexe.fe_partial = partial;
   3594    funcexe.fe_selfdict = fudi.fd_dict;
   3595    funcexe.fe_firstline = eap->line1;
   3596    funcexe.fe_lastline = eap->line2;
   3597    funcexe.fe_found_var = found_var;
   3598    funcexe.fe_evaluate = true;
   3599    failed = ex_call_inner(eap, name, &arg, startarg, &funcexe, &evalarg);
   3600  }
   3601 
   3602  // When inside :try we need to check for following "| catch" or "| endtry".
   3603  // Not when there was an error, but do check if an exception was thrown.
   3604  if ((!aborting() || did_throw) && (!failed || eap->cstack->cs_trylevel > 0)) {
   3605    // Check for trailing illegal characters and a following command.
   3606    if (!ends_excmd(*arg)) {
   3607      if (!failed && !aborting()) {
   3608        emsg_severe = true;
   3609        semsg(_(e_trailing_arg), arg);
   3610      }
   3611    } else {
   3612      eap->nextcmd = check_nextcmd(arg);
   3613    }
   3614  }
   3615  clear_evalarg(&evalarg, eap);
   3616 
   3617 end:
   3618  tv_dict_unref(fudi.fd_dict);
   3619  xfree(tofree);
   3620 }
   3621 
   3622 /// Return from a function.  Possibly makes the return pending.  Also called
   3623 /// for a pending return at the ":endtry" or after returning from an extra
   3624 /// do_cmdline().  "reanimate" is used in the latter case.
   3625 ///
   3626 /// @param reanimate  used after returning from an extra do_cmdline().
   3627 /// @param is_cmd     set when called due to a ":return" command.
   3628 /// @param rettv      may point to a typval_T with the return rettv.
   3629 ///
   3630 /// @return  true when the return can be carried out,
   3631 ///          false when the return gets pending.
   3632 bool do_return(exarg_T *eap, bool reanimate, bool is_cmd, void *rettv)
   3633 {
   3634  cstack_T *const cstack = eap->cstack;
   3635 
   3636  if (reanimate) {
   3637    // Undo the return.
   3638    current_funccal->fc_returned = false;
   3639  }
   3640 
   3641  // Cleanup (and deactivate) conditionals, but stop when a try conditional
   3642  // not in its finally clause (which then is to be executed next) is found.
   3643  // In this case, make the ":return" pending for execution at the ":endtry".
   3644  // Otherwise, return normally.
   3645  int idx = cleanup_conditionals(eap->cstack, 0, true);
   3646  if (idx >= 0) {
   3647    cstack->cs_pending[idx] = CSTP_RETURN;
   3648 
   3649    if (!is_cmd && !reanimate) {
   3650      // A pending return again gets pending.  "rettv" points to an
   3651      // allocated variable with the rettv of the original ":return"'s
   3652      // argument if present or is NULL else.
   3653      cstack->cs_rettv[idx] = rettv;
   3654    } else {
   3655      // When undoing a return in order to make it pending, get the stored
   3656      // return rettv.
   3657      if (reanimate) {
   3658        assert(current_funccal->fc_rettv);
   3659        rettv = current_funccal->fc_rettv;
   3660      }
   3661 
   3662      if (rettv != NULL) {
   3663        // Store the value of the pending return.
   3664        cstack->cs_rettv[idx] = xcalloc(1, sizeof(typval_T));
   3665        *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
   3666      } else {
   3667        cstack->cs_rettv[idx] = NULL;
   3668      }
   3669 
   3670      if (reanimate) {
   3671        // The pending return value could be overwritten by a ":return"
   3672        // without argument in a finally clause; reset the default
   3673        // return value.
   3674        current_funccal->fc_rettv->v_type = VAR_NUMBER;
   3675        current_funccal->fc_rettv->vval.v_number = 0;
   3676      }
   3677    }
   3678    report_make_pending(CSTP_RETURN, rettv);
   3679  } else {
   3680    current_funccal->fc_returned = true;
   3681 
   3682    // If the return is carried out now, store the return value.  For
   3683    // a return immediately after reanimation, the value is already
   3684    // there.
   3685    if (!reanimate && rettv != NULL) {
   3686      tv_clear(current_funccal->fc_rettv);
   3687      *current_funccal->fc_rettv = *(typval_T *)rettv;
   3688      if (!is_cmd) {
   3689        xfree(rettv);
   3690      }
   3691    }
   3692  }
   3693 
   3694  return idx < 0;
   3695 }
   3696 
   3697 /// Generate a return command for producing the value of "rettv".  The result
   3698 /// is an allocated string.  Used by report_pending() for verbose messages.
   3699 char *get_return_cmd(void *rettv)
   3700 {
   3701  char *s = NULL;
   3702  char *tofree = NULL;
   3703  size_t slen = 0;
   3704 
   3705  if (rettv != NULL) {
   3706    tofree = s = encode_tv2echo((typval_T *)rettv, NULL);
   3707  }
   3708  if (s == NULL) {
   3709    s = "";
   3710  } else {
   3711    slen = strlen(s);
   3712  }
   3713 
   3714  xstrlcpy(IObuff, ":return ", IOSIZE);
   3715  xstrlcpy(IObuff + 8, s, IOSIZE - 8);
   3716  size_t IObufflen = 8 + slen;
   3717  if (IObufflen >= IOSIZE) {
   3718    STRCPY(IObuff + IOSIZE - 4, "...");
   3719    IObufflen = IOSIZE - 1;
   3720  }
   3721  xfree(tofree);
   3722  return xstrnsave(IObuff, IObufflen);
   3723 }
   3724 
   3725 /// Get next function line.
   3726 /// Called by do_cmdline() to get the next line.
   3727 ///
   3728 /// @return  allocated string, or NULL for end of function.
   3729 char *get_func_line(int c, void *cookie, int indent, bool do_concat)
   3730 {
   3731  funccall_T *fcp = (funccall_T *)cookie;
   3732  ufunc_T *fp = fcp->fc_func;
   3733  char *retval;
   3734 
   3735  // If breakpoints have been added/deleted need to check for it.
   3736  if (fcp->fc_dbg_tick != debug_tick) {
   3737    fcp->fc_breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM);
   3738    fcp->fc_dbg_tick = debug_tick;
   3739  }
   3740  if (do_profiling == PROF_YES) {
   3741    func_line_end(cookie);
   3742  }
   3743 
   3744  garray_T *gap = &fp->uf_lines;  // growarray with function lines
   3745  if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
   3746      || fcp->fc_returned) {
   3747    retval = NULL;
   3748  } else {
   3749    // Skip NULL lines (continuation lines).
   3750    while (fcp->fc_linenr < gap->ga_len
   3751           && ((char **)(gap->ga_data))[fcp->fc_linenr] == NULL) {
   3752      fcp->fc_linenr++;
   3753    }
   3754    if (fcp->fc_linenr >= gap->ga_len) {
   3755      retval = NULL;
   3756    } else {
   3757      retval = xstrdup(((char **)(gap->ga_data))[fcp->fc_linenr++]);
   3758      SOURCING_LNUM = fcp->fc_linenr;
   3759      if (do_profiling == PROF_YES) {
   3760        func_line_start(cookie);
   3761      }
   3762    }
   3763  }
   3764 
   3765  // Did we encounter a breakpoint?
   3766  if (fcp->fc_breakpoint != 0 && fcp->fc_breakpoint <= SOURCING_LNUM) {
   3767    dbg_breakpoint(fp->uf_name, SOURCING_LNUM);
   3768    // Find next breakpoint.
   3769    fcp->fc_breakpoint = dbg_find_breakpoint(false, fp->uf_name, SOURCING_LNUM);
   3770    fcp->fc_dbg_tick = debug_tick;
   3771  }
   3772 
   3773  return retval;
   3774 }
   3775 
   3776 /// @return  true if the currently active function should be ended, because a
   3777 ///          return was encountered or an error occurred.  Used inside a ":while".
   3778 int func_has_ended(void *cookie)
   3779 {
   3780  funccall_T *fcp = (funccall_T *)cookie;
   3781 
   3782  // Ignore the "abort" flag if the abortion behavior has been changed due to
   3783  // an error inside a try conditional.
   3784  return ((fcp->fc_func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
   3785         || fcp->fc_returned;
   3786 }
   3787 
   3788 /// @return  true if cookie indicates a function which "abort"s on errors.
   3789 int func_has_abort(void *cookie)
   3790 {
   3791  return ((funccall_T *)cookie)->fc_func->uf_flags & FC_ABORT;
   3792 }
   3793 
   3794 /// Turn "dict.Func" into a partial for "Func" bound to "dict".
   3795 /// Changes "rettv" in-place.
   3796 void make_partial(dict_T *const selfdict, typval_T *const rettv)
   3797 {
   3798  ufunc_T *fp = NULL;
   3799  char fname_buf[FLEN_FIXED + 1];
   3800  int error;
   3801 
   3802  if (rettv->v_type == VAR_PARTIAL
   3803      && rettv->vval.v_partial != NULL
   3804      && rettv->vval.v_partial->pt_func != NULL) {
   3805    fp = rettv->vval.v_partial->pt_func;
   3806  } else {
   3807    char *fname = rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING
   3808                  ? rettv->vval.v_string
   3809                  : rettv->vval.v_partial == NULL
   3810                  ? NULL
   3811                  : rettv->vval.v_partial->pt_name;
   3812    if (fname == NULL) {
   3813      // There is no point binding a dict to a NULL function, just create
   3814      // a function reference.
   3815      rettv->v_type = VAR_FUNC;
   3816      rettv->vval.v_string = NULL;
   3817    } else {
   3818      char *tofree = NULL;
   3819 
   3820      // Translate "s:func" to the stored function name.
   3821      fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
   3822      fp = find_func(fname);
   3823      xfree(tofree);
   3824    }
   3825  }
   3826 
   3827  // Turn "dict.Func" into a partial for "Func" with "dict".
   3828  if (fp != NULL && (fp->uf_flags & FC_DICT)) {
   3829    partial_T *pt = (partial_T *)xcalloc(1, sizeof(partial_T));
   3830    pt->pt_refcount = 1;
   3831    pt->pt_dict = selfdict;
   3832    (selfdict->dv_refcount)++;
   3833    pt->pt_auto = true;
   3834    if (rettv->v_type == VAR_FUNC || rettv->v_type == VAR_STRING) {
   3835      // Just a function: Take over the function name and use selfdict.
   3836      pt->pt_name = rettv->vval.v_string;
   3837    } else {
   3838      partial_T *ret_pt = rettv->vval.v_partial;
   3839 
   3840      // Partial: copy the function name, use selfdict and copy
   3841      // args. Can't take over name or args, the partial might
   3842      // be referenced elsewhere.
   3843      if (ret_pt->pt_name != NULL) {
   3844        pt->pt_name = xstrdup(ret_pt->pt_name);
   3845        func_ref(pt->pt_name);
   3846      } else {
   3847        pt->pt_func = ret_pt->pt_func;
   3848        func_ptr_ref(pt->pt_func);
   3849      }
   3850      if (ret_pt->pt_argc > 0) {
   3851        size_t arg_size = sizeof(typval_T) * (size_t)ret_pt->pt_argc;
   3852        pt->pt_argv = (typval_T *)xmalloc(arg_size);
   3853        pt->pt_argc = ret_pt->pt_argc;
   3854        for (int i = 0; i < pt->pt_argc; i++) {
   3855          tv_copy(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
   3856        }
   3857      }
   3858      partial_unref(ret_pt);
   3859    }
   3860    rettv->v_type = VAR_PARTIAL;
   3861    rettv->vval.v_partial = pt;
   3862  }
   3863 }
   3864 
   3865 /// @return  the name of the executed function.
   3866 char *func_name(void *cookie)
   3867 {
   3868  return ((funccall_T *)cookie)->fc_func->uf_name;
   3869 }
   3870 
   3871 /// @return  the address holding the next breakpoint line for a funccall cookie.
   3872 linenr_T *func_breakpoint(void *cookie)
   3873 {
   3874  return &((funccall_T *)cookie)->fc_breakpoint;
   3875 }
   3876 
   3877 /// @return  the address holding the debug tick for a funccall cookie.
   3878 int *func_dbg_tick(void *cookie)
   3879 {
   3880  return &((funccall_T *)cookie)->fc_dbg_tick;
   3881 }
   3882 
   3883 /// @return  the nesting level for a funccall cookie.
   3884 int func_level(void *cookie)
   3885 {
   3886  return ((funccall_T *)cookie)->fc_level;
   3887 }
   3888 
   3889 /// @return  true when a function was ended by a ":return" command.
   3890 int current_func_returned(void)
   3891 {
   3892  return current_funccal->fc_returned;
   3893 }
   3894 
   3895 bool free_unref_funccal(int copyID, int testing)
   3896 {
   3897  bool did_free = false;
   3898  bool did_free_funccal = false;
   3899 
   3900  for (funccall_T **pfc = &previous_funccal; *pfc != NULL;) {
   3901    if (can_free_funccal(*pfc, copyID)) {
   3902      funccall_T *fc = *pfc;
   3903      *pfc = fc->fc_caller;
   3904      free_funccal_contents(fc);
   3905      did_free = true;
   3906      did_free_funccal = true;
   3907    } else {
   3908      pfc = &(*pfc)->fc_caller;
   3909    }
   3910  }
   3911  if (did_free_funccal) {
   3912    // When a funccal was freed some more items might be garbage
   3913    // collected, so run again.
   3914    garbage_collect(testing);
   3915  }
   3916  return did_free;
   3917 }
   3918 
   3919 // Get function call environment based on backtrace debug level
   3920 funccall_T *get_funccal(void)
   3921 {
   3922  funccall_T *funccal = current_funccal;
   3923  if (debug_backtrace_level > 0) {
   3924    for (int i = 0; i < debug_backtrace_level; i++) {
   3925      funccall_T *temp_funccal = funccal->fc_caller;
   3926      if (temp_funccal) {
   3927        funccal = temp_funccal;
   3928      } else {
   3929        // backtrace level overflow. reset to max
   3930        debug_backtrace_level = i;
   3931      }
   3932    }
   3933  }
   3934 
   3935  return funccal;
   3936 }
   3937 
   3938 /// @return  dict used for local variables in the current funccal or
   3939 ///          NULL if there is no current funccal.
   3940 dict_T *get_funccal_local_dict(void)
   3941 {
   3942  if (current_funccal == NULL || current_funccal->fc_l_vars.dv_refcount == 0) {
   3943    return NULL;
   3944  }
   3945  return &get_funccal()->fc_l_vars;
   3946 }
   3947 
   3948 /// @return  hashtable used for local variables in the current funccal or
   3949 ///          NULL if there is no current funccal.
   3950 hashtab_T *get_funccal_local_ht(void)
   3951 {
   3952  dict_T *d = get_funccal_local_dict();
   3953  return d != NULL ? &d->dv_hashtab : NULL;
   3954 }
   3955 
   3956 /// @return   the l: scope variable or
   3957 ///           NULL if there is no current funccal.
   3958 dictitem_T *get_funccal_local_var(void)
   3959 {
   3960  if (current_funccal == NULL || current_funccal->fc_l_vars.dv_refcount == 0) {
   3961    return NULL;
   3962  }
   3963  return (dictitem_T *)&get_funccal()->fc_l_vars_var;
   3964 }
   3965 
   3966 /// @return  the dict used for argument in the current funccal or
   3967 ///          NULL if there is no current funccal.
   3968 dict_T *get_funccal_args_dict(void)
   3969 {
   3970  if (current_funccal == NULL || current_funccal->fc_l_vars.dv_refcount == 0) {
   3971    return NULL;
   3972  }
   3973  return &get_funccal()->fc_l_avars;
   3974 }
   3975 
   3976 /// @return  the hashtable used for argument in the current funccal or
   3977 ///          NULL if there is no current funccal.
   3978 hashtab_T *get_funccal_args_ht(void)
   3979 {
   3980  dict_T *d = get_funccal_args_dict();
   3981  return d != NULL ? &d->dv_hashtab : NULL;
   3982 }
   3983 
   3984 /// @return  the a: scope variable or
   3985 ///          NULL if there is no current funccal.
   3986 dictitem_T *get_funccal_args_var(void)
   3987 {
   3988  if (current_funccal == NULL || current_funccal->fc_l_vars.dv_refcount == 0) {
   3989    return NULL;
   3990  }
   3991  return (dictitem_T *)&get_funccal()->fc_l_avars_var;
   3992 }
   3993 
   3994 /// List function variables, if there is a function.
   3995 void list_func_vars(int *first)
   3996 {
   3997  if (current_funccal != NULL && current_funccal->fc_l_vars.dv_refcount > 0) {
   3998    list_hashtable_vars(&current_funccal->fc_l_vars.dv_hashtab, "l:", false,
   3999                        first);
   4000  }
   4001 }
   4002 
   4003 /// @return  if "ht" is the hashtable for local variables in the current
   4004 ///          funccal, return the dict that contains it. Otherwise return NULL.
   4005 dict_T *get_current_funccal_dict(hashtab_T *ht)
   4006 {
   4007  if (current_funccal != NULL && ht == &current_funccal->fc_l_vars.dv_hashtab) {
   4008    return &current_funccal->fc_l_vars;
   4009  }
   4010  return NULL;
   4011 }
   4012 
   4013 /// Search hashitem in parent scope.
   4014 hashitem_T *find_hi_in_scoped_ht(const char *name, hashtab_T **pht)
   4015 {
   4016  if (current_funccal == NULL || current_funccal->fc_func->uf_scoped == NULL) {
   4017    return NULL;
   4018  }
   4019 
   4020  funccall_T *old_current_funccal = current_funccal;
   4021  hashitem_T *hi = NULL;
   4022  const size_t namelen = strlen(name);
   4023  const char *varname;
   4024 
   4025  // Search in parent scope which is possible to reference from lambda
   4026  current_funccal = current_funccal->fc_func->uf_scoped;
   4027  while (current_funccal != NULL) {
   4028    hashtab_T *ht = find_var_ht(name, namelen, &varname);
   4029    if (ht != NULL && *varname != NUL) {
   4030      hi = hash_find_len(ht, varname, namelen - (size_t)(varname - name));
   4031      if (!HASHITEM_EMPTY(hi)) {
   4032        *pht = ht;
   4033        break;
   4034      }
   4035    }
   4036    if (current_funccal == current_funccal->fc_func->uf_scoped) {
   4037      break;
   4038    }
   4039    current_funccal = current_funccal->fc_func->uf_scoped;
   4040  }
   4041  current_funccal = old_current_funccal;
   4042 
   4043  return hi;
   4044 }
   4045 
   4046 /// Search variable in parent scope.
   4047 dictitem_T *find_var_in_scoped_ht(const char *name, const size_t namelen, int no_autoload)
   4048 {
   4049  if (current_funccal == NULL || current_funccal->fc_func->uf_scoped == NULL) {
   4050    return NULL;
   4051  }
   4052 
   4053  dictitem_T *v = NULL;
   4054  funccall_T *old_current_funccal = current_funccal;
   4055  const char *varname;
   4056 
   4057  // Search in parent scope which is possible to reference from lambda
   4058  current_funccal = current_funccal->fc_func->uf_scoped;
   4059  while (current_funccal) {
   4060    hashtab_T *ht = find_var_ht(name, namelen, &varname);
   4061    if (ht != NULL && *varname != NUL) {
   4062      v = find_var_in_ht(ht, *name, varname,
   4063                         namelen - (size_t)(varname - name), no_autoload);
   4064      if (v != NULL) {
   4065        break;
   4066      }
   4067    }
   4068    if (current_funccal == current_funccal->fc_func->uf_scoped) {
   4069      break;
   4070    }
   4071    current_funccal = current_funccal->fc_func->uf_scoped;
   4072  }
   4073  current_funccal = old_current_funccal;
   4074 
   4075  return v;
   4076 }
   4077 
   4078 /// Set "copyID + 1" in previous_funccal and callers.
   4079 bool set_ref_in_previous_funccal(int copyID)
   4080 {
   4081  for (funccall_T *fc = previous_funccal; fc != NULL;
   4082       fc = fc->fc_caller) {
   4083    fc->fc_copyID = copyID + 1;
   4084    if (set_ref_in_ht(&fc->fc_l_vars.dv_hashtab, copyID + 1, NULL)
   4085        || set_ref_in_ht(&fc->fc_l_avars.dv_hashtab, copyID + 1, NULL)
   4086        || set_ref_in_list_items(&fc->fc_l_varlist, copyID + 1, NULL)) {
   4087      return true;
   4088    }
   4089  }
   4090  return false;
   4091 }
   4092 
   4093 static bool set_ref_in_funccal(funccall_T *fc, int copyID)
   4094 {
   4095  if (fc->fc_copyID != copyID) {
   4096    fc->fc_copyID = copyID;
   4097    if (set_ref_in_ht(&fc->fc_l_vars.dv_hashtab, copyID, NULL)
   4098        || set_ref_in_ht(&fc->fc_l_avars.dv_hashtab, copyID, NULL)
   4099        || set_ref_in_list_items(&fc->fc_l_varlist, copyID, NULL)
   4100        || set_ref_in_func(NULL, fc->fc_func, copyID)) {
   4101      return true;
   4102    }
   4103  }
   4104  return false;
   4105 }
   4106 
   4107 /// Set "copyID" in all local vars and arguments in the call stack.
   4108 bool set_ref_in_call_stack(int copyID)
   4109 {
   4110  for (funccall_T *fc = current_funccal; fc != NULL;
   4111       fc = fc->fc_caller) {
   4112    if (set_ref_in_funccal(fc, copyID)) {
   4113      return true;
   4114    }
   4115  }
   4116 
   4117  // Also go through the funccal_stack.
   4118  for (funccal_entry_T *entry = funccal_stack; entry != NULL;
   4119       entry = entry->next) {
   4120    for (funccall_T *fc = entry->top_funccal; fc != NULL;
   4121         fc = fc->fc_caller) {
   4122      if (set_ref_in_funccal(fc, copyID)) {
   4123        return true;
   4124      }
   4125    }
   4126  }
   4127 
   4128  return false;
   4129 }
   4130 
   4131 /// Set "copyID" in all functions available by name.
   4132 bool set_ref_in_functions(int copyID)
   4133 {
   4134  int todo = (int)func_hashtab.ht_used;
   4135  for (hashitem_T *hi = func_hashtab.ht_array; todo > 0 && !got_int; hi++) {
   4136    if (!HASHITEM_EMPTY(hi)) {
   4137      todo--;
   4138      ufunc_T *fp = HI2UF(hi);
   4139      if (!func_name_refcount(fp->uf_name)
   4140          && set_ref_in_func(NULL, fp, copyID)) {
   4141        return true;
   4142      }
   4143    }
   4144  }
   4145  return false;
   4146 }
   4147 
   4148 /// Set "copyID" in all function arguments.
   4149 bool set_ref_in_func_args(int copyID)
   4150 {
   4151  for (int i = 0; i < funcargs.ga_len; i++) {
   4152    if (set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
   4153                        copyID, NULL, NULL)) {
   4154      return true;
   4155    }
   4156  }
   4157  return false;
   4158 }
   4159 
   4160 /// Mark all lists and dicts referenced through function "name" with "copyID".
   4161 /// "list_stack" is used to add lists to be marked.  Can be NULL.
   4162 /// "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
   4163 ///
   4164 /// @return  true if setting references failed somehow.
   4165 bool set_ref_in_func(char *name, ufunc_T *fp_in, int copyID)
   4166 {
   4167  ufunc_T *fp = fp_in;
   4168  int error = FCERR_NONE;
   4169  char fname_buf[FLEN_FIXED + 1];
   4170  char *tofree = NULL;
   4171  bool abort = false;
   4172  if (name == NULL && fp_in == NULL) {
   4173    return false;
   4174  }
   4175 
   4176  if (fp_in == NULL) {
   4177    char *fname = fname_trans_sid(name, fname_buf, &tofree, &error);
   4178    fp = find_func(fname);
   4179  }
   4180  if (fp != NULL) {
   4181    for (funccall_T *fc = fp->uf_scoped; fc != NULL; fc = fc->fc_func->uf_scoped) {
   4182      abort = abort || set_ref_in_funccal(fc, copyID);
   4183    }
   4184  }
   4185  xfree(tofree);
   4186  return abort;
   4187 }
   4188 
   4189 /// Registers a luaref as a lambda.
   4190 char *register_luafunc(LuaRef ref)
   4191 {
   4192  String name = get_lambda_name();
   4193  ufunc_T *fp = alloc_ufunc(name.data, name.size);
   4194 
   4195  fp->uf_refcount = 1;
   4196  fp->uf_varargs = true;
   4197  fp->uf_flags = FC_LUAREF;
   4198  fp->uf_calls = 0;
   4199  fp->uf_script_ctx = current_sctx;
   4200  fp->uf_luaref = ref;
   4201 
   4202  hash_add(&func_hashtab, UF2HIKEY(fp));
   4203 
   4204  // coverity[leaked_storage]
   4205  return fp->uf_name;
   4206 }