blob: 71acaecc3a9373c581b04ef7ad3250f17d5190d9 [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
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200296 if (prof_def_func())
297 func_do_profile(fp);
298#endif
299 fp->uf_varargs = TRUE;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +0200300 fp->uf_flags = flags;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200301 fp->uf_calls = 0;
302 fp->uf_script_ID = current_SID;
303
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200304 pt->pt_func = fp;
305 pt->pt_refcount = 1;
306 rettv->vval.v_partial = pt;
307 rettv->v_type = VAR_PARTIAL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200308 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200309
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200310 eval_lavars_used = old_eval_lavars;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200311 return OK;
312
313errret:
314 ga_clear_strings(&newargs);
315 ga_clear_strings(&newlines);
316 vim_free(fp);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200317 eval_lavars_used = old_eval_lavars;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200318 return FAIL;
319}
320
321/*
322 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
323 * name it contains, otherwise return "name".
324 * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set
325 * "partialp".
326 */
327 char_u *
328deref_func_name(char_u *name, int *lenp, partial_T **partialp, int no_autoload)
329{
330 dictitem_T *v;
331 int cc;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200332 char_u *s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200333
334 if (partialp != NULL)
335 *partialp = NULL;
336
337 cc = name[*lenp];
338 name[*lenp] = NUL;
339 v = find_var(name, NULL, no_autoload);
340 name[*lenp] = cc;
341 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
342 {
343 if (v->di_tv.vval.v_string == NULL)
344 {
345 *lenp = 0;
346 return (char_u *)""; /* just in case */
347 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200348 s = v->di_tv.vval.v_string;
349 *lenp = (int)STRLEN(s);
350 return s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200351 }
352
353 if (v != NULL && v->di_tv.v_type == VAR_PARTIAL)
354 {
355 partial_T *pt = v->di_tv.vval.v_partial;
356
357 if (pt == NULL)
358 {
359 *lenp = 0;
360 return (char_u *)""; /* just in case */
361 }
362 if (partialp != NULL)
363 *partialp = pt;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200364 s = partial_name(pt);
365 *lenp = (int)STRLEN(s);
366 return s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200367 }
368
369 return name;
370}
371
372/*
373 * Give an error message with a function name. Handle <SNR> things.
374 * "ermsg" is to be passed without translation, use N_() instead of _().
375 */
376 static void
377emsg_funcname(char *ermsg, char_u *name)
378{
379 char_u *p;
380
381 if (*name == K_SPECIAL)
382 p = concat_str((char_u *)"<SNR>", name + 3);
383 else
384 p = name;
385 EMSG2(_(ermsg), p);
386 if (p != name)
387 vim_free(p);
388}
389
390/*
391 * Allocate a variable for the result of a function.
392 * Return OK or FAIL.
393 */
394 int
395get_func_tv(
396 char_u *name, /* name of the function */
397 int len, /* length of "name" */
398 typval_T *rettv,
399 char_u **arg, /* argument, pointing to the '(' */
400 linenr_T firstline, /* first line of range */
401 linenr_T lastline, /* last line of range */
402 int *doesrange, /* return: function handled range */
403 int evaluate,
404 partial_T *partial, /* for extra arguments */
405 dict_T *selfdict) /* Dictionary for "self" */
406{
407 char_u *argp;
408 int ret = OK;
409 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
410 int argcount = 0; /* number of arguments found */
411
412 /*
413 * Get the arguments.
414 */
415 argp = *arg;
416 while (argcount < MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
417 {
418 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
419 if (*argp == ')' || *argp == ',' || *argp == NUL)
420 break;
421 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
422 {
423 ret = FAIL;
424 break;
425 }
426 ++argcount;
427 if (*argp != ',')
428 break;
429 }
430 if (*argp == ')')
431 ++argp;
432 else
433 ret = FAIL;
434
435 if (ret == OK)
436 {
437 int i = 0;
438
439 if (get_vim_var_nr(VV_TESTING))
440 {
441 /* Prepare for calling test_garbagecollect_now(), need to know
442 * what variables are used on the call stack. */
443 if (funcargs.ga_itemsize == 0)
444 ga_init2(&funcargs, (int)sizeof(typval_T *), 50);
445 for (i = 0; i < argcount; ++i)
446 if (ga_grow(&funcargs, 1) == OK)
447 ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] =
448 &argvars[i];
449 }
450
Bram Moolenaardf48fb42016-07-22 21:50:18 +0200451 ret = call_func(name, len, rettv, argcount, argvars, NULL,
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200452 firstline, lastline, doesrange, evaluate, partial, selfdict);
453
454 funcargs.ga_len -= i;
455 }
456 else if (!aborting())
457 {
458 if (argcount == MAX_FUNC_ARGS)
459 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
460 else
461 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
462 }
463
464 while (--argcount >= 0)
465 clear_tv(&argvars[argcount]);
466
467 *arg = skipwhite(argp);
468 return ret;
469}
470
471#define FLEN_FIXED 40
472
473/*
474 * Return TRUE if "p" starts with "<SID>" or "s:".
475 * Only works if eval_fname_script() returned non-zero for "p"!
476 */
477 static int
478eval_fname_sid(char_u *p)
479{
480 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
481}
482
483/*
484 * In a script change <SID>name() and s:name() to K_SNR 123_name().
485 * Change <SNR>123_name() to K_SNR 123_name().
486 * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory
487 * (slow).
488 */
489 static char_u *
490fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error)
491{
492 int llen;
493 char_u *fname;
494 int i;
495
496 llen = eval_fname_script(name);
497 if (llen > 0)
498 {
499 fname_buf[0] = K_SPECIAL;
500 fname_buf[1] = KS_EXTRA;
501 fname_buf[2] = (int)KE_SNR;
502 i = 3;
503 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
504 {
505 if (current_SID <= 0)
506 *error = ERROR_SCRIPT;
507 else
508 {
509 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
510 i = (int)STRLEN(fname_buf);
511 }
512 }
513 if (i + STRLEN(name + llen) < FLEN_FIXED)
514 {
515 STRCPY(fname_buf + i, name + llen);
516 fname = fname_buf;
517 }
518 else
519 {
520 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
521 if (fname == NULL)
522 *error = ERROR_OTHER;
523 else
524 {
525 *tofree = fname;
526 mch_memmove(fname, fname_buf, (size_t)i);
527 STRCPY(fname + i, name + llen);
528 }
529 }
530 }
531 else
532 fname = name;
533 return fname;
534}
535
536/*
537 * Find a function by name, return pointer to it in ufuncs.
538 * Return NULL for unknown function.
539 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200540 ufunc_T *
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200541find_func(char_u *name)
542{
543 hashitem_T *hi;
544
545 hi = hash_find(&func_hashtab, name);
546 if (!HASHITEM_EMPTY(hi))
547 return HI2UF(hi);
548 return NULL;
549}
550
551/*
552 * Copy the function name of "fp" to buffer "buf".
553 * "buf" must be able to hold the function name plus three bytes.
554 * Takes care of script-local function names.
555 */
556 static void
557cat_func_name(char_u *buf, ufunc_T *fp)
558{
559 if (fp->uf_name[0] == K_SPECIAL)
560 {
561 STRCPY(buf, "<SNR>");
562 STRCAT(buf, fp->uf_name + 3);
563 }
564 else
565 STRCPY(buf, fp->uf_name);
566}
567
568/*
569 * Add a number variable "name" to dict "dp" with value "nr".
570 */
571 static void
572add_nr_var(
573 dict_T *dp,
574 dictitem_T *v,
575 char *name,
576 varnumber_T nr)
577{
578 STRCPY(v->di_key, name);
579 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
580 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
581 v->di_tv.v_type = VAR_NUMBER;
582 v->di_tv.v_lock = VAR_FIXED;
583 v->di_tv.vval.v_number = nr;
584}
585
586/*
587 * Free "fc" and what it contains.
588 */
589 static void
590free_funccal(
591 funccall_T *fc,
592 int free_val) /* a: vars were allocated */
593{
594 listitem_T *li;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200595 int i;
596
597 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
598 {
599 ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i];
600
Bram Moolenaarbc7ce672016-08-01 22:49:22 +0200601 /* When garbage collecting a funccall_T may be freed before the
602 * function that references it, clear its uf_scoped field.
603 * The function may have been redefined and point to another
604 * funccall_T, don't clear it then. */
605 if (fp != NULL && fp->uf_scoped == fc)
606 fp->uf_scoped = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200607 }
Bram Moolenaar58016442016-07-31 18:30:22 +0200608 ga_clear(&fc->fc_funcs);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200609
610 /* The a: variables typevals may not have been allocated, only free the
611 * allocated variables. */
612 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
613
614 /* free all l: variables */
615 vars_clear(&fc->l_vars.dv_hashtab);
616
617 /* Free the a:000 variables if they were allocated. */
618 if (free_val)
619 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
620 clear_tv(&li->li_tv);
621
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200622 func_ptr_unref(fc->func);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200623 vim_free(fc);
624}
625
626/*
Bram Moolenaar6914c642017-04-01 21:21:30 +0200627 * Handle the last part of returning from a function: free the local hashtable.
628 * Unless it is still in use by a closure.
629 */
630 static void
631cleanup_function_call(funccall_T *fc)
632{
633 current_funccal = fc->caller;
634
635 /* If the a:000 list and the l: and a: dicts are not referenced and there
636 * is no closure using it, we can free the funccall_T and what's in it. */
637 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
638 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
639 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT
640 && fc->fc_refcount <= 0)
641 {
642 free_funccal(fc, FALSE);
643 }
644 else
645 {
646 hashitem_T *hi;
647 listitem_T *li;
648 int todo;
649 dictitem_T *v;
650
651 /* "fc" is still in use. This can happen when returning "a:000",
652 * assigning "l:" to a global variable or defining a closure.
653 * Link "fc" in the list for garbage collection later. */
654 fc->caller = previous_funccal;
655 previous_funccal = fc;
656
657 /* Make a copy of the a: variables, since we didn't do that above. */
658 todo = (int)fc->l_avars.dv_hashtab.ht_used;
659 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
660 {
661 if (!HASHITEM_EMPTY(hi))
662 {
663 --todo;
664 v = HI2DI(hi);
665 copy_tv(&v->di_tv, &v->di_tv);
666 }
667 }
668
669 /* Make a copy of the a:000 items, since we didn't do that above. */
670 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
671 copy_tv(&li->li_tv, &li->li_tv);
672 }
673}
674
675/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200676 * Call a user function.
677 */
678 static void
679call_user_func(
680 ufunc_T *fp, /* pointer to function */
681 int argcount, /* nr of args */
682 typval_T *argvars, /* arguments */
683 typval_T *rettv, /* return value */
684 linenr_T firstline, /* first line of range */
685 linenr_T lastline, /* last line of range */
686 dict_T *selfdict) /* Dictionary for "self" */
687{
688 char_u *save_sourcing_name;
689 linenr_T save_sourcing_lnum;
690 scid_T save_current_SID;
691 funccall_T *fc;
692 int save_did_emsg;
693 static int depth = 0;
694 dictitem_T *v;
695 int fixvar_idx = 0; /* index in fixvar[] */
696 int i;
697 int ai;
698 int islambda = FALSE;
699 char_u numbuf[NUMBUFLEN];
700 char_u *name;
701 size_t len;
702#ifdef FEAT_PROFILE
703 proftime_T wait_start;
704 proftime_T call_start;
Bram Moolenaarad648092018-06-30 18:28:03 +0200705 int started_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200706#endif
707
708 /* If depth of calling is getting too high, don't execute the function */
709 if (depth >= p_mfd)
710 {
711 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
712 rettv->v_type = VAR_NUMBER;
713 rettv->vval.v_number = -1;
714 return;
715 }
716 ++depth;
717
718 line_breakcheck(); /* check for CTRL-C hit */
719
720 fc = (funccall_T *)alloc(sizeof(funccall_T));
721 fc->caller = current_funccal;
722 current_funccal = fc;
723 fc->func = fp;
724 fc->rettv = rettv;
725 rettv->vval.v_number = 0;
726 fc->linenr = 0;
727 fc->returned = FALSE;
728 fc->level = ex_nesting_level;
729 /* Check if this function has a breakpoint. */
730 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
731 fc->dbg_tick = debug_tick;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200732 /* Set up fields for closure. */
733 fc->fc_refcount = 0;
734 fc->fc_copyID = 0;
735 ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1);
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200736 func_ptr_ref(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200737
738 if (STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
739 islambda = TRUE;
740
741 /*
742 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
743 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
744 * each argument variable and saves a lot of time.
745 */
746 /*
747 * Init l: variables.
748 */
749 init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE);
750 if (selfdict != NULL)
751 {
752 /* Set l:self to "selfdict". Use "name" to avoid a warning from
753 * some compiler that checks the destination size. */
754 v = &fc->fixvar[fixvar_idx++].var;
755 name = v->di_key;
756 STRCPY(name, "self");
757 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
758 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
759 v->di_tv.v_type = VAR_DICT;
760 v->di_tv.v_lock = 0;
761 v->di_tv.vval.v_dict = selfdict;
762 ++selfdict->dv_refcount;
763 }
764
765 /*
766 * Init a: variables.
767 * Set a:0 to "argcount".
768 * Set a:000 to a list with room for the "..." arguments.
769 */
770 init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE);
771 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
772 (varnumber_T)(argcount - fp->uf_args.ga_len));
773 /* Use "name" to avoid a warning from some compiler that checks the
774 * destination size. */
775 v = &fc->fixvar[fixvar_idx++].var;
776 name = v->di_key;
777 STRCPY(name, "000");
778 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
779 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
780 v->di_tv.v_type = VAR_LIST;
781 v->di_tv.v_lock = VAR_FIXED;
782 v->di_tv.vval.v_list = &fc->l_varlist;
783 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
784 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
785 fc->l_varlist.lv_lock = VAR_FIXED;
786
787 /*
788 * Set a:firstline to "firstline" and a:lastline to "lastline".
789 * Set a:name to named arguments.
790 * Set a:N to the "..." arguments.
791 */
792 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
793 (varnumber_T)firstline);
794 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
795 (varnumber_T)lastline);
796 for (i = 0; i < argcount; ++i)
797 {
798 int addlocal = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200799
800 ai = i - fp->uf_args.ga_len;
801 if (ai < 0)
802 {
803 /* named argument a:name */
804 name = FUNCARG(fp, i);
805 if (islambda)
806 addlocal = TRUE;
807 }
808 else
809 {
810 /* "..." argument a:1, a:2, etc. */
811 sprintf((char *)numbuf, "%d", ai + 1);
812 name = numbuf;
813 }
814 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
815 {
816 v = &fc->fixvar[fixvar_idx++].var;
817 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200818 }
819 else
820 {
821 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
822 + STRLEN(name)));
823 if (v == NULL)
824 break;
825 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX | DI_FLAGS_ALLOC;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200826 }
827 STRCPY(v->di_key, name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200828
829 /* Note: the values are copied directly to avoid alloc/free.
830 * "argvars" must have VAR_FIXED for v_lock. */
831 v->di_tv = argvars[i];
832 v->di_tv.v_lock = VAR_FIXED;
833
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200834 if (addlocal)
835 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200836 /* Named arguments should be accessed without the "a:" prefix in
837 * lambda expressions. Add to the l: dict. */
838 copy_tv(&v->di_tv, &v->di_tv);
839 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200840 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200841 else
842 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200843
844 if (ai >= 0 && ai < MAX_FUNC_ARGS)
845 {
846 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
847 fc->l_listitems[ai].li_tv = argvars[i];
848 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
849 }
850 }
851
852 /* Don't redraw while executing the function. */
853 ++RedrawingDisabled;
854 save_sourcing_name = sourcing_name;
855 save_sourcing_lnum = sourcing_lnum;
856 sourcing_lnum = 1;
857 /* need space for function name + ("function " + 3) or "[number]" */
858 len = (save_sourcing_name == NULL ? 0 : STRLEN(save_sourcing_name))
859 + STRLEN(fp->uf_name) + 20;
860 sourcing_name = alloc((unsigned)len);
861 if (sourcing_name != NULL)
862 {
863 if (save_sourcing_name != NULL
864 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
865 sprintf((char *)sourcing_name, "%s[%d]..",
866 save_sourcing_name, (int)save_sourcing_lnum);
867 else
868 STRCPY(sourcing_name, "function ");
869 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
870
871 if (p_verbose >= 12)
872 {
873 ++no_wait_return;
874 verbose_enter_scroll();
875
876 smsg((char_u *)_("calling %s"), sourcing_name);
877 if (p_verbose >= 14)
878 {
879 char_u buf[MSG_BUF_LEN];
880 char_u numbuf2[NUMBUFLEN];
881 char_u *tofree;
882 char_u *s;
883
884 msg_puts((char_u *)"(");
885 for (i = 0; i < argcount; ++i)
886 {
887 if (i > 0)
888 msg_puts((char_u *)", ");
889 if (argvars[i].v_type == VAR_NUMBER)
890 msg_outnum((long)argvars[i].vval.v_number);
891 else
892 {
893 /* Do not want errors such as E724 here. */
894 ++emsg_off;
895 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
896 --emsg_off;
897 if (s != NULL)
898 {
899 if (vim_strsize(s) > MSG_BUF_CLEN)
900 {
901 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
902 s = buf;
903 }
904 msg_puts(s);
905 vim_free(tofree);
906 }
907 }
908 }
909 msg_puts((char_u *)")");
910 }
911 msg_puts((char_u *)"\n"); /* don't overwrite this either */
912
913 verbose_leave_scroll();
914 --no_wait_return;
915 }
916 }
917#ifdef FEAT_PROFILE
918 if (do_profiling == PROF_YES)
919 {
920 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
Bram Moolenaarad648092018-06-30 18:28:03 +0200921 {
922 started_profiling = TRUE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200923 func_do_profile(fp);
Bram Moolenaarad648092018-06-30 18:28:03 +0200924 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200925 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 }
Bram Moolenaarad648092018-06-30 18:28:03 +0200968 if (started_profiling)
969 // make a ":profdel func" stop profiling the function
970 fp->uf_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200971 }
972#endif
973
974 /* when being verbose, mention the return value */
975 if (p_verbose >= 12)
976 {
977 ++no_wait_return;
978 verbose_enter_scroll();
979
980 if (aborting())
981 smsg((char_u *)_("%s aborted"), sourcing_name);
982 else if (fc->rettv->v_type == VAR_NUMBER)
983 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
984 (long)fc->rettv->vval.v_number);
985 else
986 {
987 char_u buf[MSG_BUF_LEN];
988 char_u numbuf2[NUMBUFLEN];
989 char_u *tofree;
990 char_u *s;
991
992 /* The value may be very long. Skip the middle part, so that we
993 * have some idea how it starts and ends. smsg() would always
994 * truncate it at the end. Don't want errors such as E724 here. */
995 ++emsg_off;
996 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
997 --emsg_off;
998 if (s != NULL)
999 {
1000 if (vim_strsize(s) > MSG_BUF_CLEN)
1001 {
1002 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
1003 s = buf;
1004 }
1005 smsg((char_u *)_("%s returning %s"), sourcing_name, s);
1006 vim_free(tofree);
1007 }
1008 }
1009 msg_puts((char_u *)"\n"); /* don't overwrite this either */
1010
1011 verbose_leave_scroll();
1012 --no_wait_return;
1013 }
1014
1015 vim_free(sourcing_name);
1016 sourcing_name = save_sourcing_name;
1017 sourcing_lnum = save_sourcing_lnum;
1018 current_SID = save_current_SID;
1019#ifdef FEAT_PROFILE
1020 if (do_profiling == PROF_YES)
1021 script_prof_restore(&wait_start);
1022#endif
1023
1024 if (p_verbose >= 12 && sourcing_name != NULL)
1025 {
1026 ++no_wait_return;
1027 verbose_enter_scroll();
1028
1029 smsg((char_u *)_("continuing in %s"), sourcing_name);
1030 msg_puts((char_u *)"\n"); /* don't overwrite this either */
1031
1032 verbose_leave_scroll();
1033 --no_wait_return;
1034 }
1035
1036 did_emsg |= save_did_emsg;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001037 --depth;
1038
Bram Moolenaar6914c642017-04-01 21:21:30 +02001039 cleanup_function_call(fc);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001040}
1041
1042/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001043 * Unreference "fc": decrement the reference count and free it when it
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001044 * becomes zero. "fp" is detached from "fc".
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001045 * When "force" is TRUE we are exiting.
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001046 */
1047 static void
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001048funccal_unref(funccall_T *fc, ufunc_T *fp, int force)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001049{
1050 funccall_T **pfc;
1051 int i;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001052
1053 if (fc == NULL)
1054 return;
1055
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001056 if (--fc->fc_refcount <= 0 && (force || (
1057 fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001058 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001059 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001060 for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001061 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001062 if (fc == *pfc)
1063 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001064 *pfc = fc->caller;
1065 free_funccal(fc, TRUE);
1066 return;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001067 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001068 }
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001069 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001070 if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001071 ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001072}
1073
1074/*
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001075 * Remove the function from the function hashtable. If the function was
1076 * deleted while it still has references this was already done.
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001077 * Return TRUE if the entry was deleted, FALSE if it wasn't found.
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001078 */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001079 static int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001080func_remove(ufunc_T *fp)
1081{
1082 hashitem_T *hi = hash_find(&func_hashtab, UF2HIKEY(fp));
1083
1084 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001085 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001086 hash_remove(&func_hashtab, hi);
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001087 return TRUE;
1088 }
1089 return FALSE;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001090}
1091
1092/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001093 * Free all things that a function contains. Does not free the function
1094 * itself, use func_free() for that.
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001095 * When "force" is TRUE we are exiting.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001096 */
1097 static void
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001098func_clear(ufunc_T *fp, int force)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001099{
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001100 if (fp->uf_cleared)
1101 return;
1102 fp->uf_cleared = TRUE;
1103
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001104 /* clear this function */
1105 ga_clear_strings(&(fp->uf_args));
1106 ga_clear_strings(&(fp->uf_lines));
1107#ifdef FEAT_PROFILE
1108 vim_free(fp->uf_tml_count);
1109 vim_free(fp->uf_tml_total);
1110 vim_free(fp->uf_tml_self);
1111#endif
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001112 funccal_unref(fp->uf_scoped, fp, force);
1113}
1114
1115/*
1116 * Free a function and remove it from the list of functions. Does not free
1117 * what a function contains, call func_clear() first.
1118 */
1119 static void
1120func_free(ufunc_T *fp)
1121{
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001122 /* only remove it when not done already, otherwise we would remove a newer
1123 * version of the function */
1124 if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0)
1125 func_remove(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001126
1127 vim_free(fp);
1128}
1129
Bram Moolenaarc2574872016-08-11 22:51:05 +02001130/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001131 * Free all things that a function contains and free the function itself.
1132 * When "force" is TRUE we are exiting.
1133 */
1134 static void
1135func_clear_free(ufunc_T *fp, int force)
1136{
1137 func_clear(fp, force);
1138 func_free(fp);
1139}
1140
1141/*
Bram Moolenaarc2574872016-08-11 22:51:05 +02001142 * There are two kinds of function names:
1143 * 1. ordinary names, function defined with :function
1144 * 2. numbered functions and lambdas
1145 * For the first we only count the name stored in func_hashtab as a reference,
1146 * using function() does not count as a reference, because the function is
1147 * looked up by name.
1148 */
1149 static int
1150func_name_refcount(char_u *name)
1151{
1152 return isdigit(*name) || *name == '<';
1153}
1154
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001155#if defined(EXITFREE) || defined(PROTO)
1156 void
1157free_all_functions(void)
1158{
1159 hashitem_T *hi;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001160 ufunc_T *fp;
1161 long_u skipped = 0;
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001162 long_u todo = 1;
1163 long_u used;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001164
Bram Moolenaar6914c642017-04-01 21:21:30 +02001165 /* Clean up the call stack. */
1166 while (current_funccal != NULL)
1167 {
1168 clear_tv(current_funccal->rettv);
1169 cleanup_function_call(current_funccal);
1170 }
1171
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001172 /* First clear what the functions contain. Since this may lower the
1173 * reference count of a function, it may also free a function and change
1174 * the hash table. Restart if that happens. */
1175 while (todo > 0)
1176 {
1177 todo = func_hashtab.ht_used;
1178 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
1179 if (!HASHITEM_EMPTY(hi))
1180 {
1181 /* Only free functions that are not refcounted, those are
1182 * supposed to be freed when no longer referenced. */
1183 fp = HI2UF(hi);
1184 if (func_name_refcount(fp->uf_name))
1185 ++skipped;
1186 else
1187 {
1188 used = func_hashtab.ht_used;
1189 func_clear(fp, TRUE);
1190 if (used != func_hashtab.ht_used)
1191 {
1192 skipped = 0;
1193 break;
1194 }
1195 }
1196 --todo;
1197 }
1198 }
1199
1200 /* Now actually free the functions. Need to start all over every time,
1201 * because func_free() may change the hash table. */
1202 skipped = 0;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001203 while (func_hashtab.ht_used > skipped)
1204 {
1205 todo = func_hashtab.ht_used;
1206 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001207 if (!HASHITEM_EMPTY(hi))
1208 {
Bram Moolenaarc2574872016-08-11 22:51:05 +02001209 --todo;
1210 /* Only free functions that are not refcounted, those are
1211 * supposed to be freed when no longer referenced. */
1212 fp = HI2UF(hi);
1213 if (func_name_refcount(fp->uf_name))
1214 ++skipped;
1215 else
1216 {
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001217 func_free(fp);
Bram Moolenaarc2574872016-08-11 22:51:05 +02001218 skipped = 0;
1219 break;
1220 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001221 }
Bram Moolenaarc2574872016-08-11 22:51:05 +02001222 }
1223 if (skipped == 0)
1224 hash_clear(&func_hashtab);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001225}
1226#endif
1227
1228/*
1229 * Return TRUE if "name" looks like a builtin function name: starts with a
1230 * lower case letter and doesn't contain AUTOLOAD_CHAR.
1231 * "len" is the length of "name", or -1 for NUL terminated.
1232 */
1233 static int
1234builtin_function(char_u *name, int len)
1235{
1236 char_u *p;
1237
1238 if (!ASCII_ISLOWER(name[0]))
1239 return FALSE;
1240 p = vim_strchr(name, AUTOLOAD_CHAR);
1241 return p == NULL || (len > 0 && p > name + len);
1242}
1243
1244 int
1245func_call(
1246 char_u *name,
1247 typval_T *args,
1248 partial_T *partial,
1249 dict_T *selfdict,
1250 typval_T *rettv)
1251{
1252 listitem_T *item;
1253 typval_T argv[MAX_FUNC_ARGS + 1];
1254 int argc = 0;
1255 int dummy;
1256 int r = 0;
1257
1258 for (item = args->vval.v_list->lv_first; item != NULL;
1259 item = item->li_next)
1260 {
1261 if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
1262 {
1263 EMSG(_("E699: Too many arguments"));
1264 break;
1265 }
1266 /* Make a copy of each argument. This is needed to be able to set
1267 * v_lock to VAR_FIXED in the copy without changing the original list.
1268 */
1269 copy_tv(&item->li_tv, &argv[argc++]);
1270 }
1271
1272 if (item == NULL)
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001273 r = call_func(name, (int)STRLEN(name), rettv, argc, argv, NULL,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001274 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1275 &dummy, TRUE, partial, selfdict);
1276
1277 /* Free the arguments. */
1278 while (argc > 0)
1279 clear_tv(&argv[--argc]);
1280
1281 return r;
1282}
1283
1284/*
1285 * Call a function with its resolved parameters
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001286 *
1287 * "argv_func", when not NULL, can be used to fill in arguments only when the
1288 * invoked function uses them. It is called like this:
1289 * new_argcount = argv_func(current_argcount, argv, called_func_argcount)
1290 *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001291 * Return FAIL when the function can't be called, OK otherwise.
1292 * Also returns OK when an error was encountered while executing the function.
1293 */
1294 int
1295call_func(
1296 char_u *funcname, /* name of the function */
1297 int len, /* length of "name" */
1298 typval_T *rettv, /* return value goes here */
1299 int argcount_in, /* number of "argvars" */
1300 typval_T *argvars_in, /* vars for arguments, must have "argcount"
1301 PLUS ONE elements! */
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001302 int (* argv_func)(int, typval_T *, int),
1303 /* function to fill in argvars */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001304 linenr_T firstline, /* first line of range */
1305 linenr_T lastline, /* last line of range */
1306 int *doesrange, /* return: function handled range */
1307 int evaluate,
1308 partial_T *partial, /* optional, can be NULL */
1309 dict_T *selfdict_in) /* Dictionary for "self" */
1310{
1311 int ret = FAIL;
1312 int error = ERROR_NONE;
1313 int i;
1314 ufunc_T *fp;
1315 char_u fname_buf[FLEN_FIXED + 1];
1316 char_u *tofree = NULL;
1317 char_u *fname;
1318 char_u *name;
1319 int argcount = argcount_in;
1320 typval_T *argvars = argvars_in;
1321 dict_T *selfdict = selfdict_in;
1322 typval_T argv[MAX_FUNC_ARGS + 1]; /* used when "partial" is not NULL */
1323 int argv_clear = 0;
1324
1325 /* Make a copy of the name, if it comes from a funcref variable it could
1326 * be changed or deleted in the called function. */
1327 name = vim_strnsave(funcname, len);
1328 if (name == NULL)
1329 return ret;
1330
1331 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1332
1333 *doesrange = FALSE;
1334
1335 if (partial != NULL)
1336 {
1337 /* When the function has a partial with a dict and there is a dict
1338 * argument, use the dict argument. That is backwards compatible.
1339 * When the dict was bound explicitly use the one from the partial. */
1340 if (partial->pt_dict != NULL
1341 && (selfdict_in == NULL || !partial->pt_auto))
1342 selfdict = partial->pt_dict;
1343 if (error == ERROR_NONE && partial->pt_argc > 0)
1344 {
1345 for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear)
1346 copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]);
1347 for (i = 0; i < argcount_in; ++i)
1348 argv[i + argv_clear] = argvars_in[i];
1349 argvars = argv;
1350 argcount = partial->pt_argc + argcount_in;
1351 }
1352 }
1353
1354
Bram Moolenaarb4518562018-05-22 18:31:35 +02001355 /*
1356 * Execute the function if executing and no errors were detected.
1357 */
1358 if (!evaluate)
1359 {
1360 // Not evaluating, which means the return value is unknown. This
1361 // matters for giving error messages.
1362 rettv->v_type = VAR_UNKNOWN;
1363 }
1364 else if (error == ERROR_NONE)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001365 {
1366 char_u *rfname = fname;
1367
1368 /* Ignore "g:" before a function name. */
1369 if (fname[0] == 'g' && fname[1] == ':')
1370 rfname = fname + 2;
1371
1372 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
1373 rettv->vval.v_number = 0;
1374 error = ERROR_UNKNOWN;
1375
1376 if (!builtin_function(rfname, -1))
1377 {
1378 /*
1379 * User defined function.
1380 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001381 if (partial != NULL && partial->pt_func != NULL)
1382 fp = partial->pt_func;
1383 else
1384 fp = find_func(rfname);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001385
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001386 /* Trigger FuncUndefined event, may load the function. */
1387 if (fp == NULL
1388 && apply_autocmds(EVENT_FUNCUNDEFINED,
1389 rfname, rfname, TRUE, NULL)
1390 && !aborting())
1391 {
1392 /* executed an autocommand, search for the function again */
1393 fp = find_func(rfname);
1394 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001395 /* Try loading a package. */
1396 if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
1397 {
1398 /* loaded a package, search for the function again */
1399 fp = find_func(rfname);
1400 }
1401
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001402 if (fp != NULL && (fp->uf_flags & FC_DELETED))
1403 error = ERROR_DELETED;
1404 else if (fp != NULL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001405 {
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001406 if (argv_func != NULL)
1407 argcount = argv_func(argcount, argvars, fp->uf_args.ga_len);
1408
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001409 if (fp->uf_flags & FC_RANGE)
1410 *doesrange = TRUE;
1411 if (argcount < fp->uf_args.ga_len)
1412 error = ERROR_TOOFEW;
1413 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
1414 error = ERROR_TOOMANY;
1415 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
1416 error = ERROR_DICT;
1417 else
1418 {
1419 int did_save_redo = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001420 save_redo_T save_redo;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001421
1422 /*
1423 * Call the user function.
1424 * Save and restore search patterns, script variables and
1425 * redo buffer.
1426 */
1427 save_search_patterns();
1428#ifdef FEAT_INS_EXPAND
1429 if (!ins_compl_active())
1430#endif
1431 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001432 saveRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001433 did_save_redo = TRUE;
1434 }
1435 ++fp->uf_calls;
1436 call_user_func(fp, argcount, argvars, rettv,
1437 firstline, lastline,
1438 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001439 if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001440 /* Function was unreferenced while being used, free it
1441 * now. */
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001442 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001443 if (did_save_redo)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001444 restoreRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001445 restore_search_patterns();
1446 error = ERROR_NONE;
1447 }
1448 }
1449 }
1450 else
1451 {
1452 /*
1453 * Find the function name in the table, call its implementation.
1454 */
1455 error = call_internal_func(fname, argcount, argvars, rettv);
1456 }
1457 /*
1458 * The function call (or "FuncUndefined" autocommand sequence) might
1459 * have been aborted by an error, an interrupt, or an explicitly thrown
1460 * exception that has not been caught so far. This situation can be
1461 * tested for by calling aborting(). For an error in an internal
1462 * function or for the "E132" error in call_user_func(), however, the
1463 * throw point at which the "force_abort" flag (temporarily reset by
1464 * emsg()) is normally updated has not been reached yet. We need to
1465 * update that flag first to make aborting() reliable.
1466 */
1467 update_force_abort();
1468 }
1469 if (error == ERROR_NONE)
1470 ret = OK;
1471
1472 /*
1473 * Report an error unless the argument evaluation or function call has been
1474 * cancelled due to an aborting error, an interrupt, or an exception.
1475 */
1476 if (!aborting())
1477 {
1478 switch (error)
1479 {
1480 case ERROR_UNKNOWN:
1481 emsg_funcname(N_("E117: Unknown function: %s"), name);
1482 break;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001483 case ERROR_DELETED:
1484 emsg_funcname(N_("E933: Function was deleted: %s"), name);
1485 break;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001486 case ERROR_TOOMANY:
1487 emsg_funcname((char *)e_toomanyarg, name);
1488 break;
1489 case ERROR_TOOFEW:
1490 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
1491 name);
1492 break;
1493 case ERROR_SCRIPT:
1494 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
1495 name);
1496 break;
1497 case ERROR_DICT:
1498 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
1499 name);
1500 break;
1501 }
1502 }
1503
1504 while (argv_clear > 0)
1505 clear_tv(&argv[--argv_clear]);
1506 vim_free(tofree);
1507 vim_free(name);
1508
1509 return ret;
1510}
1511
1512/*
1513 * List the head of the function: "name(arg1, arg2)".
1514 */
1515 static void
1516list_func_head(ufunc_T *fp, int indent)
1517{
1518 int j;
1519
1520 msg_start();
1521 if (indent)
1522 MSG_PUTS(" ");
1523 MSG_PUTS("function ");
1524 if (fp->uf_name[0] == K_SPECIAL)
1525 {
Bram Moolenaar8820b482017-03-16 17:23:31 +01001526 MSG_PUTS_ATTR("<SNR>", HL_ATTR(HLF_8));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001527 msg_puts(fp->uf_name + 3);
1528 }
1529 else
1530 msg_puts(fp->uf_name);
1531 msg_putchar('(');
1532 for (j = 0; j < fp->uf_args.ga_len; ++j)
1533 {
1534 if (j)
1535 MSG_PUTS(", ");
1536 msg_puts(FUNCARG(fp, j));
1537 }
1538 if (fp->uf_varargs)
1539 {
1540 if (j)
1541 MSG_PUTS(", ");
1542 MSG_PUTS("...");
1543 }
1544 msg_putchar(')');
1545 if (fp->uf_flags & FC_ABORT)
1546 MSG_PUTS(" abort");
1547 if (fp->uf_flags & FC_RANGE)
1548 MSG_PUTS(" range");
1549 if (fp->uf_flags & FC_DICT)
1550 MSG_PUTS(" dict");
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02001551 if (fp->uf_flags & FC_CLOSURE)
1552 MSG_PUTS(" closure");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001553 msg_clr_eos();
1554 if (p_verbose > 0)
1555 last_set_msg(fp->uf_script_ID);
1556}
1557
1558/*
1559 * Get a function name, translating "<SID>" and "<SNR>".
1560 * Also handles a Funcref in a List or Dictionary.
1561 * Returns the function name in allocated memory, or NULL for failure.
1562 * flags:
1563 * TFN_INT: internal function name OK
1564 * TFN_QUIET: be quiet
1565 * TFN_NO_AUTOLOAD: do not use script autoloading
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001566 * TFN_NO_DEREF: do not dereference a Funcref
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001567 * Advances "pp" to just after the function name (if no error).
1568 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001569 char_u *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001570trans_function_name(
1571 char_u **pp,
1572 int skip, /* only find the end, don't evaluate */
1573 int flags,
1574 funcdict_T *fdp, /* return: info about dictionary used */
1575 partial_T **partial) /* return: partial of a FuncRef */
1576{
1577 char_u *name = NULL;
1578 char_u *start;
1579 char_u *end;
1580 int lead;
1581 char_u sid_buf[20];
1582 int len;
1583 lval_T lv;
1584
1585 if (fdp != NULL)
1586 vim_memset(fdp, 0, sizeof(funcdict_T));
1587 start = *pp;
1588
1589 /* Check for hard coded <SNR>: already translated function ID (from a user
1590 * command). */
1591 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
1592 && (*pp)[2] == (int)KE_SNR)
1593 {
1594 *pp += 3;
1595 len = get_id_len(pp) + 3;
1596 return vim_strnsave(start, len);
1597 }
1598
1599 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
1600 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
1601 lead = eval_fname_script(start);
1602 if (lead > 2)
1603 start += lead;
1604
1605 /* Note that TFN_ flags use the same values as GLV_ flags. */
Bram Moolenaar6e65d592017-12-07 22:11:27 +01001606 end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001607 lead > 2 ? 0 : FNE_CHECK_START);
1608 if (end == start)
1609 {
1610 if (!skip)
1611 EMSG(_("E129: Function name required"));
1612 goto theend;
1613 }
1614 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
1615 {
1616 /*
1617 * Report an invalid expression in braces, unless the expression
1618 * evaluation has been cancelled due to an aborting error, an
1619 * interrupt, or an exception.
1620 */
1621 if (!aborting())
1622 {
1623 if (end != NULL)
1624 EMSG2(_(e_invarg2), start);
1625 }
1626 else
1627 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
1628 goto theend;
1629 }
1630
1631 if (lv.ll_tv != NULL)
1632 {
1633 if (fdp != NULL)
1634 {
1635 fdp->fd_dict = lv.ll_dict;
1636 fdp->fd_newkey = lv.ll_newkey;
1637 lv.ll_newkey = NULL;
1638 fdp->fd_di = lv.ll_di;
1639 }
1640 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
1641 {
1642 name = vim_strsave(lv.ll_tv->vval.v_string);
1643 *pp = end;
1644 }
1645 else if (lv.ll_tv->v_type == VAR_PARTIAL
1646 && lv.ll_tv->vval.v_partial != NULL)
1647 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001648 name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001649 *pp = end;
1650 if (partial != NULL)
1651 *partial = lv.ll_tv->vval.v_partial;
1652 }
1653 else
1654 {
1655 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
1656 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
1657 EMSG(_(e_funcref));
1658 else
1659 *pp = end;
1660 name = NULL;
1661 }
1662 goto theend;
1663 }
1664
1665 if (lv.ll_name == NULL)
1666 {
1667 /* Error found, but continue after the function name. */
1668 *pp = end;
1669 goto theend;
1670 }
1671
1672 /* Check if the name is a Funcref. If so, use the value. */
1673 if (lv.ll_exp_name != NULL)
1674 {
1675 len = (int)STRLEN(lv.ll_exp_name);
1676 name = deref_func_name(lv.ll_exp_name, &len, partial,
1677 flags & TFN_NO_AUTOLOAD);
1678 if (name == lv.ll_exp_name)
1679 name = NULL;
1680 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001681 else if (!(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001682 {
1683 len = (int)(end - *pp);
1684 name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD);
1685 if (name == *pp)
1686 name = NULL;
1687 }
1688 if (name != NULL)
1689 {
1690 name = vim_strsave(name);
1691 *pp = end;
1692 if (STRNCMP(name, "<SNR>", 5) == 0)
1693 {
1694 /* Change "<SNR>" to the byte sequence. */
1695 name[0] = K_SPECIAL;
1696 name[1] = KS_EXTRA;
1697 name[2] = (int)KE_SNR;
1698 mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
1699 }
1700 goto theend;
1701 }
1702
1703 if (lv.ll_exp_name != NULL)
1704 {
1705 len = (int)STRLEN(lv.ll_exp_name);
1706 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
1707 && STRNCMP(lv.ll_name, "s:", 2) == 0)
1708 {
1709 /* When there was "s:" already or the name expanded to get a
1710 * leading "s:" then remove it. */
1711 lv.ll_name += 2;
1712 len -= 2;
1713 lead = 2;
1714 }
1715 }
1716 else
1717 {
1718 /* skip over "s:" and "g:" */
1719 if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
1720 lv.ll_name += 2;
1721 len = (int)(end - lv.ll_name);
1722 }
1723
1724 /*
1725 * Copy the function name to allocated memory.
1726 * Accept <SID>name() inside a script, translate into <SNR>123_name().
1727 * Accept <SNR>123_name() outside a script.
1728 */
1729 if (skip)
1730 lead = 0; /* do nothing */
1731 else if (lead > 0)
1732 {
1733 lead = 3;
1734 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
1735 || eval_fname_sid(*pp))
1736 {
1737 /* It's "s:" or "<SID>" */
1738 if (current_SID <= 0)
1739 {
1740 EMSG(_(e_usingsid));
1741 goto theend;
1742 }
1743 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
1744 lead += (int)STRLEN(sid_buf);
1745 }
1746 }
1747 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
1748 {
1749 EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"),
1750 start);
1751 goto theend;
1752 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001753 if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001754 {
1755 char_u *cp = vim_strchr(lv.ll_name, ':');
1756
1757 if (cp != NULL && cp < end)
1758 {
1759 EMSG2(_("E884: Function name cannot contain a colon: %s"), start);
1760 goto theend;
1761 }
1762 }
1763
1764 name = alloc((unsigned)(len + lead + 1));
1765 if (name != NULL)
1766 {
1767 if (lead > 0)
1768 {
1769 name[0] = K_SPECIAL;
1770 name[1] = KS_EXTRA;
1771 name[2] = (int)KE_SNR;
1772 if (lead > 3) /* If it's "<SID>" */
1773 STRCPY(name + 3, sid_buf);
1774 }
1775 mch_memmove(name + lead, lv.ll_name, (size_t)len);
1776 name[lead + len] = NUL;
1777 }
1778 *pp = end;
1779
1780theend:
1781 clear_lval(&lv);
1782 return name;
1783}
1784
1785/*
1786 * ":function"
1787 */
1788 void
1789ex_function(exarg_T *eap)
1790{
1791 char_u *theline;
Bram Moolenaar53564f72017-06-24 14:48:11 +02001792 char_u *line_to_free = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001793 int j;
1794 int c;
1795 int saved_did_emsg;
1796 int saved_wait_return = need_wait_return;
1797 char_u *name = NULL;
1798 char_u *p;
1799 char_u *arg;
1800 char_u *line_arg = NULL;
1801 garray_T newargs;
1802 garray_T newlines;
1803 int varargs = FALSE;
1804 int flags = 0;
1805 ufunc_T *fp;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001806 int overwrite = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001807 int indent;
1808 int nesting;
1809 char_u *skip_until = NULL;
1810 dictitem_T *v;
1811 funcdict_T fudi;
1812 static int func_nr = 0; /* number for nameless function */
1813 int paren;
1814 hashtab_T *ht;
1815 int todo;
1816 hashitem_T *hi;
1817 int sourcing_lnum_off;
1818
1819 /*
1820 * ":function" without argument: list functions.
1821 */
1822 if (ends_excmd(*eap->arg))
1823 {
1824 if (!eap->skip)
1825 {
1826 todo = (int)func_hashtab.ht_used;
1827 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1828 {
1829 if (!HASHITEM_EMPTY(hi))
1830 {
1831 --todo;
1832 fp = HI2UF(hi);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001833 if (!func_name_refcount(fp->uf_name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001834 list_func_head(fp, FALSE);
1835 }
1836 }
1837 }
1838 eap->nextcmd = check_nextcmd(eap->arg);
1839 return;
1840 }
1841
1842 /*
1843 * ":function /pat": list functions matching pattern.
1844 */
1845 if (*eap->arg == '/')
1846 {
1847 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
1848 if (!eap->skip)
1849 {
1850 regmatch_T regmatch;
1851
1852 c = *p;
1853 *p = NUL;
1854 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
1855 *p = c;
1856 if (regmatch.regprog != NULL)
1857 {
1858 regmatch.rm_ic = p_ic;
1859
1860 todo = (int)func_hashtab.ht_used;
1861 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1862 {
1863 if (!HASHITEM_EMPTY(hi))
1864 {
1865 --todo;
1866 fp = HI2UF(hi);
1867 if (!isdigit(*fp->uf_name)
1868 && vim_regexec(&regmatch, fp->uf_name, 0))
1869 list_func_head(fp, FALSE);
1870 }
1871 }
1872 vim_regfree(regmatch.regprog);
1873 }
1874 }
1875 if (*p == '/')
1876 ++p;
1877 eap->nextcmd = check_nextcmd(p);
1878 return;
1879 }
1880
1881 /*
1882 * Get the function name. There are these situations:
1883 * func normal function name
1884 * "name" == func, "fudi.fd_dict" == NULL
1885 * dict.func new dictionary entry
1886 * "name" == NULL, "fudi.fd_dict" set,
1887 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
1888 * dict.func existing dict entry with a Funcref
1889 * "name" == func, "fudi.fd_dict" set,
1890 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1891 * dict.func existing dict entry that's not a Funcref
1892 * "name" == NULL, "fudi.fd_dict" set,
1893 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1894 * s:func script-local function name
1895 * g:func global function name, same as "func"
1896 */
1897 p = eap->arg;
Bram Moolenaar3388d332017-12-07 22:23:04 +01001898 name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001899 paren = (vim_strchr(p, '(') != NULL);
1900 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
1901 {
1902 /*
1903 * Return on an invalid expression in braces, unless the expression
1904 * evaluation has been cancelled due to an aborting error, an
1905 * interrupt, or an exception.
1906 */
1907 if (!aborting())
1908 {
1909 if (!eap->skip && fudi.fd_newkey != NULL)
1910 EMSG2(_(e_dictkey), fudi.fd_newkey);
1911 vim_free(fudi.fd_newkey);
1912 return;
1913 }
1914 else
1915 eap->skip = TRUE;
1916 }
1917
1918 /* An error in a function call during evaluation of an expression in magic
1919 * braces should not cause the function not to be defined. */
1920 saved_did_emsg = did_emsg;
1921 did_emsg = FALSE;
1922
1923 /*
1924 * ":function func" with only function name: list function.
1925 */
1926 if (!paren)
1927 {
1928 if (!ends_excmd(*skipwhite(p)))
1929 {
1930 EMSG(_(e_trailing));
1931 goto ret_free;
1932 }
1933 eap->nextcmd = check_nextcmd(p);
1934 if (eap->nextcmd != NULL)
1935 *p = NUL;
1936 if (!eap->skip && !got_int)
1937 {
1938 fp = find_func(name);
1939 if (fp != NULL)
1940 {
1941 list_func_head(fp, TRUE);
1942 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
1943 {
1944 if (FUNCLINE(fp, j) == NULL)
1945 continue;
1946 msg_putchar('\n');
1947 msg_outnum((long)(j + 1));
1948 if (j < 9)
1949 msg_putchar(' ');
1950 if (j < 99)
1951 msg_putchar(' ');
1952 msg_prt_line(FUNCLINE(fp, j), FALSE);
1953 out_flush(); /* show a line at a time */
1954 ui_breakcheck();
1955 }
1956 if (!got_int)
1957 {
1958 msg_putchar('\n');
1959 msg_puts((char_u *)" endfunction");
1960 }
1961 }
1962 else
1963 emsg_funcname(N_("E123: Undefined function: %s"), name);
1964 }
1965 goto ret_free;
1966 }
1967
1968 /*
1969 * ":function name(arg1, arg2)" Define function.
1970 */
1971 p = skipwhite(p);
1972 if (*p != '(')
1973 {
1974 if (!eap->skip)
1975 {
1976 EMSG2(_("E124: Missing '(': %s"), eap->arg);
1977 goto ret_free;
1978 }
1979 /* attempt to continue by skipping some text */
1980 if (vim_strchr(p, '(') != NULL)
1981 p = vim_strchr(p, '(');
1982 }
1983 p = skipwhite(p + 1);
1984
1985 ga_init2(&newlines, (int)sizeof(char_u *), 3);
1986
1987 if (!eap->skip)
1988 {
1989 /* Check the name of the function. Unless it's a dictionary function
1990 * (that we are overwriting). */
1991 if (name != NULL)
1992 arg = name;
1993 else
1994 arg = fudi.fd_newkey;
1995 if (arg != NULL && (fudi.fd_di == NULL
1996 || (fudi.fd_di->di_tv.v_type != VAR_FUNC
1997 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL)))
1998 {
1999 if (*arg == K_SPECIAL)
2000 j = 3;
2001 else
2002 j = 0;
2003 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
2004 : eval_isnamec(arg[j])))
2005 ++j;
2006 if (arg[j] != NUL)
2007 emsg_funcname((char *)e_invarg2, arg);
2008 }
2009 /* Disallow using the g: dict. */
2010 if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
2011 EMSG(_("E862: Cannot use g: here"));
2012 }
2013
2014 if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL)
2015 goto errret_2;
2016
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002017 /* find extra arguments "range", "dict", "abort" and "closure" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002018 for (;;)
2019 {
2020 p = skipwhite(p);
2021 if (STRNCMP(p, "range", 5) == 0)
2022 {
2023 flags |= FC_RANGE;
2024 p += 5;
2025 }
2026 else if (STRNCMP(p, "dict", 4) == 0)
2027 {
2028 flags |= FC_DICT;
2029 p += 4;
2030 }
2031 else if (STRNCMP(p, "abort", 5) == 0)
2032 {
2033 flags |= FC_ABORT;
2034 p += 5;
2035 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002036 else if (STRNCMP(p, "closure", 7) == 0)
2037 {
2038 flags |= FC_CLOSURE;
2039 p += 7;
Bram Moolenaar58016442016-07-31 18:30:22 +02002040 if (current_funccal == NULL)
2041 {
Bram Moolenaarba209902016-08-24 22:06:38 +02002042 emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
Bram Moolenaar58016442016-07-31 18:30:22 +02002043 name == NULL ? (char_u *)"" : name);
2044 goto erret;
2045 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002046 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002047 else
2048 break;
2049 }
2050
2051 /* When there is a line break use what follows for the function body.
2052 * Makes 'exe "func Test()\n...\nendfunc"' work. */
2053 if (*p == '\n')
2054 line_arg = p + 1;
2055 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
2056 EMSG(_(e_trailing));
2057
2058 /*
2059 * Read the body of the function, until ":endfunction" is found.
2060 */
2061 if (KeyTyped)
2062 {
2063 /* Check if the function already exists, don't let the user type the
2064 * whole function before telling him it doesn't work! For a script we
2065 * need to skip the body to be able to find what follows. */
2066 if (!eap->skip && !eap->forceit)
2067 {
2068 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
2069 EMSG(_(e_funcdict));
2070 else if (name != NULL && find_func(name) != NULL)
2071 emsg_funcname(e_funcexts, name);
2072 }
2073
2074 if (!eap->skip && did_emsg)
2075 goto erret;
2076
2077 msg_putchar('\n'); /* don't overwrite the function name */
2078 cmdline_row = msg_row;
2079 }
2080
2081 indent = 2;
2082 nesting = 0;
2083 for (;;)
2084 {
2085 if (KeyTyped)
2086 {
2087 msg_scroll = TRUE;
2088 saved_wait_return = FALSE;
2089 }
2090 need_wait_return = FALSE;
2091 sourcing_lnum_off = sourcing_lnum;
2092
2093 if (line_arg != NULL)
2094 {
2095 /* Use eap->arg, split up in parts by line breaks. */
2096 theline = line_arg;
2097 p = vim_strchr(theline, '\n');
2098 if (p == NULL)
2099 line_arg += STRLEN(line_arg);
2100 else
2101 {
2102 *p = NUL;
2103 line_arg = p + 1;
2104 }
2105 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002106 else
Bram Moolenaar53564f72017-06-24 14:48:11 +02002107 {
2108 vim_free(line_to_free);
2109 if (eap->getline == NULL)
2110 theline = getcmdline(':', 0L, indent);
2111 else
2112 theline = eap->getline(':', eap->cookie, indent);
2113 line_to_free = theline;
2114 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002115 if (KeyTyped)
2116 lines_left = Rows - 1;
2117 if (theline == NULL)
2118 {
2119 EMSG(_("E126: Missing :endfunction"));
2120 goto erret;
2121 }
2122
2123 /* Detect line continuation: sourcing_lnum increased more than one. */
2124 if (sourcing_lnum > sourcing_lnum_off + 1)
2125 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
2126 else
2127 sourcing_lnum_off = 0;
2128
2129 if (skip_until != NULL)
2130 {
2131 /* between ":append" and "." and between ":python <<EOF" and "EOF"
2132 * don't check for ":endfunc". */
2133 if (STRCMP(theline, skip_until) == 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01002134 VIM_CLEAR(skip_until);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002135 }
2136 else
2137 {
2138 /* skip ':' and blanks*/
Bram Moolenaar1c465442017-03-12 20:10:05 +01002139 for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002140 ;
2141
2142 /* Check for "endfunction". */
2143 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
2144 {
Bram Moolenaar53564f72017-06-24 14:48:11 +02002145 char_u *nextcmd = NULL;
2146
Bram Moolenaar663bb232017-06-22 19:12:10 +02002147 if (*p == '|')
Bram Moolenaar53564f72017-06-24 14:48:11 +02002148 nextcmd = p + 1;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002149 else if (line_arg != NULL && *skipwhite(line_arg) != NUL)
Bram Moolenaar53564f72017-06-24 14:48:11 +02002150 nextcmd = line_arg;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002151 else if (*p != NUL && *p != '"' && p_verbose > 0)
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002152 give_warning2(
2153 (char_u *)_("W22: Text found after :endfunction: %s"),
2154 p, TRUE);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002155 if (nextcmd != NULL)
2156 {
2157 /* Another command follows. If the line came from "eap" we
2158 * can simply point into it, otherwise we need to change
2159 * "eap->cmdlinep". */
2160 eap->nextcmd = nextcmd;
2161 if (line_to_free != NULL)
2162 {
2163 vim_free(*eap->cmdlinep);
2164 *eap->cmdlinep = line_to_free;
2165 line_to_free = NULL;
2166 }
2167 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002168 break;
2169 }
2170
2171 /* Increase indent inside "if", "while", "for" and "try", decrease
2172 * at "end". */
2173 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
2174 indent -= 2;
2175 else if (STRNCMP(p, "if", 2) == 0
2176 || STRNCMP(p, "wh", 2) == 0
2177 || STRNCMP(p, "for", 3) == 0
2178 || STRNCMP(p, "try", 3) == 0)
2179 indent += 2;
2180
2181 /* Check for defining a function inside this function. */
2182 if (checkforcmd(&p, "function", 2))
2183 {
2184 if (*p == '!')
2185 p = skipwhite(p + 1);
2186 p += eval_fname_script(p);
2187 vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL));
2188 if (*skipwhite(p) == '(')
2189 {
2190 ++nesting;
2191 indent += 2;
2192 }
2193 }
2194
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002195 /* Check for ":append", ":change", ":insert". */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002196 p = skip_range(p, NULL);
2197 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002198 || (p[0] == 'c'
2199 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
2200 && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
2201 && (STRNCMP(&p[3], "nge", 3) != 0
2202 || !ASCII_ISALPHA(p[6])))))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002203 || (p[0] == 'i'
2204 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
2205 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
2206 skip_until = vim_strsave((char_u *)".");
2207
2208 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
2209 arg = skipwhite(skiptowhite(p));
2210 if (arg[0] == '<' && arg[1] =='<'
2211 && ((p[0] == 'p' && p[1] == 'y'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +01002212 && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2213 || ((p[2] == '3' || p[2] == 'x')
2214 && !ASCII_ISALPHA(p[3]))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002215 || (p[0] == 'p' && p[1] == 'e'
2216 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2217 || (p[0] == 't' && p[1] == 'c'
2218 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2219 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2220 && !ASCII_ISALPHA(p[3]))
2221 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2222 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2223 || (p[0] == 'm' && p[1] == 'z'
2224 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
2225 ))
2226 {
2227 /* ":python <<" continues until a dot, like ":append" */
2228 p = skipwhite(arg + 2);
2229 if (*p == NUL)
2230 skip_until = vim_strsave((char_u *)".");
2231 else
2232 skip_until = vim_strsave(p);
2233 }
2234 }
2235
2236 /* Add the line to the function. */
2237 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002238 goto erret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002239
2240 /* Copy the line to newly allocated memory. get_one_sourceline()
2241 * allocates 250 bytes per line, this saves 80% on average. The cost
2242 * is an extra alloc/free. */
2243 p = vim_strsave(theline);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002244 if (p == NULL)
2245 goto erret;
2246 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002247
2248 /* Add NULL lines for continuation lines, so that the line count is
2249 * equal to the index in the growarray. */
2250 while (sourcing_lnum_off-- > 0)
2251 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
2252
2253 /* Check for end of eap->arg. */
2254 if (line_arg != NULL && *line_arg == NUL)
2255 line_arg = NULL;
2256 }
2257
2258 /* Don't define the function when skipping commands or when an error was
2259 * detected. */
2260 if (eap->skip || did_emsg)
2261 goto erret;
2262
2263 /*
2264 * If there are no errors, add the function
2265 */
2266 if (fudi.fd_dict == NULL)
2267 {
2268 v = find_var(name, &ht, FALSE);
2269 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
2270 {
2271 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
2272 name);
2273 goto erret;
2274 }
2275
2276 fp = find_func(name);
2277 if (fp != NULL)
2278 {
2279 if (!eap->forceit)
2280 {
2281 emsg_funcname(e_funcexts, name);
2282 goto erret;
2283 }
2284 if (fp->uf_calls > 0)
2285 {
2286 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
2287 name);
2288 goto erret;
2289 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002290 if (fp->uf_refcount > 1)
2291 {
2292 /* This function is referenced somewhere, don't redefine it but
2293 * create a new one. */
2294 --fp->uf_refcount;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002295 fp->uf_flags |= FC_REMOVED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002296 fp = NULL;
2297 overwrite = TRUE;
2298 }
2299 else
2300 {
2301 /* redefine existing function */
2302 ga_clear_strings(&(fp->uf_args));
2303 ga_clear_strings(&(fp->uf_lines));
Bram Moolenaard23a8232018-02-10 18:45:26 +01002304 VIM_CLEAR(name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002305 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002306 }
2307 }
2308 else
2309 {
2310 char numbuf[20];
2311
2312 fp = NULL;
2313 if (fudi.fd_newkey == NULL && !eap->forceit)
2314 {
2315 EMSG(_(e_funcdict));
2316 goto erret;
2317 }
2318 if (fudi.fd_di == NULL)
2319 {
2320 /* Can't add a function to a locked dictionary */
2321 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE))
2322 goto erret;
2323 }
2324 /* Can't change an existing function if it is locked */
2325 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE))
2326 goto erret;
2327
2328 /* Give the function a sequential number. Can only be used with a
2329 * Funcref! */
2330 vim_free(name);
2331 sprintf(numbuf, "%d", ++func_nr);
2332 name = vim_strsave((char_u *)numbuf);
2333 if (name == NULL)
2334 goto erret;
2335 }
2336
2337 if (fp == NULL)
2338 {
2339 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
2340 {
2341 int slen, plen;
2342 char_u *scriptname;
2343
2344 /* Check that the autoload name matches the script name. */
2345 j = FAIL;
2346 if (sourcing_name != NULL)
2347 {
2348 scriptname = autoload_name(name);
2349 if (scriptname != NULL)
2350 {
2351 p = vim_strchr(scriptname, '/');
2352 plen = (int)STRLEN(p);
2353 slen = (int)STRLEN(sourcing_name);
2354 if (slen > plen && fnamecmp(p,
2355 sourcing_name + slen - plen) == 0)
2356 j = OK;
2357 vim_free(scriptname);
2358 }
2359 }
2360 if (j == FAIL)
2361 {
2362 EMSG2(_("E746: Function name does not match script file name: %s"), name);
2363 goto erret;
2364 }
2365 }
2366
Bram Moolenaar58016442016-07-31 18:30:22 +02002367 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002368 if (fp == NULL)
2369 goto erret;
2370
2371 if (fudi.fd_dict != NULL)
2372 {
2373 if (fudi.fd_di == NULL)
2374 {
2375 /* add new dict entry */
2376 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
2377 if (fudi.fd_di == NULL)
2378 {
2379 vim_free(fp);
2380 goto erret;
2381 }
2382 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
2383 {
2384 vim_free(fudi.fd_di);
2385 vim_free(fp);
2386 goto erret;
2387 }
2388 }
2389 else
2390 /* overwrite existing dict entry */
2391 clear_tv(&fudi.fd_di->di_tv);
2392 fudi.fd_di->di_tv.v_type = VAR_FUNC;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002393 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002394
2395 /* behave like "dict" was used */
2396 flags |= FC_DICT;
2397 }
2398
2399 /* insert the new function in the function list */
2400 STRCPY(fp->uf_name, name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002401 if (overwrite)
2402 {
2403 hi = hash_find(&func_hashtab, name);
2404 hi->hi_key = UF2HIKEY(fp);
2405 }
2406 else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002407 {
2408 vim_free(fp);
2409 goto erret;
2410 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002411 fp->uf_refcount = 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002412 }
2413 fp->uf_args = newargs;
2414 fp->uf_lines = newlines;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002415 if ((flags & FC_CLOSURE) != 0)
2416 {
Bram Moolenaar58016442016-07-31 18:30:22 +02002417 if (register_closure(fp) == FAIL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002418 goto erret;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002419 }
2420 else
2421 fp->uf_scoped = NULL;
2422
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002423#ifdef FEAT_PROFILE
2424 fp->uf_tml_count = NULL;
2425 fp->uf_tml_total = NULL;
2426 fp->uf_tml_self = NULL;
2427 fp->uf_profiling = FALSE;
2428 if (prof_def_func())
2429 func_do_profile(fp);
2430#endif
2431 fp->uf_varargs = varargs;
2432 fp->uf_flags = flags;
2433 fp->uf_calls = 0;
2434 fp->uf_script_ID = current_SID;
2435 goto ret_free;
2436
2437erret:
2438 ga_clear_strings(&newargs);
2439errret_2:
2440 ga_clear_strings(&newlines);
2441ret_free:
2442 vim_free(skip_until);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002443 vim_free(line_to_free);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002444 vim_free(fudi.fd_newkey);
2445 vim_free(name);
2446 did_emsg |= saved_did_emsg;
2447 need_wait_return |= saved_wait_return;
2448}
2449
2450/*
2451 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
2452 * Return 2 if "p" starts with "s:".
2453 * Return 0 otherwise.
2454 */
2455 int
2456eval_fname_script(char_u *p)
2457{
2458 /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with
2459 * the standard library function. */
2460 if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0
2461 || MB_STRNICMP(p + 1, "SNR>", 4) == 0))
2462 return 5;
2463 if (p[0] == 's' && p[1] == ':')
2464 return 2;
2465 return 0;
2466}
2467
2468 int
2469translated_function_exists(char_u *name)
2470{
2471 if (builtin_function(name, -1))
2472 return find_internal_func(name) >= 0;
2473 return find_func(name) != NULL;
2474}
2475
2476/*
2477 * Return TRUE if a function "name" exists.
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002478 * If "no_defef" is TRUE, do not dereference a Funcref.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002479 */
2480 int
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002481function_exists(char_u *name, int no_deref)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002482{
2483 char_u *nm = name;
2484 char_u *p;
2485 int n = FALSE;
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002486 int flag;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002487
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002488 flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
2489 if (no_deref)
2490 flag |= TFN_NO_DEREF;
2491 p = trans_function_name(&nm, FALSE, flag, NULL, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002492 nm = skipwhite(nm);
2493
2494 /* Only accept "funcname", "funcname ", "funcname (..." and
2495 * "funcname(...", not "funcname!...". */
2496 if (p != NULL && (*nm == NUL || *nm == '('))
2497 n = translated_function_exists(p);
2498 vim_free(p);
2499 return n;
2500}
2501
2502 char_u *
2503get_expanded_name(char_u *name, int check)
2504{
2505 char_u *nm = name;
2506 char_u *p;
2507
2508 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL);
2509
2510 if (p != NULL && *nm == NUL)
2511 if (!check || translated_function_exists(p))
2512 return p;
2513
2514 vim_free(p);
2515 return NULL;
2516}
2517
2518#if defined(FEAT_PROFILE) || defined(PROTO)
2519/*
2520 * Start profiling function "fp".
2521 */
2522 static void
2523func_do_profile(ufunc_T *fp)
2524{
2525 int len = fp->uf_lines.ga_len;
2526
Bram Moolenaarad648092018-06-30 18:28:03 +02002527 if (!fp->uf_prof_initialized)
2528 {
2529 if (len == 0)
2530 len = 1; /* avoid getting error for allocating zero bytes */
2531 fp->uf_tm_count = 0;
2532 profile_zero(&fp->uf_tm_self);
2533 profile_zero(&fp->uf_tm_total);
2534 if (fp->uf_tml_count == NULL)
2535 fp->uf_tml_count = (int *)alloc_clear(
2536 (unsigned)(sizeof(int) * len));
2537 if (fp->uf_tml_total == NULL)
2538 fp->uf_tml_total = (proftime_T *)alloc_clear(
2539 (unsigned)(sizeof(proftime_T) * len));
2540 if (fp->uf_tml_self == NULL)
2541 fp->uf_tml_self = (proftime_T *)alloc_clear(
2542 (unsigned)(sizeof(proftime_T) * len));
2543 fp->uf_tml_idx = -1;
2544 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
2545 || fp->uf_tml_self == NULL)
2546 return; /* out of memory */
2547 fp->uf_prof_initialized = TRUE;
2548 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002549
2550 fp->uf_profiling = TRUE;
2551}
2552
2553/*
2554 * Dump the profiling results for all functions in file "fd".
2555 */
2556 void
2557func_dump_profile(FILE *fd)
2558{
2559 hashitem_T *hi;
2560 int todo;
2561 ufunc_T *fp;
2562 int i;
2563 ufunc_T **sorttab;
2564 int st_len = 0;
2565
2566 todo = (int)func_hashtab.ht_used;
2567 if (todo == 0)
2568 return; /* nothing to dump */
2569
2570 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo));
2571
2572 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
2573 {
2574 if (!HASHITEM_EMPTY(hi))
2575 {
2576 --todo;
2577 fp = HI2UF(hi);
Bram Moolenaarad648092018-06-30 18:28:03 +02002578 if (fp->uf_prof_initialized)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002579 {
2580 if (sorttab != NULL)
2581 sorttab[st_len++] = fp;
2582
2583 if (fp->uf_name[0] == K_SPECIAL)
2584 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
2585 else
2586 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
2587 if (fp->uf_tm_count == 1)
2588 fprintf(fd, "Called 1 time\n");
2589 else
2590 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
2591 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
2592 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
2593 fprintf(fd, "\n");
2594 fprintf(fd, "count total (s) self (s)\n");
2595
2596 for (i = 0; i < fp->uf_lines.ga_len; ++i)
2597 {
2598 if (FUNCLINE(fp, i) == NULL)
2599 continue;
2600 prof_func_line(fd, fp->uf_tml_count[i],
2601 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
2602 fprintf(fd, "%s\n", FUNCLINE(fp, i));
2603 }
2604 fprintf(fd, "\n");
2605 }
2606 }
2607 }
2608
2609 if (sorttab != NULL && st_len > 0)
2610 {
2611 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2612 prof_total_cmp);
2613 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
2614 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2615 prof_self_cmp);
2616 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
2617 }
2618
2619 vim_free(sorttab);
2620}
2621
2622 static void
2623prof_sort_list(
2624 FILE *fd,
2625 ufunc_T **sorttab,
2626 int st_len,
2627 char *title,
2628 int prefer_self) /* when equal print only self time */
2629{
2630 int i;
2631 ufunc_T *fp;
2632
2633 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
2634 fprintf(fd, "count total (s) self (s) function\n");
2635 for (i = 0; i < 20 && i < st_len; ++i)
2636 {
2637 fp = sorttab[i];
2638 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
2639 prefer_self);
2640 if (fp->uf_name[0] == K_SPECIAL)
2641 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
2642 else
2643 fprintf(fd, " %s()\n", fp->uf_name);
2644 }
2645 fprintf(fd, "\n");
2646}
2647
2648/*
2649 * Print the count and times for one function or function line.
2650 */
2651 static void
2652prof_func_line(
2653 FILE *fd,
2654 int count,
2655 proftime_T *total,
2656 proftime_T *self,
2657 int prefer_self) /* when equal print only self time */
2658{
2659 if (count > 0)
2660 {
2661 fprintf(fd, "%5d ", count);
2662 if (prefer_self && profile_equal(total, self))
2663 fprintf(fd, " ");
2664 else
2665 fprintf(fd, "%s ", profile_msg(total));
2666 if (!prefer_self && profile_equal(total, self))
2667 fprintf(fd, " ");
2668 else
2669 fprintf(fd, "%s ", profile_msg(self));
2670 }
2671 else
2672 fprintf(fd, " ");
2673}
2674
2675/*
2676 * Compare function for total time sorting.
2677 */
2678 static int
2679#ifdef __BORLANDC__
2680_RTLENTRYF
2681#endif
2682prof_total_cmp(const void *s1, const void *s2)
2683{
2684 ufunc_T *p1, *p2;
2685
2686 p1 = *(ufunc_T **)s1;
2687 p2 = *(ufunc_T **)s2;
2688 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
2689}
2690
2691/*
2692 * Compare function for self time sorting.
2693 */
2694 static int
2695#ifdef __BORLANDC__
2696_RTLENTRYF
2697#endif
2698prof_self_cmp(const void *s1, const void *s2)
2699{
2700 ufunc_T *p1, *p2;
2701
2702 p1 = *(ufunc_T **)s1;
2703 p2 = *(ufunc_T **)s2;
2704 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
2705}
2706
2707/*
2708 * Prepare profiling for entering a child or something else that is not
2709 * counted for the script/function itself.
2710 * Should always be called in pair with prof_child_exit().
2711 */
2712 void
2713prof_child_enter(
2714 proftime_T *tm) /* place to store waittime */
2715{
2716 funccall_T *fc = current_funccal;
2717
2718 if (fc != NULL && fc->func->uf_profiling)
2719 profile_start(&fc->prof_child);
2720 script_prof_save(tm);
2721}
2722
2723/*
2724 * Take care of time spent in a child.
2725 * Should always be called after prof_child_enter().
2726 */
2727 void
2728prof_child_exit(
2729 proftime_T *tm) /* where waittime was stored */
2730{
2731 funccall_T *fc = current_funccal;
2732
2733 if (fc != NULL && fc->func->uf_profiling)
2734 {
2735 profile_end(&fc->prof_child);
2736 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
2737 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
2738 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
2739 }
2740 script_prof_restore(tm);
2741}
2742
2743#endif /* FEAT_PROFILE */
2744
2745#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2746
2747/*
2748 * Function given to ExpandGeneric() to obtain the list of user defined
2749 * function names.
2750 */
2751 char_u *
2752get_user_func_name(expand_T *xp, int idx)
2753{
2754 static long_u done;
2755 static hashitem_T *hi;
2756 ufunc_T *fp;
2757
2758 if (idx == 0)
2759 {
2760 done = 0;
2761 hi = func_hashtab.ht_array;
2762 }
2763 if (done < func_hashtab.ht_used)
2764 {
2765 if (done++ > 0)
2766 ++hi;
2767 while (HASHITEM_EMPTY(hi))
2768 ++hi;
2769 fp = HI2UF(hi);
2770
Bram Moolenaarb49edc12016-07-23 15:47:34 +02002771 if ((fp->uf_flags & FC_DICT)
2772 || STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
2773 return (char_u *)""; /* don't show dict and lambda functions */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002774
2775 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
2776 return fp->uf_name; /* prevents overflow */
2777
2778 cat_func_name(IObuff, fp);
2779 if (xp->xp_context != EXPAND_USER_FUNC)
2780 {
2781 STRCAT(IObuff, "(");
2782 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
2783 STRCAT(IObuff, ")");
2784 }
2785 return IObuff;
2786 }
2787 return NULL;
2788}
2789
2790#endif /* FEAT_CMDL_COMPL */
2791
2792/*
2793 * ":delfunction {name}"
2794 */
2795 void
2796ex_delfunction(exarg_T *eap)
2797{
2798 ufunc_T *fp = NULL;
2799 char_u *p;
2800 char_u *name;
2801 funcdict_T fudi;
2802
2803 p = eap->arg;
2804 name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
2805 vim_free(fudi.fd_newkey);
2806 if (name == NULL)
2807 {
2808 if (fudi.fd_dict != NULL && !eap->skip)
2809 EMSG(_(e_funcref));
2810 return;
2811 }
2812 if (!ends_excmd(*skipwhite(p)))
2813 {
2814 vim_free(name);
2815 EMSG(_(e_trailing));
2816 return;
2817 }
2818 eap->nextcmd = check_nextcmd(p);
2819 if (eap->nextcmd != NULL)
2820 *p = NUL;
2821
2822 if (!eap->skip)
2823 fp = find_func(name);
2824 vim_free(name);
2825
2826 if (!eap->skip)
2827 {
2828 if (fp == NULL)
2829 {
Bram Moolenaard6abcd12017-06-22 19:15:24 +02002830 if (!eap->forceit)
2831 EMSG2(_(e_nofunc), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002832 return;
2833 }
2834 if (fp->uf_calls > 0)
2835 {
2836 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
2837 return;
2838 }
2839
2840 if (fudi.fd_dict != NULL)
2841 {
2842 /* Delete the dict item that refers to the function, it will
2843 * invoke func_unref() and possibly delete the function. */
2844 dictitem_remove(fudi.fd_dict, fudi.fd_di);
2845 }
2846 else
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002847 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002848 /* A normal function (not a numbered function or lambda) has a
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002849 * refcount of 1 for the entry in the hashtable. When deleting
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002850 * it and the refcount is more than one, it should be kept.
Bram Moolenaarba209902016-08-24 22:06:38 +02002851 * A numbered function and lambda should be kept if the refcount is
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002852 * one or more. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002853 if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002854 {
2855 /* Function is still referenced somewhere. Don't free it but
2856 * do remove it from the hashtable. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002857 if (func_remove(fp))
2858 fp->uf_refcount--;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002859 fp->uf_flags |= FC_DELETED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002860 }
2861 else
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002862 func_clear_free(fp, FALSE);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002863 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002864 }
2865}
2866
2867/*
2868 * Unreference a Function: decrement the reference count and free it when it
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002869 * becomes zero.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002870 */
2871 void
2872func_unref(char_u *name)
2873{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002874 ufunc_T *fp = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002875
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002876 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002877 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002878 fp = find_func(name);
2879 if (fp == NULL && isdigit(*name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002880 {
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002881#ifdef EXITFREE
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002882 if (!entered_free_all_mem)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002883#endif
Bram Moolenaar95f09602016-11-10 20:01:45 +01002884 internal_error("func_unref()");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002885 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002886 if (fp != NULL && --fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002887 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002888 /* Only delete it when it's not being used. Otherwise it's done
2889 * when "uf_calls" becomes zero. */
2890 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002891 func_clear_free(fp, FALSE);
Bram Moolenaar97baee82016-07-26 20:46:08 +02002892 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002893}
2894
2895/*
2896 * Unreference a Function: decrement the reference count and free it when it
2897 * becomes zero.
2898 */
2899 void
2900func_ptr_unref(ufunc_T *fp)
2901{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002902 if (fp != NULL && --fp->uf_refcount <= 0)
2903 {
2904 /* Only delete it when it's not being used. Otherwise it's done
2905 * when "uf_calls" becomes zero. */
2906 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002907 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002908 }
2909}
2910
2911/*
2912 * Count a reference to a Function.
2913 */
2914 void
2915func_ref(char_u *name)
2916{
2917 ufunc_T *fp;
2918
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002919 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002920 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002921 fp = find_func(name);
2922 if (fp != NULL)
2923 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002924 else if (isdigit(*name))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002925 /* Only give an error for a numbered function.
2926 * Fail silently, when named or lambda function isn't found. */
Bram Moolenaar95f09602016-11-10 20:01:45 +01002927 internal_error("func_ref()");
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002928}
2929
2930/*
2931 * Count a reference to a Function.
2932 */
2933 void
2934func_ptr_ref(ufunc_T *fp)
2935{
2936 if (fp != NULL)
2937 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002938}
2939
2940/*
2941 * Return TRUE if items in "fc" do not have "copyID". That means they are not
2942 * referenced from anywhere that is in use.
2943 */
2944 static int
2945can_free_funccal(funccall_T *fc, int copyID)
2946{
2947 return (fc->l_varlist.lv_copyID != copyID
2948 && fc->l_vars.dv_copyID != copyID
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02002949 && fc->l_avars.dv_copyID != copyID
2950 && fc->fc_copyID != copyID);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002951}
2952
2953/*
2954 * ":return [expr]"
2955 */
2956 void
2957ex_return(exarg_T *eap)
2958{
2959 char_u *arg = eap->arg;
2960 typval_T rettv;
2961 int returning = FALSE;
2962
2963 if (current_funccal == NULL)
2964 {
2965 EMSG(_("E133: :return not inside a function"));
2966 return;
2967 }
2968
2969 if (eap->skip)
2970 ++emsg_skip;
2971
2972 eap->nextcmd = NULL;
2973 if ((*arg != NUL && *arg != '|' && *arg != '\n')
2974 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
2975 {
2976 if (!eap->skip)
2977 returning = do_return(eap, FALSE, TRUE, &rettv);
2978 else
2979 clear_tv(&rettv);
2980 }
2981 /* It's safer to return also on error. */
2982 else if (!eap->skip)
2983 {
Bram Moolenaarfabaf752017-12-23 17:26:11 +01002984 /* In return statement, cause_abort should be force_abort. */
2985 update_force_abort();
2986
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002987 /*
2988 * Return unless the expression evaluation has been cancelled due to an
2989 * aborting error, an interrupt, or an exception.
2990 */
2991 if (!aborting())
2992 returning = do_return(eap, FALSE, TRUE, NULL);
2993 }
2994
2995 /* When skipping or the return gets pending, advance to the next command
2996 * in this line (!returning). Otherwise, ignore the rest of the line.
2997 * Following lines will be ignored by get_func_line(). */
2998 if (returning)
2999 eap->nextcmd = NULL;
3000 else if (eap->nextcmd == NULL) /* no argument */
3001 eap->nextcmd = check_nextcmd(arg);
3002
3003 if (eap->skip)
3004 --emsg_skip;
3005}
3006
3007/*
3008 * ":1,25call func(arg1, arg2)" function call.
3009 */
3010 void
3011ex_call(exarg_T *eap)
3012{
3013 char_u *arg = eap->arg;
3014 char_u *startarg;
3015 char_u *name;
3016 char_u *tofree;
3017 int len;
3018 typval_T rettv;
3019 linenr_T lnum;
3020 int doesrange;
3021 int failed = FALSE;
3022 funcdict_T fudi;
3023 partial_T *partial = NULL;
3024
3025 if (eap->skip)
3026 {
3027 /* trans_function_name() doesn't work well when skipping, use eval0()
3028 * instead to skip to any following command, e.g. for:
3029 * :if 0 | call dict.foo().bar() | endif */
3030 ++emsg_skip;
3031 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3032 clear_tv(&rettv);
3033 --emsg_skip;
3034 return;
3035 }
3036
3037 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial);
3038 if (fudi.fd_newkey != NULL)
3039 {
3040 /* Still need to give an error message for missing key. */
3041 EMSG2(_(e_dictkey), fudi.fd_newkey);
3042 vim_free(fudi.fd_newkey);
3043 }
3044 if (tofree == NULL)
3045 return;
3046
3047 /* Increase refcount on dictionary, it could get deleted when evaluating
3048 * the arguments. */
3049 if (fudi.fd_dict != NULL)
3050 ++fudi.fd_dict->dv_refcount;
3051
3052 /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3053 * contents. For VAR_PARTIAL get its partial, unless we already have one
3054 * from trans_function_name(). */
3055 len = (int)STRLEN(tofree);
3056 name = deref_func_name(tofree, &len,
3057 partial != NULL ? NULL : &partial, FALSE);
3058
3059 /* Skip white space to allow ":call func ()". Not good, but required for
3060 * backward compatibility. */
3061 startarg = skipwhite(arg);
3062 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3063
3064 if (*startarg != '(')
3065 {
3066 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3067 goto end;
3068 }
3069
3070 /*
3071 * When skipping, evaluate the function once, to find the end of the
3072 * arguments.
3073 * When the function takes a range, this is discovered after the first
3074 * call, and the loop is broken.
3075 */
3076 if (eap->skip)
3077 {
3078 ++emsg_skip;
3079 lnum = eap->line2; /* do it once, also with an invalid range */
3080 }
3081 else
3082 lnum = eap->line1;
3083 for ( ; lnum <= eap->line2; ++lnum)
3084 {
3085 if (!eap->skip && eap->addr_count > 0)
3086 {
3087 curwin->w_cursor.lnum = lnum;
3088 curwin->w_cursor.col = 0;
3089#ifdef FEAT_VIRTUALEDIT
3090 curwin->w_cursor.coladd = 0;
3091#endif
3092 }
3093 arg = startarg;
3094 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3095 eap->line1, eap->line2, &doesrange,
3096 !eap->skip, partial, fudi.fd_dict) == FAIL)
3097 {
3098 failed = TRUE;
3099 break;
3100 }
Bram Moolenaarc6f9f732018-02-11 19:06:26 +01003101 if (has_watchexpr())
3102 dbg_check_breakpoint(eap);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003103
3104 /* Handle a function returning a Funcref, Dictionary or List. */
3105 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3106 {
3107 failed = TRUE;
3108 break;
3109 }
3110
3111 clear_tv(&rettv);
3112 if (doesrange || eap->skip)
3113 break;
3114
3115 /* Stop when immediately aborting on error, or when an interrupt
3116 * occurred or an exception was thrown but not caught.
3117 * get_func_tv() returned OK, so that the check for trailing
3118 * characters below is executed. */
3119 if (aborting())
3120 break;
3121 }
3122 if (eap->skip)
3123 --emsg_skip;
3124
3125 if (!failed)
3126 {
3127 /* Check for trailing illegal characters and a following command. */
3128 if (!ends_excmd(*arg))
3129 {
3130 emsg_severe = TRUE;
3131 EMSG(_(e_trailing));
3132 }
3133 else
3134 eap->nextcmd = check_nextcmd(arg);
3135 }
3136
3137end:
3138 dict_unref(fudi.fd_dict);
3139 vim_free(tofree);
3140}
3141
3142/*
3143 * Return from a function. Possibly makes the return pending. Also called
3144 * for a pending return at the ":endtry" or after returning from an extra
3145 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
3146 * when called due to a ":return" command. "rettv" may point to a typval_T
3147 * with the return rettv. Returns TRUE when the return can be carried out,
3148 * FALSE when the return gets pending.
3149 */
3150 int
3151do_return(
3152 exarg_T *eap,
3153 int reanimate,
3154 int is_cmd,
3155 void *rettv)
3156{
3157 int idx;
3158 struct condstack *cstack = eap->cstack;
3159
3160 if (reanimate)
3161 /* Undo the return. */
3162 current_funccal->returned = FALSE;
3163
3164 /*
3165 * Cleanup (and inactivate) conditionals, but stop when a try conditional
3166 * not in its finally clause (which then is to be executed next) is found.
3167 * In this case, make the ":return" pending for execution at the ":endtry".
3168 * Otherwise, return normally.
3169 */
3170 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3171 if (idx >= 0)
3172 {
3173 cstack->cs_pending[idx] = CSTP_RETURN;
3174
3175 if (!is_cmd && !reanimate)
3176 /* A pending return again gets pending. "rettv" points to an
3177 * allocated variable with the rettv of the original ":return"'s
3178 * argument if present or is NULL else. */
3179 cstack->cs_rettv[idx] = rettv;
3180 else
3181 {
3182 /* When undoing a return in order to make it pending, get the stored
3183 * return rettv. */
3184 if (reanimate)
3185 rettv = current_funccal->rettv;
3186
3187 if (rettv != NULL)
3188 {
3189 /* Store the value of the pending return. */
3190 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
3191 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3192 else
3193 EMSG(_(e_outofmem));
3194 }
3195 else
3196 cstack->cs_rettv[idx] = NULL;
3197
3198 if (reanimate)
3199 {
3200 /* The pending return value could be overwritten by a ":return"
3201 * without argument in a finally clause; reset the default
3202 * return value. */
3203 current_funccal->rettv->v_type = VAR_NUMBER;
3204 current_funccal->rettv->vval.v_number = 0;
3205 }
3206 }
3207 report_make_pending(CSTP_RETURN, rettv);
3208 }
3209 else
3210 {
3211 current_funccal->returned = TRUE;
3212
3213 /* If the return is carried out now, store the return value. For
3214 * a return immediately after reanimation, the value is already
3215 * there. */
3216 if (!reanimate && rettv != NULL)
3217 {
3218 clear_tv(current_funccal->rettv);
3219 *current_funccal->rettv = *(typval_T *)rettv;
3220 if (!is_cmd)
3221 vim_free(rettv);
3222 }
3223 }
3224
3225 return idx < 0;
3226}
3227
3228/*
3229 * Free the variable with a pending return value.
3230 */
3231 void
3232discard_pending_return(void *rettv)
3233{
3234 free_tv((typval_T *)rettv);
3235}
3236
3237/*
3238 * Generate a return command for producing the value of "rettv". The result
3239 * is an allocated string. Used by report_pending() for verbose messages.
3240 */
3241 char_u *
3242get_return_cmd(void *rettv)
3243{
3244 char_u *s = NULL;
3245 char_u *tofree = NULL;
3246 char_u numbuf[NUMBUFLEN];
3247
3248 if (rettv != NULL)
3249 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
3250 if (s == NULL)
3251 s = (char_u *)"";
3252
3253 STRCPY(IObuff, ":return ");
3254 STRNCPY(IObuff + 8, s, IOSIZE - 8);
3255 if (STRLEN(s) + 8 >= IOSIZE)
3256 STRCPY(IObuff + IOSIZE - 4, "...");
3257 vim_free(tofree);
3258 return vim_strsave(IObuff);
3259}
3260
3261/*
3262 * Get next function line.
3263 * Called by do_cmdline() to get the next line.
3264 * Returns allocated string, or NULL for end of function.
3265 */
3266 char_u *
3267get_func_line(
3268 int c UNUSED,
3269 void *cookie,
3270 int indent UNUSED)
3271{
3272 funccall_T *fcp = (funccall_T *)cookie;
3273 ufunc_T *fp = fcp->func;
3274 char_u *retval;
3275 garray_T *gap; /* growarray with function lines */
3276
3277 /* If breakpoints have been added/deleted need to check for it. */
3278 if (fcp->dbg_tick != debug_tick)
3279 {
3280 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3281 sourcing_lnum);
3282 fcp->dbg_tick = debug_tick;
3283 }
3284#ifdef FEAT_PROFILE
3285 if (do_profiling == PROF_YES)
3286 func_line_end(cookie);
3287#endif
3288
3289 gap = &fp->uf_lines;
3290 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3291 || fcp->returned)
3292 retval = NULL;
3293 else
3294 {
3295 /* Skip NULL lines (continuation lines). */
3296 while (fcp->linenr < gap->ga_len
3297 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
3298 ++fcp->linenr;
3299 if (fcp->linenr >= gap->ga_len)
3300 retval = NULL;
3301 else
3302 {
3303 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
3304 sourcing_lnum = fcp->linenr;
3305#ifdef FEAT_PROFILE
3306 if (do_profiling == PROF_YES)
3307 func_line_start(cookie);
3308#endif
3309 }
3310 }
3311
3312 /* Did we encounter a breakpoint? */
3313 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
3314 {
3315 dbg_breakpoint(fp->uf_name, sourcing_lnum);
3316 /* Find next breakpoint. */
3317 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3318 sourcing_lnum);
3319 fcp->dbg_tick = debug_tick;
3320 }
3321
3322 return retval;
3323}
3324
3325#if defined(FEAT_PROFILE) || defined(PROTO)
3326/*
3327 * Called when starting to read a function line.
3328 * "sourcing_lnum" must be correct!
3329 * When skipping lines it may not actually be executed, but we won't find out
3330 * until later and we need to store the time now.
3331 */
3332 void
3333func_line_start(void *cookie)
3334{
3335 funccall_T *fcp = (funccall_T *)cookie;
3336 ufunc_T *fp = fcp->func;
3337
3338 if (fp->uf_profiling && sourcing_lnum >= 1
3339 && sourcing_lnum <= fp->uf_lines.ga_len)
3340 {
3341 fp->uf_tml_idx = sourcing_lnum - 1;
3342 /* Skip continuation lines. */
3343 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
3344 --fp->uf_tml_idx;
3345 fp->uf_tml_execed = FALSE;
3346 profile_start(&fp->uf_tml_start);
3347 profile_zero(&fp->uf_tml_children);
3348 profile_get_wait(&fp->uf_tml_wait);
3349 }
3350}
3351
3352/*
3353 * Called when actually executing a function line.
3354 */
3355 void
3356func_line_exec(void *cookie)
3357{
3358 funccall_T *fcp = (funccall_T *)cookie;
3359 ufunc_T *fp = fcp->func;
3360
3361 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3362 fp->uf_tml_execed = TRUE;
3363}
3364
3365/*
3366 * Called when done with a function line.
3367 */
3368 void
3369func_line_end(void *cookie)
3370{
3371 funccall_T *fcp = (funccall_T *)cookie;
3372 ufunc_T *fp = fcp->func;
3373
3374 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3375 {
3376 if (fp->uf_tml_execed)
3377 {
3378 ++fp->uf_tml_count[fp->uf_tml_idx];
3379 profile_end(&fp->uf_tml_start);
3380 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
3381 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
3382 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
3383 &fp->uf_tml_children);
3384 }
3385 fp->uf_tml_idx = -1;
3386 }
3387}
3388#endif
3389
3390/*
3391 * Return TRUE if the currently active function should be ended, because a
3392 * return was encountered or an error occurred. Used inside a ":while".
3393 */
3394 int
3395func_has_ended(void *cookie)
3396{
3397 funccall_T *fcp = (funccall_T *)cookie;
3398
3399 /* Ignore the "abort" flag if the abortion behavior has been changed due to
3400 * an error inside a try conditional. */
3401 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3402 || fcp->returned);
3403}
3404
3405/*
3406 * return TRUE if cookie indicates a function which "abort"s on errors.
3407 */
3408 int
3409func_has_abort(
3410 void *cookie)
3411{
3412 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
3413}
3414
3415
3416/*
3417 * Turn "dict.Func" into a partial for "Func" bound to "dict".
3418 * Don't do this when "Func" is already a partial that was bound
3419 * explicitly (pt_auto is FALSE).
3420 * Changes "rettv" in-place.
3421 * Returns the updated "selfdict_in".
3422 */
3423 dict_T *
3424make_partial(dict_T *selfdict_in, typval_T *rettv)
3425{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003426 char_u *fname;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003427 char_u *tofree = NULL;
3428 ufunc_T *fp;
3429 char_u fname_buf[FLEN_FIXED + 1];
3430 int error;
3431 dict_T *selfdict = selfdict_in;
3432
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003433 if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL)
3434 fp = rettv->vval.v_partial->pt_func;
3435 else
3436 {
3437 fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string
3438 : rettv->vval.v_partial->pt_name;
3439 /* Translate "s:func" to the stored function name. */
3440 fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3441 fp = find_func(fname);
3442 vim_free(tofree);
3443 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003444
3445 if (fp != NULL && (fp->uf_flags & FC_DICT))
3446 {
3447 partial_T *pt = (partial_T *)alloc_clear(sizeof(partial_T));
3448
3449 if (pt != NULL)
3450 {
3451 pt->pt_refcount = 1;
3452 pt->pt_dict = selfdict;
3453 pt->pt_auto = TRUE;
3454 selfdict = NULL;
3455 if (rettv->v_type == VAR_FUNC)
3456 {
3457 /* Just a function: Take over the function name and use
3458 * selfdict. */
3459 pt->pt_name = rettv->vval.v_string;
3460 }
3461 else
3462 {
3463 partial_T *ret_pt = rettv->vval.v_partial;
3464 int i;
3465
3466 /* Partial: copy the function name, use selfdict and copy
3467 * args. Can't take over name or args, the partial might
3468 * be referenced elsewhere. */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003469 if (ret_pt->pt_name != NULL)
3470 {
3471 pt->pt_name = vim_strsave(ret_pt->pt_name);
3472 func_ref(pt->pt_name);
3473 }
3474 else
3475 {
3476 pt->pt_func = ret_pt->pt_func;
3477 func_ptr_ref(pt->pt_func);
3478 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003479 if (ret_pt->pt_argc > 0)
3480 {
3481 pt->pt_argv = (typval_T *)alloc(
3482 sizeof(typval_T) * ret_pt->pt_argc);
3483 if (pt->pt_argv == NULL)
3484 /* out of memory: drop the arguments */
3485 pt->pt_argc = 0;
3486 else
3487 {
3488 pt->pt_argc = ret_pt->pt_argc;
3489 for (i = 0; i < pt->pt_argc; i++)
3490 copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3491 }
3492 }
3493 partial_unref(ret_pt);
3494 }
3495 rettv->v_type = VAR_PARTIAL;
3496 rettv->vval.v_partial = pt;
3497 }
3498 }
3499 return selfdict;
3500}
3501
3502/*
3503 * Return the name of the executed function.
3504 */
3505 char_u *
3506func_name(void *cookie)
3507{
3508 return ((funccall_T *)cookie)->func->uf_name;
3509}
3510
3511/*
3512 * Return the address holding the next breakpoint line for a funccall cookie.
3513 */
3514 linenr_T *
3515func_breakpoint(void *cookie)
3516{
3517 return &((funccall_T *)cookie)->breakpoint;
3518}
3519
3520/*
3521 * Return the address holding the debug tick for a funccall cookie.
3522 */
3523 int *
3524func_dbg_tick(void *cookie)
3525{
3526 return &((funccall_T *)cookie)->dbg_tick;
3527}
3528
3529/*
3530 * Return the nesting level for a funccall cookie.
3531 */
3532 int
3533func_level(void *cookie)
3534{
3535 return ((funccall_T *)cookie)->level;
3536}
3537
3538/*
3539 * Return TRUE when a function was ended by a ":return" command.
3540 */
3541 int
3542current_func_returned(void)
3543{
3544 return current_funccal->returned;
3545}
3546
3547/*
3548 * Save the current function call pointer, and set it to NULL.
3549 * Used when executing autocommands and for ":source".
3550 */
3551 void *
3552save_funccal(void)
3553{
3554 funccall_T *fc = current_funccal;
3555
3556 current_funccal = NULL;
3557 return (void *)fc;
3558}
3559
3560 void
3561restore_funccal(void *vfc)
3562{
3563 funccall_T *fc = (funccall_T *)vfc;
3564
3565 current_funccal = fc;
3566}
3567
3568 int
3569free_unref_funccal(int copyID, int testing)
3570{
3571 int did_free = FALSE;
3572 int did_free_funccal = FALSE;
3573 funccall_T *fc, **pfc;
3574
3575 for (pfc = &previous_funccal; *pfc != NULL; )
3576 {
3577 if (can_free_funccal(*pfc, copyID))
3578 {
3579 fc = *pfc;
3580 *pfc = fc->caller;
3581 free_funccal(fc, TRUE);
3582 did_free = TRUE;
3583 did_free_funccal = TRUE;
3584 }
3585 else
3586 pfc = &(*pfc)->caller;
3587 }
3588 if (did_free_funccal)
3589 /* When a funccal was freed some more items might be garbage
3590 * collected, so run again. */
3591 (void)garbage_collect(testing);
3592
3593 return did_free;
3594}
3595
3596/*
Bram Moolenaarba209902016-08-24 22:06:38 +02003597 * Get function call environment based on backtrace debug level
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003598 */
3599 static funccall_T *
3600get_funccal(void)
3601{
3602 int i;
3603 funccall_T *funccal;
3604 funccall_T *temp_funccal;
3605
3606 funccal = current_funccal;
3607 if (debug_backtrace_level > 0)
3608 {
3609 for (i = 0; i < debug_backtrace_level; i++)
3610 {
3611 temp_funccal = funccal->caller;
3612 if (temp_funccal)
3613 funccal = temp_funccal;
3614 else
3615 /* backtrace level overflow. reset to max */
3616 debug_backtrace_level = i;
3617 }
3618 }
3619 return funccal;
3620}
3621
3622/*
3623 * Return the hashtable used for local variables in the current funccal.
3624 * Return NULL if there is no current funccal.
3625 */
3626 hashtab_T *
3627get_funccal_local_ht()
3628{
3629 if (current_funccal == NULL)
3630 return NULL;
3631 return &get_funccal()->l_vars.dv_hashtab;
3632}
3633
3634/*
3635 * Return the l: scope variable.
3636 * Return NULL if there is no current funccal.
3637 */
3638 dictitem_T *
3639get_funccal_local_var()
3640{
3641 if (current_funccal == NULL)
3642 return NULL;
3643 return &get_funccal()->l_vars_var;
3644}
3645
3646/*
3647 * Return the hashtable used for argument in the current funccal.
3648 * Return NULL if there is no current funccal.
3649 */
3650 hashtab_T *
3651get_funccal_args_ht()
3652{
3653 if (current_funccal == NULL)
3654 return NULL;
3655 return &get_funccal()->l_avars.dv_hashtab;
3656}
3657
3658/*
3659 * Return the a: scope variable.
3660 * Return NULL if there is no current funccal.
3661 */
3662 dictitem_T *
3663get_funccal_args_var()
3664{
3665 if (current_funccal == NULL)
3666 return NULL;
Bram Moolenaarc7d9eac2017-02-01 20:26:51 +01003667 return &get_funccal()->l_avars_var;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003668}
3669
3670/*
3671 * Clear the current_funccal and return the old value.
3672 * Caller is expected to invoke restore_current_funccal().
3673 */
3674 void *
3675clear_current_funccal()
3676{
3677 funccall_T *f = current_funccal;
3678
3679 current_funccal = NULL;
3680 return f;
3681}
3682
3683 void
3684restore_current_funccal(void *f)
3685{
3686 current_funccal = f;
3687}
3688
3689/*
3690 * List function variables, if there is a function.
3691 */
3692 void
3693list_func_vars(int *first)
3694{
3695 if (current_funccal != NULL)
3696 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
3697 (char_u *)"l:", FALSE, first);
3698}
3699
3700/*
3701 * If "ht" is the hashtable for local variables in the current funccal, return
3702 * the dict that contains it.
3703 * Otherwise return NULL.
3704 */
3705 dict_T *
3706get_current_funccal_dict(hashtab_T *ht)
3707{
3708 if (current_funccal != NULL
3709 && ht == &current_funccal->l_vars.dv_hashtab)
3710 return &current_funccal->l_vars;
3711 return NULL;
3712}
3713
3714/*
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003715 * Search hashitem in parent scope.
3716 */
3717 hashitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003718find_hi_in_scoped_ht(char_u *name, hashtab_T **pht)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003719{
3720 funccall_T *old_current_funccal = current_funccal;
3721 hashtab_T *ht;
3722 hashitem_T *hi = NULL;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003723 char_u *varname;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003724
3725 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3726 return NULL;
3727
3728 /* Search in parent scope which is possible to reference from lambda */
3729 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar58016442016-07-31 18:30:22 +02003730 while (current_funccal != NULL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003731 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003732 ht = find_var_ht(name, &varname);
3733 if (ht != NULL && *varname != NUL)
Bram Moolenaar58016442016-07-31 18:30:22 +02003734 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003735 hi = hash_find(ht, varname);
Bram Moolenaar58016442016-07-31 18:30:22 +02003736 if (!HASHITEM_EMPTY(hi))
3737 {
3738 *pht = ht;
3739 break;
3740 }
3741 }
3742 if (current_funccal == current_funccal->func->uf_scoped)
3743 break;
3744 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003745 }
3746 current_funccal = old_current_funccal;
3747
3748 return hi;
3749}
3750
3751/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003752 * Search variable in parent scope.
3753 */
3754 dictitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003755find_var_in_scoped_ht(char_u *name, int no_autoload)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003756{
3757 dictitem_T *v = NULL;
3758 funccall_T *old_current_funccal = current_funccal;
3759 hashtab_T *ht;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003760 char_u *varname;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003761
3762 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3763 return NULL;
3764
3765 /* Search in parent scope which is possible to reference from lambda */
3766 current_funccal = current_funccal->func->uf_scoped;
3767 while (current_funccal)
3768 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003769 ht = find_var_ht(name, &varname);
3770 if (ht != NULL && *varname != NUL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003771 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003772 v = find_var_in_ht(ht, *name, varname, no_autoload);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003773 if (v != NULL)
3774 break;
3775 }
3776 if (current_funccal == current_funccal->func->uf_scoped)
3777 break;
3778 current_funccal = current_funccal->func->uf_scoped;
3779 }
3780 current_funccal = old_current_funccal;
3781
3782 return v;
3783}
3784
3785/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003786 * Set "copyID + 1" in previous_funccal and callers.
3787 */
3788 int
3789set_ref_in_previous_funccal(int copyID)
3790{
3791 int abort = FALSE;
3792 funccall_T *fc;
3793
3794 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
3795 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003796 fc->fc_copyID = copyID + 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003797 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1,
3798 NULL);
3799 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1,
3800 NULL);
3801 }
3802 return abort;
3803}
3804
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003805 static int
3806set_ref_in_funccal(funccall_T *fc, int copyID)
3807{
3808 int abort = FALSE;
3809
3810 if (fc->fc_copyID != copyID)
3811 {
3812 fc->fc_copyID = copyID;
3813 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL);
3814 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL);
3815 abort = abort || set_ref_in_func(NULL, fc->func, copyID);
3816 }
3817 return abort;
3818}
3819
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003820/*
3821 * Set "copyID" in all local vars and arguments in the call stack.
3822 */
3823 int
3824set_ref_in_call_stack(int copyID)
3825{
3826 int abort = FALSE;
3827 funccall_T *fc;
3828
3829 for (fc = current_funccal; fc != NULL; fc = fc->caller)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003830 abort = abort || set_ref_in_funccal(fc, copyID);
3831 return abort;
3832}
3833
3834/*
3835 * Set "copyID" in all functions available by name.
3836 */
3837 int
3838set_ref_in_functions(int copyID)
3839{
3840 int todo;
3841 hashitem_T *hi = NULL;
3842 int abort = FALSE;
3843 ufunc_T *fp;
3844
3845 todo = (int)func_hashtab.ht_used;
3846 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003847 {
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003848 if (!HASHITEM_EMPTY(hi))
3849 {
3850 --todo;
3851 fp = HI2UF(hi);
3852 if (!func_name_refcount(fp->uf_name))
3853 abort = abort || set_ref_in_func(NULL, fp, copyID);
3854 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003855 }
3856 return abort;
3857}
3858
3859/*
3860 * Set "copyID" in all function arguments.
3861 */
3862 int
3863set_ref_in_func_args(int copyID)
3864{
3865 int i;
3866 int abort = FALSE;
3867
3868 for (i = 0; i < funcargs.ga_len; ++i)
3869 abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
3870 copyID, NULL, NULL);
3871 return abort;
3872}
3873
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003874/*
3875 * Mark all lists and dicts referenced through function "name" with "copyID".
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003876 * Returns TRUE if setting references failed somehow.
3877 */
3878 int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003879set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003880{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003881 ufunc_T *fp = fp_in;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003882 funccall_T *fc;
3883 int error = ERROR_NONE;
3884 char_u fname_buf[FLEN_FIXED + 1];
3885 char_u *tofree = NULL;
3886 char_u *fname;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003887 int abort = FALSE;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003888
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003889 if (name == NULL && fp_in == NULL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003890 return FALSE;
3891
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003892 if (fp_in == NULL)
3893 {
3894 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
3895 fp = find_func(fname);
3896 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003897 if (fp != NULL)
3898 {
3899 for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003900 abort = abort || set_ref_in_funccal(fc, copyID);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003901 }
3902 vim_free(tofree);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003903 return abort;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003904}
3905
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003906#endif /* FEAT_EVAL */