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