blob: 763903f8534531adadc17896e9a88f551c194621 [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
Bram Moolenaar209b8e32019-03-14 13:43:24 +010042// pointer to funccal for currently active function
43static funccall_T *current_funccal = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +020044
Bram Moolenaar209b8e32019-03-14 13:43:24 +010045// Pointer to list of previously used funccal, still around because some
46// item in it is still being used.
47static funccall_T *previous_funccal = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +020048
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);
Bram Moolenaareae1b912019-05-09 15:12:55 +020058static int prof_total_cmp(const void *s1, const void *s2);
59static int prof_self_cmp(const void *s1, const void *s2);
Bram Moolenaara9b579f2016-07-17 18:29:19 +020060#endif
Bram Moolenaarbc7ce672016-08-01 22:49:22 +020061static void funccal_unref(funccall_T *fc, ufunc_T *fp, int force);
Bram Moolenaara9b579f2016-07-17 18:29:19 +020062
63 void
64func_init()
65{
66 hash_init(&func_hashtab);
67}
68
Bram Moolenaar4f0383b2016-07-19 22:43:11 +020069/*
70 * Get function arguments.
71 */
Bram Moolenaara9b579f2016-07-17 18:29:19 +020072 static int
73get_function_args(
74 char_u **argp,
75 char_u endchar,
76 garray_T *newargs,
77 int *varargs,
Bram Moolenaar42ae78c2019-05-09 21:08:58 +020078 garray_T *default_args,
Bram Moolenaara9b579f2016-07-17 18:29:19 +020079 int skip)
80{
81 int mustend = FALSE;
82 char_u *arg = *argp;
83 char_u *p = arg;
84 int c;
85 int i;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +020086 int any_default = FALSE;
87 char_u *expr;
Bram Moolenaara9b579f2016-07-17 18:29:19 +020088
89 if (newargs != NULL)
90 ga_init2(newargs, (int)sizeof(char_u *), 3);
Bram Moolenaar42ae78c2019-05-09 21:08:58 +020091 if (default_args != NULL)
92 ga_init2(default_args, (int)sizeof(char_u *), 3);
Bram Moolenaara9b579f2016-07-17 18:29:19 +020093
94 if (varargs != NULL)
95 *varargs = FALSE;
96
97 /*
98 * Isolate the arguments: "arg1, arg2, ...)"
99 */
100 while (*p != endchar)
101 {
102 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
103 {
104 if (varargs != NULL)
105 *varargs = TRUE;
106 p += 3;
107 mustend = TRUE;
108 }
109 else
110 {
111 arg = p;
112 while (ASCII_ISALNUM(*p) || *p == '_')
113 ++p;
114 if (arg == p || isdigit(*arg)
115 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
116 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
117 {
118 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100119 semsg(_("E125: Illegal argument: %s"), arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200120 break;
121 }
122 if (newargs != NULL && ga_grow(newargs, 1) == FAIL)
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200123 goto err_ret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200124 if (newargs != NULL)
125 {
126 c = *p;
127 *p = NUL;
128 arg = vim_strsave(arg);
129 if (arg == NULL)
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200130 {
131 *p = c;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200132 goto err_ret;
Bram Moolenaar19df5cc2016-07-20 22:11:06 +0200133 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200134
135 /* Check for duplicate argument name. */
136 for (i = 0; i < newargs->ga_len; ++i)
137 if (STRCMP(((char_u **)(newargs->ga_data))[i], arg) == 0)
138 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100139 semsg(_("E853: Duplicate argument name: %s"), arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200140 vim_free(arg);
141 goto err_ret;
142 }
143 ((char_u **)(newargs->ga_data))[newargs->ga_len] = arg;
144 newargs->ga_len++;
145
146 *p = c;
147 }
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200148 if (*skipwhite(p) == '=' && default_args != NULL)
149 {
150 typval_T rettv;
151
152 any_default = TRUE;
153 p = skipwhite(p) + 1;
154 p = skipwhite(p);
155 expr = p;
156 if (eval1(&p, &rettv, FALSE) != FAIL)
157 {
158 if (ga_grow(default_args, 1) == FAIL)
159 goto err_ret;
160
161 // trim trailing whitespace
162 while (p > expr && VIM_ISWHITE(p[-1]))
163 p--;
164 c = *p;
165 *p = NUL;
166 expr = vim_strsave(expr);
167 if (expr == NULL)
168 {
169 *p = c;
170 goto err_ret;
171 }
172 ((char_u **)(default_args->ga_data))
173 [default_args->ga_len] = expr;
174 default_args->ga_len++;
175 *p = c;
176 }
177 else
178 mustend = TRUE;
179 }
180 else if (any_default)
181 {
182 emsg(_("E989: Non-default argument follows default argument"));
183 mustend = TRUE;
184 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200185 if (*p == ',')
186 ++p;
187 else
188 mustend = TRUE;
189 }
190 p = skipwhite(p);
191 if (mustend && *p != endchar)
192 {
193 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100194 semsg(_(e_invarg2), *argp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200195 break;
196 }
197 }
Bram Moolenaar4f0383b2016-07-19 22:43:11 +0200198 if (*p != endchar)
199 goto err_ret;
200 ++p; /* skip "endchar" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200201
202 *argp = p;
203 return OK;
204
205err_ret:
206 if (newargs != NULL)
207 ga_clear_strings(newargs);
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200208 if (default_args != NULL)
209 ga_clear_strings(default_args);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200210 return FAIL;
211}
212
213/*
Bram Moolenaar58016442016-07-31 18:30:22 +0200214 * Register function "fp" as using "current_funccal" as its scope.
215 */
216 static int
217register_closure(ufunc_T *fp)
218{
Bram Moolenaar8dd3a432016-08-01 20:46:25 +0200219 if (fp->uf_scoped == current_funccal)
220 /* no change */
221 return OK;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +0200222 funccal_unref(fp->uf_scoped, fp, FALSE);
Bram Moolenaar58016442016-07-31 18:30:22 +0200223 fp->uf_scoped = current_funccal;
224 current_funccal->fc_refcount++;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +0200225
Bram Moolenaar58016442016-07-31 18:30:22 +0200226 if (ga_grow(&current_funccal->fc_funcs, 1) == FAIL)
227 return FAIL;
228 ((ufunc_T **)current_funccal->fc_funcs.ga_data)
229 [current_funccal->fc_funcs.ga_len++] = fp;
Bram Moolenaar58016442016-07-31 18:30:22 +0200230 return OK;
231}
232
233/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200234 * Parse a lambda expression and get a Funcref from "*arg".
235 * Return OK or FAIL. Returns NOTDONE for dict or {expr}.
236 */
237 int
238get_lambda_tv(char_u **arg, typval_T *rettv, int evaluate)
239{
240 garray_T newargs;
241 garray_T newlines;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200242 garray_T *pnewargs;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200243 ufunc_T *fp = NULL;
Bram Moolenaar445e71c2019-02-14 13:43:36 +0100244 partial_T *pt = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200245 int varargs;
246 int ret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200247 char_u *start = skipwhite(*arg + 1);
248 char_u *s, *e;
249 static int lambda_no = 0;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200250 int *old_eval_lavars = eval_lavars_used;
251 int eval_lavars = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200252
253 ga_init(&newargs);
254 ga_init(&newlines);
255
256 /* First, check if this is a lambda expression. "->" must exist. */
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200257 ret = get_function_args(&start, '-', NULL, NULL, NULL, TRUE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200258 if (ret == FAIL || *start != '>')
259 return NOTDONE;
260
261 /* Parse the arguments again. */
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200262 if (evaluate)
263 pnewargs = &newargs;
264 else
265 pnewargs = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200266 *arg = skipwhite(*arg + 1);
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200267 ret = get_function_args(arg, '-', pnewargs, &varargs, NULL, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200268 if (ret == FAIL || **arg != '>')
269 goto errret;
270
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +0200271 /* Set up a flag for checking local variables and arguments. */
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200272 if (evaluate)
273 eval_lavars_used = &eval_lavars;
274
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200275 /* Get the start and the end of the expression. */
276 *arg = skipwhite(*arg + 1);
277 s = *arg;
278 ret = skip_expr(arg);
279 if (ret == FAIL)
280 goto errret;
281 e = *arg;
282 *arg = skipwhite(*arg);
283 if (**arg != '}')
284 goto errret;
285 ++*arg;
286
287 if (evaluate)
288 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200289 int len, flags = 0;
290 char_u *p;
291 char_u name[20];
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200292
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200293 sprintf((char*)name, "<lambda>%d", ++lambda_no);
294
Bram Moolenaar58016442016-07-31 18:30:22 +0200295 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200296 if (fp == NULL)
297 goto errret;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200298 pt = (partial_T *)alloc_clear((unsigned)sizeof(partial_T));
299 if (pt == NULL)
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200300 goto errret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200301
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200302 ga_init2(&newlines, (int)sizeof(char_u *), 1);
303 if (ga_grow(&newlines, 1) == FAIL)
304 goto errret;
305
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200306 /* Add "return " before the expression. */
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200307 len = 7 + e - s + 1;
308 p = (char_u *)alloc(len);
309 if (p == NULL)
310 goto errret;
311 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
312 STRCPY(p, "return ");
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200313 vim_strncpy(p + 7, s, e - s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200314
315 fp->uf_refcount = 1;
316 STRCPY(fp->uf_name, name);
317 hash_add(&func_hashtab, UF2HIKEY(fp));
318 fp->uf_args = newargs;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200319 ga_init(&fp->uf_def_args);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200320 fp->uf_lines = newlines;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200321 if (current_funccal != NULL && eval_lavars)
322 {
Bram Moolenaar10ce39a2016-07-29 22:37:06 +0200323 flags |= FC_CLOSURE;
Bram Moolenaar58016442016-07-31 18:30:22 +0200324 if (register_closure(fp) == FAIL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200325 goto errret;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200326 }
327 else
328 fp->uf_scoped = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200329
330#ifdef FEAT_PROFILE
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200331 if (prof_def_func())
332 func_do_profile(fp);
333#endif
Bram Moolenaar93343722018-07-10 19:39:18 +0200334 if (sandbox)
335 flags |= FC_SANDBOX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200336 fp->uf_varargs = TRUE;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +0200337 fp->uf_flags = flags;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200338 fp->uf_calls = 0;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200339 fp->uf_script_ctx = current_sctx;
340 fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200341
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200342 pt->pt_func = fp;
343 pt->pt_refcount = 1;
344 rettv->vval.v_partial = pt;
345 rettv->v_type = VAR_PARTIAL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200346 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200347
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200348 eval_lavars_used = old_eval_lavars;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200349 return OK;
350
351errret:
352 ga_clear_strings(&newargs);
353 ga_clear_strings(&newlines);
354 vim_free(fp);
Bram Moolenaar445e71c2019-02-14 13:43:36 +0100355 vim_free(pt);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200356 eval_lavars_used = old_eval_lavars;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200357 return FAIL;
358}
359
360/*
361 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
362 * name it contains, otherwise return "name".
363 * If "partialp" is not NULL, and "name" is of type VAR_PARTIAL also set
364 * "partialp".
365 */
366 char_u *
367deref_func_name(char_u *name, int *lenp, partial_T **partialp, int no_autoload)
368{
369 dictitem_T *v;
370 int cc;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200371 char_u *s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200372
373 if (partialp != NULL)
374 *partialp = NULL;
375
376 cc = name[*lenp];
377 name[*lenp] = NUL;
378 v = find_var(name, NULL, no_autoload);
379 name[*lenp] = cc;
380 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
381 {
382 if (v->di_tv.vval.v_string == NULL)
383 {
384 *lenp = 0;
385 return (char_u *)""; /* just in case */
386 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200387 s = v->di_tv.vval.v_string;
388 *lenp = (int)STRLEN(s);
389 return s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200390 }
391
392 if (v != NULL && v->di_tv.v_type == VAR_PARTIAL)
393 {
394 partial_T *pt = v->di_tv.vval.v_partial;
395
396 if (pt == NULL)
397 {
398 *lenp = 0;
399 return (char_u *)""; /* just in case */
400 }
401 if (partialp != NULL)
402 *partialp = pt;
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200403 s = partial_name(pt);
404 *lenp = (int)STRLEN(s);
405 return s;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200406 }
407
408 return name;
409}
410
411/*
412 * Give an error message with a function name. Handle <SNR> things.
413 * "ermsg" is to be passed without translation, use N_() instead of _().
414 */
415 static void
416emsg_funcname(char *ermsg, char_u *name)
417{
418 char_u *p;
419
420 if (*name == K_SPECIAL)
421 p = concat_str((char_u *)"<SNR>", name + 3);
422 else
423 p = name;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100424 semsg(_(ermsg), p);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200425 if (p != name)
426 vim_free(p);
427}
428
429/*
430 * Allocate a variable for the result of a function.
431 * Return OK or FAIL.
432 */
433 int
434get_func_tv(
Bram Moolenaar6ed88192019-05-11 18:37:44 +0200435 char_u *name, // name of the function
436 int len, // length of "name" or -1 to use strlen()
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200437 typval_T *rettv,
Bram Moolenaar6ed88192019-05-11 18:37:44 +0200438 char_u **arg, // argument, pointing to the '('
439 linenr_T firstline, // first line of range
440 linenr_T lastline, // last line of range
441 int *doesrange, // return: function handled range
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200442 int evaluate,
Bram Moolenaar6ed88192019-05-11 18:37:44 +0200443 partial_T *partial, // for extra arguments
444 dict_T *selfdict) // Dictionary for "self"
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200445{
446 char_u *argp;
447 int ret = OK;
448 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
449 int argcount = 0; /* number of arguments found */
450
451 /*
452 * Get the arguments.
453 */
454 argp = *arg;
455 while (argcount < MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
456 {
457 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
458 if (*argp == ')' || *argp == ',' || *argp == NUL)
459 break;
460 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
461 {
462 ret = FAIL;
463 break;
464 }
465 ++argcount;
466 if (*argp != ',')
467 break;
468 }
469 if (*argp == ')')
470 ++argp;
471 else
472 ret = FAIL;
473
474 if (ret == OK)
475 {
476 int i = 0;
477
478 if (get_vim_var_nr(VV_TESTING))
479 {
480 /* Prepare for calling test_garbagecollect_now(), need to know
481 * what variables are used on the call stack. */
482 if (funcargs.ga_itemsize == 0)
483 ga_init2(&funcargs, (int)sizeof(typval_T *), 50);
484 for (i = 0; i < argcount; ++i)
485 if (ga_grow(&funcargs, 1) == OK)
486 ((typval_T **)funcargs.ga_data)[funcargs.ga_len++] =
487 &argvars[i];
488 }
489
Bram Moolenaardf48fb42016-07-22 21:50:18 +0200490 ret = call_func(name, len, rettv, argcount, argvars, NULL,
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200491 firstline, lastline, doesrange, evaluate, partial, selfdict);
492
493 funcargs.ga_len -= i;
494 }
495 else if (!aborting())
496 {
497 if (argcount == MAX_FUNC_ARGS)
498 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
499 else
500 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
501 }
502
503 while (--argcount >= 0)
504 clear_tv(&argvars[argcount]);
505
506 *arg = skipwhite(argp);
507 return ret;
508}
509
510#define FLEN_FIXED 40
511
512/*
513 * Return TRUE if "p" starts with "<SID>" or "s:".
514 * Only works if eval_fname_script() returned non-zero for "p"!
515 */
516 static int
517eval_fname_sid(char_u *p)
518{
519 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
520}
521
522/*
523 * In a script change <SID>name() and s:name() to K_SNR 123_name().
524 * Change <SNR>123_name() to K_SNR 123_name().
525 * Use "fname_buf[FLEN_FIXED + 1]" when it fits, otherwise allocate memory
526 * (slow).
527 */
528 static char_u *
529fname_trans_sid(char_u *name, char_u *fname_buf, char_u **tofree, int *error)
530{
531 int llen;
532 char_u *fname;
533 int i;
534
535 llen = eval_fname_script(name);
536 if (llen > 0)
537 {
538 fname_buf[0] = K_SPECIAL;
539 fname_buf[1] = KS_EXTRA;
540 fname_buf[2] = (int)KE_SNR;
541 i = 3;
542 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
543 {
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200544 if (current_sctx.sc_sid <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200545 *error = ERROR_SCRIPT;
546 else
547 {
Bram Moolenaarad3ec762019-04-21 00:00:13 +0200548 sprintf((char *)fname_buf + 3, "%ld_",
549 (long)current_sctx.sc_sid);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200550 i = (int)STRLEN(fname_buf);
551 }
552 }
553 if (i + STRLEN(name + llen) < FLEN_FIXED)
554 {
555 STRCPY(fname_buf + i, name + llen);
556 fname = fname_buf;
557 }
558 else
559 {
560 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
561 if (fname == NULL)
562 *error = ERROR_OTHER;
563 else
564 {
565 *tofree = fname;
566 mch_memmove(fname, fname_buf, (size_t)i);
567 STRCPY(fname + i, name + llen);
568 }
569 }
570 }
571 else
572 fname = name;
573 return fname;
574}
575
576/*
577 * Find a function by name, return pointer to it in ufuncs.
578 * Return NULL for unknown function.
579 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200580 ufunc_T *
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200581find_func(char_u *name)
582{
583 hashitem_T *hi;
584
585 hi = hash_find(&func_hashtab, name);
586 if (!HASHITEM_EMPTY(hi))
587 return HI2UF(hi);
588 return NULL;
589}
590
591/*
592 * Copy the function name of "fp" to buffer "buf".
593 * "buf" must be able to hold the function name plus three bytes.
594 * Takes care of script-local function names.
595 */
596 static void
597cat_func_name(char_u *buf, ufunc_T *fp)
598{
599 if (fp->uf_name[0] == K_SPECIAL)
600 {
601 STRCPY(buf, "<SNR>");
602 STRCAT(buf, fp->uf_name + 3);
603 }
604 else
605 STRCPY(buf, fp->uf_name);
606}
607
608/*
609 * Add a number variable "name" to dict "dp" with value "nr".
610 */
611 static void
612add_nr_var(
613 dict_T *dp,
614 dictitem_T *v,
615 char *name,
616 varnumber_T nr)
617{
618 STRCPY(v->di_key, name);
619 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
620 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
621 v->di_tv.v_type = VAR_NUMBER;
622 v->di_tv.v_lock = VAR_FIXED;
623 v->di_tv.vval.v_number = nr;
624}
625
626/*
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100627 * Free "fc".
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200628 */
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100629 static void
630free_funccal(funccall_T *fc)
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200631{
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100632 int i;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200633
634 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
635 {
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100636 ufunc_T *fp = ((ufunc_T **)(fc->fc_funcs.ga_data))[i];
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200637
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100638 // When garbage collecting a funccall_T may be freed before the
639 // function that references it, clear its uf_scoped field.
640 // The function may have been redefined and point to another
641 // funccall_T, don't clear it then.
Bram Moolenaarbc7ce672016-08-01 22:49:22 +0200642 if (fp != NULL && fp->uf_scoped == fc)
643 fp->uf_scoped = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200644 }
Bram Moolenaar58016442016-07-31 18:30:22 +0200645 ga_clear(&fc->fc_funcs);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200646
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200647 func_ptr_unref(fc->func);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200648 vim_free(fc);
649}
650
651/*
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100652 * Free "fc" and what it contains.
653 * Can be called only when "fc" is kept beyond the period of it called,
654 * i.e. after cleanup_function_call(fc).
655 */
656 static void
657free_funccal_contents(funccall_T *fc)
658{
659 listitem_T *li;
660
661 // Free all l: variables.
662 vars_clear(&fc->l_vars.dv_hashtab);
663
664 // Free all a: variables.
665 vars_clear(&fc->l_avars.dv_hashtab);
666
667 // Free the a:000 variables.
668 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
669 clear_tv(&li->li_tv);
670
671 free_funccal(fc);
672}
673
674/*
Bram Moolenaar6914c642017-04-01 21:21:30 +0200675 * Handle the last part of returning from a function: free the local hashtable.
676 * Unless it is still in use by a closure.
677 */
678 static void
679cleanup_function_call(funccall_T *fc)
680{
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100681 int may_free_fc = fc->fc_refcount <= 0;
682 int free_fc = TRUE;
683
Bram Moolenaar6914c642017-04-01 21:21:30 +0200684 current_funccal = fc->caller;
685
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100686 // Free all l: variables if not referred.
687 if (may_free_fc && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT)
688 vars_clear(&fc->l_vars.dv_hashtab);
689 else
690 free_fc = FALSE;
691
692 // If the a:000 list and the l: and a: dicts are not referenced and
693 // there is no closure using it, we can free the funccall_T and what's
694 // in it.
695 if (may_free_fc && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
696 vars_clear_ext(&fc->l_avars.dv_hashtab, FALSE);
Bram Moolenaar6914c642017-04-01 21:21:30 +0200697 else
698 {
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100699 int todo;
700 hashitem_T *hi;
701 dictitem_T *di;
Bram Moolenaar6914c642017-04-01 21:21:30 +0200702
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100703 free_fc = FALSE;
Bram Moolenaar6914c642017-04-01 21:21:30 +0200704
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100705 // Make a copy of the a: variables, since we didn't do that above.
Bram Moolenaar6914c642017-04-01 21:21:30 +0200706 todo = (int)fc->l_avars.dv_hashtab.ht_used;
707 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
708 {
709 if (!HASHITEM_EMPTY(hi))
710 {
711 --todo;
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100712 di = HI2DI(hi);
713 copy_tv(&di->di_tv, &di->di_tv);
Bram Moolenaar6914c642017-04-01 21:21:30 +0200714 }
715 }
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100716 }
Bram Moolenaar6914c642017-04-01 21:21:30 +0200717
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100718 if (may_free_fc && fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT)
719 fc->l_varlist.lv_first = NULL;
720 else
721 {
722 listitem_T *li;
723
724 free_fc = FALSE;
725
726 // Make a copy of the a:000 items, since we didn't do that above.
Bram Moolenaar6914c642017-04-01 21:21:30 +0200727 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
728 copy_tv(&li->li_tv, &li->li_tv);
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100729 }
Bram Moolenaar4456ab52019-01-23 23:00:30 +0100730
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100731 if (free_fc)
732 free_funccal(fc);
733 else
734 {
735 static int made_copy = 0;
736
737 // "fc" is still in use. This can happen when returning "a:000",
738 // assigning "l:" to a global variable or defining a closure.
739 // Link "fc" in the list for garbage collection later.
740 fc->caller = previous_funccal;
741 previous_funccal = fc;
742
743 if (want_garbage_collect)
744 // If garbage collector is ready, clear count.
745 made_copy = 0;
746 else if (++made_copy >= (int)((4096 * 1024) / sizeof(*fc)))
Bram Moolenaar4456ab52019-01-23 23:00:30 +0100747 {
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100748 // We have made a lot of copies, worth 4 Mbyte. This can happen
749 // when repetitively calling a function that creates a reference to
Bram Moolenaar889da2f2019-02-02 14:02:30 +0100750 // itself somehow. Call the garbage collector soon to avoid using
Bram Moolenaar4456ab52019-01-23 23:00:30 +0100751 // too much memory.
752 made_copy = 0;
Bram Moolenaar889da2f2019-02-02 14:02:30 +0100753 want_garbage_collect = TRUE;
Bram Moolenaar4456ab52019-01-23 23:00:30 +0100754 }
Bram Moolenaar6914c642017-04-01 21:21:30 +0200755 }
756}
757
758/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200759 * Call a user function.
760 */
761 static void
762call_user_func(
763 ufunc_T *fp, /* pointer to function */
764 int argcount, /* nr of args */
765 typval_T *argvars, /* arguments */
766 typval_T *rettv, /* return value */
767 linenr_T firstline, /* first line of range */
768 linenr_T lastline, /* last line of range */
769 dict_T *selfdict) /* Dictionary for "self" */
770{
771 char_u *save_sourcing_name;
772 linenr_T save_sourcing_lnum;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +0200773 sctx_T save_current_sctx;
Bram Moolenaar93343722018-07-10 19:39:18 +0200774 int using_sandbox = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200775 funccall_T *fc;
776 int save_did_emsg;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200777 int default_arg_err = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200778 static int depth = 0;
779 dictitem_T *v;
780 int fixvar_idx = 0; /* index in fixvar[] */
781 int i;
782 int ai;
783 int islambda = FALSE;
784 char_u numbuf[NUMBUFLEN];
785 char_u *name;
786 size_t len;
787#ifdef FEAT_PROFILE
788 proftime_T wait_start;
789 proftime_T call_start;
Bram Moolenaarad648092018-06-30 18:28:03 +0200790 int started_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200791#endif
792
793 /* If depth of calling is getting too high, don't execute the function */
794 if (depth >= p_mfd)
795 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100796 emsg(_("E132: Function call depth is higher than 'maxfuncdepth'"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200797 rettv->v_type = VAR_NUMBER;
798 rettv->vval.v_number = -1;
799 return;
800 }
801 ++depth;
802
803 line_breakcheck(); /* check for CTRL-C hit */
804
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100805 fc = (funccall_T *)alloc_clear(sizeof(funccall_T));
Bram Moolenaar4456ab52019-01-23 23:00:30 +0100806 if (fc == NULL)
807 return;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200808 fc->caller = current_funccal;
809 current_funccal = fc;
810 fc->func = fp;
811 fc->rettv = rettv;
812 rettv->vval.v_number = 0;
813 fc->linenr = 0;
814 fc->returned = FALSE;
815 fc->level = ex_nesting_level;
816 /* Check if this function has a breakpoint. */
817 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
818 fc->dbg_tick = debug_tick;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200819 /* Set up fields for closure. */
820 fc->fc_refcount = 0;
821 fc->fc_copyID = 0;
822 ga_init2(&fc->fc_funcs, sizeof(ufunc_T *), 1);
Bram Moolenaar437bafe2016-08-01 15:40:54 +0200823 func_ptr_ref(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200824
825 if (STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
826 islambda = TRUE;
827
828 /*
829 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
830 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
831 * each argument variable and saves a lot of time.
832 */
833 /*
834 * Init l: variables.
835 */
836 init_var_dict(&fc->l_vars, &fc->l_vars_var, VAR_DEF_SCOPE);
837 if (selfdict != NULL)
838 {
839 /* Set l:self to "selfdict". Use "name" to avoid a warning from
840 * some compiler that checks the destination size. */
841 v = &fc->fixvar[fixvar_idx++].var;
842 name = v->di_key;
843 STRCPY(name, "self");
Bram Moolenaar31b81602019-02-10 22:14:27 +0100844 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200845 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
846 v->di_tv.v_type = VAR_DICT;
847 v->di_tv.v_lock = 0;
848 v->di_tv.vval.v_dict = selfdict;
849 ++selfdict->dv_refcount;
850 }
851
852 /*
853 * Init a: variables.
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200854 * Set a:0 to "argcount" less number of named arguments, if >= 0.
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200855 * Set a:000 to a list with room for the "..." arguments.
856 */
857 init_var_dict(&fc->l_avars, &fc->l_avars_var, VAR_SCOPE);
858 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200859 (varnumber_T)(argcount >= fp->uf_args.ga_len
860 ? argcount - fp->uf_args.ga_len : 0));
Bram Moolenaar31b81602019-02-10 22:14:27 +0100861 fc->l_avars.dv_lock = VAR_FIXED;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200862 /* Use "name" to avoid a warning from some compiler that checks the
863 * destination size. */
864 v = &fc->fixvar[fixvar_idx++].var;
865 name = v->di_key;
866 STRCPY(name, "000");
867 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
868 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
869 v->di_tv.v_type = VAR_LIST;
870 v->di_tv.v_lock = VAR_FIXED;
871 v->di_tv.vval.v_list = &fc->l_varlist;
872 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
873 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
874 fc->l_varlist.lv_lock = VAR_FIXED;
875
876 /*
877 * Set a:firstline to "firstline" and a:lastline to "lastline".
878 * Set a:name to named arguments.
879 * Set a:N to the "..." arguments.
880 */
881 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
882 (varnumber_T)firstline);
883 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
884 (varnumber_T)lastline);
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200885 for (i = 0; i < argcount || i < fp->uf_args.ga_len; ++i)
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200886 {
887 int addlocal = FALSE;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200888 typval_T def_rettv;
889 int isdefault = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200890
891 ai = i - fp->uf_args.ga_len;
892 if (ai < 0)
893 {
894 /* named argument a:name */
895 name = FUNCARG(fp, i);
896 if (islambda)
897 addlocal = TRUE;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200898
899 // evaluate named argument default expression
900 isdefault = ai + fp->uf_def_args.ga_len >= 0
901 && (i >= argcount || (argvars[i].v_type == VAR_SPECIAL
902 && argvars[i].vval.v_number == VVAL_NONE));
903 if (isdefault)
904 {
905 char_u *default_expr = NULL;
906 def_rettv.v_type = VAR_NUMBER;
907 def_rettv.vval.v_number = -1;
908
909 default_expr = ((char_u **)(fp->uf_def_args.ga_data))
910 [ai + fp->uf_def_args.ga_len];
911 if (eval1(&default_expr, &def_rettv, TRUE) == FAIL)
912 {
913 default_arg_err = 1;
914 break;
915 }
916 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200917 }
918 else
919 {
920 /* "..." argument a:1, a:2, etc. */
921 sprintf((char *)numbuf, "%d", ai + 1);
922 name = numbuf;
923 }
924 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
925 {
926 v = &fc->fixvar[fixvar_idx++].var;
927 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100928 STRCPY(v->di_key, name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200929 }
930 else
931 {
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100932 v = dictitem_alloc(name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200933 if (v == NULL)
934 break;
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100935 v->di_flags |= DI_FLAGS_RO | DI_FLAGS_FIX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200936 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200937
Bram Moolenaar42ae78c2019-05-09 21:08:58 +0200938 if (isdefault)
939 v->di_tv = def_rettv;
940 else
941 // Note: the values are copied directly to avoid alloc/free.
942 // "argvars" must have VAR_FIXED for v_lock.
943 v->di_tv = argvars[i];
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200944 v->di_tv.v_lock = VAR_FIXED;
945
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200946 if (addlocal)
947 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200948 /* Named arguments should be accessed without the "a:" prefix in
949 * lambda expressions. Add to the l: dict. */
950 copy_tv(&v->di_tv, &v->di_tv);
951 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200952 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +0200953 else
954 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200955
956 if (ai >= 0 && ai < MAX_FUNC_ARGS)
957 {
Bram Moolenaar209b8e32019-03-14 13:43:24 +0100958 listitem_T *li = &fc->l_listitems[ai];
959
960 li->li_tv = argvars[i];
961 li->li_tv.v_lock = VAR_FIXED;
962 list_append(&fc->l_varlist, li);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200963 }
964 }
965
966 /* Don't redraw while executing the function. */
967 ++RedrawingDisabled;
968 save_sourcing_name = sourcing_name;
969 save_sourcing_lnum = sourcing_lnum;
970 sourcing_lnum = 1;
Bram Moolenaar93343722018-07-10 19:39:18 +0200971
972 if (fp->uf_flags & FC_SANDBOX)
973 {
974 using_sandbox = TRUE;
975 ++sandbox;
976 }
977
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200978 /* need space for function name + ("function " + 3) or "[number]" */
979 len = (save_sourcing_name == NULL ? 0 : STRLEN(save_sourcing_name))
980 + STRLEN(fp->uf_name) + 20;
981 sourcing_name = alloc((unsigned)len);
982 if (sourcing_name != NULL)
983 {
984 if (save_sourcing_name != NULL
985 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
986 sprintf((char *)sourcing_name, "%s[%d]..",
987 save_sourcing_name, (int)save_sourcing_lnum);
988 else
989 STRCPY(sourcing_name, "function ");
990 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
991
992 if (p_verbose >= 12)
993 {
994 ++no_wait_return;
995 verbose_enter_scroll();
996
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100997 smsg(_("calling %s"), sourcing_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +0200998 if (p_verbose >= 14)
999 {
1000 char_u buf[MSG_BUF_LEN];
1001 char_u numbuf2[NUMBUFLEN];
1002 char_u *tofree;
1003 char_u *s;
1004
Bram Moolenaar32526b32019-01-19 17:43:09 +01001005 msg_puts("(");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001006 for (i = 0; i < argcount; ++i)
1007 {
1008 if (i > 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001009 msg_puts(", ");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001010 if (argvars[i].v_type == VAR_NUMBER)
1011 msg_outnum((long)argvars[i].vval.v_number);
1012 else
1013 {
1014 /* Do not want errors such as E724 here. */
1015 ++emsg_off;
1016 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
1017 --emsg_off;
1018 if (s != NULL)
1019 {
1020 if (vim_strsize(s) > MSG_BUF_CLEN)
1021 {
1022 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
1023 s = buf;
1024 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01001025 msg_puts((char *)s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001026 vim_free(tofree);
1027 }
1028 }
1029 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01001030 msg_puts(")");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001031 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01001032 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001033
1034 verbose_leave_scroll();
1035 --no_wait_return;
1036 }
1037 }
1038#ifdef FEAT_PROFILE
1039 if (do_profiling == PROF_YES)
1040 {
1041 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
Bram Moolenaarad648092018-06-30 18:28:03 +02001042 {
1043 started_profiling = TRUE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001044 func_do_profile(fp);
Bram Moolenaarad648092018-06-30 18:28:03 +02001045 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001046 if (fp->uf_profiling
1047 || (fc->caller != NULL && fc->caller->func->uf_profiling))
1048 {
1049 ++fp->uf_tm_count;
1050 profile_start(&call_start);
1051 profile_zero(&fp->uf_tm_children);
1052 }
1053 script_prof_save(&wait_start);
1054 }
1055#endif
1056
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001057 save_current_sctx = current_sctx;
1058 current_sctx = fp->uf_script_ctx;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001059 save_did_emsg = did_emsg;
1060 did_emsg = FALSE;
1061
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02001062 if (default_arg_err && (fp->uf_flags & FC_ABORT))
1063 did_emsg = TRUE;
1064 else
1065 // call do_cmdline() to execute the lines
1066 do_cmdline(NULL, get_func_line, (void *)fc,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001067 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
1068
1069 --RedrawingDisabled;
1070
1071 /* when the function was aborted because of an error, return -1 */
1072 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
1073 {
1074 clear_tv(rettv);
1075 rettv->v_type = VAR_NUMBER;
1076 rettv->vval.v_number = -1;
1077 }
1078
1079#ifdef FEAT_PROFILE
1080 if (do_profiling == PROF_YES && (fp->uf_profiling
1081 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
1082 {
1083 profile_end(&call_start);
1084 profile_sub_wait(&wait_start, &call_start);
1085 profile_add(&fp->uf_tm_total, &call_start);
1086 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
1087 if (fc->caller != NULL && fc->caller->func->uf_profiling)
1088 {
1089 profile_add(&fc->caller->func->uf_tm_children, &call_start);
1090 profile_add(&fc->caller->func->uf_tml_children, &call_start);
1091 }
Bram Moolenaarad648092018-06-30 18:28:03 +02001092 if (started_profiling)
1093 // make a ":profdel func" stop profiling the function
1094 fp->uf_profiling = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001095 }
1096#endif
1097
1098 /* when being verbose, mention the return value */
1099 if (p_verbose >= 12)
1100 {
1101 ++no_wait_return;
1102 verbose_enter_scroll();
1103
1104 if (aborting())
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001105 smsg(_("%s aborted"), sourcing_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001106 else if (fc->rettv->v_type == VAR_NUMBER)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001107 smsg(_("%s returning #%ld"), sourcing_name,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001108 (long)fc->rettv->vval.v_number);
1109 else
1110 {
1111 char_u buf[MSG_BUF_LEN];
1112 char_u numbuf2[NUMBUFLEN];
1113 char_u *tofree;
1114 char_u *s;
1115
1116 /* The value may be very long. Skip the middle part, so that we
1117 * have some idea how it starts and ends. smsg() would always
1118 * truncate it at the end. Don't want errors such as E724 here. */
1119 ++emsg_off;
1120 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
1121 --emsg_off;
1122 if (s != NULL)
1123 {
1124 if (vim_strsize(s) > MSG_BUF_CLEN)
1125 {
1126 trunc_string(s, buf, MSG_BUF_CLEN, MSG_BUF_LEN);
1127 s = buf;
1128 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001129 smsg(_("%s returning %s"), sourcing_name, s);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001130 vim_free(tofree);
1131 }
1132 }
Bram Moolenaar32526b32019-01-19 17:43:09 +01001133 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001134
1135 verbose_leave_scroll();
1136 --no_wait_return;
1137 }
1138
1139 vim_free(sourcing_name);
1140 sourcing_name = save_sourcing_name;
1141 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001142 current_sctx = save_current_sctx;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001143#ifdef FEAT_PROFILE
1144 if (do_profiling == PROF_YES)
1145 script_prof_restore(&wait_start);
1146#endif
Bram Moolenaar93343722018-07-10 19:39:18 +02001147 if (using_sandbox)
1148 --sandbox;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001149
1150 if (p_verbose >= 12 && sourcing_name != NULL)
1151 {
1152 ++no_wait_return;
1153 verbose_enter_scroll();
1154
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001155 smsg(_("continuing in %s"), sourcing_name);
Bram Moolenaar32526b32019-01-19 17:43:09 +01001156 msg_puts("\n"); /* don't overwrite this either */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001157
1158 verbose_leave_scroll();
1159 --no_wait_return;
1160 }
1161
1162 did_emsg |= save_did_emsg;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001163 --depth;
1164
Bram Moolenaar6914c642017-04-01 21:21:30 +02001165 cleanup_function_call(fc);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001166}
1167
1168/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001169 * Unreference "fc": decrement the reference count and free it when it
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001170 * becomes zero. "fp" is detached from "fc".
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001171 * When "force" is TRUE we are exiting.
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001172 */
1173 static void
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001174funccal_unref(funccall_T *fc, ufunc_T *fp, int force)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001175{
1176 funccall_T **pfc;
1177 int i;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001178
1179 if (fc == NULL)
1180 return;
1181
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001182 if (--fc->fc_refcount <= 0 && (force || (
1183 fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001184 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001185 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001186 for (pfc = &previous_funccal; *pfc != NULL; pfc = &(*pfc)->caller)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001187 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001188 if (fc == *pfc)
1189 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001190 *pfc = fc->caller;
Bram Moolenaar209b8e32019-03-14 13:43:24 +01001191 free_funccal_contents(fc);
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001192 return;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001193 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001194 }
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001195 for (i = 0; i < fc->fc_funcs.ga_len; ++i)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001196 if (((ufunc_T **)(fc->fc_funcs.ga_data))[i] == fp)
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001197 ((ufunc_T **)(fc->fc_funcs.ga_data))[i] = NULL;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02001198}
1199
1200/*
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001201 * Remove the function from the function hashtable. If the function was
1202 * deleted while it still has references this was already done.
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001203 * Return TRUE if the entry was deleted, FALSE if it wasn't found.
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001204 */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001205 static int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001206func_remove(ufunc_T *fp)
1207{
1208 hashitem_T *hi = hash_find(&func_hashtab, UF2HIKEY(fp));
1209
1210 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001211 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001212 hash_remove(&func_hashtab, hi);
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001213 return TRUE;
1214 }
1215 return FALSE;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001216}
1217
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02001218 static void
1219func_clear_items(ufunc_T *fp)
1220{
1221 ga_clear_strings(&(fp->uf_args));
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02001222 ga_clear_strings(&(fp->uf_def_args));
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02001223 ga_clear_strings(&(fp->uf_lines));
1224#ifdef FEAT_PROFILE
1225 vim_free(fp->uf_tml_count);
1226 fp->uf_tml_count = NULL;
1227 vim_free(fp->uf_tml_total);
1228 fp->uf_tml_total = NULL;
1229 vim_free(fp->uf_tml_self);
1230 fp->uf_tml_self = NULL;
1231#endif
1232}
1233
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001234/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001235 * Free all things that a function contains. Does not free the function
1236 * itself, use func_free() for that.
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02001237 * When "force" is TRUE we are exiting.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001238 */
1239 static void
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001240func_clear(ufunc_T *fp, int force)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001241{
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001242 if (fp->uf_cleared)
1243 return;
1244 fp->uf_cleared = TRUE;
1245
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001246 /* clear this function */
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02001247 func_clear_items(fp);
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001248 funccal_unref(fp->uf_scoped, fp, force);
1249}
1250
1251/*
1252 * Free a function and remove it from the list of functions. Does not free
1253 * what a function contains, call func_clear() first.
1254 */
1255 static void
1256func_free(ufunc_T *fp)
1257{
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02001258 /* only remove it when not done already, otherwise we would remove a newer
1259 * version of the function */
1260 if ((fp->uf_flags & (FC_DELETED | FC_REMOVED)) == 0)
1261 func_remove(fp);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001262
1263 vim_free(fp);
1264}
1265
Bram Moolenaarc2574872016-08-11 22:51:05 +02001266/*
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001267 * Free all things that a function contains and free the function itself.
1268 * When "force" is TRUE we are exiting.
1269 */
1270 static void
1271func_clear_free(ufunc_T *fp, int force)
1272{
1273 func_clear(fp, force);
1274 func_free(fp);
1275}
1276
1277/*
Bram Moolenaarc2574872016-08-11 22:51:05 +02001278 * There are two kinds of function names:
1279 * 1. ordinary names, function defined with :function
1280 * 2. numbered functions and lambdas
1281 * For the first we only count the name stored in func_hashtab as a reference,
1282 * using function() does not count as a reference, because the function is
1283 * looked up by name.
1284 */
1285 static int
1286func_name_refcount(char_u *name)
1287{
1288 return isdigit(*name) || *name == '<';
1289}
1290
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001291static funccal_entry_T *funccal_stack = NULL;
1292
1293/*
1294 * Save the current function call pointer, and set it to NULL.
1295 * Used when executing autocommands and for ":source".
1296 */
1297 void
1298save_funccal(funccal_entry_T *entry)
1299{
1300 entry->top_funccal = current_funccal;
1301 entry->next = funccal_stack;
1302 funccal_stack = entry;
1303 current_funccal = NULL;
1304}
1305
1306 void
1307restore_funccal(void)
1308{
1309 if (funccal_stack == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001310 iemsg("INTERNAL: restore_funccal()");
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001311 else
1312 {
1313 current_funccal = funccal_stack->top_funccal;
1314 funccal_stack = funccal_stack->next;
1315 }
1316}
1317
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001318#if defined(EXITFREE) || defined(PROTO)
1319 void
1320free_all_functions(void)
1321{
1322 hashitem_T *hi;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001323 ufunc_T *fp;
1324 long_u skipped = 0;
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001325 long_u todo = 1;
1326 long_u used;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001327
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001328 /* Clean up the current_funccal chain and the funccal stack. */
Bram Moolenaar6914c642017-04-01 21:21:30 +02001329 while (current_funccal != NULL)
1330 {
1331 clear_tv(current_funccal->rettv);
1332 cleanup_function_call(current_funccal);
Bram Moolenaar27e80c82018-10-14 21:41:01 +02001333 if (current_funccal == NULL && funccal_stack != NULL)
1334 restore_funccal();
Bram Moolenaar6914c642017-04-01 21:21:30 +02001335 }
1336
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001337 /* First clear what the functions contain. Since this may lower the
1338 * reference count of a function, it may also free a function and change
1339 * the hash table. Restart if that happens. */
1340 while (todo > 0)
1341 {
1342 todo = func_hashtab.ht_used;
1343 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
1344 if (!HASHITEM_EMPTY(hi))
1345 {
1346 /* Only free functions that are not refcounted, those are
1347 * supposed to be freed when no longer referenced. */
1348 fp = HI2UF(hi);
1349 if (func_name_refcount(fp->uf_name))
1350 ++skipped;
1351 else
1352 {
1353 used = func_hashtab.ht_used;
1354 func_clear(fp, TRUE);
1355 if (used != func_hashtab.ht_used)
1356 {
1357 skipped = 0;
1358 break;
1359 }
1360 }
1361 --todo;
1362 }
1363 }
1364
1365 /* Now actually free the functions. Need to start all over every time,
1366 * because func_free() may change the hash table. */
1367 skipped = 0;
Bram Moolenaarc2574872016-08-11 22:51:05 +02001368 while (func_hashtab.ht_used > skipped)
1369 {
1370 todo = func_hashtab.ht_used;
1371 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001372 if (!HASHITEM_EMPTY(hi))
1373 {
Bram Moolenaarc2574872016-08-11 22:51:05 +02001374 --todo;
1375 /* Only free functions that are not refcounted, those are
1376 * supposed to be freed when no longer referenced. */
1377 fp = HI2UF(hi);
1378 if (func_name_refcount(fp->uf_name))
1379 ++skipped;
1380 else
1381 {
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001382 func_free(fp);
Bram Moolenaarc2574872016-08-11 22:51:05 +02001383 skipped = 0;
1384 break;
1385 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001386 }
Bram Moolenaarc2574872016-08-11 22:51:05 +02001387 }
1388 if (skipped == 0)
1389 hash_clear(&func_hashtab);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001390}
1391#endif
1392
1393/*
1394 * Return TRUE if "name" looks like a builtin function name: starts with a
1395 * lower case letter and doesn't contain AUTOLOAD_CHAR.
1396 * "len" is the length of "name", or -1 for NUL terminated.
1397 */
1398 static int
1399builtin_function(char_u *name, int len)
1400{
1401 char_u *p;
1402
1403 if (!ASCII_ISLOWER(name[0]))
1404 return FALSE;
1405 p = vim_strchr(name, AUTOLOAD_CHAR);
1406 return p == NULL || (len > 0 && p > name + len);
1407}
1408
1409 int
1410func_call(
1411 char_u *name,
1412 typval_T *args,
1413 partial_T *partial,
1414 dict_T *selfdict,
1415 typval_T *rettv)
1416{
1417 listitem_T *item;
1418 typval_T argv[MAX_FUNC_ARGS + 1];
1419 int argc = 0;
1420 int dummy;
1421 int r = 0;
1422
1423 for (item = args->vval.v_list->lv_first; item != NULL;
1424 item = item->li_next)
1425 {
1426 if (argc == MAX_FUNC_ARGS - (partial == NULL ? 0 : partial->pt_argc))
1427 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001428 emsg(_("E699: Too many arguments"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001429 break;
1430 }
1431 /* Make a copy of each argument. This is needed to be able to set
1432 * v_lock to VAR_FIXED in the copy without changing the original list.
1433 */
1434 copy_tv(&item->li_tv, &argv[argc++]);
1435 }
1436
1437 if (item == NULL)
Bram Moolenaar6ed88192019-05-11 18:37:44 +02001438 r = call_func(name, -1, rettv, argc, argv, NULL,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001439 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1440 &dummy, TRUE, partial, selfdict);
1441
1442 /* Free the arguments. */
1443 while (argc > 0)
1444 clear_tv(&argv[--argc]);
1445
1446 return r;
1447}
1448
1449/*
1450 * Call a function with its resolved parameters
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001451 *
1452 * "argv_func", when not NULL, can be used to fill in arguments only when the
1453 * invoked function uses them. It is called like this:
1454 * new_argcount = argv_func(current_argcount, argv, called_func_argcount)
1455 *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001456 * Return FAIL when the function can't be called, OK otherwise.
1457 * Also returns OK when an error was encountered while executing the function.
1458 */
1459 int
1460call_func(
Bram Moolenaar6ed88192019-05-11 18:37:44 +02001461 char_u *funcname, // name of the function
1462 int len, // length of "name" or -1 to use strlen()
1463 typval_T *rettv, // return value goes here
1464 int argcount_in, // number of "argvars"
1465 typval_T *argvars_in, // vars for arguments, must have "argcount"
1466 // PLUS ONE elements!
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001467 int (* argv_func)(int, typval_T *, int),
Bram Moolenaar6ed88192019-05-11 18:37:44 +02001468 // function to fill in argvars
1469 linenr_T firstline, // first line of range
1470 linenr_T lastline, // last line of range
1471 int *doesrange, // return: function handled range
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001472 int evaluate,
Bram Moolenaar6ed88192019-05-11 18:37:44 +02001473 partial_T *partial, // optional, can be NULL
1474 dict_T *selfdict_in) // Dictionary for "self"
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001475{
1476 int ret = FAIL;
1477 int error = ERROR_NONE;
1478 int i;
1479 ufunc_T *fp;
1480 char_u fname_buf[FLEN_FIXED + 1];
1481 char_u *tofree = NULL;
1482 char_u *fname;
1483 char_u *name;
1484 int argcount = argcount_in;
1485 typval_T *argvars = argvars_in;
1486 dict_T *selfdict = selfdict_in;
1487 typval_T argv[MAX_FUNC_ARGS + 1]; /* used when "partial" is not NULL */
1488 int argv_clear = 0;
1489
Bram Moolenaar6ed88192019-05-11 18:37:44 +02001490 // Make a copy of the name, if it comes from a funcref variable it could
1491 // be changed or deleted in the called function.
1492 name = len > 0 ? vim_strnsave(funcname, len) : vim_strsave(funcname);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001493 if (name == NULL)
1494 return ret;
1495
1496 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
1497
1498 *doesrange = FALSE;
1499
1500 if (partial != NULL)
1501 {
1502 /* When the function has a partial with a dict and there is a dict
1503 * argument, use the dict argument. That is backwards compatible.
1504 * When the dict was bound explicitly use the one from the partial. */
1505 if (partial->pt_dict != NULL
1506 && (selfdict_in == NULL || !partial->pt_auto))
1507 selfdict = partial->pt_dict;
1508 if (error == ERROR_NONE && partial->pt_argc > 0)
1509 {
1510 for (argv_clear = 0; argv_clear < partial->pt_argc; ++argv_clear)
1511 copy_tv(&partial->pt_argv[argv_clear], &argv[argv_clear]);
1512 for (i = 0; i < argcount_in; ++i)
1513 argv[i + argv_clear] = argvars_in[i];
1514 argvars = argv;
1515 argcount = partial->pt_argc + argcount_in;
1516 }
1517 }
1518
1519
Bram Moolenaarb4518562018-05-22 18:31:35 +02001520 /*
1521 * Execute the function if executing and no errors were detected.
1522 */
1523 if (!evaluate)
1524 {
1525 // Not evaluating, which means the return value is unknown. This
1526 // matters for giving error messages.
1527 rettv->v_type = VAR_UNKNOWN;
1528 }
1529 else if (error == ERROR_NONE)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001530 {
1531 char_u *rfname = fname;
1532
1533 /* Ignore "g:" before a function name. */
1534 if (fname[0] == 'g' && fname[1] == ':')
1535 rfname = fname + 2;
1536
1537 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
1538 rettv->vval.v_number = 0;
1539 error = ERROR_UNKNOWN;
1540
1541 if (!builtin_function(rfname, -1))
1542 {
1543 /*
1544 * User defined function.
1545 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001546 if (partial != NULL && partial->pt_func != NULL)
1547 fp = partial->pt_func;
1548 else
1549 fp = find_func(rfname);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001550
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001551 /* Trigger FuncUndefined event, may load the function. */
1552 if (fp == NULL
1553 && apply_autocmds(EVENT_FUNCUNDEFINED,
1554 rfname, rfname, TRUE, NULL)
1555 && !aborting())
1556 {
1557 /* executed an autocommand, search for the function again */
1558 fp = find_func(rfname);
1559 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001560 /* Try loading a package. */
1561 if (fp == NULL && script_autoload(rfname, TRUE) && !aborting())
1562 {
1563 /* loaded a package, search for the function again */
1564 fp = find_func(rfname);
1565 }
1566
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001567 if (fp != NULL && (fp->uf_flags & FC_DELETED))
1568 error = ERROR_DELETED;
1569 else if (fp != NULL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001570 {
Bram Moolenaardf48fb42016-07-22 21:50:18 +02001571 if (argv_func != NULL)
1572 argcount = argv_func(argcount, argvars, fp->uf_args.ga_len);
1573
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001574 if (fp->uf_flags & FC_RANGE)
1575 *doesrange = TRUE;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02001576 if (argcount < fp->uf_args.ga_len - fp->uf_def_args.ga_len)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001577 error = ERROR_TOOFEW;
1578 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
1579 error = ERROR_TOOMANY;
1580 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
1581 error = ERROR_DICT;
1582 else
1583 {
1584 int did_save_redo = FALSE;
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001585 save_redo_T save_redo;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001586
1587 /*
1588 * Call the user function.
1589 * Save and restore search patterns, script variables and
1590 * redo buffer.
1591 */
1592 save_search_patterns();
1593#ifdef FEAT_INS_EXPAND
1594 if (!ins_compl_active())
1595#endif
1596 {
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001597 saveRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001598 did_save_redo = TRUE;
1599 }
1600 ++fp->uf_calls;
1601 call_user_func(fp, argcount, argvars, rettv,
1602 firstline, lastline,
1603 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001604 if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001605 /* Function was unreferenced while being used, free it
1606 * now. */
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01001607 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001608 if (did_save_redo)
Bram Moolenaard4863aa2017-04-07 19:50:12 +02001609 restoreRedobuff(&save_redo);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001610 restore_search_patterns();
1611 error = ERROR_NONE;
1612 }
1613 }
1614 }
1615 else
1616 {
1617 /*
1618 * Find the function name in the table, call its implementation.
1619 */
1620 error = call_internal_func(fname, argcount, argvars, rettv);
1621 }
1622 /*
1623 * The function call (or "FuncUndefined" autocommand sequence) might
1624 * have been aborted by an error, an interrupt, or an explicitly thrown
1625 * exception that has not been caught so far. This situation can be
1626 * tested for by calling aborting(). For an error in an internal
1627 * function or for the "E132" error in call_user_func(), however, the
1628 * throw point at which the "force_abort" flag (temporarily reset by
1629 * emsg()) is normally updated has not been reached yet. We need to
1630 * update that flag first to make aborting() reliable.
1631 */
1632 update_force_abort();
1633 }
1634 if (error == ERROR_NONE)
1635 ret = OK;
1636
1637 /*
1638 * Report an error unless the argument evaluation or function call has been
1639 * cancelled due to an aborting error, an interrupt, or an exception.
1640 */
1641 if (!aborting())
1642 {
1643 switch (error)
1644 {
1645 case ERROR_UNKNOWN:
1646 emsg_funcname(N_("E117: Unknown function: %s"), name);
1647 break;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001648 case ERROR_DELETED:
1649 emsg_funcname(N_("E933: Function was deleted: %s"), name);
1650 break;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001651 case ERROR_TOOMANY:
1652 emsg_funcname((char *)e_toomanyarg, name);
1653 break;
1654 case ERROR_TOOFEW:
1655 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
1656 name);
1657 break;
1658 case ERROR_SCRIPT:
1659 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
1660 name);
1661 break;
1662 case ERROR_DICT:
1663 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
1664 name);
1665 break;
1666 }
1667 }
1668
1669 while (argv_clear > 0)
1670 clear_tv(&argv[--argv_clear]);
1671 vim_free(tofree);
1672 vim_free(name);
1673
1674 return ret;
1675}
1676
1677/*
1678 * List the head of the function: "name(arg1, arg2)".
1679 */
1680 static void
1681list_func_head(ufunc_T *fp, int indent)
1682{
1683 int j;
1684
1685 msg_start();
1686 if (indent)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001687 msg_puts(" ");
1688 msg_puts("function ");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001689 if (fp->uf_name[0] == K_SPECIAL)
1690 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01001691 msg_puts_attr("<SNR>", HL_ATTR(HLF_8));
1692 msg_puts((char *)fp->uf_name + 3);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001693 }
1694 else
Bram Moolenaar32526b32019-01-19 17:43:09 +01001695 msg_puts((char *)fp->uf_name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001696 msg_putchar('(');
1697 for (j = 0; j < fp->uf_args.ga_len; ++j)
1698 {
1699 if (j)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001700 msg_puts(", ");
1701 msg_puts((char *)FUNCARG(fp, j));
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02001702 if (j >= fp->uf_args.ga_len - fp->uf_def_args.ga_len)
1703 {
1704 msg_puts(" = ");
1705 msg_puts(((char **)(fp->uf_def_args.ga_data))
1706 [j - fp->uf_args.ga_len + fp->uf_def_args.ga_len]);
1707 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001708 }
1709 if (fp->uf_varargs)
1710 {
1711 if (j)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001712 msg_puts(", ");
1713 msg_puts("...");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001714 }
1715 msg_putchar(')');
1716 if (fp->uf_flags & FC_ABORT)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001717 msg_puts(" abort");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001718 if (fp->uf_flags & FC_RANGE)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001719 msg_puts(" range");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001720 if (fp->uf_flags & FC_DICT)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001721 msg_puts(" dict");
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02001722 if (fp->uf_flags & FC_CLOSURE)
Bram Moolenaar32526b32019-01-19 17:43:09 +01001723 msg_puts(" closure");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001724 msg_clr_eos();
1725 if (p_verbose > 0)
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001726 last_set_msg(fp->uf_script_ctx);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001727}
1728
1729/*
1730 * Get a function name, translating "<SID>" and "<SNR>".
1731 * Also handles a Funcref in a List or Dictionary.
1732 * Returns the function name in allocated memory, or NULL for failure.
1733 * flags:
1734 * TFN_INT: internal function name OK
1735 * TFN_QUIET: be quiet
1736 * TFN_NO_AUTOLOAD: do not use script autoloading
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001737 * TFN_NO_DEREF: do not dereference a Funcref
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001738 * Advances "pp" to just after the function name (if no error).
1739 */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001740 char_u *
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001741trans_function_name(
1742 char_u **pp,
1743 int skip, /* only find the end, don't evaluate */
1744 int flags,
1745 funcdict_T *fdp, /* return: info about dictionary used */
1746 partial_T **partial) /* return: partial of a FuncRef */
1747{
1748 char_u *name = NULL;
1749 char_u *start;
1750 char_u *end;
1751 int lead;
1752 char_u sid_buf[20];
1753 int len;
1754 lval_T lv;
1755
1756 if (fdp != NULL)
1757 vim_memset(fdp, 0, sizeof(funcdict_T));
1758 start = *pp;
1759
1760 /* Check for hard coded <SNR>: already translated function ID (from a user
1761 * command). */
1762 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
1763 && (*pp)[2] == (int)KE_SNR)
1764 {
1765 *pp += 3;
1766 len = get_id_len(pp) + 3;
1767 return vim_strnsave(start, len);
1768 }
1769
1770 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
1771 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
1772 lead = eval_fname_script(start);
1773 if (lead > 2)
1774 start += lead;
1775
1776 /* Note that TFN_ flags use the same values as GLV_ flags. */
Bram Moolenaar6e65d592017-12-07 22:11:27 +01001777 end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001778 lead > 2 ? 0 : FNE_CHECK_START);
1779 if (end == start)
1780 {
1781 if (!skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001782 emsg(_("E129: Function name required"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001783 goto theend;
1784 }
1785 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
1786 {
1787 /*
1788 * Report an invalid expression in braces, unless the expression
1789 * evaluation has been cancelled due to an aborting error, an
1790 * interrupt, or an exception.
1791 */
1792 if (!aborting())
1793 {
1794 if (end != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001795 semsg(_(e_invarg2), start);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001796 }
1797 else
1798 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
1799 goto theend;
1800 }
1801
1802 if (lv.ll_tv != NULL)
1803 {
1804 if (fdp != NULL)
1805 {
1806 fdp->fd_dict = lv.ll_dict;
1807 fdp->fd_newkey = lv.ll_newkey;
1808 lv.ll_newkey = NULL;
1809 fdp->fd_di = lv.ll_di;
1810 }
1811 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
1812 {
1813 name = vim_strsave(lv.ll_tv->vval.v_string);
1814 *pp = end;
1815 }
1816 else if (lv.ll_tv->v_type == VAR_PARTIAL
1817 && lv.ll_tv->vval.v_partial != NULL)
1818 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001819 name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001820 *pp = end;
1821 if (partial != NULL)
1822 *partial = lv.ll_tv->vval.v_partial;
1823 }
1824 else
1825 {
1826 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
1827 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001828 emsg(_(e_funcref));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001829 else
1830 *pp = end;
1831 name = NULL;
1832 }
1833 goto theend;
1834 }
1835
1836 if (lv.ll_name == NULL)
1837 {
1838 /* Error found, but continue after the function name. */
1839 *pp = end;
1840 goto theend;
1841 }
1842
1843 /* Check if the name is a Funcref. If so, use the value. */
1844 if (lv.ll_exp_name != NULL)
1845 {
1846 len = (int)STRLEN(lv.ll_exp_name);
1847 name = deref_func_name(lv.ll_exp_name, &len, partial,
1848 flags & TFN_NO_AUTOLOAD);
1849 if (name == lv.ll_exp_name)
1850 name = NULL;
1851 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001852 else if (!(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001853 {
1854 len = (int)(end - *pp);
1855 name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD);
1856 if (name == *pp)
1857 name = NULL;
1858 }
1859 if (name != NULL)
1860 {
1861 name = vim_strsave(name);
1862 *pp = end;
1863 if (STRNCMP(name, "<SNR>", 5) == 0)
1864 {
1865 /* Change "<SNR>" to the byte sequence. */
1866 name[0] = K_SPECIAL;
1867 name[1] = KS_EXTRA;
1868 name[2] = (int)KE_SNR;
1869 mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1);
1870 }
1871 goto theend;
1872 }
1873
1874 if (lv.ll_exp_name != NULL)
1875 {
1876 len = (int)STRLEN(lv.ll_exp_name);
1877 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
1878 && STRNCMP(lv.ll_name, "s:", 2) == 0)
1879 {
1880 /* When there was "s:" already or the name expanded to get a
1881 * leading "s:" then remove it. */
1882 lv.ll_name += 2;
1883 len -= 2;
1884 lead = 2;
1885 }
1886 }
1887 else
1888 {
1889 /* skip over "s:" and "g:" */
1890 if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':'))
1891 lv.ll_name += 2;
1892 len = (int)(end - lv.ll_name);
1893 }
1894
1895 /*
1896 * Copy the function name to allocated memory.
1897 * Accept <SID>name() inside a script, translate into <SNR>123_name().
1898 * Accept <SNR>123_name() outside a script.
1899 */
1900 if (skip)
1901 lead = 0; /* do nothing */
1902 else if (lead > 0)
1903 {
1904 lead = 3;
1905 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
1906 || eval_fname_sid(*pp))
1907 {
1908 /* It's "s:" or "<SID>" */
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001909 if (current_sctx.sc_sid <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001910 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001911 emsg(_(e_usingsid));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001912 goto theend;
1913 }
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02001914 sprintf((char *)sid_buf, "%ld_", (long)current_sctx.sc_sid);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001915 lead += (int)STRLEN(sid_buf);
1916 }
1917 }
1918 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len))
1919 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001920 semsg(_("E128: Function name must start with a capital or \"s:\": %s"),
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001921 start);
1922 goto theend;
1923 }
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02001924 if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001925 {
1926 char_u *cp = vim_strchr(lv.ll_name, ':');
1927
1928 if (cp != NULL && cp < end)
1929 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001930 semsg(_("E884: Function name cannot contain a colon: %s"), start);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001931 goto theend;
1932 }
1933 }
1934
1935 name = alloc((unsigned)(len + lead + 1));
1936 if (name != NULL)
1937 {
1938 if (lead > 0)
1939 {
1940 name[0] = K_SPECIAL;
1941 name[1] = KS_EXTRA;
1942 name[2] = (int)KE_SNR;
1943 if (lead > 3) /* If it's "<SID>" */
1944 STRCPY(name + 3, sid_buf);
1945 }
1946 mch_memmove(name + lead, lv.ll_name, (size_t)len);
1947 name[lead + len] = NUL;
1948 }
1949 *pp = end;
1950
1951theend:
1952 clear_lval(&lv);
1953 return name;
1954}
1955
1956/*
1957 * ":function"
1958 */
1959 void
1960ex_function(exarg_T *eap)
1961{
1962 char_u *theline;
Bram Moolenaar53564f72017-06-24 14:48:11 +02001963 char_u *line_to_free = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001964 int j;
1965 int c;
1966 int saved_did_emsg;
1967 int saved_wait_return = need_wait_return;
1968 char_u *name = NULL;
1969 char_u *p;
1970 char_u *arg;
1971 char_u *line_arg = NULL;
1972 garray_T newargs;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02001973 garray_T default_args;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001974 garray_T newlines;
1975 int varargs = FALSE;
1976 int flags = 0;
1977 ufunc_T *fp;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02001978 int overwrite = FALSE;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001979 int indent;
1980 int nesting;
1981 char_u *skip_until = NULL;
Bram Moolenaar8471e572019-05-19 21:37:18 +02001982 char_u *trimmed = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02001983 dictitem_T *v;
1984 funcdict_T fudi;
1985 static int func_nr = 0; /* number for nameless function */
1986 int paren;
1987 hashtab_T *ht;
1988 int todo;
1989 hashitem_T *hi;
1990 int sourcing_lnum_off;
1991
1992 /*
1993 * ":function" without argument: list functions.
1994 */
1995 if (ends_excmd(*eap->arg))
1996 {
1997 if (!eap->skip)
1998 {
1999 todo = (int)func_hashtab.ht_used;
2000 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
2001 {
2002 if (!HASHITEM_EMPTY(hi))
2003 {
2004 --todo;
2005 fp = HI2UF(hi);
Bram Moolenaarf86db782018-10-25 13:31:37 +02002006 if (message_filtered(fp->uf_name))
2007 continue;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02002008 if (!func_name_refcount(fp->uf_name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002009 list_func_head(fp, FALSE);
2010 }
2011 }
2012 }
2013 eap->nextcmd = check_nextcmd(eap->arg);
2014 return;
2015 }
2016
2017 /*
2018 * ":function /pat": list functions matching pattern.
2019 */
2020 if (*eap->arg == '/')
2021 {
2022 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
2023 if (!eap->skip)
2024 {
2025 regmatch_T regmatch;
2026
2027 c = *p;
2028 *p = NUL;
2029 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
2030 *p = c;
2031 if (regmatch.regprog != NULL)
2032 {
2033 regmatch.rm_ic = p_ic;
2034
2035 todo = (int)func_hashtab.ht_used;
2036 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
2037 {
2038 if (!HASHITEM_EMPTY(hi))
2039 {
2040 --todo;
2041 fp = HI2UF(hi);
2042 if (!isdigit(*fp->uf_name)
2043 && vim_regexec(&regmatch, fp->uf_name, 0))
2044 list_func_head(fp, FALSE);
2045 }
2046 }
2047 vim_regfree(regmatch.regprog);
2048 }
2049 }
2050 if (*p == '/')
2051 ++p;
2052 eap->nextcmd = check_nextcmd(p);
2053 return;
2054 }
2055
2056 /*
2057 * Get the function name. There are these situations:
2058 * func normal function name
2059 * "name" == func, "fudi.fd_dict" == NULL
2060 * dict.func new dictionary entry
2061 * "name" == NULL, "fudi.fd_dict" set,
2062 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
2063 * dict.func existing dict entry with a Funcref
2064 * "name" == func, "fudi.fd_dict" set,
2065 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
2066 * dict.func existing dict entry that's not a Funcref
2067 * "name" == NULL, "fudi.fd_dict" set,
2068 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
2069 * s:func script-local function name
2070 * g:func global function name, same as "func"
2071 */
2072 p = eap->arg;
Bram Moolenaar3388d332017-12-07 22:23:04 +01002073 name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002074 paren = (vim_strchr(p, '(') != NULL);
2075 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
2076 {
2077 /*
2078 * Return on an invalid expression in braces, unless the expression
2079 * evaluation has been cancelled due to an aborting error, an
2080 * interrupt, or an exception.
2081 */
2082 if (!aborting())
2083 {
2084 if (!eap->skip && fudi.fd_newkey != NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002085 semsg(_(e_dictkey), fudi.fd_newkey);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002086 vim_free(fudi.fd_newkey);
2087 return;
2088 }
2089 else
2090 eap->skip = TRUE;
2091 }
2092
2093 /* An error in a function call during evaluation of an expression in magic
2094 * braces should not cause the function not to be defined. */
2095 saved_did_emsg = did_emsg;
2096 did_emsg = FALSE;
2097
2098 /*
2099 * ":function func" with only function name: list function.
2100 */
2101 if (!paren)
2102 {
2103 if (!ends_excmd(*skipwhite(p)))
2104 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002105 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002106 goto ret_free;
2107 }
2108 eap->nextcmd = check_nextcmd(p);
2109 if (eap->nextcmd != NULL)
2110 *p = NUL;
2111 if (!eap->skip && !got_int)
2112 {
2113 fp = find_func(name);
2114 if (fp != NULL)
2115 {
2116 list_func_head(fp, TRUE);
2117 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
2118 {
2119 if (FUNCLINE(fp, j) == NULL)
2120 continue;
2121 msg_putchar('\n');
2122 msg_outnum((long)(j + 1));
2123 if (j < 9)
2124 msg_putchar(' ');
2125 if (j < 99)
2126 msg_putchar(' ');
2127 msg_prt_line(FUNCLINE(fp, j), FALSE);
2128 out_flush(); /* show a line at a time */
2129 ui_breakcheck();
2130 }
2131 if (!got_int)
2132 {
2133 msg_putchar('\n');
Bram Moolenaar32526b32019-01-19 17:43:09 +01002134 msg_puts(" endfunction");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002135 }
2136 }
2137 else
2138 emsg_funcname(N_("E123: Undefined function: %s"), name);
2139 }
2140 goto ret_free;
2141 }
2142
2143 /*
2144 * ":function name(arg1, arg2)" Define function.
2145 */
2146 p = skipwhite(p);
2147 if (*p != '(')
2148 {
2149 if (!eap->skip)
2150 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002151 semsg(_("E124: Missing '(': %s"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002152 goto ret_free;
2153 }
2154 /* attempt to continue by skipping some text */
2155 if (vim_strchr(p, '(') != NULL)
2156 p = vim_strchr(p, '(');
2157 }
2158 p = skipwhite(p + 1);
2159
2160 ga_init2(&newlines, (int)sizeof(char_u *), 3);
2161
2162 if (!eap->skip)
2163 {
2164 /* Check the name of the function. Unless it's a dictionary function
2165 * (that we are overwriting). */
2166 if (name != NULL)
2167 arg = name;
2168 else
2169 arg = fudi.fd_newkey;
2170 if (arg != NULL && (fudi.fd_di == NULL
2171 || (fudi.fd_di->di_tv.v_type != VAR_FUNC
2172 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL)))
2173 {
2174 if (*arg == K_SPECIAL)
2175 j = 3;
2176 else
2177 j = 0;
2178 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
2179 : eval_isnamec(arg[j])))
2180 ++j;
2181 if (arg[j] != NUL)
2182 emsg_funcname((char *)e_invarg2, arg);
2183 }
2184 /* Disallow using the g: dict. */
2185 if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002186 emsg(_("E862: Cannot use g: here"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002187 }
2188
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002189 if (get_function_args(&p, ')', &newargs, &varargs,
2190 &default_args, eap->skip) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002191 goto errret_2;
2192
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002193 /* find extra arguments "range", "dict", "abort" and "closure" */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002194 for (;;)
2195 {
2196 p = skipwhite(p);
2197 if (STRNCMP(p, "range", 5) == 0)
2198 {
2199 flags |= FC_RANGE;
2200 p += 5;
2201 }
2202 else if (STRNCMP(p, "dict", 4) == 0)
2203 {
2204 flags |= FC_DICT;
2205 p += 4;
2206 }
2207 else if (STRNCMP(p, "abort", 5) == 0)
2208 {
2209 flags |= FC_ABORT;
2210 p += 5;
2211 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002212 else if (STRNCMP(p, "closure", 7) == 0)
2213 {
2214 flags |= FC_CLOSURE;
2215 p += 7;
Bram Moolenaar58016442016-07-31 18:30:22 +02002216 if (current_funccal == NULL)
2217 {
Bram Moolenaarba209902016-08-24 22:06:38 +02002218 emsg_funcname(N_("E932: Closure function should not be at top level: %s"),
Bram Moolenaar58016442016-07-31 18:30:22 +02002219 name == NULL ? (char_u *)"" : name);
2220 goto erret;
2221 }
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002222 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002223 else
2224 break;
2225 }
2226
2227 /* When there is a line break use what follows for the function body.
2228 * Makes 'exe "func Test()\n...\nendfunc"' work. */
2229 if (*p == '\n')
2230 line_arg = p + 1;
2231 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002232 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002233
2234 /*
2235 * Read the body of the function, until ":endfunction" is found.
2236 */
2237 if (KeyTyped)
2238 {
2239 /* Check if the function already exists, don't let the user type the
2240 * whole function before telling him it doesn't work! For a script we
2241 * need to skip the body to be able to find what follows. */
2242 if (!eap->skip && !eap->forceit)
2243 {
2244 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002245 emsg(_(e_funcdict));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002246 else if (name != NULL && find_func(name) != NULL)
2247 emsg_funcname(e_funcexts, name);
2248 }
2249
2250 if (!eap->skip && did_emsg)
2251 goto erret;
2252
2253 msg_putchar('\n'); /* don't overwrite the function name */
2254 cmdline_row = msg_row;
2255 }
2256
2257 indent = 2;
2258 nesting = 0;
2259 for (;;)
2260 {
2261 if (KeyTyped)
2262 {
2263 msg_scroll = TRUE;
2264 saved_wait_return = FALSE;
2265 }
2266 need_wait_return = FALSE;
2267 sourcing_lnum_off = sourcing_lnum;
2268
2269 if (line_arg != NULL)
2270 {
2271 /* Use eap->arg, split up in parts by line breaks. */
2272 theline = line_arg;
2273 p = vim_strchr(theline, '\n');
2274 if (p == NULL)
2275 line_arg += STRLEN(line_arg);
2276 else
2277 {
2278 *p = NUL;
2279 line_arg = p + 1;
2280 }
2281 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002282 else
Bram Moolenaar53564f72017-06-24 14:48:11 +02002283 {
2284 vim_free(line_to_free);
2285 if (eap->getline == NULL)
2286 theline = getcmdline(':', 0L, indent);
2287 else
2288 theline = eap->getline(':', eap->cookie, indent);
2289 line_to_free = theline;
2290 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002291 if (KeyTyped)
2292 lines_left = Rows - 1;
2293 if (theline == NULL)
2294 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002295 emsg(_("E126: Missing :endfunction"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002296 goto erret;
2297 }
2298
2299 /* Detect line continuation: sourcing_lnum increased more than one. */
2300 if (sourcing_lnum > sourcing_lnum_off + 1)
2301 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
2302 else
2303 sourcing_lnum_off = 0;
2304
2305 if (skip_until != NULL)
2306 {
Bram Moolenaar8471e572019-05-19 21:37:18 +02002307 // Between ":append" and "." and between ":python <<EOF" and "EOF"
2308 // don't check for ":endfunc".
2309 if (trimmed == NULL
2310 || STRNCMP(theline, trimmed, STRLEN(trimmed)) == 0)
2311 {
2312 p = trimmed == NULL ? theline : theline + STRLEN(trimmed);
2313 if (STRCMP(p, skip_until) == 0)
2314 {
2315 VIM_CLEAR(skip_until);
2316 VIM_CLEAR(trimmed);
2317 }
2318 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002319 }
2320 else
2321 {
2322 /* skip ':' and blanks*/
Bram Moolenaar1c465442017-03-12 20:10:05 +01002323 for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002324 ;
2325
2326 /* Check for "endfunction". */
2327 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
2328 {
Bram Moolenaar53564f72017-06-24 14:48:11 +02002329 char_u *nextcmd = NULL;
2330
Bram Moolenaar663bb232017-06-22 19:12:10 +02002331 if (*p == '|')
Bram Moolenaar53564f72017-06-24 14:48:11 +02002332 nextcmd = p + 1;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002333 else if (line_arg != NULL && *skipwhite(line_arg) != NUL)
Bram Moolenaar53564f72017-06-24 14:48:11 +02002334 nextcmd = line_arg;
Bram Moolenaar663bb232017-06-22 19:12:10 +02002335 else if (*p != NUL && *p != '"' && p_verbose > 0)
Bram Moolenaarf8be4612017-06-23 20:52:40 +02002336 give_warning2(
2337 (char_u *)_("W22: Text found after :endfunction: %s"),
2338 p, TRUE);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002339 if (nextcmd != NULL)
2340 {
2341 /* Another command follows. If the line came from "eap" we
2342 * can simply point into it, otherwise we need to change
2343 * "eap->cmdlinep". */
2344 eap->nextcmd = nextcmd;
2345 if (line_to_free != NULL)
2346 {
2347 vim_free(*eap->cmdlinep);
2348 *eap->cmdlinep = line_to_free;
2349 line_to_free = NULL;
2350 }
2351 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002352 break;
2353 }
2354
2355 /* Increase indent inside "if", "while", "for" and "try", decrease
2356 * at "end". */
2357 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
2358 indent -= 2;
2359 else if (STRNCMP(p, "if", 2) == 0
2360 || STRNCMP(p, "wh", 2) == 0
2361 || STRNCMP(p, "for", 3) == 0
2362 || STRNCMP(p, "try", 3) == 0)
2363 indent += 2;
2364
2365 /* Check for defining a function inside this function. */
2366 if (checkforcmd(&p, "function", 2))
2367 {
2368 if (*p == '!')
2369 p = skipwhite(p + 1);
2370 p += eval_fname_script(p);
2371 vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL));
2372 if (*skipwhite(p) == '(')
2373 {
2374 ++nesting;
2375 indent += 2;
2376 }
2377 }
2378
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002379 /* Check for ":append", ":change", ":insert". */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002380 p = skip_range(p, NULL);
2381 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
Bram Moolenaar70bcd732017-01-12 22:20:54 +01002382 || (p[0] == 'c'
2383 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h'
2384 && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a'
2385 && (STRNCMP(&p[3], "nge", 3) != 0
2386 || !ASCII_ISALPHA(p[6])))))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002387 || (p[0] == 'i'
2388 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
2389 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
2390 skip_until = vim_strsave((char_u *)".");
2391
2392 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
2393 arg = skipwhite(skiptowhite(p));
2394 if (arg[0] == '<' && arg[1] =='<'
2395 && ((p[0] == 'p' && p[1] == 'y'
Bram Moolenaarf42dd3c2017-01-28 16:06:38 +01002396 && (!ASCII_ISALNUM(p[2]) || p[2] == 't'
2397 || ((p[2] == '3' || p[2] == 'x')
2398 && !ASCII_ISALPHA(p[3]))))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002399 || (p[0] == 'p' && p[1] == 'e'
2400 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
2401 || (p[0] == 't' && p[1] == 'c'
2402 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
2403 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a'
2404 && !ASCII_ISALPHA(p[3]))
2405 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
2406 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
2407 || (p[0] == 'm' && p[1] == 'z'
2408 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
2409 ))
2410 {
2411 /* ":python <<" continues until a dot, like ":append" */
2412 p = skipwhite(arg + 2);
2413 if (*p == NUL)
2414 skip_until = vim_strsave((char_u *)".");
2415 else
2416 skip_until = vim_strsave(p);
2417 }
Bram Moolenaar8471e572019-05-19 21:37:18 +02002418
2419 // Check for ":let v =<< [trim] EOF"
2420 arg = skipwhite(skiptowhite(p));
2421 arg = skipwhite(skiptowhite(arg));
2422 if (arg[0] == '=' && arg[1] == '<' && arg[2] =='<'
2423 && ((p[0] == 'l'
2424 && p[1] == 'e'
2425 && (!ASCII_ISALNUM(p[2])
2426 || (p[2] == 't' && !ASCII_ISALNUM(p[3]))))))
2427 {
2428 // ":let v =<<" continues until a dot
2429 p = skipwhite(arg + 3);
2430 if (STRNCMP(p, "trim", 4) == 0)
2431 {
2432 // Ignore leading white space.
2433 p = skipwhite(p + 4);
2434 trimmed = vim_strnsave(theline,
2435 (int)(skipwhite(theline) - theline));
2436 }
2437 if (*p == NUL)
2438 skip_until = vim_strsave((char_u *)".");
2439 else
2440 skip_until = vim_strnsave(p, (int)(skiptowhite(p) - p));
2441 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002442 }
2443
2444 /* Add the line to the function. */
2445 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002446 goto erret;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002447
2448 /* Copy the line to newly allocated memory. get_one_sourceline()
2449 * allocates 250 bytes per line, this saves 80% on average. The cost
2450 * is an extra alloc/free. */
2451 p = vim_strsave(theline);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002452 if (p == NULL)
2453 goto erret;
2454 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002455
2456 /* Add NULL lines for continuation lines, so that the line count is
2457 * equal to the index in the growarray. */
2458 while (sourcing_lnum_off-- > 0)
2459 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
2460
2461 /* Check for end of eap->arg. */
2462 if (line_arg != NULL && *line_arg == NUL)
2463 line_arg = NULL;
2464 }
2465
2466 /* Don't define the function when skipping commands or when an error was
2467 * detected. */
2468 if (eap->skip || did_emsg)
2469 goto erret;
2470
2471 /*
2472 * If there are no errors, add the function
2473 */
2474 if (fudi.fd_dict == NULL)
2475 {
2476 v = find_var(name, &ht, FALSE);
2477 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
2478 {
2479 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
2480 name);
2481 goto erret;
2482 }
2483
2484 fp = find_func(name);
2485 if (fp != NULL)
2486 {
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002487 // Function can be replaced with "function!" and when sourcing the
2488 // same script again, but only once.
2489 if (!eap->forceit
2490 && (fp->uf_script_ctx.sc_sid != current_sctx.sc_sid
2491 || fp->uf_script_ctx.sc_seq == current_sctx.sc_seq))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002492 {
2493 emsg_funcname(e_funcexts, name);
2494 goto erret;
2495 }
2496 if (fp->uf_calls > 0)
2497 {
Bram Moolenaarded5f1b2018-11-10 17:33:29 +01002498 emsg_funcname(
2499 N_("E127: Cannot redefine function %s: It is in use"),
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002500 name);
2501 goto erret;
2502 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002503 if (fp->uf_refcount > 1)
2504 {
2505 /* This function is referenced somewhere, don't redefine it but
2506 * create a new one. */
2507 --fp->uf_refcount;
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02002508 fp->uf_flags |= FC_REMOVED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002509 fp = NULL;
2510 overwrite = TRUE;
2511 }
2512 else
2513 {
2514 /* redefine existing function */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002515 VIM_CLEAR(name);
Bram Moolenaar79c2ad52018-07-29 17:40:43 +02002516 func_clear_items(fp);
2517#ifdef FEAT_PROFILE
2518 fp->uf_profiling = FALSE;
2519 fp->uf_prof_initialized = FALSE;
2520#endif
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002521 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002522 }
2523 }
2524 else
2525 {
2526 char numbuf[20];
2527
2528 fp = NULL;
2529 if (fudi.fd_newkey == NULL && !eap->forceit)
2530 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002531 emsg(_(e_funcdict));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002532 goto erret;
2533 }
2534 if (fudi.fd_di == NULL)
2535 {
2536 /* Can't add a function to a locked dictionary */
Bram Moolenaar05c00c02019-02-11 22:00:11 +01002537 if (var_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002538 goto erret;
2539 }
2540 /* Can't change an existing function if it is locked */
Bram Moolenaar05c00c02019-02-11 22:00:11 +01002541 else if (var_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002542 goto erret;
2543
2544 /* Give the function a sequential number. Can only be used with a
2545 * Funcref! */
2546 vim_free(name);
2547 sprintf(numbuf, "%d", ++func_nr);
2548 name = vim_strsave((char_u *)numbuf);
2549 if (name == NULL)
2550 goto erret;
2551 }
2552
2553 if (fp == NULL)
2554 {
2555 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
2556 {
2557 int slen, plen;
2558 char_u *scriptname;
2559
2560 /* Check that the autoload name matches the script name. */
2561 j = FAIL;
2562 if (sourcing_name != NULL)
2563 {
2564 scriptname = autoload_name(name);
2565 if (scriptname != NULL)
2566 {
2567 p = vim_strchr(scriptname, '/');
2568 plen = (int)STRLEN(p);
2569 slen = (int)STRLEN(sourcing_name);
2570 if (slen > plen && fnamecmp(p,
2571 sourcing_name + slen - plen) == 0)
2572 j = OK;
2573 vim_free(scriptname);
2574 }
2575 }
2576 if (j == FAIL)
2577 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002578 semsg(_("E746: Function name does not match script file name: %s"), name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002579 goto erret;
2580 }
2581 }
2582
Bram Moolenaar58016442016-07-31 18:30:22 +02002583 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002584 if (fp == NULL)
2585 goto erret;
2586
2587 if (fudi.fd_dict != NULL)
2588 {
2589 if (fudi.fd_di == NULL)
2590 {
2591 /* add new dict entry */
2592 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
2593 if (fudi.fd_di == NULL)
2594 {
2595 vim_free(fp);
2596 goto erret;
2597 }
2598 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
2599 {
2600 vim_free(fudi.fd_di);
2601 vim_free(fp);
2602 goto erret;
2603 }
2604 }
2605 else
2606 /* overwrite existing dict entry */
2607 clear_tv(&fudi.fd_di->di_tv);
2608 fudi.fd_di->di_tv.v_type = VAR_FUNC;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002609 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002610
2611 /* behave like "dict" was used */
2612 flags |= FC_DICT;
2613 }
2614
2615 /* insert the new function in the function list */
2616 STRCPY(fp->uf_name, name);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002617 if (overwrite)
2618 {
2619 hi = hash_find(&func_hashtab, name);
2620 hi->hi_key = UF2HIKEY(fp);
2621 }
2622 else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002623 {
2624 vim_free(fp);
2625 goto erret;
2626 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02002627 fp->uf_refcount = 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002628 }
2629 fp->uf_args = newargs;
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002630 fp->uf_def_args = default_args;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002631 fp->uf_lines = newlines;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002632 if ((flags & FC_CLOSURE) != 0)
2633 {
Bram Moolenaar58016442016-07-31 18:30:22 +02002634 if (register_closure(fp) == FAIL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002635 goto erret;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02002636 }
2637 else
2638 fp->uf_scoped = NULL;
2639
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002640#ifdef FEAT_PROFILE
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002641 if (prof_def_func())
2642 func_do_profile(fp);
2643#endif
2644 fp->uf_varargs = varargs;
Bram Moolenaar93343722018-07-10 19:39:18 +02002645 if (sandbox)
2646 flags |= FC_SANDBOX;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002647 fp->uf_flags = flags;
2648 fp->uf_calls = 0;
Bram Moolenaarf29c1c62018-09-10 21:05:02 +02002649 fp->uf_script_ctx = current_sctx;
2650 fp->uf_script_ctx.sc_lnum += sourcing_lnum - newlines.ga_len - 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002651 goto ret_free;
2652
2653erret:
2654 ga_clear_strings(&newargs);
Bram Moolenaar42ae78c2019-05-09 21:08:58 +02002655 ga_clear_strings(&default_args);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002656errret_2:
2657 ga_clear_strings(&newlines);
2658ret_free:
2659 vim_free(skip_until);
Bram Moolenaar53564f72017-06-24 14:48:11 +02002660 vim_free(line_to_free);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002661 vim_free(fudi.fd_newkey);
2662 vim_free(name);
2663 did_emsg |= saved_did_emsg;
2664 need_wait_return |= saved_wait_return;
2665}
2666
2667/*
2668 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
2669 * Return 2 if "p" starts with "s:".
2670 * Return 0 otherwise.
2671 */
2672 int
2673eval_fname_script(char_u *p)
2674{
2675 /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with
2676 * the standard library function. */
2677 if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0
2678 || MB_STRNICMP(p + 1, "SNR>", 4) == 0))
2679 return 5;
2680 if (p[0] == 's' && p[1] == ':')
2681 return 2;
2682 return 0;
2683}
2684
2685 int
2686translated_function_exists(char_u *name)
2687{
2688 if (builtin_function(name, -1))
2689 return find_internal_func(name) >= 0;
2690 return find_func(name) != NULL;
2691}
2692
2693/*
2694 * Return TRUE if a function "name" exists.
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002695 * If "no_defef" is TRUE, do not dereference a Funcref.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002696 */
2697 int
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002698function_exists(char_u *name, int no_deref)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002699{
2700 char_u *nm = name;
2701 char_u *p;
2702 int n = FALSE;
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002703 int flag;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002704
Bram Moolenaarb54c3ff2016-07-31 14:11:58 +02002705 flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD;
2706 if (no_deref)
2707 flag |= TFN_NO_DEREF;
2708 p = trans_function_name(&nm, FALSE, flag, NULL, NULL);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002709 nm = skipwhite(nm);
2710
2711 /* Only accept "funcname", "funcname ", "funcname (..." and
2712 * "funcname(...", not "funcname!...". */
2713 if (p != NULL && (*nm == NUL || *nm == '('))
2714 n = translated_function_exists(p);
2715 vim_free(p);
2716 return n;
2717}
2718
Bram Moolenaar113e1072019-01-20 15:30:40 +01002719#if defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) || defined(PROTO)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002720 char_u *
2721get_expanded_name(char_u *name, int check)
2722{
2723 char_u *nm = name;
2724 char_u *p;
2725
2726 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL);
2727
2728 if (p != NULL && *nm == NUL)
2729 if (!check || translated_function_exists(p))
2730 return p;
2731
2732 vim_free(p);
2733 return NULL;
2734}
Bram Moolenaar113e1072019-01-20 15:30:40 +01002735#endif
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002736
2737#if defined(FEAT_PROFILE) || defined(PROTO)
2738/*
2739 * Start profiling function "fp".
2740 */
2741 static void
2742func_do_profile(ufunc_T *fp)
2743{
2744 int len = fp->uf_lines.ga_len;
2745
Bram Moolenaarad648092018-06-30 18:28:03 +02002746 if (!fp->uf_prof_initialized)
2747 {
2748 if (len == 0)
2749 len = 1; /* avoid getting error for allocating zero bytes */
2750 fp->uf_tm_count = 0;
2751 profile_zero(&fp->uf_tm_self);
2752 profile_zero(&fp->uf_tm_total);
2753 if (fp->uf_tml_count == NULL)
2754 fp->uf_tml_count = (int *)alloc_clear(
2755 (unsigned)(sizeof(int) * len));
2756 if (fp->uf_tml_total == NULL)
2757 fp->uf_tml_total = (proftime_T *)alloc_clear(
2758 (unsigned)(sizeof(proftime_T) * len));
2759 if (fp->uf_tml_self == NULL)
2760 fp->uf_tml_self = (proftime_T *)alloc_clear(
2761 (unsigned)(sizeof(proftime_T) * len));
2762 fp->uf_tml_idx = -1;
2763 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
2764 || fp->uf_tml_self == NULL)
2765 return; /* out of memory */
2766 fp->uf_prof_initialized = TRUE;
2767 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002768
2769 fp->uf_profiling = TRUE;
2770}
2771
2772/*
2773 * Dump the profiling results for all functions in file "fd".
2774 */
2775 void
2776func_dump_profile(FILE *fd)
2777{
2778 hashitem_T *hi;
2779 int todo;
2780 ufunc_T *fp;
2781 int i;
2782 ufunc_T **sorttab;
2783 int st_len = 0;
Bram Moolenaar4c7b08f2018-09-10 22:03:40 +02002784 char_u *p;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002785
2786 todo = (int)func_hashtab.ht_used;
2787 if (todo == 0)
2788 return; /* nothing to dump */
2789
2790 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo));
2791
2792 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
2793 {
2794 if (!HASHITEM_EMPTY(hi))
2795 {
2796 --todo;
2797 fp = HI2UF(hi);
Bram Moolenaarad648092018-06-30 18:28:03 +02002798 if (fp->uf_prof_initialized)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002799 {
2800 if (sorttab != NULL)
2801 sorttab[st_len++] = fp;
2802
2803 if (fp->uf_name[0] == K_SPECIAL)
2804 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
2805 else
2806 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
Bram Moolenaar4c7b08f2018-09-10 22:03:40 +02002807 p = home_replace_save(NULL,
2808 get_scriptname(fp->uf_script_ctx.sc_sid));
2809 if (p != NULL)
2810 {
2811 fprintf(fd, " Defined: %s line %ld\n",
2812 p, (long)fp->uf_script_ctx.sc_lnum);
2813 vim_free(p);
2814 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002815 if (fp->uf_tm_count == 1)
2816 fprintf(fd, "Called 1 time\n");
2817 else
2818 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
2819 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
2820 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
2821 fprintf(fd, "\n");
2822 fprintf(fd, "count total (s) self (s)\n");
2823
2824 for (i = 0; i < fp->uf_lines.ga_len; ++i)
2825 {
2826 if (FUNCLINE(fp, i) == NULL)
2827 continue;
2828 prof_func_line(fd, fp->uf_tml_count[i],
2829 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
2830 fprintf(fd, "%s\n", FUNCLINE(fp, i));
2831 }
2832 fprintf(fd, "\n");
2833 }
2834 }
2835 }
2836
2837 if (sorttab != NULL && st_len > 0)
2838 {
2839 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2840 prof_total_cmp);
2841 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
2842 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
2843 prof_self_cmp);
2844 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
2845 }
2846
2847 vim_free(sorttab);
2848}
2849
2850 static void
2851prof_sort_list(
2852 FILE *fd,
2853 ufunc_T **sorttab,
2854 int st_len,
2855 char *title,
2856 int prefer_self) /* when equal print only self time */
2857{
2858 int i;
2859 ufunc_T *fp;
2860
2861 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
2862 fprintf(fd, "count total (s) self (s) function\n");
2863 for (i = 0; i < 20 && i < st_len; ++i)
2864 {
2865 fp = sorttab[i];
2866 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
2867 prefer_self);
2868 if (fp->uf_name[0] == K_SPECIAL)
2869 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
2870 else
2871 fprintf(fd, " %s()\n", fp->uf_name);
2872 }
2873 fprintf(fd, "\n");
2874}
2875
2876/*
2877 * Print the count and times for one function or function line.
2878 */
2879 static void
2880prof_func_line(
2881 FILE *fd,
2882 int count,
2883 proftime_T *total,
2884 proftime_T *self,
2885 int prefer_self) /* when equal print only self time */
2886{
2887 if (count > 0)
2888 {
2889 fprintf(fd, "%5d ", count);
2890 if (prefer_self && profile_equal(total, self))
2891 fprintf(fd, " ");
2892 else
2893 fprintf(fd, "%s ", profile_msg(total));
2894 if (!prefer_self && profile_equal(total, self))
2895 fprintf(fd, " ");
2896 else
2897 fprintf(fd, "%s ", profile_msg(self));
2898 }
2899 else
2900 fprintf(fd, " ");
2901}
2902
2903/*
2904 * Compare function for total time sorting.
2905 */
2906 static int
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002907prof_total_cmp(const void *s1, const void *s2)
2908{
2909 ufunc_T *p1, *p2;
2910
2911 p1 = *(ufunc_T **)s1;
2912 p2 = *(ufunc_T **)s2;
2913 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
2914}
2915
2916/*
2917 * Compare function for self time sorting.
2918 */
2919 static int
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002920prof_self_cmp(const void *s1, const void *s2)
2921{
2922 ufunc_T *p1, *p2;
2923
2924 p1 = *(ufunc_T **)s1;
2925 p2 = *(ufunc_T **)s2;
2926 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
2927}
2928
2929/*
2930 * Prepare profiling for entering a child or something else that is not
2931 * counted for the script/function itself.
2932 * Should always be called in pair with prof_child_exit().
2933 */
2934 void
2935prof_child_enter(
2936 proftime_T *tm) /* place to store waittime */
2937{
2938 funccall_T *fc = current_funccal;
2939
2940 if (fc != NULL && fc->func->uf_profiling)
2941 profile_start(&fc->prof_child);
2942 script_prof_save(tm);
2943}
2944
2945/*
2946 * Take care of time spent in a child.
2947 * Should always be called after prof_child_enter().
2948 */
2949 void
2950prof_child_exit(
2951 proftime_T *tm) /* where waittime was stored */
2952{
2953 funccall_T *fc = current_funccal;
2954
2955 if (fc != NULL && fc->func->uf_profiling)
2956 {
2957 profile_end(&fc->prof_child);
2958 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
2959 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
2960 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
2961 }
2962 script_prof_restore(tm);
2963}
2964
2965#endif /* FEAT_PROFILE */
2966
2967#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2968
2969/*
2970 * Function given to ExpandGeneric() to obtain the list of user defined
2971 * function names.
2972 */
2973 char_u *
2974get_user_func_name(expand_T *xp, int idx)
2975{
2976 static long_u done;
2977 static hashitem_T *hi;
2978 ufunc_T *fp;
2979
2980 if (idx == 0)
2981 {
2982 done = 0;
2983 hi = func_hashtab.ht_array;
2984 }
2985 if (done < func_hashtab.ht_used)
2986 {
2987 if (done++ > 0)
2988 ++hi;
2989 while (HASHITEM_EMPTY(hi))
2990 ++hi;
2991 fp = HI2UF(hi);
2992
Bram Moolenaarb49edc12016-07-23 15:47:34 +02002993 if ((fp->uf_flags & FC_DICT)
2994 || STRNCMP(fp->uf_name, "<lambda>", 8) == 0)
2995 return (char_u *)""; /* don't show dict and lambda functions */
Bram Moolenaara9b579f2016-07-17 18:29:19 +02002996
2997 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
2998 return fp->uf_name; /* prevents overflow */
2999
3000 cat_func_name(IObuff, fp);
3001 if (xp->xp_context != EXPAND_USER_FUNC)
3002 {
3003 STRCAT(IObuff, "(");
3004 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
3005 STRCAT(IObuff, ")");
3006 }
3007 return IObuff;
3008 }
3009 return NULL;
3010}
3011
3012#endif /* FEAT_CMDL_COMPL */
3013
3014/*
3015 * ":delfunction {name}"
3016 */
3017 void
3018ex_delfunction(exarg_T *eap)
3019{
3020 ufunc_T *fp = NULL;
3021 char_u *p;
3022 char_u *name;
3023 funcdict_T fudi;
3024
3025 p = eap->arg;
3026 name = trans_function_name(&p, eap->skip, 0, &fudi, NULL);
3027 vim_free(fudi.fd_newkey);
3028 if (name == NULL)
3029 {
3030 if (fudi.fd_dict != NULL && !eap->skip)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003031 emsg(_(e_funcref));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003032 return;
3033 }
3034 if (!ends_excmd(*skipwhite(p)))
3035 {
3036 vim_free(name);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003037 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003038 return;
3039 }
3040 eap->nextcmd = check_nextcmd(p);
3041 if (eap->nextcmd != NULL)
3042 *p = NUL;
3043
3044 if (!eap->skip)
3045 fp = find_func(name);
3046 vim_free(name);
3047
3048 if (!eap->skip)
3049 {
3050 if (fp == NULL)
3051 {
Bram Moolenaard6abcd12017-06-22 19:15:24 +02003052 if (!eap->forceit)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003053 semsg(_(e_nofunc), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003054 return;
3055 }
3056 if (fp->uf_calls > 0)
3057 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003058 semsg(_("E131: Cannot delete function %s: It is in use"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003059 return;
3060 }
3061
3062 if (fudi.fd_dict != NULL)
3063 {
3064 /* Delete the dict item that refers to the function, it will
3065 * invoke func_unref() and possibly delete the function. */
3066 dictitem_remove(fudi.fd_dict, fudi.fd_di);
3067 }
3068 else
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003069 {
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003070 /* A normal function (not a numbered function or lambda) has a
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003071 * refcount of 1 for the entry in the hashtable. When deleting
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003072 * it and the refcount is more than one, it should be kept.
Bram Moolenaarba209902016-08-24 22:06:38 +02003073 * A numbered function and lambda should be kept if the refcount is
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003074 * one or more. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003075 if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003076 {
3077 /* Function is still referenced somewhere. Don't free it but
3078 * do remove it from the hashtable. */
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003079 if (func_remove(fp))
3080 fp->uf_refcount--;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003081 fp->uf_flags |= FC_DELETED;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003082 }
3083 else
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01003084 func_clear_free(fp, FALSE);
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003085 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003086 }
3087}
3088
3089/*
3090 * Unreference a Function: decrement the reference count and free it when it
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003091 * becomes zero.
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003092 */
3093 void
3094func_unref(char_u *name)
3095{
Bram Moolenaar97baee82016-07-26 20:46:08 +02003096 ufunc_T *fp = NULL;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003097
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003098 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003099 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003100 fp = find_func(name);
3101 if (fp == NULL && isdigit(*name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003102 {
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003103#ifdef EXITFREE
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003104 if (!entered_free_all_mem)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003105#endif
Bram Moolenaar95f09602016-11-10 20:01:45 +01003106 internal_error("func_unref()");
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003107 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003108 if (fp != NULL && --fp->uf_refcount <= 0)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003109 {
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003110 /* Only delete it when it's not being used. Otherwise it's done
3111 * when "uf_calls" becomes zero. */
3112 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01003113 func_clear_free(fp, FALSE);
Bram Moolenaar97baee82016-07-26 20:46:08 +02003114 }
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003115}
3116
3117/*
3118 * Unreference a Function: decrement the reference count and free it when it
3119 * becomes zero.
3120 */
3121 void
3122func_ptr_unref(ufunc_T *fp)
3123{
Bram Moolenaar97baee82016-07-26 20:46:08 +02003124 if (fp != NULL && --fp->uf_refcount <= 0)
3125 {
3126 /* Only delete it when it's not being used. Otherwise it's done
3127 * when "uf_calls" becomes zero. */
3128 if (fp->uf_calls == 0)
Bram Moolenaar03ff9bc2017-02-02 22:59:27 +01003129 func_clear_free(fp, FALSE);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003130 }
3131}
3132
3133/*
3134 * Count a reference to a Function.
3135 */
3136 void
3137func_ref(char_u *name)
3138{
3139 ufunc_T *fp;
3140
Bram Moolenaar8dd3a432016-08-01 20:46:25 +02003141 if (name == NULL || !func_name_refcount(name))
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003142 return;
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003143 fp = find_func(name);
3144 if (fp != NULL)
3145 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003146 else if (isdigit(*name))
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003147 /* Only give an error for a numbered function.
3148 * Fail silently, when named or lambda function isn't found. */
Bram Moolenaar95f09602016-11-10 20:01:45 +01003149 internal_error("func_ref()");
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003150}
3151
3152/*
3153 * Count a reference to a Function.
3154 */
3155 void
3156func_ptr_ref(ufunc_T *fp)
3157{
3158 if (fp != NULL)
3159 ++fp->uf_refcount;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003160}
3161
3162/*
3163 * Return TRUE if items in "fc" do not have "copyID". That means they are not
3164 * referenced from anywhere that is in use.
3165 */
3166 static int
3167can_free_funccal(funccall_T *fc, int copyID)
3168{
3169 return (fc->l_varlist.lv_copyID != copyID
3170 && fc->l_vars.dv_copyID != copyID
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003171 && fc->l_avars.dv_copyID != copyID
3172 && fc->fc_copyID != copyID);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003173}
3174
3175/*
3176 * ":return [expr]"
3177 */
3178 void
3179ex_return(exarg_T *eap)
3180{
3181 char_u *arg = eap->arg;
3182 typval_T rettv;
3183 int returning = FALSE;
3184
3185 if (current_funccal == NULL)
3186 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003187 emsg(_("E133: :return not inside a function"));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003188 return;
3189 }
3190
3191 if (eap->skip)
3192 ++emsg_skip;
3193
3194 eap->nextcmd = NULL;
3195 if ((*arg != NUL && *arg != '|' && *arg != '\n')
3196 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
3197 {
3198 if (!eap->skip)
3199 returning = do_return(eap, FALSE, TRUE, &rettv);
3200 else
3201 clear_tv(&rettv);
3202 }
3203 /* It's safer to return also on error. */
3204 else if (!eap->skip)
3205 {
Bram Moolenaarfabaf752017-12-23 17:26:11 +01003206 /* In return statement, cause_abort should be force_abort. */
3207 update_force_abort();
3208
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003209 /*
3210 * Return unless the expression evaluation has been cancelled due to an
3211 * aborting error, an interrupt, or an exception.
3212 */
3213 if (!aborting())
3214 returning = do_return(eap, FALSE, TRUE, NULL);
3215 }
3216
3217 /* When skipping or the return gets pending, advance to the next command
3218 * in this line (!returning). Otherwise, ignore the rest of the line.
3219 * Following lines will be ignored by get_func_line(). */
3220 if (returning)
3221 eap->nextcmd = NULL;
3222 else if (eap->nextcmd == NULL) /* no argument */
3223 eap->nextcmd = check_nextcmd(arg);
3224
3225 if (eap->skip)
3226 --emsg_skip;
3227}
3228
3229/*
3230 * ":1,25call func(arg1, arg2)" function call.
3231 */
3232 void
3233ex_call(exarg_T *eap)
3234{
3235 char_u *arg = eap->arg;
3236 char_u *startarg;
3237 char_u *name;
3238 char_u *tofree;
3239 int len;
3240 typval_T rettv;
3241 linenr_T lnum;
3242 int doesrange;
3243 int failed = FALSE;
3244 funcdict_T fudi;
3245 partial_T *partial = NULL;
3246
3247 if (eap->skip)
3248 {
3249 /* trans_function_name() doesn't work well when skipping, use eval0()
3250 * instead to skip to any following command, e.g. for:
3251 * :if 0 | call dict.foo().bar() | endif */
3252 ++emsg_skip;
3253 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL)
3254 clear_tv(&rettv);
3255 --emsg_skip;
3256 return;
3257 }
3258
3259 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial);
3260 if (fudi.fd_newkey != NULL)
3261 {
3262 /* Still need to give an error message for missing key. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003263 semsg(_(e_dictkey), fudi.fd_newkey);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003264 vim_free(fudi.fd_newkey);
3265 }
3266 if (tofree == NULL)
3267 return;
3268
3269 /* Increase refcount on dictionary, it could get deleted when evaluating
3270 * the arguments. */
3271 if (fudi.fd_dict != NULL)
3272 ++fudi.fd_dict->dv_refcount;
3273
3274 /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its
3275 * contents. For VAR_PARTIAL get its partial, unless we already have one
3276 * from trans_function_name(). */
3277 len = (int)STRLEN(tofree);
3278 name = deref_func_name(tofree, &len,
3279 partial != NULL ? NULL : &partial, FALSE);
3280
3281 /* Skip white space to allow ":call func ()". Not good, but required for
3282 * backward compatibility. */
3283 startarg = skipwhite(arg);
3284 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3285
3286 if (*startarg != '(')
3287 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003288 semsg(_("E107: Missing parentheses: %s"), eap->arg);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003289 goto end;
3290 }
3291
3292 /*
3293 * When skipping, evaluate the function once, to find the end of the
3294 * arguments.
3295 * When the function takes a range, this is discovered after the first
3296 * call, and the loop is broken.
3297 */
3298 if (eap->skip)
3299 {
3300 ++emsg_skip;
3301 lnum = eap->line2; /* do it once, also with an invalid range */
3302 }
3303 else
3304 lnum = eap->line1;
3305 for ( ; lnum <= eap->line2; ++lnum)
3306 {
3307 if (!eap->skip && eap->addr_count > 0)
3308 {
Bram Moolenaar9e353b52018-11-04 23:39:38 +01003309 if (lnum > curbuf->b_ml.ml_line_count)
3310 {
3311 // If the function deleted lines or switched to another buffer
3312 // the line number may become invalid.
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003313 emsg(_(e_invrange));
Bram Moolenaar9e353b52018-11-04 23:39:38 +01003314 break;
3315 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003316 curwin->w_cursor.lnum = lnum;
3317 curwin->w_cursor.col = 0;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003318 curwin->w_cursor.coladd = 0;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003319 }
3320 arg = startarg;
Bram Moolenaar6ed88192019-05-11 18:37:44 +02003321 if (get_func_tv(name, -1, &rettv, &arg,
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003322 eap->line1, eap->line2, &doesrange,
3323 !eap->skip, partial, fudi.fd_dict) == FAIL)
3324 {
3325 failed = TRUE;
3326 break;
3327 }
Bram Moolenaarc6f9f732018-02-11 19:06:26 +01003328 if (has_watchexpr())
3329 dbg_check_breakpoint(eap);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003330
3331 /* Handle a function returning a Funcref, Dictionary or List. */
3332 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3333 {
3334 failed = TRUE;
3335 break;
3336 }
3337
3338 clear_tv(&rettv);
3339 if (doesrange || eap->skip)
3340 break;
3341
3342 /* Stop when immediately aborting on error, or when an interrupt
3343 * occurred or an exception was thrown but not caught.
3344 * get_func_tv() returned OK, so that the check for trailing
3345 * characters below is executed. */
3346 if (aborting())
3347 break;
3348 }
3349 if (eap->skip)
3350 --emsg_skip;
3351
3352 if (!failed)
3353 {
3354 /* Check for trailing illegal characters and a following command. */
3355 if (!ends_excmd(*arg))
3356 {
3357 emsg_severe = TRUE;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003358 emsg(_(e_trailing));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003359 }
3360 else
3361 eap->nextcmd = check_nextcmd(arg);
3362 }
3363
3364end:
3365 dict_unref(fudi.fd_dict);
3366 vim_free(tofree);
3367}
3368
3369/*
3370 * Return from a function. Possibly makes the return pending. Also called
3371 * for a pending return at the ":endtry" or after returning from an extra
3372 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
3373 * when called due to a ":return" command. "rettv" may point to a typval_T
3374 * with the return rettv. Returns TRUE when the return can be carried out,
3375 * FALSE when the return gets pending.
3376 */
3377 int
3378do_return(
3379 exarg_T *eap,
3380 int reanimate,
3381 int is_cmd,
3382 void *rettv)
3383{
3384 int idx;
3385 struct condstack *cstack = eap->cstack;
3386
3387 if (reanimate)
3388 /* Undo the return. */
3389 current_funccal->returned = FALSE;
3390
3391 /*
3392 * Cleanup (and inactivate) conditionals, but stop when a try conditional
3393 * not in its finally clause (which then is to be executed next) is found.
3394 * In this case, make the ":return" pending for execution at the ":endtry".
3395 * Otherwise, return normally.
3396 */
3397 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
3398 if (idx >= 0)
3399 {
3400 cstack->cs_pending[idx] = CSTP_RETURN;
3401
3402 if (!is_cmd && !reanimate)
3403 /* A pending return again gets pending. "rettv" points to an
3404 * allocated variable with the rettv of the original ":return"'s
3405 * argument if present or is NULL else. */
3406 cstack->cs_rettv[idx] = rettv;
3407 else
3408 {
3409 /* When undoing a return in order to make it pending, get the stored
3410 * return rettv. */
3411 if (reanimate)
3412 rettv = current_funccal->rettv;
3413
3414 if (rettv != NULL)
3415 {
3416 /* Store the value of the pending return. */
3417 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
3418 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
3419 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003420 emsg(_(e_outofmem));
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003421 }
3422 else
3423 cstack->cs_rettv[idx] = NULL;
3424
3425 if (reanimate)
3426 {
3427 /* The pending return value could be overwritten by a ":return"
3428 * without argument in a finally clause; reset the default
3429 * return value. */
3430 current_funccal->rettv->v_type = VAR_NUMBER;
3431 current_funccal->rettv->vval.v_number = 0;
3432 }
3433 }
3434 report_make_pending(CSTP_RETURN, rettv);
3435 }
3436 else
3437 {
3438 current_funccal->returned = TRUE;
3439
3440 /* If the return is carried out now, store the return value. For
3441 * a return immediately after reanimation, the value is already
3442 * there. */
3443 if (!reanimate && rettv != NULL)
3444 {
3445 clear_tv(current_funccal->rettv);
3446 *current_funccal->rettv = *(typval_T *)rettv;
3447 if (!is_cmd)
3448 vim_free(rettv);
3449 }
3450 }
3451
3452 return idx < 0;
3453}
3454
3455/*
3456 * Free the variable with a pending return value.
3457 */
3458 void
3459discard_pending_return(void *rettv)
3460{
3461 free_tv((typval_T *)rettv);
3462}
3463
3464/*
3465 * Generate a return command for producing the value of "rettv". The result
3466 * is an allocated string. Used by report_pending() for verbose messages.
3467 */
3468 char_u *
3469get_return_cmd(void *rettv)
3470{
3471 char_u *s = NULL;
3472 char_u *tofree = NULL;
3473 char_u numbuf[NUMBUFLEN];
3474
3475 if (rettv != NULL)
3476 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
3477 if (s == NULL)
3478 s = (char_u *)"";
3479
3480 STRCPY(IObuff, ":return ");
3481 STRNCPY(IObuff + 8, s, IOSIZE - 8);
3482 if (STRLEN(s) + 8 >= IOSIZE)
3483 STRCPY(IObuff + IOSIZE - 4, "...");
3484 vim_free(tofree);
3485 return vim_strsave(IObuff);
3486}
3487
3488/*
3489 * Get next function line.
3490 * Called by do_cmdline() to get the next line.
3491 * Returns allocated string, or NULL for end of function.
3492 */
3493 char_u *
3494get_func_line(
3495 int c UNUSED,
3496 void *cookie,
3497 int indent UNUSED)
3498{
3499 funccall_T *fcp = (funccall_T *)cookie;
3500 ufunc_T *fp = fcp->func;
3501 char_u *retval;
3502 garray_T *gap; /* growarray with function lines */
3503
3504 /* If breakpoints have been added/deleted need to check for it. */
3505 if (fcp->dbg_tick != debug_tick)
3506 {
3507 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3508 sourcing_lnum);
3509 fcp->dbg_tick = debug_tick;
3510 }
3511#ifdef FEAT_PROFILE
3512 if (do_profiling == PROF_YES)
3513 func_line_end(cookie);
3514#endif
3515
3516 gap = &fp->uf_lines;
3517 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3518 || fcp->returned)
3519 retval = NULL;
3520 else
3521 {
3522 /* Skip NULL lines (continuation lines). */
3523 while (fcp->linenr < gap->ga_len
3524 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
3525 ++fcp->linenr;
3526 if (fcp->linenr >= gap->ga_len)
3527 retval = NULL;
3528 else
3529 {
3530 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
3531 sourcing_lnum = fcp->linenr;
3532#ifdef FEAT_PROFILE
3533 if (do_profiling == PROF_YES)
3534 func_line_start(cookie);
3535#endif
3536 }
3537 }
3538
3539 /* Did we encounter a breakpoint? */
3540 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
3541 {
3542 dbg_breakpoint(fp->uf_name, sourcing_lnum);
3543 /* Find next breakpoint. */
3544 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
3545 sourcing_lnum);
3546 fcp->dbg_tick = debug_tick;
3547 }
3548
3549 return retval;
3550}
3551
3552#if defined(FEAT_PROFILE) || defined(PROTO)
3553/*
3554 * Called when starting to read a function line.
3555 * "sourcing_lnum" must be correct!
3556 * When skipping lines it may not actually be executed, but we won't find out
3557 * until later and we need to store the time now.
3558 */
3559 void
3560func_line_start(void *cookie)
3561{
3562 funccall_T *fcp = (funccall_T *)cookie;
3563 ufunc_T *fp = fcp->func;
3564
3565 if (fp->uf_profiling && sourcing_lnum >= 1
3566 && sourcing_lnum <= fp->uf_lines.ga_len)
3567 {
3568 fp->uf_tml_idx = sourcing_lnum - 1;
3569 /* Skip continuation lines. */
3570 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
3571 --fp->uf_tml_idx;
3572 fp->uf_tml_execed = FALSE;
3573 profile_start(&fp->uf_tml_start);
3574 profile_zero(&fp->uf_tml_children);
3575 profile_get_wait(&fp->uf_tml_wait);
3576 }
3577}
3578
3579/*
3580 * Called when actually executing a function line.
3581 */
3582 void
3583func_line_exec(void *cookie)
3584{
3585 funccall_T *fcp = (funccall_T *)cookie;
3586 ufunc_T *fp = fcp->func;
3587
3588 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3589 fp->uf_tml_execed = TRUE;
3590}
3591
3592/*
3593 * Called when done with a function line.
3594 */
3595 void
3596func_line_end(void *cookie)
3597{
3598 funccall_T *fcp = (funccall_T *)cookie;
3599 ufunc_T *fp = fcp->func;
3600
3601 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
3602 {
3603 if (fp->uf_tml_execed)
3604 {
3605 ++fp->uf_tml_count[fp->uf_tml_idx];
3606 profile_end(&fp->uf_tml_start);
3607 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
3608 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
3609 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
3610 &fp->uf_tml_children);
3611 }
3612 fp->uf_tml_idx = -1;
3613 }
3614}
3615#endif
3616
3617/*
3618 * Return TRUE if the currently active function should be ended, because a
3619 * return was encountered or an error occurred. Used inside a ":while".
3620 */
3621 int
3622func_has_ended(void *cookie)
3623{
3624 funccall_T *fcp = (funccall_T *)cookie;
3625
3626 /* Ignore the "abort" flag if the abortion behavior has been changed due to
3627 * an error inside a try conditional. */
3628 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
3629 || fcp->returned);
3630}
3631
3632/*
3633 * return TRUE if cookie indicates a function which "abort"s on errors.
3634 */
3635 int
3636func_has_abort(
3637 void *cookie)
3638{
3639 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
3640}
3641
3642
3643/*
3644 * Turn "dict.Func" into a partial for "Func" bound to "dict".
3645 * Don't do this when "Func" is already a partial that was bound
3646 * explicitly (pt_auto is FALSE).
3647 * Changes "rettv" in-place.
3648 * Returns the updated "selfdict_in".
3649 */
3650 dict_T *
3651make_partial(dict_T *selfdict_in, typval_T *rettv)
3652{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003653 char_u *fname;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003654 char_u *tofree = NULL;
3655 ufunc_T *fp;
3656 char_u fname_buf[FLEN_FIXED + 1];
3657 int error;
3658 dict_T *selfdict = selfdict_in;
3659
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003660 if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL)
3661 fp = rettv->vval.v_partial->pt_func;
3662 else
3663 {
3664 fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string
3665 : rettv->vval.v_partial->pt_name;
3666 /* Translate "s:func" to the stored function name. */
3667 fname = fname_trans_sid(fname, fname_buf, &tofree, &error);
3668 fp = find_func(fname);
3669 vim_free(tofree);
3670 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003671
3672 if (fp != NULL && (fp->uf_flags & FC_DICT))
3673 {
3674 partial_T *pt = (partial_T *)alloc_clear(sizeof(partial_T));
3675
3676 if (pt != NULL)
3677 {
3678 pt->pt_refcount = 1;
3679 pt->pt_dict = selfdict;
3680 pt->pt_auto = TRUE;
3681 selfdict = NULL;
3682 if (rettv->v_type == VAR_FUNC)
3683 {
3684 /* Just a function: Take over the function name and use
3685 * selfdict. */
3686 pt->pt_name = rettv->vval.v_string;
3687 }
3688 else
3689 {
3690 partial_T *ret_pt = rettv->vval.v_partial;
3691 int i;
3692
3693 /* Partial: copy the function name, use selfdict and copy
3694 * args. Can't take over name or args, the partial might
3695 * be referenced elsewhere. */
Bram Moolenaar437bafe2016-08-01 15:40:54 +02003696 if (ret_pt->pt_name != NULL)
3697 {
3698 pt->pt_name = vim_strsave(ret_pt->pt_name);
3699 func_ref(pt->pt_name);
3700 }
3701 else
3702 {
3703 pt->pt_func = ret_pt->pt_func;
3704 func_ptr_ref(pt->pt_func);
3705 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003706 if (ret_pt->pt_argc > 0)
3707 {
3708 pt->pt_argv = (typval_T *)alloc(
3709 sizeof(typval_T) * ret_pt->pt_argc);
3710 if (pt->pt_argv == NULL)
3711 /* out of memory: drop the arguments */
3712 pt->pt_argc = 0;
3713 else
3714 {
3715 pt->pt_argc = ret_pt->pt_argc;
3716 for (i = 0; i < pt->pt_argc; i++)
3717 copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]);
3718 }
3719 }
3720 partial_unref(ret_pt);
3721 }
3722 rettv->v_type = VAR_PARTIAL;
3723 rettv->vval.v_partial = pt;
3724 }
3725 }
3726 return selfdict;
3727}
3728
3729/*
3730 * Return the name of the executed function.
3731 */
3732 char_u *
3733func_name(void *cookie)
3734{
3735 return ((funccall_T *)cookie)->func->uf_name;
3736}
3737
3738/*
3739 * Return the address holding the next breakpoint line for a funccall cookie.
3740 */
3741 linenr_T *
3742func_breakpoint(void *cookie)
3743{
3744 return &((funccall_T *)cookie)->breakpoint;
3745}
3746
3747/*
3748 * Return the address holding the debug tick for a funccall cookie.
3749 */
3750 int *
3751func_dbg_tick(void *cookie)
3752{
3753 return &((funccall_T *)cookie)->dbg_tick;
3754}
3755
3756/*
3757 * Return the nesting level for a funccall cookie.
3758 */
3759 int
3760func_level(void *cookie)
3761{
3762 return ((funccall_T *)cookie)->level;
3763}
3764
3765/*
3766 * Return TRUE when a function was ended by a ":return" command.
3767 */
3768 int
3769current_func_returned(void)
3770{
3771 return current_funccal->returned;
3772}
3773
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003774 int
3775free_unref_funccal(int copyID, int testing)
3776{
3777 int did_free = FALSE;
3778 int did_free_funccal = FALSE;
3779 funccall_T *fc, **pfc;
3780
3781 for (pfc = &previous_funccal; *pfc != NULL; )
3782 {
3783 if (can_free_funccal(*pfc, copyID))
3784 {
3785 fc = *pfc;
3786 *pfc = fc->caller;
Bram Moolenaar209b8e32019-03-14 13:43:24 +01003787 free_funccal_contents(fc);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003788 did_free = TRUE;
3789 did_free_funccal = TRUE;
3790 }
3791 else
3792 pfc = &(*pfc)->caller;
3793 }
3794 if (did_free_funccal)
3795 /* When a funccal was freed some more items might be garbage
3796 * collected, so run again. */
3797 (void)garbage_collect(testing);
3798
3799 return did_free;
3800}
3801
3802/*
Bram Moolenaarba209902016-08-24 22:06:38 +02003803 * Get function call environment based on backtrace debug level
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003804 */
3805 static funccall_T *
3806get_funccal(void)
3807{
3808 int i;
3809 funccall_T *funccal;
3810 funccall_T *temp_funccal;
3811
3812 funccal = current_funccal;
3813 if (debug_backtrace_level > 0)
3814 {
3815 for (i = 0; i < debug_backtrace_level; i++)
3816 {
3817 temp_funccal = funccal->caller;
3818 if (temp_funccal)
3819 funccal = temp_funccal;
3820 else
3821 /* backtrace level overflow. reset to max */
3822 debug_backtrace_level = i;
3823 }
3824 }
3825 return funccal;
3826}
3827
3828/*
3829 * Return the hashtable used for local variables in the current funccal.
3830 * Return NULL if there is no current funccal.
3831 */
3832 hashtab_T *
3833get_funccal_local_ht()
3834{
3835 if (current_funccal == NULL)
3836 return NULL;
3837 return &get_funccal()->l_vars.dv_hashtab;
3838}
3839
3840/*
3841 * Return the l: scope variable.
3842 * Return NULL if there is no current funccal.
3843 */
3844 dictitem_T *
3845get_funccal_local_var()
3846{
3847 if (current_funccal == NULL)
3848 return NULL;
3849 return &get_funccal()->l_vars_var;
3850}
3851
3852/*
3853 * Return the hashtable used for argument in the current funccal.
3854 * Return NULL if there is no current funccal.
3855 */
3856 hashtab_T *
3857get_funccal_args_ht()
3858{
3859 if (current_funccal == NULL)
3860 return NULL;
3861 return &get_funccal()->l_avars.dv_hashtab;
3862}
3863
3864/*
3865 * Return the a: scope variable.
3866 * Return NULL if there is no current funccal.
3867 */
3868 dictitem_T *
3869get_funccal_args_var()
3870{
3871 if (current_funccal == NULL)
3872 return NULL;
Bram Moolenaarc7d9eac2017-02-01 20:26:51 +01003873 return &get_funccal()->l_avars_var;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003874}
3875
3876/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003877 * List function variables, if there is a function.
3878 */
3879 void
3880list_func_vars(int *first)
3881{
3882 if (current_funccal != NULL)
3883 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
Bram Moolenaar32526b32019-01-19 17:43:09 +01003884 "l:", FALSE, first);
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003885}
3886
3887/*
3888 * If "ht" is the hashtable for local variables in the current funccal, return
3889 * the dict that contains it.
3890 * Otherwise return NULL.
3891 */
3892 dict_T *
3893get_current_funccal_dict(hashtab_T *ht)
3894{
3895 if (current_funccal != NULL
3896 && ht == &current_funccal->l_vars.dv_hashtab)
3897 return &current_funccal->l_vars;
3898 return NULL;
3899}
3900
3901/*
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003902 * Search hashitem in parent scope.
3903 */
3904 hashitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003905find_hi_in_scoped_ht(char_u *name, hashtab_T **pht)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003906{
3907 funccall_T *old_current_funccal = current_funccal;
3908 hashtab_T *ht;
3909 hashitem_T *hi = NULL;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003910 char_u *varname;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003911
3912 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3913 return NULL;
3914
3915 /* Search in parent scope which is possible to reference from lambda */
3916 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar58016442016-07-31 18:30:22 +02003917 while (current_funccal != NULL)
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003918 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003919 ht = find_var_ht(name, &varname);
3920 if (ht != NULL && *varname != NUL)
Bram Moolenaar58016442016-07-31 18:30:22 +02003921 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003922 hi = hash_find(ht, varname);
Bram Moolenaar58016442016-07-31 18:30:22 +02003923 if (!HASHITEM_EMPTY(hi))
3924 {
3925 *pht = ht;
3926 break;
3927 }
3928 }
3929 if (current_funccal == current_funccal->func->uf_scoped)
3930 break;
3931 current_funccal = current_funccal->func->uf_scoped;
Bram Moolenaar10ce39a2016-07-29 22:37:06 +02003932 }
3933 current_funccal = old_current_funccal;
3934
3935 return hi;
3936}
3937
3938/*
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003939 * Search variable in parent scope.
3940 */
3941 dictitem_T *
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003942find_var_in_scoped_ht(char_u *name, int no_autoload)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003943{
3944 dictitem_T *v = NULL;
3945 funccall_T *old_current_funccal = current_funccal;
3946 hashtab_T *ht;
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003947 char_u *varname;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003948
3949 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL)
3950 return NULL;
3951
3952 /* Search in parent scope which is possible to reference from lambda */
3953 current_funccal = current_funccal->func->uf_scoped;
3954 while (current_funccal)
3955 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003956 ht = find_var_ht(name, &varname);
3957 if (ht != NULL && *varname != NUL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003958 {
Bram Moolenaarba96e9a2016-08-01 17:10:20 +02003959 v = find_var_in_ht(ht, *name, varname, no_autoload);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003960 if (v != NULL)
3961 break;
3962 }
3963 if (current_funccal == current_funccal->func->uf_scoped)
3964 break;
3965 current_funccal = current_funccal->func->uf_scoped;
3966 }
3967 current_funccal = old_current_funccal;
3968
3969 return v;
3970}
3971
3972/*
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003973 * Set "copyID + 1" in previous_funccal and callers.
3974 */
3975 int
3976set_ref_in_previous_funccal(int copyID)
3977{
3978 int abort = FALSE;
3979 funccall_T *fc;
3980
3981 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
3982 {
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02003983 fc->fc_copyID = copyID + 1;
Bram Moolenaara9b579f2016-07-17 18:29:19 +02003984 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1,
3985 NULL);
3986 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1,
3987 NULL);
3988 }
3989 return abort;
3990}
3991
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02003992 static int
3993set_ref_in_funccal(funccall_T *fc, int copyID)
3994{
3995 int abort = FALSE;
3996
3997 if (fc->fc_copyID != copyID)
3998 {
3999 fc->fc_copyID = copyID;
4000 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL);
4001 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL);
4002 abort = abort || set_ref_in_func(NULL, fc->func, copyID);
4003 }
4004 return abort;
4005}
4006
Bram Moolenaara9b579f2016-07-17 18:29:19 +02004007/*
4008 * Set "copyID" in all local vars and arguments in the call stack.
4009 */
4010 int
4011set_ref_in_call_stack(int copyID)
4012{
4013 int abort = FALSE;
4014 funccall_T *fc;
4015
4016 for (fc = current_funccal; fc != NULL; fc = fc->caller)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02004017 abort = abort || set_ref_in_funccal(fc, copyID);
4018 return abort;
4019}
4020
4021/*
4022 * Set "copyID" in all functions available by name.
4023 */
4024 int
4025set_ref_in_functions(int copyID)
4026{
4027 int todo;
4028 hashitem_T *hi = NULL;
4029 int abort = FALSE;
4030 ufunc_T *fp;
4031
4032 todo = (int)func_hashtab.ht_used;
4033 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
Bram Moolenaara9b579f2016-07-17 18:29:19 +02004034 {
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02004035 if (!HASHITEM_EMPTY(hi))
4036 {
4037 --todo;
4038 fp = HI2UF(hi);
4039 if (!func_name_refcount(fp->uf_name))
4040 abort = abort || set_ref_in_func(NULL, fp, copyID);
4041 }
Bram Moolenaara9b579f2016-07-17 18:29:19 +02004042 }
4043 return abort;
4044}
4045
4046/*
4047 * Set "copyID" in all function arguments.
4048 */
4049 int
4050set_ref_in_func_args(int copyID)
4051{
4052 int i;
4053 int abort = FALSE;
4054
4055 for (i = 0; i < funcargs.ga_len; ++i)
4056 abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i],
4057 copyID, NULL, NULL);
4058 return abort;
4059}
4060
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004061/*
4062 * Mark all lists and dicts referenced through function "name" with "copyID".
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004063 * Returns TRUE if setting references failed somehow.
4064 */
4065 int
Bram Moolenaar437bafe2016-08-01 15:40:54 +02004066set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004067{
Bram Moolenaar437bafe2016-08-01 15:40:54 +02004068 ufunc_T *fp = fp_in;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004069 funccall_T *fc;
4070 int error = ERROR_NONE;
4071 char_u fname_buf[FLEN_FIXED + 1];
4072 char_u *tofree = NULL;
4073 char_u *fname;
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02004074 int abort = FALSE;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004075
Bram Moolenaar437bafe2016-08-01 15:40:54 +02004076 if (name == NULL && fp_in == NULL)
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004077 return FALSE;
4078
Bram Moolenaar437bafe2016-08-01 15:40:54 +02004079 if (fp_in == NULL)
4080 {
4081 fname = fname_trans_sid(name, fname_buf, &tofree, &error);
4082 fp = find_func(fname);
4083 }
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004084 if (fp != NULL)
4085 {
4086 for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped)
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02004087 abort = abort || set_ref_in_funccal(fc, copyID);
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004088 }
4089 vim_free(tofree);
Bram Moolenaarbc7ce672016-08-01 22:49:22 +02004090 return abort;
Bram Moolenaar1e96d9b2016-07-29 22:15:09 +02004091}
4092
Bram Moolenaara9b579f2016-07-17 18:29:19 +02004093#endif /* FEAT_EVAL */