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