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