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