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