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