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