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