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