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