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