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