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