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