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