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