blob: 6887c2c5c6ea4b08f8e3a214ef91f88d67fdf6ba [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 Moolenaar93343722018-07-10 19:39:18 +020017// flags used in uf_flags
18#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
24#define FC_SANDBOX 0x40 // function defined in the sandbox
Bram Moolenaara9b579f2016-07-17 18:29:19 +020025
26/* From user function to hashitem and back. */
Bram Moolenaara9b579f2016-07-17 18:29:19 +020027#define UF2HIKEY(fp) ((fp)->uf_name)
Bram Moolenaar98aefe72018-12-13 22:20:09 +010028#define HIKEY2UF(p) ((ufunc_T *)((p) - offsetof(ufunc_T, uf_name)))
Bram Moolenaara9b579f2016-07-17 18:29:19 +020029#define HI2UF(hi) HIKEY2UF((hi)->hi_key)
30
31#define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
32#define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
33
Bram Moolenaara9b579f2016-07-17 18:29:19 +020034/*
35 * All user-defined functions are found in this hashtable.
36 */
37static hashtab_T func_hashtab;
38
39/* Used by get_func_tv() */
40static garray_T funcargs = GA_EMPTY;
41
42/* pointer to funccal for currently active function */
43funccall_T *current_funccal = NULL;
44
Bram Moolenaar6914c642017-04-01 21:21:30 +020045/* Pointer to list of previously used funccal, still around because some
Bram Moolenaara9b579f2016-07-17 18:29:19 +020046 * item in it is still being used. */
47funccall_T *previous_funccal = NULL;
48
49static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
50static char *e_funcdict = N_("E717: Dictionary entry already exists");
51static char *e_funcref = N_("E718: Funcref required");
52static char *e_nofunc = N_("E130: Unknown function: %s");
53
54#ifdef FEAT_PROFILE
55static void func_do_profile(ufunc_T *fp);
56static void prof_sort_list(FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self);
57static void prof_func_line(FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self);
58static int
59# ifdef __BORLANDC__
60 _RTLENTRYF
61# endif
62 prof_total_cmp(const void *s1, const void *s2);
63static int
64# ifdef __BORLANDC__
65 _RTLENTRYF
66# endif
67 prof_self_cmp(const void *s1, const void *s2);
68#endif
Bram Moolenaarbc7ce672016-08-01 22:49:22 +020069static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force);
Bram Moolenaara9b579f2016-07-17 18:29:19 +020070
71 void
72func_init()
73{
74 hash_init(&func_hashtab);
75}
76
Bram Moolenaar4f0383b2016-07-19 22:43:11 +020077/*
78 * Get function arguments.
79 */
Bram Moolenaara9b579f2016-07-17 18:29:19 +020080 static int
81get_function_args(
82 char_u **argp,
83 char_u endchar,
84 garray_T *newargs,
85 int *varargs,
86 int skip)
87{
88 int mustend = FALSE;
89 char_u *arg = *argp;
90 char_u *p = arg;
91 int c;
92 int i;
93
94 if (newargs != NULL)
95 ga_init2(newargs, (int)sizeof(char_u *), 3);
96
97 if (varargs != NULL)
98 *varargs = FALSE;
99
100 /*
101 * Isolate the arguments: "arg1, arg2, ...)"
102 */
103 while (*p != endchar)
104 {
105 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
106 {
107 if (varargs != NULL)
108 *varargs = TRUE;
109 p += 3;
110 mustend = TRUE;
111 }
112 else
113 {
114 arg = p;
115 while (ASCII_ISALNUM(*p) || *p == '_')
116 ++p;
117 if (arg == p || isdigit(*arg)
118 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
119 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
120 {
121 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100122 semsg(_("E125: Illegal argument: %s"), arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200123 break;
124 }
125 if (newargs != NULL && ga_grow(newargs, 1) == FAIL)
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200126 goto err_ret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200127 if (newargs != NULL)
128 {
129 c = *p;
130 *p = NUL;
131 arg = vim_strsave(arg);
132 if (arg == NULL)
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200133 {
134 *p = c;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200135 goto err_ret;
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200136 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200137
138 /* Check for duplicate argument name. */
139 for (i = 0; i < newargs->ga_len; ++i)
140 if (STRCMP(((char_u **)(newargs->ga_data))[i], arg) == 0)
141 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100142 semsg(_("E853: Duplicate argument name: %s"), arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200143 vim_free(arg);
144 goto err_ret;
145 }
146 ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg;
147 newargs->ga_len++;
148
149 *p = c;
150 }
151 if (*p == ',')
152 ++p;
153 else
154 mustend = TRUE;
155 }
156 p = skipwhite(p);
157 if (mustend && *p != endchar)
158 {
159 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100160 semsg(_(e_invarg2), *argp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200161 break;
162 }
163 }
Bram Moolenaar4f0383b2016-07-19 22:43:11 +0200164 if (*p != endchar)
165 goto err_ret;
166 ++p; /* skip "endchar" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200167
168 *argp = p;
169 return OK;
170
171err_ret:
172 if (newargs != NULL)
173 ga_clear_strings(newargs);
174 return FAIL;
175}
176
177/*
Bram Moolenaar58016442016-07-31 18:30:22 +0200178 * Register function "fp" as using "current_funccal" as its scope.
179 */
180 static int
181register_closure(ufunc_T *fp)
182{
Bram Moolenaar8dd3a432016-08-01 20:46:25 +0200183 if (fp->uf_scoped == current_funccal)
184 /* no change */
185 return OK;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +0200186 funccal_unref(fp->uf_scoped, fp, FALSE);
Bram Moolenaar58016442016-07-31 18:30:22 +0200187 fp->uf_scoped = current_funccal;
188 current_funccal->fc_refcount++;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +0200189
Bram Moolenaar58016442016-07-31 18:30:22 +0200190 if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL)
191 return FAIL;
192 ((ufunc_T **)current_funccal->fc_funcs.ga_data)
193 [current_funccal->fc_funcs.ga_len++] = fp;
Bram Moolenaar58016442016-07-31 18:30:22 +0200194 return OK;
195}
196
197/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200198 * Parse a lambda expression and get a Funcref from "*arg".
199 * Return OK or FAIL. Returns NOTDONE for dict or {expr}.
200 */
201 int
202get_lambda_tv(char_u **arg, typval_T *rettv, int evaluate)
203{
204 garray_T newargs;
205 garray_T newlines;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200206 garray_T *pnewargs;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200207 ufunc_T *fp = NULL;
208 int varargs;
209 int ret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200210 char_u *start = skipwhite(*arg + 1);
211 char_u *s, *e;
212 static int lambda_no = 0;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200213 int *old_eval_lavars = eval_lavars_used;
214 int eval_lavars = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200215
216 ga_init(&newargs);
217 ga_init(&newlines);
218
219 /* First, check if this is a lambda expression. "->" must exist. */
220 ret = get_function_args(&start, '-', NULL, NULL, TRUE);
221 if (ret == FAIL || *start != '>')
222 return NOTDONE;
223
224 /* Parse the arguments again. */
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200225 if (evaluate)
226 pnewargs = &newargs;
227 else
228 pnewargs = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200229 *arg = skipwhite(*arg + 1);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200230 ret = get_function_args(arg, '-', pnewargs, &varargs, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200231 if (ret == FAIL || **arg != '>')
232 goto errret;
233
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +0200234 /* Set up a flag for checking local variables and arguments. */
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200235 if (evaluate)
236 eval_lavars_used = &eval_lavars;
237
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200238 /* Get the start and the end of the expression. */
239 *arg = skipwhite(*arg + 1);
240 s = *arg;
241 ret = skip_expr(arg);
242 if (ret == FAIL)
243 goto errret;
244 e = *arg;
245 *arg = skipwhite(*arg);
246 if (**arg != '}')
247 goto errret;
248 ++*arg;
249
250 if (evaluate)
251 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200252 int len, flags = 0;
253 char_u *p;
254 char_u name[20];
255 partial_T *pt;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200256
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200257 sprintf((char*)name, "<lambda>%d", ++lambda_no);
258
Bram Moolenaar58016442016-07-31 18:30:22 +0200259 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200260 if (fp == NULL)
261 goto errret;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200262 pt = (partial_T *)alloc_clear((unsigned)sizeof(partial_T));
263 if (pt == NULL)
264 {
265 vim_free(fp);
266 goto errret;
267 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200268
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200269 ga_init2(&newlines, (int)sizeof(char_u *), 1);
270 if (ga_grow(&newlines, 1) == FAIL)
271 goto errret;
272
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200273 /* Add "return " before the expression. */
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200274 len = 7 + e - s + 1;
275 p = (char_u *)alloc(len);
276 if (p == NULL)
277 goto errret;
278 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
279 STRCPY(p, "return ");
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200280 vim_strncpy(p + 7, s, e - s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200281
282 fp->uf_refcount = 1;
283 STRCPY(fp->uf_name, name);
284 hash_add(&func_hashtab, UF2HIKEY(fp));
285 fp->uf_args = newargs;
286 fp->uf_lines = newlines;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200287 if (current_funccal != NULL && eval_lavars)
288 {
Bram Moolenaar10ce39a2016-07-29 22:37:06 +0200289 flags |= FC_CLOSURE;
Bram Moolenaar58016442016-07-31 18:30:22 +0200290 if (register_closure(fp) == FAIL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200291 goto errret;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200292 }
293 else
294 fp->uf_scoped = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200295
296#ifdef FEAT_PROFILE
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200297 if (prof_def_func())
298 func_do_profile(fp);
299#endif
Bram Moolenaar93343722018-07-10 19:39:18 +0200300 if (sandbox)
301 flags |= FC_SANDBOX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200302 fp->uf_varargs = TRUE;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +0200303 fp->uf_flags = flags;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200304 fp->uf_calls = 0;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200305 fp->uf_script_ctx = current_sctx;
306 fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200307
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;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100389 semsg(_(ermsg), p);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200390 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 {
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200509 if (current_sctx.sc_sid <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200510 *error = ERROR_SCRIPT;
511 else
512 {
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200513 sprintf((char *)fname_buf + 3, "%ld_", (long)current_sctx.sc_sid);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200514 i = (int)STRLEN(fname_buf);
515 }
516 }
517 if (i + STRLEN(name + llen) < FLEN_FIXED)
518 {
519 STRCPY(fname_buf + i, name + llen);
520 fname = fname_buf;
521 }
522 else
523 {
524 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
525 if (fname == NULL)
526 *error = ERROR_OTHER;
527 else
528 {
529 *tofree = fname;
530 mch_memmove(fname, fname_buf, (size_t)i);
531 STRCPY(fname + i, name + llen);
532 }
533 }
534 }
535 else
536 fname = name;
537 return fname;
538}
539
540/*
541 * Find a function by name, return pointer to it in ufuncs.
542 * Return NULL for unknown function.
543 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200544 ufunc_T *
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200545find_func(char_u *name)
546{
547 hashitem_T *hi;
548
549 hi = hash_find(&func_hashtab, name);
550 if (!HASHITEM_EMPTY(hi))
551 return HI2UF(hi);
552 return NULL;
553}
554
555/*
556 * Copy the function name of "fp" to buffer "buf".
557 * "buf" must be able to hold the function name plus three bytes.
558 * Takes care of script-local function names.
559 */
560 static void
561cat_func_name(char_u *buf, ufunc_T *fp)
562{
563 if (fp->uf_name[0] == K_SPECIAL)
564 {
565 STRCPY(buf, "<SNR>");
566 STRCAT(buf, fp->uf_name + 3);
567 }
568 else
569 STRCPY(buf, fp->uf_name);
570}
571
572/*
573 * Add a number variable "name" to dict "dp" with value "nr".
574 */
575 static void
576add_nr_var(
577 dict_T *dp,
578 dictitem_T *v,
579 char *name,
580 varnumber_T nr)
581{
582 STRCPY(v->di_key, name);
583 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
584 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
585 v->di_tv.v_type = VAR_NUMBER;
586 v->di_tv.v_lock = VAR_FIXED;
587 v->di_tv.vval.v_number = nr;
588}
589
590/*
591 * Free "fc" and what it contains.
592 */
593 static void
594free_funccal(
595 funccall_T *fc,
596 int free_val) /* a: vars were allocated */
597{
598 listitem_T *li;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200599 int i;
600
601 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
602 {
603 ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i];
604
Bram Moolenaarbc7ce672016-08-01 22:49:22 +0200605 /* When garbage collecting a funccall_T may be freed before the
606 * function that references it, clear its uf_scoped field.
607 * The function may have been redefined and point to another
608 * funccall_T, don't clear it then. */
609 if (fp != NULL && fp->uf_scoped == fc)
610 fp->uf_scoped = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200611 }
Bram Moolenaar58016442016-07-31 18:30:22 +0200612 ga_clear(&fc->fc_funcs);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200613
614 /* The a: variables typevals may not have been allocated, only free the
615 * allocated variables. */
616 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
617
618 /* free all l: variables */
619 vars_clear(&fc->l_vars.dv_hashtab);
620
621 /* Free the a:000 variables if they were allocated. */
622 if (free_val)
623 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
624 clear_tv(&li->li_tv);
625
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200626 func_ptr_unref(fc->func);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200627 vim_free(fc);
628}
629
630/*
Bram Moolenaar6914c642017-04-01 21:21:30 +0200631 * Handle the last part of returning from a function: free the local hashtable.
632 * Unless it is still in use by a closure.
633 */
634 static void
635cleanup_function_call(funccall_T *fc)
636{
637 current_funccal = fc->caller;
638
639 /* If the a:000 list and the l: and a: dicts are not referenced and there
640 * is no closure using it, we can free the funccall_T and what's in it. */
641 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
642 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
643 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT
644 && fc->fc_refcount <= 0)
645 {
646 free_funccal(fc, FALSE);
647 }
648 else
649 {
650 hashitem_T *hi;
651 listitem_T *li;
652 int todo;
653 dictitem_T *v;
654
655 /* "fc" is still in use. This can happen when returning "a:000",
656 * assigning "l:" to a global variable or defining a closure.
657 * Link "fc" in the list for garbage collection later. */
658 fc->caller = previous_funccal;
659 previous_funccal = fc;
660
661 /* Make a copy of the a: variables, since we didn't do that above. */
662 todo = (int)fc->l_avars.dv_hashtab.ht_used;
663 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
664 {
665 if (!HASHITEM_EMPTY(hi))
666 {
667 --todo;
668 v = HI2DI(hi);
669 copy_tv(&v->di_tv, &v->di_tv);
670 }
671 }
672
673 /* Make a copy of the a:000 items, since we didn't do that above. */
674 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
675 copy_tv(&li->li_tv, &li->li_tv);
676 }
677}
678
679/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200680 * Call a user function.
681 */
682 static void
683call_user_func(
684 ufunc_T *fp, /* pointer to function */
685 int argcount, /* nr of args */
686 typval_T *argvars, /* arguments */
687 typval_T *rettv, /* return value */
688 linenr_T firstline, /* first line of range */
689 linenr_T lastline, /* last line of range */
690 dict_T *selfdict) /* Dictionary for "self" */
691{
692 char_u *save_sourcing_name;
693 linenr_T save_sourcing_lnum;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200694 sctx_T save_current_sctx;
Bram Moolenaar93343722018-07-10 19:39:18 +0200695 int using_sandbox = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200696 funccall_T *fc;
697 int save_did_emsg;
698 static int depth = 0;
699 dictitem_T *v;
700 int fixvar_idx = 0; /* index in fixvar[] */
701 int i;
702 int ai;
703 int islambda = FALSE;
704 char_u numbuf[NUMBUFLEN];
705 char_u *name;
706 size_t len;
707#ifdef FEAT_PROFILE
708 proftime_T wait_start;
709 proftime_T call_start;
Bram Moolenaarad648092018-06-30 18:28:03 +0200710 int started_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200711#endif
712
713 /* If depth of calling is getting too high, don't execute the function */
714 if (depth >= p_mfd)
715 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100716 emsg(_("E132: Function call depth is higher than 'maxfuncdepth'"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200717 rettv->v_type = VAR_NUMBER;
718 rettv->vval.v_number = -1;
719 return;
720 }
721 ++depth;
722
723 line_breakcheck(); /* check for CTRL-C hit */
724
725 fc = (funccall_T *)alloc(sizeof(funccall_T));
726 fc->caller = current_funccal;
727 current_funccal = fc;
728 fc->func = fp;
729 fc->rettv = rettv;
730 rettv->vval.v_number = 0;
731 fc->linenr = 0;
732 fc->returned = FALSE;
733 fc->level = ex_nesting_level;
734 /* Check if this function has a breakpoint. */
735 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
736 fc->dbg_tick = debug_tick;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200737 /* Set up fields for closure. */
738 fc->fc_refcount = 0;
739 fc->fc_copyID = 0;
740 ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1);
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200741 func_ptr_ref(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200742
743 if (STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
744 islambda = TRUE;
745
746 /*
747 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
748 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
749 * each argument variable and saves a lot of time.
750 */
751 /*
752 * Init l: variables.
753 */
754 init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE);
755 if (selfdict != NULL)
756 {
757 /* Set l:self to "selfdict". Use "name" to avoid a warning from
758 * some compiler that checks the destination size. */
759 v = &fc->fixvar[fixvar_idx++].var;
760 name = v->di_key;
761 STRCPY(name, "self");
762 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
763 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
764 v->di_tv.v_type = VAR_DICT;
765 v->di_tv.v_lock = 0;
766 v->di_tv.vval.v_dict = selfdict;
767 ++selfdict->dv_refcount;
768 }
769
770 /*
771 * Init a: variables.
772 * Set a:0 to "argcount".
773 * Set a:000 to a list with room for the "..." arguments.
774 */
775 init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE);
776 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
777 (varnumber_T)(argcount - fp->uf_args.ga_len));
778 /* Use "name" to avoid a warning from some compiler that checks the
779 * destination size. */
780 v = &fc->fixvar[fixvar_idx++].var;
781 name = v->di_key;
782 STRCPY(name, "000");
783 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
784 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
785 v->di_tv.v_type = VAR_LIST;
786 v->di_tv.v_lock = VAR_FIXED;
787 v->di_tv.vval.v_list = &fc->l_varlist;
788 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
789 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
790 fc->l_varlist.lv_lock = VAR_FIXED;
791
792 /*
793 * Set a:firstline to "firstline" and a:lastline to "lastline".
794 * Set a:name to named arguments.
795 * Set a:N to the "..." arguments.
796 */
797 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
798 (varnumber_T)firstline);
799 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
800 (varnumber_T)lastline);
801 for (i = 0; i < argcount; ++i)
802 {
803 int addlocal = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200804
805 ai = i - fp->uf_args.ga_len;
806 if (ai < 0)
807 {
808 /* named argument a:name */
809 name = FUNCARG(fp, i);
810 if (islambda)
811 addlocal = TRUE;
812 }
813 else
814 {
815 /* "..." argument a:1, a:2, etc. */
816 sprintf((char *)numbuf, "%d", ai + 1);
817 name = numbuf;
818 }
819 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
820 {
821 v = &fc->fixvar[fixvar_idx++].var;
822 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200823 }
824 else
825 {
826 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
827 + STRLEN(name)));
828 if (v == NULL)
829 break;
830 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX | DI_FLAGS_ALLOC;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200831 }
832 STRCPY(v->di_key, name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200833
834 /* Note: the values are copied directly to avoid alloc/free.
835 * "argvars" must have VAR_FIXED for v_lock. */
836 v->di_tv = argvars[i];
837 v->di_tv.v_lock = VAR_FIXED;
838
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200839 if (addlocal)
840 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200841 /* Named arguments should be accessed without the "a:" prefix in
842 * lambda expressions. Add to the l: dict. */
843 copy_tv(&v->di_tv, &v->di_tv);
844 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200845 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200846 else
847 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200848
849 if (ai >= 0 && ai < MAX_FUNC_ARGS)
850 {
851 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
852 fc->l_listitems[ai].li_tv = argvars[i];
853 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
854 }
855 }
856
857 /* Don't redraw while executing the function. */
858 ++RedrawingDisabled;
859 save_sourcing_name = sourcing_name;
860 save_sourcing_lnum = sourcing_lnum;
861 sourcing_lnum = 1;
Bram Moolenaar93343722018-07-10 19:39:18 +0200862
863 if (fp->uf_flags & FC_SANDBOX)
864 {
865 using_sandbox = TRUE;
866 ++sandbox;
867 }
868
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200869 /* need space for function name + ("function " + 3) or "[number]" */
870 len = (save_sourcing_name == NULL ? 0 : STRLEN(save_sourcing_name))
871 + STRLEN(fp->uf_name) + 20;
872 sourcing_name = alloc((unsigned)len);
873 if (sourcing_name != NULL)
874 {
875 if (save_sourcing_name != NULL
876 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
877 sprintf((char *)sourcing_name, "%s[%d]..",
878 save_sourcing_name, (int)save_sourcing_lnum);
879 else
880 STRCPY(sourcing_name, "function ");
881 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
882
883 if (p_verbose >= 12)
884 {
885 ++no_wait_return;
886 verbose_enter_scroll();
887
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100888 smsg(_("calling %s"), sourcing_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200889 if (p_verbose >= 14)
890 {
891 char_u buf[MSG_BUF_LEN];
892 char_u numbuf2[NUMBUFLEN];
893 char_u *tofree;
894 char_u *s;
895
Bram Moolenaar32526b32019-01-19 17:43:09 +0100896 msg_puts("(");
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200897 for (i = 0; i < argcount; ++i)
898 {
899 if (i > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +0100900 msg_puts(", ");
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200901 if (argvars[i].v_type == VAR_NUMBER)
902 msg_outnum((long)argvars[i].vval.v_number);
903 else
904 {
905 /* Do not want errors such as E724 here. */
906 ++emsg_off;
907 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
908 --emsg_off;
909 if (s != NULL)
910 {
911 if (vim_strsize(s) > MSG_BUF_CLEN)
912 {
913 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
914 s = buf;
915 }
Bram Moolenaar32526b32019-01-19 17:43:09 +0100916 msg_puts((char *)s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200917 vim_free(tofree);
918 }
919 }
920 }
Bram Moolenaar32526b32019-01-19 17:43:09 +0100921 msg_puts(")");
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200922 }
Bram Moolenaar32526b32019-01-19 17:43:09 +0100923 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200924
925 verbose_leave_scroll();
926 --no_wait_return;
927 }
928 }
929#ifdef FEAT_PROFILE
930 if (do_profiling == PROF_YES)
931 {
932 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
Bram Moolenaarad648092018-06-30 18:28:03 +0200933 {
934 started_profiling = TRUE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200935 func_do_profile(fp);
Bram Moolenaarad648092018-06-30 18:28:03 +0200936 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200937 if (fp->uf_profiling
938 || (fc->caller != NULL && fc->caller->func->uf_profiling))
939 {
940 ++fp->uf_tm_count;
941 profile_start(&call_start);
942 profile_zero(&fp->uf_tm_children);
943 }
944 script_prof_save(&wait_start);
945 }
946#endif
947
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200948 save_current_sctx = current_sctx;
949 current_sctx = fp->uf_script_ctx;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200950 save_did_emsg = did_emsg;
951 did_emsg = FALSE;
952
953 /* call do_cmdline() to execute the lines */
954 do_cmdline(NULL, get_func_line, (void *)fc,
955 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
956
957 --RedrawingDisabled;
958
959 /* when the function was aborted because of an error, return -1 */
960 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
961 {
962 clear_tv(rettv);
963 rettv->v_type = VAR_NUMBER;
964 rettv->vval.v_number = -1;
965 }
966
967#ifdef FEAT_PROFILE
968 if (do_profiling == PROF_YES && (fp->uf_profiling
969 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
970 {
971 profile_end(&call_start);
972 profile_sub_wait(&wait_start, &call_start);
973 profile_add(&fp->uf_tm_total, &call_start);
974 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
975 if (fc->caller != NULL && fc->caller->func->uf_profiling)
976 {
977 profile_add(&fc->caller->func->uf_tm_children, &call_start);
978 profile_add(&fc->caller->func->uf_tml_children, &call_start);
979 }
Bram Moolenaarad648092018-06-30 18:28:03 +0200980 if (started_profiling)
981 // make a ":profdel func" stop profiling the function
982 fp->uf_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200983 }
984#endif
985
986 /* when being verbose, mention the return value */
987 if (p_verbose >= 12)
988 {
989 ++no_wait_return;
990 verbose_enter_scroll();
991
992 if (aborting())
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100993 smsg(_("%s aborted"), sourcing_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200994 else if (fc->rettv->v_type == VAR_NUMBER)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100995 smsg(_("%s returning #%ld"), sourcing_name,
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200996 (long)fc->rettv->vval.v_number);
997 else
998 {
999 char_u buf[MSG_BUF_LEN];
1000 char_u numbuf2[NUMBUFLEN];
1001 char_u *tofree;
1002 char_u *s;
1003
1004 /* The value may be very long. Skip the middle part, so that we
1005 * have some idea how it starts and ends. smsg() would always
1006 * truncate it at the end. Don't want errors such as E724 here. */
1007 ++emsg_off;
1008 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
1009 --emsg_off;
1010 if (s != NULL)
1011 {
1012 if (vim_strsize(s) > MSG_BUF_CLEN)
1013 {
1014 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
1015 s = buf;
1016 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001017 smsg(_("%s returning %s"), sourcing_name, s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001018 vim_free(tofree);
1019 }
1020 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01001021 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001022
1023 verbose_leave_scroll();
1024 --no_wait_return;
1025 }
1026
1027 vim_free(sourcing_name);
1028 sourcing_name = save_sourcing_name;
1029 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001030 current_sctx = save_current_sctx;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001031#ifdef FEAT_PROFILE
1032 if (do_profiling == PROF_YES)
1033 script_prof_restore(&wait_start);
1034#endif
Bram Moolenaar93343722018-07-10 19:39:18 +02001035 if (using_sandbox)
1036 --sandbox;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001037
1038 if (p_verbose >= 12 && sourcing_name != NULL)
1039 {
1040 ++no_wait_return;
1041 verbose_enter_scroll();
1042
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001043 smsg(_("continuing in %s"), sourcing_name);
Bram Moolenaar32526b32019-01-19 17:43:09 +01001044 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001045
1046 verbose_leave_scroll();
1047 --no_wait_return;
1048 }
1049
1050 did_emsg |= save_did_emsg;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001051 --depth;
1052
Bram Moolenaar6914c642017-04-01 21:21:30 +02001053 cleanup_function_call(fc);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001054}
1055
1056/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001057 * Unreference "fc": decrement the reference count and free it when it
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001058 * becomes zero. "fp" is detached from "fc".
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001059 * When "force" is TRUE we are exiting.
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001060 */
1061 static void
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001062funccal_unref(funccall_T *fc, ufunc_T *fp, int force)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001063{
1064 funccall_T **pfc;
1065 int i;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001066
1067 if (fc == NULL)
1068 return;
1069
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001070 if (--fc->fc_refcount <= 0 && (force || (
1071 fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001072 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001073 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001074 for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001075 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001076 if (fc == *pfc)
1077 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001078 *pfc = fc->caller;
1079 free_funccal(fc, TRUE);
1080 return;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001081 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001082 }
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001083 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001084 if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001085 ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001086}
1087
1088/*
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001089 * Remove the function from the function hashtable. If the function was
1090 * deleted while it still has references this was already done.
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001091 * Return TRUE if the entry was deleted, FALSE if it wasn't found.
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001092 */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001093 static int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001094func_remove(ufunc_T *fp)
1095{
1096 hashitem_T *hi = hash_find(&func_hashtab, UF2HIKEY(fp));
1097
1098 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001099 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001100 hash_remove(&func_hashtab, hi);
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001101 return TRUE;
1102 }
1103 return FALSE;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001104}
1105
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02001106 static void
1107func_clear_items(ufunc_T *fp)
1108{
1109 ga_clear_strings(&(fp->uf_args));
1110 ga_clear_strings(&(fp->uf_lines));
1111#ifdef FEAT_PROFILE
1112 vim_free(fp->uf_tml_count);
1113 fp->uf_tml_count = NULL;
1114 vim_free(fp->uf_tml_total);
1115 fp->uf_tml_total = NULL;
1116 vim_free(fp->uf_tml_self);
1117 fp->uf_tml_self = NULL;
1118#endif
1119}
1120
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001121/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001122 * Free all things that a function contains. Does not free the function
1123 * itself, use func_free() for that.
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001124 * When "force" is TRUE we are exiting.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001125 */
1126 static void
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001127func_clear(ufunc_T *fp, int force)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001128{
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001129 if (fp->uf_cleared)
1130 return;
1131 fp->uf_cleared = TRUE;
1132
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001133 /* clear this function */
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02001134 func_clear_items(fp);
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001135 funccal_unref(fp->uf_scoped, fp, force);
1136}
1137
1138/*
1139 * Free a function and remove it from the list of functions. Does not free
1140 * what a function contains, call func_clear() first.
1141 */
1142 static void
1143func_free(ufunc_T *fp)
1144{
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001145 /* only remove it when not done already, otherwise we would remove a newer
1146 * version of the function */
1147 if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0)
1148 func_remove(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001149
1150 vim_free(fp);
1151}
1152
Bram Moolenaarc2574872016-08-11 22:51:05 +02001153/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001154 * Free all things that a function contains and free the function itself.
1155 * When "force" is TRUE we are exiting.
1156 */
1157 static void
1158func_clear_free(ufunc_T *fp, int force)
1159{
1160 func_clear(fp, force);
1161 func_free(fp);
1162}
1163
1164/*
Bram Moolenaarc2574872016-08-11 22:51:05 +02001165 * There are two kinds of function names:
1166 * 1. ordinary names, function defined with :function
1167 * 2. numbered functions and lambdas
1168 * For the first we only count the name stored in func_hashtab as a reference,
1169 * using function() does not count as a reference, because the function is
1170 * looked up by name.
1171 */
1172 static int
1173func_name_refcount(char_u *name)
1174{
1175 return isdigit(*name) || *name == '<';
1176}
1177
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001178static funccal_entry_T *funccal_stack = NULL;
1179
1180/*
1181 * Save the current function call pointer, and set it to NULL.
1182 * Used when executing autocommands and for ":source".
1183 */
1184 void
1185save_funccal(funccal_entry_T *entry)
1186{
1187 entry->top_funccal = current_funccal;
1188 entry->next = funccal_stack;
1189 funccal_stack = entry;
1190 current_funccal = NULL;
1191}
1192
1193 void
1194restore_funccal(void)
1195{
1196 if (funccal_stack == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001197 iemsg("INTERNAL: restore_funccal()");
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001198 else
1199 {
1200 current_funccal = funccal_stack->top_funccal;
1201 funccal_stack = funccal_stack->next;
1202 }
1203}
1204
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001205#if defined(EXITFREE) || defined(PROTO)
1206 void
1207free_all_functions(void)
1208{
1209 hashitem_T *hi;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001210 ufunc_T *fp;
1211 long_u skipped = 0;
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001212 long_u todo = 1;
1213 long_u used;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001214
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001215 /* Clean up the current_funccal chain and the funccal stack. */
Bram Moolenaar6914c642017-04-01 21:21:30 +02001216 while (current_funccal != NULL)
1217 {
1218 clear_tv(current_funccal->rettv);
1219 cleanup_function_call(current_funccal);
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001220 if (current_funccal == NULL && funccal_stack != NULL)
1221 restore_funccal();
Bram Moolenaar6914c642017-04-01 21:21:30 +02001222 }
1223
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001224 /* First clear what the functions contain. Since this may lower the
1225 * reference count of a function, it may also free a function and change
1226 * the hash table. Restart if that happens. */
1227 while (todo > 0)
1228 {
1229 todo = func_hashtab.ht_used;
1230 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
1231 if (!HASHITEM_EMPTY(hi))
1232 {
1233 /* Only free functions that are not refcounted, those are
1234 * supposed to be freed when no longer referenced. */
1235 fp = HI2UF(hi);
1236 if (func_name_refcount(fp->uf_name))
1237 ++skipped;
1238 else
1239 {
1240 used = func_hashtab.ht_used;
1241 func_clear(fp, TRUE);
1242 if (used != func_hashtab.ht_used)
1243 {
1244 skipped = 0;
1245 break;
1246 }
1247 }
1248 --todo;
1249 }
1250 }
1251
1252 /* Now actually free the functions. Need to start all over every time,
1253 * because func_free() may change the hash table. */
1254 skipped = 0;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001255 while (func_hashtab.ht_used > skipped)
1256 {
1257 todo = func_hashtab.ht_used;
1258 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001259 if (!HASHITEM_EMPTY(hi))
1260 {
Bram Moolenaarc2574872016-08-11 22:51:05 +02001261 --todo;
1262 /* Only free functions that are not refcounted, those are
1263 * supposed to be freed when no longer referenced. */
1264 fp = HI2UF(hi);
1265 if (func_name_refcount(fp->uf_name))
1266 ++skipped;
1267 else
1268 {
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001269 func_free(fp);
Bram Moolenaarc2574872016-08-11 22:51:05 +02001270 skipped = 0;
1271 break;
1272 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001273 }
Bram Moolenaarc2574872016-08-11 22:51:05 +02001274 }
1275 if (skipped == 0)
1276 hash_clear(&func_hashtab);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001277}
1278#endif
1279
1280/*
1281 * Return TRUE if "name" looks like a builtin function name: starts with a
1282 * lower case letter and doesn't contain AUTOLOAD_CHAR.
1283 * "len" is the length of "name", or -1 for NUL terminated.
1284 */
1285 static int
1286builtin_function(char_u *name, int len)
1287{
1288 char_u *p;
1289
1290 if (!ASCII_ISLOWER(name[0]))
1291 return FALSE;
1292 p = vim_strchr(name, AUTOLOAD_CHAR);
1293 return p == NULL || (len > 0 && p > name + len);
1294}
1295
1296 int
1297func_call(
1298 char_u *name,
1299 typval_T *args,
1300 partial_T *partial,
1301 dict_T *selfdict,
1302 typval_T *rettv)
1303{
1304 listitem_T *item;
1305 typval_T argv[MAX_FUNC_ARGS + 1];
1306 int argc = 0;
1307 int dummy;
1308 int r = 0;
1309
1310 for (item = args->vval.v_list->lv_first; item != NULL;
1311 item = item->li_next)
1312 {
1313 if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
1314 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001315 emsg(_("E699: Too many arguments"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001316 break;
1317 }
1318 /* Make a copy of each argument. This is needed to be able to set
1319 * v_lock to VAR_FIXED in the copy without changing the original list.
1320 */
1321 copy_tv(&item->li_tv, &argv[argc++]);
1322 }
1323
1324 if (item == NULL)
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001325 r = call_func(name, (int)STRLEN(name), rettv, argc, argv, NULL,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001326 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1327 &dummy, TRUE, partial, selfdict);
1328
1329 /* Free the arguments. */
1330 while (argc > 0)
1331 clear_tv(&argv[--argc]);
1332
1333 return r;
1334}
1335
1336/*
1337 * Call a function with its resolved parameters
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001338 *
1339 * "argv_func", when not NULL, can be used to fill in arguments only when the
1340 * invoked function uses them. It is called like this:
1341 * new_argcount = argv_func(current_argcount, argv, called_func_argcount)
1342 *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001343 * Return FAIL when the function can't be called, OK otherwise.
1344 * Also returns OK when an error was encountered while executing the function.
1345 */
1346 int
1347call_func(
1348 char_u *funcname, /* name of the function */
1349 int len, /* length of "name" */
1350 typval_T *rettv, /* return value goes here */
1351 int argcount_in, /* number of "argvars" */
1352 typval_T *argvars_in, /* vars for arguments, must have "argcount"
1353 PLUS ONE elements! */
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001354 int (* argv_func)(int, typval_T *, int),
1355 /* function to fill in argvars */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001356 linenr_T firstline, /* first line of range */
1357 linenr_T lastline, /* last line of range */
1358 int *doesrange, /* return: function handled range */
1359 int evaluate,
1360 partial_T *partial, /* optional, can be NULL */
1361 dict_T *selfdict_in) /* Dictionary for "self" */
1362{
1363 int ret = FAIL;
1364 int error = ERROR_NONE;
1365 int i;
1366 ufunc_T *fp;
1367 char_u fname_buf[FLEN_FIXED + 1];
1368 char_u *tofree = NULL;
1369 char_u *fname;
1370 char_u *name;
1371 int argcount = argcount_in;
1372 typval_T *argvars = argvars_in;
1373 dict_T *selfdict = selfdict_in;
1374 typval_T argv[MAX_FUNC_ARGS + 1]; /* used when "partial" is not NULL */
1375 int argv_clear = 0;
1376
1377 /* Make a copy of the name, if it comes from a funcref variable it could
1378 * be changed or deleted in the called function. */
1379 name = vim_strnsave(funcname, len);
1380 if (name == NULL)
1381 return ret;
1382
1383 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1384
1385 *doesrange = FALSE;
1386
1387 if (partial != NULL)
1388 {
1389 /* When the function has a partial with a dict and there is a dict
1390 * argument, use the dict argument. That is backwards compatible.
1391 * When the dict was bound explicitly use the one from the partial. */
1392 if (partial->pt_dict != NULL
1393 && (selfdict_in == NULL || !partial->pt_auto))
1394 selfdict = partial->pt_dict;
1395 if (error == ERROR_NONE && partial->pt_argc > 0)
1396 {
1397 for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear)
1398 copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]);
1399 for (i = 0; i < argcount_in; ++i)
1400 argv[i + argv_clear] = argvars_in[i];
1401 argvars = argv;
1402 argcount = partial->pt_argc + argcount_in;
1403 }
1404 }
1405
1406
Bram Moolenaarb4518562018-05-22 18:31:35 +02001407 /*
1408 * Execute the function if executing and no errors were detected.
1409 */
1410 if (!evaluate)
1411 {
1412 // Not evaluating, which means the return value is unknown. This
1413 // matters for giving error messages.
1414 rettv->v_type = VAR_UNKNOWN;
1415 }
1416 else if (error == ERROR_NONE)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001417 {
1418 char_u *rfname = fname;
1419
1420 /* Ignore "g:" before a function name. */
1421 if (fname[0] == 'g' && fname[1] == ':')
1422 rfname = fname + 2;
1423
1424 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
1425 rettv->vval.v_number = 0;
1426 error = ERROR_UNKNOWN;
1427
1428 if (!builtin_function(rfname, -1))
1429 {
1430 /*
1431 * User defined function.
1432 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001433 if (partial != NULL && partial->pt_func != NULL)
1434 fp = partial->pt_func;
1435 else
1436 fp = find_func(rfname);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001437
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001438 /* Trigger FuncUndefined event, may load the function. */
1439 if (fp == NULL
1440 && apply_autocmds(EVENT_FUNCUNDEFINED,
1441 rfname, rfname, TRUE, NULL)
1442 && !aborting())
1443 {
1444 /* executed an autocommand, search for the function again */
1445 fp = find_func(rfname);
1446 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001447 /* Try loading a package. */
1448 if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
1449 {
1450 /* loaded a package, search for the function again */
1451 fp = find_func(rfname);
1452 }
1453
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001454 if (fp != NULL && (fp->uf_flags & FC_DELETED))
1455 error = ERROR_DELETED;
1456 else if (fp != NULL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001457 {
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001458 if (argv_func != NULL)
1459 argcount = argv_func(argcount, argvars, fp->uf_args.ga_len);
1460
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001461 if (fp->uf_flags & FC_RANGE)
1462 *doesrange = TRUE;
1463 if (argcount < fp->uf_args.ga_len)
1464 error = ERROR_TOOFEW;
1465 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
1466 error = ERROR_TOOMANY;
1467 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
1468 error = ERROR_DICT;
1469 else
1470 {
1471 int did_save_redo = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001472 save_redo_T save_redo;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001473
1474 /*
1475 * Call the user function.
1476 * Save and restore search patterns, script variables and
1477 * redo buffer.
1478 */
1479 save_search_patterns();
1480#ifdef FEAT_INS_EXPAND
1481 if (!ins_compl_active())
1482#endif
1483 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001484 saveRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001485 did_save_redo = TRUE;
1486 }
1487 ++fp->uf_calls;
1488 call_user_func(fp, argcount, argvars, rettv,
1489 firstline, lastline,
1490 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001491 if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001492 /* Function was unreferenced while being used, free it
1493 * now. */
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001494 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001495 if (did_save_redo)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001496 restoreRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001497 restore_search_patterns();
1498 error = ERROR_NONE;
1499 }
1500 }
1501 }
1502 else
1503 {
1504 /*
1505 * Find the function name in the table, call its implementation.
1506 */
1507 error = call_internal_func(fname, argcount, argvars, rettv);
1508 }
1509 /*
1510 * The function call (or "FuncUndefined" autocommand sequence) might
1511 * have been aborted by an error, an interrupt, or an explicitly thrown
1512 * exception that has not been caught so far. This situation can be
1513 * tested for by calling aborting(). For an error in an internal
1514 * function or for the "E132" error in call_user_func(), however, the
1515 * throw point at which the "force_abort" flag (temporarily reset by
1516 * emsg()) is normally updated has not been reached yet. We need to
1517 * update that flag first to make aborting() reliable.
1518 */
1519 update_force_abort();
1520 }
1521 if (error == ERROR_NONE)
1522 ret = OK;
1523
1524 /*
1525 * Report an error unless the argument evaluation or function call has been
1526 * cancelled due to an aborting error, an interrupt, or an exception.
1527 */
1528 if (!aborting())
1529 {
1530 switch (error)
1531 {
1532 case ERROR_UNKNOWN:
1533 emsg_funcname(N_("E117: Unknown function: %s"), name);
1534 break;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001535 case ERROR_DELETED:
1536 emsg_funcname(N_("E933: Function was deleted: %s"), name);
1537 break;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001538 case ERROR_TOOMANY:
1539 emsg_funcname((char *)e_toomanyarg, name);
1540 break;
1541 case ERROR_TOOFEW:
1542 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
1543 name);
1544 break;
1545 case ERROR_SCRIPT:
1546 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
1547 name);
1548 break;
1549 case ERROR_DICT:
1550 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
1551 name);
1552 break;
1553 }
1554 }
1555
1556 while (argv_clear > 0)
1557 clear_tv(&argv[--argv_clear]);
1558 vim_free(tofree);
1559 vim_free(name);
1560
1561 return ret;
1562}
1563
1564/*
1565 * List the head of the function: "name(arg1, arg2)".
1566 */
1567 static void
1568list_func_head(ufunc_T *fp, int indent)
1569{
1570 int j;
1571
1572 msg_start();
1573 if (indent)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001574 msg_puts(" ");
1575 msg_puts("function ");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001576 if (fp->uf_name[0] == K_SPECIAL)
1577 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01001578 msg_puts_attr("<SNR>", HL_ATTR(HLF_8));
1579 msg_puts((char *)fp->uf_name + 3);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001580 }
1581 else
Bram Moolenaar32526b32019-01-19 17:43:09 +01001582 msg_puts((char *)fp->uf_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001583 msg_putchar('(');
1584 for (j = 0; j < fp->uf_args.ga_len; ++j)
1585 {
1586 if (j)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001587 msg_puts(", ");
1588 msg_puts((char *)FUNCARG(fp, j));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001589 }
1590 if (fp->uf_varargs)
1591 {
1592 if (j)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001593 msg_puts(", ");
1594 msg_puts("...");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001595 }
1596 msg_putchar(')');
1597 if (fp->uf_flags & FC_ABORT)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001598 msg_puts(" abort");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001599 if (fp->uf_flags & FC_RANGE)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001600 msg_puts(" range");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001601 if (fp->uf_flags & FC_DICT)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001602 msg_puts(" dict");
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02001603 if (fp->uf_flags & FC_CLOSURE)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001604 msg_puts(" closure");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001605 msg_clr_eos();
1606 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001607 last_set_msg(fp->uf_script_ctx);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001608}
1609
1610/*
1611 * Get a function name, translating "<SID>" and "<SNR>".
1612 * Also handles a Funcref in a List or Dictionary.
1613 * Returns the function name in allocated memory, or NULL for failure.
1614 * flags:
1615 * TFN_INT: internal function name OK
1616 * TFN_QUIET: be quiet
1617 * TFN_NO_AUTOLOAD: do not use script autoloading
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001618 * TFN_NO_DEREF: do not dereference a Funcref
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001619 * Advances "pp" to just after the function name (if no error).
1620 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001621 char_u *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001622trans_function_name(
1623 char_u **pp,
1624 int skip, /* only find the end, don't evaluate */
1625 int flags,
1626 funcdict_T *fdp, /* return: info about dictionary used */
1627 partial_T **partial) /* return: partial of a FuncRef */
1628{
1629 char_u *name = NULL;
1630 char_u *start;
1631 char_u *end;
1632 int lead;
1633 char_u sid_buf[20];
1634 int len;
1635 lval_T lv;
1636
1637 if (fdp != NULL)
1638 vim_memset(fdp, 0, sizeof(funcdict_T));
1639 start = *pp;
1640
1641 /* Check for hard coded <SNR>: already translated function ID (from a user
1642 * command). */
1643 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
1644 && (*pp)[2] == (int)KE_SNR)
1645 {
1646 *pp += 3;
1647 len = get_id_len(pp) + 3;
1648 return vim_strnsave(start, len);
1649 }
1650
1651 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
1652 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
1653 lead = eval_fname_script(start);
1654 if (lead > 2)
1655 start += lead;
1656
1657 /* Note that TFN_ flags use the same values as GLV_ flags. */
Bram Moolenaar6e65d592017-12-07 22:11:27 +01001658 end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001659 lead > 2 ? 0 : FNE_CHECK_START);
1660 if (end == start)
1661 {
1662 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001663 emsg(_("E129: Function name required"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001664 goto theend;
1665 }
1666 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
1667 {
1668 /*
1669 * Report an invalid expression in braces, unless the expression
1670 * evaluation has been cancelled due to an aborting error, an
1671 * interrupt, or an exception.
1672 */
1673 if (!aborting())
1674 {
1675 if (end != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001676 semsg(_(e_invarg2), start);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001677 }
1678 else
1679 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
1680 goto theend;
1681 }
1682
1683 if (lv.ll_tv != NULL)
1684 {
1685 if (fdp != NULL)
1686 {
1687 fdp->fd_dict = lv.ll_dict;
1688 fdp->fd_newkey = lv.ll_newkey;
1689 lv.ll_newkey = NULL;
1690 fdp->fd_di = lv.ll_di;
1691 }
1692 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
1693 {
1694 name = vim_strsave(lv.ll_tv->vval.v_string);
1695 *pp = end;
1696 }
1697 else if (lv.ll_tv->v_type == VAR_PARTIAL
1698 && lv.ll_tv->vval.v_partial != NULL)
1699 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001700 name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001701 *pp = end;
1702 if (partial != NULL)
1703 *partial = lv.ll_tv->vval.v_partial;
1704 }
1705 else
1706 {
1707 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
1708 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001709 emsg(_(e_funcref));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001710 else
1711 *pp = end;
1712 name = NULL;
1713 }
1714 goto theend;
1715 }
1716
1717 if (lv.ll_name == NULL)
1718 {
1719 /* Error found, but continue after the function name. */
1720 *pp = end;
1721 goto theend;
1722 }
1723
1724 /* Check if the name is a Funcref. If so, use the value. */
1725 if (lv.ll_exp_name != NULL)
1726 {
1727 len = (int)STRLEN(lv.ll_exp_name);
1728 name = deref_func_name(lv.ll_exp_name, &len, partial,
1729 flags & TFN_NO_AUTOLOAD);
1730 if (name == lv.ll_exp_name)
1731 name = NULL;
1732 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001733 else if (!(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001734 {
1735 len = (int)(end - *pp);
1736 name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD);
1737 if (name == *pp)
1738 name = NULL;
1739 }
1740 if (name != NULL)
1741 {
1742 name = vim_strsave(name);
1743 *pp = end;
1744 if (STRNCMP(name, "<SNR>", 5) == 0)
1745 {
1746 /* Change "<SNR>" to the byte sequence. */
1747 name[0] = K_SPECIAL;
1748 name[1] = KS_EXTRA;
1749 name[2] = (int)KE_SNR;
1750 mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
1751 }
1752 goto theend;
1753 }
1754
1755 if (lv.ll_exp_name != NULL)
1756 {
1757 len = (int)STRLEN(lv.ll_exp_name);
1758 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
1759 && STRNCMP(lv.ll_name, "s:", 2) == 0)
1760 {
1761 /* When there was "s:" already or the name expanded to get a
1762 * leading "s:" then remove it. */
1763 lv.ll_name += 2;
1764 len -= 2;
1765 lead = 2;
1766 }
1767 }
1768 else
1769 {
1770 /* skip over "s:" and "g:" */
1771 if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
1772 lv.ll_name += 2;
1773 len = (int)(end - lv.ll_name);
1774 }
1775
1776 /*
1777 * Copy the function name to allocated memory.
1778 * Accept <SID>name() inside a script, translate into <SNR>123_name().
1779 * Accept <SNR>123_name() outside a script.
1780 */
1781 if (skip)
1782 lead = 0; /* do nothing */
1783 else if (lead > 0)
1784 {
1785 lead = 3;
1786 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
1787 || eval_fname_sid(*pp))
1788 {
1789 /* It's "s:" or "<SID>" */
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001790 if (current_sctx.sc_sid <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001791 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001792 emsg(_(e_usingsid));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001793 goto theend;
1794 }
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001795 sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001796 lead += (int)STRLEN(sid_buf);
1797 }
1798 }
1799 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
1800 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001801 semsg(_("E128: Function name must start with a capital or \"s:\": %s"),
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001802 start);
1803 goto theend;
1804 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001805 if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001806 {
1807 char_u *cp = vim_strchr(lv.ll_name, ':');
1808
1809 if (cp != NULL && cp < end)
1810 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001811 semsg(_("E884: Function name cannot contain a colon: %s"), start);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001812 goto theend;
1813 }
1814 }
1815
1816 name = alloc((unsigned)(len + lead + 1));
1817 if (name != NULL)
1818 {
1819 if (lead > 0)
1820 {
1821 name[0] = K_SPECIAL;
1822 name[1] = KS_EXTRA;
1823 name[2] = (int)KE_SNR;
1824 if (lead > 3) /* If it's "<SID>" */
1825 STRCPY(name + 3, sid_buf);
1826 }
1827 mch_memmove(name + lead, lv.ll_name, (size_t)len);
1828 name[lead + len] = NUL;
1829 }
1830 *pp = end;
1831
1832theend:
1833 clear_lval(&lv);
1834 return name;
1835}
1836
1837/*
1838 * ":function"
1839 */
1840 void
1841ex_function(exarg_T *eap)
1842{
1843 char_u *theline;
Bram Moolenaar53564f72017-06-24 14:48:11 +02001844 char_u *line_to_free = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001845 int j;
1846 int c;
1847 int saved_did_emsg;
1848 int saved_wait_return = need_wait_return;
1849 char_u *name = NULL;
1850 char_u *p;
1851 char_u *arg;
1852 char_u *line_arg = NULL;
1853 garray_T newargs;
1854 garray_T newlines;
1855 int varargs = FALSE;
1856 int flags = 0;
1857 ufunc_T *fp;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001858 int overwrite = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001859 int indent;
1860 int nesting;
1861 char_u *skip_until = NULL;
1862 dictitem_T *v;
1863 funcdict_T fudi;
1864 static int func_nr = 0; /* number for nameless function */
1865 int paren;
1866 hashtab_T *ht;
1867 int todo;
1868 hashitem_T *hi;
1869 int sourcing_lnum_off;
1870
1871 /*
1872 * ":function" without argument: list functions.
1873 */
1874 if (ends_excmd(*eap->arg))
1875 {
1876 if (!eap->skip)
1877 {
1878 todo = (int)func_hashtab.ht_used;
1879 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1880 {
1881 if (!HASHITEM_EMPTY(hi))
1882 {
1883 --todo;
1884 fp = HI2UF(hi);
Bram Moolenaarf86db782018-10-25 13:31:37 +02001885 if (message_filtered(fp->uf_name))
1886 continue;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001887 if (!func_name_refcount(fp->uf_name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001888 list_func_head(fp, FALSE);
1889 }
1890 }
1891 }
1892 eap->nextcmd = check_nextcmd(eap->arg);
1893 return;
1894 }
1895
1896 /*
1897 * ":function /pat": list functions matching pattern.
1898 */
1899 if (*eap->arg == '/')
1900 {
1901 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
1902 if (!eap->skip)
1903 {
1904 regmatch_T regmatch;
1905
1906 c = *p;
1907 *p = NUL;
1908 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
1909 *p = c;
1910 if (regmatch.regprog != NULL)
1911 {
1912 regmatch.rm_ic = p_ic;
1913
1914 todo = (int)func_hashtab.ht_used;
1915 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
1916 {
1917 if (!HASHITEM_EMPTY(hi))
1918 {
1919 --todo;
1920 fp = HI2UF(hi);
1921 if (!isdigit(*fp->uf_name)
1922 && vim_regexec(&regmatch, fp->uf_name, 0))
1923 list_func_head(fp, FALSE);
1924 }
1925 }
1926 vim_regfree(regmatch.regprog);
1927 }
1928 }
1929 if (*p == '/')
1930 ++p;
1931 eap->nextcmd = check_nextcmd(p);
1932 return;
1933 }
1934
1935 /*
1936 * Get the function name. There are these situations:
1937 * func normal function name
1938 * "name" == func, "fudi.fd_dict" == NULL
1939 * dict.func new dictionary entry
1940 * "name" == NULL, "fudi.fd_dict" set,
1941 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
1942 * dict.func existing dict entry with a Funcref
1943 * "name" == func, "fudi.fd_dict" set,
1944 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1945 * dict.func existing dict entry that's not a Funcref
1946 * "name" == NULL, "fudi.fd_dict" set,
1947 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
1948 * s:func script-local function name
1949 * g:func global function name, same as "func"
1950 */
1951 p = eap->arg;
Bram Moolenaar3388d332017-12-07 22:23:04 +01001952 name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001953 paren = (vim_strchr(p, '(') != NULL);
1954 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
1955 {
1956 /*
1957 * Return on an invalid expression in braces, unless the expression
1958 * evaluation has been cancelled due to an aborting error, an
1959 * interrupt, or an exception.
1960 */
1961 if (!aborting())
1962 {
1963 if (!eap->skip && fudi.fd_newkey != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001964 semsg(_(e_dictkey), fudi.fd_newkey);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001965 vim_free(fudi.fd_newkey);
1966 return;
1967 }
1968 else
1969 eap->skip = TRUE;
1970 }
1971
1972 /* An error in a function call during evaluation of an expression in magic
1973 * braces should not cause the function not to be defined. */
1974 saved_did_emsg = did_emsg;
1975 did_emsg = FALSE;
1976
1977 /*
1978 * ":function func" with only function name: list function.
1979 */
1980 if (!paren)
1981 {
1982 if (!ends_excmd(*skipwhite(p)))
1983 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001984 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001985 goto ret_free;
1986 }
1987 eap->nextcmd = check_nextcmd(p);
1988 if (eap->nextcmd != NULL)
1989 *p = NUL;
1990 if (!eap->skip && !got_int)
1991 {
1992 fp = find_func(name);
1993 if (fp != NULL)
1994 {
1995 list_func_head(fp, TRUE);
1996 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
1997 {
1998 if (FUNCLINE(fp, j) == NULL)
1999 continue;
2000 msg_putchar('\n');
2001 msg_outnum((long)(j + 1));
2002 if (j < 9)
2003 msg_putchar(' ');
2004 if (j < 99)
2005 msg_putchar(' ');
2006 msg_prt_line(FUNCLINE(fp, j), FALSE);
2007 out_flush(); /* show a line at a time */
2008 ui_breakcheck();
2009 }
2010 if (!got_int)
2011 {
2012 msg_putchar('\n');
Bram Moolenaar32526b32019-01-19 17:43:09 +01002013 msg_puts(" endfunction");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002014 }
2015 }
2016 else
2017 emsg_funcname(N_("E123: Undefined function: %s"), name);
2018 }
2019 goto ret_free;
2020 }
2021
2022 /*
2023 * ":function name(arg1, arg2)" Define function.
2024 */
2025 p = skipwhite(p);
2026 if (*p != '(')
2027 {
2028 if (!eap->skip)
2029 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002030 semsg(_("E124: Missing '(': %s"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002031 goto ret_free;
2032 }
2033 /* attempt to continue by skipping some text */
2034 if (vim_strchr(p, '(') != NULL)
2035 p = vim_strchr(p, '(');
2036 }
2037 p = skipwhite(p + 1);
2038
2039 ga_init2(&newlines, (int)sizeof(char_u *), 3);
2040
2041 if (!eap->skip)
2042 {
2043 /* Check the name of the function. Unless it's a dictionary function
2044 * (that we are overwriting). */
2045 if (name != NULL)
2046 arg = name;
2047 else
2048 arg = fudi.fd_newkey;
2049 if (arg != NULL && (fudi.fd_di == NULL
2050 || (fudi.fd_di->di_tv.v_type != VAR_FUNC
2051 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL)))
2052 {
2053 if (*arg == K_SPECIAL)
2054 j = 3;
2055 else
2056 j = 0;
2057 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
2058 : eval_isnamec(arg[j])))
2059 ++j;
2060 if (arg[j] != NUL)
2061 emsg_funcname((char *)e_invarg2, arg);
2062 }
2063 /* Disallow using the g: dict. */
2064 if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002065 emsg(_("E862: Cannot use g: here"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002066 }
2067
2068 if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL)
2069 goto errret_2;
2070
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002071 /* find extra arguments "range", "dict", "abort" and "closure" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002072 for (;;)
2073 {
2074 p = skipwhite(p);
2075 if (STRNCMP(p, "range", 5) == 0)
2076 {
2077 flags |= FC_RANGE;
2078 p += 5;
2079 }
2080 else if (STRNCMP(p, "dict", 4) == 0)
2081 {
2082 flags |= FC_DICT;
2083 p += 4;
2084 }
2085 else if (STRNCMP(p, "abort", 5) == 0)
2086 {
2087 flags |= FC_ABORT;
2088 p += 5;
2089 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002090 else if (STRNCMP(p, "closure", 7) == 0)
2091 {
2092 flags |= FC_CLOSURE;
2093 p += 7;
Bram Moolenaar58016442016-07-31 18:30:22 +02002094 if (current_funccal == NULL)
2095 {
Bram Moolenaarba209902016-08-24 22:06:38 +02002096 emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
Bram Moolenaar58016442016-07-31 18:30:22 +02002097 name == NULL ? (char_u *)"" : name);
2098 goto erret;
2099 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002100 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002101 else
2102 break;
2103 }
2104
2105 /* When there is a line break use what follows for the function body.
2106 * Makes 'exe "func Test()\n...\nendfunc"' work. */
2107 if (*p == '\n')
2108 line_arg = p + 1;
2109 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002110 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002111
2112 /*
2113 * Read the body of the function, until ":endfunction" is found.
2114 */
2115 if (KeyTyped)
2116 {
2117 /* Check if the function already exists, don't let the user type the
2118 * whole function before telling him it doesn't work! For a script we
2119 * need to skip the body to be able to find what follows. */
2120 if (!eap->skip && !eap->forceit)
2121 {
2122 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002123 emsg(_(e_funcdict));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002124 else if (name != NULL && find_func(name) != NULL)
2125 emsg_funcname(e_funcexts, name);
2126 }
2127
2128 if (!eap->skip && did_emsg)
2129 goto erret;
2130
2131 msg_putchar('\n'); /* don't overwrite the function name */
2132 cmdline_row = msg_row;
2133 }
2134
2135 indent = 2;
2136 nesting = 0;
2137 for (;;)
2138 {
2139 if (KeyTyped)
2140 {
2141 msg_scroll = TRUE;
2142 saved_wait_return = FALSE;
2143 }
2144 need_wait_return = FALSE;
2145 sourcing_lnum_off = sourcing_lnum;
2146
2147 if (line_arg != NULL)
2148 {
2149 /* Use eap->arg, split up in parts by line breaks. */
2150 theline = line_arg;
2151 p = vim_strchr(theline, '\n');
2152 if (p == NULL)
2153 line_arg += STRLEN(line_arg);
2154 else
2155 {
2156 *p = NUL;
2157 line_arg = p + 1;
2158 }
2159 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002160 else
Bram Moolenaar53564f72017-06-24 14:48:11 +02002161 {
2162 vim_free(line_to_free);
2163 if (eap->getline == NULL)
2164 theline = getcmdline(':', 0L, indent);
2165 else
2166 theline = eap->getline(':', eap->cookie, indent);
2167 line_to_free = theline;
2168 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002169 if (KeyTyped)
2170 lines_left = Rows - 1;
2171 if (theline == NULL)
2172 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002173 emsg(_("E126: Missing :endfunction"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002174 goto erret;
2175 }
2176
2177 /* Detect line continuation: sourcing_lnum increased more than one. */
2178 if (sourcing_lnum > sourcing_lnum_off + 1)
2179 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
2180 else
2181 sourcing_lnum_off = 0;
2182
2183 if (skip_until != NULL)
2184 {
2185 /* between ":append" and "." and between ":python <<EOF" and "EOF"
2186 * don't check for ":endfunc". */
2187 if (STRCMP(theline, skip_until) == 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01002188 VIM_CLEAR(skip_until);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002189 }
2190 else
2191 {
2192 /* skip ':' and blanks*/
Bram Moolenaar1c465442017-03-12 20:10:05 +01002193 for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002194 ;
2195
2196 /* Check for "endfunction". */
2197 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
2198 {
Bram Moolenaar53564f72017-06-24 14:48:11 +02002199 char_u *nextcmd = NULL;
2200
Bram Moolenaar663bb232017-06-22 19:12:10 +02002201 if (*p == '|')
Bram Moolenaar53564f72017-06-24 14:48:11 +02002202 nextcmd = p + 1;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002203 else if (line_arg != NULL && *skipwhite(line_arg) != NUL)
Bram Moolenaar53564f72017-06-24 14:48:11 +02002204 nextcmd = line_arg;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002205 else if (*p != NUL && *p != '"' && p_verbose > 0)
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002206 give_warning2(
2207 (char_u *)_("W22: Text found after :endfunction: %s"),
2208 p, TRUE);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002209 if (nextcmd != NULL)
2210 {
2211 /* Another command follows. If the line came from "eap" we
2212 * can simply point into it, otherwise we need to change
2213 * "eap->cmdlinep". */
2214 eap->nextcmd = nextcmd;
2215 if (line_to_free != NULL)
2216 {
2217 vim_free(*eap->cmdlinep);
2218 *eap->cmdlinep = line_to_free;
2219 line_to_free = NULL;
2220 }
2221 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002222 break;
2223 }
2224
2225 /* Increase indent inside "if", "while", "for" and "try", decrease
2226 * at "end". */
2227 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
2228 indent -= 2;
2229 else if (STRNCMP(p, "if", 2) == 0
2230 || STRNCMP(p, "wh", 2) == 0
2231 || STRNCMP(p, "for", 3) == 0
2232 || STRNCMP(p, "try", 3) == 0)
2233 indent += 2;
2234
2235 /* Check for defining a function inside this function. */
2236 if (checkforcmd(&p, "function", 2))
2237 {
2238 if (*p == '!')
2239 p = skipwhite(p + 1);
2240 p += eval_fname_script(p);
2241 vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL));
2242 if (*skipwhite(p) == '(')
2243 {
2244 ++nesting;
2245 indent += 2;
2246 }
2247 }
2248
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002249 /* Check for ":append", ":change", ":insert". */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002250 p = skip_range(p, NULL);
2251 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002252 || (p[0] == 'c'
2253 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
2254 && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
2255 && (STRNCMP(&p[3], "nge", 3) != 0
2256 || !ASCII_ISALPHA(p[6])))))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002257 || (p[0] == 'i'
2258 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
2259 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
2260 skip_until = vim_strsave((char_u *)".");
2261
2262 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
2263 arg = skipwhite(skiptowhite(p));
2264 if (arg[0] == '<' && arg[1] =='<'
2265 && ((p[0] == 'p' && p[1] == 'y'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +01002266 && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2267 || ((p[2] == '3' || p[2] == 'x')
2268 && !ASCII_ISALPHA(p[3]))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002269 || (p[0] == 'p' && p[1] == 'e'
2270 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2271 || (p[0] == 't' && p[1] == 'c'
2272 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2273 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2274 && !ASCII_ISALPHA(p[3]))
2275 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2276 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2277 || (p[0] == 'm' && p[1] == 'z'
2278 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
2279 ))
2280 {
2281 /* ":python <<" continues until a dot, like ":append" */
2282 p = skipwhite(arg + 2);
2283 if (*p == NUL)
2284 skip_until = vim_strsave((char_u *)".");
2285 else
2286 skip_until = vim_strsave(p);
2287 }
2288 }
2289
2290 /* Add the line to the function. */
2291 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002292 goto erret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002293
2294 /* Copy the line to newly allocated memory. get_one_sourceline()
2295 * allocates 250 bytes per line, this saves 80% on average. The cost
2296 * is an extra alloc/free. */
2297 p = vim_strsave(theline);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002298 if (p == NULL)
2299 goto erret;
2300 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002301
2302 /* Add NULL lines for continuation lines, so that the line count is
2303 * equal to the index in the growarray. */
2304 while (sourcing_lnum_off-- > 0)
2305 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
2306
2307 /* Check for end of eap->arg. */
2308 if (line_arg != NULL && *line_arg == NUL)
2309 line_arg = NULL;
2310 }
2311
2312 /* Don't define the function when skipping commands or when an error was
2313 * detected. */
2314 if (eap->skip || did_emsg)
2315 goto erret;
2316
2317 /*
2318 * If there are no errors, add the function
2319 */
2320 if (fudi.fd_dict == NULL)
2321 {
2322 v = find_var(name, &ht, FALSE);
2323 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
2324 {
2325 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
2326 name);
2327 goto erret;
2328 }
2329
2330 fp = find_func(name);
2331 if (fp != NULL)
2332 {
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002333 // Function can be replaced with "function!" and when sourcing the
2334 // same script again, but only once.
2335 if (!eap->forceit
2336 && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid
2337 || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002338 {
2339 emsg_funcname(e_funcexts, name);
2340 goto erret;
2341 }
2342 if (fp->uf_calls > 0)
2343 {
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002344 emsg_funcname(
2345 N_("E127: Cannot redefine function %s: It is in use"),
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002346 name);
2347 goto erret;
2348 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002349 if (fp->uf_refcount > 1)
2350 {
2351 /* This function is referenced somewhere, don't redefine it but
2352 * create a new one. */
2353 --fp->uf_refcount;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002354 fp->uf_flags |= FC_REMOVED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002355 fp = NULL;
2356 overwrite = TRUE;
2357 }
2358 else
2359 {
2360 /* redefine existing function */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002361 VIM_CLEAR(name);
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02002362 func_clear_items(fp);
2363#ifdef FEAT_PROFILE
2364 fp->uf_profiling = FALSE;
2365 fp->uf_prof_initialized = FALSE;
2366#endif
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002367 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002368 }
2369 }
2370 else
2371 {
2372 char numbuf[20];
2373
2374 fp = NULL;
2375 if (fudi.fd_newkey == NULL && !eap->forceit)
2376 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002377 emsg(_(e_funcdict));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002378 goto erret;
2379 }
2380 if (fudi.fd_di == NULL)
2381 {
2382 /* Can't add a function to a locked dictionary */
2383 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE))
2384 goto erret;
2385 }
2386 /* Can't change an existing function if it is locked */
2387 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE))
2388 goto erret;
2389
2390 /* Give the function a sequential number. Can only be used with a
2391 * Funcref! */
2392 vim_free(name);
2393 sprintf(numbuf, "%d", ++func_nr);
2394 name = vim_strsave((char_u *)numbuf);
2395 if (name == NULL)
2396 goto erret;
2397 }
2398
2399 if (fp == NULL)
2400 {
2401 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
2402 {
2403 int slen, plen;
2404 char_u *scriptname;
2405
2406 /* Check that the autoload name matches the script name. */
2407 j = FAIL;
2408 if (sourcing_name != NULL)
2409 {
2410 scriptname = autoload_name(name);
2411 if (scriptname != NULL)
2412 {
2413 p = vim_strchr(scriptname, '/');
2414 plen = (int)STRLEN(p);
2415 slen = (int)STRLEN(sourcing_name);
2416 if (slen > plen && fnamecmp(p,
2417 sourcing_name + slen - plen) == 0)
2418 j = OK;
2419 vim_free(scriptname);
2420 }
2421 }
2422 if (j == FAIL)
2423 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002424 semsg(_("E746: Function name does not match script file name: %s"), name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002425 goto erret;
2426 }
2427 }
2428
Bram Moolenaar58016442016-07-31 18:30:22 +02002429 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002430 if (fp == NULL)
2431 goto erret;
2432
2433 if (fudi.fd_dict != NULL)
2434 {
2435 if (fudi.fd_di == NULL)
2436 {
2437 /* add new dict entry */
2438 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
2439 if (fudi.fd_di == NULL)
2440 {
2441 vim_free(fp);
2442 goto erret;
2443 }
2444 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
2445 {
2446 vim_free(fudi.fd_di);
2447 vim_free(fp);
2448 goto erret;
2449 }
2450 }
2451 else
2452 /* overwrite existing dict entry */
2453 clear_tv(&fudi.fd_di->di_tv);
2454 fudi.fd_di->di_tv.v_type = VAR_FUNC;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002455 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002456
2457 /* behave like "dict" was used */
2458 flags |= FC_DICT;
2459 }
2460
2461 /* insert the new function in the function list */
2462 STRCPY(fp->uf_name, name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002463 if (overwrite)
2464 {
2465 hi = hash_find(&func_hashtab, name);
2466 hi->hi_key = UF2HIKEY(fp);
2467 }
2468 else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002469 {
2470 vim_free(fp);
2471 goto erret;
2472 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002473 fp->uf_refcount = 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002474 }
2475 fp->uf_args = newargs;
2476 fp->uf_lines = newlines;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002477 if ((flags & FC_CLOSURE) != 0)
2478 {
Bram Moolenaar58016442016-07-31 18:30:22 +02002479 if (register_closure(fp) == FAIL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002480 goto erret;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002481 }
2482 else
2483 fp->uf_scoped = NULL;
2484
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002485#ifdef FEAT_PROFILE
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002486 if (prof_def_func())
2487 func_do_profile(fp);
2488#endif
2489 fp->uf_varargs = varargs;
Bram Moolenaar93343722018-07-10 19:39:18 +02002490 if (sandbox)
2491 flags |= FC_SANDBOX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002492 fp->uf_flags = flags;
2493 fp->uf_calls = 0;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02002494 fp->uf_script_ctx = current_sctx;
2495 fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len - 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002496 goto ret_free;
2497
2498erret:
2499 ga_clear_strings(&newargs);
2500errret_2:
2501 ga_clear_strings(&newlines);
2502ret_free:
2503 vim_free(skip_until);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002504 vim_free(line_to_free);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002505 vim_free(fudi.fd_newkey);
2506 vim_free(name);
2507 did_emsg |= saved_did_emsg;
2508 need_wait_return |= saved_wait_return;
2509}
2510
2511/*
2512 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
2513 * Return 2 if "p" starts with "s:".
2514 * Return 0 otherwise.
2515 */
2516 int
2517eval_fname_script(char_u *p)
2518{
2519 /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with
2520 * the standard library function. */
2521 if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0
2522 || MB_STRNICMP(p + 1, "SNR>", 4) == 0))
2523 return 5;
2524 if (p[0] == 's' && p[1] == ':')
2525 return 2;
2526 return 0;
2527}
2528
2529 int
2530translated_function_exists(char_u *name)
2531{
2532 if (builtin_function(name, -1))
2533 return find_internal_func(name) >= 0;
2534 return find_func(name) != NULL;
2535}
2536
2537/*
2538 * Return TRUE if a function "name" exists.
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002539 * If "no_defef" is TRUE, do not dereference a Funcref.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002540 */
2541 int
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002542function_exists(char_u *name, int no_deref)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002543{
2544 char_u *nm = name;
2545 char_u *p;
2546 int n = FALSE;
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002547 int flag;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002548
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002549 flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
2550 if (no_deref)
2551 flag |= TFN_NO_DEREF;
2552 p = trans_function_name(&nm, FALSE, flag, NULL, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002553 nm = skipwhite(nm);
2554
2555 /* Only accept "funcname", "funcname ", "funcname (..." and
2556 * "funcname(...", not "funcname!...". */
2557 if (p != NULL && (*nm == NUL || *nm == '('))
2558 n = translated_function_exists(p);
2559 vim_free(p);
2560 return n;
2561}
2562
Bram Moolenaar113e1072019-01-20 15:30:40 +01002563#if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002564 char_u *
2565get_expanded_name(char_u *name, int check)
2566{
2567 char_u *nm = name;
2568 char_u *p;
2569
2570 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL);
2571
2572 if (p != NULL && *nm == NUL)
2573 if (!check || translated_function_exists(p))
2574 return p;
2575
2576 vim_free(p);
2577 return NULL;
2578}
Bram Moolenaar113e1072019-01-20 15:30:40 +01002579#endif
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002580
2581#if defined(FEAT_PROFILE) || defined(PROTO)
2582/*
2583 * Start profiling function "fp".
2584 */
2585 static void
2586func_do_profile(ufunc_T *fp)
2587{
2588 int len = fp->uf_lines.ga_len;
2589
Bram Moolenaarad648092018-06-30 18:28:03 +02002590 if (!fp->uf_prof_initialized)
2591 {
2592 if (len == 0)
2593 len = 1; /* avoid getting error for allocating zero bytes */
2594 fp->uf_tm_count = 0;
2595 profile_zero(&fp->uf_tm_self);
2596 profile_zero(&fp->uf_tm_total);
2597 if (fp->uf_tml_count == NULL)
2598 fp->uf_tml_count = (int *)alloc_clear(
2599 (unsigned)(sizeof(int) * len));
2600 if (fp->uf_tml_total == NULL)
2601 fp->uf_tml_total = (proftime_T *)alloc_clear(
2602 (unsigned)(sizeof(proftime_T) * len));
2603 if (fp->uf_tml_self == NULL)
2604 fp->uf_tml_self = (proftime_T *)alloc_clear(
2605 (unsigned)(sizeof(proftime_T) * len));
2606 fp->uf_tml_idx = -1;
2607 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
2608 || fp->uf_tml_self == NULL)
2609 return; /* out of memory */
2610 fp->uf_prof_initialized = TRUE;
2611 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002612
2613 fp->uf_profiling = TRUE;
2614}
2615
2616/*
2617 * Dump the profiling results for all functions in file "fd".
2618 */
2619 void
2620func_dump_profile(FILE *fd)
2621{
2622 hashitem_T *hi;
2623 int todo;
2624 ufunc_T *fp;
2625 int i;
2626 ufunc_T **sorttab;
2627 int st_len = 0;
Bram Moolenaar4c7b08f2018-09-10 22:03:40 +02002628 char_u *p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002629
2630 todo = (int)func_hashtab.ht_used;
2631 if (todo == 0)
2632 return; /* nothing to dump */
2633
2634 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo));
2635
2636 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
2637 {
2638 if (!HASHITEM_EMPTY(hi))
2639 {
2640 --todo;
2641 fp = HI2UF(hi);
Bram Moolenaarad648092018-06-30 18:28:03 +02002642 if (fp->uf_prof_initialized)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002643 {
2644 if (sorttab != NULL)
2645 sorttab[st_len++] = fp;
2646
2647 if (fp->uf_name[0] == K_SPECIAL)
2648 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
2649 else
2650 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
Bram Moolenaar4c7b08f2018-09-10 22:03:40 +02002651 p = home_replace_save(NULL,
2652 get_scriptname(fp->uf_script_ctx.sc_sid));
2653 if (p != NULL)
2654 {
2655 fprintf(fd, " Defined: %s line %ld\n",
2656 p, (long)fp->uf_script_ctx.sc_lnum);
2657 vim_free(p);
2658 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002659 if (fp->uf_tm_count == 1)
2660 fprintf(fd, "Called 1 time\n");
2661 else
2662 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
2663 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
2664 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
2665 fprintf(fd, "\n");
2666 fprintf(fd, "count total (s) self (s)\n");
2667
2668 for (i = 0; i < fp->uf_lines.ga_len; ++i)
2669 {
2670 if (FUNCLINE(fp, i) == NULL)
2671 continue;
2672 prof_func_line(fd, fp->uf_tml_count[i],
2673 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
2674 fprintf(fd, "%s\n", FUNCLINE(fp, i));
2675 }
2676 fprintf(fd, "\n");
2677 }
2678 }
2679 }
2680
2681 if (sorttab != NULL && st_len > 0)
2682 {
2683 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2684 prof_total_cmp);
2685 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
2686 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2687 prof_self_cmp);
2688 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
2689 }
2690
2691 vim_free(sorttab);
2692}
2693
2694 static void
2695prof_sort_list(
2696 FILE *fd,
2697 ufunc_T **sorttab,
2698 int st_len,
2699 char *title,
2700 int prefer_self) /* when equal print only self time */
2701{
2702 int i;
2703 ufunc_T *fp;
2704
2705 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
2706 fprintf(fd, "count total (s) self (s) function\n");
2707 for (i = 0; i < 20 && i < st_len; ++i)
2708 {
2709 fp = sorttab[i];
2710 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
2711 prefer_self);
2712 if (fp->uf_name[0] == K_SPECIAL)
2713 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
2714 else
2715 fprintf(fd, " %s()\n", fp->uf_name);
2716 }
2717 fprintf(fd, "\n");
2718}
2719
2720/*
2721 * Print the count and times for one function or function line.
2722 */
2723 static void
2724prof_func_line(
2725 FILE *fd,
2726 int count,
2727 proftime_T *total,
2728 proftime_T *self,
2729 int prefer_self) /* when equal print only self time */
2730{
2731 if (count > 0)
2732 {
2733 fprintf(fd, "%5d ", count);
2734 if (prefer_self && profile_equal(total, self))
2735 fprintf(fd, " ");
2736 else
2737 fprintf(fd, "%s ", profile_msg(total));
2738 if (!prefer_self && profile_equal(total, self))
2739 fprintf(fd, " ");
2740 else
2741 fprintf(fd, "%s ", profile_msg(self));
2742 }
2743 else
2744 fprintf(fd, " ");
2745}
2746
2747/*
2748 * Compare function for total time sorting.
2749 */
2750 static int
2751#ifdef __BORLANDC__
2752_RTLENTRYF
2753#endif
2754prof_total_cmp(const void *s1, const void *s2)
2755{
2756 ufunc_T *p1, *p2;
2757
2758 p1 = *(ufunc_T **)s1;
2759 p2 = *(ufunc_T **)s2;
2760 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
2761}
2762
2763/*
2764 * Compare function for self time sorting.
2765 */
2766 static int
2767#ifdef __BORLANDC__
2768_RTLENTRYF
2769#endif
2770prof_self_cmp(const void *s1, const void *s2)
2771{
2772 ufunc_T *p1, *p2;
2773
2774 p1 = *(ufunc_T **)s1;
2775 p2 = *(ufunc_T **)s2;
2776 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
2777}
2778
2779/*
2780 * Prepare profiling for entering a child or something else that is not
2781 * counted for the script/function itself.
2782 * Should always be called in pair with prof_child_exit().
2783 */
2784 void
2785prof_child_enter(
2786 proftime_T *tm) /* place to store waittime */
2787{
2788 funccall_T *fc = current_funccal;
2789
2790 if (fc != NULL && fc->func->uf_profiling)
2791 profile_start(&fc->prof_child);
2792 script_prof_save(tm);
2793}
2794
2795/*
2796 * Take care of time spent in a child.
2797 * Should always be called after prof_child_enter().
2798 */
2799 void
2800prof_child_exit(
2801 proftime_T *tm) /* where waittime was stored */
2802{
2803 funccall_T *fc = current_funccal;
2804
2805 if (fc != NULL && fc->func->uf_profiling)
2806 {
2807 profile_end(&fc->prof_child);
2808 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
2809 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
2810 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
2811 }
2812 script_prof_restore(tm);
2813}
2814
2815#endif /* FEAT_PROFILE */
2816
2817#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2818
2819/*
2820 * Function given to ExpandGeneric() to obtain the list of user defined
2821 * function names.
2822 */
2823 char_u *
2824get_user_func_name(expand_T *xp, int idx)
2825{
2826 static long_u done;
2827 static hashitem_T *hi;
2828 ufunc_T *fp;
2829
2830 if (idx == 0)
2831 {
2832 done = 0;
2833 hi = func_hashtab.ht_array;
2834 }
2835 if (done < func_hashtab.ht_used)
2836 {
2837 if (done++ > 0)
2838 ++hi;
2839 while (HASHITEM_EMPTY(hi))
2840 ++hi;
2841 fp = HI2UF(hi);
2842
Bram Moolenaarb49edc12016-07-23 15:47:34 +02002843 if ((fp->uf_flags & FC_DICT)
2844 || STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
2845 return (char_u *)""; /* don't show dict and lambda functions */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002846
2847 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
2848 return fp->uf_name; /* prevents overflow */
2849
2850 cat_func_name(IObuff, fp);
2851 if (xp->xp_context != EXPAND_USER_FUNC)
2852 {
2853 STRCAT(IObuff, "(");
2854 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
2855 STRCAT(IObuff, ")");
2856 }
2857 return IObuff;
2858 }
2859 return NULL;
2860}
2861
2862#endif /* FEAT_CMDL_COMPL */
2863
2864/*
2865 * ":delfunction {name}"
2866 */
2867 void
2868ex_delfunction(exarg_T *eap)
2869{
2870 ufunc_T *fp = NULL;
2871 char_u *p;
2872 char_u *name;
2873 funcdict_T fudi;
2874
2875 p = eap->arg;
2876 name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
2877 vim_free(fudi.fd_newkey);
2878 if (name == NULL)
2879 {
2880 if (fudi.fd_dict != NULL && !eap->skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002881 emsg(_(e_funcref));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002882 return;
2883 }
2884 if (!ends_excmd(*skipwhite(p)))
2885 {
2886 vim_free(name);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002887 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002888 return;
2889 }
2890 eap->nextcmd = check_nextcmd(p);
2891 if (eap->nextcmd != NULL)
2892 *p = NUL;
2893
2894 if (!eap->skip)
2895 fp = find_func(name);
2896 vim_free(name);
2897
2898 if (!eap->skip)
2899 {
2900 if (fp == NULL)
2901 {
Bram Moolenaard6abcd12017-06-22 19:15:24 +02002902 if (!eap->forceit)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002903 semsg(_(e_nofunc), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002904 return;
2905 }
2906 if (fp->uf_calls > 0)
2907 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002908 semsg(_("E131: Cannot delete function %s: It is in use"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002909 return;
2910 }
2911
2912 if (fudi.fd_dict != NULL)
2913 {
2914 /* Delete the dict item that refers to the function, it will
2915 * invoke func_unref() and possibly delete the function. */
2916 dictitem_remove(fudi.fd_dict, fudi.fd_di);
2917 }
2918 else
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002919 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002920 /* A normal function (not a numbered function or lambda) has a
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002921 * refcount of 1 for the entry in the hashtable. When deleting
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002922 * it and the refcount is more than one, it should be kept.
Bram Moolenaarba209902016-08-24 22:06:38 +02002923 * A numbered function and lambda should be kept if the refcount is
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002924 * one or more. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002925 if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002926 {
2927 /* Function is still referenced somewhere. Don't free it but
2928 * do remove it from the hashtable. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002929 if (func_remove(fp))
2930 fp->uf_refcount--;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002931 fp->uf_flags |= FC_DELETED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002932 }
2933 else
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002934 func_clear_free(fp, FALSE);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002935 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002936 }
2937}
2938
2939/*
2940 * Unreference a Function: decrement the reference count and free it when it
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002941 * becomes zero.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002942 */
2943 void
2944func_unref(char_u *name)
2945{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002946 ufunc_T *fp = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002947
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002948 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002949 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002950 fp = find_func(name);
2951 if (fp == NULL && isdigit(*name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002952 {
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002953#ifdef EXITFREE
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002954 if (!entered_free_all_mem)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002955#endif
Bram Moolenaar95f09602016-11-10 20:01:45 +01002956 internal_error("func_unref()");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002957 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002958 if (fp != NULL && --fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002959 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002960 /* Only delete it when it's not being used. Otherwise it's done
2961 * when "uf_calls" becomes zero. */
2962 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002963 func_clear_free(fp, FALSE);
Bram Moolenaar97baee82016-07-26 20:46:08 +02002964 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002965}
2966
2967/*
2968 * Unreference a Function: decrement the reference count and free it when it
2969 * becomes zero.
2970 */
2971 void
2972func_ptr_unref(ufunc_T *fp)
2973{
Bram Moolenaar97baee82016-07-26 20:46:08 +02002974 if (fp != NULL && --fp->uf_refcount <= 0)
2975 {
2976 /* Only delete it when it's not being used. Otherwise it's done
2977 * when "uf_calls" becomes zero. */
2978 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01002979 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002980 }
2981}
2982
2983/*
2984 * Count a reference to a Function.
2985 */
2986 void
2987func_ref(char_u *name)
2988{
2989 ufunc_T *fp;
2990
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002991 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002992 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002993 fp = find_func(name);
2994 if (fp != NULL)
2995 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002996 else if (isdigit(*name))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002997 /* Only give an error for a numbered function.
2998 * Fail silently, when named or lambda function isn't found. */
Bram Moolenaar95f09602016-11-10 20:01:45 +01002999 internal_error("func_ref()");
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003000}
3001
3002/*
3003 * Count a reference to a Function.
3004 */
3005 void
3006func_ptr_ref(ufunc_T *fp)
3007{
3008 if (fp != NULL)
3009 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003010}
3011
3012/*
3013 * Return TRUE if items in "fc" do not have "copyID". That means they are not
3014 * referenced from anywhere that is in use.
3015 */
3016 static int
3017can_free_funccal(funccall_T *fc, int copyID)
3018{
3019 return (fc->l_varlist.lv_copyID != copyID
3020 && fc->l_vars.dv_copyID != copyID
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003021 && fc->l_avars.dv_copyID != copyID
3022 && fc->fc_copyID != copyID);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003023}
3024
3025/*
3026 * ":return [expr]"
3027 */
3028 void
3029ex_return(exarg_T *eap)
3030{
3031 char_u *arg = eap->arg;
3032 typval_T rettv;
3033 int returning = FALSE;
3034
3035 if (current_funccal == NULL)
3036 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003037 emsg(_("E133: :return not inside a function"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003038 return;
3039 }
3040
3041 if (eap->skip)
3042 ++emsg_skip;
3043
3044 eap->nextcmd = NULL;
3045 if ((*arg != NUL && *arg != '|' && *arg != '\n')
3046 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
3047 {
3048 if (!eap->skip)
3049 returning = do_return(eap, FALSE, TRUE, &rettv);
3050 else
3051 clear_tv(&rettv);
3052 }
3053 /* It's safer to return also on error. */
3054 else if (!eap->skip)
3055 {
Bram Moolenaarfabaf752017-12-23 17:26:11 +01003056 /* In return statement, cause_abort should be force_abort. */
3057 update_force_abort();
3058
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003059 /*
3060 * Return unless the expression evaluation has been cancelled due to an
3061 * aborting error, an interrupt, or an exception.
3062 */
3063 if (!aborting())
3064 returning = do_return(eap, FALSE, TRUE, NULL);
3065 }
3066
3067 /* When skipping or the return gets pending, advance to the next command
3068 * in this line (!returning). Otherwise, ignore the rest of the line.
3069 * Following lines will be ignored by get_func_line(). */
3070 if (returning)
3071 eap->nextcmd = NULL;
3072 else if (eap->nextcmd == NULL) /* no argument */
3073 eap->nextcmd = check_nextcmd(arg);
3074
3075 if (eap->skip)
3076 --emsg_skip;
3077}
3078
3079/*
3080 * ":1,25call func(arg1, arg2)" function call.
3081 */
3082 void
3083ex_call(exarg_T *eap)
3084{
3085 char_u *arg = eap->arg;
3086 char_u *startarg;
3087 char_u *name;
3088 char_u *tofree;
3089 int len;
3090 typval_T rettv;
3091 linenr_T lnum;
3092 int doesrange;
3093 int failed = FALSE;
3094 funcdict_T fudi;
3095 partial_T *partial = NULL;
3096
3097 if (eap->skip)
3098 {
3099 /* trans_function_name() doesn't work well when skipping, use eval0()
3100 * instead to skip to any following command, e.g. for:
3101 * :if 0 | call dict.foo().bar() | endif */
3102 ++emsg_skip;
3103 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3104 clear_tv(&rettv);
3105 --emsg_skip;
3106 return;
3107 }
3108
3109 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial);
3110 if (fudi.fd_newkey != NULL)
3111 {
3112 /* Still need to give an error message for missing key. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003113 semsg(_(e_dictkey), fudi.fd_newkey);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003114 vim_free(fudi.fd_newkey);
3115 }
3116 if (tofree == NULL)
3117 return;
3118
3119 /* Increase refcount on dictionary, it could get deleted when evaluating
3120 * the arguments. */
3121 if (fudi.fd_dict != NULL)
3122 ++fudi.fd_dict->dv_refcount;
3123
3124 /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3125 * contents. For VAR_PARTIAL get its partial, unless we already have one
3126 * from trans_function_name(). */
3127 len = (int)STRLEN(tofree);
3128 name = deref_func_name(tofree, &len,
3129 partial != NULL ? NULL : &partial, FALSE);
3130
3131 /* Skip white space to allow ":call func ()". Not good, but required for
3132 * backward compatibility. */
3133 startarg = skipwhite(arg);
3134 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3135
3136 if (*startarg != '(')
3137 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003138 semsg(_("E107: Missing parentheses: %s"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003139 goto end;
3140 }
3141
3142 /*
3143 * When skipping, evaluate the function once, to find the end of the
3144 * arguments.
3145 * When the function takes a range, this is discovered after the first
3146 * call, and the loop is broken.
3147 */
3148 if (eap->skip)
3149 {
3150 ++emsg_skip;
3151 lnum = eap->line2; /* do it once, also with an invalid range */
3152 }
3153 else
3154 lnum = eap->line1;
3155 for ( ; lnum <= eap->line2; ++lnum)
3156 {
3157 if (!eap->skip && eap->addr_count > 0)
3158 {
Bram Moolenaar9e353b52018-11-04 23:39:38 +01003159 if (lnum > curbuf->b_ml.ml_line_count)
3160 {
3161 // If the function deleted lines or switched to another buffer
3162 // the line number may become invalid.
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003163 emsg(_(e_invrange));
Bram Moolenaar9e353b52018-11-04 23:39:38 +01003164 break;
3165 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003166 curwin->w_cursor.lnum = lnum;
3167 curwin->w_cursor.col = 0;
3168#ifdef FEAT_VIRTUALEDIT
3169 curwin->w_cursor.coladd = 0;
3170#endif
3171 }
3172 arg = startarg;
3173 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3174 eap->line1, eap->line2, &doesrange,
3175 !eap->skip, partial, fudi.fd_dict) == FAIL)
3176 {
3177 failed = TRUE;
3178 break;
3179 }
Bram Moolenaarc6f9f732018-02-11 19:06:26 +01003180 if (has_watchexpr())
3181 dbg_check_breakpoint(eap);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003182
3183 /* Handle a function returning a Funcref, Dictionary or List. */
3184 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3185 {
3186 failed = TRUE;
3187 break;
3188 }
3189
3190 clear_tv(&rettv);
3191 if (doesrange || eap->skip)
3192 break;
3193
3194 /* Stop when immediately aborting on error, or when an interrupt
3195 * occurred or an exception was thrown but not caught.
3196 * get_func_tv() returned OK, so that the check for trailing
3197 * characters below is executed. */
3198 if (aborting())
3199 break;
3200 }
3201 if (eap->skip)
3202 --emsg_skip;
3203
3204 if (!failed)
3205 {
3206 /* Check for trailing illegal characters and a following command. */
3207 if (!ends_excmd(*arg))
3208 {
3209 emsg_severe = TRUE;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003210 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003211 }
3212 else
3213 eap->nextcmd = check_nextcmd(arg);
3214 }
3215
3216end:
3217 dict_unref(fudi.fd_dict);
3218 vim_free(tofree);
3219}
3220
3221/*
3222 * Return from a function. Possibly makes the return pending. Also called
3223 * for a pending return at the ":endtry" or after returning from an extra
3224 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
3225 * when called due to a ":return" command. "rettv" may point to a typval_T
3226 * with the return rettv. Returns TRUE when the return can be carried out,
3227 * FALSE when the return gets pending.
3228 */
3229 int
3230do_return(
3231 exarg_T *eap,
3232 int reanimate,
3233 int is_cmd,
3234 void *rettv)
3235{
3236 int idx;
3237 struct condstack *cstack = eap->cstack;
3238
3239 if (reanimate)
3240 /* Undo the return. */
3241 current_funccal->returned = FALSE;
3242
3243 /*
3244 * Cleanup (and inactivate) conditionals, but stop when a try conditional
3245 * not in its finally clause (which then is to be executed next) is found.
3246 * In this case, make the ":return" pending for execution at the ":endtry".
3247 * Otherwise, return normally.
3248 */
3249 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3250 if (idx >= 0)
3251 {
3252 cstack->cs_pending[idx] = CSTP_RETURN;
3253
3254 if (!is_cmd && !reanimate)
3255 /* A pending return again gets pending. "rettv" points to an
3256 * allocated variable with the rettv of the original ":return"'s
3257 * argument if present or is NULL else. */
3258 cstack->cs_rettv[idx] = rettv;
3259 else
3260 {
3261 /* When undoing a return in order to make it pending, get the stored
3262 * return rettv. */
3263 if (reanimate)
3264 rettv = current_funccal->rettv;
3265
3266 if (rettv != NULL)
3267 {
3268 /* Store the value of the pending return. */
3269 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
3270 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3271 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003272 emsg(_(e_outofmem));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003273 }
3274 else
3275 cstack->cs_rettv[idx] = NULL;
3276
3277 if (reanimate)
3278 {
3279 /* The pending return value could be overwritten by a ":return"
3280 * without argument in a finally clause; reset the default
3281 * return value. */
3282 current_funccal->rettv->v_type = VAR_NUMBER;
3283 current_funccal->rettv->vval.v_number = 0;
3284 }
3285 }
3286 report_make_pending(CSTP_RETURN, rettv);
3287 }
3288 else
3289 {
3290 current_funccal->returned = TRUE;
3291
3292 /* If the return is carried out now, store the return value. For
3293 * a return immediately after reanimation, the value is already
3294 * there. */
3295 if (!reanimate && rettv != NULL)
3296 {
3297 clear_tv(current_funccal->rettv);
3298 *current_funccal->rettv = *(typval_T *)rettv;
3299 if (!is_cmd)
3300 vim_free(rettv);
3301 }
3302 }
3303
3304 return idx < 0;
3305}
3306
3307/*
3308 * Free the variable with a pending return value.
3309 */
3310 void
3311discard_pending_return(void *rettv)
3312{
3313 free_tv((typval_T *)rettv);
3314}
3315
3316/*
3317 * Generate a return command for producing the value of "rettv". The result
3318 * is an allocated string. Used by report_pending() for verbose messages.
3319 */
3320 char_u *
3321get_return_cmd(void *rettv)
3322{
3323 char_u *s = NULL;
3324 char_u *tofree = NULL;
3325 char_u numbuf[NUMBUFLEN];
3326
3327 if (rettv != NULL)
3328 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
3329 if (s == NULL)
3330 s = (char_u *)"";
3331
3332 STRCPY(IObuff, ":return ");
3333 STRNCPY(IObuff + 8, s, IOSIZE - 8);
3334 if (STRLEN(s) + 8 >= IOSIZE)
3335 STRCPY(IObuff + IOSIZE - 4, "...");
3336 vim_free(tofree);
3337 return vim_strsave(IObuff);
3338}
3339
3340/*
3341 * Get next function line.
3342 * Called by do_cmdline() to get the next line.
3343 * Returns allocated string, or NULL for end of function.
3344 */
3345 char_u *
3346get_func_line(
3347 int c UNUSED,
3348 void *cookie,
3349 int indent UNUSED)
3350{
3351 funccall_T *fcp = (funccall_T *)cookie;
3352 ufunc_T *fp = fcp->func;
3353 char_u *retval;
3354 garray_T *gap; /* growarray with function lines */
3355
3356 /* If breakpoints have been added/deleted need to check for it. */
3357 if (fcp->dbg_tick != debug_tick)
3358 {
3359 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3360 sourcing_lnum);
3361 fcp->dbg_tick = debug_tick;
3362 }
3363#ifdef FEAT_PROFILE
3364 if (do_profiling == PROF_YES)
3365 func_line_end(cookie);
3366#endif
3367
3368 gap = &fp->uf_lines;
3369 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3370 || fcp->returned)
3371 retval = NULL;
3372 else
3373 {
3374 /* Skip NULL lines (continuation lines). */
3375 while (fcp->linenr < gap->ga_len
3376 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
3377 ++fcp->linenr;
3378 if (fcp->linenr >= gap->ga_len)
3379 retval = NULL;
3380 else
3381 {
3382 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
3383 sourcing_lnum = fcp->linenr;
3384#ifdef FEAT_PROFILE
3385 if (do_profiling == PROF_YES)
3386 func_line_start(cookie);
3387#endif
3388 }
3389 }
3390
3391 /* Did we encounter a breakpoint? */
3392 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
3393 {
3394 dbg_breakpoint(fp->uf_name, sourcing_lnum);
3395 /* Find next breakpoint. */
3396 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3397 sourcing_lnum);
3398 fcp->dbg_tick = debug_tick;
3399 }
3400
3401 return retval;
3402}
3403
3404#if defined(FEAT_PROFILE) || defined(PROTO)
3405/*
3406 * Called when starting to read a function line.
3407 * "sourcing_lnum" must be correct!
3408 * When skipping lines it may not actually be executed, but we won't find out
3409 * until later and we need to store the time now.
3410 */
3411 void
3412func_line_start(void *cookie)
3413{
3414 funccall_T *fcp = (funccall_T *)cookie;
3415 ufunc_T *fp = fcp->func;
3416
3417 if (fp->uf_profiling && sourcing_lnum >= 1
3418 && sourcing_lnum <= fp->uf_lines.ga_len)
3419 {
3420 fp->uf_tml_idx = sourcing_lnum - 1;
3421 /* Skip continuation lines. */
3422 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
3423 --fp->uf_tml_idx;
3424 fp->uf_tml_execed = FALSE;
3425 profile_start(&fp->uf_tml_start);
3426 profile_zero(&fp->uf_tml_children);
3427 profile_get_wait(&fp->uf_tml_wait);
3428 }
3429}
3430
3431/*
3432 * Called when actually executing a function line.
3433 */
3434 void
3435func_line_exec(void *cookie)
3436{
3437 funccall_T *fcp = (funccall_T *)cookie;
3438 ufunc_T *fp = fcp->func;
3439
3440 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3441 fp->uf_tml_execed = TRUE;
3442}
3443
3444/*
3445 * Called when done with a function line.
3446 */
3447 void
3448func_line_end(void *cookie)
3449{
3450 funccall_T *fcp = (funccall_T *)cookie;
3451 ufunc_T *fp = fcp->func;
3452
3453 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3454 {
3455 if (fp->uf_tml_execed)
3456 {
3457 ++fp->uf_tml_count[fp->uf_tml_idx];
3458 profile_end(&fp->uf_tml_start);
3459 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
3460 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
3461 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
3462 &fp->uf_tml_children);
3463 }
3464 fp->uf_tml_idx = -1;
3465 }
3466}
3467#endif
3468
3469/*
3470 * Return TRUE if the currently active function should be ended, because a
3471 * return was encountered or an error occurred. Used inside a ":while".
3472 */
3473 int
3474func_has_ended(void *cookie)
3475{
3476 funccall_T *fcp = (funccall_T *)cookie;
3477
3478 /* Ignore the "abort" flag if the abortion behavior has been changed due to
3479 * an error inside a try conditional. */
3480 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3481 || fcp->returned);
3482}
3483
3484/*
3485 * return TRUE if cookie indicates a function which "abort"s on errors.
3486 */
3487 int
3488func_has_abort(
3489 void *cookie)
3490{
3491 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
3492}
3493
3494
3495/*
3496 * Turn "dict.Func" into a partial for "Func" bound to "dict".
3497 * Don't do this when "Func" is already a partial that was bound
3498 * explicitly (pt_auto is FALSE).
3499 * Changes "rettv" in-place.
3500 * Returns the updated "selfdict_in".
3501 */
3502 dict_T *
3503make_partial(dict_T *selfdict_in, typval_T *rettv)
3504{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003505 char_u *fname;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003506 char_u *tofree = NULL;
3507 ufunc_T *fp;
3508 char_u fname_buf[FLEN_FIXED + 1];
3509 int error;
3510 dict_T *selfdict = selfdict_in;
3511
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003512 if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL)
3513 fp = rettv->vval.v_partial->pt_func;
3514 else
3515 {
3516 fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string
3517 : rettv->vval.v_partial->pt_name;
3518 /* Translate "s:func" to the stored function name. */
3519 fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3520 fp = find_func(fname);
3521 vim_free(tofree);
3522 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003523
3524 if (fp != NULL && (fp->uf_flags & FC_DICT))
3525 {
3526 partial_T *pt = (partial_T *)alloc_clear(sizeof(partial_T));
3527
3528 if (pt != NULL)
3529 {
3530 pt->pt_refcount = 1;
3531 pt->pt_dict = selfdict;
3532 pt->pt_auto = TRUE;
3533 selfdict = NULL;
3534 if (rettv->v_type == VAR_FUNC)
3535 {
3536 /* Just a function: Take over the function name and use
3537 * selfdict. */
3538 pt->pt_name = rettv->vval.v_string;
3539 }
3540 else
3541 {
3542 partial_T *ret_pt = rettv->vval.v_partial;
3543 int i;
3544
3545 /* Partial: copy the function name, use selfdict and copy
3546 * args. Can't take over name or args, the partial might
3547 * be referenced elsewhere. */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003548 if (ret_pt->pt_name != NULL)
3549 {
3550 pt->pt_name = vim_strsave(ret_pt->pt_name);
3551 func_ref(pt->pt_name);
3552 }
3553 else
3554 {
3555 pt->pt_func = ret_pt->pt_func;
3556 func_ptr_ref(pt->pt_func);
3557 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003558 if (ret_pt->pt_argc > 0)
3559 {
3560 pt->pt_argv = (typval_T *)alloc(
3561 sizeof(typval_T) * ret_pt->pt_argc);
3562 if (pt->pt_argv == NULL)
3563 /* out of memory: drop the arguments */
3564 pt->pt_argc = 0;
3565 else
3566 {
3567 pt->pt_argc = ret_pt->pt_argc;
3568 for (i = 0; i < pt->pt_argc; i++)
3569 copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3570 }
3571 }
3572 partial_unref(ret_pt);
3573 }
3574 rettv->v_type = VAR_PARTIAL;
3575 rettv->vval.v_partial = pt;
3576 }
3577 }
3578 return selfdict;
3579}
3580
3581/*
3582 * Return the name of the executed function.
3583 */
3584 char_u *
3585func_name(void *cookie)
3586{
3587 return ((funccall_T *)cookie)->func->uf_name;
3588}
3589
3590/*
3591 * Return the address holding the next breakpoint line for a funccall cookie.
3592 */
3593 linenr_T *
3594func_breakpoint(void *cookie)
3595{
3596 return &((funccall_T *)cookie)->breakpoint;
3597}
3598
3599/*
3600 * Return the address holding the debug tick for a funccall cookie.
3601 */
3602 int *
3603func_dbg_tick(void *cookie)
3604{
3605 return &((funccall_T *)cookie)->dbg_tick;
3606}
3607
3608/*
3609 * Return the nesting level for a funccall cookie.
3610 */
3611 int
3612func_level(void *cookie)
3613{
3614 return ((funccall_T *)cookie)->level;
3615}
3616
3617/*
3618 * Return TRUE when a function was ended by a ":return" command.
3619 */
3620 int
3621current_func_returned(void)
3622{
3623 return current_funccal->returned;
3624}
3625
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003626 int
3627free_unref_funccal(int copyID, int testing)
3628{
3629 int did_free = FALSE;
3630 int did_free_funccal = FALSE;
3631 funccall_T *fc, **pfc;
3632
3633 for (pfc = &previous_funccal; *pfc != NULL; )
3634 {
3635 if (can_free_funccal(*pfc, copyID))
3636 {
3637 fc = *pfc;
3638 *pfc = fc->caller;
3639 free_funccal(fc, TRUE);
3640 did_free = TRUE;
3641 did_free_funccal = TRUE;
3642 }
3643 else
3644 pfc = &(*pfc)->caller;
3645 }
3646 if (did_free_funccal)
3647 /* When a funccal was freed some more items might be garbage
3648 * collected, so run again. */
3649 (void)garbage_collect(testing);
3650
3651 return did_free;
3652}
3653
3654/*
Bram Moolenaarba209902016-08-24 22:06:38 +02003655 * Get function call environment based on backtrace debug level
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003656 */
3657 static funccall_T *
3658get_funccal(void)
3659{
3660 int i;
3661 funccall_T *funccal;
3662 funccall_T *temp_funccal;
3663
3664 funccal = current_funccal;
3665 if (debug_backtrace_level > 0)
3666 {
3667 for (i = 0; i < debug_backtrace_level; i++)
3668 {
3669 temp_funccal = funccal->caller;
3670 if (temp_funccal)
3671 funccal = temp_funccal;
3672 else
3673 /* backtrace level overflow. reset to max */
3674 debug_backtrace_level = i;
3675 }
3676 }
3677 return funccal;
3678}
3679
3680/*
3681 * Return the hashtable used for local variables in the current funccal.
3682 * Return NULL if there is no current funccal.
3683 */
3684 hashtab_T *
3685get_funccal_local_ht()
3686{
3687 if (current_funccal == NULL)
3688 return NULL;
3689 return &get_funccal()->l_vars.dv_hashtab;
3690}
3691
3692/*
3693 * Return the l: scope variable.
3694 * Return NULL if there is no current funccal.
3695 */
3696 dictitem_T *
3697get_funccal_local_var()
3698{
3699 if (current_funccal == NULL)
3700 return NULL;
3701 return &get_funccal()->l_vars_var;
3702}
3703
3704/*
3705 * Return the hashtable used for argument in the current funccal.
3706 * Return NULL if there is no current funccal.
3707 */
3708 hashtab_T *
3709get_funccal_args_ht()
3710{
3711 if (current_funccal == NULL)
3712 return NULL;
3713 return &get_funccal()->l_avars.dv_hashtab;
3714}
3715
3716/*
3717 * Return the a: scope variable.
3718 * Return NULL if there is no current funccal.
3719 */
3720 dictitem_T *
3721get_funccal_args_var()
3722{
3723 if (current_funccal == NULL)
3724 return NULL;
Bram Moolenaarc7d9eac2017-02-01 20:26:51 +01003725 return &get_funccal()->l_avars_var;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003726}
3727
3728/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003729 * List function variables, if there is a function.
3730 */
3731 void
3732list_func_vars(int *first)
3733{
3734 if (current_funccal != NULL)
3735 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
Bram Moolenaar32526b32019-01-19 17:43:09 +01003736 "l:", FALSE, first);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003737}
3738
3739/*
3740 * If "ht" is the hashtable for local variables in the current funccal, return
3741 * the dict that contains it.
3742 * Otherwise return NULL.
3743 */
3744 dict_T *
3745get_current_funccal_dict(hashtab_T *ht)
3746{
3747 if (current_funccal != NULL
3748 && ht == &current_funccal->l_vars.dv_hashtab)
3749 return &current_funccal->l_vars;
3750 return NULL;
3751}
3752
3753/*
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003754 * Search hashitem in parent scope.
3755 */
3756 hashitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003757find_hi_in_scoped_ht(char_u *name, hashtab_T **pht)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003758{
3759 funccall_T *old_current_funccal = current_funccal;
3760 hashtab_T *ht;
3761 hashitem_T *hi = NULL;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003762 char_u *varname;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003763
3764 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3765 return NULL;
3766
3767 /* Search in parent scope which is possible to reference from lambda */
3768 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar58016442016-07-31 18:30:22 +02003769 while (current_funccal != NULL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003770 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003771 ht = find_var_ht(name, &varname);
3772 if (ht != NULL && *varname != NUL)
Bram Moolenaar58016442016-07-31 18:30:22 +02003773 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003774 hi = hash_find(ht, varname);
Bram Moolenaar58016442016-07-31 18:30:22 +02003775 if (!HASHITEM_EMPTY(hi))
3776 {
3777 *pht = ht;
3778 break;
3779 }
3780 }
3781 if (current_funccal == current_funccal->func->uf_scoped)
3782 break;
3783 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003784 }
3785 current_funccal = old_current_funccal;
3786
3787 return hi;
3788}
3789
3790/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003791 * Search variable in parent scope.
3792 */
3793 dictitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003794find_var_in_scoped_ht(char_u *name, int no_autoload)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003795{
3796 dictitem_T *v = NULL;
3797 funccall_T *old_current_funccal = current_funccal;
3798 hashtab_T *ht;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003799 char_u *varname;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003800
3801 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3802 return NULL;
3803
3804 /* Search in parent scope which is possible to reference from lambda */
3805 current_funccal = current_funccal->func->uf_scoped;
3806 while (current_funccal)
3807 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003808 ht = find_var_ht(name, &varname);
3809 if (ht != NULL && *varname != NUL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003810 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003811 v = find_var_in_ht(ht, *name, varname, no_autoload);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003812 if (v != NULL)
3813 break;
3814 }
3815 if (current_funccal == current_funccal->func->uf_scoped)
3816 break;
3817 current_funccal = current_funccal->func->uf_scoped;
3818 }
3819 current_funccal = old_current_funccal;
3820
3821 return v;
3822}
3823
3824/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003825 * Set "copyID + 1" in previous_funccal and callers.
3826 */
3827 int
3828set_ref_in_previous_funccal(int copyID)
3829{
3830 int abort = FALSE;
3831 funccall_T *fc;
3832
3833 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
3834 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003835 fc->fc_copyID = copyID + 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003836 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1,
3837 NULL);
3838 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1,
3839 NULL);
3840 }
3841 return abort;
3842}
3843
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003844 static int
3845set_ref_in_funccal(funccall_T *fc, int copyID)
3846{
3847 int abort = FALSE;
3848
3849 if (fc->fc_copyID != copyID)
3850 {
3851 fc->fc_copyID = copyID;
3852 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL);
3853 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL);
3854 abort = abort || set_ref_in_func(NULL, fc->func, copyID);
3855 }
3856 return abort;
3857}
3858
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003859/*
3860 * Set "copyID" in all local vars and arguments in the call stack.
3861 */
3862 int
3863set_ref_in_call_stack(int copyID)
3864{
3865 int abort = FALSE;
3866 funccall_T *fc;
3867
3868 for (fc = current_funccal; fc != NULL; fc = fc->caller)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003869 abort = abort || set_ref_in_funccal(fc, copyID);
3870 return abort;
3871}
3872
3873/*
3874 * Set "copyID" in all functions available by name.
3875 */
3876 int
3877set_ref_in_functions(int copyID)
3878{
3879 int todo;
3880 hashitem_T *hi = NULL;
3881 int abort = FALSE;
3882 ufunc_T *fp;
3883
3884 todo = (int)func_hashtab.ht_used;
3885 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003886 {
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003887 if (!HASHITEM_EMPTY(hi))
3888 {
3889 --todo;
3890 fp = HI2UF(hi);
3891 if (!func_name_refcount(fp->uf_name))
3892 abort = abort || set_ref_in_func(NULL, fp, copyID);
3893 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003894 }
3895 return abort;
3896}
3897
3898/*
3899 * Set "copyID" in all function arguments.
3900 */
3901 int
3902set_ref_in_func_args(int copyID)
3903{
3904 int i;
3905 int abort = FALSE;
3906
3907 for (i = 0; i < funcargs.ga_len; ++i)
3908 abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
3909 copyID, NULL, NULL);
3910 return abort;
3911}
3912
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003913/*
3914 * Mark all lists and dicts referenced through function "name" with "copyID".
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003915 * Returns TRUE if setting references failed somehow.
3916 */
3917 int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003918set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003919{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003920 ufunc_T *fp = fp_in;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003921 funccall_T *fc;
3922 int error = ERROR_NONE;
3923 char_u fname_buf[FLEN_FIXED + 1];
3924 char_u *tofree = NULL;
3925 char_u *fname;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003926 int abort = FALSE;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003927
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003928 if (name == NULL && fp_in == NULL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003929 return FALSE;
3930
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003931 if (fp_in == NULL)
3932 {
3933 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
3934 fp = find_func(fname);
3935 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003936 if (fp != NULL)
3937 {
3938 for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003939 abort = abort || set_ref_in_funccal(fc, copyID);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003940 }
3941 vim_free(tofree);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003942 return abort;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003943}
3944
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003945#endif /* FEAT_EVAL */