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