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