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