blob: f9b0e81923ba13a4bbfd5abaaaba6a948e00c260 [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
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001375 /* Trigger FuncUndefined event, may load the function. */
1376 if (fp == NULL
1377 && apply_autocmds(EVENT_FUNCUNDEFINED,
1378 rfname, rfname, TRUE, NULL)
1379 && !aborting())
1380 {
1381 /* executed an autocommand, search for the function again */
1382 fp = find_func(rfname);
1383 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001384 /* Try loading a package. */
1385 if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
1386 {
1387 /* loaded a package, search for the function again */
1388 fp = find_func(rfname);
1389 }
1390
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001391 if (fp != NULL && (fp->uf_flags & FC_DELETED))
1392 error = ERROR_DELETED;
1393 else if (fp != NULL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001394 {
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001395 if (argv_func != NULL)
1396 argcount = argv_func(argcount, argvars, fp->uf_args.ga_len);
1397
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001398 if (fp->uf_flags & FC_RANGE)
1399 *doesrange = TRUE;
1400 if (argcount < fp->uf_args.ga_len)
1401 error = ERROR_TOOFEW;
1402 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
1403 error = ERROR_TOOMANY;
1404 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
1405 error = ERROR_DICT;
1406 else
1407 {
1408 int did_save_redo = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001409 save_redo_T save_redo;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001410
1411 /*
1412 * Call the user function.
1413 * Save and restore search patterns, script variables and
1414 * redo buffer.
1415 */
1416 save_search_patterns();
1417#ifdef FEAT_INS_EXPAND
1418 if (!ins_compl_active())
1419#endif
1420 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001421 saveRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001422 did_save_redo = TRUE;
1423 }
1424 ++fp->uf_calls;
1425 call_user_func(fp, argcount, argvars, rettv,
1426 firstline, lastline,
1427 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001428 if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001429 /* Function was unreferenced while being used, free it
1430 * now. */
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001431 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001432 if (did_save_redo)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001433 restoreRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001434 restore_search_patterns();
1435 error = ERROR_NONE;
1436 }
1437 }
1438 }
1439 else
1440 {
1441 /*
1442 * Find the function name in the table, call its implementation.
1443 */
1444 error = call_internal_func(fname, argcount, argvars, rettv);
1445 }
1446 /*
1447 * The function call (or "FuncUndefined" autocommand sequence) might
1448 * have been aborted by an error, an interrupt, or an explicitly thrown
1449 * exception that has not been caught so far. This situation can be
1450 * tested for by calling aborting(). For an error in an internal
1451 * function or for the "E132" error in call_user_func(), however, the
1452 * throw point at which the "force_abort" flag (temporarily reset by
1453 * emsg()) is normally updated has not been reached yet. We need to
1454 * update that flag first to make aborting() reliable.
1455 */
1456 update_force_abort();
1457 }
1458 if (error == ERROR_NONE)
1459 ret = OK;
1460
1461 /*
1462 * Report an error unless the argument evaluation or function call has been
1463 * cancelled due to an aborting error, an interrupt, or an exception.
1464 */
1465 if (!aborting())
1466 {
1467 switch (error)
1468 {
1469 case ERROR_UNKNOWN:
1470 emsg_funcname(N_("E117: Unknown function: %s"), name);
1471 break;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001472 case ERROR_DELETED:
1473 emsg_funcname(N_("E933: Function was deleted: %s"), name);
1474 break;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001475 case ERROR_TOOMANY:
1476 emsg_funcname((char *)e_toomanyarg, name);
1477 break;
1478 case ERROR_TOOFEW:
1479 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
1480 name);
1481 break;
1482 case ERROR_SCRIPT:
1483 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
1484 name);
1485 break;
1486 case ERROR_DICT:
1487 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
1488 name);
1489 break;
1490 }
1491 }
1492
1493 while (argv_clear > 0)
1494 clear_tv(&argv[--argv_clear]);
1495 vim_free(tofree);
1496 vim_free(name);
1497
1498 return ret;
1499}
1500
1501/*
1502 * List the head of the function: "name(arg1, arg2)".
1503 */
1504 static void
1505list_func_head(ufunc_T *fp, int indent)
1506{
1507 int j;
1508
1509 msg_start();
1510 if (indent)
1511 MSG_PUTS(" ");
1512 MSG_PUTS("function ");
1513 if (fp->uf_name[0] == K_SPECIAL)
1514 {
Bram Moolenaar8820b482017-03-16 17:23:31 +01001515 MSG_PUTS_ATTR("<SNR>", HL_ATTR(HLF_8));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001516 msg_puts(fp->uf_name + 3);
1517 }
1518 else
1519 msg_puts(fp->uf_name);
1520 msg_putchar('(');
1521 for (j = 0; j < fp->uf_args.ga_len; ++j)
1522 {
1523 if (j)
1524 MSG_PUTS(", ");
1525 msg_puts(FUNCARG(fp, j));
1526 }
1527 if (fp->uf_varargs)
1528 {
1529 if (j)
1530 MSG_PUTS(", ");
1531 MSG_PUTS("...");
1532 }
1533 msg_putchar(')');
1534 if (fp->uf_flags & FC_ABORT)
1535 MSG_PUTS(" abort");
1536 if (fp->uf_flags & FC_RANGE)
1537 MSG_PUTS(" range");
1538 if (fp->uf_flags & FC_DICT)
1539 MSG_PUTS(" dict");
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02001540 if (fp->uf_flags & FC_CLOSURE)
1541 MSG_PUTS(" closure");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001542 msg_clr_eos();
1543 if (p_verbose > 0)
1544 last_set_msg(fp->uf_script_ID);
1545}
1546
1547/*
1548 * Get a function name, translating "<SID>" and "<SNR>".
1549 * Also handles a Funcref in a List or Dictionary.
1550 * Returns the function name in allocated memory, or NULL for failure.
1551 * flags:
1552 * TFN_INT: internal function name OK
1553 * TFN_QUIET: be quiet
1554 * TFN_NO_AUTOLOAD: do not use script autoloading
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001555 * TFN_NO_DEREF: do not dereference a Funcref
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001556 * Advances "pp" to just after the function name (if no error).
1557 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001558 char_u *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001559trans_function_name(
1560 char_u **pp,
1561 int skip, /* only find the end, don't evaluate */
1562 int flags,
1563 funcdict_T *fdp, /* return: info about dictionary used */
1564 partial_T **partial) /* return: partial of a FuncRef */
1565{
1566 char_u *name = NULL;
1567 char_u *start;
1568 char_u *end;
1569 int lead;
1570 char_u sid_buf[20];
1571 int len;
1572 lval_T lv;
1573
1574 if (fdp != NULL)
1575 vim_memset(fdp, 0, sizeof(funcdict_T));
1576 start = *pp;
1577
1578 /* Check for hard coded <SNR>: already translated function ID (from a user
1579 * command). */
1580 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
1581 && (*pp)[2] == (int)KE_SNR)
1582 {
1583 *pp += 3;
1584 len = get_id_len(pp) + 3;
1585 return vim_strnsave(start, len);
1586 }
1587
1588 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
1589 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
1590 lead = eval_fname_script(start);
1591 if (lead > 2)
1592 start += lead;
1593
1594 /* Note that TFN_ flags use the same values as GLV_ flags. */
Bram Moolenaar6e65d592017-12-07 22:11:27 +01001595 end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001596 lead > 2 ? 0 : FNE_CHECK_START);
1597 if (end == start)
1598 {
1599 if (!skip)
1600 EMSG(_("E129: Function name required"));
1601 goto theend;
1602 }
1603 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
1604 {
1605 /*
1606 * Report an invalid expression in braces, unless the expression
1607 * evaluation has been cancelled due to an aborting error, an
1608 * interrupt, or an exception.
1609 */
1610 if (!aborting())
1611 {
1612 if (end != NULL)
1613 EMSG2(_(e_invarg2), start);
1614 }
1615 else
1616 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
1617 goto theend;
1618 }
1619
1620 if (lv.ll_tv != NULL)
1621 {
1622 if (fdp != NULL)
1623 {
1624 fdp->fd_dict = lv.ll_dict;
1625 fdp->fd_newkey = lv.ll_newkey;
1626 lv.ll_newkey = NULL;
1627 fdp->fd_di = lv.ll_di;
1628 }
1629 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
1630 {
1631 name = vim_strsave(lv.ll_tv->vval.v_string);
1632 *pp = end;
1633 }
1634 else if (lv.ll_tv->v_type == VAR_PARTIAL
1635 && lv.ll_tv->vval.v_partial != NULL)
1636 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001637 name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001638 *pp = end;
1639 if (partial != NULL)
1640 *partial = lv.ll_tv->vval.v_partial;
1641 }
1642 else
1643 {
1644 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
1645 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
1646 EMSG(_(e_funcref));
1647 else
1648 *pp = end;
1649 name = NULL;
1650 }
1651 goto theend;
1652 }
1653
1654 if (lv.ll_name == NULL)
1655 {
1656 /* Error found, but continue after the function name. */
1657 *pp = end;
1658 goto theend;
1659 }
1660
1661 /* Check if the name is a Funcref. If so, use the value. */
1662 if (lv.ll_exp_name != NULL)
1663 {
1664 len = (int)STRLEN(lv.ll_exp_name);
1665 name = deref_func_name(lv.ll_exp_name, &len, partial,
1666 flags & TFN_NO_AUTOLOAD);
1667 if (name == lv.ll_exp_name)
1668 name = NULL;
1669 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001670 else if (!(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001671 {
1672 len = (int)(end - *pp);
1673 name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD);
1674 if (name == *pp)
1675 name = NULL;
1676 }
1677 if (name != NULL)
1678 {
1679 name = vim_strsave(name);
1680 *pp = end;
1681 if (STRNCMP(name, "<SNR>", 5) == 0)
1682 {
1683 /* Change "<SNR>" to the byte sequence. */
1684 name[0] = K_SPECIAL;
1685 name[1] = KS_EXTRA;
1686 name[2] = (int)KE_SNR;
1687 mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
1688 }
1689 goto theend;
1690 }
1691
1692 if (lv.ll_exp_name != NULL)
1693 {
1694 len = (int)STRLEN(lv.ll_exp_name);
1695 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
1696 && STRNCMP(lv.ll_name, "s:", 2) == 0)
1697 {
1698 /* When there was "s:" already or the name expanded to get a
1699 * leading "s:" then remove it. */
1700 lv.ll_name += 2;
1701 len -= 2;
1702 lead = 2;
1703 }
1704 }
1705 else
1706 {
1707 /* skip over "s:" and "g:" */
1708 if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
1709 lv.ll_name += 2;
1710 len = (int)(end - lv.ll_name);
1711 }
1712
1713 /*
1714 * Copy the function name to allocated memory.
1715 * Accept <SID>name() inside a script, translate into <SNR>123_name().
1716 * Accept <SNR>123_name() outside a script.
1717 */
1718 if (skip)
1719 lead = 0; /* do nothing */
1720 else if (lead > 0)
1721 {
1722 lead = 3;
1723 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
1724 || eval_fname_sid(*pp))
1725 {
1726 /* It's "s:" or "<SID>" */
1727 if (current_SID <= 0)
1728 {
1729 EMSG(_(e_usingsid));
1730 goto theend;
1731 }
1732 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
1733 lead += (int)STRLEN(sid_buf);
1734 }
1735 }
1736 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
1737 {
1738 EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"),
1739 start);
1740 goto theend;
1741 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001742 if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001743 {
1744 char_u *cp = vim_strchr(lv.ll_name, ':');
1745
1746 if (cp != NULL && cp < end)
1747 {
1748 EMSG2(_("E884: Function name cannot contain a colon: %s"), start);
1749 goto theend;
1750 }
1751 }
1752
1753 name = alloc((unsigned)(len + lead + 1));
1754 if (name != NULL)
1755 {
1756 if (lead > 0)
1757 {
1758 name[0] = K_SPECIAL;
1759 name[1] = KS_EXTRA;
1760 name[2] = (int)KE_SNR;
1761 if (lead > 3) /* If it's "<SID>" */
1762 STRCPY(name + 3, sid_buf);
1763 }
1764 mch_memmove(name + lead, lv.ll_name, (size_t)len);
1765 name[lead + len] = NUL;
1766 }
1767 *pp = end;
1768
1769theend:
1770 clear_lval(&lv);
1771 return name;
1772}
1773
1774/*
1775 * ":function"
1776 */
1777 void
1778ex_function(exarg_T *eap)
1779{
1780 char_u *theline;
Bram Moolenaar53564f72017-06-24 14:48:11 +02001781 char_u *line_to_free = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001782 int j;
1783 int c;
1784 int saved_did_emsg;
1785 int saved_wait_return = need_wait_return;
1786 char_u *name = NULL;
1787 char_u *p;
1788 char_u *arg;
1789 char_u *line_arg = NULL;
1790 garray_T newargs;
1791 garray_T newlines;
1792 int varargs = FALSE;
1793 int flags = 0;
1794 ufunc_T *fp;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001795 int overwrite = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001796 int indent;
1797 int nesting;
1798 char_u *skip_until = NULL;
1799 dictitem_T *v;
1800 funcdict_T fudi;
1801 static int func_nr = 0; /* number for nameless function */
1802 int paren;
1803 hashtab_T *ht;
1804 int todo;
1805 hashitem_T *hi;
1806 int sourcing_lnum_off;
1807
1808 /*
1809 * ":function" without argument: list functions.
1810 */
1811 if (ends_excmd(*eap->arg))
1812 {
1813 if (!eap->skip)
1814 {
1815 todo = (int)func_hashtab.ht_used;
1816 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1817 {
1818 if (!HASHITEM_EMPTY(hi))
1819 {
1820 --todo;
1821 fp = HI2UF(hi);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001822 if (!func_name_refcount(fp->uf_name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001823 list_func_head(fp, FALSE);
1824 }
1825 }
1826 }
1827 eap->nextcmd = check_nextcmd(eap->arg);
1828 return;
1829 }
1830
1831 /*
1832 * ":function /pat": list functions matching pattern.
1833 */
1834 if (*eap->arg == '/')
1835 {
1836 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
1837 if (!eap->skip)
1838 {
1839 regmatch_T regmatch;
1840
1841 c = *p;
1842 *p = NUL;
1843 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
1844 *p = c;
1845 if (regmatch.regprog != NULL)
1846 {
1847 regmatch.rm_ic = p_ic;
1848
1849 todo = (int)func_hashtab.ht_used;
1850 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1851 {
1852 if (!HASHITEM_EMPTY(hi))
1853 {
1854 --todo;
1855 fp = HI2UF(hi);
1856 if (!isdigit(*fp->uf_name)
1857 && vim_regexec(&regmatch, fp->uf_name, 0))
1858 list_func_head(fp, FALSE);
1859 }
1860 }
1861 vim_regfree(regmatch.regprog);
1862 }
1863 }
1864 if (*p == '/')
1865 ++p;
1866 eap->nextcmd = check_nextcmd(p);
1867 return;
1868 }
1869
1870 /*
1871 * Get the function name. There are these situations:
1872 * func normal function name
1873 * "name" == func, "fudi.fd_dict" == NULL
1874 * dict.func new dictionary entry
1875 * "name" == NULL, "fudi.fd_dict" set,
1876 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
1877 * dict.func existing dict entry with a Funcref
1878 * "name" == func, "fudi.fd_dict" set,
1879 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1880 * dict.func existing dict entry that's not a Funcref
1881 * "name" == NULL, "fudi.fd_dict" set,
1882 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1883 * s:func script-local function name
1884 * g:func global function name, same as "func"
1885 */
1886 p = eap->arg;
Bram Moolenaar3388d332017-12-07 22:23:04 +01001887 name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001888 paren = (vim_strchr(p, '(') != NULL);
1889 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
1890 {
1891 /*
1892 * Return on an invalid expression in braces, unless the expression
1893 * evaluation has been cancelled due to an aborting error, an
1894 * interrupt, or an exception.
1895 */
1896 if (!aborting())
1897 {
1898 if (!eap->skip && fudi.fd_newkey != NULL)
1899 EMSG2(_(e_dictkey), fudi.fd_newkey);
1900 vim_free(fudi.fd_newkey);
1901 return;
1902 }
1903 else
1904 eap->skip = TRUE;
1905 }
1906
1907 /* An error in a function call during evaluation of an expression in magic
1908 * braces should not cause the function not to be defined. */
1909 saved_did_emsg = did_emsg;
1910 did_emsg = FALSE;
1911
1912 /*
1913 * ":function func" with only function name: list function.
1914 */
1915 if (!paren)
1916 {
1917 if (!ends_excmd(*skipwhite(p)))
1918 {
1919 EMSG(_(e_trailing));
1920 goto ret_free;
1921 }
1922 eap->nextcmd = check_nextcmd(p);
1923 if (eap->nextcmd != NULL)
1924 *p = NUL;
1925 if (!eap->skip && !got_int)
1926 {
1927 fp = find_func(name);
1928 if (fp != NULL)
1929 {
1930 list_func_head(fp, TRUE);
1931 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
1932 {
1933 if (FUNCLINE(fp, j) == NULL)
1934 continue;
1935 msg_putchar('\n');
1936 msg_outnum((long)(j + 1));
1937 if (j < 9)
1938 msg_putchar(' ');
1939 if (j < 99)
1940 msg_putchar(' ');
1941 msg_prt_line(FUNCLINE(fp, j), FALSE);
1942 out_flush(); /* show a line at a time */
1943 ui_breakcheck();
1944 }
1945 if (!got_int)
1946 {
1947 msg_putchar('\n');
1948 msg_puts((char_u *)" endfunction");
1949 }
1950 }
1951 else
1952 emsg_funcname(N_("E123: Undefined function: %s"), name);
1953 }
1954 goto ret_free;
1955 }
1956
1957 /*
1958 * ":function name(arg1, arg2)" Define function.
1959 */
1960 p = skipwhite(p);
1961 if (*p != '(')
1962 {
1963 if (!eap->skip)
1964 {
1965 EMSG2(_("E124: Missing '(': %s"), eap->arg);
1966 goto ret_free;
1967 }
1968 /* attempt to continue by skipping some text */
1969 if (vim_strchr(p, '(') != NULL)
1970 p = vim_strchr(p, '(');
1971 }
1972 p = skipwhite(p + 1);
1973
1974 ga_init2(&newlines, (int)sizeof(char_u *), 3);
1975
1976 if (!eap->skip)
1977 {
1978 /* Check the name of the function. Unless it's a dictionary function
1979 * (that we are overwriting). */
1980 if (name != NULL)
1981 arg = name;
1982 else
1983 arg = fudi.fd_newkey;
1984 if (arg != NULL && (fudi.fd_di == NULL
1985 || (fudi.fd_di->di_tv.v_type != VAR_FUNC
1986 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL)))
1987 {
1988 if (*arg == K_SPECIAL)
1989 j = 3;
1990 else
1991 j = 0;
1992 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
1993 : eval_isnamec(arg[j])))
1994 ++j;
1995 if (arg[j] != NUL)
1996 emsg_funcname((char *)e_invarg2, arg);
1997 }
1998 /* Disallow using the g: dict. */
1999 if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
2000 EMSG(_("E862: Cannot use g: here"));
2001 }
2002
2003 if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL)
2004 goto errret_2;
2005
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002006 /* find extra arguments "range", "dict", "abort" and "closure" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002007 for (;;)
2008 {
2009 p = skipwhite(p);
2010 if (STRNCMP(p, "range", 5) == 0)
2011 {
2012 flags |= FC_RANGE;
2013 p += 5;
2014 }
2015 else if (STRNCMP(p, "dict", 4) == 0)
2016 {
2017 flags |= FC_DICT;
2018 p += 4;
2019 }
2020 else if (STRNCMP(p, "abort", 5) == 0)
2021 {
2022 flags |= FC_ABORT;
2023 p += 5;
2024 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002025 else if (STRNCMP(p, "closure", 7) == 0)
2026 {
2027 flags |= FC_CLOSURE;
2028 p += 7;
Bram Moolenaar58016442016-07-31 18:30:22 +02002029 if (current_funccal == NULL)
2030 {
Bram Moolenaarba209902016-08-24 22:06:38 +02002031 emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
Bram Moolenaar58016442016-07-31 18:30:22 +02002032 name == NULL ? (char_u *)"" : name);
2033 goto erret;
2034 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002035 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002036 else
2037 break;
2038 }
2039
2040 /* When there is a line break use what follows for the function body.
2041 * Makes 'exe "func Test()\n...\nendfunc"' work. */
2042 if (*p == '\n')
2043 line_arg = p + 1;
2044 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
2045 EMSG(_(e_trailing));
2046
2047 /*
2048 * Read the body of the function, until ":endfunction" is found.
2049 */
2050 if (KeyTyped)
2051 {
2052 /* Check if the function already exists, don't let the user type the
2053 * whole function before telling him it doesn't work! For a script we
2054 * need to skip the body to be able to find what follows. */
2055 if (!eap->skip && !eap->forceit)
2056 {
2057 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
2058 EMSG(_(e_funcdict));
2059 else if (name != NULL && find_func(name) != NULL)
2060 emsg_funcname(e_funcexts, name);
2061 }
2062
2063 if (!eap->skip && did_emsg)
2064 goto erret;
2065
2066 msg_putchar('\n'); /* don't overwrite the function name */
2067 cmdline_row = msg_row;
2068 }
2069
2070 indent = 2;
2071 nesting = 0;
2072 for (;;)
2073 {
2074 if (KeyTyped)
2075 {
2076 msg_scroll = TRUE;
2077 saved_wait_return = FALSE;
2078 }
2079 need_wait_return = FALSE;
2080 sourcing_lnum_off = sourcing_lnum;
2081
2082 if (line_arg != NULL)
2083 {
2084 /* Use eap->arg, split up in parts by line breaks. */
2085 theline = line_arg;
2086 p = vim_strchr(theline, '\n');
2087 if (p == NULL)
2088 line_arg += STRLEN(line_arg);
2089 else
2090 {
2091 *p = NUL;
2092 line_arg = p + 1;
2093 }
2094 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002095 else
Bram Moolenaar53564f72017-06-24 14:48:11 +02002096 {
2097 vim_free(line_to_free);
2098 if (eap->getline == NULL)
2099 theline = getcmdline(':', 0L, indent);
2100 else
2101 theline = eap->getline(':', eap->cookie, indent);
2102 line_to_free = theline;
2103 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002104 if (KeyTyped)
2105 lines_left = Rows - 1;
2106 if (theline == NULL)
2107 {
2108 EMSG(_("E126: Missing :endfunction"));
2109 goto erret;
2110 }
2111
2112 /* Detect line continuation: sourcing_lnum increased more than one. */
2113 if (sourcing_lnum > sourcing_lnum_off + 1)
2114 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
2115 else
2116 sourcing_lnum_off = 0;
2117
2118 if (skip_until != NULL)
2119 {
2120 /* between ":append" and "." and between ":python <<EOF" and "EOF"
2121 * don't check for ":endfunc". */
2122 if (STRCMP(theline, skip_until) == 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01002123 VIM_CLEAR(skip_until);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002124 }
2125 else
2126 {
2127 /* skip ':' and blanks*/
Bram Moolenaar1c465442017-03-12 20:10:05 +01002128 for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002129 ;
2130
2131 /* Check for "endfunction". */
2132 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
2133 {
Bram Moolenaar53564f72017-06-24 14:48:11 +02002134 char_u *nextcmd = NULL;
2135
Bram Moolenaar663bb232017-06-22 19:12:10 +02002136 if (*p == '|')
Bram Moolenaar53564f72017-06-24 14:48:11 +02002137 nextcmd = p + 1;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002138 else if (line_arg != NULL && *skipwhite(line_arg) != NUL)
Bram Moolenaar53564f72017-06-24 14:48:11 +02002139 nextcmd = line_arg;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002140 else if (*p != NUL && *p != '"' && p_verbose > 0)
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002141 give_warning2(
2142 (char_u *)_("W22: Text found after :endfunction: %s"),
2143 p, TRUE);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002144 if (nextcmd != NULL)
2145 {
2146 /* Another command follows. If the line came from "eap" we
2147 * can simply point into it, otherwise we need to change
2148 * "eap->cmdlinep". */
2149 eap->nextcmd = nextcmd;
2150 if (line_to_free != NULL)
2151 {
2152 vim_free(*eap->cmdlinep);
2153 *eap->cmdlinep = line_to_free;
2154 line_to_free = NULL;
2155 }
2156 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002157 break;
2158 }
2159
2160 /* Increase indent inside "if", "while", "for" and "try", decrease
2161 * at "end". */
2162 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
2163 indent -= 2;
2164 else if (STRNCMP(p, "if", 2) == 0
2165 || STRNCMP(p, "wh", 2) == 0
2166 || STRNCMP(p, "for", 3) == 0
2167 || STRNCMP(p, "try", 3) == 0)
2168 indent += 2;
2169
2170 /* Check for defining a function inside this function. */
2171 if (checkforcmd(&p, "function", 2))
2172 {
2173 if (*p == '!')
2174 p = skipwhite(p + 1);
2175 p += eval_fname_script(p);
2176 vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL));
2177 if (*skipwhite(p) == '(')
2178 {
2179 ++nesting;
2180 indent += 2;
2181 }
2182 }
2183
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002184 /* Check for ":append", ":change", ":insert". */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002185 p = skip_range(p, NULL);
2186 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002187 || (p[0] == 'c'
2188 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
2189 && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
2190 && (STRNCMP(&p[3], "nge", 3) != 0
2191 || !ASCII_ISALPHA(p[6])))))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002192 || (p[0] == 'i'
2193 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
2194 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
2195 skip_until = vim_strsave((char_u *)".");
2196
2197 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
2198 arg = skipwhite(skiptowhite(p));
2199 if (arg[0] == '<' && arg[1] =='<'
2200 && ((p[0] == 'p' && p[1] == 'y'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +01002201 && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2202 || ((p[2] == '3' || p[2] == 'x')
2203 && !ASCII_ISALPHA(p[3]))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002204 || (p[0] == 'p' && p[1] == 'e'
2205 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2206 || (p[0] == 't' && p[1] == 'c'
2207 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2208 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2209 && !ASCII_ISALPHA(p[3]))
2210 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2211 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2212 || (p[0] == 'm' && p[1] == 'z'
2213 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
2214 ))
2215 {
2216 /* ":python <<" continues until a dot, like ":append" */
2217 p = skipwhite(arg + 2);
2218 if (*p == NUL)
2219 skip_until = vim_strsave((char_u *)".");
2220 else
2221 skip_until = vim_strsave(p);
2222 }
2223 }
2224
2225 /* Add the line to the function. */
2226 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002227 goto erret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002228
2229 /* Copy the line to newly allocated memory. get_one_sourceline()
2230 * allocates 250 bytes per line, this saves 80% on average. The cost
2231 * is an extra alloc/free. */
2232 p = vim_strsave(theline);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002233 if (p == NULL)
2234 goto erret;
2235 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002236
2237 /* Add NULL lines for continuation lines, so that the line count is
2238 * equal to the index in the growarray. */
2239 while (sourcing_lnum_off-- > 0)
2240 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
2241
2242 /* Check for end of eap->arg. */
2243 if (line_arg != NULL && *line_arg == NUL)
2244 line_arg = NULL;
2245 }
2246
2247 /* Don't define the function when skipping commands or when an error was
2248 * detected. */
2249 if (eap->skip || did_emsg)
2250 goto erret;
2251
2252 /*
2253 * If there are no errors, add the function
2254 */
2255 if (fudi.fd_dict == NULL)
2256 {
2257 v = find_var(name, &ht, FALSE);
2258 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
2259 {
2260 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
2261 name);
2262 goto erret;
2263 }
2264
2265 fp = find_func(name);
2266 if (fp != NULL)
2267 {
2268 if (!eap->forceit)
2269 {
2270 emsg_funcname(e_funcexts, name);
2271 goto erret;
2272 }
2273 if (fp->uf_calls > 0)
2274 {
2275 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
2276 name);
2277 goto erret;
2278 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002279 if (fp->uf_refcount > 1)
2280 {
2281 /* This function is referenced somewhere, don't redefine it but
2282 * create a new one. */
2283 --fp->uf_refcount;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002284 fp->uf_flags |= FC_REMOVED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002285 fp = NULL;
2286 overwrite = TRUE;
2287 }
2288 else
2289 {
2290 /* redefine existing function */
2291 ga_clear_strings(&(fp->uf_args));
2292 ga_clear_strings(&(fp->uf_lines));
Bram Moolenaard23a8232018-02-10 18:45:26 +01002293 VIM_CLEAR(name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002294 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002295 }
2296 }
2297 else
2298 {
2299 char numbuf[20];
2300
2301 fp = NULL;
2302 if (fudi.fd_newkey == NULL && !eap->forceit)
2303 {
2304 EMSG(_(e_funcdict));
2305 goto erret;
2306 }
2307 if (fudi.fd_di == NULL)
2308 {
2309 /* Can't add a function to a locked dictionary */
2310 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE))
2311 goto erret;
2312 }
2313 /* Can't change an existing function if it is locked */
2314 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE))
2315 goto erret;
2316
2317 /* Give the function a sequential number. Can only be used with a
2318 * Funcref! */
2319 vim_free(name);
2320 sprintf(numbuf, "%d", ++func_nr);
2321 name = vim_strsave((char_u *)numbuf);
2322 if (name == NULL)
2323 goto erret;
2324 }
2325
2326 if (fp == NULL)
2327 {
2328 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
2329 {
2330 int slen, plen;
2331 char_u *scriptname;
2332
2333 /* Check that the autoload name matches the script name. */
2334 j = FAIL;
2335 if (sourcing_name != NULL)
2336 {
2337 scriptname = autoload_name(name);
2338 if (scriptname != NULL)
2339 {
2340 p = vim_strchr(scriptname, '/');
2341 plen = (int)STRLEN(p);
2342 slen = (int)STRLEN(sourcing_name);
2343 if (slen > plen && fnamecmp(p,
2344 sourcing_name + slen - plen) == 0)
2345 j = OK;
2346 vim_free(scriptname);
2347 }
2348 }
2349 if (j == FAIL)
2350 {
2351 EMSG2(_("E746: Function name does not match script file name: %s"), name);
2352 goto erret;
2353 }
2354 }
2355
Bram Moolenaar58016442016-07-31 18:30:22 +02002356 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002357 if (fp == NULL)
2358 goto erret;
2359
2360 if (fudi.fd_dict != NULL)
2361 {
2362 if (fudi.fd_di == NULL)
2363 {
2364 /* add new dict entry */
2365 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
2366 if (fudi.fd_di == NULL)
2367 {
2368 vim_free(fp);
2369 goto erret;
2370 }
2371 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
2372 {
2373 vim_free(fudi.fd_di);
2374 vim_free(fp);
2375 goto erret;
2376 }
2377 }
2378 else
2379 /* overwrite existing dict entry */
2380 clear_tv(&fudi.fd_di->di_tv);
2381 fudi.fd_di->di_tv.v_type = VAR_FUNC;
2382 fudi.fd_di->di_tv.v_lock = 0;
2383 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002384
2385 /* behave like "dict" was used */
2386 flags |= FC_DICT;
2387 }
2388
2389 /* insert the new function in the function list */
2390 STRCPY(fp->uf_name, name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002391 if (overwrite)
2392 {
2393 hi = hash_find(&func_hashtab, name);
2394 hi->hi_key = UF2HIKEY(fp);
2395 }
2396 else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002397 {
2398 vim_free(fp);
2399 goto erret;
2400 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002401 fp->uf_refcount = 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002402 }
2403 fp->uf_args = newargs;
2404 fp->uf_lines = newlines;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002405 if ((flags & FC_CLOSURE) != 0)
2406 {
Bram Moolenaar58016442016-07-31 18:30:22 +02002407 if (register_closure(fp) == FAIL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002408 goto erret;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002409 }
2410 else
2411 fp->uf_scoped = NULL;
2412
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002413#ifdef FEAT_PROFILE
2414 fp->uf_tml_count = NULL;
2415 fp->uf_tml_total = NULL;
2416 fp->uf_tml_self = NULL;
2417 fp->uf_profiling = FALSE;
2418 if (prof_def_func())
2419 func_do_profile(fp);
2420#endif
2421 fp->uf_varargs = varargs;
2422 fp->uf_flags = flags;
2423 fp->uf_calls = 0;
2424 fp->uf_script_ID = current_SID;
2425 goto ret_free;
2426
2427erret:
2428 ga_clear_strings(&newargs);
2429errret_2:
2430 ga_clear_strings(&newlines);
2431ret_free:
2432 vim_free(skip_until);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002433 vim_free(line_to_free);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002434 vim_free(fudi.fd_newkey);
2435 vim_free(name);
2436 did_emsg |= saved_did_emsg;
2437 need_wait_return |= saved_wait_return;
2438}
2439
2440/*
2441 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
2442 * Return 2 if "p" starts with "s:".
2443 * Return 0 otherwise.
2444 */
2445 int
2446eval_fname_script(char_u *p)
2447{
2448 /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with
2449 * the standard library function. */
2450 if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0
2451 || MB_STRNICMP(p + 1, "SNR>", 4) == 0))
2452 return 5;
2453 if (p[0] == 's' && p[1] == ':')
2454 return 2;
2455 return 0;
2456}
2457
2458 int
2459translated_function_exists(char_u *name)
2460{
2461 if (builtin_function(name, -1))
2462 return find_internal_func(name) >= 0;
2463 return find_func(name) != NULL;
2464}
2465
2466/*
2467 * Return TRUE if a function "name" exists.
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002468 * If "no_defef" is TRUE, do not dereference a Funcref.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002469 */
2470 int
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002471function_exists(char_u *name, int no_deref)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002472{
2473 char_u *nm = name;
2474 char_u *p;
2475 int n = FALSE;
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002476 int flag;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002477
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002478 flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
2479 if (no_deref)
2480 flag |= TFN_NO_DEREF;
2481 p = trans_function_name(&nm, FALSE, flag, NULL, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002482 nm = skipwhite(nm);
2483
2484 /* Only accept "funcname", "funcname ", "funcname (..." and
2485 * "funcname(...", not "funcname!...". */
2486 if (p != NULL && (*nm == NUL || *nm == '('))
2487 n = translated_function_exists(p);
2488 vim_free(p);
2489 return n;
2490}
2491
2492 char_u *
2493get_expanded_name(char_u *name, int check)
2494{
2495 char_u *nm = name;
2496 char_u *p;
2497
2498 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL);
2499
2500 if (p != NULL && *nm == NUL)
2501 if (!check || translated_function_exists(p))
2502 return p;
2503
2504 vim_free(p);
2505 return NULL;
2506}
2507
2508#if defined(FEAT_PROFILE) || defined(PROTO)
2509/*
2510 * Start profiling function "fp".
2511 */
2512 static void
2513func_do_profile(ufunc_T *fp)
2514{
2515 int len = fp->uf_lines.ga_len;
2516
2517 if (len == 0)
2518 len = 1; /* avoid getting error for allocating zero bytes */
2519 fp->uf_tm_count = 0;
2520 profile_zero(&fp->uf_tm_self);
2521 profile_zero(&fp->uf_tm_total);
2522 if (fp->uf_tml_count == NULL)
2523 fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len));
2524 if (fp->uf_tml_total == NULL)
2525 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
2526 (sizeof(proftime_T) * len));
2527 if (fp->uf_tml_self == NULL)
2528 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
2529 (sizeof(proftime_T) * len));
2530 fp->uf_tml_idx = -1;
2531 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
2532 || fp->uf_tml_self == NULL)
2533 return; /* out of memory */
2534
2535 fp->uf_profiling = TRUE;
2536}
2537
2538/*
2539 * Dump the profiling results for all functions in file "fd".
2540 */
2541 void
2542func_dump_profile(FILE *fd)
2543{
2544 hashitem_T *hi;
2545 int todo;
2546 ufunc_T *fp;
2547 int i;
2548 ufunc_T **sorttab;
2549 int st_len = 0;
2550
2551 todo = (int)func_hashtab.ht_used;
2552 if (todo == 0)
2553 return; /* nothing to dump */
2554
2555 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo));
2556
2557 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
2558 {
2559 if (!HASHITEM_EMPTY(hi))
2560 {
2561 --todo;
2562 fp = HI2UF(hi);
2563 if (fp->uf_profiling)
2564 {
2565 if (sorttab != NULL)
2566 sorttab[st_len++] = fp;
2567
2568 if (fp->uf_name[0] == K_SPECIAL)
2569 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
2570 else
2571 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
2572 if (fp->uf_tm_count == 1)
2573 fprintf(fd, "Called 1 time\n");
2574 else
2575 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
2576 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
2577 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
2578 fprintf(fd, "\n");
2579 fprintf(fd, "count total (s) self (s)\n");
2580
2581 for (i = 0; i < fp->uf_lines.ga_len; ++i)
2582 {
2583 if (FUNCLINE(fp, i) == NULL)
2584 continue;
2585 prof_func_line(fd, fp->uf_tml_count[i],
2586 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
2587 fprintf(fd, "%s\n", FUNCLINE(fp, i));
2588 }
2589 fprintf(fd, "\n");
2590 }
2591 }
2592 }
2593
2594 if (sorttab != NULL && st_len > 0)
2595 {
2596 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2597 prof_total_cmp);
2598 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
2599 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2600 prof_self_cmp);
2601 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
2602 }
2603
2604 vim_free(sorttab);
2605}
2606
2607 static void
2608prof_sort_list(
2609 FILE *fd,
2610 ufunc_T **sorttab,
2611 int st_len,
2612 char *title,
2613 int prefer_self) /* when equal print only self time */
2614{
2615 int i;
2616 ufunc_T *fp;
2617
2618 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
2619 fprintf(fd, "count total (s) self (s) function\n");
2620 for (i = 0; i < 20 && i < st_len; ++i)
2621 {
2622 fp = sorttab[i];
2623 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
2624 prefer_self);
2625 if (fp->uf_name[0] == K_SPECIAL)
2626 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
2627 else
2628 fprintf(fd, " %s()\n", fp->uf_name);
2629 }
2630 fprintf(fd, "\n");
2631}
2632
2633/*
2634 * Print the count and times for one function or function line.
2635 */
2636 static void
2637prof_func_line(
2638 FILE *fd,
2639 int count,
2640 proftime_T *total,
2641 proftime_T *self,
2642 int prefer_self) /* when equal print only self time */
2643{
2644 if (count > 0)
2645 {
2646 fprintf(fd, "%5d ", count);
2647 if (prefer_self && profile_equal(total, self))
2648 fprintf(fd, " ");
2649 else
2650 fprintf(fd, "%s ", profile_msg(total));
2651 if (!prefer_self && profile_equal(total, self))
2652 fprintf(fd, " ");
2653 else
2654 fprintf(fd, "%s ", profile_msg(self));
2655 }
2656 else
2657 fprintf(fd, " ");
2658}
2659
2660/*
2661 * Compare function for total time sorting.
2662 */
2663 static int
2664#ifdef __BORLANDC__
2665_RTLENTRYF
2666#endif
2667prof_total_cmp(const void *s1, const void *s2)
2668{
2669 ufunc_T *p1, *p2;
2670
2671 p1 = *(ufunc_T **)s1;
2672 p2 = *(ufunc_T **)s2;
2673 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
2674}
2675
2676/*
2677 * Compare function for self time sorting.
2678 */
2679 static int
2680#ifdef __BORLANDC__
2681_RTLENTRYF
2682#endif
2683prof_self_cmp(const void *s1, const void *s2)
2684{
2685 ufunc_T *p1, *p2;
2686
2687 p1 = *(ufunc_T **)s1;
2688 p2 = *(ufunc_T **)s2;
2689 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
2690}
2691
2692/*
2693 * Prepare profiling for entering a child or something else that is not
2694 * counted for the script/function itself.
2695 * Should always be called in pair with prof_child_exit().
2696 */
2697 void
2698prof_child_enter(
2699 proftime_T *tm) /* place to store waittime */
2700{
2701 funccall_T *fc = current_funccal;
2702
2703 if (fc != NULL && fc->func->uf_profiling)
2704 profile_start(&fc->prof_child);
2705 script_prof_save(tm);
2706}
2707
2708/*
2709 * Take care of time spent in a child.
2710 * Should always be called after prof_child_enter().
2711 */
2712 void
2713prof_child_exit(
2714 proftime_T *tm) /* where waittime was stored */
2715{
2716 funccall_T *fc = current_funccal;
2717
2718 if (fc != NULL && fc->func->uf_profiling)
2719 {
2720 profile_end(&fc->prof_child);
2721 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
2722 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
2723 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
2724 }
2725 script_prof_restore(tm);
2726}
2727
2728#endif /* FEAT_PROFILE */
2729
2730#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2731
2732/*
2733 * Function given to ExpandGeneric() to obtain the list of user defined
2734 * function names.
2735 */
2736 char_u *
2737get_user_func_name(expand_T *xp, int idx)
2738{
2739 static long_u done;
2740 static hashitem_T *hi;
2741 ufunc_T *fp;
2742
2743 if (idx == 0)
2744 {
2745 done = 0;
2746 hi = func_hashtab.ht_array;
2747 }
2748 if (done < func_hashtab.ht_used)
2749 {
2750 if (done++ > 0)
2751 ++hi;
2752 while (HASHITEM_EMPTY(hi))
2753 ++hi;
2754 fp = HI2UF(hi);
2755
Bram Moolenaarb49edc12016-07-23 15:47:34 +02002756 if ((fp->uf_flags & FC_DICT)
2757 || STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
2758 return (char_u *)""; /* don't show dict and lambda functions */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002759
2760 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
2761 return fp->uf_name; /* prevents overflow */
2762
2763 cat_func_name(IObuff, fp);
2764 if (xp->xp_context != EXPAND_USER_FUNC)
2765 {
2766 STRCAT(IObuff, "(");
2767 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
2768 STRCAT(IObuff, ")");
2769 }
2770 return IObuff;
2771 }
2772 return NULL;
2773}
2774
2775#endif /* FEAT_CMDL_COMPL */
2776
2777/*
2778 * ":delfunction {name}"
2779 */
2780 void
2781ex_delfunction(exarg_T *eap)
2782{
2783 ufunc_T *fp = NULL;
2784 char_u *p;
2785 char_u *name;
2786 funcdict_T fudi;
2787
2788 p = eap->arg;
2789 name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
2790 vim_free(fudi.fd_newkey);
2791 if (name == NULL)
2792 {
2793 if (fudi.fd_dict != NULL && !eap->skip)
2794 EMSG(_(e_funcref));
2795 return;
2796 }
2797 if (!ends_excmd(*skipwhite(p)))
2798 {
2799 vim_free(name);
2800 EMSG(_(e_trailing));
2801 return;
2802 }
2803 eap->nextcmd = check_nextcmd(p);
2804 if (eap->nextcmd != NULL)
2805 *p = NUL;
2806
2807 if (!eap->skip)
2808 fp = find_func(name);
2809 vim_free(name);
2810
2811 if (!eap->skip)
2812 {
2813 if (fp == NULL)
2814 {
Bram Moolenaard6abcd12017-06-22 19:15:24 +02002815 if (!eap->forceit)
2816 EMSG2(_(e_nofunc), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002817 return;
2818 }
2819 if (fp->uf_calls > 0)
2820 {
2821 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
2822 return;
2823 }
2824
2825 if (fudi.fd_dict != NULL)
2826 {
2827 /* Delete the dict item that refers to the function, it will
2828 * invoke func_unref() and possibly delete the function. */
2829 dictitem_remove(fudi.fd_dict, fudi.fd_di);
2830 }
2831 else
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002832 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002833 /* A normal function (not a numbered function or lambda) has a
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002834 * refcount of 1 for the entry in the hashtable. When deleting
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002835 * it and the refcount is more than one, it should be kept.
Bram Moolenaarba209902016-08-24 22:06:38 +02002836 * A numbered function and lambda should be kept if the refcount is
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002837 * one or more. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002838 if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002839 {
2840 /* Function is still referenced somewhere. Don't free it but
2841 * do remove it from the hashtable. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002842 if (func_remove(fp))
2843 fp->uf_refcount--;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002844 fp->uf_flags |= FC_DELETED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002845 }
2846 else
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002847 func_clear_free(fp, FALSE);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002848 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002849 }
2850}
2851
2852/*
2853 * Unreference a Function: decrement the reference count and free it when it
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002854 * becomes zero.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002855 */
2856 void
2857func_unref(char_u *name)
2858{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002859 ufunc_T *fp = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002860
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002861 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002862 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002863 fp = find_func(name);
2864 if (fp == NULL && isdigit(*name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002865 {
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002866#ifdef EXITFREE
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002867 if (!entered_free_all_mem)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002868#endif
Bram Moolenaar95f09602016-11-10 20:01:45 +01002869 internal_error("func_unref()");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002870 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002871 if (fp != NULL && --fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002872 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002873 /* Only delete it when it's not being used. Otherwise it's done
2874 * when "uf_calls" becomes zero. */
2875 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002876 func_clear_free(fp, FALSE);
Bram Moolenaar97baee82016-07-26 20:46:08 +02002877 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002878}
2879
2880/*
2881 * Unreference a Function: decrement the reference count and free it when it
2882 * becomes zero.
2883 */
2884 void
2885func_ptr_unref(ufunc_T *fp)
2886{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002887 if (fp != NULL && --fp->uf_refcount <= 0)
2888 {
2889 /* Only delete it when it's not being used. Otherwise it's done
2890 * when "uf_calls" becomes zero. */
2891 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002892 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002893 }
2894}
2895
2896/*
2897 * Count a reference to a Function.
2898 */
2899 void
2900func_ref(char_u *name)
2901{
2902 ufunc_T *fp;
2903
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002904 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002905 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002906 fp = find_func(name);
2907 if (fp != NULL)
2908 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002909 else if (isdigit(*name))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002910 /* Only give an error for a numbered function.
2911 * Fail silently, when named or lambda function isn't found. */
Bram Moolenaar95f09602016-11-10 20:01:45 +01002912 internal_error("func_ref()");
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002913}
2914
2915/*
2916 * Count a reference to a Function.
2917 */
2918 void
2919func_ptr_ref(ufunc_T *fp)
2920{
2921 if (fp != NULL)
2922 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002923}
2924
2925/*
2926 * Return TRUE if items in "fc" do not have "copyID". That means they are not
2927 * referenced from anywhere that is in use.
2928 */
2929 static int
2930can_free_funccal(funccall_T *fc, int copyID)
2931{
2932 return (fc->l_varlist.lv_copyID != copyID
2933 && fc->l_vars.dv_copyID != copyID
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02002934 && fc->l_avars.dv_copyID != copyID
2935 && fc->fc_copyID != copyID);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002936}
2937
2938/*
2939 * ":return [expr]"
2940 */
2941 void
2942ex_return(exarg_T *eap)
2943{
2944 char_u *arg = eap->arg;
2945 typval_T rettv;
2946 int returning = FALSE;
2947
2948 if (current_funccal == NULL)
2949 {
2950 EMSG(_("E133: :return not inside a function"));
2951 return;
2952 }
2953
2954 if (eap->skip)
2955 ++emsg_skip;
2956
2957 eap->nextcmd = NULL;
2958 if ((*arg != NUL && *arg != '|' && *arg != '\n')
2959 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
2960 {
2961 if (!eap->skip)
2962 returning = do_return(eap, FALSE, TRUE, &rettv);
2963 else
2964 clear_tv(&rettv);
2965 }
2966 /* It's safer to return also on error. */
2967 else if (!eap->skip)
2968 {
Bram Moolenaarfabaf752017-12-23 17:26:11 +01002969 /* In return statement, cause_abort should be force_abort. */
2970 update_force_abort();
2971
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002972 /*
2973 * Return unless the expression evaluation has been cancelled due to an
2974 * aborting error, an interrupt, or an exception.
2975 */
2976 if (!aborting())
2977 returning = do_return(eap, FALSE, TRUE, NULL);
2978 }
2979
2980 /* When skipping or the return gets pending, advance to the next command
2981 * in this line (!returning). Otherwise, ignore the rest of the line.
2982 * Following lines will be ignored by get_func_line(). */
2983 if (returning)
2984 eap->nextcmd = NULL;
2985 else if (eap->nextcmd == NULL) /* no argument */
2986 eap->nextcmd = check_nextcmd(arg);
2987
2988 if (eap->skip)
2989 --emsg_skip;
2990}
2991
2992/*
2993 * ":1,25call func(arg1, arg2)" function call.
2994 */
2995 void
2996ex_call(exarg_T *eap)
2997{
2998 char_u *arg = eap->arg;
2999 char_u *startarg;
3000 char_u *name;
3001 char_u *tofree;
3002 int len;
3003 typval_T rettv;
3004 linenr_T lnum;
3005 int doesrange;
3006 int failed = FALSE;
3007 funcdict_T fudi;
3008 partial_T *partial = NULL;
3009
3010 if (eap->skip)
3011 {
3012 /* trans_function_name() doesn't work well when skipping, use eval0()
3013 * instead to skip to any following command, e.g. for:
3014 * :if 0 | call dict.foo().bar() | endif */
3015 ++emsg_skip;
3016 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3017 clear_tv(&rettv);
3018 --emsg_skip;
3019 return;
3020 }
3021
3022 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial);
3023 if (fudi.fd_newkey != NULL)
3024 {
3025 /* Still need to give an error message for missing key. */
3026 EMSG2(_(e_dictkey), fudi.fd_newkey);
3027 vim_free(fudi.fd_newkey);
3028 }
3029 if (tofree == NULL)
3030 return;
3031
3032 /* Increase refcount on dictionary, it could get deleted when evaluating
3033 * the arguments. */
3034 if (fudi.fd_dict != NULL)
3035 ++fudi.fd_dict->dv_refcount;
3036
3037 /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3038 * contents. For VAR_PARTIAL get its partial, unless we already have one
3039 * from trans_function_name(). */
3040 len = (int)STRLEN(tofree);
3041 name = deref_func_name(tofree, &len,
3042 partial != NULL ? NULL : &partial, FALSE);
3043
3044 /* Skip white space to allow ":call func ()". Not good, but required for
3045 * backward compatibility. */
3046 startarg = skipwhite(arg);
3047 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3048
3049 if (*startarg != '(')
3050 {
3051 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3052 goto end;
3053 }
3054
3055 /*
3056 * When skipping, evaluate the function once, to find the end of the
3057 * arguments.
3058 * When the function takes a range, this is discovered after the first
3059 * call, and the loop is broken.
3060 */
3061 if (eap->skip)
3062 {
3063 ++emsg_skip;
3064 lnum = eap->line2; /* do it once, also with an invalid range */
3065 }
3066 else
3067 lnum = eap->line1;
3068 for ( ; lnum <= eap->line2; ++lnum)
3069 {
3070 if (!eap->skip && eap->addr_count > 0)
3071 {
3072 curwin->w_cursor.lnum = lnum;
3073 curwin->w_cursor.col = 0;
3074#ifdef FEAT_VIRTUALEDIT
3075 curwin->w_cursor.coladd = 0;
3076#endif
3077 }
3078 arg = startarg;
3079 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3080 eap->line1, eap->line2, &doesrange,
3081 !eap->skip, partial, fudi.fd_dict) == FAIL)
3082 {
3083 failed = TRUE;
3084 break;
3085 }
Bram Moolenaarc6f9f732018-02-11 19:06:26 +01003086 if (has_watchexpr())
3087 dbg_check_breakpoint(eap);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003088
3089 /* Handle a function returning a Funcref, Dictionary or List. */
3090 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3091 {
3092 failed = TRUE;
3093 break;
3094 }
3095
3096 clear_tv(&rettv);
3097 if (doesrange || eap->skip)
3098 break;
3099
3100 /* Stop when immediately aborting on error, or when an interrupt
3101 * occurred or an exception was thrown but not caught.
3102 * get_func_tv() returned OK, so that the check for trailing
3103 * characters below is executed. */
3104 if (aborting())
3105 break;
3106 }
3107 if (eap->skip)
3108 --emsg_skip;
3109
3110 if (!failed)
3111 {
3112 /* Check for trailing illegal characters and a following command. */
3113 if (!ends_excmd(*arg))
3114 {
3115 emsg_severe = TRUE;
3116 EMSG(_(e_trailing));
3117 }
3118 else
3119 eap->nextcmd = check_nextcmd(arg);
3120 }
3121
3122end:
3123 dict_unref(fudi.fd_dict);
3124 vim_free(tofree);
3125}
3126
3127/*
3128 * Return from a function. Possibly makes the return pending. Also called
3129 * for a pending return at the ":endtry" or after returning from an extra
3130 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
3131 * when called due to a ":return" command. "rettv" may point to a typval_T
3132 * with the return rettv. Returns TRUE when the return can be carried out,
3133 * FALSE when the return gets pending.
3134 */
3135 int
3136do_return(
3137 exarg_T *eap,
3138 int reanimate,
3139 int is_cmd,
3140 void *rettv)
3141{
3142 int idx;
3143 struct condstack *cstack = eap->cstack;
3144
3145 if (reanimate)
3146 /* Undo the return. */
3147 current_funccal->returned = FALSE;
3148
3149 /*
3150 * Cleanup (and inactivate) conditionals, but stop when a try conditional
3151 * not in its finally clause (which then is to be executed next) is found.
3152 * In this case, make the ":return" pending for execution at the ":endtry".
3153 * Otherwise, return normally.
3154 */
3155 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3156 if (idx >= 0)
3157 {
3158 cstack->cs_pending[idx] = CSTP_RETURN;
3159
3160 if (!is_cmd && !reanimate)
3161 /* A pending return again gets pending. "rettv" points to an
3162 * allocated variable with the rettv of the original ":return"'s
3163 * argument if present or is NULL else. */
3164 cstack->cs_rettv[idx] = rettv;
3165 else
3166 {
3167 /* When undoing a return in order to make it pending, get the stored
3168 * return rettv. */
3169 if (reanimate)
3170 rettv = current_funccal->rettv;
3171
3172 if (rettv != NULL)
3173 {
3174 /* Store the value of the pending return. */
3175 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
3176 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3177 else
3178 EMSG(_(e_outofmem));
3179 }
3180 else
3181 cstack->cs_rettv[idx] = NULL;
3182
3183 if (reanimate)
3184 {
3185 /* The pending return value could be overwritten by a ":return"
3186 * without argument in a finally clause; reset the default
3187 * return value. */
3188 current_funccal->rettv->v_type = VAR_NUMBER;
3189 current_funccal->rettv->vval.v_number = 0;
3190 }
3191 }
3192 report_make_pending(CSTP_RETURN, rettv);
3193 }
3194 else
3195 {
3196 current_funccal->returned = TRUE;
3197
3198 /* If the return is carried out now, store the return value. For
3199 * a return immediately after reanimation, the value is already
3200 * there. */
3201 if (!reanimate && rettv != NULL)
3202 {
3203 clear_tv(current_funccal->rettv);
3204 *current_funccal->rettv = *(typval_T *)rettv;
3205 if (!is_cmd)
3206 vim_free(rettv);
3207 }
3208 }
3209
3210 return idx < 0;
3211}
3212
3213/*
3214 * Free the variable with a pending return value.
3215 */
3216 void
3217discard_pending_return(void *rettv)
3218{
3219 free_tv((typval_T *)rettv);
3220}
3221
3222/*
3223 * Generate a return command for producing the value of "rettv". The result
3224 * is an allocated string. Used by report_pending() for verbose messages.
3225 */
3226 char_u *
3227get_return_cmd(void *rettv)
3228{
3229 char_u *s = NULL;
3230 char_u *tofree = NULL;
3231 char_u numbuf[NUMBUFLEN];
3232
3233 if (rettv != NULL)
3234 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
3235 if (s == NULL)
3236 s = (char_u *)"";
3237
3238 STRCPY(IObuff, ":return ");
3239 STRNCPY(IObuff + 8, s, IOSIZE - 8);
3240 if (STRLEN(s) + 8 >= IOSIZE)
3241 STRCPY(IObuff + IOSIZE - 4, "...");
3242 vim_free(tofree);
3243 return vim_strsave(IObuff);
3244}
3245
3246/*
3247 * Get next function line.
3248 * Called by do_cmdline() to get the next line.
3249 * Returns allocated string, or NULL for end of function.
3250 */
3251 char_u *
3252get_func_line(
3253 int c UNUSED,
3254 void *cookie,
3255 int indent UNUSED)
3256{
3257 funccall_T *fcp = (funccall_T *)cookie;
3258 ufunc_T *fp = fcp->func;
3259 char_u *retval;
3260 garray_T *gap; /* growarray with function lines */
3261
3262 /* If breakpoints have been added/deleted need to check for it. */
3263 if (fcp->dbg_tick != debug_tick)
3264 {
3265 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3266 sourcing_lnum);
3267 fcp->dbg_tick = debug_tick;
3268 }
3269#ifdef FEAT_PROFILE
3270 if (do_profiling == PROF_YES)
3271 func_line_end(cookie);
3272#endif
3273
3274 gap = &fp->uf_lines;
3275 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3276 || fcp->returned)
3277 retval = NULL;
3278 else
3279 {
3280 /* Skip NULL lines (continuation lines). */
3281 while (fcp->linenr < gap->ga_len
3282 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
3283 ++fcp->linenr;
3284 if (fcp->linenr >= gap->ga_len)
3285 retval = NULL;
3286 else
3287 {
3288 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
3289 sourcing_lnum = fcp->linenr;
3290#ifdef FEAT_PROFILE
3291 if (do_profiling == PROF_YES)
3292 func_line_start(cookie);
3293#endif
3294 }
3295 }
3296
3297 /* Did we encounter a breakpoint? */
3298 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
3299 {
3300 dbg_breakpoint(fp->uf_name, sourcing_lnum);
3301 /* Find next breakpoint. */
3302 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3303 sourcing_lnum);
3304 fcp->dbg_tick = debug_tick;
3305 }
3306
3307 return retval;
3308}
3309
3310#if defined(FEAT_PROFILE) || defined(PROTO)
3311/*
3312 * Called when starting to read a function line.
3313 * "sourcing_lnum" must be correct!
3314 * When skipping lines it may not actually be executed, but we won't find out
3315 * until later and we need to store the time now.
3316 */
3317 void
3318func_line_start(void *cookie)
3319{
3320 funccall_T *fcp = (funccall_T *)cookie;
3321 ufunc_T *fp = fcp->func;
3322
3323 if (fp->uf_profiling && sourcing_lnum >= 1
3324 && sourcing_lnum <= fp->uf_lines.ga_len)
3325 {
3326 fp->uf_tml_idx = sourcing_lnum - 1;
3327 /* Skip continuation lines. */
3328 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
3329 --fp->uf_tml_idx;
3330 fp->uf_tml_execed = FALSE;
3331 profile_start(&fp->uf_tml_start);
3332 profile_zero(&fp->uf_tml_children);
3333 profile_get_wait(&fp->uf_tml_wait);
3334 }
3335}
3336
3337/*
3338 * Called when actually executing a function line.
3339 */
3340 void
3341func_line_exec(void *cookie)
3342{
3343 funccall_T *fcp = (funccall_T *)cookie;
3344 ufunc_T *fp = fcp->func;
3345
3346 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3347 fp->uf_tml_execed = TRUE;
3348}
3349
3350/*
3351 * Called when done with a function line.
3352 */
3353 void
3354func_line_end(void *cookie)
3355{
3356 funccall_T *fcp = (funccall_T *)cookie;
3357 ufunc_T *fp = fcp->func;
3358
3359 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3360 {
3361 if (fp->uf_tml_execed)
3362 {
3363 ++fp->uf_tml_count[fp->uf_tml_idx];
3364 profile_end(&fp->uf_tml_start);
3365 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
3366 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
3367 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
3368 &fp->uf_tml_children);
3369 }
3370 fp->uf_tml_idx = -1;
3371 }
3372}
3373#endif
3374
3375/*
3376 * Return TRUE if the currently active function should be ended, because a
3377 * return was encountered or an error occurred. Used inside a ":while".
3378 */
3379 int
3380func_has_ended(void *cookie)
3381{
3382 funccall_T *fcp = (funccall_T *)cookie;
3383
3384 /* Ignore the "abort" flag if the abortion behavior has been changed due to
3385 * an error inside a try conditional. */
3386 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3387 || fcp->returned);
3388}
3389
3390/*
3391 * return TRUE if cookie indicates a function which "abort"s on errors.
3392 */
3393 int
3394func_has_abort(
3395 void *cookie)
3396{
3397 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
3398}
3399
3400
3401/*
3402 * Turn "dict.Func" into a partial for "Func" bound to "dict".
3403 * Don't do this when "Func" is already a partial that was bound
3404 * explicitly (pt_auto is FALSE).
3405 * Changes "rettv" in-place.
3406 * Returns the updated "selfdict_in".
3407 */
3408 dict_T *
3409make_partial(dict_T *selfdict_in, typval_T *rettv)
3410{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003411 char_u *fname;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003412 char_u *tofree = NULL;
3413 ufunc_T *fp;
3414 char_u fname_buf[FLEN_FIXED + 1];
3415 int error;
3416 dict_T *selfdict = selfdict_in;
3417
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003418 if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL)
3419 fp = rettv->vval.v_partial->pt_func;
3420 else
3421 {
3422 fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string
3423 : rettv->vval.v_partial->pt_name;
3424 /* Translate "s:func" to the stored function name. */
3425 fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3426 fp = find_func(fname);
3427 vim_free(tofree);
3428 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003429
3430 if (fp != NULL && (fp->uf_flags & FC_DICT))
3431 {
3432 partial_T *pt = (partial_T *)alloc_clear(sizeof(partial_T));
3433
3434 if (pt != NULL)
3435 {
3436 pt->pt_refcount = 1;
3437 pt->pt_dict = selfdict;
3438 pt->pt_auto = TRUE;
3439 selfdict = NULL;
3440 if (rettv->v_type == VAR_FUNC)
3441 {
3442 /* Just a function: Take over the function name and use
3443 * selfdict. */
3444 pt->pt_name = rettv->vval.v_string;
3445 }
3446 else
3447 {
3448 partial_T *ret_pt = rettv->vval.v_partial;
3449 int i;
3450
3451 /* Partial: copy the function name, use selfdict and copy
3452 * args. Can't take over name or args, the partial might
3453 * be referenced elsewhere. */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003454 if (ret_pt->pt_name != NULL)
3455 {
3456 pt->pt_name = vim_strsave(ret_pt->pt_name);
3457 func_ref(pt->pt_name);
3458 }
3459 else
3460 {
3461 pt->pt_func = ret_pt->pt_func;
3462 func_ptr_ref(pt->pt_func);
3463 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003464 if (ret_pt->pt_argc > 0)
3465 {
3466 pt->pt_argv = (typval_T *)alloc(
3467 sizeof(typval_T) * ret_pt->pt_argc);
3468 if (pt->pt_argv == NULL)
3469 /* out of memory: drop the arguments */
3470 pt->pt_argc = 0;
3471 else
3472 {
3473 pt->pt_argc = ret_pt->pt_argc;
3474 for (i = 0; i < pt->pt_argc; i++)
3475 copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3476 }
3477 }
3478 partial_unref(ret_pt);
3479 }
3480 rettv->v_type = VAR_PARTIAL;
3481 rettv->vval.v_partial = pt;
3482 }
3483 }
3484 return selfdict;
3485}
3486
3487/*
3488 * Return the name of the executed function.
3489 */
3490 char_u *
3491func_name(void *cookie)
3492{
3493 return ((funccall_T *)cookie)->func->uf_name;
3494}
3495
3496/*
3497 * Return the address holding the next breakpoint line for a funccall cookie.
3498 */
3499 linenr_T *
3500func_breakpoint(void *cookie)
3501{
3502 return &((funccall_T *)cookie)->breakpoint;
3503}
3504
3505/*
3506 * Return the address holding the debug tick for a funccall cookie.
3507 */
3508 int *
3509func_dbg_tick(void *cookie)
3510{
3511 return &((funccall_T *)cookie)->dbg_tick;
3512}
3513
3514/*
3515 * Return the nesting level for a funccall cookie.
3516 */
3517 int
3518func_level(void *cookie)
3519{
3520 return ((funccall_T *)cookie)->level;
3521}
3522
3523/*
3524 * Return TRUE when a function was ended by a ":return" command.
3525 */
3526 int
3527current_func_returned(void)
3528{
3529 return current_funccal->returned;
3530}
3531
3532/*
3533 * Save the current function call pointer, and set it to NULL.
3534 * Used when executing autocommands and for ":source".
3535 */
3536 void *
3537save_funccal(void)
3538{
3539 funccall_T *fc = current_funccal;
3540
3541 current_funccal = NULL;
3542 return (void *)fc;
3543}
3544
3545 void
3546restore_funccal(void *vfc)
3547{
3548 funccall_T *fc = (funccall_T *)vfc;
3549
3550 current_funccal = fc;
3551}
3552
3553 int
3554free_unref_funccal(int copyID, int testing)
3555{
3556 int did_free = FALSE;
3557 int did_free_funccal = FALSE;
3558 funccall_T *fc, **pfc;
3559
3560 for (pfc = &previous_funccal; *pfc != NULL; )
3561 {
3562 if (can_free_funccal(*pfc, copyID))
3563 {
3564 fc = *pfc;
3565 *pfc = fc->caller;
3566 free_funccal(fc, TRUE);
3567 did_free = TRUE;
3568 did_free_funccal = TRUE;
3569 }
3570 else
3571 pfc = &(*pfc)->caller;
3572 }
3573 if (did_free_funccal)
3574 /* When a funccal was freed some more items might be garbage
3575 * collected, so run again. */
3576 (void)garbage_collect(testing);
3577
3578 return did_free;
3579}
3580
3581/*
Bram Moolenaarba209902016-08-24 22:06:38 +02003582 * Get function call environment based on backtrace debug level
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003583 */
3584 static funccall_T *
3585get_funccal(void)
3586{
3587 int i;
3588 funccall_T *funccal;
3589 funccall_T *temp_funccal;
3590
3591 funccal = current_funccal;
3592 if (debug_backtrace_level > 0)
3593 {
3594 for (i = 0; i < debug_backtrace_level; i++)
3595 {
3596 temp_funccal = funccal->caller;
3597 if (temp_funccal)
3598 funccal = temp_funccal;
3599 else
3600 /* backtrace level overflow. reset to max */
3601 debug_backtrace_level = i;
3602 }
3603 }
3604 return funccal;
3605}
3606
3607/*
3608 * Return the hashtable used for local variables in the current funccal.
3609 * Return NULL if there is no current funccal.
3610 */
3611 hashtab_T *
3612get_funccal_local_ht()
3613{
3614 if (current_funccal == NULL)
3615 return NULL;
3616 return &get_funccal()->l_vars.dv_hashtab;
3617}
3618
3619/*
3620 * Return the l: scope variable.
3621 * Return NULL if there is no current funccal.
3622 */
3623 dictitem_T *
3624get_funccal_local_var()
3625{
3626 if (current_funccal == NULL)
3627 return NULL;
3628 return &get_funccal()->l_vars_var;
3629}
3630
3631/*
3632 * Return the hashtable used for argument in the current funccal.
3633 * Return NULL if there is no current funccal.
3634 */
3635 hashtab_T *
3636get_funccal_args_ht()
3637{
3638 if (current_funccal == NULL)
3639 return NULL;
3640 return &get_funccal()->l_avars.dv_hashtab;
3641}
3642
3643/*
3644 * Return the a: scope variable.
3645 * Return NULL if there is no current funccal.
3646 */
3647 dictitem_T *
3648get_funccal_args_var()
3649{
3650 if (current_funccal == NULL)
3651 return NULL;
Bram Moolenaarc7d9eac2017-02-01 20:26:51 +01003652 return &get_funccal()->l_avars_var;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003653}
3654
3655/*
3656 * Clear the current_funccal and return the old value.
3657 * Caller is expected to invoke restore_current_funccal().
3658 */
3659 void *
3660clear_current_funccal()
3661{
3662 funccall_T *f = current_funccal;
3663
3664 current_funccal = NULL;
3665 return f;
3666}
3667
3668 void
3669restore_current_funccal(void *f)
3670{
3671 current_funccal = f;
3672}
3673
3674/*
3675 * List function variables, if there is a function.
3676 */
3677 void
3678list_func_vars(int *first)
3679{
3680 if (current_funccal != NULL)
3681 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
3682 (char_u *)"l:", FALSE, first);
3683}
3684
3685/*
3686 * If "ht" is the hashtable for local variables in the current funccal, return
3687 * the dict that contains it.
3688 * Otherwise return NULL.
3689 */
3690 dict_T *
3691get_current_funccal_dict(hashtab_T *ht)
3692{
3693 if (current_funccal != NULL
3694 && ht == &current_funccal->l_vars.dv_hashtab)
3695 return &current_funccal->l_vars;
3696 return NULL;
3697}
3698
3699/*
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003700 * Search hashitem in parent scope.
3701 */
3702 hashitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003703find_hi_in_scoped_ht(char_u *name, hashtab_T **pht)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003704{
3705 funccall_T *old_current_funccal = current_funccal;
3706 hashtab_T *ht;
3707 hashitem_T *hi = NULL;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003708 char_u *varname;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003709
3710 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3711 return NULL;
3712
3713 /* Search in parent scope which is possible to reference from lambda */
3714 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar58016442016-07-31 18:30:22 +02003715 while (current_funccal != NULL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003716 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003717 ht = find_var_ht(name, &varname);
3718 if (ht != NULL && *varname != NUL)
Bram Moolenaar58016442016-07-31 18:30:22 +02003719 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003720 hi = hash_find(ht, varname);
Bram Moolenaar58016442016-07-31 18:30:22 +02003721 if (!HASHITEM_EMPTY(hi))
3722 {
3723 *pht = ht;
3724 break;
3725 }
3726 }
3727 if (current_funccal == current_funccal->func->uf_scoped)
3728 break;
3729 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003730 }
3731 current_funccal = old_current_funccal;
3732
3733 return hi;
3734}
3735
3736/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003737 * Search variable in parent scope.
3738 */
3739 dictitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003740find_var_in_scoped_ht(char_u *name, int no_autoload)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003741{
3742 dictitem_T *v = NULL;
3743 funccall_T *old_current_funccal = current_funccal;
3744 hashtab_T *ht;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003745 char_u *varname;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003746
3747 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3748 return NULL;
3749
3750 /* Search in parent scope which is possible to reference from lambda */
3751 current_funccal = current_funccal->func->uf_scoped;
3752 while (current_funccal)
3753 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003754 ht = find_var_ht(name, &varname);
3755 if (ht != NULL && *varname != NUL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003756 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003757 v = find_var_in_ht(ht, *name, varname, no_autoload);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003758 if (v != NULL)
3759 break;
3760 }
3761 if (current_funccal == current_funccal->func->uf_scoped)
3762 break;
3763 current_funccal = current_funccal->func->uf_scoped;
3764 }
3765 current_funccal = old_current_funccal;
3766
3767 return v;
3768}
3769
3770/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003771 * Set "copyID + 1" in previous_funccal and callers.
3772 */
3773 int
3774set_ref_in_previous_funccal(int copyID)
3775{
3776 int abort = FALSE;
3777 funccall_T *fc;
3778
3779 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
3780 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003781 fc->fc_copyID = copyID + 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003782 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1,
3783 NULL);
3784 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1,
3785 NULL);
3786 }
3787 return abort;
3788}
3789
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003790 static int
3791set_ref_in_funccal(funccall_T *fc, int copyID)
3792{
3793 int abort = FALSE;
3794
3795 if (fc->fc_copyID != copyID)
3796 {
3797 fc->fc_copyID = copyID;
3798 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL);
3799 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL);
3800 abort = abort || set_ref_in_func(NULL, fc->func, copyID);
3801 }
3802 return abort;
3803}
3804
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003805/*
3806 * Set "copyID" in all local vars and arguments in the call stack.
3807 */
3808 int
3809set_ref_in_call_stack(int copyID)
3810{
3811 int abort = FALSE;
3812 funccall_T *fc;
3813
3814 for (fc = current_funccal; fc != NULL; fc = fc->caller)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003815 abort = abort || set_ref_in_funccal(fc, copyID);
3816 return abort;
3817}
3818
3819/*
3820 * Set "copyID" in all functions available by name.
3821 */
3822 int
3823set_ref_in_functions(int copyID)
3824{
3825 int todo;
3826 hashitem_T *hi = NULL;
3827 int abort = FALSE;
3828 ufunc_T *fp;
3829
3830 todo = (int)func_hashtab.ht_used;
3831 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003832 {
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003833 if (!HASHITEM_EMPTY(hi))
3834 {
3835 --todo;
3836 fp = HI2UF(hi);
3837 if (!func_name_refcount(fp->uf_name))
3838 abort = abort || set_ref_in_func(NULL, fp, copyID);
3839 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003840 }
3841 return abort;
3842}
3843
3844/*
3845 * Set "copyID" in all function arguments.
3846 */
3847 int
3848set_ref_in_func_args(int copyID)
3849{
3850 int i;
3851 int abort = FALSE;
3852
3853 for (i = 0; i < funcargs.ga_len; ++i)
3854 abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
3855 copyID, NULL, NULL);
3856 return abort;
3857}
3858
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003859/*
3860 * Mark all lists and dicts referenced through function "name" with "copyID".
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003861 * Returns TRUE if setting references failed somehow.
3862 */
3863 int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003864set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003865{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003866 ufunc_T *fp = fp_in;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003867 funccall_T *fc;
3868 int error = ERROR_NONE;
3869 char_u fname_buf[FLEN_FIXED + 1];
3870 char_u *tofree = NULL;
3871 char_u *fname;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003872 int abort = FALSE;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003873
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003874 if (name == NULL && fp_in == NULL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003875 return FALSE;
3876
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003877 if (fp_in == NULL)
3878 {
3879 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
3880 fp = find_func(fname);
3881 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003882 if (fp != NULL)
3883 {
3884 for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003885 abort = abort || set_ref_in_funccal(fc, copyID);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003886 }
3887 vim_free(tofree);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003888 return abort;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003889}
3890
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003891#endif /* FEAT_EVAL */