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