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