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