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