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