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