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