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