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