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