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