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