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