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