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