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