xref: /vim-8.2.3635/src/userfunc.c (revision e0720cbf)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * eval.c: User defined function support
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_EVAL) || defined(PROTO)
17 /* 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 all things that a function contains.  Does not free the function
1079  * itself, use func_free() for that.
1080  * When "force" is TRUE we are exiting.
1081  */
1082     static void
1083 func_clear(ufunc_T *fp, int force)
1084 {
1085     if (fp->uf_cleared)
1086 	return;
1087     fp->uf_cleared = TRUE;
1088 
1089     /* clear this function */
1090     ga_clear_strings(&(fp->uf_args));
1091     ga_clear_strings(&(fp->uf_lines));
1092 #ifdef FEAT_PROFILE
1093     vim_free(fp->uf_tml_count);
1094     vim_free(fp->uf_tml_total);
1095     vim_free(fp->uf_tml_self);
1096 #endif
1097     funccal_unref(fp->uf_scoped, fp, force);
1098 }
1099 
1100 /*
1101  * Free a function and remove it from the list of functions.  Does not free
1102  * what a function contains, call func_clear() first.
1103  */
1104     static void
1105 func_free(ufunc_T *fp)
1106 {
1107     /* only remove it when not done already, otherwise we would remove a newer
1108      * version of the function */
1109     if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0)
1110 	func_remove(fp);
1111 
1112     vim_free(fp);
1113 }
1114 
1115 /*
1116  * Free all things that a function contains and free the function itself.
1117  * When "force" is TRUE we are exiting.
1118  */
1119     static void
1120 func_clear_free(ufunc_T *fp, int force)
1121 {
1122     func_clear(fp, force);
1123     func_free(fp);
1124 }
1125 
1126 /*
1127  * There are two kinds of function names:
1128  * 1. ordinary names, function defined with :function
1129  * 2. numbered functions and lambdas
1130  * For the first we only count the name stored in func_hashtab as a reference,
1131  * using function() does not count as a reference, because the function is
1132  * looked up by name.
1133  */
1134     static int
1135 func_name_refcount(char_u *name)
1136 {
1137     return isdigit(*name) || *name == '<';
1138 }
1139 
1140 #if defined(EXITFREE) || defined(PROTO)
1141     void
1142 free_all_functions(void)
1143 {
1144     hashitem_T	*hi;
1145     ufunc_T	*fp;
1146     long_u	skipped = 0;
1147     long_u	todo = 1;
1148     long_u	used;
1149 
1150     /* First clear what the functions contain.  Since this may lower the
1151      * reference count of a function, it may also free a function and change
1152      * the hash table. Restart if that happens. */
1153     while (todo > 0)
1154     {
1155 	todo = func_hashtab.ht_used;
1156 	for (hi = func_hashtab.ht_array; todo > 0; ++hi)
1157 	    if (!HASHITEM_EMPTY(hi))
1158 	    {
1159 		/* Only free functions that are not refcounted, those are
1160 		 * supposed to be freed when no longer referenced. */
1161 		fp = HI2UF(hi);
1162 		if (func_name_refcount(fp->uf_name))
1163 		    ++skipped;
1164 		else
1165 		{
1166 		    used = func_hashtab.ht_used;
1167 		    func_clear(fp, TRUE);
1168 		    if (used != func_hashtab.ht_used)
1169 		    {
1170 			skipped = 0;
1171 			break;
1172 		    }
1173 		}
1174 		--todo;
1175 	    }
1176     }
1177 
1178     /* Now actually free the functions.  Need to start all over every time,
1179      * because func_free() may change the hash table. */
1180     skipped = 0;
1181     while (func_hashtab.ht_used > skipped)
1182     {
1183 	todo = func_hashtab.ht_used;
1184 	for (hi = func_hashtab.ht_array; todo > 0; ++hi)
1185 	    if (!HASHITEM_EMPTY(hi))
1186 	    {
1187 		--todo;
1188 		/* Only free functions that are not refcounted, those are
1189 		 * supposed to be freed when no longer referenced. */
1190 		fp = HI2UF(hi);
1191 		if (func_name_refcount(fp->uf_name))
1192 		    ++skipped;
1193 		else
1194 		{
1195 		    func_free(fp);
1196 		    skipped = 0;
1197 		    break;
1198 		}
1199 	    }
1200     }
1201     if (skipped == 0)
1202 	hash_clear(&func_hashtab);
1203 }
1204 #endif
1205 
1206 /*
1207  * Return TRUE if "name" looks like a builtin function name: starts with a
1208  * lower case letter and doesn't contain AUTOLOAD_CHAR.
1209  * "len" is the length of "name", or -1 for NUL terminated.
1210  */
1211     static int
1212 builtin_function(char_u *name, int len)
1213 {
1214     char_u *p;
1215 
1216     if (!ASCII_ISLOWER(name[0]))
1217 	return FALSE;
1218     p = vim_strchr(name, AUTOLOAD_CHAR);
1219     return p == NULL || (len > 0 && p > name + len);
1220 }
1221 
1222     int
1223 func_call(
1224     char_u	*name,
1225     typval_T	*args,
1226     partial_T	*partial,
1227     dict_T	*selfdict,
1228     typval_T	*rettv)
1229 {
1230     listitem_T	*item;
1231     typval_T	argv[MAX_FUNC_ARGS + 1];
1232     int		argc = 0;
1233     int		dummy;
1234     int		r = 0;
1235 
1236     for (item = args->vval.v_list->lv_first; item != NULL;
1237 							 item = item->li_next)
1238     {
1239 	if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
1240 	{
1241 	    EMSG(_("E699: Too many arguments"));
1242 	    break;
1243 	}
1244 	/* Make a copy of each argument.  This is needed to be able to set
1245 	 * v_lock to VAR_FIXED in the copy without changing the original list.
1246 	 */
1247 	copy_tv(&item->li_tv, &argv[argc++]);
1248     }
1249 
1250     if (item == NULL)
1251 	r = call_func(name, (int)STRLEN(name), rettv, argc, argv, NULL,
1252 				 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1253 					     &dummy, TRUE, partial, selfdict);
1254 
1255     /* Free the arguments. */
1256     while (argc > 0)
1257 	clear_tv(&argv[--argc]);
1258 
1259     return r;
1260 }
1261 
1262 /*
1263  * Call a function with its resolved parameters
1264  *
1265  * "argv_func", when not NULL, can be used to fill in arguments only when the
1266  * invoked function uses them.  It is called like this:
1267  *   new_argcount = argv_func(current_argcount, argv, called_func_argcount)
1268  *
1269  * Return FAIL when the function can't be called,  OK otherwise.
1270  * Also returns OK when an error was encountered while executing the function.
1271  */
1272     int
1273 call_func(
1274     char_u	*funcname,	/* name of the function */
1275     int		len,		/* length of "name" */
1276     typval_T	*rettv,		/* return value goes here */
1277     int		argcount_in,	/* number of "argvars" */
1278     typval_T	*argvars_in,	/* vars for arguments, must have "argcount"
1279 				   PLUS ONE elements! */
1280     int		(* argv_func)(int, typval_T *, int),
1281 				/* function to fill in argvars */
1282     linenr_T	firstline,	/* first line of range */
1283     linenr_T	lastline,	/* last line of range */
1284     int		*doesrange,	/* return: function handled range */
1285     int		evaluate,
1286     partial_T	*partial,	/* optional, can be NULL */
1287     dict_T	*selfdict_in)	/* Dictionary for "self" */
1288 {
1289     int		ret = FAIL;
1290     int		error = ERROR_NONE;
1291     int		i;
1292     ufunc_T	*fp;
1293     char_u	fname_buf[FLEN_FIXED + 1];
1294     char_u	*tofree = NULL;
1295     char_u	*fname;
1296     char_u	*name;
1297     int		argcount = argcount_in;
1298     typval_T	*argvars = argvars_in;
1299     dict_T	*selfdict = selfdict_in;
1300     typval_T	argv[MAX_FUNC_ARGS + 1]; /* used when "partial" is not NULL */
1301     int		argv_clear = 0;
1302 
1303     /* Make a copy of the name, if it comes from a funcref variable it could
1304      * be changed or deleted in the called function. */
1305     name = vim_strnsave(funcname, len);
1306     if (name == NULL)
1307 	return ret;
1308 
1309     fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1310 
1311     *doesrange = FALSE;
1312 
1313     if (partial != NULL)
1314     {
1315 	/* When the function has a partial with a dict and there is a dict
1316 	 * argument, use the dict argument.  That is backwards compatible.
1317 	 * When the dict was bound explicitly use the one from the partial. */
1318 	if (partial->pt_dict != NULL
1319 		&& (selfdict_in == NULL || !partial->pt_auto))
1320 	    selfdict = partial->pt_dict;
1321 	if (error == ERROR_NONE && partial->pt_argc > 0)
1322 	{
1323 	    for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear)
1324 		copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]);
1325 	    for (i = 0; i < argcount_in; ++i)
1326 		argv[i + argv_clear] = argvars_in[i];
1327 	    argvars = argv;
1328 	    argcount = partial->pt_argc + argcount_in;
1329 	}
1330     }
1331 
1332 
1333     /* execute the function if no errors detected and executing */
1334     if (evaluate && error == ERROR_NONE)
1335     {
1336 	char_u *rfname = fname;
1337 
1338 	/* Ignore "g:" before a function name. */
1339 	if (fname[0] == 'g' && fname[1] == ':')
1340 	    rfname = fname + 2;
1341 
1342 	rettv->v_type = VAR_NUMBER;	/* default rettv is number zero */
1343 	rettv->vval.v_number = 0;
1344 	error = ERROR_UNKNOWN;
1345 
1346 	if (!builtin_function(rfname, -1))
1347 	{
1348 	    /*
1349 	     * User defined function.
1350 	     */
1351 	    if (partial != NULL && partial->pt_func != NULL)
1352 		fp = partial->pt_func;
1353 	    else
1354 		fp = find_func(rfname);
1355 
1356 #ifdef FEAT_AUTOCMD
1357 	    /* Trigger FuncUndefined event, may load the function. */
1358 	    if (fp == NULL
1359 		    && apply_autocmds(EVENT_FUNCUNDEFINED,
1360 						     rfname, rfname, TRUE, NULL)
1361 		    && !aborting())
1362 	    {
1363 		/* executed an autocommand, search for the function again */
1364 		fp = find_func(rfname);
1365 	    }
1366 #endif
1367 	    /* Try loading a package. */
1368 	    if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
1369 	    {
1370 		/* loaded a package, search for the function again */
1371 		fp = find_func(rfname);
1372 	    }
1373 
1374 	    if (fp != NULL && (fp->uf_flags & FC_DELETED))
1375 		error = ERROR_DELETED;
1376 	    else if (fp != NULL)
1377 	    {
1378 		if (argv_func != NULL)
1379 		    argcount = argv_func(argcount, argvars, fp->uf_args.ga_len);
1380 
1381 		if (fp->uf_flags & FC_RANGE)
1382 		    *doesrange = TRUE;
1383 		if (argcount < fp->uf_args.ga_len)
1384 		    error = ERROR_TOOFEW;
1385 		else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
1386 		    error = ERROR_TOOMANY;
1387 		else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
1388 		    error = ERROR_DICT;
1389 		else
1390 		{
1391 		    int did_save_redo = FALSE;
1392 
1393 		    /*
1394 		     * Call the user function.
1395 		     * Save and restore search patterns, script variables and
1396 		     * redo buffer.
1397 		     */
1398 		    save_search_patterns();
1399 #ifdef FEAT_INS_EXPAND
1400 		    if (!ins_compl_active())
1401 #endif
1402 		    {
1403 			saveRedobuff();
1404 			did_save_redo = TRUE;
1405 		    }
1406 		    ++fp->uf_calls;
1407 		    call_user_func(fp, argcount, argvars, rettv,
1408 					       firstline, lastline,
1409 				  (fp->uf_flags & FC_DICT) ? selfdict : NULL);
1410 		    if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0)
1411 			/* Function was unreferenced while being used, free it
1412 			 * now. */
1413 			func_clear_free(fp, FALSE);
1414 		    if (did_save_redo)
1415 			restoreRedobuff();
1416 		    restore_search_patterns();
1417 		    error = ERROR_NONE;
1418 		}
1419 	    }
1420 	}
1421 	else
1422 	{
1423 	    /*
1424 	     * Find the function name in the table, call its implementation.
1425 	     */
1426 	    error = call_internal_func(fname, argcount, argvars, rettv);
1427 	}
1428 	/*
1429 	 * The function call (or "FuncUndefined" autocommand sequence) might
1430 	 * have been aborted by an error, an interrupt, or an explicitly thrown
1431 	 * exception that has not been caught so far.  This situation can be
1432 	 * tested for by calling aborting().  For an error in an internal
1433 	 * function or for the "E132" error in call_user_func(), however, the
1434 	 * throw point at which the "force_abort" flag (temporarily reset by
1435 	 * emsg()) is normally updated has not been reached yet. We need to
1436 	 * update that flag first to make aborting() reliable.
1437 	 */
1438 	update_force_abort();
1439     }
1440     if (error == ERROR_NONE)
1441 	ret = OK;
1442 
1443     /*
1444      * Report an error unless the argument evaluation or function call has been
1445      * cancelled due to an aborting error, an interrupt, or an exception.
1446      */
1447     if (!aborting())
1448     {
1449 	switch (error)
1450 	{
1451 	    case ERROR_UNKNOWN:
1452 		    emsg_funcname(N_("E117: Unknown function: %s"), name);
1453 		    break;
1454 	    case ERROR_DELETED:
1455 		    emsg_funcname(N_("E933: Function was deleted: %s"), name);
1456 		    break;
1457 	    case ERROR_TOOMANY:
1458 		    emsg_funcname((char *)e_toomanyarg, name);
1459 		    break;
1460 	    case ERROR_TOOFEW:
1461 		    emsg_funcname(N_("E119: Not enough arguments for function: %s"),
1462 									name);
1463 		    break;
1464 	    case ERROR_SCRIPT:
1465 		    emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
1466 									name);
1467 		    break;
1468 	    case ERROR_DICT:
1469 		    emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
1470 									name);
1471 		    break;
1472 	}
1473     }
1474 
1475     while (argv_clear > 0)
1476 	clear_tv(&argv[--argv_clear]);
1477     vim_free(tofree);
1478     vim_free(name);
1479 
1480     return ret;
1481 }
1482 
1483 /*
1484  * List the head of the function: "name(arg1, arg2)".
1485  */
1486     static void
1487 list_func_head(ufunc_T *fp, int indent)
1488 {
1489     int		j;
1490 
1491     msg_start();
1492     if (indent)
1493 	MSG_PUTS("   ");
1494     MSG_PUTS("function ");
1495     if (fp->uf_name[0] == K_SPECIAL)
1496     {
1497 	MSG_PUTS_ATTR("<SNR>", HL_ATTR(HLF_8));
1498 	msg_puts(fp->uf_name + 3);
1499     }
1500     else
1501 	msg_puts(fp->uf_name);
1502     msg_putchar('(');
1503     for (j = 0; j < fp->uf_args.ga_len; ++j)
1504     {
1505 	if (j)
1506 	    MSG_PUTS(", ");
1507 	msg_puts(FUNCARG(fp, j));
1508     }
1509     if (fp->uf_varargs)
1510     {
1511 	if (j)
1512 	    MSG_PUTS(", ");
1513 	MSG_PUTS("...");
1514     }
1515     msg_putchar(')');
1516     if (fp->uf_flags & FC_ABORT)
1517 	MSG_PUTS(" abort");
1518     if (fp->uf_flags & FC_RANGE)
1519 	MSG_PUTS(" range");
1520     if (fp->uf_flags & FC_DICT)
1521 	MSG_PUTS(" dict");
1522     if (fp->uf_flags & FC_CLOSURE)
1523 	MSG_PUTS(" closure");
1524     msg_clr_eos();
1525     if (p_verbose > 0)
1526 	last_set_msg(fp->uf_script_ID);
1527 }
1528 
1529 /*
1530  * Get a function name, translating "<SID>" and "<SNR>".
1531  * Also handles a Funcref in a List or Dictionary.
1532  * Returns the function name in allocated memory, or NULL for failure.
1533  * flags:
1534  * TFN_INT:	    internal function name OK
1535  * TFN_QUIET:	    be quiet
1536  * TFN_NO_AUTOLOAD: do not use script autoloading
1537  * TFN_NO_DEREF:    do not dereference a Funcref
1538  * Advances "pp" to just after the function name (if no error).
1539  */
1540     char_u *
1541 trans_function_name(
1542     char_u	**pp,
1543     int		skip,		/* only find the end, don't evaluate */
1544     int		flags,
1545     funcdict_T	*fdp,		/* return: info about dictionary used */
1546     partial_T	**partial)	/* return: partial of a FuncRef */
1547 {
1548     char_u	*name = NULL;
1549     char_u	*start;
1550     char_u	*end;
1551     int		lead;
1552     char_u	sid_buf[20];
1553     int		len;
1554     lval_T	lv;
1555 
1556     if (fdp != NULL)
1557 	vim_memset(fdp, 0, sizeof(funcdict_T));
1558     start = *pp;
1559 
1560     /* Check for hard coded <SNR>: already translated function ID (from a user
1561      * command). */
1562     if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
1563 						   && (*pp)[2] == (int)KE_SNR)
1564     {
1565 	*pp += 3;
1566 	len = get_id_len(pp) + 3;
1567 	return vim_strnsave(start, len);
1568     }
1569 
1570     /* A name starting with "<SID>" or "<SNR>" is local to a script.  But
1571      * don't skip over "s:", get_lval() needs it for "s:dict.func". */
1572     lead = eval_fname_script(start);
1573     if (lead > 2)
1574 	start += lead;
1575 
1576     /* Note that TFN_ flags use the same values as GLV_ flags. */
1577     end = get_lval(start, NULL, &lv, FALSE, skip, flags,
1578 					      lead > 2 ? 0 : FNE_CHECK_START);
1579     if (end == start)
1580     {
1581 	if (!skip)
1582 	    EMSG(_("E129: Function name required"));
1583 	goto theend;
1584     }
1585     if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
1586     {
1587 	/*
1588 	 * Report an invalid expression in braces, unless the expression
1589 	 * evaluation has been cancelled due to an aborting error, an
1590 	 * interrupt, or an exception.
1591 	 */
1592 	if (!aborting())
1593 	{
1594 	    if (end != NULL)
1595 		EMSG2(_(e_invarg2), start);
1596 	}
1597 	else
1598 	    *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
1599 	goto theend;
1600     }
1601 
1602     if (lv.ll_tv != NULL)
1603     {
1604 	if (fdp != NULL)
1605 	{
1606 	    fdp->fd_dict = lv.ll_dict;
1607 	    fdp->fd_newkey = lv.ll_newkey;
1608 	    lv.ll_newkey = NULL;
1609 	    fdp->fd_di = lv.ll_di;
1610 	}
1611 	if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
1612 	{
1613 	    name = vim_strsave(lv.ll_tv->vval.v_string);
1614 	    *pp = end;
1615 	}
1616 	else if (lv.ll_tv->v_type == VAR_PARTIAL
1617 					  && lv.ll_tv->vval.v_partial != NULL)
1618 	{
1619 	    name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial));
1620 	    *pp = end;
1621 	    if (partial != NULL)
1622 		*partial = lv.ll_tv->vval.v_partial;
1623 	}
1624 	else
1625 	{
1626 	    if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
1627 			     || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
1628 		EMSG(_(e_funcref));
1629 	    else
1630 		*pp = end;
1631 	    name = NULL;
1632 	}
1633 	goto theend;
1634     }
1635 
1636     if (lv.ll_name == NULL)
1637     {
1638 	/* Error found, but continue after the function name. */
1639 	*pp = end;
1640 	goto theend;
1641     }
1642 
1643     /* Check if the name is a Funcref.  If so, use the value. */
1644     if (lv.ll_exp_name != NULL)
1645     {
1646 	len = (int)STRLEN(lv.ll_exp_name);
1647 	name = deref_func_name(lv.ll_exp_name, &len, partial,
1648 						     flags & TFN_NO_AUTOLOAD);
1649 	if (name == lv.ll_exp_name)
1650 	    name = NULL;
1651     }
1652     else if (!(flags & TFN_NO_DEREF))
1653     {
1654 	len = (int)(end - *pp);
1655 	name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD);
1656 	if (name == *pp)
1657 	    name = NULL;
1658     }
1659     if (name != NULL)
1660     {
1661 	name = vim_strsave(name);
1662 	*pp = end;
1663 	if (STRNCMP(name, "<SNR>", 5) == 0)
1664 	{
1665 	    /* Change "<SNR>" to the byte sequence. */
1666 	    name[0] = K_SPECIAL;
1667 	    name[1] = KS_EXTRA;
1668 	    name[2] = (int)KE_SNR;
1669 	    mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
1670 	}
1671 	goto theend;
1672     }
1673 
1674     if (lv.ll_exp_name != NULL)
1675     {
1676 	len = (int)STRLEN(lv.ll_exp_name);
1677 	if (lead <= 2 && lv.ll_name == lv.ll_exp_name
1678 					 && STRNCMP(lv.ll_name, "s:", 2) == 0)
1679 	{
1680 	    /* When there was "s:" already or the name expanded to get a
1681 	     * leading "s:" then remove it. */
1682 	    lv.ll_name += 2;
1683 	    len -= 2;
1684 	    lead = 2;
1685 	}
1686     }
1687     else
1688     {
1689 	/* skip over "s:" and "g:" */
1690 	if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
1691 	    lv.ll_name += 2;
1692 	len = (int)(end - lv.ll_name);
1693     }
1694 
1695     /*
1696      * Copy the function name to allocated memory.
1697      * Accept <SID>name() inside a script, translate into <SNR>123_name().
1698      * Accept <SNR>123_name() outside a script.
1699      */
1700     if (skip)
1701 	lead = 0;	/* do nothing */
1702     else if (lead > 0)
1703     {
1704 	lead = 3;
1705 	if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
1706 						       || eval_fname_sid(*pp))
1707 	{
1708 	    /* It's "s:" or "<SID>" */
1709 	    if (current_SID <= 0)
1710 	    {
1711 		EMSG(_(e_usingsid));
1712 		goto theend;
1713 	    }
1714 	    sprintf((char *)sid_buf, "%ld_", (long)current_SID);
1715 	    lead += (int)STRLEN(sid_buf);
1716 	}
1717     }
1718     else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
1719     {
1720 	EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"),
1721 								       start);
1722 	goto theend;
1723     }
1724     if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF))
1725     {
1726 	char_u *cp = vim_strchr(lv.ll_name, ':');
1727 
1728 	if (cp != NULL && cp < end)
1729 	{
1730 	    EMSG2(_("E884: Function name cannot contain a colon: %s"), start);
1731 	    goto theend;
1732 	}
1733     }
1734 
1735     name = alloc((unsigned)(len + lead + 1));
1736     if (name != NULL)
1737     {
1738 	if (lead > 0)
1739 	{
1740 	    name[0] = K_SPECIAL;
1741 	    name[1] = KS_EXTRA;
1742 	    name[2] = (int)KE_SNR;
1743 	    if (lead > 3)	/* If it's "<SID>" */
1744 		STRCPY(name + 3, sid_buf);
1745 	}
1746 	mch_memmove(name + lead, lv.ll_name, (size_t)len);
1747 	name[lead + len] = NUL;
1748     }
1749     *pp = end;
1750 
1751 theend:
1752     clear_lval(&lv);
1753     return name;
1754 }
1755 
1756 /*
1757  * ":function"
1758  */
1759     void
1760 ex_function(exarg_T *eap)
1761 {
1762     char_u	*theline;
1763     int		j;
1764     int		c;
1765     int		saved_did_emsg;
1766     int		saved_wait_return = need_wait_return;
1767     char_u	*name = NULL;
1768     char_u	*p;
1769     char_u	*arg;
1770     char_u	*line_arg = NULL;
1771     garray_T	newargs;
1772     garray_T	newlines;
1773     int		varargs = FALSE;
1774     int		flags = 0;
1775     ufunc_T	*fp;
1776     int		overwrite = FALSE;
1777     int		indent;
1778     int		nesting;
1779     char_u	*skip_until = NULL;
1780     dictitem_T	*v;
1781     funcdict_T	fudi;
1782     static int	func_nr = 0;	    /* number for nameless function */
1783     int		paren;
1784     hashtab_T	*ht;
1785     int		todo;
1786     hashitem_T	*hi;
1787     int		sourcing_lnum_off;
1788 
1789     /*
1790      * ":function" without argument: list functions.
1791      */
1792     if (ends_excmd(*eap->arg))
1793     {
1794 	if (!eap->skip)
1795 	{
1796 	    todo = (int)func_hashtab.ht_used;
1797 	    for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1798 	    {
1799 		if (!HASHITEM_EMPTY(hi))
1800 		{
1801 		    --todo;
1802 		    fp = HI2UF(hi);
1803 		    if (!func_name_refcount(fp->uf_name))
1804 			list_func_head(fp, FALSE);
1805 		}
1806 	    }
1807 	}
1808 	eap->nextcmd = check_nextcmd(eap->arg);
1809 	return;
1810     }
1811 
1812     /*
1813      * ":function /pat": list functions matching pattern.
1814      */
1815     if (*eap->arg == '/')
1816     {
1817 	p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
1818 	if (!eap->skip)
1819 	{
1820 	    regmatch_T	regmatch;
1821 
1822 	    c = *p;
1823 	    *p = NUL;
1824 	    regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
1825 	    *p = c;
1826 	    if (regmatch.regprog != NULL)
1827 	    {
1828 		regmatch.rm_ic = p_ic;
1829 
1830 		todo = (int)func_hashtab.ht_used;
1831 		for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1832 		{
1833 		    if (!HASHITEM_EMPTY(hi))
1834 		    {
1835 			--todo;
1836 			fp = HI2UF(hi);
1837 			if (!isdigit(*fp->uf_name)
1838 				    && vim_regexec(&regmatch, fp->uf_name, 0))
1839 			    list_func_head(fp, FALSE);
1840 		    }
1841 		}
1842 		vim_regfree(regmatch.regprog);
1843 	    }
1844 	}
1845 	if (*p == '/')
1846 	    ++p;
1847 	eap->nextcmd = check_nextcmd(p);
1848 	return;
1849     }
1850 
1851     /*
1852      * Get the function name.  There are these situations:
1853      * func	    normal function name
1854      *		    "name" == func, "fudi.fd_dict" == NULL
1855      * dict.func    new dictionary entry
1856      *		    "name" == NULL, "fudi.fd_dict" set,
1857      *		    "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
1858      * dict.func    existing dict entry with a Funcref
1859      *		    "name" == func, "fudi.fd_dict" set,
1860      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1861      * dict.func    existing dict entry that's not a Funcref
1862      *		    "name" == NULL, "fudi.fd_dict" set,
1863      *		    "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1864      * s:func	    script-local function name
1865      * g:func	    global function name, same as "func"
1866      */
1867     p = eap->arg;
1868     name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
1869     paren = (vim_strchr(p, '(') != NULL);
1870     if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
1871     {
1872 	/*
1873 	 * Return on an invalid expression in braces, unless the expression
1874 	 * evaluation has been cancelled due to an aborting error, an
1875 	 * interrupt, or an exception.
1876 	 */
1877 	if (!aborting())
1878 	{
1879 	    if (!eap->skip && fudi.fd_newkey != NULL)
1880 		EMSG2(_(e_dictkey), fudi.fd_newkey);
1881 	    vim_free(fudi.fd_newkey);
1882 	    return;
1883 	}
1884 	else
1885 	    eap->skip = TRUE;
1886     }
1887 
1888     /* An error in a function call during evaluation of an expression in magic
1889      * braces should not cause the function not to be defined. */
1890     saved_did_emsg = did_emsg;
1891     did_emsg = FALSE;
1892 
1893     /*
1894      * ":function func" with only function name: list function.
1895      */
1896     if (!paren)
1897     {
1898 	if (!ends_excmd(*skipwhite(p)))
1899 	{
1900 	    EMSG(_(e_trailing));
1901 	    goto ret_free;
1902 	}
1903 	eap->nextcmd = check_nextcmd(p);
1904 	if (eap->nextcmd != NULL)
1905 	    *p = NUL;
1906 	if (!eap->skip && !got_int)
1907 	{
1908 	    fp = find_func(name);
1909 	    if (fp != NULL)
1910 	    {
1911 		list_func_head(fp, TRUE);
1912 		for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
1913 		{
1914 		    if (FUNCLINE(fp, j) == NULL)
1915 			continue;
1916 		    msg_putchar('\n');
1917 		    msg_outnum((long)(j + 1));
1918 		    if (j < 9)
1919 			msg_putchar(' ');
1920 		    if (j < 99)
1921 			msg_putchar(' ');
1922 		    msg_prt_line(FUNCLINE(fp, j), FALSE);
1923 		    out_flush();	/* show a line at a time */
1924 		    ui_breakcheck();
1925 		}
1926 		if (!got_int)
1927 		{
1928 		    msg_putchar('\n');
1929 		    msg_puts((char_u *)"   endfunction");
1930 		}
1931 	    }
1932 	    else
1933 		emsg_funcname(N_("E123: Undefined function: %s"), name);
1934 	}
1935 	goto ret_free;
1936     }
1937 
1938     /*
1939      * ":function name(arg1, arg2)" Define function.
1940      */
1941     p = skipwhite(p);
1942     if (*p != '(')
1943     {
1944 	if (!eap->skip)
1945 	{
1946 	    EMSG2(_("E124: Missing '(': %s"), eap->arg);
1947 	    goto ret_free;
1948 	}
1949 	/* attempt to continue by skipping some text */
1950 	if (vim_strchr(p, '(') != NULL)
1951 	    p = vim_strchr(p, '(');
1952     }
1953     p = skipwhite(p + 1);
1954 
1955     ga_init2(&newlines, (int)sizeof(char_u *), 3);
1956 
1957     if (!eap->skip)
1958     {
1959 	/* Check the name of the function.  Unless it's a dictionary function
1960 	 * (that we are overwriting). */
1961 	if (name != NULL)
1962 	    arg = name;
1963 	else
1964 	    arg = fudi.fd_newkey;
1965 	if (arg != NULL && (fudi.fd_di == NULL
1966 				     || (fudi.fd_di->di_tv.v_type != VAR_FUNC
1967 				 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL)))
1968 	{
1969 	    if (*arg == K_SPECIAL)
1970 		j = 3;
1971 	    else
1972 		j = 0;
1973 	    while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
1974 						      : eval_isnamec(arg[j])))
1975 		++j;
1976 	    if (arg[j] != NUL)
1977 		emsg_funcname((char *)e_invarg2, arg);
1978 	}
1979 	/* Disallow using the g: dict. */
1980 	if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
1981 	    EMSG(_("E862: Cannot use g: here"));
1982     }
1983 
1984     if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL)
1985 	goto errret_2;
1986 
1987     /* find extra arguments "range", "dict", "abort" and "closure" */
1988     for (;;)
1989     {
1990 	p = skipwhite(p);
1991 	if (STRNCMP(p, "range", 5) == 0)
1992 	{
1993 	    flags |= FC_RANGE;
1994 	    p += 5;
1995 	}
1996 	else if (STRNCMP(p, "dict", 4) == 0)
1997 	{
1998 	    flags |= FC_DICT;
1999 	    p += 4;
2000 	}
2001 	else if (STRNCMP(p, "abort", 5) == 0)
2002 	{
2003 	    flags |= FC_ABORT;
2004 	    p += 5;
2005 	}
2006 	else if (STRNCMP(p, "closure", 7) == 0)
2007 	{
2008 	    flags |= FC_CLOSURE;
2009 	    p += 7;
2010 	    if (current_funccal == NULL)
2011 	    {
2012 		emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
2013 			name == NULL ? (char_u *)"" : name);
2014 		goto erret;
2015 	    }
2016 	}
2017 	else
2018 	    break;
2019     }
2020 
2021     /* When there is a line break use what follows for the function body.
2022      * Makes 'exe "func Test()\n...\nendfunc"' work. */
2023     if (*p == '\n')
2024 	line_arg = p + 1;
2025     else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
2026 	EMSG(_(e_trailing));
2027 
2028     /*
2029      * Read the body of the function, until ":endfunction" is found.
2030      */
2031     if (KeyTyped)
2032     {
2033 	/* Check if the function already exists, don't let the user type the
2034 	 * whole function before telling him it doesn't work!  For a script we
2035 	 * need to skip the body to be able to find what follows. */
2036 	if (!eap->skip && !eap->forceit)
2037 	{
2038 	    if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
2039 		EMSG(_(e_funcdict));
2040 	    else if (name != NULL && find_func(name) != NULL)
2041 		emsg_funcname(e_funcexts, name);
2042 	}
2043 
2044 	if (!eap->skip && did_emsg)
2045 	    goto erret;
2046 
2047 	msg_putchar('\n');	    /* don't overwrite the function name */
2048 	cmdline_row = msg_row;
2049     }
2050 
2051     indent = 2;
2052     nesting = 0;
2053     for (;;)
2054     {
2055 	if (KeyTyped)
2056 	{
2057 	    msg_scroll = TRUE;
2058 	    saved_wait_return = FALSE;
2059 	}
2060 	need_wait_return = FALSE;
2061 	sourcing_lnum_off = sourcing_lnum;
2062 
2063 	if (line_arg != NULL)
2064 	{
2065 	    /* Use eap->arg, split up in parts by line breaks. */
2066 	    theline = line_arg;
2067 	    p = vim_strchr(theline, '\n');
2068 	    if (p == NULL)
2069 		line_arg += STRLEN(line_arg);
2070 	    else
2071 	    {
2072 		*p = NUL;
2073 		line_arg = p + 1;
2074 	    }
2075 	}
2076 	else if (eap->getline == NULL)
2077 	    theline = getcmdline(':', 0L, indent);
2078 	else
2079 	    theline = eap->getline(':', eap->cookie, indent);
2080 	if (KeyTyped)
2081 	    lines_left = Rows - 1;
2082 	if (theline == NULL)
2083 	{
2084 	    EMSG(_("E126: Missing :endfunction"));
2085 	    goto erret;
2086 	}
2087 
2088 	/* Detect line continuation: sourcing_lnum increased more than one. */
2089 	if (sourcing_lnum > sourcing_lnum_off + 1)
2090 	    sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
2091 	else
2092 	    sourcing_lnum_off = 0;
2093 
2094 	if (skip_until != NULL)
2095 	{
2096 	    /* between ":append" and "." and between ":python <<EOF" and "EOF"
2097 	     * don't check for ":endfunc". */
2098 	    if (STRCMP(theline, skip_until) == 0)
2099 	    {
2100 		vim_free(skip_until);
2101 		skip_until = NULL;
2102 	    }
2103 	}
2104 	else
2105 	{
2106 	    /* skip ':' and blanks*/
2107 	    for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
2108 		;
2109 
2110 	    /* Check for "endfunction". */
2111 	    if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
2112 	    {
2113 		if (line_arg == NULL)
2114 		    vim_free(theline);
2115 		break;
2116 	    }
2117 
2118 	    /* Increase indent inside "if", "while", "for" and "try", decrease
2119 	     * at "end". */
2120 	    if (indent > 2 && STRNCMP(p, "end", 3) == 0)
2121 		indent -= 2;
2122 	    else if (STRNCMP(p, "if", 2) == 0
2123 		    || STRNCMP(p, "wh", 2) == 0
2124 		    || STRNCMP(p, "for", 3) == 0
2125 		    || STRNCMP(p, "try", 3) == 0)
2126 		indent += 2;
2127 
2128 	    /* Check for defining a function inside this function. */
2129 	    if (checkforcmd(&p, "function", 2))
2130 	    {
2131 		if (*p == '!')
2132 		    p = skipwhite(p + 1);
2133 		p += eval_fname_script(p);
2134 		vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL));
2135 		if (*skipwhite(p) == '(')
2136 		{
2137 		    ++nesting;
2138 		    indent += 2;
2139 		}
2140 	    }
2141 
2142 	    /* Check for ":append", ":change", ":insert". */
2143 	    p = skip_range(p, NULL);
2144 	    if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
2145 		    || (p[0] == 'c'
2146 			&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
2147 				&& (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
2148 					&& (STRNCMP(&p[3], "nge", 3) != 0
2149 					    || !ASCII_ISALPHA(p[6])))))))
2150 		    || (p[0] == 'i'
2151 			&& (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
2152 				&& (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
2153 		skip_until = vim_strsave((char_u *)".");
2154 
2155 	    /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
2156 	    arg = skipwhite(skiptowhite(p));
2157 	    if (arg[0] == '<' && arg[1] =='<'
2158 		    && ((p[0] == 'p' && p[1] == 'y'
2159 				    && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2160 					|| ((p[2] == '3' || p[2] == 'x')
2161 						   && !ASCII_ISALPHA(p[3]))))
2162 			|| (p[0] == 'p' && p[1] == 'e'
2163 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2164 			|| (p[0] == 't' && p[1] == 'c'
2165 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2166 			|| (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2167 				    && !ASCII_ISALPHA(p[3]))
2168 			|| (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2169 				    && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2170 			|| (p[0] == 'm' && p[1] == 'z'
2171 				    && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
2172 			))
2173 	    {
2174 		/* ":python <<" continues until a dot, like ":append" */
2175 		p = skipwhite(arg + 2);
2176 		if (*p == NUL)
2177 		    skip_until = vim_strsave((char_u *)".");
2178 		else
2179 		    skip_until = vim_strsave(p);
2180 	    }
2181 	}
2182 
2183 	/* Add the line to the function. */
2184 	if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
2185 	{
2186 	    if (line_arg == NULL)
2187 		vim_free(theline);
2188 	    goto erret;
2189 	}
2190 
2191 	/* Copy the line to newly allocated memory.  get_one_sourceline()
2192 	 * allocates 250 bytes per line, this saves 80% on average.  The cost
2193 	 * is an extra alloc/free. */
2194 	p = vim_strsave(theline);
2195 	if (p != NULL)
2196 	{
2197 	    if (line_arg == NULL)
2198 		vim_free(theline);
2199 	    theline = p;
2200 	}
2201 
2202 	((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
2203 
2204 	/* Add NULL lines for continuation lines, so that the line count is
2205 	 * equal to the index in the growarray.   */
2206 	while (sourcing_lnum_off-- > 0)
2207 	    ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
2208 
2209 	/* Check for end of eap->arg. */
2210 	if (line_arg != NULL && *line_arg == NUL)
2211 	    line_arg = NULL;
2212     }
2213 
2214     /* Don't define the function when skipping commands or when an error was
2215      * detected. */
2216     if (eap->skip || did_emsg)
2217 	goto erret;
2218 
2219     /*
2220      * If there are no errors, add the function
2221      */
2222     if (fudi.fd_dict == NULL)
2223     {
2224 	v = find_var(name, &ht, FALSE);
2225 	if (v != NULL && v->di_tv.v_type == VAR_FUNC)
2226 	{
2227 	    emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
2228 									name);
2229 	    goto erret;
2230 	}
2231 
2232 	fp = find_func(name);
2233 	if (fp != NULL)
2234 	{
2235 	    if (!eap->forceit)
2236 	    {
2237 		emsg_funcname(e_funcexts, name);
2238 		goto erret;
2239 	    }
2240 	    if (fp->uf_calls > 0)
2241 	    {
2242 		emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
2243 									name);
2244 		goto erret;
2245 	    }
2246 	    if (fp->uf_refcount > 1)
2247 	    {
2248 		/* This function is referenced somewhere, don't redefine it but
2249 		 * create a new one. */
2250 		--fp->uf_refcount;
2251 		fp->uf_flags |= FC_REMOVED;
2252 		fp = NULL;
2253 		overwrite = TRUE;
2254 	    }
2255 	    else
2256 	    {
2257 		/* redefine existing function */
2258 		ga_clear_strings(&(fp->uf_args));
2259 		ga_clear_strings(&(fp->uf_lines));
2260 		vim_free(name);
2261 		name = NULL;
2262 	    }
2263 	}
2264     }
2265     else
2266     {
2267 	char	numbuf[20];
2268 
2269 	fp = NULL;
2270 	if (fudi.fd_newkey == NULL && !eap->forceit)
2271 	{
2272 	    EMSG(_(e_funcdict));
2273 	    goto erret;
2274 	}
2275 	if (fudi.fd_di == NULL)
2276 	{
2277 	    /* Can't add a function to a locked dictionary */
2278 	    if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE))
2279 		goto erret;
2280 	}
2281 	    /* Can't change an existing function if it is locked */
2282 	else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE))
2283 	    goto erret;
2284 
2285 	/* Give the function a sequential number.  Can only be used with a
2286 	 * Funcref! */
2287 	vim_free(name);
2288 	sprintf(numbuf, "%d", ++func_nr);
2289 	name = vim_strsave((char_u *)numbuf);
2290 	if (name == NULL)
2291 	    goto erret;
2292     }
2293 
2294     if (fp == NULL)
2295     {
2296 	if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
2297 	{
2298 	    int	    slen, plen;
2299 	    char_u  *scriptname;
2300 
2301 	    /* Check that the autoload name matches the script name. */
2302 	    j = FAIL;
2303 	    if (sourcing_name != NULL)
2304 	    {
2305 		scriptname = autoload_name(name);
2306 		if (scriptname != NULL)
2307 		{
2308 		    p = vim_strchr(scriptname, '/');
2309 		    plen = (int)STRLEN(p);
2310 		    slen = (int)STRLEN(sourcing_name);
2311 		    if (slen > plen && fnamecmp(p,
2312 					    sourcing_name + slen - plen) == 0)
2313 			j = OK;
2314 		    vim_free(scriptname);
2315 		}
2316 	    }
2317 	    if (j == FAIL)
2318 	    {
2319 		EMSG2(_("E746: Function name does not match script file name: %s"), name);
2320 		goto erret;
2321 	    }
2322 	}
2323 
2324 	fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
2325 	if (fp == NULL)
2326 	    goto erret;
2327 
2328 	if (fudi.fd_dict != NULL)
2329 	{
2330 	    if (fudi.fd_di == NULL)
2331 	    {
2332 		/* add new dict entry */
2333 		fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
2334 		if (fudi.fd_di == NULL)
2335 		{
2336 		    vim_free(fp);
2337 		    goto erret;
2338 		}
2339 		if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
2340 		{
2341 		    vim_free(fudi.fd_di);
2342 		    vim_free(fp);
2343 		    goto erret;
2344 		}
2345 	    }
2346 	    else
2347 		/* overwrite existing dict entry */
2348 		clear_tv(&fudi.fd_di->di_tv);
2349 	    fudi.fd_di->di_tv.v_type = VAR_FUNC;
2350 	    fudi.fd_di->di_tv.v_lock = 0;
2351 	    fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
2352 
2353 	    /* behave like "dict" was used */
2354 	    flags |= FC_DICT;
2355 	}
2356 
2357 	/* insert the new function in the function list */
2358 	STRCPY(fp->uf_name, name);
2359 	if (overwrite)
2360 	{
2361 	    hi = hash_find(&func_hashtab, name);
2362 	    hi->hi_key = UF2HIKEY(fp);
2363 	}
2364 	else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL)
2365 	{
2366 	    vim_free(fp);
2367 	    goto erret;
2368 	}
2369 	fp->uf_refcount = 1;
2370     }
2371     fp->uf_args = newargs;
2372     fp->uf_lines = newlines;
2373     if ((flags & FC_CLOSURE) != 0)
2374     {
2375 	if (register_closure(fp) == FAIL)
2376 	    goto erret;
2377     }
2378     else
2379 	fp->uf_scoped = NULL;
2380 
2381 #ifdef FEAT_PROFILE
2382     fp->uf_tml_count = NULL;
2383     fp->uf_tml_total = NULL;
2384     fp->uf_tml_self = NULL;
2385     fp->uf_profiling = FALSE;
2386     if (prof_def_func())
2387 	func_do_profile(fp);
2388 #endif
2389     fp->uf_varargs = varargs;
2390     fp->uf_flags = flags;
2391     fp->uf_calls = 0;
2392     fp->uf_script_ID = current_SID;
2393     goto ret_free;
2394 
2395 erret:
2396     ga_clear_strings(&newargs);
2397 errret_2:
2398     ga_clear_strings(&newlines);
2399 ret_free:
2400     vim_free(skip_until);
2401     vim_free(fudi.fd_newkey);
2402     vim_free(name);
2403     did_emsg |= saved_did_emsg;
2404     need_wait_return |= saved_wait_return;
2405 }
2406 
2407 /*
2408  * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
2409  * Return 2 if "p" starts with "s:".
2410  * Return 0 otherwise.
2411  */
2412     int
2413 eval_fname_script(char_u *p)
2414 {
2415     /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with
2416      * the standard library function. */
2417     if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0
2418 				       || MB_STRNICMP(p + 1, "SNR>", 4) == 0))
2419 	return 5;
2420     if (p[0] == 's' && p[1] == ':')
2421 	return 2;
2422     return 0;
2423 }
2424 
2425     int
2426 translated_function_exists(char_u *name)
2427 {
2428     if (builtin_function(name, -1))
2429 	return find_internal_func(name) >= 0;
2430     return find_func(name) != NULL;
2431 }
2432 
2433 /*
2434  * Return TRUE if a function "name" exists.
2435  * If "no_defef" is TRUE, do not dereference a Funcref.
2436  */
2437     int
2438 function_exists(char_u *name, int no_deref)
2439 {
2440     char_u  *nm = name;
2441     char_u  *p;
2442     int	    n = FALSE;
2443     int	    flag;
2444 
2445     flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
2446     if (no_deref)
2447 	flag |= TFN_NO_DEREF;
2448     p = trans_function_name(&nm, FALSE, flag, NULL, NULL);
2449     nm = skipwhite(nm);
2450 
2451     /* Only accept "funcname", "funcname ", "funcname (..." and
2452      * "funcname(...", not "funcname!...". */
2453     if (p != NULL && (*nm == NUL || *nm == '('))
2454 	n = translated_function_exists(p);
2455     vim_free(p);
2456     return n;
2457 }
2458 
2459     char_u *
2460 get_expanded_name(char_u *name, int check)
2461 {
2462     char_u	*nm = name;
2463     char_u	*p;
2464 
2465     p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL);
2466 
2467     if (p != NULL && *nm == NUL)
2468 	if (!check || translated_function_exists(p))
2469 	    return p;
2470 
2471     vim_free(p);
2472     return NULL;
2473 }
2474 
2475 #if defined(FEAT_PROFILE) || defined(PROTO)
2476 /*
2477  * Start profiling function "fp".
2478  */
2479     static void
2480 func_do_profile(ufunc_T *fp)
2481 {
2482     int		len = fp->uf_lines.ga_len;
2483 
2484     if (len == 0)
2485 	len = 1;  /* avoid getting error for allocating zero bytes */
2486     fp->uf_tm_count = 0;
2487     profile_zero(&fp->uf_tm_self);
2488     profile_zero(&fp->uf_tm_total);
2489     if (fp->uf_tml_count == NULL)
2490 	fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len));
2491     if (fp->uf_tml_total == NULL)
2492 	fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
2493 						  (sizeof(proftime_T) * len));
2494     if (fp->uf_tml_self == NULL)
2495 	fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
2496 						  (sizeof(proftime_T) * len));
2497     fp->uf_tml_idx = -1;
2498     if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
2499 						   || fp->uf_tml_self == NULL)
2500 	return;	    /* out of memory */
2501 
2502     fp->uf_profiling = TRUE;
2503 }
2504 
2505 /*
2506  * Dump the profiling results for all functions in file "fd".
2507  */
2508     void
2509 func_dump_profile(FILE *fd)
2510 {
2511     hashitem_T	*hi;
2512     int		todo;
2513     ufunc_T	*fp;
2514     int		i;
2515     ufunc_T	**sorttab;
2516     int		st_len = 0;
2517 
2518     todo = (int)func_hashtab.ht_used;
2519     if (todo == 0)
2520 	return;     /* nothing to dump */
2521 
2522     sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo));
2523 
2524     for (hi = func_hashtab.ht_array; todo > 0; ++hi)
2525     {
2526 	if (!HASHITEM_EMPTY(hi))
2527 	{
2528 	    --todo;
2529 	    fp = HI2UF(hi);
2530 	    if (fp->uf_profiling)
2531 	    {
2532 		if (sorttab != NULL)
2533 		    sorttab[st_len++] = fp;
2534 
2535 		if (fp->uf_name[0] == K_SPECIAL)
2536 		    fprintf(fd, "FUNCTION  <SNR>%s()\n", fp->uf_name + 3);
2537 		else
2538 		    fprintf(fd, "FUNCTION  %s()\n", fp->uf_name);
2539 		if (fp->uf_tm_count == 1)
2540 		    fprintf(fd, "Called 1 time\n");
2541 		else
2542 		    fprintf(fd, "Called %d times\n", fp->uf_tm_count);
2543 		fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
2544 		fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
2545 		fprintf(fd, "\n");
2546 		fprintf(fd, "count  total (s)   self (s)\n");
2547 
2548 		for (i = 0; i < fp->uf_lines.ga_len; ++i)
2549 		{
2550 		    if (FUNCLINE(fp, i) == NULL)
2551 			continue;
2552 		    prof_func_line(fd, fp->uf_tml_count[i],
2553 			     &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
2554 		    fprintf(fd, "%s\n", FUNCLINE(fp, i));
2555 		}
2556 		fprintf(fd, "\n");
2557 	    }
2558 	}
2559     }
2560 
2561     if (sorttab != NULL && st_len > 0)
2562     {
2563 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2564 							      prof_total_cmp);
2565 	prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
2566 	qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2567 							      prof_self_cmp);
2568 	prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
2569     }
2570 
2571     vim_free(sorttab);
2572 }
2573 
2574     static void
2575 prof_sort_list(
2576     FILE	*fd,
2577     ufunc_T	**sorttab,
2578     int		st_len,
2579     char	*title,
2580     int		prefer_self)	/* when equal print only self time */
2581 {
2582     int		i;
2583     ufunc_T	*fp;
2584 
2585     fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
2586     fprintf(fd, "count  total (s)   self (s)  function\n");
2587     for (i = 0; i < 20 && i < st_len; ++i)
2588     {
2589 	fp = sorttab[i];
2590 	prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
2591 								 prefer_self);
2592 	if (fp->uf_name[0] == K_SPECIAL)
2593 	    fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
2594 	else
2595 	    fprintf(fd, " %s()\n", fp->uf_name);
2596     }
2597     fprintf(fd, "\n");
2598 }
2599 
2600 /*
2601  * Print the count and times for one function or function line.
2602  */
2603     static void
2604 prof_func_line(
2605     FILE	*fd,
2606     int		count,
2607     proftime_T	*total,
2608     proftime_T	*self,
2609     int		prefer_self)	/* when equal print only self time */
2610 {
2611     if (count > 0)
2612     {
2613 	fprintf(fd, "%5d ", count);
2614 	if (prefer_self && profile_equal(total, self))
2615 	    fprintf(fd, "           ");
2616 	else
2617 	    fprintf(fd, "%s ", profile_msg(total));
2618 	if (!prefer_self && profile_equal(total, self))
2619 	    fprintf(fd, "           ");
2620 	else
2621 	    fprintf(fd, "%s ", profile_msg(self));
2622     }
2623     else
2624 	fprintf(fd, "                            ");
2625 }
2626 
2627 /*
2628  * Compare function for total time sorting.
2629  */
2630     static int
2631 #ifdef __BORLANDC__
2632 _RTLENTRYF
2633 #endif
2634 prof_total_cmp(const void *s1, const void *s2)
2635 {
2636     ufunc_T	*p1, *p2;
2637 
2638     p1 = *(ufunc_T **)s1;
2639     p2 = *(ufunc_T **)s2;
2640     return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
2641 }
2642 
2643 /*
2644  * Compare function for self time sorting.
2645  */
2646     static int
2647 #ifdef __BORLANDC__
2648 _RTLENTRYF
2649 #endif
2650 prof_self_cmp(const void *s1, const void *s2)
2651 {
2652     ufunc_T	*p1, *p2;
2653 
2654     p1 = *(ufunc_T **)s1;
2655     p2 = *(ufunc_T **)s2;
2656     return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
2657 }
2658 
2659 /*
2660  * Prepare profiling for entering a child or something else that is not
2661  * counted for the script/function itself.
2662  * Should always be called in pair with prof_child_exit().
2663  */
2664     void
2665 prof_child_enter(
2666     proftime_T *tm)	/* place to store waittime */
2667 {
2668     funccall_T *fc = current_funccal;
2669 
2670     if (fc != NULL && fc->func->uf_profiling)
2671 	profile_start(&fc->prof_child);
2672     script_prof_save(tm);
2673 }
2674 
2675 /*
2676  * Take care of time spent in a child.
2677  * Should always be called after prof_child_enter().
2678  */
2679     void
2680 prof_child_exit(
2681     proftime_T *tm)	/* where waittime was stored */
2682 {
2683     funccall_T *fc = current_funccal;
2684 
2685     if (fc != NULL && fc->func->uf_profiling)
2686     {
2687 	profile_end(&fc->prof_child);
2688 	profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
2689 	profile_add(&fc->func->uf_tm_children, &fc->prof_child);
2690 	profile_add(&fc->func->uf_tml_children, &fc->prof_child);
2691     }
2692     script_prof_restore(tm);
2693 }
2694 
2695 #endif /* FEAT_PROFILE */
2696 
2697 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2698 
2699 /*
2700  * Function given to ExpandGeneric() to obtain the list of user defined
2701  * function names.
2702  */
2703     char_u *
2704 get_user_func_name(expand_T *xp, int idx)
2705 {
2706     static long_u	done;
2707     static hashitem_T	*hi;
2708     ufunc_T		*fp;
2709 
2710     if (idx == 0)
2711     {
2712 	done = 0;
2713 	hi = func_hashtab.ht_array;
2714     }
2715     if (done < func_hashtab.ht_used)
2716     {
2717 	if (done++ > 0)
2718 	    ++hi;
2719 	while (HASHITEM_EMPTY(hi))
2720 	    ++hi;
2721 	fp = HI2UF(hi);
2722 
2723 	if ((fp->uf_flags & FC_DICT)
2724 				|| STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
2725 	    return (char_u *)""; /* don't show dict and lambda functions */
2726 
2727 	if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
2728 	    return fp->uf_name;	/* prevents overflow */
2729 
2730 	cat_func_name(IObuff, fp);
2731 	if (xp->xp_context != EXPAND_USER_FUNC)
2732 	{
2733 	    STRCAT(IObuff, "(");
2734 	    if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
2735 		STRCAT(IObuff, ")");
2736 	}
2737 	return IObuff;
2738     }
2739     return NULL;
2740 }
2741 
2742 #endif /* FEAT_CMDL_COMPL */
2743 
2744 /*
2745  * ":delfunction {name}"
2746  */
2747     void
2748 ex_delfunction(exarg_T *eap)
2749 {
2750     ufunc_T	*fp = NULL;
2751     char_u	*p;
2752     char_u	*name;
2753     funcdict_T	fudi;
2754 
2755     p = eap->arg;
2756     name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
2757     vim_free(fudi.fd_newkey);
2758     if (name == NULL)
2759     {
2760 	if (fudi.fd_dict != NULL && !eap->skip)
2761 	    EMSG(_(e_funcref));
2762 	return;
2763     }
2764     if (!ends_excmd(*skipwhite(p)))
2765     {
2766 	vim_free(name);
2767 	EMSG(_(e_trailing));
2768 	return;
2769     }
2770     eap->nextcmd = check_nextcmd(p);
2771     if (eap->nextcmd != NULL)
2772 	*p = NUL;
2773 
2774     if (!eap->skip)
2775 	fp = find_func(name);
2776     vim_free(name);
2777 
2778     if (!eap->skip)
2779     {
2780 	if (fp == NULL)
2781 	{
2782 	    EMSG2(_(e_nofunc), eap->arg);
2783 	    return;
2784 	}
2785 	if (fp->uf_calls > 0)
2786 	{
2787 	    EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
2788 	    return;
2789 	}
2790 
2791 	if (fudi.fd_dict != NULL)
2792 	{
2793 	    /* Delete the dict item that refers to the function, it will
2794 	     * invoke func_unref() and possibly delete the function. */
2795 	    dictitem_remove(fudi.fd_dict, fudi.fd_di);
2796 	}
2797 	else
2798 	{
2799 	    /* A normal function (not a numbered function or lambda) has a
2800 	     * refcount of 1 for the entry in the hashtable.  When deleting
2801 	     * it and the refcount is more than one, it should be kept.
2802 	     * A numbered function and lambda should be kept if the refcount is
2803 	     * one or more. */
2804 	    if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1))
2805 	    {
2806 		/* Function is still referenced somewhere.  Don't free it but
2807 		 * do remove it from the hashtable. */
2808 		if (func_remove(fp))
2809 		    fp->uf_refcount--;
2810 		fp->uf_flags |= FC_DELETED;
2811 	    }
2812 	    else
2813 		func_clear_free(fp, FALSE);
2814 	}
2815     }
2816 }
2817 
2818 /*
2819  * Unreference a Function: decrement the reference count and free it when it
2820  * becomes zero.
2821  */
2822     void
2823 func_unref(char_u *name)
2824 {
2825     ufunc_T *fp = NULL;
2826 
2827     if (name == NULL || !func_name_refcount(name))
2828 	return;
2829     fp = find_func(name);
2830     if (fp == NULL && isdigit(*name))
2831     {
2832 #ifdef EXITFREE
2833 	if (!entered_free_all_mem)
2834 #endif
2835 	    internal_error("func_unref()");
2836     }
2837     if (fp != NULL && --fp->uf_refcount <= 0)
2838     {
2839 	/* Only delete it when it's not being used.  Otherwise it's done
2840 	 * when "uf_calls" becomes zero. */
2841 	if (fp->uf_calls == 0)
2842 	    func_clear_free(fp, FALSE);
2843     }
2844 }
2845 
2846 /*
2847  * Unreference a Function: decrement the reference count and free it when it
2848  * becomes zero.
2849  */
2850     void
2851 func_ptr_unref(ufunc_T *fp)
2852 {
2853     if (fp != NULL && --fp->uf_refcount <= 0)
2854     {
2855 	/* Only delete it when it's not being used.  Otherwise it's done
2856 	 * when "uf_calls" becomes zero. */
2857 	if (fp->uf_calls == 0)
2858 	    func_clear_free(fp, FALSE);
2859     }
2860 }
2861 
2862 /*
2863  * Count a reference to a Function.
2864  */
2865     void
2866 func_ref(char_u *name)
2867 {
2868     ufunc_T *fp;
2869 
2870     if (name == NULL || !func_name_refcount(name))
2871 	return;
2872     fp = find_func(name);
2873     if (fp != NULL)
2874 	++fp->uf_refcount;
2875     else if (isdigit(*name))
2876 	/* Only give an error for a numbered function.
2877 	 * Fail silently, when named or lambda function isn't found. */
2878 	internal_error("func_ref()");
2879 }
2880 
2881 /*
2882  * Count a reference to a Function.
2883  */
2884     void
2885 func_ptr_ref(ufunc_T *fp)
2886 {
2887     if (fp != NULL)
2888 	++fp->uf_refcount;
2889 }
2890 
2891 /*
2892  * Return TRUE if items in "fc" do not have "copyID".  That means they are not
2893  * referenced from anywhere that is in use.
2894  */
2895     static int
2896 can_free_funccal(funccall_T *fc, int copyID)
2897 {
2898     return (fc->l_varlist.lv_copyID != copyID
2899 	    && fc->l_vars.dv_copyID != copyID
2900 	    && fc->l_avars.dv_copyID != copyID
2901 	    && fc->fc_copyID != copyID);
2902 }
2903 
2904 /*
2905  * ":return [expr]"
2906  */
2907     void
2908 ex_return(exarg_T *eap)
2909 {
2910     char_u	*arg = eap->arg;
2911     typval_T	rettv;
2912     int		returning = FALSE;
2913 
2914     if (current_funccal == NULL)
2915     {
2916 	EMSG(_("E133: :return not inside a function"));
2917 	return;
2918     }
2919 
2920     if (eap->skip)
2921 	++emsg_skip;
2922 
2923     eap->nextcmd = NULL;
2924     if ((*arg != NUL && *arg != '|' && *arg != '\n')
2925 	    && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
2926     {
2927 	if (!eap->skip)
2928 	    returning = do_return(eap, FALSE, TRUE, &rettv);
2929 	else
2930 	    clear_tv(&rettv);
2931     }
2932     /* It's safer to return also on error. */
2933     else if (!eap->skip)
2934     {
2935 	/*
2936 	 * Return unless the expression evaluation has been cancelled due to an
2937 	 * aborting error, an interrupt, or an exception.
2938 	 */
2939 	if (!aborting())
2940 	    returning = do_return(eap, FALSE, TRUE, NULL);
2941     }
2942 
2943     /* When skipping or the return gets pending, advance to the next command
2944      * in this line (!returning).  Otherwise, ignore the rest of the line.
2945      * Following lines will be ignored by get_func_line(). */
2946     if (returning)
2947 	eap->nextcmd = NULL;
2948     else if (eap->nextcmd == NULL)	    /* no argument */
2949 	eap->nextcmd = check_nextcmd(arg);
2950 
2951     if (eap->skip)
2952 	--emsg_skip;
2953 }
2954 
2955 /*
2956  * ":1,25call func(arg1, arg2)"	function call.
2957  */
2958     void
2959 ex_call(exarg_T *eap)
2960 {
2961     char_u	*arg = eap->arg;
2962     char_u	*startarg;
2963     char_u	*name;
2964     char_u	*tofree;
2965     int		len;
2966     typval_T	rettv;
2967     linenr_T	lnum;
2968     int		doesrange;
2969     int		failed = FALSE;
2970     funcdict_T	fudi;
2971     partial_T	*partial = NULL;
2972 
2973     if (eap->skip)
2974     {
2975 	/* trans_function_name() doesn't work well when skipping, use eval0()
2976 	 * instead to skip to any following command, e.g. for:
2977 	 *   :if 0 | call dict.foo().bar() | endif  */
2978 	++emsg_skip;
2979 	if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
2980 	    clear_tv(&rettv);
2981 	--emsg_skip;
2982 	return;
2983     }
2984 
2985     tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial);
2986     if (fudi.fd_newkey != NULL)
2987     {
2988 	/* Still need to give an error message for missing key. */
2989 	EMSG2(_(e_dictkey), fudi.fd_newkey);
2990 	vim_free(fudi.fd_newkey);
2991     }
2992     if (tofree == NULL)
2993 	return;
2994 
2995     /* Increase refcount on dictionary, it could get deleted when evaluating
2996      * the arguments. */
2997     if (fudi.fd_dict != NULL)
2998 	++fudi.fd_dict->dv_refcount;
2999 
3000     /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3001      * contents.  For VAR_PARTIAL get its partial, unless we already have one
3002      * from trans_function_name(). */
3003     len = (int)STRLEN(tofree);
3004     name = deref_func_name(tofree, &len,
3005 				    partial != NULL ? NULL : &partial, FALSE);
3006 
3007     /* Skip white space to allow ":call func ()".  Not good, but required for
3008      * backward compatibility. */
3009     startarg = skipwhite(arg);
3010     rettv.v_type = VAR_UNKNOWN;	/* clear_tv() uses this */
3011 
3012     if (*startarg != '(')
3013     {
3014 	EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3015 	goto end;
3016     }
3017 
3018     /*
3019      * When skipping, evaluate the function once, to find the end of the
3020      * arguments.
3021      * When the function takes a range, this is discovered after the first
3022      * call, and the loop is broken.
3023      */
3024     if (eap->skip)
3025     {
3026 	++emsg_skip;
3027 	lnum = eap->line2;	/* do it once, also with an invalid range */
3028     }
3029     else
3030 	lnum = eap->line1;
3031     for ( ; lnum <= eap->line2; ++lnum)
3032     {
3033 	if (!eap->skip && eap->addr_count > 0)
3034 	{
3035 	    curwin->w_cursor.lnum = lnum;
3036 	    curwin->w_cursor.col = 0;
3037 #ifdef FEAT_VIRTUALEDIT
3038 	    curwin->w_cursor.coladd = 0;
3039 #endif
3040 	}
3041 	arg = startarg;
3042 	if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3043 		    eap->line1, eap->line2, &doesrange,
3044 				   !eap->skip, partial, fudi.fd_dict) == FAIL)
3045 	{
3046 	    failed = TRUE;
3047 	    break;
3048 	}
3049 
3050 	/* Handle a function returning a Funcref, Dictionary or List. */
3051 	if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3052 	{
3053 	    failed = TRUE;
3054 	    break;
3055 	}
3056 
3057 	clear_tv(&rettv);
3058 	if (doesrange || eap->skip)
3059 	    break;
3060 
3061 	/* Stop when immediately aborting on error, or when an interrupt
3062 	 * occurred or an exception was thrown but not caught.
3063 	 * get_func_tv() returned OK, so that the check for trailing
3064 	 * characters below is executed. */
3065 	if (aborting())
3066 	    break;
3067     }
3068     if (eap->skip)
3069 	--emsg_skip;
3070 
3071     if (!failed)
3072     {
3073 	/* Check for trailing illegal characters and a following command. */
3074 	if (!ends_excmd(*arg))
3075 	{
3076 	    emsg_severe = TRUE;
3077 	    EMSG(_(e_trailing));
3078 	}
3079 	else
3080 	    eap->nextcmd = check_nextcmd(arg);
3081     }
3082 
3083 end:
3084     dict_unref(fudi.fd_dict);
3085     vim_free(tofree);
3086 }
3087 
3088 /*
3089  * Return from a function.  Possibly makes the return pending.  Also called
3090  * for a pending return at the ":endtry" or after returning from an extra
3091  * do_cmdline().  "reanimate" is used in the latter case.  "is_cmd" is set
3092  * when called due to a ":return" command.  "rettv" may point to a typval_T
3093  * with the return rettv.  Returns TRUE when the return can be carried out,
3094  * FALSE when the return gets pending.
3095  */
3096     int
3097 do_return(
3098     exarg_T	*eap,
3099     int		reanimate,
3100     int		is_cmd,
3101     void	*rettv)
3102 {
3103     int		idx;
3104     struct condstack *cstack = eap->cstack;
3105 
3106     if (reanimate)
3107 	/* Undo the return. */
3108 	current_funccal->returned = FALSE;
3109 
3110     /*
3111      * Cleanup (and inactivate) conditionals, but stop when a try conditional
3112      * not in its finally clause (which then is to be executed next) is found.
3113      * In this case, make the ":return" pending for execution at the ":endtry".
3114      * Otherwise, return normally.
3115      */
3116     idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3117     if (idx >= 0)
3118     {
3119 	cstack->cs_pending[idx] = CSTP_RETURN;
3120 
3121 	if (!is_cmd && !reanimate)
3122 	    /* A pending return again gets pending.  "rettv" points to an
3123 	     * allocated variable with the rettv of the original ":return"'s
3124 	     * argument if present or is NULL else. */
3125 	    cstack->cs_rettv[idx] = rettv;
3126 	else
3127 	{
3128 	    /* When undoing a return in order to make it pending, get the stored
3129 	     * return rettv. */
3130 	    if (reanimate)
3131 		rettv = current_funccal->rettv;
3132 
3133 	    if (rettv != NULL)
3134 	    {
3135 		/* Store the value of the pending return. */
3136 		if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
3137 		    *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3138 		else
3139 		    EMSG(_(e_outofmem));
3140 	    }
3141 	    else
3142 		cstack->cs_rettv[idx] = NULL;
3143 
3144 	    if (reanimate)
3145 	    {
3146 		/* The pending return value could be overwritten by a ":return"
3147 		 * without argument in a finally clause; reset the default
3148 		 * return value. */
3149 		current_funccal->rettv->v_type = VAR_NUMBER;
3150 		current_funccal->rettv->vval.v_number = 0;
3151 	    }
3152 	}
3153 	report_make_pending(CSTP_RETURN, rettv);
3154     }
3155     else
3156     {
3157 	current_funccal->returned = TRUE;
3158 
3159 	/* If the return is carried out now, store the return value.  For
3160 	 * a return immediately after reanimation, the value is already
3161 	 * there. */
3162 	if (!reanimate && rettv != NULL)
3163 	{
3164 	    clear_tv(current_funccal->rettv);
3165 	    *current_funccal->rettv = *(typval_T *)rettv;
3166 	    if (!is_cmd)
3167 		vim_free(rettv);
3168 	}
3169     }
3170 
3171     return idx < 0;
3172 }
3173 
3174 /*
3175  * Free the variable with a pending return value.
3176  */
3177     void
3178 discard_pending_return(void *rettv)
3179 {
3180     free_tv((typval_T *)rettv);
3181 }
3182 
3183 /*
3184  * Generate a return command for producing the value of "rettv".  The result
3185  * is an allocated string.  Used by report_pending() for verbose messages.
3186  */
3187     char_u *
3188 get_return_cmd(void *rettv)
3189 {
3190     char_u	*s = NULL;
3191     char_u	*tofree = NULL;
3192     char_u	numbuf[NUMBUFLEN];
3193 
3194     if (rettv != NULL)
3195 	s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
3196     if (s == NULL)
3197 	s = (char_u *)"";
3198 
3199     STRCPY(IObuff, ":return ");
3200     STRNCPY(IObuff + 8, s, IOSIZE - 8);
3201     if (STRLEN(s) + 8 >= IOSIZE)
3202 	STRCPY(IObuff + IOSIZE - 4, "...");
3203     vim_free(tofree);
3204     return vim_strsave(IObuff);
3205 }
3206 
3207 /*
3208  * Get next function line.
3209  * Called by do_cmdline() to get the next line.
3210  * Returns allocated string, or NULL for end of function.
3211  */
3212     char_u *
3213 get_func_line(
3214     int	    c UNUSED,
3215     void    *cookie,
3216     int	    indent UNUSED)
3217 {
3218     funccall_T	*fcp = (funccall_T *)cookie;
3219     ufunc_T	*fp = fcp->func;
3220     char_u	*retval;
3221     garray_T	*gap;  /* growarray with function lines */
3222 
3223     /* If breakpoints have been added/deleted need to check for it. */
3224     if (fcp->dbg_tick != debug_tick)
3225     {
3226 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3227 							       sourcing_lnum);
3228 	fcp->dbg_tick = debug_tick;
3229     }
3230 #ifdef FEAT_PROFILE
3231     if (do_profiling == PROF_YES)
3232 	func_line_end(cookie);
3233 #endif
3234 
3235     gap = &fp->uf_lines;
3236     if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3237 	    || fcp->returned)
3238 	retval = NULL;
3239     else
3240     {
3241 	/* Skip NULL lines (continuation lines). */
3242 	while (fcp->linenr < gap->ga_len
3243 			  && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
3244 	    ++fcp->linenr;
3245 	if (fcp->linenr >= gap->ga_len)
3246 	    retval = NULL;
3247 	else
3248 	{
3249 	    retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
3250 	    sourcing_lnum = fcp->linenr;
3251 #ifdef FEAT_PROFILE
3252 	    if (do_profiling == PROF_YES)
3253 		func_line_start(cookie);
3254 #endif
3255 	}
3256     }
3257 
3258     /* Did we encounter a breakpoint? */
3259     if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
3260     {
3261 	dbg_breakpoint(fp->uf_name, sourcing_lnum);
3262 	/* Find next breakpoint. */
3263 	fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3264 							       sourcing_lnum);
3265 	fcp->dbg_tick = debug_tick;
3266     }
3267 
3268     return retval;
3269 }
3270 
3271 #if defined(FEAT_PROFILE) || defined(PROTO)
3272 /*
3273  * Called when starting to read a function line.
3274  * "sourcing_lnum" must be correct!
3275  * When skipping lines it may not actually be executed, but we won't find out
3276  * until later and we need to store the time now.
3277  */
3278     void
3279 func_line_start(void *cookie)
3280 {
3281     funccall_T	*fcp = (funccall_T *)cookie;
3282     ufunc_T	*fp = fcp->func;
3283 
3284     if (fp->uf_profiling && sourcing_lnum >= 1
3285 				      && sourcing_lnum <= fp->uf_lines.ga_len)
3286     {
3287 	fp->uf_tml_idx = sourcing_lnum - 1;
3288 	/* Skip continuation lines. */
3289 	while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
3290 	    --fp->uf_tml_idx;
3291 	fp->uf_tml_execed = FALSE;
3292 	profile_start(&fp->uf_tml_start);
3293 	profile_zero(&fp->uf_tml_children);
3294 	profile_get_wait(&fp->uf_tml_wait);
3295     }
3296 }
3297 
3298 /*
3299  * Called when actually executing a function line.
3300  */
3301     void
3302 func_line_exec(void *cookie)
3303 {
3304     funccall_T	*fcp = (funccall_T *)cookie;
3305     ufunc_T	*fp = fcp->func;
3306 
3307     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3308 	fp->uf_tml_execed = TRUE;
3309 }
3310 
3311 /*
3312  * Called when done with a function line.
3313  */
3314     void
3315 func_line_end(void *cookie)
3316 {
3317     funccall_T	*fcp = (funccall_T *)cookie;
3318     ufunc_T	*fp = fcp->func;
3319 
3320     if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3321     {
3322 	if (fp->uf_tml_execed)
3323 	{
3324 	    ++fp->uf_tml_count[fp->uf_tml_idx];
3325 	    profile_end(&fp->uf_tml_start);
3326 	    profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
3327 	    profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
3328 	    profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
3329 							&fp->uf_tml_children);
3330 	}
3331 	fp->uf_tml_idx = -1;
3332     }
3333 }
3334 #endif
3335 
3336 /*
3337  * Return TRUE if the currently active function should be ended, because a
3338  * return was encountered or an error occurred.  Used inside a ":while".
3339  */
3340     int
3341 func_has_ended(void *cookie)
3342 {
3343     funccall_T  *fcp = (funccall_T *)cookie;
3344 
3345     /* Ignore the "abort" flag if the abortion behavior has been changed due to
3346      * an error inside a try conditional. */
3347     return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3348 	    || fcp->returned);
3349 }
3350 
3351 /*
3352  * return TRUE if cookie indicates a function which "abort"s on errors.
3353  */
3354     int
3355 func_has_abort(
3356     void    *cookie)
3357 {
3358     return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
3359 }
3360 
3361 
3362 /*
3363  * Turn "dict.Func" into a partial for "Func" bound to "dict".
3364  * Don't do this when "Func" is already a partial that was bound
3365  * explicitly (pt_auto is FALSE).
3366  * Changes "rettv" in-place.
3367  * Returns the updated "selfdict_in".
3368  */
3369     dict_T *
3370 make_partial(dict_T *selfdict_in, typval_T *rettv)
3371 {
3372     char_u	*fname;
3373     char_u	*tofree = NULL;
3374     ufunc_T	*fp;
3375     char_u	fname_buf[FLEN_FIXED + 1];
3376     int		error;
3377     dict_T	*selfdict = selfdict_in;
3378 
3379     if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL)
3380 	fp = rettv->vval.v_partial->pt_func;
3381     else
3382     {
3383 	fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string
3384 					      : rettv->vval.v_partial->pt_name;
3385 	/* Translate "s:func" to the stored function name. */
3386 	fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3387 	fp = find_func(fname);
3388 	vim_free(tofree);
3389     }
3390 
3391     if (fp != NULL && (fp->uf_flags & FC_DICT))
3392     {
3393 	partial_T	*pt = (partial_T *)alloc_clear(sizeof(partial_T));
3394 
3395 	if (pt != NULL)
3396 	{
3397 	    pt->pt_refcount = 1;
3398 	    pt->pt_dict = selfdict;
3399 	    pt->pt_auto = TRUE;
3400 	    selfdict = NULL;
3401 	    if (rettv->v_type == VAR_FUNC)
3402 	    {
3403 		/* Just a function: Take over the function name and use
3404 		 * selfdict. */
3405 		pt->pt_name = rettv->vval.v_string;
3406 	    }
3407 	    else
3408 	    {
3409 		partial_T	*ret_pt = rettv->vval.v_partial;
3410 		int		i;
3411 
3412 		/* Partial: copy the function name, use selfdict and copy
3413 		 * args.  Can't take over name or args, the partial might
3414 		 * be referenced elsewhere. */
3415 		if (ret_pt->pt_name != NULL)
3416 		{
3417 		    pt->pt_name = vim_strsave(ret_pt->pt_name);
3418 		    func_ref(pt->pt_name);
3419 		}
3420 		else
3421 		{
3422 		    pt->pt_func = ret_pt->pt_func;
3423 		    func_ptr_ref(pt->pt_func);
3424 		}
3425 		if (ret_pt->pt_argc > 0)
3426 		{
3427 		    pt->pt_argv = (typval_T *)alloc(
3428 				      sizeof(typval_T) * ret_pt->pt_argc);
3429 		    if (pt->pt_argv == NULL)
3430 			/* out of memory: drop the arguments */
3431 			pt->pt_argc = 0;
3432 		    else
3433 		    {
3434 			pt->pt_argc = ret_pt->pt_argc;
3435 			for (i = 0; i < pt->pt_argc; i++)
3436 			    copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3437 		    }
3438 		}
3439 		partial_unref(ret_pt);
3440 	    }
3441 	    rettv->v_type = VAR_PARTIAL;
3442 	    rettv->vval.v_partial = pt;
3443 	}
3444     }
3445     return selfdict;
3446 }
3447 
3448 /*
3449  * Return the name of the executed function.
3450  */
3451     char_u *
3452 func_name(void *cookie)
3453 {
3454     return ((funccall_T *)cookie)->func->uf_name;
3455 }
3456 
3457 /*
3458  * Return the address holding the next breakpoint line for a funccall cookie.
3459  */
3460     linenr_T *
3461 func_breakpoint(void *cookie)
3462 {
3463     return &((funccall_T *)cookie)->breakpoint;
3464 }
3465 
3466 /*
3467  * Return the address holding the debug tick for a funccall cookie.
3468  */
3469     int *
3470 func_dbg_tick(void *cookie)
3471 {
3472     return &((funccall_T *)cookie)->dbg_tick;
3473 }
3474 
3475 /*
3476  * Return the nesting level for a funccall cookie.
3477  */
3478     int
3479 func_level(void *cookie)
3480 {
3481     return ((funccall_T *)cookie)->level;
3482 }
3483 
3484 /*
3485  * Return TRUE when a function was ended by a ":return" command.
3486  */
3487     int
3488 current_func_returned(void)
3489 {
3490     return current_funccal->returned;
3491 }
3492 
3493 /*
3494  * Save the current function call pointer, and set it to NULL.
3495  * Used when executing autocommands and for ":source".
3496  */
3497     void *
3498 save_funccal(void)
3499 {
3500     funccall_T *fc = current_funccal;
3501 
3502     current_funccal = NULL;
3503     return (void *)fc;
3504 }
3505 
3506     void
3507 restore_funccal(void *vfc)
3508 {
3509     funccall_T *fc = (funccall_T *)vfc;
3510 
3511     current_funccal = fc;
3512 }
3513 
3514     int
3515 free_unref_funccal(int copyID, int testing)
3516 {
3517     int		did_free = FALSE;
3518     int		did_free_funccal = FALSE;
3519     funccall_T	*fc, **pfc;
3520 
3521     for (pfc = &previous_funccal; *pfc != NULL; )
3522     {
3523 	if (can_free_funccal(*pfc, copyID))
3524 	{
3525 	    fc = *pfc;
3526 	    *pfc = fc->caller;
3527 	    free_funccal(fc, TRUE);
3528 	    did_free = TRUE;
3529 	    did_free_funccal = TRUE;
3530 	}
3531 	else
3532 	    pfc = &(*pfc)->caller;
3533     }
3534     if (did_free_funccal)
3535 	/* When a funccal was freed some more items might be garbage
3536 	 * collected, so run again. */
3537 	(void)garbage_collect(testing);
3538 
3539     return did_free;
3540 }
3541 
3542 /*
3543  * Get function call environment based on backtrace debug level
3544  */
3545     static funccall_T *
3546 get_funccal(void)
3547 {
3548     int		i;
3549     funccall_T	*funccal;
3550     funccall_T	*temp_funccal;
3551 
3552     funccal = current_funccal;
3553     if (debug_backtrace_level > 0)
3554     {
3555 	for (i = 0; i < debug_backtrace_level; i++)
3556 	{
3557 	    temp_funccal = funccal->caller;
3558 	    if (temp_funccal)
3559 		funccal = temp_funccal;
3560 	    else
3561 		/* backtrace level overflow. reset to max */
3562 		debug_backtrace_level = i;
3563 	}
3564     }
3565     return funccal;
3566 }
3567 
3568 /*
3569  * Return the hashtable used for local variables in the current funccal.
3570  * Return NULL if there is no current funccal.
3571  */
3572     hashtab_T *
3573 get_funccal_local_ht()
3574 {
3575     if (current_funccal == NULL)
3576 	return NULL;
3577     return &get_funccal()->l_vars.dv_hashtab;
3578 }
3579 
3580 /*
3581  * Return the l: scope variable.
3582  * Return NULL if there is no current funccal.
3583  */
3584     dictitem_T *
3585 get_funccal_local_var()
3586 {
3587     if (current_funccal == NULL)
3588 	return NULL;
3589     return &get_funccal()->l_vars_var;
3590 }
3591 
3592 /*
3593  * Return the hashtable used for argument in the current funccal.
3594  * Return NULL if there is no current funccal.
3595  */
3596     hashtab_T *
3597 get_funccal_args_ht()
3598 {
3599     if (current_funccal == NULL)
3600 	return NULL;
3601     return &get_funccal()->l_avars.dv_hashtab;
3602 }
3603 
3604 /*
3605  * Return the a: scope variable.
3606  * Return NULL if there is no current funccal.
3607  */
3608     dictitem_T *
3609 get_funccal_args_var()
3610 {
3611     if (current_funccal == NULL)
3612 	return NULL;
3613     return &get_funccal()->l_avars_var;
3614 }
3615 
3616 /*
3617  * Clear the current_funccal and return the old value.
3618  * Caller is expected to invoke restore_current_funccal().
3619  */
3620     void *
3621 clear_current_funccal()
3622 {
3623     funccall_T *f = current_funccal;
3624 
3625     current_funccal = NULL;
3626     return f;
3627 }
3628 
3629     void
3630 restore_current_funccal(void *f)
3631 {
3632     current_funccal = f;
3633 }
3634 
3635 /*
3636  * List function variables, if there is a function.
3637  */
3638     void
3639 list_func_vars(int *first)
3640 {
3641     if (current_funccal != NULL)
3642 	list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
3643 						(char_u *)"l:", FALSE, first);
3644 }
3645 
3646 /*
3647  * If "ht" is the hashtable for local variables in the current funccal, return
3648  * the dict that contains it.
3649  * Otherwise return NULL.
3650  */
3651     dict_T *
3652 get_current_funccal_dict(hashtab_T *ht)
3653 {
3654     if (current_funccal != NULL
3655 	    && ht == &current_funccal->l_vars.dv_hashtab)
3656 	return &current_funccal->l_vars;
3657     return NULL;
3658 }
3659 
3660 /*
3661  * Search hashitem in parent scope.
3662  */
3663     hashitem_T *
3664 find_hi_in_scoped_ht(char_u *name, hashtab_T **pht)
3665 {
3666     funccall_T	*old_current_funccal = current_funccal;
3667     hashtab_T	*ht;
3668     hashitem_T	*hi = NULL;
3669     char_u	*varname;
3670 
3671     if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3672       return NULL;
3673 
3674     /* Search in parent scope which is possible to reference from lambda */
3675     current_funccal = current_funccal->func->uf_scoped;
3676     while (current_funccal != NULL)
3677     {
3678 	ht = find_var_ht(name, &varname);
3679 	if (ht != NULL && *varname != NUL)
3680 	{
3681 	    hi = hash_find(ht, varname);
3682 	    if (!HASHITEM_EMPTY(hi))
3683 	    {
3684 		*pht = ht;
3685 		break;
3686 	    }
3687 	}
3688 	if (current_funccal == current_funccal->func->uf_scoped)
3689 	    break;
3690 	current_funccal = current_funccal->func->uf_scoped;
3691     }
3692     current_funccal = old_current_funccal;
3693 
3694     return hi;
3695 }
3696 
3697 /*
3698  * Search variable in parent scope.
3699  */
3700     dictitem_T *
3701 find_var_in_scoped_ht(char_u *name, int no_autoload)
3702 {
3703     dictitem_T	*v = NULL;
3704     funccall_T	*old_current_funccal = current_funccal;
3705     hashtab_T	*ht;
3706     char_u	*varname;
3707 
3708     if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3709 	return NULL;
3710 
3711     /* Search in parent scope which is possible to reference from lambda */
3712     current_funccal = current_funccal->func->uf_scoped;
3713     while (current_funccal)
3714     {
3715 	ht = find_var_ht(name, &varname);
3716 	if (ht != NULL && *varname != NUL)
3717 	{
3718 	    v = find_var_in_ht(ht, *name, varname, no_autoload);
3719 	    if (v != NULL)
3720 		break;
3721 	}
3722 	if (current_funccal == current_funccal->func->uf_scoped)
3723 	    break;
3724 	current_funccal = current_funccal->func->uf_scoped;
3725     }
3726     current_funccal = old_current_funccal;
3727 
3728     return v;
3729 }
3730 
3731 /*
3732  * Set "copyID + 1" in previous_funccal and callers.
3733  */
3734     int
3735 set_ref_in_previous_funccal(int copyID)
3736 {
3737     int		abort = FALSE;
3738     funccall_T	*fc;
3739 
3740     for (fc = previous_funccal; fc != NULL; fc = fc->caller)
3741     {
3742 	fc->fc_copyID = copyID + 1;
3743 	abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1,
3744 									NULL);
3745 	abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1,
3746 									NULL);
3747     }
3748     return abort;
3749 }
3750 
3751     static int
3752 set_ref_in_funccal(funccall_T *fc, int copyID)
3753 {
3754     int abort = FALSE;
3755 
3756     if (fc->fc_copyID != copyID)
3757     {
3758 	fc->fc_copyID = copyID;
3759 	abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL);
3760 	abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL);
3761 	abort = abort || set_ref_in_func(NULL, fc->func, copyID);
3762     }
3763     return abort;
3764 }
3765 
3766 /*
3767  * Set "copyID" in all local vars and arguments in the call stack.
3768  */
3769     int
3770 set_ref_in_call_stack(int copyID)
3771 {
3772     int		abort = FALSE;
3773     funccall_T	*fc;
3774 
3775     for (fc = current_funccal; fc != NULL; fc = fc->caller)
3776 	abort = abort || set_ref_in_funccal(fc, copyID);
3777     return abort;
3778 }
3779 
3780 /*
3781  * Set "copyID" in all functions available by name.
3782  */
3783     int
3784 set_ref_in_functions(int copyID)
3785 {
3786     int		todo;
3787     hashitem_T	*hi = NULL;
3788     int		abort = FALSE;
3789     ufunc_T	*fp;
3790 
3791     todo = (int)func_hashtab.ht_used;
3792     for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
3793     {
3794 	if (!HASHITEM_EMPTY(hi))
3795 	{
3796 	    --todo;
3797 	    fp = HI2UF(hi);
3798 	    if (!func_name_refcount(fp->uf_name))
3799 		abort = abort || set_ref_in_func(NULL, fp, copyID);
3800 	}
3801     }
3802     return abort;
3803 }
3804 
3805 /*
3806  * Set "copyID" in all function arguments.
3807  */
3808     int
3809 set_ref_in_func_args(int copyID)
3810 {
3811     int i;
3812     int abort = FALSE;
3813 
3814     for (i = 0; i < funcargs.ga_len; ++i)
3815 	abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
3816 							  copyID, NULL, NULL);
3817     return abort;
3818 }
3819 
3820 /*
3821  * Mark all lists and dicts referenced through function "name" with "copyID".
3822  * Returns TRUE if setting references failed somehow.
3823  */
3824     int
3825 set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
3826 {
3827     ufunc_T	*fp = fp_in;
3828     funccall_T	*fc;
3829     int		error = ERROR_NONE;
3830     char_u	fname_buf[FLEN_FIXED + 1];
3831     char_u	*tofree = NULL;
3832     char_u	*fname;
3833     int		abort = FALSE;
3834 
3835     if (name == NULL && fp_in == NULL)
3836 	return FALSE;
3837 
3838     if (fp_in == NULL)
3839     {
3840 	fname = fname_trans_sid(name, fname_buf, &tofree, &error);
3841 	fp = find_func(fname);
3842     }
3843     if (fp != NULL)
3844     {
3845 	for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped)
3846 	    abort = abort || set_ref_in_funccal(fc, copyID);
3847     }
3848     vim_free(tofree);
3849     return abort;
3850 }
3851 
3852 #endif /* FEAT_EVAL */
3853