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