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 /* 1353 * Execute the function if executing and no errors were detected. 1354 */ 1355 if (!evaluate) 1356 { 1357 // Not evaluating, which means the return value is unknown. This 1358 // matters for giving error messages. 1359 rettv->v_type = VAR_UNKNOWN; 1360 } 1361 else if (error == ERROR_NONE) 1362 { 1363 char_u *rfname = fname; 1364 1365 /* Ignore "g:" before a function name. */ 1366 if (fname[0] == 'g' && fname[1] == ':') 1367 rfname = fname + 2; 1368 1369 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */ 1370 rettv->vval.v_number = 0; 1371 error = ERROR_UNKNOWN; 1372 1373 if (!builtin_function(rfname, -1)) 1374 { 1375 /* 1376 * User defined function. 1377 */ 1378 if (partial != NULL && partial->pt_func != NULL) 1379 fp = partial->pt_func; 1380 else 1381 fp = find_func(rfname); 1382 1383 /* Trigger FuncUndefined event, may load the function. */ 1384 if (fp == NULL 1385 && apply_autocmds(EVENT_FUNCUNDEFINED, 1386 rfname, rfname, TRUE, NULL) 1387 && !aborting()) 1388 { 1389 /* executed an autocommand, search for the function again */ 1390 fp = find_func(rfname); 1391 } 1392 /* Try loading a package. */ 1393 if (fp == NULL && script_autoload(rfname, TRUE) && !aborting()) 1394 { 1395 /* loaded a package, search for the function again */ 1396 fp = find_func(rfname); 1397 } 1398 1399 if (fp != NULL && (fp->uf_flags & FC_DELETED)) 1400 error = ERROR_DELETED; 1401 else if (fp != NULL) 1402 { 1403 if (argv_func != NULL) 1404 argcount = argv_func(argcount, argvars, fp->uf_args.ga_len); 1405 1406 if (fp->uf_flags & FC_RANGE) 1407 *doesrange = TRUE; 1408 if (argcount < fp->uf_args.ga_len) 1409 error = ERROR_TOOFEW; 1410 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len) 1411 error = ERROR_TOOMANY; 1412 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL) 1413 error = ERROR_DICT; 1414 else 1415 { 1416 int did_save_redo = FALSE; 1417 save_redo_T save_redo; 1418 1419 /* 1420 * Call the user function. 1421 * Save and restore search patterns, script variables and 1422 * redo buffer. 1423 */ 1424 save_search_patterns(); 1425 #ifdef FEAT_INS_EXPAND 1426 if (!ins_compl_active()) 1427 #endif 1428 { 1429 saveRedobuff(&save_redo); 1430 did_save_redo = TRUE; 1431 } 1432 ++fp->uf_calls; 1433 call_user_func(fp, argcount, argvars, rettv, 1434 firstline, lastline, 1435 (fp->uf_flags & FC_DICT) ? selfdict : NULL); 1436 if (--fp->uf_calls <= 0 && fp->uf_refcount <= 0) 1437 /* Function was unreferenced while being used, free it 1438 * now. */ 1439 func_clear_free(fp, FALSE); 1440 if (did_save_redo) 1441 restoreRedobuff(&save_redo); 1442 restore_search_patterns(); 1443 error = ERROR_NONE; 1444 } 1445 } 1446 } 1447 else 1448 { 1449 /* 1450 * Find the function name in the table, call its implementation. 1451 */ 1452 error = call_internal_func(fname, argcount, argvars, rettv); 1453 } 1454 /* 1455 * The function call (or "FuncUndefined" autocommand sequence) might 1456 * have been aborted by an error, an interrupt, or an explicitly thrown 1457 * exception that has not been caught so far. This situation can be 1458 * tested for by calling aborting(). For an error in an internal 1459 * function or for the "E132" error in call_user_func(), however, the 1460 * throw point at which the "force_abort" flag (temporarily reset by 1461 * emsg()) is normally updated has not been reached yet. We need to 1462 * update that flag first to make aborting() reliable. 1463 */ 1464 update_force_abort(); 1465 } 1466 if (error == ERROR_NONE) 1467 ret = OK; 1468 1469 /* 1470 * Report an error unless the argument evaluation or function call has been 1471 * cancelled due to an aborting error, an interrupt, or an exception. 1472 */ 1473 if (!aborting()) 1474 { 1475 switch (error) 1476 { 1477 case ERROR_UNKNOWN: 1478 emsg_funcname(N_("E117: Unknown function: %s"), name); 1479 break; 1480 case ERROR_DELETED: 1481 emsg_funcname(N_("E933: Function was deleted: %s"), name); 1482 break; 1483 case ERROR_TOOMANY: 1484 emsg_funcname((char *)e_toomanyarg, name); 1485 break; 1486 case ERROR_TOOFEW: 1487 emsg_funcname(N_("E119: Not enough arguments for function: %s"), 1488 name); 1489 break; 1490 case ERROR_SCRIPT: 1491 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"), 1492 name); 1493 break; 1494 case ERROR_DICT: 1495 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"), 1496 name); 1497 break; 1498 } 1499 } 1500 1501 while (argv_clear > 0) 1502 clear_tv(&argv[--argv_clear]); 1503 vim_free(tofree); 1504 vim_free(name); 1505 1506 return ret; 1507 } 1508 1509 /* 1510 * List the head of the function: "name(arg1, arg2)". 1511 */ 1512 static void 1513 list_func_head(ufunc_T *fp, int indent) 1514 { 1515 int j; 1516 1517 msg_start(); 1518 if (indent) 1519 MSG_PUTS(" "); 1520 MSG_PUTS("function "); 1521 if (fp->uf_name[0] == K_SPECIAL) 1522 { 1523 MSG_PUTS_ATTR("<SNR>", HL_ATTR(HLF_8)); 1524 msg_puts(fp->uf_name + 3); 1525 } 1526 else 1527 msg_puts(fp->uf_name); 1528 msg_putchar('('); 1529 for (j = 0; j < fp->uf_args.ga_len; ++j) 1530 { 1531 if (j) 1532 MSG_PUTS(", "); 1533 msg_puts(FUNCARG(fp, j)); 1534 } 1535 if (fp->uf_varargs) 1536 { 1537 if (j) 1538 MSG_PUTS(", "); 1539 MSG_PUTS("..."); 1540 } 1541 msg_putchar(')'); 1542 if (fp->uf_flags & FC_ABORT) 1543 MSG_PUTS(" abort"); 1544 if (fp->uf_flags & FC_RANGE) 1545 MSG_PUTS(" range"); 1546 if (fp->uf_flags & FC_DICT) 1547 MSG_PUTS(" dict"); 1548 if (fp->uf_flags & FC_CLOSURE) 1549 MSG_PUTS(" closure"); 1550 msg_clr_eos(); 1551 if (p_verbose > 0) 1552 last_set_msg(fp->uf_script_ID); 1553 } 1554 1555 /* 1556 * Get a function name, translating "<SID>" and "<SNR>". 1557 * Also handles a Funcref in a List or Dictionary. 1558 * Returns the function name in allocated memory, or NULL for failure. 1559 * flags: 1560 * TFN_INT: internal function name OK 1561 * TFN_QUIET: be quiet 1562 * TFN_NO_AUTOLOAD: do not use script autoloading 1563 * TFN_NO_DEREF: do not dereference a Funcref 1564 * Advances "pp" to just after the function name (if no error). 1565 */ 1566 char_u * 1567 trans_function_name( 1568 char_u **pp, 1569 int skip, /* only find the end, don't evaluate */ 1570 int flags, 1571 funcdict_T *fdp, /* return: info about dictionary used */ 1572 partial_T **partial) /* return: partial of a FuncRef */ 1573 { 1574 char_u *name = NULL; 1575 char_u *start; 1576 char_u *end; 1577 int lead; 1578 char_u sid_buf[20]; 1579 int len; 1580 lval_T lv; 1581 1582 if (fdp != NULL) 1583 vim_memset(fdp, 0, sizeof(funcdict_T)); 1584 start = *pp; 1585 1586 /* Check for hard coded <SNR>: already translated function ID (from a user 1587 * command). */ 1588 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA 1589 && (*pp)[2] == (int)KE_SNR) 1590 { 1591 *pp += 3; 1592 len = get_id_len(pp) + 3; 1593 return vim_strnsave(start, len); 1594 } 1595 1596 /* A name starting with "<SID>" or "<SNR>" is local to a script. But 1597 * don't skip over "s:", get_lval() needs it for "s:dict.func". */ 1598 lead = eval_fname_script(start); 1599 if (lead > 2) 1600 start += lead; 1601 1602 /* Note that TFN_ flags use the same values as GLV_ flags. */ 1603 end = get_lval(start, NULL, &lv, FALSE, skip, flags | GLV_READ_ONLY, 1604 lead > 2 ? 0 : FNE_CHECK_START); 1605 if (end == start) 1606 { 1607 if (!skip) 1608 EMSG(_("E129: Function name required")); 1609 goto theend; 1610 } 1611 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range))) 1612 { 1613 /* 1614 * Report an invalid expression in braces, unless the expression 1615 * evaluation has been cancelled due to an aborting error, an 1616 * interrupt, or an exception. 1617 */ 1618 if (!aborting()) 1619 { 1620 if (end != NULL) 1621 EMSG2(_(e_invarg2), start); 1622 } 1623 else 1624 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR); 1625 goto theend; 1626 } 1627 1628 if (lv.ll_tv != NULL) 1629 { 1630 if (fdp != NULL) 1631 { 1632 fdp->fd_dict = lv.ll_dict; 1633 fdp->fd_newkey = lv.ll_newkey; 1634 lv.ll_newkey = NULL; 1635 fdp->fd_di = lv.ll_di; 1636 } 1637 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL) 1638 { 1639 name = vim_strsave(lv.ll_tv->vval.v_string); 1640 *pp = end; 1641 } 1642 else if (lv.ll_tv->v_type == VAR_PARTIAL 1643 && lv.ll_tv->vval.v_partial != NULL) 1644 { 1645 name = vim_strsave(partial_name(lv.ll_tv->vval.v_partial)); 1646 *pp = end; 1647 if (partial != NULL) 1648 *partial = lv.ll_tv->vval.v_partial; 1649 } 1650 else 1651 { 1652 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL 1653 || lv.ll_dict == NULL || fdp->fd_newkey == NULL)) 1654 EMSG(_(e_funcref)); 1655 else 1656 *pp = end; 1657 name = NULL; 1658 } 1659 goto theend; 1660 } 1661 1662 if (lv.ll_name == NULL) 1663 { 1664 /* Error found, but continue after the function name. */ 1665 *pp = end; 1666 goto theend; 1667 } 1668 1669 /* Check if the name is a Funcref. If so, use the value. */ 1670 if (lv.ll_exp_name != NULL) 1671 { 1672 len = (int)STRLEN(lv.ll_exp_name); 1673 name = deref_func_name(lv.ll_exp_name, &len, partial, 1674 flags & TFN_NO_AUTOLOAD); 1675 if (name == lv.ll_exp_name) 1676 name = NULL; 1677 } 1678 else if (!(flags & TFN_NO_DEREF)) 1679 { 1680 len = (int)(end - *pp); 1681 name = deref_func_name(*pp, &len, partial, flags & TFN_NO_AUTOLOAD); 1682 if (name == *pp) 1683 name = NULL; 1684 } 1685 if (name != NULL) 1686 { 1687 name = vim_strsave(name); 1688 *pp = end; 1689 if (STRNCMP(name, "<SNR>", 5) == 0) 1690 { 1691 /* Change "<SNR>" to the byte sequence. */ 1692 name[0] = K_SPECIAL; 1693 name[1] = KS_EXTRA; 1694 name[2] = (int)KE_SNR; 1695 mch_memmove(name + 3, name + 5, STRLEN(name + 5) + 1); 1696 } 1697 goto theend; 1698 } 1699 1700 if (lv.ll_exp_name != NULL) 1701 { 1702 len = (int)STRLEN(lv.ll_exp_name); 1703 if (lead <= 2 && lv.ll_name == lv.ll_exp_name 1704 && STRNCMP(lv.ll_name, "s:", 2) == 0) 1705 { 1706 /* When there was "s:" already or the name expanded to get a 1707 * leading "s:" then remove it. */ 1708 lv.ll_name += 2; 1709 len -= 2; 1710 lead = 2; 1711 } 1712 } 1713 else 1714 { 1715 /* skip over "s:" and "g:" */ 1716 if (lead == 2 || (lv.ll_name[0] == 'g' && lv.ll_name[1] == ':')) 1717 lv.ll_name += 2; 1718 len = (int)(end - lv.ll_name); 1719 } 1720 1721 /* 1722 * Copy the function name to allocated memory. 1723 * Accept <SID>name() inside a script, translate into <SNR>123_name(). 1724 * Accept <SNR>123_name() outside a script. 1725 */ 1726 if (skip) 1727 lead = 0; /* do nothing */ 1728 else if (lead > 0) 1729 { 1730 lead = 3; 1731 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name)) 1732 || eval_fname_sid(*pp)) 1733 { 1734 /* It's "s:" or "<SID>" */ 1735 if (current_SID <= 0) 1736 { 1737 EMSG(_(e_usingsid)); 1738 goto theend; 1739 } 1740 sprintf((char *)sid_buf, "%ld_", (long)current_SID); 1741 lead += (int)STRLEN(sid_buf); 1742 } 1743 } 1744 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name, len)) 1745 { 1746 EMSG2(_("E128: Function name must start with a capital or \"s:\": %s"), 1747 start); 1748 goto theend; 1749 } 1750 if (!skip && !(flags & TFN_QUIET) && !(flags & TFN_NO_DEREF)) 1751 { 1752 char_u *cp = vim_strchr(lv.ll_name, ':'); 1753 1754 if (cp != NULL && cp < end) 1755 { 1756 EMSG2(_("E884: Function name cannot contain a colon: %s"), start); 1757 goto theend; 1758 } 1759 } 1760 1761 name = alloc((unsigned)(len + lead + 1)); 1762 if (name != NULL) 1763 { 1764 if (lead > 0) 1765 { 1766 name[0] = K_SPECIAL; 1767 name[1] = KS_EXTRA; 1768 name[2] = (int)KE_SNR; 1769 if (lead > 3) /* If it's "<SID>" */ 1770 STRCPY(name + 3, sid_buf); 1771 } 1772 mch_memmove(name + lead, lv.ll_name, (size_t)len); 1773 name[lead + len] = NUL; 1774 } 1775 *pp = end; 1776 1777 theend: 1778 clear_lval(&lv); 1779 return name; 1780 } 1781 1782 /* 1783 * ":function" 1784 */ 1785 void 1786 ex_function(exarg_T *eap) 1787 { 1788 char_u *theline; 1789 char_u *line_to_free = NULL; 1790 int j; 1791 int c; 1792 int saved_did_emsg; 1793 int saved_wait_return = need_wait_return; 1794 char_u *name = NULL; 1795 char_u *p; 1796 char_u *arg; 1797 char_u *line_arg = NULL; 1798 garray_T newargs; 1799 garray_T newlines; 1800 int varargs = FALSE; 1801 int flags = 0; 1802 ufunc_T *fp; 1803 int overwrite = FALSE; 1804 int indent; 1805 int nesting; 1806 char_u *skip_until = NULL; 1807 dictitem_T *v; 1808 funcdict_T fudi; 1809 static int func_nr = 0; /* number for nameless function */ 1810 int paren; 1811 hashtab_T *ht; 1812 int todo; 1813 hashitem_T *hi; 1814 int sourcing_lnum_off; 1815 1816 /* 1817 * ":function" without argument: list functions. 1818 */ 1819 if (ends_excmd(*eap->arg)) 1820 { 1821 if (!eap->skip) 1822 { 1823 todo = (int)func_hashtab.ht_used; 1824 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) 1825 { 1826 if (!HASHITEM_EMPTY(hi)) 1827 { 1828 --todo; 1829 fp = HI2UF(hi); 1830 if (!func_name_refcount(fp->uf_name)) 1831 list_func_head(fp, FALSE); 1832 } 1833 } 1834 } 1835 eap->nextcmd = check_nextcmd(eap->arg); 1836 return; 1837 } 1838 1839 /* 1840 * ":function /pat": list functions matching pattern. 1841 */ 1842 if (*eap->arg == '/') 1843 { 1844 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL); 1845 if (!eap->skip) 1846 { 1847 regmatch_T regmatch; 1848 1849 c = *p; 1850 *p = NUL; 1851 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC); 1852 *p = c; 1853 if (regmatch.regprog != NULL) 1854 { 1855 regmatch.rm_ic = p_ic; 1856 1857 todo = (int)func_hashtab.ht_used; 1858 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) 1859 { 1860 if (!HASHITEM_EMPTY(hi)) 1861 { 1862 --todo; 1863 fp = HI2UF(hi); 1864 if (!isdigit(*fp->uf_name) 1865 && vim_regexec(®match, fp->uf_name, 0)) 1866 list_func_head(fp, FALSE); 1867 } 1868 } 1869 vim_regfree(regmatch.regprog); 1870 } 1871 } 1872 if (*p == '/') 1873 ++p; 1874 eap->nextcmd = check_nextcmd(p); 1875 return; 1876 } 1877 1878 /* 1879 * Get the function name. There are these situations: 1880 * func normal function name 1881 * "name" == func, "fudi.fd_dict" == NULL 1882 * dict.func new dictionary entry 1883 * "name" == NULL, "fudi.fd_dict" set, 1884 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func 1885 * dict.func existing dict entry with a Funcref 1886 * "name" == func, "fudi.fd_dict" set, 1887 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL 1888 * dict.func existing dict entry that's not a Funcref 1889 * "name" == NULL, "fudi.fd_dict" set, 1890 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL 1891 * s:func script-local function name 1892 * g:func global function name, same as "func" 1893 */ 1894 p = eap->arg; 1895 name = trans_function_name(&p, eap->skip, TFN_NO_AUTOLOAD, &fudi, NULL); 1896 paren = (vim_strchr(p, '(') != NULL); 1897 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip) 1898 { 1899 /* 1900 * Return on an invalid expression in braces, unless the expression 1901 * evaluation has been cancelled due to an aborting error, an 1902 * interrupt, or an exception. 1903 */ 1904 if (!aborting()) 1905 { 1906 if (!eap->skip && fudi.fd_newkey != NULL) 1907 EMSG2(_(e_dictkey), fudi.fd_newkey); 1908 vim_free(fudi.fd_newkey); 1909 return; 1910 } 1911 else 1912 eap->skip = TRUE; 1913 } 1914 1915 /* An error in a function call during evaluation of an expression in magic 1916 * braces should not cause the function not to be defined. */ 1917 saved_did_emsg = did_emsg; 1918 did_emsg = FALSE; 1919 1920 /* 1921 * ":function func" with only function name: list function. 1922 */ 1923 if (!paren) 1924 { 1925 if (!ends_excmd(*skipwhite(p))) 1926 { 1927 EMSG(_(e_trailing)); 1928 goto ret_free; 1929 } 1930 eap->nextcmd = check_nextcmd(p); 1931 if (eap->nextcmd != NULL) 1932 *p = NUL; 1933 if (!eap->skip && !got_int) 1934 { 1935 fp = find_func(name); 1936 if (fp != NULL) 1937 { 1938 list_func_head(fp, TRUE); 1939 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j) 1940 { 1941 if (FUNCLINE(fp, j) == NULL) 1942 continue; 1943 msg_putchar('\n'); 1944 msg_outnum((long)(j + 1)); 1945 if (j < 9) 1946 msg_putchar(' '); 1947 if (j < 99) 1948 msg_putchar(' '); 1949 msg_prt_line(FUNCLINE(fp, j), FALSE); 1950 out_flush(); /* show a line at a time */ 1951 ui_breakcheck(); 1952 } 1953 if (!got_int) 1954 { 1955 msg_putchar('\n'); 1956 msg_puts((char_u *)" endfunction"); 1957 } 1958 } 1959 else 1960 emsg_funcname(N_("E123: Undefined function: %s"), name); 1961 } 1962 goto ret_free; 1963 } 1964 1965 /* 1966 * ":function name(arg1, arg2)" Define function. 1967 */ 1968 p = skipwhite(p); 1969 if (*p != '(') 1970 { 1971 if (!eap->skip) 1972 { 1973 EMSG2(_("E124: Missing '(': %s"), eap->arg); 1974 goto ret_free; 1975 } 1976 /* attempt to continue by skipping some text */ 1977 if (vim_strchr(p, '(') != NULL) 1978 p = vim_strchr(p, '('); 1979 } 1980 p = skipwhite(p + 1); 1981 1982 ga_init2(&newlines, (int)sizeof(char_u *), 3); 1983 1984 if (!eap->skip) 1985 { 1986 /* Check the name of the function. Unless it's a dictionary function 1987 * (that we are overwriting). */ 1988 if (name != NULL) 1989 arg = name; 1990 else 1991 arg = fudi.fd_newkey; 1992 if (arg != NULL && (fudi.fd_di == NULL 1993 || (fudi.fd_di->di_tv.v_type != VAR_FUNC 1994 && fudi.fd_di->di_tv.v_type != VAR_PARTIAL))) 1995 { 1996 if (*arg == K_SPECIAL) 1997 j = 3; 1998 else 1999 j = 0; 2000 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j]) 2001 : eval_isnamec(arg[j]))) 2002 ++j; 2003 if (arg[j] != NUL) 2004 emsg_funcname((char *)e_invarg2, arg); 2005 } 2006 /* Disallow using the g: dict. */ 2007 if (fudi.fd_dict != NULL && fudi.fd_dict->dv_scope == VAR_DEF_SCOPE) 2008 EMSG(_("E862: Cannot use g: here")); 2009 } 2010 2011 if (get_function_args(&p, ')', &newargs, &varargs, eap->skip) == FAIL) 2012 goto errret_2; 2013 2014 /* find extra arguments "range", "dict", "abort" and "closure" */ 2015 for (;;) 2016 { 2017 p = skipwhite(p); 2018 if (STRNCMP(p, "range", 5) == 0) 2019 { 2020 flags |= FC_RANGE; 2021 p += 5; 2022 } 2023 else if (STRNCMP(p, "dict", 4) == 0) 2024 { 2025 flags |= FC_DICT; 2026 p += 4; 2027 } 2028 else if (STRNCMP(p, "abort", 5) == 0) 2029 { 2030 flags |= FC_ABORT; 2031 p += 5; 2032 } 2033 else if (STRNCMP(p, "closure", 7) == 0) 2034 { 2035 flags |= FC_CLOSURE; 2036 p += 7; 2037 if (current_funccal == NULL) 2038 { 2039 emsg_funcname(N_("E932: Closure function should not be at top level: %s"), 2040 name == NULL ? (char_u *)"" : name); 2041 goto erret; 2042 } 2043 } 2044 else 2045 break; 2046 } 2047 2048 /* When there is a line break use what follows for the function body. 2049 * Makes 'exe "func Test()\n...\nendfunc"' work. */ 2050 if (*p == '\n') 2051 line_arg = p + 1; 2052 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg) 2053 EMSG(_(e_trailing)); 2054 2055 /* 2056 * Read the body of the function, until ":endfunction" is found. 2057 */ 2058 if (KeyTyped) 2059 { 2060 /* Check if the function already exists, don't let the user type the 2061 * whole function before telling him it doesn't work! For a script we 2062 * need to skip the body to be able to find what follows. */ 2063 if (!eap->skip && !eap->forceit) 2064 { 2065 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL) 2066 EMSG(_(e_funcdict)); 2067 else if (name != NULL && find_func(name) != NULL) 2068 emsg_funcname(e_funcexts, name); 2069 } 2070 2071 if (!eap->skip && did_emsg) 2072 goto erret; 2073 2074 msg_putchar('\n'); /* don't overwrite the function name */ 2075 cmdline_row = msg_row; 2076 } 2077 2078 indent = 2; 2079 nesting = 0; 2080 for (;;) 2081 { 2082 if (KeyTyped) 2083 { 2084 msg_scroll = TRUE; 2085 saved_wait_return = FALSE; 2086 } 2087 need_wait_return = FALSE; 2088 sourcing_lnum_off = sourcing_lnum; 2089 2090 if (line_arg != NULL) 2091 { 2092 /* Use eap->arg, split up in parts by line breaks. */ 2093 theline = line_arg; 2094 p = vim_strchr(theline, '\n'); 2095 if (p == NULL) 2096 line_arg += STRLEN(line_arg); 2097 else 2098 { 2099 *p = NUL; 2100 line_arg = p + 1; 2101 } 2102 } 2103 else 2104 { 2105 vim_free(line_to_free); 2106 if (eap->getline == NULL) 2107 theline = getcmdline(':', 0L, indent); 2108 else 2109 theline = eap->getline(':', eap->cookie, indent); 2110 line_to_free = theline; 2111 } 2112 if (KeyTyped) 2113 lines_left = Rows - 1; 2114 if (theline == NULL) 2115 { 2116 EMSG(_("E126: Missing :endfunction")); 2117 goto erret; 2118 } 2119 2120 /* Detect line continuation: sourcing_lnum increased more than one. */ 2121 if (sourcing_lnum > sourcing_lnum_off + 1) 2122 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1; 2123 else 2124 sourcing_lnum_off = 0; 2125 2126 if (skip_until != NULL) 2127 { 2128 /* between ":append" and "." and between ":python <<EOF" and "EOF" 2129 * don't check for ":endfunc". */ 2130 if (STRCMP(theline, skip_until) == 0) 2131 VIM_CLEAR(skip_until); 2132 } 2133 else 2134 { 2135 /* skip ':' and blanks*/ 2136 for (p = theline; VIM_ISWHITE(*p) || *p == ':'; ++p) 2137 ; 2138 2139 /* Check for "endfunction". */ 2140 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0) 2141 { 2142 char_u *nextcmd = NULL; 2143 2144 if (*p == '|') 2145 nextcmd = p + 1; 2146 else if (line_arg != NULL && *skipwhite(line_arg) != NUL) 2147 nextcmd = line_arg; 2148 else if (*p != NUL && *p != '"' && p_verbose > 0) 2149 give_warning2( 2150 (char_u *)_("W22: Text found after :endfunction: %s"), 2151 p, TRUE); 2152 if (nextcmd != NULL) 2153 { 2154 /* Another command follows. If the line came from "eap" we 2155 * can simply point into it, otherwise we need to change 2156 * "eap->cmdlinep". */ 2157 eap->nextcmd = nextcmd; 2158 if (line_to_free != NULL) 2159 { 2160 vim_free(*eap->cmdlinep); 2161 *eap->cmdlinep = line_to_free; 2162 line_to_free = NULL; 2163 } 2164 } 2165 break; 2166 } 2167 2168 /* Increase indent inside "if", "while", "for" and "try", decrease 2169 * at "end". */ 2170 if (indent > 2 && STRNCMP(p, "end", 3) == 0) 2171 indent -= 2; 2172 else if (STRNCMP(p, "if", 2) == 0 2173 || STRNCMP(p, "wh", 2) == 0 2174 || STRNCMP(p, "for", 3) == 0 2175 || STRNCMP(p, "try", 3) == 0) 2176 indent += 2; 2177 2178 /* Check for defining a function inside this function. */ 2179 if (checkforcmd(&p, "function", 2)) 2180 { 2181 if (*p == '!') 2182 p = skipwhite(p + 1); 2183 p += eval_fname_script(p); 2184 vim_free(trans_function_name(&p, TRUE, 0, NULL, NULL)); 2185 if (*skipwhite(p) == '(') 2186 { 2187 ++nesting; 2188 indent += 2; 2189 } 2190 } 2191 2192 /* Check for ":append", ":change", ":insert". */ 2193 p = skip_range(p, NULL); 2194 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p')) 2195 || (p[0] == 'c' 2196 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'h' 2197 && (!ASCII_ISALPHA(p[2]) || (p[2] == 'a' 2198 && (STRNCMP(&p[3], "nge", 3) != 0 2199 || !ASCII_ISALPHA(p[6]))))))) 2200 || (p[0] == 'i' 2201 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n' 2202 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's')))))) 2203 skip_until = vim_strsave((char_u *)"."); 2204 2205 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */ 2206 arg = skipwhite(skiptowhite(p)); 2207 if (arg[0] == '<' && arg[1] =='<' 2208 && ((p[0] == 'p' && p[1] == 'y' 2209 && (!ASCII_ISALNUM(p[2]) || p[2] == 't' 2210 || ((p[2] == '3' || p[2] == 'x') 2211 && !ASCII_ISALPHA(p[3])))) 2212 || (p[0] == 'p' && p[1] == 'e' 2213 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r')) 2214 || (p[0] == 't' && p[1] == 'c' 2215 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l')) 2216 || (p[0] == 'l' && p[1] == 'u' && p[2] == 'a' 2217 && !ASCII_ISALPHA(p[3])) 2218 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b' 2219 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y')) 2220 || (p[0] == 'm' && p[1] == 'z' 2221 && (!ASCII_ISALPHA(p[2]) || p[2] == 's')) 2222 )) 2223 { 2224 /* ":python <<" continues until a dot, like ":append" */ 2225 p = skipwhite(arg + 2); 2226 if (*p == NUL) 2227 skip_until = vim_strsave((char_u *)"."); 2228 else 2229 skip_until = vim_strsave(p); 2230 } 2231 } 2232 2233 /* Add the line to the function. */ 2234 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL) 2235 goto erret; 2236 2237 /* Copy the line to newly allocated memory. get_one_sourceline() 2238 * allocates 250 bytes per line, this saves 80% on average. The cost 2239 * is an extra alloc/free. */ 2240 p = vim_strsave(theline); 2241 if (p == NULL) 2242 goto erret; 2243 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = p; 2244 2245 /* Add NULL lines for continuation lines, so that the line count is 2246 * equal to the index in the growarray. */ 2247 while (sourcing_lnum_off-- > 0) 2248 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL; 2249 2250 /* Check for end of eap->arg. */ 2251 if (line_arg != NULL && *line_arg == NUL) 2252 line_arg = NULL; 2253 } 2254 2255 /* Don't define the function when skipping commands or when an error was 2256 * detected. */ 2257 if (eap->skip || did_emsg) 2258 goto erret; 2259 2260 /* 2261 * If there are no errors, add the function 2262 */ 2263 if (fudi.fd_dict == NULL) 2264 { 2265 v = find_var(name, &ht, FALSE); 2266 if (v != NULL && v->di_tv.v_type == VAR_FUNC) 2267 { 2268 emsg_funcname(N_("E707: Function name conflicts with variable: %s"), 2269 name); 2270 goto erret; 2271 } 2272 2273 fp = find_func(name); 2274 if (fp != NULL) 2275 { 2276 if (!eap->forceit) 2277 { 2278 emsg_funcname(e_funcexts, name); 2279 goto erret; 2280 } 2281 if (fp->uf_calls > 0) 2282 { 2283 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"), 2284 name); 2285 goto erret; 2286 } 2287 if (fp->uf_refcount > 1) 2288 { 2289 /* This function is referenced somewhere, don't redefine it but 2290 * create a new one. */ 2291 --fp->uf_refcount; 2292 fp->uf_flags |= FC_REMOVED; 2293 fp = NULL; 2294 overwrite = TRUE; 2295 } 2296 else 2297 { 2298 /* redefine existing function */ 2299 ga_clear_strings(&(fp->uf_args)); 2300 ga_clear_strings(&(fp->uf_lines)); 2301 VIM_CLEAR(name); 2302 } 2303 } 2304 } 2305 else 2306 { 2307 char numbuf[20]; 2308 2309 fp = NULL; 2310 if (fudi.fd_newkey == NULL && !eap->forceit) 2311 { 2312 EMSG(_(e_funcdict)); 2313 goto erret; 2314 } 2315 if (fudi.fd_di == NULL) 2316 { 2317 /* Can't add a function to a locked dictionary */ 2318 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg, FALSE)) 2319 goto erret; 2320 } 2321 /* Can't change an existing function if it is locked */ 2322 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg, FALSE)) 2323 goto erret; 2324 2325 /* Give the function a sequential number. Can only be used with a 2326 * Funcref! */ 2327 vim_free(name); 2328 sprintf(numbuf, "%d", ++func_nr); 2329 name = vim_strsave((char_u *)numbuf); 2330 if (name == NULL) 2331 goto erret; 2332 } 2333 2334 if (fp == NULL) 2335 { 2336 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL) 2337 { 2338 int slen, plen; 2339 char_u *scriptname; 2340 2341 /* Check that the autoload name matches the script name. */ 2342 j = FAIL; 2343 if (sourcing_name != NULL) 2344 { 2345 scriptname = autoload_name(name); 2346 if (scriptname != NULL) 2347 { 2348 p = vim_strchr(scriptname, '/'); 2349 plen = (int)STRLEN(p); 2350 slen = (int)STRLEN(sourcing_name); 2351 if (slen > plen && fnamecmp(p, 2352 sourcing_name + slen - plen) == 0) 2353 j = OK; 2354 vim_free(scriptname); 2355 } 2356 } 2357 if (j == FAIL) 2358 { 2359 EMSG2(_("E746: Function name does not match script file name: %s"), name); 2360 goto erret; 2361 } 2362 } 2363 2364 fp = (ufunc_T *)alloc_clear((unsigned)(sizeof(ufunc_T) + STRLEN(name))); 2365 if (fp == NULL) 2366 goto erret; 2367 2368 if (fudi.fd_dict != NULL) 2369 { 2370 if (fudi.fd_di == NULL) 2371 { 2372 /* add new dict entry */ 2373 fudi.fd_di = dictitem_alloc(fudi.fd_newkey); 2374 if (fudi.fd_di == NULL) 2375 { 2376 vim_free(fp); 2377 goto erret; 2378 } 2379 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL) 2380 { 2381 vim_free(fudi.fd_di); 2382 vim_free(fp); 2383 goto erret; 2384 } 2385 } 2386 else 2387 /* overwrite existing dict entry */ 2388 clear_tv(&fudi.fd_di->di_tv); 2389 fudi.fd_di->di_tv.v_type = VAR_FUNC; 2390 fudi.fd_di->di_tv.v_lock = 0; 2391 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name); 2392 2393 /* behave like "dict" was used */ 2394 flags |= FC_DICT; 2395 } 2396 2397 /* insert the new function in the function list */ 2398 STRCPY(fp->uf_name, name); 2399 if (overwrite) 2400 { 2401 hi = hash_find(&func_hashtab, name); 2402 hi->hi_key = UF2HIKEY(fp); 2403 } 2404 else if (hash_add(&func_hashtab, UF2HIKEY(fp)) == FAIL) 2405 { 2406 vim_free(fp); 2407 goto erret; 2408 } 2409 fp->uf_refcount = 1; 2410 } 2411 fp->uf_args = newargs; 2412 fp->uf_lines = newlines; 2413 if ((flags & FC_CLOSURE) != 0) 2414 { 2415 if (register_closure(fp) == FAIL) 2416 goto erret; 2417 } 2418 else 2419 fp->uf_scoped = NULL; 2420 2421 #ifdef FEAT_PROFILE 2422 fp->uf_tml_count = NULL; 2423 fp->uf_tml_total = NULL; 2424 fp->uf_tml_self = NULL; 2425 fp->uf_profiling = FALSE; 2426 if (prof_def_func()) 2427 func_do_profile(fp); 2428 #endif 2429 fp->uf_varargs = varargs; 2430 fp->uf_flags = flags; 2431 fp->uf_calls = 0; 2432 fp->uf_script_ID = current_SID; 2433 goto ret_free; 2434 2435 erret: 2436 ga_clear_strings(&newargs); 2437 errret_2: 2438 ga_clear_strings(&newlines); 2439 ret_free: 2440 vim_free(skip_until); 2441 vim_free(line_to_free); 2442 vim_free(fudi.fd_newkey); 2443 vim_free(name); 2444 did_emsg |= saved_did_emsg; 2445 need_wait_return |= saved_wait_return; 2446 } 2447 2448 /* 2449 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case). 2450 * Return 2 if "p" starts with "s:". 2451 * Return 0 otherwise. 2452 */ 2453 int 2454 eval_fname_script(char_u *p) 2455 { 2456 /* Use MB_STRICMP() because in Turkish comparing the "I" may not work with 2457 * the standard library function. */ 2458 if (p[0] == '<' && (MB_STRNICMP(p + 1, "SID>", 4) == 0 2459 || MB_STRNICMP(p + 1, "SNR>", 4) == 0)) 2460 return 5; 2461 if (p[0] == 's' && p[1] == ':') 2462 return 2; 2463 return 0; 2464 } 2465 2466 int 2467 translated_function_exists(char_u *name) 2468 { 2469 if (builtin_function(name, -1)) 2470 return find_internal_func(name) >= 0; 2471 return find_func(name) != NULL; 2472 } 2473 2474 /* 2475 * Return TRUE if a function "name" exists. 2476 * If "no_defef" is TRUE, do not dereference a Funcref. 2477 */ 2478 int 2479 function_exists(char_u *name, int no_deref) 2480 { 2481 char_u *nm = name; 2482 char_u *p; 2483 int n = FALSE; 2484 int flag; 2485 2486 flag = TFN_INT | TFN_QUIET | TFN_NO_AUTOLOAD; 2487 if (no_deref) 2488 flag |= TFN_NO_DEREF; 2489 p = trans_function_name(&nm, FALSE, flag, NULL, NULL); 2490 nm = skipwhite(nm); 2491 2492 /* Only accept "funcname", "funcname ", "funcname (..." and 2493 * "funcname(...", not "funcname!...". */ 2494 if (p != NULL && (*nm == NUL || *nm == '(')) 2495 n = translated_function_exists(p); 2496 vim_free(p); 2497 return n; 2498 } 2499 2500 char_u * 2501 get_expanded_name(char_u *name, int check) 2502 { 2503 char_u *nm = name; 2504 char_u *p; 2505 2506 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL, NULL); 2507 2508 if (p != NULL && *nm == NUL) 2509 if (!check || translated_function_exists(p)) 2510 return p; 2511 2512 vim_free(p); 2513 return NULL; 2514 } 2515 2516 #if defined(FEAT_PROFILE) || defined(PROTO) 2517 /* 2518 * Start profiling function "fp". 2519 */ 2520 static void 2521 func_do_profile(ufunc_T *fp) 2522 { 2523 int len = fp->uf_lines.ga_len; 2524 2525 if (len == 0) 2526 len = 1; /* avoid getting error for allocating zero bytes */ 2527 fp->uf_tm_count = 0; 2528 profile_zero(&fp->uf_tm_self); 2529 profile_zero(&fp->uf_tm_total); 2530 if (fp->uf_tml_count == NULL) 2531 fp->uf_tml_count = (int *)alloc_clear((unsigned) (sizeof(int) * len)); 2532 if (fp->uf_tml_total == NULL) 2533 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned) 2534 (sizeof(proftime_T) * len)); 2535 if (fp->uf_tml_self == NULL) 2536 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned) 2537 (sizeof(proftime_T) * len)); 2538 fp->uf_tml_idx = -1; 2539 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL 2540 || fp->uf_tml_self == NULL) 2541 return; /* out of memory */ 2542 2543 fp->uf_profiling = TRUE; 2544 } 2545 2546 /* 2547 * Dump the profiling results for all functions in file "fd". 2548 */ 2549 void 2550 func_dump_profile(FILE *fd) 2551 { 2552 hashitem_T *hi; 2553 int todo; 2554 ufunc_T *fp; 2555 int i; 2556 ufunc_T **sorttab; 2557 int st_len = 0; 2558 2559 todo = (int)func_hashtab.ht_used; 2560 if (todo == 0) 2561 return; /* nothing to dump */ 2562 2563 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T *) * todo)); 2564 2565 for (hi = func_hashtab.ht_array; todo > 0; ++hi) 2566 { 2567 if (!HASHITEM_EMPTY(hi)) 2568 { 2569 --todo; 2570 fp = HI2UF(hi); 2571 if (fp->uf_profiling) 2572 { 2573 if (sorttab != NULL) 2574 sorttab[st_len++] = fp; 2575 2576 if (fp->uf_name[0] == K_SPECIAL) 2577 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3); 2578 else 2579 fprintf(fd, "FUNCTION %s()\n", fp->uf_name); 2580 if (fp->uf_tm_count == 1) 2581 fprintf(fd, "Called 1 time\n"); 2582 else 2583 fprintf(fd, "Called %d times\n", fp->uf_tm_count); 2584 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total)); 2585 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self)); 2586 fprintf(fd, "\n"); 2587 fprintf(fd, "count total (s) self (s)\n"); 2588 2589 for (i = 0; i < fp->uf_lines.ga_len; ++i) 2590 { 2591 if (FUNCLINE(fp, i) == NULL) 2592 continue; 2593 prof_func_line(fd, fp->uf_tml_count[i], 2594 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE); 2595 fprintf(fd, "%s\n", FUNCLINE(fp, i)); 2596 } 2597 fprintf(fd, "\n"); 2598 } 2599 } 2600 } 2601 2602 if (sorttab != NULL && st_len > 0) 2603 { 2604 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), 2605 prof_total_cmp); 2606 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE); 2607 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *), 2608 prof_self_cmp); 2609 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE); 2610 } 2611 2612 vim_free(sorttab); 2613 } 2614 2615 static void 2616 prof_sort_list( 2617 FILE *fd, 2618 ufunc_T **sorttab, 2619 int st_len, 2620 char *title, 2621 int prefer_self) /* when equal print only self time */ 2622 { 2623 int i; 2624 ufunc_T *fp; 2625 2626 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title); 2627 fprintf(fd, "count total (s) self (s) function\n"); 2628 for (i = 0; i < 20 && i < st_len; ++i) 2629 { 2630 fp = sorttab[i]; 2631 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self, 2632 prefer_self); 2633 if (fp->uf_name[0] == K_SPECIAL) 2634 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3); 2635 else 2636 fprintf(fd, " %s()\n", fp->uf_name); 2637 } 2638 fprintf(fd, "\n"); 2639 } 2640 2641 /* 2642 * Print the count and times for one function or function line. 2643 */ 2644 static void 2645 prof_func_line( 2646 FILE *fd, 2647 int count, 2648 proftime_T *total, 2649 proftime_T *self, 2650 int prefer_self) /* when equal print only self time */ 2651 { 2652 if (count > 0) 2653 { 2654 fprintf(fd, "%5d ", count); 2655 if (prefer_self && profile_equal(total, self)) 2656 fprintf(fd, " "); 2657 else 2658 fprintf(fd, "%s ", profile_msg(total)); 2659 if (!prefer_self && profile_equal(total, self)) 2660 fprintf(fd, " "); 2661 else 2662 fprintf(fd, "%s ", profile_msg(self)); 2663 } 2664 else 2665 fprintf(fd, " "); 2666 } 2667 2668 /* 2669 * Compare function for total time sorting. 2670 */ 2671 static int 2672 #ifdef __BORLANDC__ 2673 _RTLENTRYF 2674 #endif 2675 prof_total_cmp(const void *s1, const void *s2) 2676 { 2677 ufunc_T *p1, *p2; 2678 2679 p1 = *(ufunc_T **)s1; 2680 p2 = *(ufunc_T **)s2; 2681 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total); 2682 } 2683 2684 /* 2685 * Compare function for self time sorting. 2686 */ 2687 static int 2688 #ifdef __BORLANDC__ 2689 _RTLENTRYF 2690 #endif 2691 prof_self_cmp(const void *s1, const void *s2) 2692 { 2693 ufunc_T *p1, *p2; 2694 2695 p1 = *(ufunc_T **)s1; 2696 p2 = *(ufunc_T **)s2; 2697 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self); 2698 } 2699 2700 /* 2701 * Prepare profiling for entering a child or something else that is not 2702 * counted for the script/function itself. 2703 * Should always be called in pair with prof_child_exit(). 2704 */ 2705 void 2706 prof_child_enter( 2707 proftime_T *tm) /* place to store waittime */ 2708 { 2709 funccall_T *fc = current_funccal; 2710 2711 if (fc != NULL && fc->func->uf_profiling) 2712 profile_start(&fc->prof_child); 2713 script_prof_save(tm); 2714 } 2715 2716 /* 2717 * Take care of time spent in a child. 2718 * Should always be called after prof_child_enter(). 2719 */ 2720 void 2721 prof_child_exit( 2722 proftime_T *tm) /* where waittime was stored */ 2723 { 2724 funccall_T *fc = current_funccal; 2725 2726 if (fc != NULL && fc->func->uf_profiling) 2727 { 2728 profile_end(&fc->prof_child); 2729 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */ 2730 profile_add(&fc->func->uf_tm_children, &fc->prof_child); 2731 profile_add(&fc->func->uf_tml_children, &fc->prof_child); 2732 } 2733 script_prof_restore(tm); 2734 } 2735 2736 #endif /* FEAT_PROFILE */ 2737 2738 #if defined(FEAT_CMDL_COMPL) || defined(PROTO) 2739 2740 /* 2741 * Function given to ExpandGeneric() to obtain the list of user defined 2742 * function names. 2743 */ 2744 char_u * 2745 get_user_func_name(expand_T *xp, int idx) 2746 { 2747 static long_u done; 2748 static hashitem_T *hi; 2749 ufunc_T *fp; 2750 2751 if (idx == 0) 2752 { 2753 done = 0; 2754 hi = func_hashtab.ht_array; 2755 } 2756 if (done < func_hashtab.ht_used) 2757 { 2758 if (done++ > 0) 2759 ++hi; 2760 while (HASHITEM_EMPTY(hi)) 2761 ++hi; 2762 fp = HI2UF(hi); 2763 2764 if ((fp->uf_flags & FC_DICT) 2765 || STRNCMP(fp->uf_name, "<lambda>", 8) == 0) 2766 return (char_u *)""; /* don't show dict and lambda functions */ 2767 2768 if (STRLEN(fp->uf_name) + 4 >= IOSIZE) 2769 return fp->uf_name; /* prevents overflow */ 2770 2771 cat_func_name(IObuff, fp); 2772 if (xp->xp_context != EXPAND_USER_FUNC) 2773 { 2774 STRCAT(IObuff, "("); 2775 if (!fp->uf_varargs && fp->uf_args.ga_len == 0) 2776 STRCAT(IObuff, ")"); 2777 } 2778 return IObuff; 2779 } 2780 return NULL; 2781 } 2782 2783 #endif /* FEAT_CMDL_COMPL */ 2784 2785 /* 2786 * ":delfunction {name}" 2787 */ 2788 void 2789 ex_delfunction(exarg_T *eap) 2790 { 2791 ufunc_T *fp = NULL; 2792 char_u *p; 2793 char_u *name; 2794 funcdict_T fudi; 2795 2796 p = eap->arg; 2797 name = trans_function_name(&p, eap->skip, 0, &fudi, NULL); 2798 vim_free(fudi.fd_newkey); 2799 if (name == NULL) 2800 { 2801 if (fudi.fd_dict != NULL && !eap->skip) 2802 EMSG(_(e_funcref)); 2803 return; 2804 } 2805 if (!ends_excmd(*skipwhite(p))) 2806 { 2807 vim_free(name); 2808 EMSG(_(e_trailing)); 2809 return; 2810 } 2811 eap->nextcmd = check_nextcmd(p); 2812 if (eap->nextcmd != NULL) 2813 *p = NUL; 2814 2815 if (!eap->skip) 2816 fp = find_func(name); 2817 vim_free(name); 2818 2819 if (!eap->skip) 2820 { 2821 if (fp == NULL) 2822 { 2823 if (!eap->forceit) 2824 EMSG2(_(e_nofunc), eap->arg); 2825 return; 2826 } 2827 if (fp->uf_calls > 0) 2828 { 2829 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg); 2830 return; 2831 } 2832 2833 if (fudi.fd_dict != NULL) 2834 { 2835 /* Delete the dict item that refers to the function, it will 2836 * invoke func_unref() and possibly delete the function. */ 2837 dictitem_remove(fudi.fd_dict, fudi.fd_di); 2838 } 2839 else 2840 { 2841 /* A normal function (not a numbered function or lambda) has a 2842 * refcount of 1 for the entry in the hashtable. When deleting 2843 * it and the refcount is more than one, it should be kept. 2844 * A numbered function and lambda should be kept if the refcount is 2845 * one or more. */ 2846 if (fp->uf_refcount > (func_name_refcount(fp->uf_name) ? 0 : 1)) 2847 { 2848 /* Function is still referenced somewhere. Don't free it but 2849 * do remove it from the hashtable. */ 2850 if (func_remove(fp)) 2851 fp->uf_refcount--; 2852 fp->uf_flags |= FC_DELETED; 2853 } 2854 else 2855 func_clear_free(fp, FALSE); 2856 } 2857 } 2858 } 2859 2860 /* 2861 * Unreference a Function: decrement the reference count and free it when it 2862 * becomes zero. 2863 */ 2864 void 2865 func_unref(char_u *name) 2866 { 2867 ufunc_T *fp = NULL; 2868 2869 if (name == NULL || !func_name_refcount(name)) 2870 return; 2871 fp = find_func(name); 2872 if (fp == NULL && isdigit(*name)) 2873 { 2874 #ifdef EXITFREE 2875 if (!entered_free_all_mem) 2876 #endif 2877 internal_error("func_unref()"); 2878 } 2879 if (fp != NULL && --fp->uf_refcount <= 0) 2880 { 2881 /* Only delete it when it's not being used. Otherwise it's done 2882 * when "uf_calls" becomes zero. */ 2883 if (fp->uf_calls == 0) 2884 func_clear_free(fp, FALSE); 2885 } 2886 } 2887 2888 /* 2889 * Unreference a Function: decrement the reference count and free it when it 2890 * becomes zero. 2891 */ 2892 void 2893 func_ptr_unref(ufunc_T *fp) 2894 { 2895 if (fp != NULL && --fp->uf_refcount <= 0) 2896 { 2897 /* Only delete it when it's not being used. Otherwise it's done 2898 * when "uf_calls" becomes zero. */ 2899 if (fp->uf_calls == 0) 2900 func_clear_free(fp, FALSE); 2901 } 2902 } 2903 2904 /* 2905 * Count a reference to a Function. 2906 */ 2907 void 2908 func_ref(char_u *name) 2909 { 2910 ufunc_T *fp; 2911 2912 if (name == NULL || !func_name_refcount(name)) 2913 return; 2914 fp = find_func(name); 2915 if (fp != NULL) 2916 ++fp->uf_refcount; 2917 else if (isdigit(*name)) 2918 /* Only give an error for a numbered function. 2919 * Fail silently, when named or lambda function isn't found. */ 2920 internal_error("func_ref()"); 2921 } 2922 2923 /* 2924 * Count a reference to a Function. 2925 */ 2926 void 2927 func_ptr_ref(ufunc_T *fp) 2928 { 2929 if (fp != NULL) 2930 ++fp->uf_refcount; 2931 } 2932 2933 /* 2934 * Return TRUE if items in "fc" do not have "copyID". That means they are not 2935 * referenced from anywhere that is in use. 2936 */ 2937 static int 2938 can_free_funccal(funccall_T *fc, int copyID) 2939 { 2940 return (fc->l_varlist.lv_copyID != copyID 2941 && fc->l_vars.dv_copyID != copyID 2942 && fc->l_avars.dv_copyID != copyID 2943 && fc->fc_copyID != copyID); 2944 } 2945 2946 /* 2947 * ":return [expr]" 2948 */ 2949 void 2950 ex_return(exarg_T *eap) 2951 { 2952 char_u *arg = eap->arg; 2953 typval_T rettv; 2954 int returning = FALSE; 2955 2956 if (current_funccal == NULL) 2957 { 2958 EMSG(_("E133: :return not inside a function")); 2959 return; 2960 } 2961 2962 if (eap->skip) 2963 ++emsg_skip; 2964 2965 eap->nextcmd = NULL; 2966 if ((*arg != NUL && *arg != '|' && *arg != '\n') 2967 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL) 2968 { 2969 if (!eap->skip) 2970 returning = do_return(eap, FALSE, TRUE, &rettv); 2971 else 2972 clear_tv(&rettv); 2973 } 2974 /* It's safer to return also on error. */ 2975 else if (!eap->skip) 2976 { 2977 /* In return statement, cause_abort should be force_abort. */ 2978 update_force_abort(); 2979 2980 /* 2981 * Return unless the expression evaluation has been cancelled due to an 2982 * aborting error, an interrupt, or an exception. 2983 */ 2984 if (!aborting()) 2985 returning = do_return(eap, FALSE, TRUE, NULL); 2986 } 2987 2988 /* When skipping or the return gets pending, advance to the next command 2989 * in this line (!returning). Otherwise, ignore the rest of the line. 2990 * Following lines will be ignored by get_func_line(). */ 2991 if (returning) 2992 eap->nextcmd = NULL; 2993 else if (eap->nextcmd == NULL) /* no argument */ 2994 eap->nextcmd = check_nextcmd(arg); 2995 2996 if (eap->skip) 2997 --emsg_skip; 2998 } 2999 3000 /* 3001 * ":1,25call func(arg1, arg2)" function call. 3002 */ 3003 void 3004 ex_call(exarg_T *eap) 3005 { 3006 char_u *arg = eap->arg; 3007 char_u *startarg; 3008 char_u *name; 3009 char_u *tofree; 3010 int len; 3011 typval_T rettv; 3012 linenr_T lnum; 3013 int doesrange; 3014 int failed = FALSE; 3015 funcdict_T fudi; 3016 partial_T *partial = NULL; 3017 3018 if (eap->skip) 3019 { 3020 /* trans_function_name() doesn't work well when skipping, use eval0() 3021 * instead to skip to any following command, e.g. for: 3022 * :if 0 | call dict.foo().bar() | endif */ 3023 ++emsg_skip; 3024 if (eval0(eap->arg, &rettv, &eap->nextcmd, FALSE) != FAIL) 3025 clear_tv(&rettv); 3026 --emsg_skip; 3027 return; 3028 } 3029 3030 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi, &partial); 3031 if (fudi.fd_newkey != NULL) 3032 { 3033 /* Still need to give an error message for missing key. */ 3034 EMSG2(_(e_dictkey), fudi.fd_newkey); 3035 vim_free(fudi.fd_newkey); 3036 } 3037 if (tofree == NULL) 3038 return; 3039 3040 /* Increase refcount on dictionary, it could get deleted when evaluating 3041 * the arguments. */ 3042 if (fudi.fd_dict != NULL) 3043 ++fudi.fd_dict->dv_refcount; 3044 3045 /* If it is the name of a variable of type VAR_FUNC or VAR_PARTIAL use its 3046 * contents. For VAR_PARTIAL get its partial, unless we already have one 3047 * from trans_function_name(). */ 3048 len = (int)STRLEN(tofree); 3049 name = deref_func_name(tofree, &len, 3050 partial != NULL ? NULL : &partial, FALSE); 3051 3052 /* Skip white space to allow ":call func ()". Not good, but required for 3053 * backward compatibility. */ 3054 startarg = skipwhite(arg); 3055 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */ 3056 3057 if (*startarg != '(') 3058 { 3059 EMSG2(_("E107: Missing parentheses: %s"), eap->arg); 3060 goto end; 3061 } 3062 3063 /* 3064 * When skipping, evaluate the function once, to find the end of the 3065 * arguments. 3066 * When the function takes a range, this is discovered after the first 3067 * call, and the loop is broken. 3068 */ 3069 if (eap->skip) 3070 { 3071 ++emsg_skip; 3072 lnum = eap->line2; /* do it once, also with an invalid range */ 3073 } 3074 else 3075 lnum = eap->line1; 3076 for ( ; lnum <= eap->line2; ++lnum) 3077 { 3078 if (!eap->skip && eap->addr_count > 0) 3079 { 3080 curwin->w_cursor.lnum = lnum; 3081 curwin->w_cursor.col = 0; 3082 #ifdef FEAT_VIRTUALEDIT 3083 curwin->w_cursor.coladd = 0; 3084 #endif 3085 } 3086 arg = startarg; 3087 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg, 3088 eap->line1, eap->line2, &doesrange, 3089 !eap->skip, partial, fudi.fd_dict) == FAIL) 3090 { 3091 failed = TRUE; 3092 break; 3093 } 3094 if (has_watchexpr()) 3095 dbg_check_breakpoint(eap); 3096 3097 /* Handle a function returning a Funcref, Dictionary or List. */ 3098 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL) 3099 { 3100 failed = TRUE; 3101 break; 3102 } 3103 3104 clear_tv(&rettv); 3105 if (doesrange || eap->skip) 3106 break; 3107 3108 /* Stop when immediately aborting on error, or when an interrupt 3109 * occurred or an exception was thrown but not caught. 3110 * get_func_tv() returned OK, so that the check for trailing 3111 * characters below is executed. */ 3112 if (aborting()) 3113 break; 3114 } 3115 if (eap->skip) 3116 --emsg_skip; 3117 3118 if (!failed) 3119 { 3120 /* Check for trailing illegal characters and a following command. */ 3121 if (!ends_excmd(*arg)) 3122 { 3123 emsg_severe = TRUE; 3124 EMSG(_(e_trailing)); 3125 } 3126 else 3127 eap->nextcmd = check_nextcmd(arg); 3128 } 3129 3130 end: 3131 dict_unref(fudi.fd_dict); 3132 vim_free(tofree); 3133 } 3134 3135 /* 3136 * Return from a function. Possibly makes the return pending. Also called 3137 * for a pending return at the ":endtry" or after returning from an extra 3138 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set 3139 * when called due to a ":return" command. "rettv" may point to a typval_T 3140 * with the return rettv. Returns TRUE when the return can be carried out, 3141 * FALSE when the return gets pending. 3142 */ 3143 int 3144 do_return( 3145 exarg_T *eap, 3146 int reanimate, 3147 int is_cmd, 3148 void *rettv) 3149 { 3150 int idx; 3151 struct condstack *cstack = eap->cstack; 3152 3153 if (reanimate) 3154 /* Undo the return. */ 3155 current_funccal->returned = FALSE; 3156 3157 /* 3158 * Cleanup (and inactivate) conditionals, but stop when a try conditional 3159 * not in its finally clause (which then is to be executed next) is found. 3160 * In this case, make the ":return" pending for execution at the ":endtry". 3161 * Otherwise, return normally. 3162 */ 3163 idx = cleanup_conditionals(eap->cstack, 0, TRUE); 3164 if (idx >= 0) 3165 { 3166 cstack->cs_pending[idx] = CSTP_RETURN; 3167 3168 if (!is_cmd && !reanimate) 3169 /* A pending return again gets pending. "rettv" points to an 3170 * allocated variable with the rettv of the original ":return"'s 3171 * argument if present or is NULL else. */ 3172 cstack->cs_rettv[idx] = rettv; 3173 else 3174 { 3175 /* When undoing a return in order to make it pending, get the stored 3176 * return rettv. */ 3177 if (reanimate) 3178 rettv = current_funccal->rettv; 3179 3180 if (rettv != NULL) 3181 { 3182 /* Store the value of the pending return. */ 3183 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL) 3184 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv; 3185 else 3186 EMSG(_(e_outofmem)); 3187 } 3188 else 3189 cstack->cs_rettv[idx] = NULL; 3190 3191 if (reanimate) 3192 { 3193 /* The pending return value could be overwritten by a ":return" 3194 * without argument in a finally clause; reset the default 3195 * return value. */ 3196 current_funccal->rettv->v_type = VAR_NUMBER; 3197 current_funccal->rettv->vval.v_number = 0; 3198 } 3199 } 3200 report_make_pending(CSTP_RETURN, rettv); 3201 } 3202 else 3203 { 3204 current_funccal->returned = TRUE; 3205 3206 /* If the return is carried out now, store the return value. For 3207 * a return immediately after reanimation, the value is already 3208 * there. */ 3209 if (!reanimate && rettv != NULL) 3210 { 3211 clear_tv(current_funccal->rettv); 3212 *current_funccal->rettv = *(typval_T *)rettv; 3213 if (!is_cmd) 3214 vim_free(rettv); 3215 } 3216 } 3217 3218 return idx < 0; 3219 } 3220 3221 /* 3222 * Free the variable with a pending return value. 3223 */ 3224 void 3225 discard_pending_return(void *rettv) 3226 { 3227 free_tv((typval_T *)rettv); 3228 } 3229 3230 /* 3231 * Generate a return command for producing the value of "rettv". The result 3232 * is an allocated string. Used by report_pending() for verbose messages. 3233 */ 3234 char_u * 3235 get_return_cmd(void *rettv) 3236 { 3237 char_u *s = NULL; 3238 char_u *tofree = NULL; 3239 char_u numbuf[NUMBUFLEN]; 3240 3241 if (rettv != NULL) 3242 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0); 3243 if (s == NULL) 3244 s = (char_u *)""; 3245 3246 STRCPY(IObuff, ":return "); 3247 STRNCPY(IObuff + 8, s, IOSIZE - 8); 3248 if (STRLEN(s) + 8 >= IOSIZE) 3249 STRCPY(IObuff + IOSIZE - 4, "..."); 3250 vim_free(tofree); 3251 return vim_strsave(IObuff); 3252 } 3253 3254 /* 3255 * Get next function line. 3256 * Called by do_cmdline() to get the next line. 3257 * Returns allocated string, or NULL for end of function. 3258 */ 3259 char_u * 3260 get_func_line( 3261 int c UNUSED, 3262 void *cookie, 3263 int indent UNUSED) 3264 { 3265 funccall_T *fcp = (funccall_T *)cookie; 3266 ufunc_T *fp = fcp->func; 3267 char_u *retval; 3268 garray_T *gap; /* growarray with function lines */ 3269 3270 /* If breakpoints have been added/deleted need to check for it. */ 3271 if (fcp->dbg_tick != debug_tick) 3272 { 3273 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, 3274 sourcing_lnum); 3275 fcp->dbg_tick = debug_tick; 3276 } 3277 #ifdef FEAT_PROFILE 3278 if (do_profiling == PROF_YES) 3279 func_line_end(cookie); 3280 #endif 3281 3282 gap = &fp->uf_lines; 3283 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) 3284 || fcp->returned) 3285 retval = NULL; 3286 else 3287 { 3288 /* Skip NULL lines (continuation lines). */ 3289 while (fcp->linenr < gap->ga_len 3290 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL) 3291 ++fcp->linenr; 3292 if (fcp->linenr >= gap->ga_len) 3293 retval = NULL; 3294 else 3295 { 3296 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]); 3297 sourcing_lnum = fcp->linenr; 3298 #ifdef FEAT_PROFILE 3299 if (do_profiling == PROF_YES) 3300 func_line_start(cookie); 3301 #endif 3302 } 3303 } 3304 3305 /* Did we encounter a breakpoint? */ 3306 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum) 3307 { 3308 dbg_breakpoint(fp->uf_name, sourcing_lnum); 3309 /* Find next breakpoint. */ 3310 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, 3311 sourcing_lnum); 3312 fcp->dbg_tick = debug_tick; 3313 } 3314 3315 return retval; 3316 } 3317 3318 #if defined(FEAT_PROFILE) || defined(PROTO) 3319 /* 3320 * Called when starting to read a function line. 3321 * "sourcing_lnum" must be correct! 3322 * When skipping lines it may not actually be executed, but we won't find out 3323 * until later and we need to store the time now. 3324 */ 3325 void 3326 func_line_start(void *cookie) 3327 { 3328 funccall_T *fcp = (funccall_T *)cookie; 3329 ufunc_T *fp = fcp->func; 3330 3331 if (fp->uf_profiling && sourcing_lnum >= 1 3332 && sourcing_lnum <= fp->uf_lines.ga_len) 3333 { 3334 fp->uf_tml_idx = sourcing_lnum - 1; 3335 /* Skip continuation lines. */ 3336 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL) 3337 --fp->uf_tml_idx; 3338 fp->uf_tml_execed = FALSE; 3339 profile_start(&fp->uf_tml_start); 3340 profile_zero(&fp->uf_tml_children); 3341 profile_get_wait(&fp->uf_tml_wait); 3342 } 3343 } 3344 3345 /* 3346 * Called when actually executing a function line. 3347 */ 3348 void 3349 func_line_exec(void *cookie) 3350 { 3351 funccall_T *fcp = (funccall_T *)cookie; 3352 ufunc_T *fp = fcp->func; 3353 3354 if (fp->uf_profiling && fp->uf_tml_idx >= 0) 3355 fp->uf_tml_execed = TRUE; 3356 } 3357 3358 /* 3359 * Called when done with a function line. 3360 */ 3361 void 3362 func_line_end(void *cookie) 3363 { 3364 funccall_T *fcp = (funccall_T *)cookie; 3365 ufunc_T *fp = fcp->func; 3366 3367 if (fp->uf_profiling && fp->uf_tml_idx >= 0) 3368 { 3369 if (fp->uf_tml_execed) 3370 { 3371 ++fp->uf_tml_count[fp->uf_tml_idx]; 3372 profile_end(&fp->uf_tml_start); 3373 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start); 3374 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start); 3375 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start, 3376 &fp->uf_tml_children); 3377 } 3378 fp->uf_tml_idx = -1; 3379 } 3380 } 3381 #endif 3382 3383 /* 3384 * Return TRUE if the currently active function should be ended, because a 3385 * return was encountered or an error occurred. Used inside a ":while". 3386 */ 3387 int 3388 func_has_ended(void *cookie) 3389 { 3390 funccall_T *fcp = (funccall_T *)cookie; 3391 3392 /* Ignore the "abort" flag if the abortion behavior has been changed due to 3393 * an error inside a try conditional. */ 3394 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try()) 3395 || fcp->returned); 3396 } 3397 3398 /* 3399 * return TRUE if cookie indicates a function which "abort"s on errors. 3400 */ 3401 int 3402 func_has_abort( 3403 void *cookie) 3404 { 3405 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT; 3406 } 3407 3408 3409 /* 3410 * Turn "dict.Func" into a partial for "Func" bound to "dict". 3411 * Don't do this when "Func" is already a partial that was bound 3412 * explicitly (pt_auto is FALSE). 3413 * Changes "rettv" in-place. 3414 * Returns the updated "selfdict_in". 3415 */ 3416 dict_T * 3417 make_partial(dict_T *selfdict_in, typval_T *rettv) 3418 { 3419 char_u *fname; 3420 char_u *tofree = NULL; 3421 ufunc_T *fp; 3422 char_u fname_buf[FLEN_FIXED + 1]; 3423 int error; 3424 dict_T *selfdict = selfdict_in; 3425 3426 if (rettv->v_type == VAR_PARTIAL && rettv->vval.v_partial->pt_func != NULL) 3427 fp = rettv->vval.v_partial->pt_func; 3428 else 3429 { 3430 fname = rettv->v_type == VAR_FUNC ? rettv->vval.v_string 3431 : rettv->vval.v_partial->pt_name; 3432 /* Translate "s:func" to the stored function name. */ 3433 fname = fname_trans_sid(fname, fname_buf, &tofree, &error); 3434 fp = find_func(fname); 3435 vim_free(tofree); 3436 } 3437 3438 if (fp != NULL && (fp->uf_flags & FC_DICT)) 3439 { 3440 partial_T *pt = (partial_T *)alloc_clear(sizeof(partial_T)); 3441 3442 if (pt != NULL) 3443 { 3444 pt->pt_refcount = 1; 3445 pt->pt_dict = selfdict; 3446 pt->pt_auto = TRUE; 3447 selfdict = NULL; 3448 if (rettv->v_type == VAR_FUNC) 3449 { 3450 /* Just a function: Take over the function name and use 3451 * selfdict. */ 3452 pt->pt_name = rettv->vval.v_string; 3453 } 3454 else 3455 { 3456 partial_T *ret_pt = rettv->vval.v_partial; 3457 int i; 3458 3459 /* Partial: copy the function name, use selfdict and copy 3460 * args. Can't take over name or args, the partial might 3461 * be referenced elsewhere. */ 3462 if (ret_pt->pt_name != NULL) 3463 { 3464 pt->pt_name = vim_strsave(ret_pt->pt_name); 3465 func_ref(pt->pt_name); 3466 } 3467 else 3468 { 3469 pt->pt_func = ret_pt->pt_func; 3470 func_ptr_ref(pt->pt_func); 3471 } 3472 if (ret_pt->pt_argc > 0) 3473 { 3474 pt->pt_argv = (typval_T *)alloc( 3475 sizeof(typval_T) * ret_pt->pt_argc); 3476 if (pt->pt_argv == NULL) 3477 /* out of memory: drop the arguments */ 3478 pt->pt_argc = 0; 3479 else 3480 { 3481 pt->pt_argc = ret_pt->pt_argc; 3482 for (i = 0; i < pt->pt_argc; i++) 3483 copy_tv(&ret_pt->pt_argv[i], &pt->pt_argv[i]); 3484 } 3485 } 3486 partial_unref(ret_pt); 3487 } 3488 rettv->v_type = VAR_PARTIAL; 3489 rettv->vval.v_partial = pt; 3490 } 3491 } 3492 return selfdict; 3493 } 3494 3495 /* 3496 * Return the name of the executed function. 3497 */ 3498 char_u * 3499 func_name(void *cookie) 3500 { 3501 return ((funccall_T *)cookie)->func->uf_name; 3502 } 3503 3504 /* 3505 * Return the address holding the next breakpoint line for a funccall cookie. 3506 */ 3507 linenr_T * 3508 func_breakpoint(void *cookie) 3509 { 3510 return &((funccall_T *)cookie)->breakpoint; 3511 } 3512 3513 /* 3514 * Return the address holding the debug tick for a funccall cookie. 3515 */ 3516 int * 3517 func_dbg_tick(void *cookie) 3518 { 3519 return &((funccall_T *)cookie)->dbg_tick; 3520 } 3521 3522 /* 3523 * Return the nesting level for a funccall cookie. 3524 */ 3525 int 3526 func_level(void *cookie) 3527 { 3528 return ((funccall_T *)cookie)->level; 3529 } 3530 3531 /* 3532 * Return TRUE when a function was ended by a ":return" command. 3533 */ 3534 int 3535 current_func_returned(void) 3536 { 3537 return current_funccal->returned; 3538 } 3539 3540 /* 3541 * Save the current function call pointer, and set it to NULL. 3542 * Used when executing autocommands and for ":source". 3543 */ 3544 void * 3545 save_funccal(void) 3546 { 3547 funccall_T *fc = current_funccal; 3548 3549 current_funccal = NULL; 3550 return (void *)fc; 3551 } 3552 3553 void 3554 restore_funccal(void *vfc) 3555 { 3556 funccall_T *fc = (funccall_T *)vfc; 3557 3558 current_funccal = fc; 3559 } 3560 3561 int 3562 free_unref_funccal(int copyID, int testing) 3563 { 3564 int did_free = FALSE; 3565 int did_free_funccal = FALSE; 3566 funccall_T *fc, **pfc; 3567 3568 for (pfc = &previous_funccal; *pfc != NULL; ) 3569 { 3570 if (can_free_funccal(*pfc, copyID)) 3571 { 3572 fc = *pfc; 3573 *pfc = fc->caller; 3574 free_funccal(fc, TRUE); 3575 did_free = TRUE; 3576 did_free_funccal = TRUE; 3577 } 3578 else 3579 pfc = &(*pfc)->caller; 3580 } 3581 if (did_free_funccal) 3582 /* When a funccal was freed some more items might be garbage 3583 * collected, so run again. */ 3584 (void)garbage_collect(testing); 3585 3586 return did_free; 3587 } 3588 3589 /* 3590 * Get function call environment based on backtrace debug level 3591 */ 3592 static funccall_T * 3593 get_funccal(void) 3594 { 3595 int i; 3596 funccall_T *funccal; 3597 funccall_T *temp_funccal; 3598 3599 funccal = current_funccal; 3600 if (debug_backtrace_level > 0) 3601 { 3602 for (i = 0; i < debug_backtrace_level; i++) 3603 { 3604 temp_funccal = funccal->caller; 3605 if (temp_funccal) 3606 funccal = temp_funccal; 3607 else 3608 /* backtrace level overflow. reset to max */ 3609 debug_backtrace_level = i; 3610 } 3611 } 3612 return funccal; 3613 } 3614 3615 /* 3616 * Return the hashtable used for local variables in the current funccal. 3617 * Return NULL if there is no current funccal. 3618 */ 3619 hashtab_T * 3620 get_funccal_local_ht() 3621 { 3622 if (current_funccal == NULL) 3623 return NULL; 3624 return &get_funccal()->l_vars.dv_hashtab; 3625 } 3626 3627 /* 3628 * Return the l: scope variable. 3629 * Return NULL if there is no current funccal. 3630 */ 3631 dictitem_T * 3632 get_funccal_local_var() 3633 { 3634 if (current_funccal == NULL) 3635 return NULL; 3636 return &get_funccal()->l_vars_var; 3637 } 3638 3639 /* 3640 * Return the hashtable used for argument in the current funccal. 3641 * Return NULL if there is no current funccal. 3642 */ 3643 hashtab_T * 3644 get_funccal_args_ht() 3645 { 3646 if (current_funccal == NULL) 3647 return NULL; 3648 return &get_funccal()->l_avars.dv_hashtab; 3649 } 3650 3651 /* 3652 * Return the a: scope variable. 3653 * Return NULL if there is no current funccal. 3654 */ 3655 dictitem_T * 3656 get_funccal_args_var() 3657 { 3658 if (current_funccal == NULL) 3659 return NULL; 3660 return &get_funccal()->l_avars_var; 3661 } 3662 3663 /* 3664 * Clear the current_funccal and return the old value. 3665 * Caller is expected to invoke restore_current_funccal(). 3666 */ 3667 void * 3668 clear_current_funccal() 3669 { 3670 funccall_T *f = current_funccal; 3671 3672 current_funccal = NULL; 3673 return f; 3674 } 3675 3676 void 3677 restore_current_funccal(void *f) 3678 { 3679 current_funccal = f; 3680 } 3681 3682 /* 3683 * List function variables, if there is a function. 3684 */ 3685 void 3686 list_func_vars(int *first) 3687 { 3688 if (current_funccal != NULL) 3689 list_hashtable_vars(¤t_funccal->l_vars.dv_hashtab, 3690 (char_u *)"l:", FALSE, first); 3691 } 3692 3693 /* 3694 * If "ht" is the hashtable for local variables in the current funccal, return 3695 * the dict that contains it. 3696 * Otherwise return NULL. 3697 */ 3698 dict_T * 3699 get_current_funccal_dict(hashtab_T *ht) 3700 { 3701 if (current_funccal != NULL 3702 && ht == ¤t_funccal->l_vars.dv_hashtab) 3703 return ¤t_funccal->l_vars; 3704 return NULL; 3705 } 3706 3707 /* 3708 * Search hashitem in parent scope. 3709 */ 3710 hashitem_T * 3711 find_hi_in_scoped_ht(char_u *name, hashtab_T **pht) 3712 { 3713 funccall_T *old_current_funccal = current_funccal; 3714 hashtab_T *ht; 3715 hashitem_T *hi = NULL; 3716 char_u *varname; 3717 3718 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) 3719 return NULL; 3720 3721 /* Search in parent scope which is possible to reference from lambda */ 3722 current_funccal = current_funccal->func->uf_scoped; 3723 while (current_funccal != NULL) 3724 { 3725 ht = find_var_ht(name, &varname); 3726 if (ht != NULL && *varname != NUL) 3727 { 3728 hi = hash_find(ht, varname); 3729 if (!HASHITEM_EMPTY(hi)) 3730 { 3731 *pht = ht; 3732 break; 3733 } 3734 } 3735 if (current_funccal == current_funccal->func->uf_scoped) 3736 break; 3737 current_funccal = current_funccal->func->uf_scoped; 3738 } 3739 current_funccal = old_current_funccal; 3740 3741 return hi; 3742 } 3743 3744 /* 3745 * Search variable in parent scope. 3746 */ 3747 dictitem_T * 3748 find_var_in_scoped_ht(char_u *name, int no_autoload) 3749 { 3750 dictitem_T *v = NULL; 3751 funccall_T *old_current_funccal = current_funccal; 3752 hashtab_T *ht; 3753 char_u *varname; 3754 3755 if (current_funccal == NULL || current_funccal->func->uf_scoped == NULL) 3756 return NULL; 3757 3758 /* Search in parent scope which is possible to reference from lambda */ 3759 current_funccal = current_funccal->func->uf_scoped; 3760 while (current_funccal) 3761 { 3762 ht = find_var_ht(name, &varname); 3763 if (ht != NULL && *varname != NUL) 3764 { 3765 v = find_var_in_ht(ht, *name, varname, no_autoload); 3766 if (v != NULL) 3767 break; 3768 } 3769 if (current_funccal == current_funccal->func->uf_scoped) 3770 break; 3771 current_funccal = current_funccal->func->uf_scoped; 3772 } 3773 current_funccal = old_current_funccal; 3774 3775 return v; 3776 } 3777 3778 /* 3779 * Set "copyID + 1" in previous_funccal and callers. 3780 */ 3781 int 3782 set_ref_in_previous_funccal(int copyID) 3783 { 3784 int abort = FALSE; 3785 funccall_T *fc; 3786 3787 for (fc = previous_funccal; fc != NULL; fc = fc->caller) 3788 { 3789 fc->fc_copyID = copyID + 1; 3790 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1, 3791 NULL); 3792 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1, 3793 NULL); 3794 } 3795 return abort; 3796 } 3797 3798 static int 3799 set_ref_in_funccal(funccall_T *fc, int copyID) 3800 { 3801 int abort = FALSE; 3802 3803 if (fc->fc_copyID != copyID) 3804 { 3805 fc->fc_copyID = copyID; 3806 abort = abort || set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID, NULL); 3807 abort = abort || set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID, NULL); 3808 abort = abort || set_ref_in_func(NULL, fc->func, copyID); 3809 } 3810 return abort; 3811 } 3812 3813 /* 3814 * Set "copyID" in all local vars and arguments in the call stack. 3815 */ 3816 int 3817 set_ref_in_call_stack(int copyID) 3818 { 3819 int abort = FALSE; 3820 funccall_T *fc; 3821 3822 for (fc = current_funccal; fc != NULL; fc = fc->caller) 3823 abort = abort || set_ref_in_funccal(fc, copyID); 3824 return abort; 3825 } 3826 3827 /* 3828 * Set "copyID" in all functions available by name. 3829 */ 3830 int 3831 set_ref_in_functions(int copyID) 3832 { 3833 int todo; 3834 hashitem_T *hi = NULL; 3835 int abort = FALSE; 3836 ufunc_T *fp; 3837 3838 todo = (int)func_hashtab.ht_used; 3839 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi) 3840 { 3841 if (!HASHITEM_EMPTY(hi)) 3842 { 3843 --todo; 3844 fp = HI2UF(hi); 3845 if (!func_name_refcount(fp->uf_name)) 3846 abort = abort || set_ref_in_func(NULL, fp, copyID); 3847 } 3848 } 3849 return abort; 3850 } 3851 3852 /* 3853 * Set "copyID" in all function arguments. 3854 */ 3855 int 3856 set_ref_in_func_args(int copyID) 3857 { 3858 int i; 3859 int abort = FALSE; 3860 3861 for (i = 0; i < funcargs.ga_len; ++i) 3862 abort = abort || set_ref_in_item(((typval_T **)funcargs.ga_data)[i], 3863 copyID, NULL, NULL); 3864 return abort; 3865 } 3866 3867 /* 3868 * Mark all lists and dicts referenced through function "name" with "copyID". 3869 * Returns TRUE if setting references failed somehow. 3870 */ 3871 int 3872 set_ref_in_func(char_u *name, ufunc_T *fp_in, int copyID) 3873 { 3874 ufunc_T *fp = fp_in; 3875 funccall_T *fc; 3876 int error = ERROR_NONE; 3877 char_u fname_buf[FLEN_FIXED + 1]; 3878 char_u *tofree = NULL; 3879 char_u *fname; 3880 int abort = FALSE; 3881 3882 if (name == NULL && fp_in == NULL) 3883 return FALSE; 3884 3885 if (fp_in == NULL) 3886 { 3887 fname = fname_trans_sid(name, fname_buf, &tofree, &error); 3888 fp = find_func(fname); 3889 } 3890 if (fp != NULL) 3891 { 3892 for (fc = fp->uf_scoped; fc != NULL; fc = fc->func->uf_scoped) 3893 abort = abort || set_ref_in_funccal(fc, copyID); 3894 } 3895 vim_free(tofree); 3896 return abort; 3897 } 3898 3899 #endif /* FEAT_EVAL */ 3900