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