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