robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
9f600c8914
master
1// eval.c: Expression evaluation. 2 3#include <assert.h> 4#include <ctype.h> 5#include <math.h> 6#include <stdio.h> 7#include <stdlib.h> 8#include <string.h> 9#include <uv.h> 10 11#include "auto/config.h" 12#include "nvim/api/private/converter.h" 13#include "nvim/api/private/defs.h" 14#include "nvim/api/private/helpers.h" 15#include "nvim/ascii_defs.h" 16#include "nvim/autocmd.h" 17#include "nvim/buffer.h" 18#include "nvim/buffer_defs.h" 19#include "nvim/change.h" 20#include "nvim/channel.h" 21#include "nvim/charset.h" 22#include "nvim/cmdexpand_defs.h" 23#include "nvim/context.h" 24#include "nvim/cursor.h" 25#include "nvim/errors.h" 26#include "nvim/eval.h" 27#include "nvim/eval/encode.h" 28#include "nvim/eval/executor.h" 29#include "nvim/eval/funcs.h" 30#include "nvim/eval/gc.h" 31#include "nvim/eval/typval.h" 32#include "nvim/eval/userfunc.h" 33#include "nvim/eval/vars.h" 34#include "nvim/event/loop.h" 35#include "nvim/event/multiqueue.h" 36#include "nvim/event/proc.h" 37#include "nvim/event/time.h" 38#include "nvim/ex_cmds.h" 39#include "nvim/ex_docmd.h" 40#include "nvim/ex_eval.h" 41#include "nvim/garray.h" 42#include "nvim/garray_defs.h" 43#include "nvim/gettext_defs.h" 44#include "nvim/globals.h" 45#include "nvim/hashtab.h" 46#include "nvim/highlight_group.h" 47#include "nvim/insert.h" 48#include "nvim/insexpand.h" 49#include "nvim/keycodes.h" 50#include "nvim/lib/queue_defs.h" 51#include "nvim/lua/executor.h" 52#include "nvim/macros_defs.h" 53#include "nvim/main.h" 54#include "nvim/map_defs.h" 55#include "nvim/mark.h" 56#include "nvim/mark_defs.h" 57#include "nvim/mbyte.h" 58#include "nvim/memline.h" 59#include "nvim/memory.h" 60#include "nvim/message.h" 61#include "nvim/move.h" 62#include "nvim/msgpack_rpc/channel_defs.h" 63#include "nvim/ops.h" 64#include "nvim/option.h" 65#include "nvim/option_vars.h" 66#include "nvim/optionstr.h" 67#include "nvim/os/fs.h" 68#include "nvim/os/lang.h" 69#include "nvim/os/os.h" 70#include "nvim/os/os_defs.h" 71#include "nvim/os/shell.h" 72#include "nvim/path.h" 73#include "nvim/pos_defs.h" 74#include "nvim/profile.h" 75#include "nvim/quickfix.h" 76#include "nvim/regexp.h" 77#include "nvim/regexp_defs.h" 78#include "nvim/register.h" 79#include "nvim/runtime.h" 80#include "nvim/runtime_defs.h" 81#include "nvim/strings.h" 82#include "nvim/tag.h" 83#include "nvim/types_defs.h" 84#include "nvim/ui.h" 85#include "nvim/undo.h" 86#include "nvim/vim_defs.h" 87#include "nvim/window.h" 88 89// TODO(ZyX-I): Remove DICT_MAXNEST, make users be non-recursive instead 90 91#define DICT_MAXNEST 100 // maximum nesting of lists and dicts 92 93static const char * e_missbrac = N_ ("E111: Missing ']'" ); 94static const char * e_list_end = N_ ("E697: Missing end of List ']': %s" ); 95static const char e_cannot_slice_dictionary [] 96= N_ ("E719: Cannot slice a Dictionary" ); 97static const char e_cannot_index_special_variable [] 98= N_ ("E909: Cannot index a special variable" ); 99static const char * e_nowhitespace 100= N_ ("E274: No white space allowed before parenthesis" ); 101static const char e_cannot_index_a_funcref [] 102= N_ ("E695: Cannot index a Funcref" ); 103static const char e_variable_nested_too_deep_for_making_copy [] 104= N_ ("E698: Variable nested too deep for making a copy" ); 105static const char e_string_list_or_blob_required [] 106= N_ ("E1098: String, List or Blob required" ); 107static const char e_expression_too_recursive_str [] 108= N_ ("E1169: Expression too recursive: %s" ); 109static const char e_dot_can_only_be_used_on_dictionary_str [] 110= N_ ("E1203: Dot can only be used on a dictionary: %s" ); 111static const char e_empty_function_name [] 112= N_ ("E1192: Empty function name" ); 113static const char e_cannot_use_partial_here [] 114= N_ ("E1265: Cannot use a partial here" ); 115 116static char * const namespace_char = "abglstvw" ; 117 118/// Used for checking if local variables or arguments used in a lambda. 119bool * eval_lavars_used = NULL ; 120 121static int echo_hl_id = 0 ;// highlight id used for ":echo" 122 123/// Info used by a ":for" loop. 124typedef struct { 125int fi_semicolon ;// true if ending in '; var]' 126int fi_varcount ;// nr of variables in the list 127listwatch_T fi_lw ;// keep an eye on the item used. 128list_T * fi_list ;// list being used 129int fi_bi ;// index of blob 130blob_T * fi_blob ;// blob being used 131char * fi_string ;// copy of string being used 132int fi_byte_idx ;// byte index in fi_string 133}forinfo_T ; 134 135typedef enum { 136GLV_FAIL , 137GLV_OK , 138GLV_STOP , 139}glv_status_T ; 140 141#include "eval.c.generated.h" 142 143static uint64_t last_timer_id = 1 ; 144static PMap (uint64_t )timers = MAP_INIT ; 145 146dict_T * get_v_event (save_v_event_T * sve ) 147{ 148dict_T * v_event = get_vim_var_dict (VV_EVENT ); 149 150if (v_event -> dv_hashtab .ht_used > 0 ) { 151// recursive use of v:event, save, make empty and restore later 152sve -> sve_did_save = true; 153sve -> sve_hashtab = v_event -> dv_hashtab ; 154hash_init (& v_event -> dv_hashtab ); 155 }else { 156sve -> sve_did_save = false; 157 } 158return v_event ; 159} 160 161void restore_v_event (dict_T * v_event ,save_v_event_T * sve ) 162{ 163tv_dict_free_contents (v_event ); 164if (sve -> sve_did_save ) { 165v_event -> dv_hashtab = sve -> sve_hashtab ; 166 }else { 167hash_init (& v_event -> dv_hashtab ); 168 } 169} 170 171/// @return "n1" divided by "n2", taking care of dividing by zero. 172varnumber_T num_divide (varnumber_T n1 ,varnumber_T n2 ) 173FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT 174{ 175varnumber_T result ; 176 177if (n2 == 0 ) {// give an error message? 178if (n1 == 0 ) { 179result = VARNUMBER_MIN ;// similar to NaN 180 }else if (n1 < 0 ) { 181result = - VARNUMBER_MAX ; 182 }else { 183result = VARNUMBER_MAX ; 184 } 185 }else if (n1 == VARNUMBER_MIN && n2 == -1 ) { 186// specific case: trying to do VARNUMBAR_MIN / -1 results in a positive 187// number that doesn't fit in varnumber_T and causes an FPE 188result = VARNUMBER_MAX ; 189 }else { 190result = n1 /n2 ; 191 } 192 193return result ; 194} 195 196/// @return "n1" modulus "n2", taking care of dividing by zero. 197varnumber_T num_modulus (varnumber_T n1 ,varnumber_T n2 ) 198FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT 199{ 200// Give an error when n2 is 0? 201return (n2 == 0 ) ?0 : (n1 %n2 ); 202} 203 204/// Initialize the global and v: variables. 205void eval_init (void ) 206{ 207evalvars_init (); 208func_init (); 209} 210 211#ifdef EXITFREE 212void eval_clear (void ) 213{ 214evalvars_clear (); 215free_scriptnames ();// must come after evalvars_clear(). 216free_locales (); 217 218// autoloaded script names 219free_autoload_scriptnames (); 220 221// unreferenced lists and dicts 222garbage_collect (false); 223 224// functions not garbage collected 225free_all_functions (); 226} 227 228#endif 229 230void fill_evalarg_from_eap (evalarg_T * evalarg ,exarg_T * eap ,bool skip ) 231{ 232* evalarg = (evalarg_T ){ .eval_flags = skip ?0 :EVAL_EVALUATE }; 233 234if (eap == NULL ) { 235return ; 236 } 237 238if (sourcing_a_script (eap )|| eap -> ea_getline == get_list_line ) { 239evalarg -> eval_getline = eap -> ea_getline ; 240evalarg -> eval_cookie = eap -> cookie ; 241 } 242} 243 244/// Top level evaluation function, returning a boolean. 245/// Sets "error" to true if there was an error. 246/// 247/// @param skip only parse, don't execute 248/// 249/// @return true or false. 250bool eval_to_bool (char * arg ,bool * error ,exarg_T * eap ,const bool skip , 251const bool use_simple_function ) 252{ 253typval_T tv ; 254bool retval = false; 255evalarg_T evalarg ; 256 257fill_evalarg_from_eap (& evalarg ,eap ,skip ); 258 259if (skip ) { 260emsg_skip ++ ; 261 } 262int r = use_simple_function ?eval0_simple_funccal (arg ,& tv ,eap ,& evalarg ) 263 :eval0 (arg ,& tv ,eap ,& evalarg ); 264if (r == FAIL ) { 265* error = true; 266 }else { 267* error = false; 268if (!skip ) { 269retval = (tv_get_number_chk (& tv ,error )!= 0 ); 270tv_clear (& tv ); 271 } 272 } 273if (skip ) { 274emsg_skip -- ; 275 } 276clear_evalarg (& evalarg ,eap ); 277 278return retval ; 279} 280 281/// Call eval1() and give an error message if not done at a lower level. 282static int eval1_emsg (char ** arg ,typval_T * rettv ,exarg_T * eap ) 283FUNC_ATTR_NONNULL_ARG (1 ,2 ) 284{ 285const char * const start = * arg ; 286const int did_emsg_before = did_emsg ; 287const int called_emsg_before = called_emsg ; 288evalarg_T evalarg ; 289 290fill_evalarg_from_eap (& evalarg ,eap ,eap != NULL && eap -> skip ); 291 292const int ret = eval1 (arg ,rettv ,& evalarg ); 293if (ret == FAIL ) { 294// Report the invalid expression unless the expression evaluation has 295// been cancelled due to an aborting error, an interrupt, or an 296// exception, or we already gave a more specific error. 297// Also check called_emsg for when using assert_fails(). 298if (!aborting () 299&& did_emsg == did_emsg_before 300&& called_emsg == called_emsg_before ) { 301semsg (_ (e_invexpr2 ),start ); 302 } 303 } 304clear_evalarg (& evalarg ,eap ); 305return ret ; 306} 307 308/// @return whether a typval is a valid expression to pass to eval_expr_typval() 309/// or eval_expr_to_bool(). An empty string returns false; 310bool eval_expr_valid_arg (const typval_T * const tv ) 311FUNC_ATTR_NONNULL_ALL FUNC_ATTR_CONST 312{ 313return tv -> v_type != VAR_UNKNOWN 314&& (tv -> v_type != VAR_STRING || (tv -> vval .v_string != NULL && * tv -> vval .v_string != NUL )); 315} 316 317/// Evaluate a partial. 318/// Pass arguments "argv[argc]". 319/// Return the result in "rettv" and OK or FAIL. 320static int eval_expr_partial (const typval_T * expr ,typval_T * argv ,int argc ,typval_T * rettv ) 321FUNC_ATTR_NONNULL_ALL 322{ 323partial_T * const partial = expr -> vval .v_partial ; 324if (partial == NULL ) { 325return FAIL ; 326 } 327 328const char * const s = partial_name (partial ); 329if (s == NULL || * s == NUL ) { 330return FAIL ; 331 } 332 333funcexe_T funcexe = FUNCEXE_INIT ; 334funcexe .fe_evaluate = true; 335funcexe .fe_partial = partial ; 336if (call_func (s ,-1 ,rettv ,argc ,argv ,& funcexe )== FAIL ) { 337return FAIL ; 338 } 339 340return OK ; 341} 342 343/// Evaluate an expression which is a function. 344/// Pass arguments "argv[argc]". 345/// Return the result in "rettv" and OK or FAIL. 346static int eval_expr_func (const typval_T * expr ,typval_T * argv ,int argc ,typval_T * rettv ) 347FUNC_ATTR_NONNULL_ALL 348{ 349char buf [NUMBUFLEN ]; 350const char * const s = (expr -> v_type == VAR_FUNC 351 ?expr -> vval .v_string 352 :tv_get_string_buf_chk (expr ,buf )); 353if (s == NULL || * s == NUL ) { 354return FAIL ; 355 } 356 357funcexe_T funcexe = FUNCEXE_INIT ; 358funcexe .fe_evaluate = true; 359if (call_func (s ,-1 ,rettv ,argc ,argv ,& funcexe )== FAIL ) { 360return FAIL ; 361 } 362 363return OK ; 364} 365 366/// Evaluate an expression, which is a string. 367/// Return the result in "rettv" and OK or FAIL. 368static int eval_expr_string (const typval_T * expr ,typval_T * rettv ) 369FUNC_ATTR_NONNULL_ALL 370{ 371char buf [NUMBUFLEN ]; 372char * s = (char * )tv_get_string_buf_chk (expr ,buf ); 373if (s == NULL ) { 374return FAIL ; 375 } 376 377s = skipwhite (s ); 378if (eval1_emsg (& s ,rettv ,NULL )== FAIL ) { 379return FAIL ; 380 } 381 382if (* skipwhite (s )!= NUL ) {// check for trailing chars after expr 383tv_clear (rettv ); 384semsg (_ (e_invexpr2 ),s ); 385return FAIL ; 386 } 387 388return OK ; 389} 390 391/// Evaluate an expression, which can be a function, partial or string. 392/// Pass arguments "argv[argc]". 393/// Return the result in "rettv" and OK or FAIL. 394/// 395/// @param want_func if true, treat a string as a function name, not an expression 396int eval_expr_typval (const typval_T * expr ,bool want_func ,typval_T * argv ,int argc , 397typval_T * rettv ) 398FUNC_ATTR_NONNULL_ALL 399{ 400if (expr -> v_type == VAR_PARTIAL ) { 401return eval_expr_partial (expr ,argv ,argc ,rettv ); 402 } 403if (expr -> v_type == VAR_FUNC || want_func ) { 404return eval_expr_func (expr ,argv ,argc ,rettv ); 405 } 406 407return eval_expr_string (expr ,rettv ); 408} 409 410/// Like eval_to_bool() but using a typval_T instead of a string. 411/// Works for string, funcref and partial. 412bool eval_expr_to_bool (const typval_T * expr ,bool * error ) 413FUNC_ATTR_NONNULL_ARG (1 ,2 ) 414{ 415typval_T argv ,rettv ; 416 417if (eval_expr_typval (expr , false,& argv ,0 ,& rettv )== FAIL ) { 418* error = true; 419return false; 420 } 421const bool res = (tv_get_number_chk (& rettv ,error )!= 0 ); 422tv_clear (& rettv ); 423return res ; 424} 425 426/// Top level evaluation function, returning a string 427/// 428/// @param[in] arg String to evaluate. 429/// @param[in] skip If true, only do parsing to nextcmd without reporting 430/// errors or actually evaluating anything. 431/// 432/// @return [allocated] string result of evaluation or NULL in case of error or 433/// when skipping. 434char * eval_to_string_skip (char * arg ,exarg_T * eap ,const bool skip ) 435FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ARG (1 )FUNC_ATTR_WARN_UNUSED_RESULT 436{ 437typval_T tv ; 438char * retval ; 439evalarg_T evalarg ; 440 441fill_evalarg_from_eap (& evalarg ,eap ,skip ); 442if (skip ) { 443emsg_skip ++ ; 444 } 445if (eval0 (arg ,& tv ,eap ,& evalarg )== FAIL || skip ) { 446retval = NULL ; 447 }else { 448retval = xstrdup (tv_get_string (& tv )); 449tv_clear (& tv ); 450 } 451if (skip ) { 452emsg_skip -- ; 453 } 454clear_evalarg (& evalarg ,eap ); 455 456return retval ; 457} 458 459/// Skip over an expression at "*pp". 460/// 461/// @return FAIL for an error, OK otherwise. 462int skip_expr (char ** pp ,evalarg_T * const evalarg ) 463{ 464const int save_flags = evalarg == NULL ?0 :evalarg -> eval_flags ; 465 466// Don't evaluate the expression. 467if (evalarg != NULL ) { 468evalarg -> eval_flags &= ~EVAL_EVALUATE ; 469 } 470 471* pp = skipwhite (* pp ); 472typval_T rettv ; 473int res = eval1 (pp ,& rettv ,NULL ); 474 475if (evalarg != NULL ) { 476evalarg -> eval_flags = save_flags ; 477 } 478 479return res ; 480} 481 482/// Convert "tv" to a string. 483/// 484/// @param join_list when true convert a List into a sequence of lines. 485/// 486/// @return an allocated string. 487static char * typval2string (typval_T * tv ,bool join_list ) 488{ 489if (join_list && tv -> v_type == VAR_LIST ) { 490garray_T ga ; 491ga_init (& ga , (int )sizeof (char ),80 ); 492if (tv -> vval .v_list != NULL ) { 493tv_list_join (& ga ,tv -> vval .v_list ,"\n" ); 494if (tv_list_len (tv -> vval .v_list )> 0 ) { 495ga_append (& ga ,NL ); 496 } 497 } 498ga_append (& ga ,NUL ); 499return (char * )ga .ga_data ; 500 }else if (tv -> v_type == VAR_LIST || tv -> v_type == VAR_DICT ) { 501return encode_tv2string (tv ,NULL ); 502 } 503return xstrdup (tv_get_string (tv )); 504} 505 506/// Top level evaluation function, returning a string. 507/// 508/// @param join_list when true convert a List into a sequence of lines. 509/// 510/// @return pointer to allocated memory, or NULL for failure. 511char * eval_to_string_eap (char * arg ,const bool join_list ,exarg_T * eap , 512const bool use_simple_function ) 513{ 514typval_T tv ; 515char * retval ; 516 517evalarg_T evalarg ; 518fill_evalarg_from_eap (& evalarg ,eap ,eap != NULL && eap -> skip ); 519int r = use_simple_function ?eval0_simple_funccal (arg ,& tv ,NULL ,& evalarg ) 520 :eval0 (arg ,& tv ,NULL ,& evalarg ); 521if (r == FAIL ) { 522retval = NULL ; 523 }else { 524retval = typval2string (& tv ,join_list ); 525tv_clear (& tv ); 526 } 527clear_evalarg (& evalarg ,NULL ); 528 529return retval ; 530} 531 532char * eval_to_string (char * arg ,const bool join_list ,const bool use_simple_function ) 533{ 534return eval_to_string_eap (arg ,join_list ,NULL ,use_simple_function ); 535} 536 537/// Call eval_to_string() without using current local variables and using 538/// textlock. 539/// 540/// @param use_sandbox when true, use the sandbox. 541char * eval_to_string_safe (char * arg ,const bool use_sandbox ,const bool use_simple_function ) 542{ 543char * retval ; 544funccal_entry_T funccal_entry ; 545 546save_funccal (& funccal_entry ); 547if (use_sandbox ) { 548sandbox ++ ; 549 } 550textlock ++ ; 551retval = eval_to_string (arg , false,use_simple_function ); 552if (use_sandbox ) { 553sandbox -- ; 554 } 555textlock -- ; 556restore_funccal (); 557return retval ; 558} 559 560/// Top level evaluation function, returning a number. 561/// Evaluates "expr" silently. 562/// 563/// @return -1 for an error. 564varnumber_T eval_to_number (char * expr ,const bool use_simple_function ) 565{ 566typval_T rettv ; 567varnumber_T retval ; 568char * p = skipwhite (expr ); 569int r = NOTDONE ; 570 571emsg_off ++ ; 572 573if (use_simple_function ) { 574r = may_call_simple_func (expr ,& rettv ); 575 } 576if (r == NOTDONE ) { 577r = eval1 (& p ,& rettv ,& EVALARG_EVALUATE ); 578 } 579if (r == FAIL ) { 580retval = -1 ; 581 }else { 582retval = tv_get_number_chk (& rettv ,NULL ); 583tv_clear (& rettv ); 584 } 585emsg_off -- ; 586 587return retval ; 588} 589 590/// Top level evaluation function. 591/// 592/// @return an allocated typval_T with the result or 593/// NULL when there is an error. 594typval_T * eval_expr (char * arg ,exarg_T * eap ) 595{ 596return eval_expr_ext (arg ,eap , false); 597} 598 599typval_T * eval_expr_ext (char * arg ,exarg_T * eap ,const bool use_simple_function ) 600{ 601typval_T * tv = xmalloc (sizeof (* tv )); 602evalarg_T evalarg ; 603 604fill_evalarg_from_eap (& evalarg ,eap ,eap != NULL && eap -> skip ); 605 606int r = NOTDONE ; 607 608if (use_simple_function ) { 609r = eval0_simple_funccal (arg ,tv ,eap ,& evalarg ); 610 } 611if (r == NOTDONE ) { 612r = eval0 (arg ,tv ,eap ,& evalarg ); 613 } 614 615if (r == FAIL ) { 616XFREE_CLEAR (tv ); 617 } 618 619clear_evalarg (& evalarg ,eap ); 620return tv ; 621} 622 623/// Call some Vim script function and return the result in "*rettv". 624/// Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] 625/// should have type VAR_UNKNOWN. 626/// 627/// @return OK or FAIL. 628int call_vim_function (const char * func ,int argc ,typval_T * argv ,typval_T * rettv ) 629FUNC_ATTR_NONNULL_ALL 630{ 631int ret ; 632int len = (int )strlen (func ); 633partial_T * pt = NULL ; 634 635if (len >=6 && !memcmp (func ,"v:lua." ,6 )) { 636func += 6 ; 637len = check_luafunc_name (func , false); 638if (len == 0 ) { 639ret = FAIL ; 640 gotofail ; 641 } 642pt = get_vim_var_partial (VV_LUA ); 643 } 644 645rettv -> v_type = VAR_UNKNOWN ;// tv_clear() uses this. 646funcexe_T funcexe = FUNCEXE_INIT ; 647funcexe .fe_firstline = curwin -> w_cursor .lnum ; 648funcexe .fe_lastline = curwin -> w_cursor .lnum ; 649funcexe .fe_evaluate = true; 650funcexe .fe_partial = pt ; 651ret = call_func (func ,len ,rettv ,argc ,argv ,& funcexe ); 652 653fail : 654if (ret == FAIL ) { 655tv_clear (rettv ); 656 } 657 658return ret ; 659} 660 661/// Call Vim script function and return the result as a string. 662/// Uses "argv[0]" to "argv[argc - 1]" for the function arguments. "argv[argc]" 663/// should have type VAR_UNKNOWN. 664/// 665/// @param[in] func Function name. 666/// @param[in] argc Number of arguments. 667/// @param[in] argv Array with typval_T arguments. 668/// 669/// @return [allocated] NULL when calling function fails, allocated string 670/// otherwise. 671void * call_func_retstr (const char * const func ,int argc ,typval_T * argv ) 672FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_MALLOC 673{ 674typval_T rettv ; 675// All arguments are passed as strings, no conversion to number. 676if (call_vim_function (func ,argc ,argv ,& rettv ) 677== FAIL ) { 678return NULL ; 679 } 680 681char * const retval = xstrdup (tv_get_string (& rettv )); 682tv_clear (& rettv ); 683return retval ; 684} 685 686/// Call Vim script function and return the result as a List. 687/// Uses "argv" and "argc" as call_func_retstr(). 688/// 689/// @param[in] func Function name. 690/// @param[in] argc Number of arguments. 691/// @param[in] argv Array with typval_T arguments. 692/// 693/// @return [allocated] NULL when calling function fails or return tv is not a 694/// List, allocated List otherwise. 695void * call_func_retlist (const char * func ,int argc ,typval_T * argv ) 696FUNC_ATTR_NONNULL_ALL 697{ 698typval_T rettv ; 699 700// All arguments are passed as strings, no conversion to number. 701if (call_vim_function (func ,argc ,argv ,& rettv )== FAIL ) { 702return NULL ; 703 } 704 705if (rettv .v_type != VAR_LIST ) { 706tv_clear (& rettv ); 707return NULL ; 708 } 709 710return rettv .vval .v_list ; 711} 712 713/// Evaluate a number-valued "expr" option ('indentexpr'/'formatexpr') via its callback. 714/// 715/// Copies the callback first (the option could be changed while evaluating it) and suppresses 716/// errors; evaluates in the sandbox when `use_sandbox`. `v:` context, `current_sctx` and any 717/// textlock are the caller's responsibility. 718/// 719/// @return The number result, or -1 on failure. 720int eval_expr_option_number (Callback * cb ,bool use_sandbox ) 721{ 722Callback copy ; 723callback_copy (& copy ,cb ); 724if (use_sandbox ) { 725sandbox ++ ; 726 } 727emsg_off ++ ; 728typval_T tv ; 729typval_T argv [1 ]; 730int retval = -1 ; 731if (callback_call (& copy ,0 ,argv ,& tv )) { 732retval = (int )tv_get_number_chk (& tv ,NULL ); 733tv_clear (& tv ); 734 } 735emsg_off -- ; 736if (use_sandbox ) { 737sandbox -- ; 738 } 739callback_free (& copy ); 740return retval ; 741} 742 743/// Evaluate a "expr" option ('foldtext'/'includeexpr') via its callback, under |textlock| and an 744/// isolated funccal stack; evaluates in the |sandbox| when `use_sandbox`. The caller sets up `v:` 745/// context and interprets `*ret_tv` (which it must clear on success). 746/// 747/// @return Whether the callback was called (result in `*ret_tv`). 748bool eval_expr_option_tv (Callback * cb ,bool use_sandbox ,typval_T * ret_tv ) 749{ 750funccal_entry_T funccal_entry ; 751save_funccal (& funccal_entry ); 752if (use_sandbox ) { 753sandbox ++ ; 754 } 755textlock ++ ; 756typval_T argv [1 ]; 757bool ok = callback_call (cb ,0 ,argv ,ret_tv ); 758textlock -- ; 759if (use_sandbox ) { 760sandbox -- ; 761 } 762restore_funccal (); 763return ok ; 764} 765 766/// Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding 767/// it in "*cp". Doesn't give error messages. 768int eval_foldexpr (win_T * wp ,int * cp ) 769{ 770const sctx_T saved_sctx = current_sctx ; 771const bool use_sandbox = was_set_insecurely (wp ,kOptFoldexpr ,OPT_LOCAL ); 772 773// 'foldexpr' (string) evaluates in the script where it was set; current line is v:lnum. 774current_sctx = wp -> w_p_script_ctx [kWinOptFoldexpr ]; 775 776emsg_off ++ ; 777if (use_sandbox ) { 778sandbox ++ ; 779 } 780textlock ++ ; 781* cp = NUL ; 782 783typval_T tv ; 784typval_T argv [1 ];// Unused: func 'foldexpr' takes no args (v:lnum legacy). 785varnumber_T retval ; 786if (!callback_call (& wp -> w_p_fde ,0 ,argv ,& tv )) { 787retval = 0 ; 788 }else { 789// If the result is a number, just return the number. 790if (tv .v_type == VAR_NUMBER ) { 791retval = tv .vval .v_number ; 792 }else if (tv .v_type != VAR_STRING || tv .vval .v_string == NULL ) { 793retval = 0 ; 794 }else { 795// If the result is a string, check if there is a non-digit before 796// the number. 797char * s = tv .vval .v_string ; 798if (* s != NUL && !ascii_isdigit (* s )&& * s != '-' ) { 799* cp = (uint8_t )(* s ++ ); 800 } 801retval = atol (s ); 802 } 803tv_clear (& tv ); 804 } 805 806emsg_off -- ; 807if (use_sandbox ) { 808sandbox -- ; 809 } 810textlock -- ; 811current_sctx = saved_sctx ; 812 813return (int )retval ; 814} 815 816/// Evaluate 'foldtext', returning an Array or a String (NULL_STRING on failure). 817Object eval_foldtext (win_T * wp ) 818{ 819const bool use_sandbox = was_set_insecurely (wp ,kOptFoldtext ,OPT_LOCAL ); 820typval_T tv ; 821Object retval ; 822if (!eval_expr_option_tv (& wp -> w_p_fdt ,use_sandbox ,& tv )) { 823retval = STRING_OBJ (NULL_STRING ); 824 }else { 825if (tv .v_type == VAR_LIST ) { 826retval = vim_to_object (& tv ,NULL , false); 827 }else { 828retval = STRING_OBJ (cstr_to_string (tv_get_string (& tv ))); 829 } 830tv_clear (& tv ); 831 } 832return retval ; 833} 834 835/// Find the end of a variable or function name. Unlike find_name_end() this 836/// does not recognize magic braces. 837/// When "use_namespace" is true recognize "b:", "s:", etc. 838/// Return a pointer to just after the name. Equal to "arg" if there is no 839/// valid name. 840static const char * to_name_end (const char * arg ,bool use_namespace ) 841{ 842// Quick check for valid starting character. 843if (!eval_isnamec1 (* arg )) { 844return arg ; 845 } 846 847const char * p ; 848for (p = arg + 1 ;* p != NUL && eval_isnamec (* p );MB_PTR_ADV (p )) { 849// Include a namespace such as "s:var" and "v:var". But "n:" is not 850// and can be used in slice "[n:]". 851if (* p == ':' && (p != arg + 1 852|| !use_namespace 853|| vim_strchr ("bgstvw" ,* arg )== NULL )) { 854break ; 855 } 856 } 857return p ; 858} 859 860/// Get an Dict lval variable that can be assigned a value to: "name", 861/// "name[expr]", "name[expr][expr]", "name.key", "name.key[expr]" etc. 862/// "name" points to the start of the name. 863/// If "rettv" is not NULL it points to the value to be assigned. 864/// "unlet" is true for ":unlet": slightly different behavior when something is 865/// wrong; must end in space or cmd separator. 866/// 867/// flags: 868/// GLV_QUIET: do not give error messages 869/// GLV_READ_ONLY: will not change the variable 870/// GLV_NO_AUTOLOAD: do not use script autoloading 871/// 872/// The Dict is returned in 'lp'. Returns GLV_OK on success and GLV_FAIL on 873/// failure. Returns GLV_STOP to stop processing the characters following 874/// 'key_end'. 875static glv_status_T get_lval_dict_item (lval_T * lp ,char * name ,char * key ,int len ,char ** key_end , 876typval_T * var1 ,int flags ,bool unlet ,typval_T * rettv ) 877{ 878bool quiet = flags & GLV_QUIET ; 879char * p = * key_end ; 880 881if (len == -1 ) { 882// "[key]": get key from "var1" 883key = (char * )tv_get_string (var1 );// is number or string 884 } 885lp -> ll_list = NULL ; 886 887// a NULL dict is equivalent with an empty dict 888if (lp -> ll_tv -> vval .v_dict == NULL ) { 889lp -> ll_tv -> vval .v_dict = tv_dict_alloc (); 890lp -> ll_tv -> vval .v_dict -> dv_refcount ++ ; 891 } 892lp -> ll_dict = lp -> ll_tv -> vval .v_dict ; 893 894lp -> ll_di = tv_dict_find (lp -> ll_dict ,key ,len ); 895 896// When assigning to a scope dictionary check that a function and 897// variable name is valid (only variable name unless it is l: or 898// g: dictionary). Disallow overwriting a builtin function. 899if (rettv != NULL && lp -> ll_dict -> dv_scope != 0 ) { 900char prevval ; 901if (len != -1 ) { 902prevval = key [len ]; 903key [len ]= NUL ; 904 }else { 905prevval = 0 ;// Avoid compiler warning. 906 } 907bool wrong = ((lp -> ll_dict -> dv_scope == VAR_DEF_SCOPE 908&& tv_is_func (* rettv ) 909&& var_wrong_func_name (key ,lp -> ll_di == NULL )) 910|| !valid_varname (key )); 911if (len != -1 ) { 912key [len ]= prevval ; 913 } 914if (wrong ) { 915return GLV_FAIL ; 916 } 917 } 918 919if (lp -> ll_di != NULL && tv_is_luafunc (& lp -> ll_di -> di_tv ) 920&& len == -1 && rettv == NULL ) { 921semsg (e_illvar ,"v:['lua']" ); 922return GLV_FAIL ; 923 } 924 925if (lp -> ll_di == NULL ) { 926// Can't add "v:" or "a:" variable. 927if (lp -> ll_dict == get_vimvar_dict () 928|| & lp -> ll_dict -> dv_hashtab == get_funccal_args_ht ()) { 929semsg (_ (e_illvar ),name ); 930return GLV_FAIL ; 931 } 932 933// Key does not exist in dict: may need to add it. 934if (* p == '[' || * p == '.' || unlet ) { 935if (!quiet ) { 936semsg (_ (e_dictkey ),key ); 937 } 938return GLV_FAIL ; 939 } 940if (len == -1 ) { 941lp -> ll_newkey = xstrdup (key ); 942 }else { 943lp -> ll_newkey = xmemdupz (key , (size_t )len ); 944 } 945* key_end = p ; 946return GLV_STOP ; 947// existing variable, need to check if it can be changed 948 }else if (!(flags & GLV_READ_ONLY ) 949&& (var_check_ro (lp -> ll_di -> di_flags ,name , (size_t )(p - name )) 950|| var_check_lock (lp -> ll_di -> di_flags ,name , (size_t )(p - name )))) { 951return GLV_FAIL ; 952 } 953 954lp -> ll_tv = & lp -> ll_di -> di_tv ; 955 956return GLV_OK ; 957} 958 959/// Get an blob lval variable that can be assigned a value to: "name", 960/// "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]", etc. 961/// 962/// 'var1' specifies the starting blob index and 'var2' specifies the ending 963/// blob index. If the first index is not specified in a range, then 'empty1' 964/// is true. If 'quiet' is true, then error messages are not displayed for 965/// invalid indexes. 966/// 967/// The blob is returned in 'lp'. Returns OK on success and FAIL on failure. 968static int get_lval_blob (lval_T * lp ,typval_T * var1 ,typval_T * var2 ,bool empty1 ,bool quiet ) 969{ 970const int bloblen = tv_blob_len (lp -> ll_tv -> vval .v_blob ); 971 972// Get the number and item for the only or first index of the List. 973if (empty1 ) { 974lp -> ll_n1 = 0 ; 975 }else { 976// Is number or string. 977lp -> ll_n1 = (int )tv_get_number (var1 ); 978 } 979 980if (tv_blob_check_index (bloblen ,lp -> ll_n1 ,quiet )== FAIL ) { 981return FAIL ; 982 } 983if (lp -> ll_range && !lp -> ll_empty2 ) { 984lp -> ll_n2 = (int )tv_get_number (var2 ); 985if (tv_blob_check_range (bloblen ,lp -> ll_n1 ,lp -> ll_n2 ,quiet )== FAIL ) { 986return FAIL ; 987 } 988 } 989 990lp -> ll_blob = lp -> ll_tv -> vval .v_blob ; 991lp -> ll_tv = NULL ; 992 993return OK ; 994} 995 996/// Get a List lval variable that can be assigned a value to: "name", 997/// "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]", etc. 998/// 999/// 'var1' specifies the starting List index and 'var2' specifies the ending 1000/// List index. If the first index is not specified in a range, then 'empty1' 1001/// is true. If 'quiet' is true, then error messages are not displayed for 1002/// invalid indexes. 1003/// 1004/// The List is returned in 'lp'. Returns OK on success and FAIL on failure. 1005static int get_lval_list (lval_T * lp ,typval_T * var1 ,typval_T * var2 ,bool empty1 ,int flags , 1006bool quiet ) 1007{ 1008// Get the number and item for the only or first index of the List. 1009if (empty1 ) { 1010lp -> ll_n1 = 0 ; 1011 }else { 1012// Is number or string. 1013lp -> ll_n1 = (int )tv_get_number (var1 ); 1014 } 1015 1016lp -> ll_dict = NULL ; 1017lp -> ll_list = lp -> ll_tv -> vval .v_list ; 1018lp -> ll_li = tv_list_check_range_index_one (lp -> ll_list ,& lp -> ll_n1 ,quiet ); 1019if (lp -> ll_li == NULL ) { 1020return FAIL ; 1021 } 1022 1023// May need to find the item or absolute index for the second 1024// index of a range. 1025// When no index given: "lp->ll_empty2" is true. 1026// Otherwise "lp->ll_n2" is set to the second index. 1027if (lp -> ll_range && !lp -> ll_empty2 ) { 1028lp -> ll_n2 = (int )tv_get_number (var2 );// Is number or string. 1029if (tv_list_check_range_index_two (lp -> ll_list , 1030& lp -> ll_n1 ,lp -> ll_li , 1031& lp -> ll_n2 ,quiet )== FAIL ) { 1032return FAIL ; 1033 } 1034 } 1035 1036lp -> ll_tv = TV_LIST_ITEM_TV (lp -> ll_li ); 1037 1038return OK ; 1039} 1040 1041/// Get the lval of a list/dict/blob subitem starting at "p". Loop 1042/// until no more [idx] or .key is following. 1043/// 1044/// If "rettv" is not NULL it points to the value to be assigned. 1045/// "unlet" is true for ":unlet". 1046/// 1047/// @param[in] flags @see GetLvalFlags. 1048/// 1049/// @return A pointer to the character after the subscript on success or NULL on 1050/// failure. 1051static char * get_lval_subscript (lval_T * lp ,char * p ,char * name ,typval_T * rettv ,hashtab_T * ht , 1052dictitem_T * v ,bool unlet ,int flags ) 1053{ 1054bool quiet = flags & GLV_QUIET ; 1055typval_T var1 ; 1056var1 .v_type = VAR_UNKNOWN ; 1057typval_T var2 ; 1058var2 .v_type = VAR_UNKNOWN ; 1059bool empty1 = false; 1060int rc = FAIL ; 1061 1062// Loop until no more [idx] or .key is following. 1063while (* p == '[' || (* p == '.' && p [1 ]!= '=' && p [1 ]!= '.' )) { 1064if (* p == '.' && lp -> ll_tv -> v_type != VAR_DICT ) { 1065if (!quiet ) { 1066semsg (_ (e_dot_can_only_be_used_on_dictionary_str ),name ); 1067 } 1068return NULL ; 1069 } 1070if (lp -> ll_tv -> v_type != VAR_LIST 1071&& lp -> ll_tv -> v_type != VAR_DICT 1072&& lp -> ll_tv -> v_type != VAR_BLOB ) { 1073if (!quiet ) { 1074emsg (_ ("E689: Can only index a List, Dictionary or Blob" )); 1075 } 1076return NULL ; 1077 } 1078 1079// A NULL list/blob works like an empty list/blob, allocate one now. 1080if (lp -> ll_tv -> v_type == VAR_LIST && lp -> ll_tv -> vval .v_list == NULL ) { 1081tv_list_alloc_ret (lp -> ll_tv ,kListLenUnknown ); 1082 }else if (lp -> ll_tv -> v_type == VAR_BLOB && lp -> ll_tv -> vval .v_blob == NULL ) { 1083tv_blob_alloc_ret (lp -> ll_tv ); 1084 } 1085 1086if (lp -> ll_range ) { 1087if (!quiet ) { 1088emsg (_ ("E708: [:] must come last" )); 1089 } 1090 gotodone ; 1091 } 1092 1093int len = -1 ; 1094char * key = NULL ; 1095if (* p == '.' ) { 1096key = p + 1 ; 1097 1098for (len = 0 ;ASCII_ISALNUM (key [len ])|| key [len ]== '_' ;len ++ ) {} 1099if (len == 0 ) { 1100if (!quiet ) { 1101emsg (_ ("E713: Cannot use empty key after ." )); 1102 } 1103return NULL ; 1104 } 1105p = key + len ; 1106 }else { 1107// Get the index [expr] or the first index [expr: ]. 1108p = skipwhite (p + 1 ); 1109if (* p == ':' ) { 1110empty1 = true; 1111 }else { 1112empty1 = false; 1113if (eval1 (& p ,& var1 ,& EVALARG_EVALUATE )== FAIL ) {// Recursive! 1114 gotodone ; 1115 } 1116if (!tv_check_str (& var1 )) { 1117// Not a number or string. 1118 gotodone ; 1119 } 1120p = skipwhite (p ); 1121 } 1122 1123// Optionally get the second index [ :expr]. 1124if (* p == ':' ) { 1125if (lp -> ll_tv -> v_type == VAR_DICT ) { 1126if (!quiet ) { 1127emsg (_ (e_cannot_slice_dictionary )); 1128 } 1129 gotodone ; 1130 } 1131if (rettv != NULL 1132&& !(rettv -> v_type == VAR_LIST && rettv -> vval .v_list != NULL ) 1133&& !(rettv -> v_type == VAR_BLOB && rettv -> vval .v_blob != NULL )) { 1134if (!quiet ) { 1135emsg (_ ("E709: [:] requires a List or Blob value" )); 1136 } 1137 gotodone ; 1138 } 1139p = skipwhite (p + 1 ); 1140if (* p == ']' ) { 1141lp -> ll_empty2 = true; 1142 }else { 1143lp -> ll_empty2 = false; 1144// Recursive! 1145if (eval1 (& p ,& var2 ,& EVALARG_EVALUATE )== FAIL ) { 1146 gotodone ; 1147 } 1148if (!tv_check_str (& var2 )) { 1149// Not a number or string. 1150 gotodone ; 1151 } 1152 } 1153lp -> ll_range = true; 1154 }else { 1155lp -> ll_range = false; 1156 } 1157 1158if (* p != ']' ) { 1159if (!quiet ) { 1160emsg (_ (e_missbrac )); 1161 } 1162 gotodone ; 1163 } 1164 1165// Skip to past ']'. 1166p ++ ; 1167 } 1168 1169if (lp -> ll_tv -> v_type == VAR_DICT ) { 1170glv_status_T glv_status = get_lval_dict_item (lp ,name ,key ,len ,& p ,& var1 , 1171flags ,unlet ,rettv ); 1172if (glv_status == GLV_FAIL ) { 1173 gotodone ; 1174 } 1175if (glv_status == GLV_STOP ) { 1176break ; 1177 } 1178 }else if (lp -> ll_tv -> v_type == VAR_BLOB ) { 1179if (get_lval_blob (lp ,& var1 ,& var2 ,empty1 ,quiet )== FAIL ) { 1180 gotodone ; 1181 } 1182break ; 1183 }else { 1184if (get_lval_list (lp ,& var1 ,& var2 ,empty1 ,flags ,quiet )== FAIL ) { 1185 gotodone ; 1186 } 1187 } 1188 1189tv_clear (& var1 ); 1190tv_clear (& var2 ); 1191var1 .v_type = VAR_UNKNOWN ; 1192var2 .v_type = VAR_UNKNOWN ; 1193 } 1194 1195rc = OK ; 1196 1197done : 1198tv_clear (& var1 ); 1199tv_clear (& var2 ); 1200return rc == OK ?p :NULL ; 1201} 1202 1203/// Get an lvalue 1204/// 1205/// Lvalue may be 1206/// - variable: "name", "na{me}" 1207/// - dictionary item: "dict.key", "dict['key']" 1208/// - list item: "list[expr]" 1209/// - list slice: "list[expr:expr]" 1210/// 1211/// Indexing only works if trying to use it with an existing List or Dictionary. 1212/// 1213/// @param[in] name Name to parse. 1214/// @param rettv Pointer to the value to be assigned or NULL. 1215/// @param[out] lp Lvalue definition. When evaluation errors occur `->ll_name` 1216/// is NULL. 1217/// @param[in] unlet True if using `:unlet`. This results in slightly 1218/// different behaviour when something is wrong; must end in 1219/// space or cmd separator. 1220/// @param[in] skip True when skipping. 1221/// @param[in] flags @see GetLvalFlags. 1222/// @param[in] fne_flags Flags for find_name_end(). 1223/// 1224/// @return A pointer to just after the name, including indexes. Returns NULL 1225/// for a parsing error, but it is still needed to free items in lp. 1226char * get_lval (char * const name ,typval_T * const rettv ,lval_T * const lp ,const bool unlet , 1227const bool skip ,const int flags ,const int fne_flags ) 1228FUNC_ATTR_NONNULL_ARG (1 ,3 ) 1229{ 1230int quiet = flags & GLV_QUIET ; 1231 1232// Clear everything in "lp". 1233CLEAR_POINTER (lp ); 1234 1235if (skip ) { 1236// When skipping just find the end of the name. 1237lp -> ll_name = name ; 1238return (char * )find_name_end (name ,NULL ,NULL ,FNE_INCL_BR |fne_flags ); 1239 } 1240 1241// Find the end of the name. 1242char * expr_start ; 1243char * expr_end ; 1244char * p = (char * )find_name_end (name , (const char ** )& expr_start , 1245 (const char ** )& expr_end , 1246fne_flags ); 1247if (expr_start != NULL ) { 1248// Don't expand the name when we already know there is an error. 1249if (unlet && !ascii_iswhite (* p )&& !ends_excmd (* p ) 1250&& * p != '[' && * p != '.' ) { 1251semsg (_ (e_trailing_arg ),p ); 1252return NULL ; 1253 } 1254 1255lp -> ll_exp_name = make_expanded_name (name ,expr_start ,expr_end ,p ); 1256lp -> ll_name = lp -> ll_exp_name ; 1257if (lp -> ll_exp_name == NULL ) { 1258// Report an invalid expression in braces, unless the 1259// expression evaluation has been cancelled due to an 1260// aborting error, an interrupt, or an exception. 1261if (!aborting ()&& !quiet ) { 1262emsg_severe = true; 1263semsg (_ (e_invarg2 ),name ); 1264return NULL ; 1265 } 1266lp -> ll_name_len = 0 ; 1267 }else { 1268lp -> ll_name_len = strlen (lp -> ll_name ); 1269 } 1270 }else { 1271lp -> ll_name = name ; 1272lp -> ll_name_len = (size_t )(p - lp -> ll_name ); 1273 } 1274 1275// Without [idx] or .key we are done. 1276if ((* p != '[' && * p != '.' )|| lp -> ll_name == NULL ) { 1277return p ; 1278 } 1279 1280hashtab_T * ht = NULL ; 1281 1282// Only pass &ht when we would write to the variable, it prevents autoload 1283// as well. 1284dictitem_T * v = find_var (lp -> ll_name ,lp -> ll_name_len , 1285 (flags & GLV_READ_ONLY ) ?NULL :& ht , 1286flags & GLV_NO_AUTOLOAD ); 1287if (v == NULL && !quiet ) { 1288semsg (_ ("E121: Undefined variable: %.*s" ), 1289 (int )lp -> ll_name_len ,lp -> ll_name ); 1290 } 1291if (v == NULL ) { 1292return NULL ; 1293 } 1294 1295lp -> ll_tv = & v -> di_tv ; 1296 1297if (tv_is_luafunc (lp -> ll_tv )) { 1298// For v:lua just return a pointer to the "." after the "v:lua". 1299// If the caller is trans_function_name() it will check for a Lua function name. 1300return p ; 1301 } 1302 1303// If the next character is a "." or a "[", then process the subitem. 1304p = get_lval_subscript (lp ,p ,name ,rettv ,ht ,v ,unlet ,flags ); 1305if (p == NULL ) { 1306return NULL ; 1307 } 1308 1309lp -> ll_name_len = (size_t )(p - lp -> ll_name ); 1310return p ; 1311} 1312 1313/// Clear lval "lp" that was filled by get_lval(). 1314void clear_lval (lval_T * lp ) 1315{ 1316xfree (lp -> ll_exp_name ); 1317xfree (lp -> ll_newkey ); 1318} 1319 1320/// Set a variable that was parsed by get_lval() to "rettv". 1321/// 1322/// @param endp points to just after the parsed name. 1323/// @param op NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=", 1324/// "%" for "%=", "." for ".=" or "=" for "=". 1325void set_var_lval (lval_T * lp ,char * endp ,typval_T * rettv ,bool copy ,const bool is_const , 1326const char * op ) 1327{ 1328int cc ; 1329dictitem_T * di ; 1330 1331if (lp -> ll_tv == NULL ) { 1332cc = (uint8_t )(* endp ); 1333* endp = NUL ; 1334if (lp -> ll_blob != NULL ) { 1335if (op != NULL && * op != '=' ) { 1336semsg (_ (e_letwrong ),op ); 1337return ; 1338 } 1339if (value_check_lock (lp -> ll_blob -> bv_lock ,lp -> ll_name ,TV_CSTRING )) { 1340return ; 1341 } 1342 1343if (lp -> ll_range && rettv -> v_type == VAR_BLOB ) { 1344if (lp -> ll_empty2 ) { 1345lp -> ll_n2 = tv_blob_len (lp -> ll_blob )- 1 ; 1346 } 1347 1348if (tv_blob_set_range (lp -> ll_blob ,lp -> ll_n1 ,lp -> ll_n2 ,rettv )== FAIL ) { 1349return ; 1350 } 1351 }else { 1352bool error = false; 1353const varnumber_T val = tv_get_number_chk (rettv ,& error ); 1354if (!error ) { 1355if (val < 0 || val > 255 ) { 1356semsg (_ (e_invalid_value_for_blob_nr ),val ); 1357 }else { 1358tv_blob_set_append (lp -> ll_blob ,lp -> ll_n1 , (uint8_t )val ); 1359 } 1360 } 1361 } 1362 }else if (op != NULL && * op != '=' ) { 1363typval_T tv ; 1364 1365if (is_const ) { 1366emsg (_ (e_cannot_mod )); 1367* endp = (char )cc ; 1368return ; 1369 } 1370 1371// handle +=, -=, *=, /=, %= and .= 1372di = NULL ; 1373if (eval_variable (lp -> ll_name , (int )lp -> ll_name_len , 1374& tv ,& di , true, false)== OK ) { 1375if ((di == NULL 1376|| (!var_check_ro (di -> di_flags ,lp -> ll_name ,TV_CSTRING ) 1377&& !tv_check_lock (& di -> di_tv ,lp -> ll_name ,TV_CSTRING ))) 1378&& eexe_mod_op (& tv ,rettv ,op )== OK ) { 1379set_var (lp -> ll_name ,lp -> ll_name_len ,& tv , false); 1380 } 1381tv_clear (& tv ); 1382 } 1383 }else { 1384set_var_const (lp -> ll_name ,lp -> ll_name_len ,rettv ,copy ,is_const ); 1385 } 1386* endp = (char )cc ; 1387 }else if (value_check_lock (lp -> ll_newkey == NULL 1388 ?lp -> ll_tv -> v_lock 1389 :lp -> ll_tv -> vval .v_dict -> dv_lock , 1390lp -> ll_name ,TV_CSTRING )) { 1391// Skip 1392 }else if (lp -> ll_range ) { 1393if (is_const ) { 1394emsg (_ ("E996: Cannot lock a range" )); 1395return ; 1396 } 1397 1398tv_list_assign_range (lp -> ll_list ,rettv -> vval .v_list , 1399lp -> ll_n1 ,lp -> ll_n2 ,lp -> ll_empty2 ,op ,lp -> ll_name ); 1400 }else { 1401typval_T oldtv = TV_INITIAL_VALUE ; 1402dict_T * dict = lp -> ll_dict ; 1403bool watched = tv_dict_is_watched (dict ); 1404 1405if (is_const ) { 1406emsg (_ ("E996: Cannot lock a list or dict" )); 1407return ; 1408 } 1409 1410// Assign to a List or Dictionary item. 1411if (lp -> ll_newkey != NULL ) { 1412if (op != NULL && * op != '=' ) { 1413semsg (_ (e_dictkey ),lp -> ll_newkey ); 1414return ; 1415 } 1416if (tv_dict_wrong_func_name (lp -> ll_tv -> vval .v_dict ,rettv ,lp -> ll_newkey )) { 1417return ; 1418 } 1419 1420// Need to add an item to the Dictionary. 1421di = tv_dict_item_alloc (lp -> ll_newkey ); 1422if (tv_dict_add (lp -> ll_tv -> vval .v_dict ,di )== FAIL ) { 1423xfree (di ); 1424return ; 1425 } 1426lp -> ll_tv = & di -> di_tv ; 1427 }else { 1428if (watched ) { 1429tv_copy (lp -> ll_tv ,& oldtv ); 1430 } 1431 1432if (op != NULL && * op != '=' ) { 1433eexe_mod_op (lp -> ll_tv ,rettv ,op ); 1434 gotonotify ; 1435 }else { 1436tv_clear (lp -> ll_tv ); 1437 } 1438 } 1439 1440// Assign the value to the variable or list item. 1441if (copy ) { 1442tv_copy (rettv ,lp -> ll_tv ); 1443 }else { 1444* lp -> ll_tv = * rettv ; 1445lp -> ll_tv -> v_lock = VAR_UNLOCKED ; 1446tv_init (rettv ); 1447 } 1448 1449notify : 1450if (watched ) { 1451if (oldtv .v_type == VAR_UNKNOWN ) { 1452assert (lp -> ll_newkey != NULL ); 1453tv_dict_watcher_notify (dict ,lp -> ll_newkey ,lp -> ll_tv ,NULL ); 1454 }else { 1455dictitem_T * di_ = lp -> ll_di ; 1456assert (di_ -> di_key != NULL ); 1457tv_dict_watcher_notify (dict ,di_ -> di_key ,lp -> ll_tv ,& oldtv ); 1458tv_clear (& oldtv ); 1459 } 1460 } 1461 } 1462} 1463 1464/// Evaluate the expression used in a ":for var in expr" command. 1465/// "arg" points to "var". 1466/// 1467/// @param[out] *errp set to true for an error, false otherwise; 1468/// 1469/// @return a pointer that holds the info. Null when there is an error. 1470void * eval_for_line (const char * arg ,bool * errp ,exarg_T * eap ,evalarg_T * const evalarg ) 1471{ 1472forinfo_T * fi = xcalloc (1 ,sizeof (forinfo_T )); 1473typval_T tv ; 1474list_T * l ; 1475const bool skip = !(evalarg -> eval_flags & EVAL_EVALUATE ); 1476 1477* errp = true;// Default: there is an error. 1478 1479const char * expr = skip_var_list (arg ,& fi -> fi_varcount ,& fi -> fi_semicolon , false); 1480if (expr == NULL ) { 1481return fi ; 1482 } 1483 1484expr = skipwhite (expr ); 1485if (expr [0 ]!= 'i' || expr [1 ]!= 'n' 1486|| !(expr [2 ]== NUL || ascii_iswhite (expr [2 ]))) { 1487emsg (_ ("E690: Missing \"in\" after :for" )); 1488return fi ; 1489 } 1490 1491if (skip ) { 1492emsg_skip ++ ; 1493 } 1494expr = skipwhite (expr + 2 ); 1495if (eval0 ((char * )expr ,& tv ,eap ,evalarg )== OK ) { 1496* errp = false; 1497if (!skip ) { 1498if (tv .v_type == VAR_LIST ) { 1499l = tv .vval .v_list ; 1500if (l == NULL ) { 1501// a null list is like an empty list: do nothing 1502tv_clear (& tv ); 1503 }else { 1504// No need to increment the refcount, it's already set for 1505// the list being used in "tv". 1506fi -> fi_list = l ; 1507tv_list_watch_add (l ,& fi -> fi_lw ); 1508fi -> fi_lw .lw_item = tv_list_first (l ); 1509 } 1510 }else if (tv .v_type == VAR_BLOB ) { 1511fi -> fi_bi = 0 ; 1512if (tv .vval .v_blob != NULL ) { 1513typval_T btv ; 1514 1515// Make a copy, so that the iteration still works when the 1516// blob is changed. 1517tv_blob_copy (tv .vval .v_blob ,& btv ); 1518fi -> fi_blob = btv .vval .v_blob ; 1519 } 1520tv_clear (& tv ); 1521 }else if (tv .v_type == VAR_STRING ) { 1522fi -> fi_byte_idx = 0 ; 1523fi -> fi_string = tv .vval .v_string ; 1524tv .vval .v_string = NULL ; 1525if (fi -> fi_string == NULL ) { 1526fi -> fi_string = xstrdup ("" ); 1527 } 1528 }else { 1529emsg (_ (e_string_list_or_blob_required )); 1530tv_clear (& tv ); 1531 } 1532 } 1533 } 1534if (skip ) { 1535emsg_skip -- ; 1536 } 1537 1538return fi ; 1539} 1540 1541/// Use the first item in a ":for" list. Advance to the next. 1542/// Assign the values to the variable (list). "arg" points to the first one. 1543/// 1544/// @return true when a valid item was found, false when at end of list or 1545/// something wrong. 1546bool next_for_item (void * fi_void ,char * arg ) 1547{ 1548forinfo_T * fi = (forinfo_T * )fi_void ; 1549 1550if (fi -> fi_blob != NULL ) { 1551if (fi -> fi_bi >=tv_blob_len (fi -> fi_blob )) { 1552return false; 1553 } 1554typval_T tv ; 1555tv .v_type = VAR_NUMBER ; 1556tv .v_lock = VAR_FIXED ; 1557tv .vval .v_number = tv_blob_get (fi -> fi_blob ,fi -> fi_bi ); 1558fi -> fi_bi ++ ; 1559return ex_let_vars (arg ,& tv , true,fi -> fi_semicolon ,fi -> fi_varcount , false,NULL )== OK ; 1560 } 1561 1562if (fi -> fi_string != NULL ) { 1563const int len = utfc_ptr2len (fi -> fi_string + fi -> fi_byte_idx ); 1564if (len == 0 ) { 1565return false; 1566 } 1567typval_T tv ; 1568tv .v_type = VAR_STRING ; 1569tv .v_lock = VAR_FIXED ; 1570tv .vval .v_string = xmemdupz (fi -> fi_string + fi -> fi_byte_idx , (size_t )len ); 1571fi -> fi_byte_idx += len ; 1572const int result 1573= ex_let_vars (arg ,& tv , true,fi -> fi_semicolon ,fi -> fi_varcount , false,NULL )== OK ; 1574xfree (tv .vval .v_string ); 1575return result ; 1576 } 1577 1578listitem_T * item = fi -> fi_lw .lw_item ; 1579if (item == NULL ) { 1580return false; 1581 } 1582fi -> fi_lw .lw_item = TV_LIST_ITEM_NEXT (fi -> fi_list ,item ); 1583return (ex_let_vars (arg ,TV_LIST_ITEM_TV (item ), true, 1584fi -> fi_semicolon ,fi -> fi_varcount , false,NULL )== OK ); 1585} 1586 1587/// Free the structure used to store info used by ":for". 1588void free_for_info (void * fi_void ) 1589{ 1590forinfo_T * fi = (forinfo_T * )fi_void ; 1591 1592if (fi == NULL ) { 1593return ; 1594 } 1595if (fi -> fi_list != NULL ) { 1596tv_list_watch_remove (fi -> fi_list ,& fi -> fi_lw ); 1597tv_list_unref (fi -> fi_list ); 1598 }else if (fi -> fi_blob != NULL ) { 1599tv_blob_unref (fi -> fi_blob ); 1600 }else { 1601xfree (fi -> fi_string ); 1602 } 1603xfree (fi ); 1604} 1605 1606void set_context_for_expression (expand_T * xp ,char * arg ,cmdidx_T cmdidx ) 1607FUNC_ATTR_NONNULL_ALL 1608{ 1609bool got_eq = false; 1610 1611if (cmdidx == CMD_let || cmdidx == CMD_const ) { 1612xp -> xp_context = EXPAND_USER_VARS ; 1613if (strpbrk (arg ,"\"'+-*/%.=!?~|&$([<>,#" )== NULL ) { 1614// ":let var1 var2 ...": find last space. 1615for (char * p = arg + strlen (arg );p >=arg ;) { 1616xp -> xp_pattern = p ; 1617MB_PTR_BACK (arg ,p ); 1618if (ascii_iswhite (* p )) { 1619break ; 1620 } 1621 } 1622return ; 1623 } 1624 }else { 1625xp -> xp_context = cmdidx == CMD_call ?EXPAND_FUNCTIONS 1626 :EXPAND_EXPRESSION ; 1627 } 1628while ((xp -> xp_pattern = strpbrk (arg ,"\"'+-*/%.=!?~|&$([<>,#" ))!= NULL ) { 1629int c = (uint8_t )(* xp -> xp_pattern ); 1630if (c == '&' ) { 1631c = (uint8_t )xp -> xp_pattern [1 ]; 1632if (c == '&' ) { 1633xp -> xp_pattern ++ ; 1634xp -> xp_context = cmdidx != CMD_let || got_eq 1635 ?EXPAND_EXPRESSION :EXPAND_NOTHING ; 1636 }else if (c != ' ' ) { 1637xp -> xp_context = EXPAND_SETTINGS ; 1638if ((c == 'l' || c == 'g' )&& xp -> xp_pattern [2 ]== ':' ) { 1639xp -> xp_pattern += 2 ; 1640 } 1641 } 1642 }else if (c == '$' ) { 1643// environment variable 1644xp -> xp_context = EXPAND_ENV_VARS ; 1645 }else if (c == '=' ) { 1646got_eq = true; 1647xp -> xp_context = EXPAND_EXPRESSION ; 1648 }else if (c == '#' 1649&& xp -> xp_context == EXPAND_EXPRESSION ) { 1650// Autoload function/variable contains '#' 1651break ; 1652 }else if ((c == '<' || c == '#' ) 1653&& xp -> xp_context == EXPAND_FUNCTIONS 1654&& vim_strchr (xp -> xp_pattern ,'(' )== NULL ) { 1655// Function name can start with "<SNR>" and contain '#'. 1656break ; 1657 }else if (cmdidx != CMD_let || got_eq ) { 1658if (c == '"' ) {// string 1659while ((c = (uint8_t )(*++ xp -> xp_pattern ))!= NUL && c != '"' ) { 1660if (c == '\\' && xp -> xp_pattern [1 ]!= NUL ) { 1661xp -> xp_pattern ++ ; 1662 } 1663 } 1664xp -> xp_context = EXPAND_NOTHING ; 1665 }else if (c == '\'' ) {// literal string 1666// Trick: '' is like stopping and starting a literal string. 1667while ((c = (uint8_t )(*++ xp -> xp_pattern ))!= NUL && c != '\'' ) {} 1668xp -> xp_context = EXPAND_NOTHING ; 1669 }else if (c == '|' ) { 1670if (xp -> xp_pattern [1 ]== '|' ) { 1671xp -> xp_pattern ++ ; 1672xp -> xp_context = EXPAND_EXPRESSION ; 1673 }else { 1674xp -> xp_context = EXPAND_COMMANDS ; 1675 } 1676 }else { 1677xp -> xp_context = EXPAND_EXPRESSION ; 1678 } 1679 }else { 1680// Doesn't look like something valid, expand as an expression 1681// anyway. 1682xp -> xp_context = EXPAND_EXPRESSION ; 1683 } 1684arg = xp -> xp_pattern ; 1685if (* arg != NUL ) { 1686while ((c = (uint8_t )(*++ arg ))!= NUL && (c == ' ' || c == '\t' )) {} 1687 } 1688 } 1689 1690// ":exe one two" completes "two" 1691if (cmd_has_expr_args (cmdidx )&& xp -> xp_context == EXPAND_EXPRESSION ) { 1692while (true) { 1693char * const n = skiptowhite (arg ); 1694 1695if (n == arg || ascii_iswhite_or_nul (* skipwhite (n ))) { 1696break ; 1697 } 1698arg = skipwhite (n ); 1699 } 1700 } 1701 1702xp -> xp_pattern = arg ; 1703} 1704 1705/// Does not use 'cpo' and always uses 'magic'. 1706/// 1707/// @return true if "pat" matches "text". 1708int pattern_match (const char * pat ,const char * text ,bool ic ) 1709{ 1710int matches = 0 ; 1711regmatch_T regmatch ; 1712 1713// avoid 'l' flag in 'cpoptions' 1714char * save_cpo = p_cpo ; 1715p_cpo = empty_string_option ; 1716regmatch .regprog = vim_regcomp (pat ,RE_MAGIC + RE_STRING ); 1717if (regmatch .regprog != NULL ) { 1718regmatch .rm_ic = ic ; 1719matches = vim_regexec_nl (& regmatch ,text ,0 ); 1720vim_regfree (regmatch .regprog ); 1721 } 1722p_cpo = save_cpo ; 1723return matches ; 1724} 1725 1726/// Handle a name followed by "(". Both for just "name(arg)" and for 1727/// "expr->name(arg)". 1728/// 1729/// @param arg Points to "(", will be advanced 1730/// @param basetv "expr" for "expr->name(arg)" 1731/// 1732/// @return OK or FAIL. 1733static int eval_func (char ** const arg ,evalarg_T * const evalarg ,char * const name , 1734const int name_len ,typval_T * const rettv ,const int flags , 1735typval_T * const basetv ) 1736FUNC_ATTR_NONNULL_ARG (1 ,3 ,5 ) 1737{ 1738const bool evaluate = flags & EVAL_EVALUATE ; 1739char * s = name ; 1740int len = name_len ; 1741bool found_var = false; 1742 1743if (!evaluate ) { 1744check_vars (s , (size_t )len ); 1745 } 1746 1747// If "s" is the name of a variable of type VAR_FUNC 1748// use its contents. 1749partial_T * partial ; 1750s = deref_func_name (s ,& len ,& partial , !evaluate ,& found_var ); 1751 1752// Need to make a copy, in case evaluating the arguments makes 1753// the name invalid. 1754s = xmemdupz (s , (size_t )len ); 1755 1756// Invoke the function. 1757funcexe_T funcexe = FUNCEXE_INIT ; 1758funcexe .fe_firstline = curwin -> w_cursor .lnum ; 1759funcexe .fe_lastline = curwin -> w_cursor .lnum ; 1760funcexe .fe_evaluate = evaluate ; 1761funcexe .fe_partial = partial ; 1762funcexe .fe_basetv = basetv ; 1763funcexe .fe_found_var = found_var ; 1764int ret = get_func_tv (s ,len ,rettv ,arg ,evalarg ,& funcexe ); 1765 1766xfree (s ); 1767 1768// If evaluate is false rettv->v_type was not set in 1769// get_func_tv, but it's needed in handle_subscript() to parse 1770// what follows. So set it here. 1771if (rettv -> v_type == VAR_UNKNOWN && !evaluate && ** arg == '(' ) { 1772rettv -> vval .v_string = (char * )tv_empty_string ; 1773rettv -> v_type = VAR_FUNC ; 1774 } 1775 1776// Stop the expression evaluation when immediately 1777// aborting on error, or when an interrupt occurred or 1778// an exception was thrown but not caught. 1779if (evaluate && aborting ()) { 1780if (ret == OK ) { 1781tv_clear (rettv ); 1782 } 1783ret = FAIL ; 1784 } 1785return ret ; 1786} 1787 1788/// After using "evalarg" filled from "eap": free the memory. 1789void clear_evalarg (evalarg_T * evalarg ,exarg_T * eap ) 1790{ 1791if (evalarg == NULL ) { 1792return ; 1793 } 1794 1795if (evalarg -> eval_tofree != NULL ) { 1796if (eap != NULL ) { 1797// We may need to keep the original command line, e.g. for 1798// ":let" it has the variable names. But we may also need the 1799// new one, "nextcmd" points into it. Keep both. 1800xfree (eap -> cmdline_tofree ); 1801eap -> cmdline_tofree = * eap -> cmdlinep ; 1802* eap -> cmdlinep = evalarg -> eval_tofree ; 1803 }else { 1804xfree (evalarg -> eval_tofree ); 1805 } 1806evalarg -> eval_tofree = NULL ; 1807 } 1808} 1809 1810/// The "eval" functions have an "evalarg" argument: When NULL or 1811/// "evalarg->eval_flags" does not have EVAL_EVALUATE, then the argument is only 1812/// parsed but not executed. The functions may return OK, but the rettv will be 1813/// of type VAR_UNKNOWN. The functions still returns FAIL for a syntax error. 1814 1815/// Handle zero level expression. 1816/// This calls eval1() and handles error message and nextcmd. 1817/// Put the result in "rettv" when returning OK and "evaluate" is true. 1818/// 1819/// @param evalarg can be NULL, &EVALARG_EVALUATE or a pointer. 1820/// 1821/// @return OK or FAIL. 1822int eval0 (char * arg ,typval_T * rettv ,exarg_T * eap ,evalarg_T * const evalarg ) 1823{ 1824const int did_emsg_before = did_emsg ; 1825const int called_emsg_before = called_emsg ; 1826bool end_error = false; 1827 1828char * p = skipwhite (arg ); 1829int ret = eval1 (& p ,rettv ,evalarg ); 1830 1831if (ret != FAIL ) { 1832end_error = !ends_excmd (* p ); 1833 } 1834if (ret == FAIL || end_error ) { 1835if (ret != FAIL ) { 1836tv_clear (rettv ); 1837 } 1838// Report the invalid expression unless the expression evaluation has 1839// been cancelled due to an aborting error, an interrupt, or an 1840// exception, or we already gave a more specific error. 1841// Also check called_emsg for when using assert_fails(). 1842if (!aborting () 1843&& did_emsg == did_emsg_before 1844&& called_emsg == called_emsg_before ) { 1845if (end_error ) { 1846semsg (_ (e_trailing_arg ),p ); 1847 }else { 1848semsg (_ (e_invexpr2 ),arg ); 1849 } 1850 } 1851 1852if (eap != NULL && p != NULL ) { 1853// Some of the expression may not have been consumed. 1854// Only execute a next command if it cannot be a "||" operator. 1855// The next command may be "catch". 1856char * nextcmd = check_nextcmd (p ); 1857if (nextcmd != NULL && * nextcmd != '|' ) { 1858eap -> nextcmd = nextcmd ; 1859 } 1860 } 1861return FAIL ; 1862 } 1863 1864if (eap != NULL ) { 1865eap -> nextcmd = check_nextcmd (p ); 1866 } 1867 1868return ret ; 1869} 1870 1871/// If "arg" is a simple function call without arguments then call it and return 1872/// the result. Otherwise return NOTDONE. 1873int may_call_simple_func (const char * arg ,typval_T * rettv ) 1874{ 1875const char * parens = strstr (arg ,"()" ); 1876int r = NOTDONE ; 1877 1878// If the expression is "FuncName()" then we can skip a lot of overhead. 1879if (parens != NULL && * skipwhite (parens + 2 )== NUL ) { 1880if (strnequal (arg ,"v:lua." ,6 )) { 1881const char * p = arg + 6 ; 1882if (p != parens && skip_luafunc_name (p )== parens ) { 1883r = call_simple_luafunc (p , (size_t )(parens - p ),rettv ); 1884 } 1885 }else { 1886const char * p = strncmp (arg ,"<SNR>" ,5 )== 0 ?skipdigits (arg + 5 ) :arg ; 1887if (to_name_end (p , true)== parens ) { 1888r = call_simple_func (arg , (size_t )(parens - arg ),rettv ); 1889 } 1890 } 1891 } 1892return r ; 1893} 1894 1895/// Handle zero level expression with optimization for a simple function call. 1896/// Same arguments and return value as eval0(). 1897static int eval0_simple_funccal (char * arg ,typval_T * rettv ,exarg_T * eap ,evalarg_T * const evalarg ) 1898{ 1899int r = may_call_simple_func (arg ,rettv ); 1900 1901if (r == NOTDONE ) { 1902r = eval0 (arg ,rettv ,eap ,evalarg ); 1903 } 1904return r ; 1905} 1906 1907/// Handle top level expression: 1908/// expr2 ? expr1 : expr1 1909/// expr2 ?? expr1 1910/// 1911/// "arg" must point to the first non-white of the expression. 1912/// "arg" is advanced to the next non-white after the recognized expression. 1913/// 1914/// @return OK or FAIL. 1915int eval1 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ) 1916{ 1917CLEAR_POINTER (rettv ); 1918 1919// Get the first variable. 1920if (eval2 (arg ,rettv ,evalarg )== FAIL ) { 1921return FAIL ; 1922 } 1923 1924char * p = * arg ; 1925if (* p == '?' ) { 1926const bool op_falsy = p [1 ]== '?' ; 1927evalarg_T * evalarg_used = evalarg ; 1928evalarg_T local_evalarg ; 1929if (evalarg == NULL ) { 1930local_evalarg = (evalarg_T ){ .eval_flags = 0 }; 1931evalarg_used = & local_evalarg ; 1932 } 1933const int orig_flags = evalarg_used -> eval_flags ; 1934const bool evaluate = evalarg_used -> eval_flags & EVAL_EVALUATE ; 1935 1936bool result = false; 1937if (evaluate ) { 1938bool error = false; 1939 1940if (op_falsy ) { 1941result = tv2bool (rettv ); 1942 }else if (tv_get_number_chk (rettv ,& error )!= 0 ) { 1943result = true; 1944 } 1945if (error || !op_falsy || !result ) { 1946tv_clear (rettv ); 1947 } 1948if (error ) { 1949return FAIL ; 1950 } 1951 } 1952 1953// Get the second variable. Recursive! 1954if (op_falsy ) { 1955 (* arg )++ ; 1956 } 1957* arg = skipwhite (* arg + 1 ); 1958evalarg_used -> eval_flags = (op_falsy ? !result :result ) 1959 ?orig_flags : (orig_flags & ~EVAL_EVALUATE ); 1960typval_T var2 ; 1961if (eval1 (arg ,& var2 ,evalarg_used )== FAIL ) { 1962evalarg_used -> eval_flags = orig_flags ; 1963return FAIL ; 1964 } 1965if (!op_falsy || !result ) { 1966* rettv = var2 ; 1967 } 1968 1969if (!op_falsy ) { 1970// Check for the ":". 1971p = * arg ; 1972if (* p != ':' ) { 1973emsg (_ ("E109: Missing ':' after '?'" )); 1974if (evaluate && result ) { 1975tv_clear (rettv ); 1976 } 1977evalarg_used -> eval_flags = orig_flags ; 1978return FAIL ; 1979 } 1980 1981// Get the third variable. Recursive! 1982* arg = skipwhite (* arg + 1 ); 1983evalarg_used -> eval_flags = !result ?orig_flags : (orig_flags & ~EVAL_EVALUATE ); 1984if (eval1 (arg ,& var2 ,evalarg_used )== FAIL ) { 1985if (evaluate && result ) { 1986tv_clear (rettv ); 1987 } 1988evalarg_used -> eval_flags = orig_flags ; 1989return FAIL ; 1990 } 1991if (evaluate && !result ) { 1992* rettv = var2 ; 1993 } 1994 } 1995 1996if (evalarg == NULL ) { 1997clear_evalarg (& local_evalarg ,NULL ); 1998 }else { 1999evalarg -> eval_flags = orig_flags ; 2000 } 2001 } 2002 2003return OK ; 2004} 2005 2006/// Handle first level expression: 2007/// expr2 || expr2 || expr2 logical OR 2008/// 2009/// "arg" must point to the first non-white of the expression. 2010/// "arg" is advanced to the next non-white after the recognized expression. 2011/// 2012/// @return OK or FAIL. 2013static int eval2 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ) 2014{ 2015// Get the first variable. 2016if (eval3 (arg ,rettv ,evalarg )== FAIL ) { 2017return FAIL ; 2018 } 2019 2020// Handle the "||" operator. 2021char * p = * arg ; 2022if (p [0 ]== '|' && p [1 ]== '|' ) { 2023evalarg_T * evalarg_used = evalarg ; 2024evalarg_T local_evalarg ; 2025if (evalarg == NULL ) { 2026local_evalarg = (evalarg_T ){ .eval_flags = 0 }; 2027evalarg_used = & local_evalarg ; 2028 } 2029const int orig_flags = evalarg_used -> eval_flags ; 2030const bool evaluate = evalarg_used -> eval_flags & EVAL_EVALUATE ; 2031 2032bool result = false; 2033 2034if (evaluate ) { 2035bool error = false; 2036if (tv_get_number_chk (rettv ,& error )!= 0 ) { 2037result = true; 2038 } 2039tv_clear (rettv ); 2040if (error ) { 2041return FAIL ; 2042 } 2043 } 2044 2045// Repeat until there is no following "||". 2046while (p [0 ]== '|' && p [1 ]== '|' ) { 2047// Get the second variable. 2048* arg = skipwhite (* arg + 2 ); 2049evalarg_used -> eval_flags = !result ?orig_flags : (orig_flags & ~EVAL_EVALUATE ); 2050typval_T var2 ; 2051if (eval3 (arg ,& var2 ,evalarg_used )== FAIL ) { 2052return FAIL ; 2053 } 2054 2055// Compute the result. 2056if (evaluate && !result ) { 2057bool error = false; 2058if (tv_get_number_chk (& var2 ,& error )!= 0 ) { 2059result = true; 2060 } 2061tv_clear (& var2 ); 2062if (error ) { 2063return FAIL ; 2064 } 2065 } 2066if (evaluate ) { 2067rettv -> v_type = VAR_NUMBER ; 2068rettv -> vval .v_number = result ; 2069 } 2070 2071p = * arg ; 2072 } 2073 2074if (evalarg == NULL ) { 2075clear_evalarg (& local_evalarg ,NULL ); 2076 }else { 2077evalarg -> eval_flags = orig_flags ; 2078 } 2079 } 2080 2081return OK ; 2082} 2083 2084/// Handle second level expression: 2085/// expr3 && expr3 && expr3 logical AND 2086/// 2087/// @param arg must point to the first non-white of the expression. 2088/// `arg` is advanced to the next non-white after the recognized expression. 2089/// 2090/// @return OK or FAIL. 2091static int eval3 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ) 2092{ 2093// Get the first variable. 2094if (eval4 (arg ,rettv ,evalarg )== FAIL ) { 2095return FAIL ; 2096 } 2097 2098char * p = * arg ; 2099// Handle the "&&" operator. 2100if (p [0 ]== '&' && p [1 ]== '&' ) { 2101evalarg_T * evalarg_used = evalarg ; 2102evalarg_T local_evalarg ; 2103if (evalarg == NULL ) { 2104local_evalarg = (evalarg_T ){ .eval_flags = 0 }; 2105evalarg_used = & local_evalarg ; 2106 } 2107const int orig_flags = evalarg_used -> eval_flags ; 2108const bool evaluate = evalarg_used -> eval_flags & EVAL_EVALUATE ; 2109 2110bool result = true; 2111 2112if (evaluate ) { 2113bool error = false; 2114if (tv_get_number_chk (rettv ,& error )== 0 ) { 2115result = false; 2116 } 2117tv_clear (rettv ); 2118if (error ) { 2119return FAIL ; 2120 } 2121 } 2122 2123// Repeat until there is no following "&&". 2124while (p [0 ]== '&' && p [1 ]== '&' ) { 2125// Get the second variable. 2126* arg = skipwhite (* arg + 2 ); 2127evalarg_used -> eval_flags = result ?orig_flags : (orig_flags & ~EVAL_EVALUATE ); 2128typval_T var2 ; 2129if (eval4 (arg ,& var2 ,evalarg_used )== FAIL ) { 2130return FAIL ; 2131 } 2132 2133// Compute the result. 2134if (evaluate && result ) { 2135bool error = false; 2136if (tv_get_number_chk (& var2 ,& error )== 0 ) { 2137result = false; 2138 } 2139tv_clear (& var2 ); 2140if (error ) { 2141return FAIL ; 2142 } 2143 } 2144if (evaluate ) { 2145rettv -> v_type = VAR_NUMBER ; 2146rettv -> vval .v_number = result ; 2147 } 2148 2149p = * arg ; 2150 } 2151 2152if (evalarg == NULL ) { 2153clear_evalarg (& local_evalarg ,NULL ); 2154 }else { 2155evalarg -> eval_flags = orig_flags ; 2156 } 2157 } 2158 2159return OK ; 2160} 2161 2162/// Handle third level expression: 2163/// var1 == var2 2164/// var1 =~ var2 2165/// var1 != var2 2166/// var1 !~ var2 2167/// var1 > var2 2168/// var1 >= var2 2169/// var1 < var2 2170/// var1 <= var2 2171/// var1 is var2 2172/// var1 isnot var2 2173/// 2174/// "arg" must point to the first non-white of the expression. 2175/// "arg" is advanced to the next non-white after the recognized expression. 2176/// 2177/// @return OK or FAIL. 2178static int eval4 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ) 2179{ 2180typval_T var2 ; 2181exprtype_T type = EXPR_UNKNOWN ; 2182int len = 2 ; 2183 2184// Get the first variable. 2185if (eval5 (arg ,rettv ,evalarg )== FAIL ) { 2186return FAIL ; 2187 } 2188 2189char * p = * arg ; 2190switch (p [0 ]) { 2191case '=' : 2192if (p [1 ]== '=' ) { 2193type = EXPR_EQUAL ; 2194 }else if (p [1 ]== '~' ) { 2195type = EXPR_MATCH ; 2196 } 2197break ; 2198case '!' : 2199if (p [1 ]== '=' ) { 2200type = EXPR_NEQUAL ; 2201 }else if (p [1 ]== '~' ) { 2202type = EXPR_NOMATCH ; 2203 } 2204break ; 2205case '>' : 2206if (p [1 ]!= '=' ) { 2207type = EXPR_GREATER ; 2208len = 1 ; 2209 }else { 2210type = EXPR_GEQUAL ; 2211 } 2212break ; 2213case '<' : 2214if (p [1 ]!= '=' ) { 2215type = EXPR_SMALLER ; 2216len = 1 ; 2217 }else { 2218type = EXPR_SEQUAL ; 2219 } 2220break ; 2221case 'i' : 2222if (p [1 ]== 's' ) { 2223if (p [2 ]== 'n' && p [3 ]== 'o' && p [4 ]== 't' ) { 2224len = 5 ; 2225 } 2226if (!isalnum ((uint8_t )p [len ])&& p [len ]!= '_' ) { 2227type = len == 2 ?EXPR_IS :EXPR_ISNOT ; 2228 } 2229 } 2230break ; 2231 } 2232 2233// If there is a comparative operator, use it. 2234if (type != EXPR_UNKNOWN ) { 2235bool ic ; 2236// extra question mark appended: ignore case 2237if (p [len ]== '?' ) { 2238ic = true; 2239len ++ ; 2240 }else if (p [len ]== '#' ) {// extra '#' appended: match case 2241ic = false; 2242len ++ ; 2243 }else {// nothing appended: use 'ignorecase' 2244ic = p_ic ; 2245 } 2246 2247// Get the second variable. 2248* arg = skipwhite (p + len ); 2249if (eval5 (arg ,& var2 ,evalarg )== FAIL ) { 2250tv_clear (rettv ); 2251return FAIL ; 2252 } 2253if (evalarg != NULL && (evalarg -> eval_flags & EVAL_EVALUATE )) { 2254const int ret = typval_compare (rettv ,& var2 ,type ,ic ); 2255 2256tv_clear (& var2 ); 2257return ret ; 2258 } 2259 } 2260 2261return OK ; 2262} 2263 2264/// Make a copy of blob "tv1" and append blob "tv2". 2265static void eval_addblob (typval_T * tv1 ,typval_T * tv2 ) 2266{ 2267const blob_T * const b1 = tv1 -> vval .v_blob ; 2268const blob_T * const b2 = tv2 -> vval .v_blob ; 2269blob_T * const b = tv_blob_alloc (); 2270 2271int64_t len1 = tv_blob_len (b1 ); 2272int64_t len2 = tv_blob_len (b2 ); 2273int64_t totallen = len1 + len2 ; 2274 2275if (totallen >=0 && totallen <=INT_MAX ) { 2276ga_grow (& b -> bv_ga , (int )totallen ); 2277if (len1 > 0 ) { 2278memmove ((char * )b -> bv_ga .ga_data ,b1 -> bv_ga .ga_data , (size_t )len1 ); 2279 } 2280if (len2 > 0 ) { 2281memmove ((char * )b -> bv_ga .ga_data + len1 ,b2 -> bv_ga .ga_data , (size_t )len2 ); 2282 } 2283b -> bv_ga .ga_len = (int )totallen ; 2284 } 2285 2286tv_clear (tv1 ); 2287tv_blob_set_ret (tv1 ,b ); 2288} 2289 2290/// Make a copy of list "tv1" and append list "tv2". 2291static int eval_addlist (typval_T * tv1 ,typval_T * tv2 ) 2292{ 2293typval_T var3 ; 2294// Concatenate Lists. 2295if (tv_list_concat (tv1 -> vval .v_list ,tv2 -> vval .v_list ,& var3 )== FAIL ) { 2296tv_clear (tv1 ); 2297tv_clear (tv2 ); 2298return FAIL ; 2299 } 2300tv_clear (tv1 ); 2301* tv1 = var3 ; 2302return OK ; 2303} 2304 2305/// Append string "s2" to the string in "tv1". 2306/// Returns OK if "tv1" was grown in place, FAIL otherwise. 2307int grow_string_tv (typval_T * tv1 ,const char * s2 ) 2308{ 2309if (tv1 -> v_type != VAR_STRING || tv1 -> vval .v_string == NULL ) { 2310return FAIL ; 2311 } 2312 2313size_t len1 = strlen (tv1 -> vval .v_string ); 2314size_t len2 = strlen (s2 ); 2315char * p = xrealloc (tv1 -> vval .v_string ,len1 + len2 + 1 ); 2316 2317memmove (p + len1 ,s2 ,len2 + 1 ); 2318tv1 -> vval .v_string = p ; 2319return OK ; 2320} 2321 2322/// Concatenate strings "tv1" and "tv2" and store the result in "tv1". 2323static int eval_concat_str (typval_T * tv1 ,typval_T * tv2 ) 2324{ 2325char buf1 [NUMBUFLEN ]; 2326char buf2 [NUMBUFLEN ]; 2327// s1 already checked 2328const char * const s1 = tv_get_string_buf (tv1 ,buf1 ); 2329const char * const s2 = tv_get_string_buf_chk (tv2 ,buf2 ); 2330if (s2 == NULL ) {// Type error? 2331tv_clear (tv1 ); 2332tv_clear (tv2 ); 2333return FAIL ; 2334 } 2335 2336// When possible, grow the existing string in place to avoid alloc/free. 2337if (grow_string_tv (tv1 ,s2 )== OK ) { 2338return OK ; 2339 } 2340 2341char * p = concat_str (s1 ,s2 ); 2342tv_clear (tv1 ); 2343tv1 -> v_type = VAR_STRING ; 2344tv1 -> vval .v_string = p ; 2345 2346return OK ; 2347} 2348 2349/// Add or subtract numbers "tv1" and "tv2" and store the result in "tv1". 2350/// The numbers can be whole numbers or floats. 2351static int eval_addsub_number (typval_T * tv1 ,typval_T * tv2 ,int op ) 2352{ 2353bool error = false; 2354varnumber_T n1 ,n2 ; 2355float_T f1 = 0 ; 2356float_T f2 = 0 ; 2357 2358if (tv1 -> v_type == VAR_FLOAT ) { 2359f1 = tv1 -> vval .v_float ; 2360n1 = 0 ; 2361 }else { 2362n1 = tv_get_number_chk (tv1 ,& error ); 2363if (error ) { 2364// This can only happen for "list + non-list" or 2365// "blob + non-blob". For "non-list + ..." or 2366// "something - ...", we returned before evaluating the 2367// 2nd operand. 2368tv_clear (tv1 ); 2369tv_clear (tv2 ); 2370return FAIL ; 2371 } 2372if (tv2 -> v_type == VAR_FLOAT ) { 2373f1 = (float_T )n1 ; 2374 } 2375 } 2376if (tv2 -> v_type == VAR_FLOAT ) { 2377f2 = tv2 -> vval .v_float ; 2378n2 = 0 ; 2379 }else { 2380n2 = tv_get_number_chk (tv2 ,& error ); 2381if (error ) { 2382tv_clear (tv1 ); 2383tv_clear (tv2 ); 2384return FAIL ; 2385 } 2386if (tv1 -> v_type == VAR_FLOAT ) { 2387f2 = (float_T )n2 ; 2388 } 2389 } 2390tv_clear (tv1 ); 2391 2392// If there is a float on either side the result is a float. 2393if (tv1 -> v_type == VAR_FLOAT || tv2 -> v_type == VAR_FLOAT ) { 2394if (op == '+' ) { 2395f1 = f1 + f2 ; 2396 }else { 2397f1 = f1 - f2 ; 2398 } 2399tv1 -> v_type = VAR_FLOAT ; 2400tv1 -> vval .v_float = f1 ; 2401 }else { 2402if (op == '+' ) { 2403n1 = n1 + n2 ; 2404 }else { 2405n1 = n1 - n2 ; 2406 } 2407tv1 -> v_type = VAR_NUMBER ; 2408tv1 -> vval .v_number = n1 ; 2409 } 2410 2411return OK ; 2412} 2413 2414/// Handle fourth level expression: 2415/// + number addition, concatenation of list or blob 2416/// - number subtraction 2417/// . string concatenation 2418/// .. string concatenation 2419/// 2420/// @param arg must point to the first non-white of the expression. 2421/// `arg` is advanced to the next non-white after the recognized expression. 2422/// 2423/// @return OK or FAIL. 2424static int eval5 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ) 2425{ 2426// Get the first variable. 2427if (eval6 (arg ,rettv ,evalarg , false)== FAIL ) { 2428return FAIL ; 2429 } 2430 2431// Repeat computing, until no '+', '-' or '.' is following. 2432while (true) { 2433int op = (uint8_t )(** arg ); 2434bool concat = op == '.' ; 2435if (op != '+' && op != '-' && !concat ) { 2436break ; 2437 } 2438 2439const bool evaluate = evalarg == NULL ?0 : (evalarg -> eval_flags & EVAL_EVALUATE ); 2440if ((op != '+' || (rettv -> v_type != VAR_LIST && rettv -> v_type != VAR_BLOB )) 2441&& (op == '.' || rettv -> v_type != VAR_FLOAT )&& evaluate ) { 2442// For "list + ...", an illegal use of the first operand as 2443// a number cannot be determined before evaluating the 2nd 2444// operand: if this is also a list, all is ok. 2445// For "something . ...", "something - ..." or "non-list + ...", 2446// we know that the first operand needs to be a string or number 2447// without evaluating the 2nd operand. So check before to avoid 2448// side effects after an error. 2449if ((op == '.' && !tv_check_str (rettv ))|| (op != '.' && !tv_check_num (rettv ))) { 2450tv_clear (rettv ); 2451return FAIL ; 2452 } 2453 } 2454 2455// Get the second variable. 2456if (op == '.' && * (* arg + 1 )== '.' ) {// ..string concatenation 2457 (* arg )++ ; 2458 } 2459* arg = skipwhite (* arg + 1 ); 2460typval_T var2 ; 2461if (eval6 (arg ,& var2 ,evalarg ,op == '.' )== FAIL ) { 2462tv_clear (rettv ); 2463return FAIL ; 2464 } 2465 2466if (evaluate ) { 2467// Compute the result. 2468if (op == '.' ) { 2469if (eval_concat_str (rettv ,& var2 )== FAIL ) { 2470return FAIL ; 2471 } 2472 }else if (op == '+' && rettv -> v_type == VAR_BLOB && var2 .v_type == VAR_BLOB ) { 2473eval_addblob (rettv ,& var2 ); 2474 }else if (op == '+' && rettv -> v_type == VAR_LIST && var2 .v_type == VAR_LIST ) { 2475if (eval_addlist (rettv ,& var2 )== FAIL ) { 2476return FAIL ; 2477 } 2478 }else { 2479if (eval_addsub_number (rettv ,& var2 ,op )== FAIL ) { 2480return FAIL ; 2481 } 2482 } 2483tv_clear (& var2 ); 2484 } 2485 } 2486return OK ; 2487} 2488 2489/// Multiply or divide or compute the modulo of numbers "tv1" and "tv2" and 2490/// store the result in "tv1". The numbers can be whole numbers or floats. 2491static int eval_multdiv_number (typval_T * tv1 ,typval_T * tv2 ,int op ) 2492FUNC_ATTR_NO_SANITIZE_UNDEFINED 2493{ 2494varnumber_T n1 ,n2 ; 2495bool use_float = false; 2496 2497float_T f1 = 0 ; 2498float_T f2 = 0 ; 2499bool error = false; 2500if (tv1 -> v_type == VAR_FLOAT ) { 2501f1 = tv1 -> vval .v_float ; 2502use_float = true; 2503n1 = 0 ; 2504 }else { 2505n1 = tv_get_number_chk (tv1 ,& error ); 2506 } 2507tv_clear (tv1 ); 2508if (error ) { 2509tv_clear (tv2 ); 2510return FAIL ; 2511 } 2512 2513if (tv2 -> v_type == VAR_FLOAT ) { 2514if (!use_float ) { 2515f1 = (float_T )n1 ; 2516use_float = true; 2517 } 2518f2 = tv2 -> vval .v_float ; 2519n2 = 0 ; 2520 }else { 2521n2 = tv_get_number_chk (tv2 ,& error ); 2522tv_clear (tv2 ); 2523if (error ) { 2524return FAIL ; 2525 } 2526if (use_float ) { 2527f2 = (float_T )n2 ; 2528 } 2529 } 2530 2531// Compute the result. 2532// When either side is a float the result is a float. 2533if (use_float ) { 2534if (op == '*' ) { 2535f1 = f1 * f2 ; 2536 }else if (op == '/' ) { 2537// uncrustify:off 2538 2539// Division by zero triggers error from AddressSanitizer 2540f1 = (f2 == 0 ? ( 2541#ifdef NAN 2542f1 == 0 ? (float_T )NAN : 2543#endif 2544 (f1 > 0 ? (float_T )INFINITY : (float_T )- INFINITY )) :f1 /f2 ); 2545 2546// uncrustify:on 2547 }else { 2548emsg (_ ("E804: Cannot use '%' with Float" )); 2549return FAIL ; 2550 } 2551tv1 -> v_type = VAR_FLOAT ; 2552tv1 -> vval .v_float = f1 ; 2553 }else { 2554if (op == '*' ) { 2555n1 = n1 * n2 ; 2556 }else if (op == '/' ) { 2557n1 = num_divide (n1 ,n2 ); 2558 }else { 2559n1 = num_modulus (n1 ,n2 ); 2560 } 2561tv1 -> v_type = VAR_NUMBER ; 2562tv1 -> vval .v_number = n1 ; 2563 } 2564 2565return OK ; 2566} 2567 2568/// Handle fifth level expression: 2569/// - * number multiplication 2570/// - / number division 2571/// - % number modulo 2572/// 2573/// @param[in,out] arg Points to the first non-whitespace character of the 2574/// expression. Is advanced to the next non-whitespace 2575/// character after the recognized expression. 2576/// @param[out] rettv Location where result is saved. 2577/// @param[in] want_string True if "." is string_concatenation, otherwise 2578/// float 2579/// @return OK or FAIL. 2580static int eval6 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ,bool want_string ) 2581{ 2582// Get the first variable. 2583if (eval7 (arg ,rettv ,evalarg ,want_string )== FAIL ) { 2584return FAIL ; 2585 } 2586 2587// Repeat computing, until no '*', '/' or '%' is following. 2588while (true) { 2589int op = (uint8_t )(** arg ); 2590if (op != '*' && op != '/' && op != '%' ) { 2591break ; 2592 } 2593 2594const bool evaluate = evalarg == NULL ?0 : (evalarg -> eval_flags & EVAL_EVALUATE ); 2595 2596// Get the second variable. 2597* arg = skipwhite (* arg + 1 ); 2598typval_T var2 ; 2599if (eval7 (arg ,& var2 ,evalarg , false)== FAIL ) { 2600return FAIL ; 2601 } 2602 2603if (evaluate ) { 2604// Compute the result. 2605if (eval_multdiv_number (rettv ,& var2 ,op )== FAIL ) { 2606return FAIL ; 2607 } 2608 } 2609 } 2610 2611return OK ; 2612} 2613 2614/// Handle sixth level expression: 2615/// number number constant 2616/// 0zFFFFFFFF Blob constant 2617/// "string" string constant 2618/// 'string' literal string constant 2619/// &option-name option value 2620/// @r register contents 2621/// identifier variable value 2622/// function() function call 2623/// $VAR environment variable 2624/// (expression) nested expression 2625/// [expr, expr] List 2626/// {key: val, key: val} Dictionary 2627/// #{key: val, key: val} Dictionary with literal keys 2628/// 2629/// Also handle: 2630/// ! in front logical NOT 2631/// - in front unary minus 2632/// + in front unary plus (ignored) 2633/// trailing [] subscript in String or List 2634/// trailing .name entry in Dictionary 2635/// trailing ->name() method call 2636/// 2637/// "arg" must point to the first non-white of the expression. 2638/// "arg" is advanced to the next non-white after the recognized expression. 2639/// 2640/// @param want_string after "." operator 2641/// 2642/// @return OK or FAIL. 2643static int eval7 (char ** arg ,typval_T * rettv ,evalarg_T * const evalarg ,bool want_string ) 2644{ 2645const bool evaluate = evalarg != NULL && (evalarg -> eval_flags & EVAL_EVALUATE ); 2646int ret = OK ; 2647static int recurse = 0 ; 2648 2649// Initialise variable so that tv_clear() can't mistake this for a 2650// string and free a string that isn't there. 2651rettv -> v_type = VAR_UNKNOWN ; 2652 2653// Skip '!', '-' and '+' characters. They are handled later. 2654const char * start_leader = * arg ; 2655while (** arg == '!' || ** arg == '-' || ** arg == '+' ) { 2656* arg = skipwhite (* arg + 1 ); 2657 } 2658const char * end_leader = * arg ; 2659 2660// Limit recursion to 1000 levels. At least at 10000 we run out of stack 2661// and crash. With MSVC the stack is smaller. 2662if (recurse == 2663#ifdef _MSC_VER 2664300 2665#else 26661000 2667#endif 2668 ) { 2669semsg (_ (e_expression_too_recursive_str ),* arg ); 2670return FAIL ; 2671 } 2672recurse ++ ; 2673 2674switch (** arg ) { 2675// Number constant. 2676case '0' : 2677case '1' : 2678case '2' : 2679case '3' : 2680case '4' : 2681case '5' : 2682case '6' : 2683case '7' : 2684case '8' : 2685case '9' : 2686ret = eval_number (arg ,rettv ,evaluate ,want_string ); 2687 2688// Apply prefixed "-" and "+" now. Matters especially when 2689// "->" follows. 2690if (ret == OK && evaluate && end_leader > start_leader ) { 2691ret = eval7_leader (rettv , true,start_leader ,& end_leader ); 2692 } 2693break ; 2694 2695// String constant: "string". 2696case '"' : 2697ret = eval_string (arg ,rettv ,evaluate , false); 2698break ; 2699 2700// Literal string constant: 'str''ing'. 2701case '\'' : 2702ret = eval_lit_string (arg ,rettv ,evaluate , false); 2703break ; 2704 2705// List: [expr, expr] 2706case '[' : 2707ret = eval_list (arg ,rettv ,evalarg ); 2708break ; 2709 2710// Literal Dictionary: #{key: val, key: val} 2711case '#' : 2712ret = eval_lit_dict (arg ,rettv ,evalarg ); 2713break ; 2714 2715// Lambda: {arg, arg -> expr} 2716// Dictionary: {'key': val, 'key': val} 2717case '{' : 2718ret = get_lambda_tv (arg ,rettv ,evalarg ); 2719if (ret == NOTDONE ) { 2720ret = eval_dict (arg ,rettv ,evalarg , false); 2721 } 2722break ; 2723 2724// Option value: &name 2725case '&' : 2726ret = eval_option ((const char ** )arg ,rettv ,evaluate ); 2727break ; 2728// Environment variable: $VAR. 2729// Interpolated string: $"string" or $'string'. 2730case '$' : 2731if ((* arg )[1 ]== '"' || (* arg )[1 ]== '\'' ) { 2732ret = eval_interp_string (arg ,rettv ,evaluate ); 2733 }else { 2734ret = eval_env_var (arg ,rettv ,evaluate ); 2735 } 2736break ; 2737 2738// Register contents: @r. 2739case '@' : 2740 (* arg )++ ; 2741if (evaluate ) { 2742rettv -> v_type = VAR_STRING ; 2743rettv -> vval .v_string = get_reg_contents (** arg ,kGRegExprSrc ); 2744 } 2745if (** arg != NUL ) { 2746 (* arg )++ ; 2747 } 2748break ; 2749 2750// nested expression: (expression). 2751case '(' : 2752* arg = skipwhite (* arg + 1 ); 2753 2754ret = eval1 (arg ,rettv ,evalarg );// recursive! 2755if (** arg == ')' ) { 2756 (* arg )++ ; 2757 }else if (ret == OK ) { 2758emsg (_ ("E110: Missing ')'" )); 2759tv_clear (rettv ); 2760ret = FAIL ; 2761 } 2762break ; 2763 2764default : 2765ret = NOTDONE ; 2766break ; 2767 } 2768 2769if (ret == NOTDONE ) { 2770// Must be a variable or function name. 2771// Can also be a curly-braces kind of name: {expr}. 2772char * s = * arg ; 2773char * alias ; 2774int len = get_name_len ((const char ** )arg ,& alias ,evaluate , true); 2775if (alias != NULL ) { 2776s = alias ; 2777 } 2778 2779if (len <=0 ) { 2780ret = FAIL ; 2781 }else { 2782const int flags = evalarg == NULL ?0 :evalarg -> eval_flags ; 2783if (* skipwhite (* arg )== '(' ) { 2784// "name(..." recursive! 2785* arg = skipwhite (* arg ); 2786ret = eval_func (arg ,evalarg ,s ,len ,rettv ,flags ,NULL ); 2787 }else if (evaluate ) { 2788// get the value of a variable 2789ret = eval_variable (s ,len ,rettv ,NULL , true, false); 2790 }else { 2791// skip the name 2792check_vars (s , (size_t )len ); 2793// If evaluate is false rettv->v_type was not set, but it's needed 2794// in handle_subscript() to parse v:lua, so set it here. 2795if (rettv -> v_type == VAR_UNKNOWN && !evaluate && strnequal (s ,"v:lua." ,6 )) { 2796rettv -> v_type = VAR_PARTIAL ; 2797rettv -> vval .v_partial = get_vim_var_partial (VV_LUA ); 2798rettv -> vval .v_partial -> pt_refcount ++ ; 2799 } 2800ret = OK ; 2801 } 2802 } 2803xfree (alias ); 2804 } 2805 2806* arg = skipwhite (* arg ); 2807 2808// Handle following '[', '(' and '.' for expr[expr], expr.name, 2809// expr(expr), expr->name(expr) 2810if (ret == OK ) { 2811ret = handle_subscript ((const char ** )arg ,rettv ,evalarg , true); 2812 } 2813 2814// Apply logical NOT and unary '-', from right to left, ignore '+'. 2815if (ret == OK && evaluate && end_leader > start_leader ) { 2816ret = eval7_leader (rettv , false,start_leader ,& end_leader ); 2817 } 2818 2819recurse -- ; 2820return ret ; 2821} 2822 2823/// Apply the leading "!" and "-" before an eval7 expression to "rettv". 2824/// Adjusts "end_leaderp" until it is at "start_leader". 2825/// 2826/// @param numeric_only if true only handle "+" and "-". 2827/// 2828/// @return OK on success, FAIL on failure. 2829static int eval7_leader ( typval_T * const rettv , const bool numeric_only , 2830const char * const start_leader , const char ** const end_leaderp ) 2831FUNC_ATTR_NONNULL_ALL 2832{ 2833const char * end_leader = * end_leaderp ; 2834int ret = OK ; 2835bool error = false; 2836varnumber_T val = 0 ; 2837float_T f = 0.0 ; 2838 2839if ( rettv -> v_type == VAR_FLOAT ) { 2840f = rettv -> vval . v_float ; 2841} else { 2842val = tv_get_number_chk ( rettv , & error ); 2843} 2844if ( error ) { 2845tv_clear ( rettv ); 2846ret = FAIL ; 2847} else { 2848while ( end_leader > start_leader ) { 2849end_leader -- ; 2850if ( * end_leader == '!' ) { 2851if ( numeric_only ) { 2852end_leader ++ ; 2853break; 2854} 2855if ( rettv -> v_type == VAR_FLOAT ) { 2856rettv -> v_type = VAR_BOOL ; 2857val = f == 0.0 ? kBoolVarTrue : kBoolVarFalse ; 2858} else { 2859val = ! val ; 2860} 2861} else if ( * end_leader == '-' ) { 2862if ( rettv -> v_type == VAR_FLOAT ) { 2863f = - f ; 2864} else { 2865val = - val ; 2866} 2867} 2868} 2869if ( rettv -> v_type == VAR_FLOAT ) { 2870tv_clear ( rettv ); 2871rettv -> vval . v_float = f ; 2872} else { 2873tv_clear ( rettv ); 2874rettv -> v_type = VAR_NUMBER ; 2875rettv -> vval . v_number = val ; 2876} 2877} 2878 2879* end_leaderp = end_leader ; 2880return ret ; 2881} 2882 2883/// Call the function referred to in "rettv". 2884/// @param lua_funcname If `rettv` refers to a v:lua function, this must point 2885/// to the name of the Lua function to call (after the 2886/// "v:lua." prefix). 2887/// @return OK on success, FAIL on failure. 2888static int call_func_rettv ( char ** const arg , evalarg_T * const evalarg , typval_T * const rettv , 2889const bool evaluate , dict_T * const selfdict , typval_T * const basetv , 2890const char * const lua_funcname ) 2891FUNC_ATTR_NONNULL_ARG ( 1 , 3 ) 2892{ 2893partial_T * pt = NULL ; 2894typval_T functv ; 2895const char * funcname ; 2896bool is_lua = false; 2897int ret ; 2898 2899// need to copy the funcref so that we can clear rettv 2900if ( evaluate ) { 2901functv = * rettv ; 2902rettv -> v_type = VAR_UNKNOWN ; 2903 2904// Invoke the function. Recursive! 2905if ( functv . v_type == VAR_PARTIAL ) { 2906pt = functv . vval . v_partial ; 2907is_lua = is_luafunc ( pt ); 2908funcname = is_lua ? lua_funcname : partial_name ( pt ); 2909} else { 2910funcname = functv . vval . v_string ; 2911if ( funcname == NULL || * funcname == NUL ) { 2912emsg ( _ ( e_empty_function_name )); 2913ret = FAIL ; 2914goto theend ; 2915} 2916} 2917} else { 2918funcname = "" ; 2919} 2920 2921funcexe_T funcexe = FUNCEXE_INIT ; 2922funcexe . fe_firstline = curwin -> w_cursor . lnum ; 2923funcexe . fe_lastline = curwin -> w_cursor . lnum ; 2924funcexe . fe_evaluate = evaluate ; 2925funcexe . fe_partial = pt ; 2926funcexe . fe_selfdict = selfdict ; 2927funcexe . fe_basetv = basetv ; 2928ret = get_func_tv ( funcname , is_lua ? ( int )( * arg - funcname ) : -1 , rettv , 2929arg , evalarg , & funcexe ); 2930 2931theend : 2932// Clear the funcref afterwards, so that deleting it while 2933// evaluating the arguments is possible (see test55). 2934if ( evaluate ) { 2935tv_clear ( & functv ); 2936} 2937 2938return ret ; 2939} 2940 2941/// Evaluate "->method()". 2942/// 2943/// @param verbose if true, give error messages. 2944/// @param *arg points to the '-'. 2945/// 2946/// @return FAIL or OK. 2947/// 2948/// @note "*arg" is advanced to after the ')'. 2949static int eval_lambda ( char ** const arg , typval_T * const rettv , evalarg_T * const evalarg , 2950const bool verbose ) 2951FUNC_ATTR_NONNULL_ARG ( 1 , 2 ) 2952{ 2953const bool evaluate = evalarg != NULL && ( evalarg -> eval_flags & EVAL_EVALUATE ); 2954// Skip over the ->. 2955* arg += 2 ; 2956typval_T base = * rettv ; 2957rettv -> v_type = VAR_UNKNOWN ; 2958 2959int ret = get_lambda_tv ( arg , rettv , evalarg ); 2960if ( ret != OK ) { 2961return FAIL ; 2962} else if ( ** arg != '(' ) { 2963if ( verbose ) { 2964if ( * skipwhite ( * arg ) == '(' ) { 2965emsg ( _ ( e_nowhitespace )); 2966} else { 2967semsg ( _ ( e_missingparen ), "lambda" ); 2968} 2969} 2970tv_clear ( rettv ); 2971ret = FAIL ; 2972} else { 2973ret = call_func_rettv ( arg , evalarg , rettv , evaluate , NULL , & base , NULL ); 2974} 2975 2976// Clear the funcref afterwards, so that deleting it while 2977// evaluating the arguments is possible (see test55). 2978if ( evaluate ) { 2979tv_clear ( & base ); 2980} 2981 2982return ret ; 2983} 2984 2985/// Evaluate "->method()" or "->v:lua.method()". 2986/// 2987/// @param *arg points to the '-'. 2988/// 2989/// @return FAIL or OK. "*arg" is advanced to after the ')'. 2990static int eval_method ( char ** const arg , typval_T * const rettv , evalarg_T * const evalarg , 2991const bool verbose ) 2992FUNC_ATTR_NONNULL_ARG ( 1 , 2 ) 2993{ 2994const bool evaluate = evalarg != NULL && ( evalarg -> eval_flags & EVAL_EVALUATE ); 2995 2996// Skip over the ->. 2997* arg += 2 ; 2998typval_T base = * rettv ; 2999rettv -> v_type = VAR_UNKNOWN ; 3000 3001// Locate the method name. 3002int len ; 3003char * name = * arg ; 3004char * lua_funcname = NULL ; 3005char * alias = NULL ; 3006if ( strnequal ( name , "v:lua." , 6 )) { 3007lua_funcname = name + 6 ; 3008* arg = ( char * ) skip_luafunc_name ( lua_funcname ); 3009* arg = skipwhite ( * arg ); // to detect trailing whitespace later 3010len = ( int )( * arg - lua_funcname ); 3011} else { 3012len = get_name_len ((const char ** ) arg , & alias , evaluate , true); 3013if ( alias != NULL ) { 3014name = alias ; 3015} 3016} 3017 3018char * tofree = NULL ; 3019int ret = OK ; 3020 3021if ( len <= 0 ) { 3022if ( verbose ) { 3023if ( lua_funcname == NULL ) { 3024emsg ( _ ( "E260: Missing name after ->" )); 3025} else { 3026semsg ( _ ( e_invexpr2 ), name ); 3027} 3028} 3029ret = FAIL ; 3030} else { 3031* arg = skipwhite ( * arg ); 3032 3033// If there is no "(" immediately following, but there is further on, 3034// it can be "dict.Func()", "list[nr]", etc. 3035// Does not handle anything where "(" is part of the expression. 3036char * paren ; 3037if ( ** arg != '(' && lua_funcname == NULL && alias == NULL 3038&& ( paren = vim_strchr ( * arg , '(' )) != NULL ) { 3039* arg = name ; 3040* paren = NUL ; 3041typval_T ref ; 3042ref . v_type = VAR_UNKNOWN ; 3043if ( eval7 ( arg , & ref , evalarg , false) == FAIL ) { 3044* arg = name + len ; 3045ret = FAIL ; 3046} else if ( * skipwhite ( * arg ) != NUL ) { 3047if ( verbose ) { 3048semsg ( _ ( e_trailing_arg ), * arg ); 3049} 3050ret = FAIL ; 3051} else if ( ref . v_type == VAR_FUNC && ref . vval . v_string != NULL ) { 3052name = ref . vval . v_string ; 3053ref . vval . v_string = NULL ; 3054tofree = name ; 3055len = ( int ) strlen ( name ); 3056} else if ( ref . v_type == VAR_PARTIAL && ref . vval . v_partial != NULL ) { 3057if ( ref . vval . v_partial -> pt_argc > 0 || ref . vval . v_partial -> pt_dict != NULL ) { 3058if ( verbose ) { 3059emsg ( _ ( e_cannot_use_partial_here )); 3060} 3061ret = FAIL ; 3062} else { 3063name = xstrdup ( partial_name ( ref . vval . v_partial )); 3064tofree = name ; 3065if ( name == NULL ) { 3066ret = FAIL ; 3067name = * arg ; 3068} else { 3069len = ( int ) strlen ( name ); 3070} 3071} 3072} else { 3073if ( verbose ) { 3074semsg ( _ ( e_not_callable_type_str ), name ); 3075} 3076ret = FAIL ; 3077} 3078tv_clear ( & ref ); 3079* paren = '(' ; 3080} 3081 3082if ( ret == OK ) { 3083if ( ** arg != '(' ) { 3084if ( verbose ) { 3085semsg ( _ ( e_missingparen ), name ); 3086} 3087ret = FAIL ; 3088} else if ( ascii_iswhite (( * arg )[ -1 ])) { 3089if ( verbose ) { 3090emsg ( _ ( e_nowhitespace )); 3091} 3092ret = FAIL ; 3093} else if ( lua_funcname != NULL ) { 3094if ( evaluate ) { 3095rettv -> v_type = VAR_PARTIAL ; 3096rettv -> vval . v_partial = get_vim_var_partial ( VV_LUA ); 3097rettv -> vval . v_partial -> pt_refcount ++ ; 3098} 3099ret = call_func_rettv ( arg , evalarg , rettv , evaluate , NULL , & base , lua_funcname ); 3100} else { 3101ret = eval_func ( arg , evalarg , name , len , rettv , 3102evaluate ? EVAL_EVALUATE : 0 , & base ); 3103} 3104} 3105} 3106 3107// Clear the funcref afterwards, so that deleting it while 3108// evaluating the arguments is possible (see test55). 3109if ( evaluate ) { 3110tv_clear ( & base ); 3111} 3112xfree ( tofree ); 3113 3114if ( alias != NULL ) { 3115xfree ( alias ); 3116} 3117 3118return ret ; 3119} 3120 3121/// Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key". 3122/// "*arg" points to the '[' or '.'. 3123/// 3124/// @param verbose give error messages 3125/// 3126/// @returns FAIL or OK. "*arg" is advanced to after the ']'. 3127static int eval_index ( char ** arg , typval_T * rettv , evalarg_T * const evalarg , bool verbose ) 3128{ 3129const bool evaluate = evalarg != NULL && ( evalarg -> eval_flags & EVAL_EVALUATE ); 3130bool empty1 = false; 3131bool empty2 = false; 3132bool range = false; 3133const char * key = NULL ; 3134ptrdiff_t keylen = -1 ; 3135 3136if ( check_can_index ( rettv , evaluate , verbose ) == FAIL ) { 3137return FAIL ; 3138} 3139 3140typval_T var1 = TV_INITIAL_VALUE ; 3141typval_T var2 = TV_INITIAL_VALUE ; 3142if ( ** arg == '.' ) { 3143// dict.name 3144key = * arg + 1 ; 3145for ( keylen = 0 ; eval_isdictc ( key [ keylen ]); keylen ++ ) {} 3146if ( keylen == 0 ) { 3147return FAIL ; 3148} 3149* arg = skipwhite ( key + keylen ); 3150} else { 3151// something[idx] 3152// 3153// Get the (first) variable from inside the []. 3154* arg = skipwhite ( * arg + 1 ); 3155if ( ** arg == ':' ) { 3156empty1 = true; 3157} else if ( eval1 ( arg , & var1 , evalarg ) == FAIL ) { // Recursive! 3158return FAIL ; 3159} else if ( evaluate && ! tv_check_str ( & var1 )) { 3160// Not a number or string. 3161tv_clear ( & var1 ); 3162return FAIL ; 3163} 3164 3165// Get the second variable from inside the [:]. 3166if ( ** arg == ':' ) { 3167range = true; 3168* arg = skipwhite ( * arg + 1 ); 3169if ( ** arg == ']' ) { 3170empty2 = true; 3171} else if ( eval1 ( arg , & var2 , evalarg ) == FAIL ) { // Recursive! 3172if (! empty1 ) { 3173tv_clear ( & var1 ); 3174} 3175return FAIL ; 3176} else if ( evaluate && ! tv_check_str ( & var2 )) { 3177// Not a number or string. 3178if (! empty1 ) { 3179tv_clear ( & var1 ); 3180} 3181tv_clear ( & var2 ); 3182return FAIL ; 3183} 3184} 3185 3186// Check for the ']'. 3187if ( ** arg != ']' ) { 3188if ( verbose ) { 3189emsg ( _ ( e_missbrac )); 3190} 3191tv_clear ( & var1 ); 3192if ( range ) { 3193tv_clear ( & var2 ); 3194} 3195return FAIL ; 3196} 3197* arg = skipwhite ( * arg + 1 ); // skip the ']' 3198} 3199 3200if ( evaluate ) { 3201int res = eval_index_inner ( rettv , range , 3202empty1 ? NULL : & var1 , empty2 ? NULL : & var2 , false, 3203key , keylen , verbose ); 3204if (! empty1 ) { 3205tv_clear ( & var1 ); 3206} 3207if ( range ) { 3208tv_clear ( & var2 ); 3209} 3210return res ; 3211} 3212return OK ; 3213} 3214 3215/// Check if "rettv" can have an [index] or [sli:ce] 3216static int check_can_index ( typval_T * rettv , bool evaluate , bool verbose ) 3217{ 3218switch ( rettv -> v_type ) { 3219case VAR_FUNC : 3220case VAR_PARTIAL : 3221if ( verbose ) { 3222emsg ( _ ( e_cannot_index_a_funcref )); 3223} 3224return FAIL ; 3225case VAR_FLOAT : 3226if ( verbose ) { 3227emsg ( _ ( e_using_float_as_string )); 3228} 3229return FAIL ; 3230case VAR_BOOL : 3231case VAR_SPECIAL : 3232if ( verbose ) { 3233emsg ( _ ( e_cannot_index_special_variable )); 3234} 3235return FAIL ; 3236case VAR_UNKNOWN : 3237if ( evaluate ) { 3238emsg ( _ ( e_cannot_index_special_variable )); 3239return FAIL ; 3240} 3241FALLTHROUGH ; 3242case VAR_STRING : 3243case VAR_NUMBER : 3244case VAR_LIST : 3245case VAR_DICT : 3246case VAR_BLOB : 3247break; 3248} 3249return OK ; 3250} 3251 3252/// slice() function 3253void f_slice ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 3254{ 3255if ( check_can_index ( & argvars [ 0 ], true, false) != OK ) { 3256return; 3257} 3258 3259tv_copy ( argvars , rettv ); 3260eval_index_inner ( rettv , true, argvars + 1 , 3261argvars [ 2 ]. v_type == VAR_UNKNOWN ? NULL : argvars + 2 , 3262true, NULL , 0 , false); 3263} 3264 3265/// Apply index or range to "rettv". 3266/// 3267/// @param var1 the first index, NULL for [:expr]. 3268/// @param var2 the second index, NULL for [expr] and [expr: ] 3269/// @param exclusive true for slice(): second index is exclusive, use character 3270/// index for string. 3271/// Alternatively, "key" is not NULL, then key[keylen] is the dict index. 3272static int eval_index_inner ( typval_T * rettv , bool is_range , typval_T * var1 , typval_T * var2 , 3273bool exclusive , const char * key , ptrdiff_t keylen , bool verbose ) 3274{ 3275varnumber_T n1 = 0 ; 3276varnumber_T n2 = 0 ; 3277if ( var1 != NULL && rettv -> v_type != VAR_DICT ) { 3278n1 = tv_get_number ( var1 ); 3279} 3280 3281if ( is_range ) { 3282if ( rettv -> v_type == VAR_DICT ) { 3283if ( verbose ) { 3284emsg ( _ ( e_cannot_slice_dictionary )); 3285} 3286return FAIL ; 3287} 3288if ( var2 != NULL ) { 3289n2 = tv_get_number ( var2 ); 3290} else { 3291n2 = VARNUMBER_MAX ; 3292} 3293} 3294 3295switch ( rettv -> v_type ) { 3296case VAR_BOOL : 3297case VAR_SPECIAL : 3298case VAR_FUNC : 3299case VAR_FLOAT : 3300case VAR_PARTIAL : 3301case VAR_UNKNOWN : 3302break; // Not evaluating, skipping over subscript 3303 3304case VAR_NUMBER : 3305case VAR_STRING : { 3306const char * const s = tv_get_string ( rettv ); 3307char * v ; 3308int len = ( int ) strlen ( s ); 3309if ( exclusive ) { 3310if ( is_range ) { 3311v = string_slice ( s , n1 , n2 , exclusive ); 3312} else { 3313v = char_from_string ( s , n1 ); 3314} 3315} else if ( is_range ) { 3316// The resulting variable is a substring. If the indexes 3317// are out of range the result is empty. 3318if ( n1 < 0 ) { 3319n1 = len + n1 ; 3320if ( n1 < 0 ) { 3321n1 = 0 ; 3322} 3323} 3324if ( n2 < 0 ) { 3325n2 = len + n2 ; 3326} else if ( n2 >= len ) { 3327n2 = len ; 3328} 3329if ( n1 >= len || n2 < 0 || n1 > n2 ) { 3330v = NULL ; 3331} else { 3332v = xmemdupz ( s + n1 , ( size_t ) n2 - ( size_t ) n1 + 1 ); 3333} 3334} else { 3335// The resulting variable is a string of a single 3336// character. If the index is too big or negative the 3337// result is empty. 3338if ( n1 >= len || n1 < 0 ) { 3339v = NULL ; 3340} else { 3341v = xmemdupz ( s + n1 , 1 ); 3342} 3343} 3344tv_clear ( rettv ); 3345rettv -> v_type = VAR_STRING ; 3346rettv -> vval . v_string = v ; 3347break; 3348} 3349 3350case VAR_BLOB : 3351tv_blob_slice_or_index ( rettv -> vval . v_blob , is_range , n1 , n2 , exclusive , rettv ); 3352break; 3353 3354case VAR_LIST : 3355if ( var1 == NULL ) { 3356n1 = 0 ; 3357} 3358if ( var2 == NULL ) { 3359n2 = VARNUMBER_MAX ; 3360} 3361if ( tv_list_slice_or_index ( rettv -> vval . v_list , 3362is_range , n1 , n2 , exclusive , rettv , verbose ) == FAIL ) { 3363return FAIL ; 3364} 3365break; 3366 3367case VAR_DICT : { 3368if ( key == NULL ) { 3369key = tv_get_string_chk ( var1 ); 3370if ( key == NULL ) { 3371return FAIL ; 3372} 3373} 3374 3375dictitem_T * const item = tv_dict_find ( rettv -> vval . v_dict , key , keylen ); 3376 3377if ( item == NULL && verbose ) { 3378if ( keylen > 0 ) { 3379semsg ( _ ( e_dictkey_len ), keylen , key ); 3380} else { 3381semsg ( _ ( e_dictkey ), key ); 3382} 3383} 3384if ( item == NULL || tv_is_luafunc ( & item -> di_tv )) { 3385return FAIL ; 3386} 3387 3388typval_T tmp ; 3389tv_copy ( & item -> di_tv , & tmp ); 3390tv_clear ( rettv ); 3391* rettv = tmp ; 3392break; 3393} 3394} 3395return OK ; 3396} 3397 3398/// Get an option value 3399/// 3400/// @param[in,out] arg Points to the '&' or '+' before the option name. Is 3401/// advanced to the character after the option name. 3402/// @param[out] rettv Location where result is saved. 3403/// @param[in] evaluate If not true, rettv is not populated. 3404/// 3405/// @return OK or FAIL. 3406int eval_option (const char ** const arg , typval_T * const rettv , const bool evaluate ) 3407FUNC_ATTR_NONNULL_ARG ( 1 ) 3408{ 3409const bool working = ( ** arg == '+' ); // has("+option") 3410OptIndex opt_idx ; 3411int opt_flags ; 3412 3413// Isolate the option name and find its value. 3414char * const option_end = ( char * ) find_option_var_end ( arg , & opt_idx , & opt_flags ); 3415 3416if ( option_end == NULL ) { 3417if ( rettv != NULL ) { 3418semsg ( _ ( "E112: Option name missing: %s" ), * arg ); 3419} 3420return FAIL ; 3421} 3422 3423if (! evaluate ) { 3424* arg = option_end ; 3425return OK ; 3426} 3427 3428char c = * option_end ; 3429* option_end = NUL ; 3430 3431int ret = OK ; 3432bool is_tty_opt = is_tty_option ( * arg ); 3433 3434if ( opt_idx == kOptInvalid && ! is_tty_opt ) { 3435// Only give error if result is going to be used. 3436if ( rettv != NULL ) { 3437semsg ( _ ( "E113: Unknown option: %s" ), * arg ); 3438} 3439 3440ret = FAIL ; 3441} else if ( rettv != NULL ) { 3442Object value = is_tty_opt ? get_tty_option ( * arg ) : get_option_value ( opt_idx , opt_flags ); 3443assert ( value . type != kObjectTypeNil ); 3444 3445* rettv = opt_to_tv ( value , true); 3446optval_free ( value ); 3447} else if ( working && ! is_tty_opt && is_option_hidden ( opt_idx )) { 3448ret = FAIL ; 3449} 3450 3451* option_end = c ; // put back for error messages 3452* arg = option_end ; 3453 3454return ret ; 3455} 3456 3457/// Allocate a variable for a number constant. Also deals with "0z" for blob. 3458/// 3459/// @return OK or FAIL. 3460static int eval_number ( char ** arg , typval_T * rettv , bool evaluate , bool want_string ) 3461{ 3462char * p = skipdigits ( * arg + 1 ); 3463bool get_float = false; 3464 3465// We accept a float when the format matches 3466// "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very 3467// strict to avoid backwards compatibility problems. 3468// Don't look for a float after the "." operator, so that 3469// ":let vers = 1.2.3" doesn't fail. 3470if (! want_string && p [ 0 ] == '.' && ascii_isdigit ( p [ 1 ])) { 3471get_float = true; 3472p = skipdigits ( p + 2 ); 3473if ( * p == 'e' || * p == 'E' ) { 3474p ++ ; 3475if ( * p == '-' || * p == '+' ) { 3476p ++ ; 3477} 3478if (! ascii_isdigit ( * p )) { 3479get_float = false; 3480} else { 3481p = skipdigits ( p + 1 ); 3482} 3483} 3484if ( ASCII_ISALPHA ( * p ) || * p == '.' ) { 3485get_float = false; 3486} 3487} 3488if ( get_float ) { 3489float_T f ; 3490* arg += string2float ( * arg , & f ); 3491if ( evaluate ) { 3492rettv -> v_type = VAR_FLOAT ; 3493rettv -> vval . v_float = f ; 3494} 3495} else if ( ** arg == '0' && (( * arg )[ 1 ] == 'z' || ( * arg )[ 1 ] == 'Z' )) { 3496// Blob constant: 0z0123456789abcdef 3497blob_T * blob = NULL ; 3498if ( evaluate ) { 3499blob = tv_blob_alloc (); 3500} 3501char * bp ; 3502for ( bp = * arg + 2 ; ascii_isxdigit ( bp [ 0 ]); bp += 2 ) { 3503if (! ascii_isxdigit ( bp [ 1 ])) { 3504if ( blob != NULL ) { 3505emsg ( _ ( "E973: Blob literal should have an even number of hex characters" )); 3506ga_clear ( & blob -> bv_ga ); 3507XFREE_CLEAR ( blob ); 3508} 3509return FAIL ; 3510} 3511if ( blob != NULL ) { 3512ga_append ( & blob -> bv_ga , ( uint8_t )(( hex2nr ( * bp ) << 4 ) + hex2nr ( * ( bp + 1 )))); 3513} 3514if ( bp [ 2 ] == '.' && ascii_isxdigit ( bp [ 3 ])) { 3515bp ++ ; 3516} 3517} 3518if ( blob != NULL ) { 3519tv_blob_set_ret ( rettv , blob ); 3520} 3521* arg = bp ; 3522} else { 3523// decimal, hex or octal number 3524int len ; 3525varnumber_T n ; 3526vim_str2nr ( * arg , NULL , & len , STR2NR_ALL , & n , NULL , 0 , true, NULL ); 3527if ( len == 0 ) { 3528if ( evaluate ) { 3529semsg ( _ ( e_invexpr2 ), * arg ); 3530} 3531return FAIL ; 3532} 3533* arg += len ; 3534if ( evaluate ) { 3535rettv -> v_type = VAR_NUMBER ; 3536rettv -> vval . v_number = n ; 3537} 3538} 3539return OK ; 3540} 3541 3542/// Evaluate a string constant and put the result in "rettv". 3543/// "*arg" points to the double quote or to after it when "interpolate" is true. 3544/// When "interpolate" is true reduce "{{" to "{", reduce "}}" to "}" and stop 3545/// at a single "{". 3546/// 3547/// @return OK or FAIL. 3548static int eval_string ( char ** arg , typval_T * rettv , bool evaluate , bool interpolate ) 3549{ 3550char * p ; 3551const char * const arg_end = * arg + strlen ( * arg ); 3552unsigned extra = interpolate ? 1 : 0 ; 3553const int off = interpolate ? 0 : 1 ; 3554 3555// Find the end of the string, skipping backslashed characters. 3556for ( p = * arg + off ; * p != NUL && * p != '"' ; MB_PTR_ADV ( p )) { 3557if ( * p == '\\' && p [ 1 ] != NUL ) { 3558p ++ ; 3559// A "\<x>" form occupies at least 4 characters, and produces up 3560// to 9 characters (6 for the char and 3 for a modifier): 3561// reserve space for 5 extra. 3562if ( * p == '<' ) { 3563int modifiers = 0 ; 3564int flags = FSK_KEYCODE | FSK_IN_STRING ; 3565 3566extra += 5 ; 3567 3568// Skip to the '>' to avoid using '{' inside for string 3569// interpolation. 3570if ( p [ 1 ] != '*' ) { 3571flags |= FSK_SIMPLIFY ; 3572} 3573if ( find_special_key ((const char ** ) & p , ( size_t )( arg_end - p ), 3574& modifiers , flags , NULL ) != 0 ) { 3575p -- ; // leave "p" on the ">" 3576} 3577} 3578} else if ( interpolate && ( * p == '{' || * p == '}' )) { 3579if ( * p == '{' && p [ 1 ] != '{' ) { // start of expression 3580break; 3581} 3582p ++ ; 3583if ( p [ -1 ] == '}' && * p != '}' ) { // single '}' is an error 3584semsg ( _ ( e_stray_closing_curly_str ), * arg ); 3585return FAIL ; 3586} 3587extra -- ; // "{{" becomes "{", "}}" becomes "}" 3588} 3589} 3590 3591if ( * p != '"' && !( interpolate && * p == '{' )) { 3592semsg ( _ ( "E114: Missing quote: %s" ), * arg ); 3593return FAIL ; 3594} 3595 3596// If only parsing, set *arg and return here 3597if (! evaluate ) { 3598* arg = p + off ; 3599return OK ; 3600} 3601 3602// Copy the string into allocated memory, handling backslashed 3603// characters. 3604rettv -> v_type = VAR_STRING ; 3605const int len = ( int )( p - * arg + extra ); 3606rettv -> vval . v_string = xmalloc (( size_t ) len ); 3607char * end = rettv -> vval . v_string ; 3608 3609for ( p = * arg + off ; * p != NUL && * p != '"' ;) { 3610if ( * p == '\\' ) { 3611switch ( *++ p ) { 3612case 'b' : 3613* end ++ = BS ; ++ p ; break; 3614case 'e' : 3615* end ++ = ESC ; ++ p ; break; 3616case 'f' : 3617* end ++ = FF ; ++ p ; break; 3618case 'n' : 3619* end ++ = NL ; ++ p ; break; 3620case 'r' : 3621* end ++ = CAR ; ++ p ; break; 3622case 't' : 3623* end ++ = TAB ; ++ p ; break; 3624 3625case 'X' : // hex: "\x1", "\x12" 3626case 'x' : 3627case 'u' : // Unicode: "\u0023" 3628case 'U' : 3629if ( ascii_isxdigit ( p [ 1 ])) { 3630int n , nr ; 3631int c = toupper (( uint8_t )( * p )); 3632 3633if ( c == 'X' ) { 3634n = 2 ; 3635} else if ( * p == 'u' ) { 3636n = 4 ; 3637} else { 3638n = 8 ; 3639} 3640nr = 0 ; 3641while ( -- n >= 0 && ascii_isxdigit ( p [ 1 ])) { 3642p ++ ; 3643nr = ( nr << 4 ) + hex2nr ( * p ); 3644} 3645p ++ ; 3646// For "\u" store the number according to 3647// 'encoding'. 3648if ( c != 'X' ) { 3649end += utf_char2bytes ( nr , end ); 3650} else { 3651* end ++ = ( char ) nr ; 3652} 3653} 3654break; 3655 3656// octal: "\1", "\12", "\123" 3657case '0' : 3658case '1' : 3659case '2' : 3660case '3' : 3661case '4' : 3662case '5' : 3663case '6' : 3664case '7' : 3665* end = ( char )( * p ++ - '0' ); 3666if ( * p >= '0' && * p <= '7' ) { 3667* end = ( char )(( * end << 3 ) + * p ++ - '0' ); 3668if ( * p >= '0' && * p <= '7' ) { 3669* end = ( char )(( * end << 3 ) + * p ++ - '0' ); 3670} 3671} 3672end ++ ; 3673break; 3674 3675// Special key, e.g.: "\<C-W>" 3676case '<' : { 3677int flags = FSK_KEYCODE | FSK_IN_STRING ; 3678 3679if ( p [ 1 ] != '*' ) { 3680flags |= FSK_SIMPLIFY ; 3681} 3682extra = trans_special ((const char ** ) & p , ( size_t )( arg_end - p ), 3683end , flags , false, NULL ); 3684if ( extra != 0 ) { 3685end += extra ; 3686if ( end >= rettv -> vval . v_string + len ) { 3687iemsg ( "eval_string() used more space than allocated" ); 3688} 3689break; 3690} 3691} 3692FALLTHROUGH ; 3693 3694default: 3695mb_copy_char ((const char ** ) & p , & end ); 3696break; 3697} 3698} else { 3699if ( interpolate && ( * p == '{' || * p == '}' )) { 3700if ( * p == '{' && p [ 1 ] != '{' ) { // start of expression 3701break; 3702} 3703p ++ ; // reduce "{{" to "{" and "}}" to "}" 3704} 3705mb_copy_char ((const char ** ) & p , & end ); 3706} 3707} 3708* end = NUL ; 3709if ( * p == '"' && ! interpolate ) { 3710p ++ ; 3711} 3712* arg = p ; 3713 3714return OK ; 3715} 3716 3717/// Allocate a variable for a 'str''ing' constant. 3718/// When "interpolate" is true reduce "{{" to "{" and stop at a single "{". 3719/// 3720/// @return OK when a "rettv" was set to the string. 3721/// FAIL on error, "rettv" is not set. 3722static int eval_lit_string ( char ** arg , typval_T * rettv , bool evaluate , bool interpolate ) 3723{ 3724char * p ; 3725int reduce = interpolate ? -1 : 0 ; 3726const int off = interpolate ? 0 : 1 ; 3727 3728// Find the end of the string, skipping ''. 3729for ( p = * arg + off ; * p != NUL ; MB_PTR_ADV ( p )) { 3730if ( * p == '\'' ) { 3731if ( p [ 1 ] != '\'' ) { 3732break; 3733} 3734reduce ++ ; 3735p ++ ; 3736} else if ( interpolate ) { 3737if ( * p == '{' ) { 3738if ( p [ 1 ] != '{' ) { 3739break; 3740} 3741p ++ ; 3742reduce ++ ; 3743} else if ( * p == '}' ) { 3744p ++ ; 3745if ( * p != '}' ) { 3746semsg ( _ ( e_stray_closing_curly_str ), * arg ); 3747return FAIL ; 3748} 3749reduce ++ ; 3750} 3751} 3752} 3753 3754if ( * p != '\'' && !( interpolate && * p == '{' )) { 3755semsg ( _ ( "E115: Missing quote: %s" ), * arg ); 3756return FAIL ; 3757} 3758 3759// If only parsing return after setting "*arg" 3760if (! evaluate ) { 3761* arg = p + off ; 3762return OK ; 3763} 3764 3765// Copy the string into allocated memory, handling '' to ' reduction and 3766// any expressions. 3767char * str = xmalloc (( size_t )(( p - * arg ) - reduce )); 3768rettv -> v_type = VAR_STRING ; 3769rettv -> vval . v_string = str ; 3770 3771for ( p = * arg + off ; * p != NUL ;) { 3772if ( * p == '\'' ) { 3773if ( p [ 1 ] != '\'' ) { 3774break; 3775} 3776p ++ ; 3777} else if ( interpolate && ( * p == '{' || * p == '}' )) { 3778if ( * p == '{' && p [ 1 ] != '{' ) { 3779break; 3780} 3781p ++ ; 3782} 3783mb_copy_char ((const char ** ) & p , & str ); 3784} 3785* str = NUL ; 3786* arg = p + off ; 3787 3788return OK ; 3789} 3790 3791/// Evaluate a single or double quoted string possibly containing expressions. 3792/// "arg" points to the '$'. The result is put in "rettv". 3793/// 3794/// @return OK or FAIL. 3795int eval_interp_string ( char ** arg , typval_T * rettv , bool evaluate ) 3796{ 3797int ret = OK ; 3798 3799garray_T ga ; 3800ga_init ( & ga , 1 , 80 ); 3801 3802// *arg is on the '$' character, move it to the first string character. 3803( * arg ) ++ ; 3804const int quote = ( uint8_t )( ** arg ); 3805( * arg ) ++ ; 3806 3807while (true) { 3808typval_T tv ; 3809// Get the string up to the matching quote or to a single '{'. 3810// "arg" is advanced to either the quote or the '{'. 3811if ( quote == '"' ) { 3812ret = eval_string ( arg , & tv , evaluate , true); 3813} else { 3814ret = eval_lit_string ( arg , & tv , evaluate , true); 3815} 3816if ( ret == FAIL ) { 3817break; 3818} 3819if ( evaluate ) { 3820ga_concat ( & ga , tv . vval . v_string ); 3821tv_clear ( & tv ); 3822} 3823 3824if ( ** arg != '{' ) { 3825// found terminating quote 3826( * arg ) ++ ; 3827break; 3828} 3829char * p = eval_one_expr_in_str ( * arg , & ga , evaluate ); 3830if ( p == NULL ) { 3831ret = FAIL ; 3832break; 3833} 3834* arg = p ; 3835} 3836 3837rettv -> v_type = VAR_STRING ; 3838if ( ret != FAIL && evaluate ) { 3839ga_append ( & ga , NUL ); 3840} 3841rettv -> vval . v_string = ga . ga_data ; 3842return OK ; 3843} 3844 3845/// @return the function name of the partial. 3846char * partial_name ( partial_T * pt ) 3847FUNC_ATTR_PURE 3848{ 3849if ( pt != NULL ) { 3850if ( pt -> pt_name != NULL ) { 3851return pt -> pt_name ; 3852} 3853if ( pt -> pt_func != NULL ) { 3854return pt -> pt_func -> uf_name ; 3855} 3856} 3857return "" ; 3858} 3859 3860static void partial_free ( partial_T * pt ) 3861{ 3862for ( int i = 0 ; i < pt -> pt_argc ; i ++ ) { 3863tv_clear ( & pt -> pt_argv [ i ]); 3864} 3865xfree ( pt -> pt_argv ); 3866tv_dict_unref ( pt -> pt_dict ); 3867if ( pt -> pt_name != NULL ) { 3868func_unref ( pt -> pt_name ); 3869xfree ( pt -> pt_name ); 3870} else { 3871func_ptr_unref ( pt -> pt_func ); 3872} 3873xfree ( pt ); 3874} 3875 3876/// Unreference a closure: decrement the reference count and free it when it 3877/// becomes zero. 3878void partial_unref ( partial_T * pt ) 3879{ 3880if ( pt == NULL ) { 3881return; 3882} 3883 3884if ( -- pt -> pt_refcount <= 0 ) { 3885partial_free ( pt ); 3886} 3887} 3888 3889/// Allocate a variable for a List and fill it from "*arg". 3890/// 3891/// @param arg "*arg" points to the "[". 3892/// @return OK or FAIL. 3893static int eval_list ( char ** arg , typval_T * rettv , evalarg_T * const evalarg ) 3894{ 3895const bool evaluate = evalarg == NULL ? false : evalarg -> eval_flags & EVAL_EVALUATE ; 3896list_T * l = NULL ; 3897 3898if ( evaluate ) { 3899l = tv_list_alloc ( kListLenShouldKnow ); 3900} 3901 3902* arg = skipwhite ( * arg + 1 ); 3903while ( ** arg != ']' && ** arg != NUL ) { 3904typval_T tv ; 3905if ( eval1 ( arg , & tv , evalarg ) == FAIL ) { // Recursive! 3906goto failret ; 3907} 3908if ( evaluate ) { 3909tv . v_lock = VAR_UNLOCKED ; 3910tv_list_append_owned_tv ( l , tv ); 3911} 3912 3913// the comma must come after the value 3914bool had_comma = ** arg == ',' ; 3915if ( had_comma ) { 3916* arg = skipwhite ( * arg + 1 ); 3917} 3918 3919if ( ** arg == ']' ) { 3920break; 3921} 3922 3923if (! had_comma ) { 3924semsg ( _ ( "E696: Missing comma in List: %s" ), * arg ); 3925goto failret ; 3926} 3927} 3928 3929if ( ** arg != ']' ) { 3930semsg ( _ ( e_list_end ), * arg ); 3931failret : 3932if ( evaluate ) { 3933tv_list_free ( l ); 3934} 3935return FAIL ; 3936} 3937 3938* arg = skipwhite ( * arg + 1 ); 3939if ( evaluate ) { 3940tv_list_set_ret ( rettv , l ); 3941} 3942 3943return OK ; 3944} 3945 3946/// @param ic ignore case 3947bool func_equal ( typval_T * tv1 , typval_T * tv2 , bool ic ) 3948{ 3949// empty and NULL function name considered the same 3950char * s1 = tv1 -> v_type == VAR_FUNC ? tv1 -> vval . v_string : partial_name ( tv1 -> vval . v_partial ); 3951if ( s1 != NULL && * s1 == NUL ) { 3952s1 = NULL ; 3953} 3954char * s2 = tv2 -> v_type == VAR_FUNC ? tv2 -> vval . v_string : partial_name ( tv2 -> vval . v_partial ); 3955if ( s2 != NULL && * s2 == NUL ) { 3956s2 = NULL ; 3957} 3958if ( s1 == NULL || s2 == NULL ) { 3959if ( s1 != s2 ) { 3960return false; 3961} 3962} else if ( strcmp ( s1 , s2 ) != 0 ) { 3963return false; 3964} 3965 3966// empty dict and NULL dict is different 3967dict_T * d1 = tv1 -> v_type == VAR_FUNC ? NULL : tv1 -> vval . v_partial -> pt_dict ; 3968dict_T * d2 = tv2 -> v_type == VAR_FUNC ? NULL : tv2 -> vval . v_partial -> pt_dict ; 3969if ( d1 == NULL || d2 == NULL ) { 3970if ( d1 != d2 ) { 3971return false; 3972} 3973} else if (! tv_dict_equal ( d1 , d2 , ic )) { 3974return false; 3975} 3976 3977// empty list and no list considered the same 3978int a1 = tv1 -> v_type == VAR_FUNC ? 0 : tv1 -> vval . v_partial -> pt_argc ; 3979int a2 = tv2 -> v_type == VAR_FUNC ? 0 : tv2 -> vval . v_partial -> pt_argc ; 3980if ( a1 != a2 ) { 3981return false; 3982} 3983for ( int i = 0 ; i < a1 ; i ++ ) { 3984if (! tv_equal ( tv1 -> vval . v_partial -> pt_argv + i , 3985tv2 -> vval . v_partial -> pt_argv + i , ic )) { 3986return false; 3987} 3988} 3989return true; 3990} 3991 3992/// Get next (unique) copy ID 3993/// 3994/// Used for traversing nested structures e.g. when serializing them or garbage 3995/// collecting. 3996int get_copyID ( void ) 3997FUNC_ATTR_WARN_UNUSED_RESULT 3998{ 3999// CopyID for recursively traversing lists and dicts 4000// 4001// This value is needed to avoid endless recursiveness. Last bit is used for 4002// previous_funccal and normally ignored when comparing. 4003static int current_copyID = 0 ; 4004current_copyID += COPYID_INC ; 4005return current_copyID ; 4006} 4007 4008/// Garbage collection for lists and dictionaries. 4009/// 4010/// We use reference counts to be able to free most items right away when they 4011/// are no longer used. But for composite items it's possible that it becomes 4012/// unused while the reference count is > 0: When there is a recursive 4013/// reference. Example: 4014/// :let l = [1, 2, 3] 4015/// :let d = {9: l} 4016/// :let l[1] = d 4017/// 4018/// Since this is quite unusual we handle this with garbage collection: every 4019/// once in a while find out which lists and dicts are not referenced from any 4020/// variable. 4021/// 4022/// Here is a good reference text about garbage collection (refers to Python 4023/// but it applies to all reference-counting mechanisms): 4024/// http://python.ca/nas/python/gc/ 4025 4026/// Do garbage collection for lists and dicts. 4027/// 4028/// @param testing true if called from test_garbagecollect_now(). 4029/// 4030/// @return true if some memory was freed. 4031bool garbage_collect ( bool testing ) 4032{ 4033bool abort = false; 4034#define ABORTING ( func ) abort = abort || func 4035 4036if (! testing ) { 4037// Only do this once. 4038want_garbage_collect = false; 4039may_garbage_collect = false; 4040garbage_collect_at_exit = false; 4041} 4042 4043// The execution stack can grow big, limit the size. 4044if ( exestack . ga_maxlen - exestack . ga_len > 500 ) { 4045// Keep 150% of the current size, with a minimum of the growth size. 4046int n = exestack . ga_len / 2 ; 4047if ( n < exestack . ga_growsize ) { 4048n = exestack . ga_growsize ; 4049} 4050 4051// Don't make it bigger though. 4052if ( exestack . ga_len + n < exestack . ga_maxlen ) { 4053size_t new_len = ( size_t ) exestack . ga_itemsize * ( size_t )( exestack . ga_len + n ); 4054char * pp = xrealloc ( exestack . ga_data , new_len ); 4055exestack . ga_maxlen = exestack . ga_len + n ; 4056exestack . ga_data = pp ; 4057} 4058} 4059 4060// We advance by two (COPYID_INC) because we add one for items referenced 4061// through previous_funccal. 4062const int copyID = get_copyID (); 4063 4064// 1. Go through all accessible variables and mark all lists and dicts 4065// with copyID. 4066 4067// Don't free variables in the previous_funccal list unless they are only 4068// referenced through previous_funccal. This must be first, because if 4069// the item is referenced elsewhere the funccal must not be freed. 4070ABORTING ( set_ref_in_previous_funccal )( copyID ); 4071 4072// script-local variables 4073ABORTING ( garbage_collect_scriptvars )( copyID ); 4074 4075FOR_ALL_BUFFERS ( buf ) { 4076// buffer-local variables 4077ABORTING ( set_ref_in_item )( & buf -> b_bufvar . di_tv , copyID , NULL , NULL ); 4078 4079// buffer callback functions 4080ABORTING ( set_ref_in_callback )( & buf -> b_prompt_callback , copyID , NULL , NULL ); 4081ABORTING ( set_ref_in_callback )( & buf -> b_prompt_interrupt , copyID , NULL , NULL ); 4082ABORTING ( set_ref_in_callback )( & buf -> b_p_cfu , copyID , NULL , NULL ); 4083ABORTING ( set_ref_in_callback )( & buf -> b_p_ofu , copyID , NULL , NULL ); 4084ABORTING ( set_ref_in_callback )( & buf -> b_p_tsrfu , copyID , NULL , NULL ); 4085ABORTING ( set_ref_in_callback )( & buf -> b_p_tfu , copyID , NULL , NULL ); 4086ABORTING ( set_ref_in_callback )( & buf -> b_p_ffu , copyID , NULL , NULL ); 4087if (! abort && buf -> b_p_cpt_cb != NULL ) { 4088ABORTING ( set_ref_in_cpt_callbacks )( buf -> b_p_cpt_cb , buf -> b_p_cpt_count , copyID ); 4089} 4090} 4091 4092// 'completefunc', 'omnifunc' and 'thesaurusfunc' callbacks 4093ABORTING ( set_ref_in_insexpand_funcs )( copyID ); 4094 4095// 'operatorfunc' callback 4096ABORTING ( set_ref_in_opfunc )( copyID ); 4097 4098// 'tagfunc' callback 4099ABORTING ( set_ref_in_tagfunc )( copyID ); 4100 4101// 'findfunc' callback 4102ABORTING ( set_ref_in_findfunc )( copyID ); 4103 4104FOR_ALL_TAB_WINDOWS ( tp , wp ) { 4105// window-local variables 4106ABORTING ( set_ref_in_item )( & wp -> w_winvar . di_tv , copyID , NULL , NULL ); 4107} 4108// window-local variables in autocmd windows 4109for ( int i = 0 ; i < CTX_WIN_COUNT ; i ++ ) { 4110if ( ctx_win [ i ]. cw_win != NULL ) { 4111ABORTING ( set_ref_in_item )( & ctx_win [ i ]. cw_win -> w_winvar . di_tv , copyID , NULL , NULL ); 4112} 4113} 4114 4115// registers (ShaDa additional data) 4116{ 4117const void * reg_iter = NULL ; 4118do { 4119yankreg_T reg ; 4120char name = NUL ; 4121bool is_unnamed = false; 4122reg_iter = op_global_reg_iter ( reg_iter , & name , & reg , & is_unnamed ); 4123} while ( reg_iter != NULL ); 4124} 4125 4126// global marks (ShaDa additional data) 4127{ 4128const void * mark_iter = NULL ; 4129do { 4130xfmark_T fm ; 4131char name = NUL ; 4132mark_iter = mark_global_iter ( mark_iter , & name , & fm ); 4133} while ( mark_iter != NULL ); 4134} 4135 4136// tabpage-local variables 4137FOR_ALL_TABS ( tp ) { 4138ABORTING ( set_ref_in_item )( & tp -> tp_winvar . di_tv , copyID , NULL , NULL ); 4139} 4140 4141// global variables 4142ABORTING ( garbage_collect_globvars )( copyID ); 4143 4144// function-local variables 4145ABORTING ( set_ref_in_call_stack )( copyID ); 4146 4147// named functions (matters for closures) 4148ABORTING ( set_ref_in_functions )( copyID ); 4149 4150// Channels 4151{ 4152Channel * data ; 4153map_foreach_value ( & channels , data , { 4154set_ref_in_callback_reader ( & data -> on_data , copyID , NULL , NULL ); 4155set_ref_in_callback_reader ( & data -> on_stderr , copyID , NULL , NULL ); 4156set_ref_in_callback ( & data -> on_exit , copyID , NULL , NULL ); 4157}) 4158} 4159 4160// Timers 4161{ 4162timer_T * timer ; 4163map_foreach_value ( & timers , timer , { 4164set_ref_in_callback ( & timer -> callback , copyID , NULL , NULL ); 4165}) 4166} 4167 4168// function call arguments, if v:testing is set. 4169ABORTING ( set_ref_in_func_args )( copyID ); 4170 4171// v: vars 4172ABORTING ( garbage_collect_vimvars )( copyID ); 4173 4174ABORTING ( set_ref_in_quickfix )( copyID ); 4175 4176bool did_free = false; 4177if (! abort ) { 4178// 2. Free lists and dictionaries that are not referenced. 4179did_free = free_unref_items ( copyID ); 4180 4181// 3. Check if any funccal can be freed now. 4182// This may call us back recursively. 4183did_free = free_unref_funccal ( copyID , testing ) || did_free ; 4184} else if ( p_verbose > 0 ) { 4185verb_msg ( _ ( "Not enough memory to set references, garbage collection aborted!" )); 4186} 4187#undef ABORTING 4188return did_free ; 4189} 4190 4191/// Free lists and dictionaries that are no longer referenced. 4192/// 4193/// @note This function may only be called from garbage_collect(). 4194/// 4195/// @param copyID Free lists/dictionaries that don't have this ID. 4196/// 4197/// @return true, if something was freed. 4198static int free_unref_items ( int copyID ) 4199{ 4200bool did_free = false; 4201 4202// Let all "free" functions know that we are here. This means no 4203// dictionaries, lists, or jobs are to be freed, because we will 4204// do that here. 4205tv_in_free_unref_items = true; 4206 4207// PASS 1: free the contents of the items. We don't free the items 4208// themselves yet, so that it is possible to decrement refcount counters. 4209 4210// Go through the list of dicts and free items without the copyID. 4211// Don't free dicts that are referenced internally. 4212for ( dict_T * dd = gc_first_dict ; dd != NULL ; dd = dd -> dv_used_next ) { 4213if (( dd -> dv_copyID & COPYID_MASK ) != ( copyID & COPYID_MASK )) { 4214// Free the Dictionary and ordinary items it contains, but don't 4215// recurse into Lists and Dictionaries, they will be in the list 4216// of dicts or list of lists. 4217tv_dict_free_contents ( dd ); 4218did_free = true; 4219} 4220} 4221 4222// Go through the list of lists and free items without the copyID. 4223// But don't free a list that has a watcher (used in a for loop), these 4224// are not referenced anywhere. 4225for ( list_T * ll = gc_first_list ; ll != NULL ; ll = ll -> lv_used_next ) { 4226if (( tv_list_copyid ( ll ) & COPYID_MASK ) != ( copyID & COPYID_MASK ) 4227&& ! tv_list_has_watchers ( ll )) { 4228// Free the List and ordinary items it contains, but don't recurse 4229// into Lists and Dictionaries, they will be in the list of dicts 4230// or list of lists. 4231tv_list_free_contents ( ll ); 4232did_free = true; 4233} 4234} 4235 4236// PASS 2: free the items themselves. 4237dict_T * dd_next ; 4238for ( dict_T * dd = gc_first_dict ; dd != NULL ; dd = dd_next ) { 4239dd_next = dd -> dv_used_next ; 4240if (( dd -> dv_copyID & COPYID_MASK ) != ( copyID & COPYID_MASK )) { 4241tv_dict_free_dict ( dd ); 4242} 4243} 4244 4245list_T * ll_next ; 4246for ( list_T * ll = gc_first_list ; ll != NULL ; ll = ll_next ) { 4247ll_next = ll -> lv_used_next ; 4248if (( ll -> lv_copyID & COPYID_MASK ) != ( copyID & COPYID_MASK ) 4249&& ! tv_list_has_watchers ( ll )) { 4250// Free the List and ordinary items it contains, but don't recurse 4251// into Lists and Dictionaries, they will be in the list of dicts 4252// or list of lists. 4253tv_list_free_list ( ll ); 4254} 4255} 4256tv_in_free_unref_items = false; 4257return did_free ; 4258} 4259 4260/// Mark all lists and dicts referenced through hashtab "ht" with "copyID". 4261/// 4262/// @param ht Hashtab content will be marked. 4263/// @param copyID New mark for lists and dicts. 4264/// @param list_stack Used to add lists to be marked. Can be NULL. 4265/// 4266/// @returns true if setting references failed somehow. 4267bool set_ref_in_ht ( hashtab_T * ht , int copyID , list_stack_T ** list_stack ) 4268FUNC_ATTR_WARN_UNUSED_RESULT 4269{ 4270bool abort = false; 4271ht_stack_T * ht_stack = NULL ; 4272 4273hashtab_T * cur_ht = ht ; 4274while (true) { 4275if (! abort ) { 4276// Mark each item in the hashtab. If the item contains a hashtab 4277// it is added to ht_stack, if it contains a list it is added to 4278// list_stack. 4279HASHTAB_ITER ( cur_ht , hi , { 4280abort = abort || set_ref_in_item ( & TV_DICT_HI2DI ( hi ) -> di_tv , copyID , & ht_stack , list_stack ); 4281}); 4282} 4283 4284if ( ht_stack == NULL ) { 4285break; 4286} 4287 4288// take an item from the stack 4289cur_ht = ht_stack -> ht ; 4290ht_stack_T * tempitem = ht_stack ; 4291ht_stack = ht_stack -> prev ; 4292xfree ( tempitem ); 4293} 4294 4295return abort ; 4296} 4297 4298/// Mark all lists and dicts referenced through list "l" with "copyID". 4299/// 4300/// @param l List content will be marked. 4301/// @param copyID New mark for lists and dicts. 4302/// @param ht_stack Used to add hashtabs to be marked. Can be NULL. 4303/// 4304/// @returns true if setting references failed somehow. 4305bool set_ref_in_list_items ( list_T * l , int copyID , ht_stack_T ** ht_stack ) 4306FUNC_ATTR_WARN_UNUSED_RESULT 4307{ 4308bool abort = false; 4309list_stack_T * list_stack = NULL ; 4310 4311list_T * cur_l = l ; 4312while (true) { 4313// Mark each item in the list. If the item contains a hashtab 4314// it is added to ht_stack, if it contains a list it is added to 4315// list_stack. 4316TV_LIST_ITER ( cur_l , li , { 4317if ( abort ) { 4318break; 4319} 4320abort = set_ref_in_item ( TV_LIST_ITEM_TV ( li ), copyID , ht_stack , 4321& list_stack ); 4322}); 4323 4324if ( list_stack == NULL ) { 4325break; 4326} 4327 4328// take an item from the stack 4329cur_l = list_stack -> list ; 4330list_stack_T * tempitem = list_stack ; 4331list_stack = list_stack -> prev ; 4332xfree ( tempitem ); 4333} 4334 4335return abort ; 4336} 4337 4338/// Mark the dict "dd" with "copyID". 4339/// Also see set_ref_in_item(). 4340static bool set_ref_in_item_dict ( dict_T * dd , int copyID , ht_stack_T ** ht_stack , 4341list_stack_T ** list_stack ) 4342{ 4343if ( dd == NULL || dd -> dv_copyID == copyID ) { 4344return false; 4345} 4346 4347// Didn't see this dict yet. 4348dd -> dv_copyID = copyID ; 4349if ( ht_stack == NULL ) { 4350return set_ref_in_ht ( & dd -> dv_hashtab , copyID , list_stack ); 4351} 4352 4353ht_stack_T * const newitem = xmalloc (sizeof( ht_stack_T )); 4354newitem -> ht = & dd -> dv_hashtab ; 4355newitem -> prev = * ht_stack ; 4356* ht_stack = newitem ; 4357 4358QUEUE * w = NULL ; 4359DictWatcher * watcher = NULL ; 4360QUEUE_FOREACH ( w , & dd -> watchers , { 4361watcher = tv_dict_watcher_node_data ( w ); 4362set_ref_in_callback ( & watcher -> callback , copyID , ht_stack , list_stack ); 4363}) 4364 4365return false; 4366} 4367 4368/// Mark the list "ll" with "copyID". 4369/// Also see set_ref_in_item(). 4370static bool set_ref_in_item_list ( list_T * ll , int copyID , ht_stack_T ** ht_stack , 4371list_stack_T ** list_stack ) 4372{ 4373if ( ll == NULL || ll -> lv_copyID == copyID ) { 4374return false; 4375} 4376 4377// Didn't see this list yet. 4378ll -> lv_copyID = copyID ; 4379if ( list_stack == NULL ) { 4380return set_ref_in_list_items ( ll , copyID , ht_stack ); 4381} 4382 4383list_stack_T * const newitem = xmalloc (sizeof( list_stack_T )); 4384newitem -> list = ll ; 4385newitem -> prev = * list_stack ; 4386* list_stack = newitem ; 4387 4388return false; 4389} 4390 4391/// Mark the partial "pt" with "copyID". 4392/// Also see set_ref_in_item(). 4393static bool set_ref_in_item_partial ( partial_T * pt , int copyID , ht_stack_T ** ht_stack , 4394list_stack_T ** list_stack ) 4395{ 4396if ( pt == NULL || pt -> pt_copyID == copyID ) { 4397return false; 4398} 4399 4400// Didn't see this partial yet. 4401pt -> pt_copyID = copyID ; 4402 4403bool abort = set_ref_in_func ( pt -> pt_name , pt -> pt_func , copyID ); 4404 4405if ( pt -> pt_dict != NULL ) { 4406typval_T dtv ; 4407 4408dtv . v_type = VAR_DICT ; 4409dtv . vval . v_dict = pt -> pt_dict ; 4410abort = abort || set_ref_in_item ( & dtv , copyID , ht_stack , list_stack ); 4411} 4412 4413for ( int i = 0 ; i < pt -> pt_argc ; i ++ ) { 4414abort = abort || set_ref_in_item ( & pt -> pt_argv [ i ], copyID , ht_stack , list_stack ); 4415} 4416 4417return abort ; 4418} 4419 4420/// Mark all lists and dicts referenced through typval "tv" with "copyID". 4421/// 4422/// @param tv Typval content will be marked. 4423/// @param copyID New mark for lists and dicts. 4424/// @param ht_stack Used to add hashtabs to be marked. Can be NULL. 4425/// @param list_stack Used to add lists to be marked. Can be NULL. 4426/// 4427/// @returns true if setting references failed somehow. 4428bool set_ref_in_item ( typval_T * tv , int copyID , ht_stack_T ** ht_stack , list_stack_T ** list_stack ) 4429FUNC_ATTR_WARN_UNUSED_RESULT 4430{ 4431bool abort = false; 4432 4433switch ( tv -> v_type ) { 4434case VAR_DICT : 4435return set_ref_in_item_dict ( tv -> vval . v_dict , copyID , ht_stack , list_stack ); 4436case VAR_LIST : 4437return set_ref_in_item_list ( tv -> vval . v_list , copyID , ht_stack , list_stack ); 4438case VAR_FUNC : 4439abort = set_ref_in_func ( tv -> vval . v_string , NULL , copyID ); 4440break; 4441case VAR_PARTIAL : 4442return set_ref_in_item_partial ( tv -> vval . v_partial , copyID , ht_stack , list_stack ); 4443case VAR_UNKNOWN : 4444case VAR_BOOL : 4445case VAR_SPECIAL : 4446case VAR_FLOAT : 4447case VAR_NUMBER : 4448case VAR_STRING : 4449case VAR_BLOB : 4450break; 4451} 4452return abort ; 4453} 4454 4455/// Get the key for #{key: val} into "tv" and advance "arg". 4456/// 4457/// @return FAIL when there is no valid key. 4458static int get_literal_key ( char ** arg , typval_T * tv ) 4459FUNC_ATTR_NONNULL_ALL 4460{ 4461char * p ; 4462 4463if (! ASCII_ISALNUM ( ** arg ) && ** arg != '_' && ** arg != '-' ) { 4464return FAIL ; 4465} 4466for ( p = * arg ; ASCII_ISALNUM ( * p ) || * p == '_' || * p == '-' ; p ++ ) {} 4467tv -> v_type = VAR_STRING ; 4468tv -> vval . v_string = xmemdupz ( * arg , ( size_t )( p - * arg )); 4469 4470* arg = skipwhite ( p ); 4471return OK ; 4472} 4473 4474/// Allocate a variable for a Dictionary and fill it from "*arg". 4475/// 4476/// @param arg "*arg" points to the "{". 4477/// @param literal true for #{key: val} 4478/// 4479/// @return OK or FAIL. Returns NOTDONE for {expr}. 4480static int eval_dict ( char ** arg , typval_T * rettv , evalarg_T * const evalarg , bool literal ) 4481{ 4482const bool evaluate = evalarg == NULL ? false : evalarg -> eval_flags & EVAL_EVALUATE ; 4483typval_T tv ; 4484char * key = NULL ; 4485char * curly_expr = skipwhite ( * arg + 1 ); 4486char buf [ NUMBUFLEN ]; 4487 4488// First check if it's not a curly-braces expression: {expr}. 4489// Must do this without evaluating, otherwise a function may be called 4490// twice. Unfortunately this means we need to call eval1() twice for the 4491// first item. 4492// "{}" is an empty Dictionary. 4493// "#{abc}" is never a curly-braces expression. 4494if ( * curly_expr != '}' 4495&& ! literal 4496&& eval1 ( & curly_expr , & tv , NULL ) == OK 4497&& * skipwhite ( curly_expr ) == '}' ) { 4498return NOTDONE ; 4499} 4500 4501dict_T * d = NULL ; 4502if ( evaluate ) { 4503d = tv_dict_alloc (); 4504} 4505typval_T tvkey ; 4506tvkey . v_type = VAR_UNKNOWN ; 4507tv . v_type = VAR_UNKNOWN ; 4508 4509* arg = skipwhite ( * arg + 1 ); 4510while ( ** arg != '}' && ** arg != NUL ) { 4511if (( literal 4512? get_literal_key ( arg , & tvkey ) 4513: eval1 ( arg , & tvkey , evalarg )) == FAIL ) { // recursive! 4514goto failret ; 4515} 4516if ( ** arg != ':' ) { 4517semsg ( _ ( "E720: Missing colon in Dictionary: %s" ), * arg ); 4518tv_clear ( & tvkey ); 4519goto failret ; 4520} 4521if ( evaluate ) { 4522key = ( char * ) tv_get_string_buf_chk ( & tvkey , buf ); 4523if ( key == NULL ) { 4524// "key" is NULL when tv_get_string_buf_chk() gave an errmsg 4525tv_clear ( & tvkey ); 4526goto failret ; 4527} 4528} 4529 4530* arg = skipwhite ( * arg + 1 ); 4531if ( eval1 ( arg , & tv , evalarg ) == FAIL ) { // Recursive! 4532tv_clear ( & tvkey ); 4533goto failret ; 4534} 4535if ( evaluate ) { 4536dictitem_T * item = tv_dict_find ( d , key , -1 ); 4537if ( item != NULL ) { 4538semsg ( _ ( "E721: Duplicate key in Dictionary: \"%s\"" ), key ); 4539tv_clear ( & tvkey ); 4540tv_clear ( & tv ); 4541goto failret ; 4542} 4543item = tv_dict_item_alloc ( key ); 4544item -> di_tv = tv ; 4545item -> di_tv . v_lock = VAR_UNLOCKED ; 4546if ( tv_dict_add ( d , item ) == FAIL ) { 4547tv_dict_item_free ( item ); 4548} 4549} 4550tv_clear ( & tvkey ); 4551 4552// the comma must come after the value 4553bool had_comma = ** arg == ',' ; 4554if ( had_comma ) { 4555* arg = skipwhite ( * arg + 1 ); 4556} 4557 4558if ( ** arg == '}' ) { 4559break; 4560} 4561if (! had_comma ) { 4562semsg ( _ ( "E722: Missing comma in Dictionary: %s" ), * arg ); 4563goto failret ; 4564} 4565} 4566 4567if ( ** arg != '}' ) { 4568semsg ( _ ( "E723: Missing end of Dictionary '}': %s" ), * arg ); 4569failret : 4570if ( d != NULL ) { 4571tv_dict_free ( d ); 4572} 4573return FAIL ; 4574} 4575 4576* arg = skipwhite ( * arg + 1 ); 4577if ( evaluate ) { 4578tv_dict_set_ret ( rettv , d ); 4579} 4580 4581return OK ; 4582} 4583 4584/// Evaluate a literal dictionary: #{key: val, key: val} 4585/// "*arg" points to the "#". 4586/// On return, "*arg" points to the character after the Dict. 4587/// Return OK or FAIL. Returns NOTDONE for {expr}. 4588static int eval_lit_dict ( char ** arg , typval_T * rettv , evalarg_T * const evalarg ) 4589{ 4590int ret = OK ; 4591 4592if (( * arg )[ 1 ] == '{' ) { 4593( * arg ) ++ ; 4594ret = eval_dict ( arg , rettv , evalarg , true); 4595} else { 4596ret = NOTDONE ; 4597} 4598 4599return ret ; 4600} 4601 4602/// Convert the string to a floating point number 4603/// 4604/// This uses strtod(). setlocale(LC_NUMERIC, "C") has been used earlier to 4605/// make sure this always uses a decimal point. 4606/// 4607/// @param[in] text String to convert. 4608/// @param[out] ret_value Location where conversion result is saved. 4609/// 4610/// @return Length of the text that was consumed. 4611size_t string2float (const char * const text , float_T * const ret_value ) 4612FUNC_ATTR_NONNULL_ALL 4613{ 4614// MS-Windows does not deal with "inf" and "nan" properly 4615if ( STRNICMP ( text , "inf" , 3 ) == 0 ) { 4616* ret_value = ( float_T ) INFINITY ; 4617return 3 ; 4618} 4619if ( STRNICMP ( text , "-inf" , 4 ) == 0 ) { 4620* ret_value = ( float_T )( - INFINITY ); 4621return 4 ; 4622} 4623if ( STRNICMP ( text , "nan" , 3 ) == 0 ) { 4624* ret_value = ( float_T ) NAN ; 4625return 3 ; 4626} 4627char * s = NULL ; 4628* ret_value = strtod ( text , & s ); 4629return ( size_t )( s - text ); 4630} 4631 4632/// Get the value of an environment variable. 4633/// 4634/// If the environment variable was not set, silently assume it is empty. 4635/// 4636/// @param arg Points to the '$'. It is advanced to after the name. 4637/// 4638/// @return FAIL if the name is invalid. 4639static int eval_env_var ( char ** arg , typval_T * rettv , int evaluate ) 4640{ 4641( * arg ) ++ ; 4642char * name = * arg ; 4643int len = get_env_len ((const char ** ) arg ); 4644 4645if ( evaluate ) { 4646if ( len == 0 ) { 4647return FAIL ; // Invalid empty name. 4648} 4649int cc = ( int ) name [ len ]; 4650name [ len ] = NUL ; 4651// First try vim_getenv(), fast for normal environment vars. 4652char * string = vim_getenv ( name ); 4653if ( string == NULL || * string == NUL ) { 4654xfree ( string ); 4655 4656// Next try expanding things like $VIM and ${HOME}. 4657string = expand_env_save ( name - 1 ); 4658if ( string != NULL && * string == '$' ) { 4659XFREE_CLEAR ( string ); 4660} 4661} 4662name [ len ] = ( char ) cc ; 4663rettv -> v_type = VAR_STRING ; 4664rettv -> vval . v_string = string ; 4665rettv -> v_lock = VAR_UNLOCKED ; 4666} 4667 4668return OK ; 4669} 4670 4671/// Builds a process argument vector from a Vimscript object (typval_T). 4672/// 4673/// @param[in] cmd_tv Vimscript object 4674/// @param[out] cmd Returns the command or executable name. 4675/// @param[out] executable Returns `false` if argv[0] is not executable. 4676/// 4677/// @return Result of `shell_build_argv()` if `cmd_tv` is a String. 4678/// Else, string values of `cmd_tv` copied to a (char **) list with 4679/// argv[0] resolved to full path ($PATHEXT-resolved on Windows). 4680char ** tv_to_argv ( typval_T * cmd_tv , const char ** cmd , bool * executable ) 4681{ 4682if ( cmd_tv -> v_type == VAR_STRING ) { // String => "shell semantics". 4683const char * cmd_str = tv_get_string ( cmd_tv ); 4684if ( cmd ) { 4685* cmd = cmd_str ; 4686} 4687return shell_build_argv ( cmd_str , NULL ); 4688} 4689 4690if ( cmd_tv -> v_type != VAR_LIST ) { 4691semsg ( _ ( e_invarg2 ), "expected String or List" ); 4692return NULL ; 4693} 4694 4695list_T * argl = cmd_tv -> vval . v_list ; 4696int argc = tv_list_len ( argl ); 4697if (! argc ) { 4698emsg ( _ ( e_invarg )); // List must have at least one item. 4699return NULL ; 4700} 4701 4702const char * arg0 = tv_get_string_chk ( TV_LIST_ITEM_TV ( tv_list_first ( argl ))); 4703char * exe_resolved = NULL ; 4704if (! arg0 || ! os_can_exe ( arg0 , & exe_resolved , true)) { 4705if ( arg0 && executable ) { 4706char buf [ IOSIZE ]; 4707snprintf ( buf , sizeof( buf ), "'%s' is not executable" , arg0 ); 4708semsg ( _ ( e_invargNval ), "cmd" , buf ); 4709* executable = false; 4710} 4711return NULL ; 4712} 4713 4714if ( cmd ) { 4715* cmd = exe_resolved ; 4716} 4717 4718// Build the argument vector 4719int i = 0 ; 4720char ** argv = xcalloc (( size_t ) argc + 1 , sizeof( char * )); 4721TV_LIST_ITER_CONST ( argl , arg , { 4722const char * a = tv_get_string_chk ( TV_LIST_ITEM_TV ( arg )); 4723if (! a ) { 4724// Did emsg in tv_get_string_chk; just deallocate argv. 4725shell_free_argv ( argv ); 4726xfree ( exe_resolved ); 4727return NULL ; 4728} 4729argv [ i ++ ] = xstrdup ( a ); 4730}); 4731// Replace argv[0] with absolute path. The only reason for this is to make 4732// $PATHEXT work on Windows with jobstart([…]). #9569 4733xfree ( argv [ 0 ]); 4734argv [ 0 ] = exe_resolved ; 4735 4736return argv ; 4737} 4738 4739static list_T * string_to_list (const char * str , size_t len , const bool keepempty ) 4740{ 4741if (! keepempty && str [ len - 1 ] == NL ) { 4742len -- ; 4743} 4744list_T * const list = tv_list_alloc ( kListLenMayKnow ); 4745encode_list_write ( list , str , len ); 4746return list ; 4747} 4748 4749/// os_system wrapper. Handles 'verbose', :profile, and v:shell_error. 4750static void get_system_output_as_rettv ( typval_T * argvars , typval_T * rettv , bool retlist ) 4751{ 4752proftime_T wait_time ; 4753bool profiling = do_profiling == PROF_YES ; 4754 4755rettv -> v_type = VAR_STRING ; 4756rettv -> vval . v_string = NULL ; 4757 4758if ( check_secure ()) { 4759return; 4760} 4761 4762// get input to the shell command (if any), and its length 4763ptrdiff_t input_len ; 4764char * input = save_tv_as_string ( & argvars [ 1 ], & input_len , false, false); 4765if ( input_len < 0 ) { 4766assert ( input == NULL ); 4767return; 4768} 4769 4770// get shell command to execute 4771bool executable = true; 4772char ** argv = tv_to_argv ( & argvars [ 0 ], NULL , & executable ); 4773if (! argv ) { 4774if (! executable ) { 4775set_vim_var_nr ( VV_SHELL_ERROR , -1 ); 4776} 4777xfree ( input ); 4778return; // Already did emsg. 4779} 4780 4781if ( p_verbose > 3 ) { 4782char * cmdstr = shell_argv_to_str ( argv ); 4783verbose_enter_scroll (); 4784smsg ( 0 , _ ( "Executing command: \"%s\"" ), cmdstr ); 4785msg_puts ( "\n\n" ); 4786verbose_leave_scroll (); 4787xfree ( cmdstr ); 4788} 4789 4790if ( profiling ) { 4791prof_child_enter ( & wait_time ); 4792} 4793 4794// execute the command 4795size_t nread = 0 ; 4796char * res = NULL ; 4797int status = os_system ( argv , input , ( size_t ) input_len , & res , & nread ); 4798 4799if ( profiling ) { 4800prof_child_exit ( & wait_time ); 4801} 4802 4803xfree ( input ); 4804 4805set_vim_var_nr ( VV_SHELL_ERROR , status ); 4806 4807if ( res == NULL ) { 4808if ( retlist ) { 4809// return an empty list when there's no output 4810tv_list_alloc_ret ( rettv , 0 ); 4811} else { 4812rettv -> vval . v_string = xstrdup ( "" ); 4813} 4814return; 4815} 4816 4817if ( retlist ) { 4818int keepempty = 0 ; 4819if ( argvars [ 1 ]. v_type != VAR_UNKNOWN && argvars [ 2 ]. v_type != VAR_UNKNOWN ) { 4820keepempty = ( int ) tv_get_number ( & argvars [ 2 ]); 4821} 4822rettv -> vval . v_list = string_to_list ( res , nread , ( bool ) keepempty ); 4823tv_list_ref ( rettv -> vval . v_list ); 4824rettv -> v_type = VAR_LIST ; 4825 4826xfree ( res ); 4827} else { 4828// res may contain several NULs before the final terminating one. 4829// Replace them with SOH (1) like in get_cmd_output() to avoid truncation. 4830memchrsub ( res , NUL , 1 , nread ); 4831#ifdef USE_CRNL 4832// translate <CR><NL> into <NL> 4833char * d = res ; 4834for ( char * s = res ; * s ; s ++ ) { 4835if ( s [ 0 ] == CAR && s [ 1 ] == NL ) { 4836s ++ ; 4837} 4838 4839* d ++ = * s ; 4840} 4841 4842* d = NUL ; 4843#endif 4844rettv -> vval . v_string = res ; 4845} 4846} 4847 4848/// f_system - the Vimscript system() function 4849void f_system ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 4850{ 4851get_system_output_as_rettv ( argvars , rettv , false); 4852} 4853 4854void f_systemlist ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 4855{ 4856get_system_output_as_rettv ( argvars , rettv , true); 4857} 4858 4859/// Get a callback from "arg". It can be a Funcref or a function name. 4860bool callback_from_typval ( Callback * const callback , const typval_T * const arg ) 4861FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 4862{ 4863int r = OK ; 4864 4865if ( arg -> v_type == VAR_PARTIAL && arg -> vval . v_partial != NULL ) { 4866callback -> data . partial = arg -> vval . v_partial ; 4867callback -> data . partial -> pt_refcount ++ ; 4868callback -> type = kCallbackPartial ; 4869} else if ( arg -> v_type == VAR_STRING 4870&& arg -> vval . v_string != NULL 4871&& ascii_isdigit ( * arg -> vval . v_string )) { 4872r = FAIL ; 4873} else if ( arg -> v_type == VAR_FUNC || arg -> v_type == VAR_STRING ) { 4874char * name = arg -> vval . v_string ; 4875if ( name == NULL ) { 4876r = FAIL ; 4877} else if ( * name == NUL ) { 4878callback -> type = kCallbackNone ; 4879callback -> data . funcref = NULL ; 4880} else { 4881callback -> data . funcref = NULL ; 4882if ( arg -> v_type == VAR_STRING ) { 4883callback -> data . funcref = get_scriptlocal_funcname ( name ); 4884} 4885if ( callback -> data . funcref == NULL ) { 4886callback -> data . funcref = xstrdup ( name ); 4887} 4888func_ref ( callback -> data . funcref ); 4889callback -> type = kCallbackFuncref ; 4890} 4891} else if ( nlua_is_table_from_lua ( arg )) { 4892// TODO(tjdvries): UnifiedCallback 4893char * name = nlua_register_table_as_callable ( arg ); 4894 4895if ( name != NULL ) { 4896callback -> data . funcref = xstrdup ( name ); 4897callback -> type = kCallbackFuncref ; 4898} else { 4899r = FAIL ; 4900} 4901} else if ( arg -> v_type == VAR_SPECIAL 4902|| ( arg -> v_type == VAR_NUMBER && arg -> vval . v_number == 0 )) { 4903callback -> type = kCallbackNone ; 4904callback -> data . funcref = NULL ; 4905} else { 4906r = FAIL ; 4907} 4908 4909if ( r == FAIL ) { 4910emsg ( _ ( "E921: Invalid callback argument" )); 4911return false; 4912} 4913return true; 4914} 4915 4916static int callback_depth = 0 ; 4917 4918int get_callback_depth ( void ) 4919{ 4920return callback_depth ; 4921} 4922 4923/// @return whether the callback could be called. 4924bool callback_call ( Callback * const callback , const int argcount_in , typval_T * const argvars_in , 4925typval_T * const rettv ) 4926FUNC_ATTR_NONNULL_ALL 4927{ 4928if ( callback_depth > p_mfd ) { 4929emsg ( _ ( e_command_too_recursive )); 4930return false; 4931} 4932 4933partial_T * partial ; 4934char * name ; 4935switch ( callback -> type ) { 4936case kCallbackFuncref : 4937name = callback -> data . funcref ; 4938int len = ( int ) strlen ( name ); 4939if ( len >= 6 && ! memcmp ( name , "v:lua." , 6 )) { 4940name += 6 ; 4941len = check_luafunc_name ( name , false); 4942if ( len == 0 ) { 4943return false; 4944} 4945partial = get_vim_var_partial ( VV_LUA ); 4946} else { 4947partial = NULL ; 4948} 4949break; 4950 4951case kCallbackPartial : 4952partial = callback -> data . partial ; 4953name = partial_name ( partial ); 4954break; 4955 4956case kCallbackLua : { 4957// Call the Lua function with the given args and return its result via rettv. 4958Arena arena = ARENA_EMPTY ; 4959Array luaargs = arena_array ( & arena , ( size_t ) argcount_in ); 4960for ( int i = 0 ; i < argcount_in ; i ++ ) { 4961ADD_C ( luaargs , vim_to_object ( & argvars_in [ i ], & arena , false)); 4962} 4963Error err = ERROR_INIT ; 4964callback_depth ++ ; 4965Object result = nlua_call_ref ( callback -> data . luaref , NULL , luaargs , kRetObject , & arena , & err ); 4966callback_depth -- ; 4967const bool ok = ! ERROR_SET ( & err ); 4968if (! ok ) { 4969semsg_multiline ( "emsg" , "E5108: %s" , err . msg ); 4970api_clear_error ( & err ); 4971} else { 4972object_to_vim ( result , rettv , NULL ); 4973} 4974arena_mem_free ( arena_finish ( & arena )); 4975return ok ; 4976} 4977 4978case kCallbackExpr : { 4979// Evaluate Vimscript expression ("expr" options). 4980// Optimization: If the expression is "FuncName()" call the function directly. 4981callback_depth ++ ; 4982int r = eval0_simple_funccal ( skipwhite ( callback -> data . expr ), rettv , NULL , & EVALARG_EVALUATE ); 4983callback_depth -- ; 4984clear_evalarg ( & EVALARG_EVALUATE , NULL ); 4985return r == OK ; 4986} 4987 4988case kCallbackNone : 4989return false; 4990break; 4991} 4992 4993funcexe_T funcexe = FUNCEXE_INIT ; 4994funcexe . fe_firstline = curwin -> w_cursor . lnum ; 4995funcexe . fe_lastline = curwin -> w_cursor . lnum ; 4996funcexe . fe_evaluate = true; 4997funcexe . fe_partial = partial ; 4998 4999callback_depth ++ ; 5000int ret = call_func ( name , -1 , rettv , argcount_in , argvars_in , & funcexe ); 5001callback_depth -- ; 5002return ret ; 5003} 5004 5005bool set_ref_in_callback ( Callback * callback , int copyID , ht_stack_T ** ht_stack , 5006list_stack_T ** list_stack ) 5007{ 5008typval_T tv ; 5009switch ( callback -> type ) { 5010case kCallbackExpr : 5011case kCallbackFuncref : 5012case kCallbackNone : 5013break; 5014 5015case kCallbackLua : 5016// LuaRef is owned by the Lua registry, not traced by Vimscript's mark-sweep; nothing to mark. 5017break; 5018 5019case kCallbackPartial : 5020tv . v_type = VAR_PARTIAL ; 5021tv . vval . v_partial = callback -> data . partial ; 5022return set_ref_in_item ( & tv , copyID , ht_stack , list_stack ); 5023} 5024return false; 5025} 5026 5027static bool set_ref_in_callback_reader ( CallbackReader * reader , int copyID , ht_stack_T ** ht_stack , 5028list_stack_T ** list_stack ) 5029{ 5030if ( set_ref_in_callback ( & reader -> cb , copyID , ht_stack , list_stack )) { 5031return true; 5032} 5033 5034if ( reader -> self ) { 5035typval_T tv ; 5036tv . v_type = VAR_DICT ; 5037tv . vval . v_dict = reader -> self ; 5038return set_ref_in_item ( & tv , copyID , ht_stack , list_stack ); 5039} 5040return false; 5041} 5042 5043timer_T * find_timer_by_nr ( varnumber_T xx ) 5044{ 5045return pmap_get ( uint64_t )( & timers , ( uint64_t ) xx ); 5046} 5047 5048void add_timer_info ( typval_T * rettv , timer_T * timer ) 5049{ 5050list_T * list = rettv -> vval . v_list ; 5051dict_T * dict = tv_dict_alloc (); 5052 5053tv_list_append_dict ( list , dict ); 5054tv_dict_add_nr ( dict , S_LEN ( "id" ), timer -> timer_id ); 5055tv_dict_add_nr ( dict , S_LEN ( "time" ), timer -> timeout ); 5056tv_dict_add_nr ( dict , S_LEN ( "paused" ), timer -> paused ); 5057 5058tv_dict_add_nr ( dict , S_LEN ( "repeat" ), 5059( timer -> repeat_count < 0 ? -1 : timer -> repeat_count )); 5060 5061dictitem_T * di = tv_dict_item_alloc ( "callback" ); 5062if ( tv_dict_add ( dict , di ) == FAIL ) { 5063xfree ( di ); 5064return; 5065} 5066 5067callback_put ( & timer -> callback , & di -> di_tv ); 5068} 5069 5070void add_timer_info_all ( typval_T * rettv ) 5071{ 5072tv_list_alloc_ret ( rettv , map_size ( & timers )); 5073timer_T * timer ; 5074map_foreach_value ( & timers , timer , { 5075if (! timer -> stopped || timer -> refcount > 1 ) { 5076add_timer_info ( rettv , timer ); 5077} 5078}) 5079} 5080 5081/// invoked on the main loop 5082void timer_due_cb ( TimeWatcher * tw , void * data ) 5083{ 5084timer_T * timer = ( timer_T * ) data ; 5085int save_did_emsg = did_emsg ; 5086const int called_emsg_before = called_emsg ; 5087 5088if ( timer -> stopped || timer -> paused ) { 5089return; 5090} 5091 5092timer -> refcount ++ ; 5093// if repeat was negative repeat forever 5094if ( timer -> repeat_count >= 0 && -- timer -> repeat_count == 0 ) { 5095timer_stop ( timer ); 5096} 5097 5098typval_T argv [ 2 ] = { TV_INITIAL_VALUE , TV_INITIAL_VALUE }; 5099argv [ 0 ]. v_type = VAR_NUMBER ; 5100argv [ 0 ]. vval . v_number = timer -> timer_id ; 5101typval_T rettv = TV_INITIAL_VALUE ; 5102 5103callback_call ( & timer -> callback , 1 , argv , & rettv ); 5104 5105// Handle error message 5106if ( called_emsg > called_emsg_before && did_emsg ) { 5107timer -> emsg_count ++ ; 5108if ( did_throw ) { 5109discard_current_exception (); 5110} 5111} 5112did_emsg = save_did_emsg ; 5113 5114if ( timer -> emsg_count >= 3 ) { 5115timer_stop ( timer ); 5116} 5117 5118tv_clear ( & rettv ); 5119 5120if (! timer -> stopped && timer -> timeout == 0 ) { 5121// special case: timeout=0 means the callback will be 5122// invoked again on the next event loop tick. 5123// we don't use uv_idle_t to not spin the event loop 5124// when the main loop is blocked. 5125time_watcher_start ( & timer -> tw , timer_due_cb , 0 , 0 ); 5126} 5127timer_decref ( timer ); 5128} 5129 5130uint64_t timer_start (const int64_t timeout , const int repeat_count , const Callback * const callback ) 5131{ 5132timer_T * timer = xmalloc (sizeof * timer ); 5133timer -> refcount = 1 ; 5134timer -> stopped = false; 5135timer -> paused = false; 5136timer -> emsg_count = 0 ; 5137timer -> repeat_count = repeat_count ; 5138timer -> timeout = timeout ; 5139timer -> timer_id = ( int ) last_timer_id ++ ; 5140timer -> callback = * callback ; 5141 5142time_watcher_init ( & main_loop , & timer -> tw , timer ); 5143timer -> tw . events = multiqueue_new_child ( main_loop . events ); 5144// if main loop is blocked, don't queue up multiple events 5145timer -> tw . blockable = true; 5146time_watcher_start ( & timer -> tw , timer_due_cb , ( uint64_t ) timeout , ( uint64_t ) timeout ); 5147 5148pmap_put ( uint64_t )( & timers , ( uint64_t ) timer -> timer_id , timer ); 5149return ( uint64_t ) timer -> timer_id ; 5150} 5151 5152void timer_stop ( timer_T * timer ) 5153{ 5154if ( timer -> stopped ) { 5155// avoid double free 5156return; 5157} 5158timer -> stopped = true; 5159time_watcher_stop ( & timer -> tw ); 5160time_watcher_close ( & timer -> tw , timer_close_cb ); 5161} 5162 5163/// This will be run on the main loop after the last timer_due_cb, so at this 5164/// point it is safe to free the callback. 5165static void timer_close_cb ( TimeWatcher * tw , void * data ) 5166{ 5167timer_T * timer = ( timer_T * ) data ; 5168multiqueue_free ( timer -> tw . events ); 5169callback_free ( & timer -> callback ); 5170pmap_del ( uint64_t )( & timers , ( uint64_t ) timer -> timer_id , NULL ); 5171timer_decref ( timer ); 5172} 5173 5174static void timer_decref ( timer_T * timer ) 5175{ 5176if ( -- timer -> refcount == 0 ) { 5177xfree ( timer ); 5178} 5179} 5180 5181void timer_stop_all ( void ) 5182{ 5183timer_T * timer ; 5184map_foreach_value ( & timers , timer , { 5185timer_stop ( timer ); 5186}) 5187} 5188 5189void timer_teardown ( void ) 5190{ 5191timer_stop_all (); 5192} 5193 5194/// Saves a typval_T as a string. 5195/// 5196/// For lists or buffers, replaces NLs with NUL and separates items with NLs. 5197/// 5198/// @param[in] tv Value to store as a string. 5199/// @param[out] len Length of the resulting string or -1 on error. 5200/// @param[in] endnl If true, the output will end in a newline (if a list). 5201/// @param[in] crlf If true, list items will be joined with CRLF (if a list). 5202/// @returns an allocated string if `tv` represents a Vimscript string, list, or 5203/// number; NULL otherwise. 5204char * save_tv_as_string ( typval_T * tv , ptrdiff_t * const len , bool endnl , bool crlf ) 5205FUNC_ATTR_MALLOC FUNC_ATTR_NONNULL_ALL 5206{ 5207* len = 0 ; 5208if ( tv -> v_type == VAR_UNKNOWN ) { 5209return NULL ; 5210} 5211 5212// For other types, let tv_get_string_buf_chk() get the value or 5213// print an error. 5214if ( tv -> v_type != VAR_LIST && tv -> v_type != VAR_NUMBER ) { 5215const char * ret = tv_get_string_chk ( tv ); 5216if ( ret ) { 5217* len = ( ptrdiff_t ) strlen ( ret ); 5218return xmemdupz ( ret , ( size_t )( * len )); 5219} else { 5220* len = -1 ; 5221return NULL ; 5222} 5223} 5224 5225if ( tv -> v_type == VAR_NUMBER ) { // Treat number as a buffer-id. 5226buf_T * buf = buflist_findnr (( int ) tv -> vval . v_number ); 5227if ( buf ) { 5228for ( linenr_T lnum = 1 ; lnum <= buf -> b_ml . ml_line_count ; lnum ++ ) { 5229for ( char * p = ml_get_buf ( buf , lnum ); * p != NUL ; p ++ ) { 5230* len += 1 ; 5231} 5232* len += 1 ; 5233} 5234} else { 5235semsg ( _ ( e_nobufnr ), tv -> vval . v_number ); 5236* len = -1 ; 5237return NULL ; 5238} 5239 5240if ( * len == 0 ) { 5241return NULL ; 5242} 5243 5244char * ret = xmalloc (( size_t )( * len ) + 1 ); 5245char * end = ret ; 5246for ( linenr_T lnum = 1 ; lnum <= buf -> b_ml . ml_line_count ; lnum ++ ) { 5247for ( char * p = ml_get_buf ( buf , lnum ); * p != NUL ; p ++ ) { 5248* end ++ = ( * p == '\n' ) ? NUL : * p ; 5249} 5250* end ++ = '\n' ; 5251} 5252* end = NUL ; 5253* len = end - ret ; 5254return ret ; 5255} 5256 5257assert ( tv -> v_type == VAR_LIST ); 5258// Pre-calculate the resulting length. 5259list_T * list = tv -> vval . v_list ; 5260TV_LIST_ITER_CONST ( list , li , { 5261* len += ( ptrdiff_t ) strlen ( tv_get_string ( TV_LIST_ITEM_TV ( li ))) + ( crlf ? 2 : 1 ); 5262}); 5263 5264if ( * len == 0 ) { 5265return NULL ; 5266} 5267 5268char * ret = xmalloc (( size_t )( * len ) + ( endnl ? ( crlf ? 2 : 1 ) : 0 )); 5269char * end = ret ; 5270TV_LIST_ITER_CONST ( list , li , { 5271for (const char * s = tv_get_string ( TV_LIST_ITEM_TV ( li )); * s != NUL ; s ++ ) { 5272* end ++ = ( * s == '\n' ) ? NUL : * s ; 5273} 5274if ( endnl || TV_LIST_ITEM_NEXT ( list , li ) != NULL ) { 5275if ( crlf ) { 5276* end ++ = '\r' ; 5277} 5278* end ++ = '\n' ; 5279} 5280}); 5281* end = NUL ; 5282* len = end - ret ; 5283return ret ; 5284} 5285 5286/// Convert the specified byte index of line 'lnum' in buffer 'buf' to a 5287/// character index. Works only for loaded buffers. Returns -1 on failure. 5288/// The index of the first byte and the first character is zero. 5289int buf_byteidx_to_charidx ( buf_T * buf , linenr_T lnum , int byteidx ) 5290{ 5291if ( buf == NULL || buf -> b_ml . ml_mfp == NULL ) { 5292return -1 ; 5293} 5294 5295if ( lnum > buf -> b_ml . ml_line_count ) { 5296lnum = buf -> b_ml . ml_line_count ; 5297} 5298 5299char * str = ml_get_buf ( buf , lnum ); 5300 5301if ( * str == NUL ) { 5302return 0 ; 5303} 5304 5305// count the number of characters 5306char * t = str ; 5307int count ; 5308for ( count = 0 ; * t != NUL && t <= str + byteidx ; count ++ ) { 5309t += utfc_ptr2len ( t ); 5310} 5311 5312// In insert mode, when the cursor is at the end of a non-empty line, 5313// byteidx points to the NUL character immediately past the end of the 5314// string. In this case, add one to the character count. 5315if ( * t == NUL && byteidx != 0 && t == str + byteidx ) { 5316count ++ ; 5317} 5318 5319return count - 1 ; 5320} 5321 5322/// Convert the specified character index of line 'lnum' in buffer 'buf' to a 5323/// byte index. Works only for loaded buffers. 5324/// The index of the first byte and the first character is zero. 5325/// 5326/// @return -1 on failure. 5327int buf_charidx_to_byteidx ( buf_T * buf , linenr_T lnum , int charidx ) 5328{ 5329if ( buf == NULL || buf -> b_ml . ml_mfp == NULL ) { 5330return -1 ; 5331} 5332 5333if ( lnum > buf -> b_ml . ml_line_count ) { 5334lnum = buf -> b_ml . ml_line_count ; 5335} 5336 5337char * str = ml_get_buf ( buf , lnum ); 5338 5339// Convert the character offset to a byte offset 5340char * t = str ; 5341while ( * t != NUL && -- charidx > 0 ) { 5342t += utfc_ptr2len ( t ); 5343} 5344 5345return ( int )( t - str ); 5346} 5347 5348/// Translate a Vimscript object into a position 5349/// 5350/// Accepts VAR_LIST and VAR_STRING objects. Does not give an error for invalid 5351/// type. 5352/// 5353/// @param[in] tv Object to translate. 5354/// @param[in] dollar_lnum True when "$" is last line. 5355/// @param[out] ret_fnum Set to fnum for marks. 5356/// @param[in] charcol True to return character column. 5357/// @param[in] wp Window for which to get the position. 5358/// 5359/// @return Pointer to position or NULL in case of error (e.g. invalid type). 5360pos_T * var2fpos (const typval_T * const tv , const bool dollar_lnum , int * const ret_fnum , 5361const bool charcol , win_T * wp ) 5362FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 5363{ 5364static pos_T pos ; 5365 5366buf_T * bp = wp -> w_buffer ; 5367 5368// Argument can be [lnum, col, coladd]. 5369if ( tv -> v_type == VAR_LIST ) { 5370bool error = false; 5371 5372list_T * l = tv -> vval . v_list ; 5373if ( l == NULL ) { 5374return NULL ; 5375} 5376 5377// Get the line number. 5378pos . lnum = ( linenr_T ) tv_list_find_nr ( l , 0 , & error ); 5379if ( error || pos . lnum <= 0 || pos . lnum > bp -> b_ml . ml_line_count ) { 5380// Invalid line number. 5381return NULL ; 5382} 5383 5384// Get the column number. 5385pos . col = ( colnr_T ) tv_list_find_nr ( l , 1 , & error ); 5386if ( error ) { 5387return NULL ; 5388} 5389int len ; 5390if ( charcol ) { 5391len = mb_charlen ( ml_get_buf ( bp , pos . lnum )); 5392} else { 5393len = ml_get_buf_len ( bp , pos . lnum ); 5394} 5395 5396// We accept "$" for the column number: last column. 5397listitem_T * li = tv_list_find ( l , 1 ); 5398if ( li != NULL && TV_LIST_ITEM_TV ( li ) -> v_type == VAR_STRING 5399&& TV_LIST_ITEM_TV ( li ) -> vval . v_string != NULL 5400&& strcmp ( TV_LIST_ITEM_TV ( li ) -> vval . v_string , "$" ) == 0 ) { 5401pos . col = len + 1 ; 5402} 5403 5404// Accept a position up to the NUL after the line. 5405if ( pos . col == 0 || ( int ) pos . col > len + 1 ) { 5406// Invalid column number. 5407return NULL ; 5408} 5409pos . col -- ; 5410 5411// Get the virtual offset. Defaults to zero. 5412pos . coladd = ( colnr_T ) tv_list_find_nr ( l , 2 , & error ); 5413if ( error ) { 5414pos . coladd = 0 ; 5415} 5416 5417return & pos ; 5418} 5419 5420const char * const name = tv_get_string_chk ( tv ); 5421if ( name == NULL ) { 5422return NULL ; 5423} 5424 5425pos . lnum = 0 ; 5426if ( name [ 0 ] == '.' ) { 5427// cursor 5428pos = wp -> w_cursor ; 5429} else if ( name [ 0 ] == 'v' && name [ 1 ] == NUL ) { 5430// Visual start 5431if ( Visual . active && wp == curwin ) { 5432pos = Visual . start ; 5433} else { 5434pos = wp -> w_cursor ; 5435} 5436} else if ( name [ 0 ] == '\'' ) { 5437// mark 5438int mname = ( uint8_t ) name [ 1 ]; 5439const fmark_T * const fm = mark_get ( bp , wp , NULL , kMarkAll , mname ); 5440if ( fm == NULL || fm -> mark . lnum <= 0 ) { 5441return NULL ; 5442} 5443pos = fm -> mark ; 5444// Vimscript behavior, only provide fnum if mark is global. 5445* ret_fnum = ASCII_ISUPPER ( mname ) || ascii_isdigit ( mname ) ? fm -> fnum : * ret_fnum ; 5446} 5447if ( pos . lnum != 0 ) { 5448if ( charcol ) { 5449pos . col = buf_byteidx_to_charidx ( bp , pos . lnum , pos . col ); 5450} 5451return & pos ; 5452} 5453 5454pos . coladd = 0 ; 5455 5456if ( name [ 0 ] == 'w' && dollar_lnum ) { 5457// the "w_valid" flags are not reset when moving the cursor, but they 5458// do matter for update_topline() and validate_botline_win(). 5459check_cursor_moved ( wp ); 5460 5461pos . col = 0 ; 5462if ( name [ 1 ] == '0' ) { // "w0": first visible line 5463update_topline ( wp ); 5464// In silent Ex mode topline is zero, but that's not a valid line 5465// number; use one instead. 5466pos . lnum = wp -> w_topline > 0 ? wp -> w_topline : 1 ; 5467return & pos ; 5468} else if ( name [ 1 ] == '$' ) { // "w$": last visible line 5469validate_botline_win ( wp ); 5470// In silent Ex mode botline is zero, return zero then. 5471pos . lnum = wp -> w_botline > 0 ? wp -> w_botline - 1 : 0 ; 5472return & pos ; 5473} 5474} else if ( name [ 0 ] == '$' ) { // last column or line 5475if ( dollar_lnum ) { 5476pos . lnum = bp -> b_ml . ml_line_count ; 5477pos . col = 0 ; 5478} else { 5479pos . lnum = wp -> w_cursor . lnum ; 5480if ( charcol ) { 5481pos . col = ( colnr_T ) mb_charlen ( ml_get_buf ( bp , wp -> w_cursor . lnum )); 5482} else { 5483pos . col = ml_get_buf_len ( bp , wp -> w_cursor . lnum ); 5484} 5485} 5486return & pos ; 5487} 5488return NULL ; 5489} 5490 5491/// Convert list in "arg" into position "posp" and optional file number "fnump". 5492/// When "fnump" is NULL there is no file number, only 3 items: [lnum, col, off] 5493/// Note that the column is passed on as-is, the caller may want to decrement 5494/// it to use 1 for the first column. 5495/// 5496/// @param charcol if true, use the column as the character index instead of the 5497/// byte index. 5498/// 5499/// @return FAIL when conversion is not possible, doesn't check the position for 5500/// validity. 5501int list2fpos ( typval_T * arg , pos_T * posp , int * fnump , colnr_T * curswantp , bool charcol ) 5502{ 5503list_T * l ; 5504 5505// List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only 5506// there when "fnump" isn't NULL; "coladd" and "curswant" are optional. 5507if ( arg -> v_type != VAR_LIST 5508|| ( l = arg -> vval . v_list ) == NULL 5509|| tv_list_len ( l ) < ( fnump == NULL ? 2 : 3 ) 5510|| tv_list_len ( l ) > ( fnump == NULL ? 4 : 5 )) { 5511return FAIL ; 5512} 5513 5514int i = 0 ; 5515int n ; 5516if ( fnump != NULL ) { 5517n = ( int ) tv_list_find_nr ( l , i ++ , NULL ); // fnum 5518if ( n < 0 ) { 5519return FAIL ; 5520} 5521if ( n == 0 ) { 5522n = curbuf -> b_fnum ; // Current buffer. 5523} 5524* fnump = n ; 5525} 5526 5527n = ( int ) tv_list_find_nr ( l , i ++ , NULL ); // lnum 5528if ( n < 0 ) { 5529return FAIL ; 5530} 5531posp -> lnum = n ; 5532 5533n = ( int ) tv_list_find_nr ( l , i ++ , NULL ); // col 5534if ( n < 0 ) { 5535return FAIL ; 5536} 5537// If character position is specified, then convert to byte position 5538// If the line number is zero use the cursor line. 5539if ( charcol ) { 5540// Get the text for the specified line in a loaded buffer 5541buf_T * buf = buflist_findnr ( fnump == NULL ? curbuf -> b_fnum : * fnump ); 5542if ( buf == NULL || buf -> b_ml . ml_mfp == NULL ) { 5543return FAIL ; 5544} 5545n = buf_charidx_to_byteidx ( buf , 5546posp -> lnum == 0 ? curwin -> w_cursor . lnum : posp -> lnum , 5547n ) + 1 ; 5548} 5549posp -> col = n ; 5550 5551n = ( int ) tv_list_find_nr ( l , i , NULL ); // off 5552if ( n < 0 ) { 5553posp -> coladd = 0 ; 5554} else { 5555posp -> coladd = n ; 5556} 5557 5558if ( curswantp != NULL ) { 5559* curswantp = ( colnr_T ) tv_list_find_nr ( l , i + 1 , NULL ); // curswant 5560} 5561 5562return OK ; 5563} 5564 5565/// Get the length of an environment variable name. 5566/// Advance "arg" to the first character after the name. 5567/// 5568/// @return 0 for error. 5569int get_env_len (const char ** arg ) 5570{ 5571const char * p ; 5572for ( p = * arg ; vim_isIDc (( uint8_t )( * p )); p ++ ) {} 5573if ( p == * arg ) { // No name found. 5574return 0 ; 5575} 5576 5577int len = ( int )( p - * arg ); 5578* arg = p ; 5579return len ; 5580} 5581 5582/// Get the length of the name of a function or internal variable. 5583/// 5584/// @param arg is advanced to the first non-white character after the name. 5585/// 5586/// @return 0 if something is wrong. 5587int get_id_len (const char ** const arg ) 5588{ 5589int len ; 5590 5591// Find the end of the name. 5592const char * p ; 5593for ( p = * arg ; eval_isnamec ( * p ); p ++ ) { 5594if ( * p == ':' ) { 5595// "s:" is start of "s:var", but "n:" is not and can be used in 5596// slice "[n:]". Also "xx:" is not a namespace. 5597len = ( int )( p - * arg ); 5598if ( len > 1 5599|| ( len == 1 && vim_strchr ( namespace_char , ( uint8_t )( ** arg )) == NULL )) { 5600break; 5601} 5602} 5603} 5604if ( p == * arg ) { // no name found 5605return 0 ; 5606} 5607 5608len = ( int )( p - * arg ); 5609* arg = skipwhite ( p ); 5610 5611return len ; 5612} 5613 5614/// Get the length of the name of a variable or function. 5615/// Only the name is recognized, does not handle ".key" or "[idx]". 5616/// 5617/// @param arg is advanced to the first non-white character after the name. 5618/// If the name contains 'magic' {}'s, expand them and return the 5619/// expanded name in an allocated string via 'alias' - caller must free. 5620/// 5621/// @return -1 if curly braces expansion failed or 5622/// 0 if something else is wrong. 5623int get_name_len (const char ** const arg , char ** alias , bool evaluate , bool verbose ) 5624{ 5625* alias = NULL ; // default to no alias 5626 5627if (( * arg )[ 0 ] == ( char ) K_SPECIAL && ( * arg )[ 1 ] == ( char ) KS_EXTRA 5628&& ( * arg )[ 2 ] == ( char ) KE_SNR ) { 5629// Hard coded <SNR>, already translated. 5630* arg += 3 ; 5631return get_id_len ( arg ) + 3 ; 5632} 5633int len = eval_fname_script ( * arg ); 5634if ( len > 0 ) { 5635// literal "<SID>", "s:" or "<SNR>" 5636* arg += len ; 5637} 5638 5639// Find the end of the name; check for {} construction. 5640char * expr_start ; 5641char * expr_end ; 5642const char * p = find_name_end (( * arg ), (const char ** ) & expr_start , (const char ** ) & expr_end , 5643len > 0 ? 0 : FNE_CHECK_START ); 5644if ( expr_start != NULL ) { 5645if (! evaluate ) { 5646len += ( int )( p - * arg ); 5647* arg = skipwhite ( p ); 5648return len ; 5649} 5650 5651// Include any <SID> etc in the expanded string: 5652// Thus the -len here. 5653char * temp_string = make_expanded_name ( * arg - len , expr_start , expr_end , ( char * ) p ); 5654if ( temp_string == NULL ) { 5655return -1 ; 5656} 5657* alias = temp_string ; 5658* arg = skipwhite ( p ); 5659return ( int ) strlen ( temp_string ); 5660} 5661 5662len += get_id_len ( arg ); 5663// Only give an error when there is something, otherwise it will be 5664// reported at a higher level. 5665if ( len == 0 && verbose && ** arg != NUL ) { 5666semsg ( _ ( e_invexpr2 ), * arg ); 5667} 5668 5669return len ; 5670} 5671 5672/// Find the end of a variable or function name, taking care of magic braces. 5673/// 5674/// @param expr_start if not NULL, then `expr_start` and `expr_end` are set to the 5675/// start and end of the first magic braces item. 5676/// 5677/// @param flags can have FNE_INCL_BR and FNE_CHECK_START. 5678/// 5679/// @return a pointer to just after the name. Equal to "arg" if there is no 5680/// valid name. 5681const char * find_name_end (const char * arg , const char ** expr_start , const char ** expr_end , 5682int flags ) 5683{ 5684if ( expr_start != NULL ) { 5685* expr_start = NULL ; 5686* expr_end = NULL ; 5687} 5688 5689// Quick check for valid starting character. 5690if (( flags & FNE_CHECK_START ) && ! eval_isnamec1 ( * arg ) && * arg != '{' ) { 5691return arg ; 5692} 5693 5694int mb_nest = 0 ; 5695int br_nest = 0 ; 5696int len ; 5697 5698const char * p ; 5699for ( p = arg ; * p != NUL 5700&& ( eval_isnamec ( * p ) 5701|| * p == '{' 5702|| (( flags & FNE_INCL_BR ) && ( * p == '[' 5703|| ( * p == '.' && eval_isdictc ( p [ 1 ])))) 5704|| mb_nest != 0 5705|| br_nest != 0 ); MB_PTR_ADV ( p )) { 5706if ( * p == '\'' ) { 5707// skip over 'string' to avoid counting [ and ] inside it. 5708for ( p = p + 1 ; * p != NUL && * p != '\'' ; MB_PTR_ADV ( p )) {} 5709if ( * p == NUL ) { 5710break; 5711} 5712} else if ( * p == '"' ) { 5713// skip over "str\"ing" to avoid counting [ and ] inside it. 5714for ( p = p + 1 ; * p != NUL && * p != '"' ; MB_PTR_ADV ( p )) { 5715if ( * p == '\\' && p [ 1 ] != NUL ) { 5716p ++ ; 5717} 5718} 5719if ( * p == NUL ) { 5720break; 5721} 5722} else if ( br_nest == 0 && mb_nest == 0 && * p == ':' ) { 5723// "s:" is start of "s:var", but "n:" is not and can be used in 5724// slice "[n:]". Also "xx:" is not a namespace. But {ns}: is. 5725len = ( int )( p - arg ); 5726if (( len > 1 && p [ -1 ] != '}' ) 5727|| ( len == 1 && vim_strchr ( namespace_char , ( uint8_t )( * arg )) == NULL )) { 5728break; 5729} 5730} 5731 5732if ( mb_nest == 0 ) { 5733if ( * p == '[' ) { 5734br_nest ++ ; 5735} else if ( * p == ']' ) { 5736br_nest -- ; 5737} 5738} 5739 5740if ( br_nest == 0 ) { 5741if ( * p == '{' ) { 5742mb_nest ++ ; 5743if ( expr_start != NULL && * expr_start == NULL ) { 5744* expr_start = p ; 5745} 5746} else if ( * p == '}' ) { 5747mb_nest -- ; 5748if ( expr_start != NULL && mb_nest == 0 && * expr_end == NULL ) { 5749* expr_end = p ; 5750} 5751} 5752} 5753} 5754 5755return p ; 5756} 5757 5758/// Expands out the 'magic' {}'s in a variable/function name. 5759/// Note that this can call itself recursively, to deal with 5760/// constructs like foo{bar}{baz}{bam} 5761/// The four pointer arguments point to "foo{expre}ss{ion}bar" 5762/// "in_start" ^ 5763/// "expr_start" ^ 5764/// "expr_end" ^ 5765/// "in_end" ^ 5766/// 5767/// @return a new allocated string, which the caller must free or 5768/// NULL for failure. 5769static char * make_expanded_name (const char * in_start , char * expr_start , char * expr_end , 5770char * in_end ) 5771{ 5772if ( expr_end == NULL || in_end == NULL ) { 5773return NULL ; 5774} 5775 5776char * retval = NULL ; 5777 5778* expr_start = NUL ; 5779* expr_end = NUL ; 5780char c1 = * in_end ; 5781* in_end = NUL ; 5782 5783char * temp_result = eval_to_string ( expr_start + 1 , false, false); 5784if ( temp_result != NULL ) { 5785size_t retvalsize = ( size_t )( expr_start - in_start ) 5786+ strlen ( temp_result ) 5787+ ( size_t )( in_end - expr_end ) + 1 ; 5788retval = xmalloc ( retvalsize ); 5789vim_snprintf ( retval , retvalsize , "%s%s%s" , in_start , temp_result , expr_end + 1 ); 5790} 5791xfree ( temp_result ); 5792 5793* in_end = c1 ; // put char back for error messages 5794* expr_start = '{' ; 5795* expr_end = '}' ; 5796 5797if ( retval != NULL ) { 5798temp_result = ( char * ) find_name_end ( retval , 5799(const char ** ) & expr_start , 5800(const char ** ) & expr_end , 0 ); 5801if ( expr_start != NULL ) { 5802// Further expansion! 5803temp_result = make_expanded_name ( retval , expr_start , 5804expr_end , temp_result ); 5805xfree ( retval ); 5806retval = temp_result ; 5807} 5808} 5809 5810return retval ; 5811} 5812 5813/// @return true if character "c" can be used in a variable or function name. 5814/// Does not include '{' or '}' for magic braces. 5815bool eval_isnamec ( int c ) 5816{ 5817return ASCII_ISALNUM ( c ) || c == '_' || c == ':' || c == AUTOLOAD_CHAR ; 5818} 5819 5820/// @return true if character "c" can be used as the first character in a 5821/// variable or function name (excluding '{' and '}'). 5822bool eval_isnamec1 ( int c ) 5823{ 5824return ASCII_ISALPHA ( c ) || c == '_' ; 5825} 5826 5827/// @return true if character "c" can be used as the first character of a 5828/// dictionary key. 5829bool eval_isdictc ( int c ) 5830{ 5831return ASCII_ISALNUM ( c ) || c == '_' ; 5832} 5833 5834/// Set the v:argv list. 5835void set_argv_var ( char ** argv , int argc ) 5836{ 5837list_T * l = tv_list_alloc ( argc ); 5838 5839tv_list_set_lock ( l , VAR_FIXED ); 5840for ( int i = 0 ; i < argc ; i ++ ) { 5841tv_list_append_string ( l , (const char * const) argv [ i ], -1 ); 5842TV_LIST_ITEM_TV ( tv_list_last ( l )) -> v_lock = VAR_FIXED ; 5843} 5844set_vim_var_list ( VV_ARGV , l ); 5845} 5846 5847/// check if special v:lua value for calling lua functions 5848bool is_luafunc ( partial_T * partial ) 5849FUNC_ATTR_PURE 5850{ 5851return partial == get_vim_var_partial ( VV_LUA ); 5852} 5853 5854/// check if special v:lua value for calling lua functions 5855static bool tv_is_luafunc ( typval_T * tv ) 5856{ 5857return tv -> v_type == VAR_PARTIAL && is_luafunc ( tv -> vval . v_partial ); 5858} 5859 5860/// Skips one character past the end of the name of a v:lua function. 5861/// @param p Pointer to the char AFTER the "v:lua." prefix. 5862/// @return Pointer to the char one past the end of the function's name. 5863const char * skip_luafunc_name (const char * p ) 5864FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 5865{ 5866while ( ASCII_ISALNUM ( * p ) || * p == '_' || * p == '-' || * p == '.' || * p == '\'' ) { 5867p ++ ; 5868} 5869return p ; 5870} 5871 5872/// check the function name after "v:lua." 5873int check_luafunc_name (const char * const str , const bool paren ) 5874FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 5875{ 5876const char * const p = skip_luafunc_name ( str ); 5877if ( * p != ( paren ? '(' : NUL )) { 5878return 0 ; 5879} 5880return ( int )( p - str ); 5881} 5882 5883/// Return the character "str[index]" where "index" is the character index, 5884/// including composing characters. 5885/// If "index" is out of range NULL is returned. 5886char * char_from_string (const char * str , varnumber_T index ) 5887{ 5888varnumber_T nchar = index ; 5889 5890if ( str == NULL ) { 5891return NULL ; 5892} 5893size_t slen = strlen ( str ); 5894 5895// do the same as for a list: a negative index counts from the end 5896if ( index < 0 ) { 5897int clen = 0 ; 5898 5899for ( size_t nbyte = 0 ; nbyte < slen ; clen ++ ) { 5900nbyte += ( size_t ) utfc_ptr2len ( str + nbyte ); 5901} 5902nchar = clen + index ; 5903if ( nchar < 0 ) { 5904// unlike list: index out of range results in empty string 5905return NULL ; 5906} 5907} 5908 5909size_t nbyte = 0 ; 5910for (; nchar > 0 && nbyte < slen ; nchar -- ) { 5911nbyte += ( size_t ) utfc_ptr2len ( str + nbyte ); 5912} 5913if ( nbyte >= slen ) { 5914return NULL ; 5915} 5916return xmemdupz ( str + nbyte , ( size_t ) utfc_ptr2len ( str + nbyte )); 5917} 5918 5919/// Get the byte index for character index "idx" in string "str" with length 5920/// "str_len". Composing characters are included. 5921/// If going over the end return "str_len". 5922/// If "idx" is negative count from the end, -1 is the last character. 5923/// When going over the start return -1. 5924static ssize_t char_idx2byte (const char * str , size_t str_len , varnumber_T idx ) 5925{ 5926varnumber_T nchar = idx ; 5927size_t nbyte = 0 ; 5928 5929if ( nchar >= 0 ) { 5930while ( nchar > 0 && nbyte < str_len ) { 5931nbyte += ( size_t ) utfc_ptr2len ( str + nbyte ); 5932nchar -- ; 5933} 5934} else { 5935nbyte = str_len ; 5936while ( nchar < 0 && nbyte > 0 ) { 5937nbyte -- ; 5938nbyte -= ( size_t ) utf_head_off ( str , str + nbyte ); 5939nchar ++ ; 5940} 5941if ( nchar < 0 ) { 5942return -1 ; 5943} 5944} 5945return ( ssize_t ) nbyte ; 5946} 5947 5948/// Return the slice "str[first : last]" using character indexes. Composing 5949/// characters are included. 5950/// 5951/// @param exclusive true for slice(). 5952/// 5953/// Return NULL when the result is empty. 5954char * string_slice (const char * str , varnumber_T first , varnumber_T last , bool exclusive ) 5955{ 5956if ( str == NULL ) { 5957return NULL ; 5958} 5959size_t slen = strlen ( str ); 5960ssize_t start_byte = char_idx2byte ( str , slen , first ); 5961if ( start_byte < 0 ) { 5962start_byte = 0 ; // first index very negative: use zero 5963} 5964ssize_t end_byte ; 5965if (( last == -1 && ! exclusive ) || last == VARNUMBER_MAX ) { 5966end_byte = ( ssize_t ) slen ; 5967} else { 5968end_byte = char_idx2byte ( str , slen , last ); 5969if (! exclusive && end_byte >= 0 && end_byte < ( ssize_t ) slen ) { 5970// end index is inclusive 5971end_byte += utfc_ptr2len ( str + end_byte ); 5972} 5973} 5974 5975if ( start_byte >= ( ssize_t ) slen || end_byte <= start_byte ) { 5976return NULL ; 5977} 5978return xmemdupz ( str + start_byte , ( size_t )( end_byte - start_byte )); 5979} 5980 5981/// Handle: 5982/// - expr[expr], expr[expr:expr] subscript 5983/// - ".name" lookup 5984/// - function call with Funcref variable: func(expr) 5985/// - method call: var->method() 5986/// 5987/// Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len() 5988/// 5989/// @param verbose give error messages 5990/// @param start_leader start of '!' and '-' prefixes 5991/// @param end_leaderp end of '!' and '-' prefixes 5992int handle_subscript (const char ** const arg , typval_T * rettv , evalarg_T * const evalarg , 5993bool verbose ) 5994{ 5995const bool evaluate = evalarg != NULL && ( evalarg -> eval_flags & EVAL_EVALUATE ); 5996int ret = OK ; 5997dict_T * selfdict = NULL ; 5998const char * lua_funcname = NULL ; 5999 6000if ( tv_is_luafunc ( rettv )) { 6001if (! evaluate ) { 6002tv_clear ( rettv ); 6003} 6004 6005if ( ** arg != '.' ) { 6006tv_clear ( rettv ); 6007ret = FAIL ; 6008} else { 6009( * arg ) ++ ; 6010 6011lua_funcname = * arg ; 6012const int len = check_luafunc_name ( * arg , true); 6013if ( len == 0 ) { 6014tv_clear ( rettv ); 6015ret = FAIL ; 6016} 6017( * arg ) += len ; 6018} 6019} 6020 6021// "." is ".name" lookup when we found a dict. 6022while ( ret == OK 6023&& ((( ** arg == '[' || ( ** arg == '.' && rettv -> v_type == VAR_DICT ) 6024|| ( ** arg == '(' && (! evaluate || tv_is_func ( * rettv )))) 6025&& ! ascii_iswhite ( * ( * arg - 1 ))) 6026|| ( ** arg == '-' && ( * arg )[ 1 ] == '>' ))) { 6027if ( ** arg == '(' ) { 6028ret = call_func_rettv (( char ** ) arg , evalarg , rettv , evaluate , selfdict , NULL , lua_funcname ); 6029 6030// Stop the expression evaluation when immediately aborting on 6031// error, or when an interrupt occurred or an exception was thrown 6032// but not caught. 6033if ( aborting ()) { 6034if ( ret == OK ) { 6035tv_clear ( rettv ); 6036} 6037ret = FAIL ; 6038} 6039tv_dict_unref ( selfdict ); 6040selfdict = NULL ; 6041} else if ( ** arg == '-' ) { 6042if (( * arg )[ 2 ] == '{' ) { 6043// expr->{lambda}() 6044ret = eval_lambda (( char ** ) arg , rettv , evalarg , verbose ); 6045} else { 6046// expr->name() 6047ret = eval_method (( char ** ) arg , rettv , evalarg , verbose ); 6048} 6049} else { // **arg == '[' || **arg == '.' 6050tv_dict_unref ( selfdict ); 6051if ( rettv -> v_type == VAR_DICT ) { 6052selfdict = rettv -> vval . v_dict ; 6053if ( selfdict != NULL ) { 6054selfdict -> dv_refcount ++ ; 6055} 6056} else { 6057selfdict = NULL ; 6058} 6059if ( eval_index (( char ** ) arg , rettv , evalarg , verbose ) == FAIL ) { 6060tv_clear ( rettv ); 6061ret = FAIL ; 6062} 6063} 6064} 6065 6066// Turn "dict.Func" into a partial for "Func" bound to "dict". 6067if ( selfdict != NULL && tv_is_func ( * rettv )) { 6068set_selfdict ( rettv , selfdict ); 6069} 6070 6071tv_dict_unref ( selfdict ); 6072return ret ; 6073} 6074 6075void set_selfdict ( typval_T * const rettv , dict_T * const selfdict ) 6076{ 6077// Don't do this when "dict.Func" is already a partial that was bound 6078// explicitly (pt_auto is false). 6079if ( rettv -> v_type == VAR_PARTIAL && ! rettv -> vval . v_partial -> pt_auto 6080&& rettv -> vval . v_partial -> pt_dict != NULL ) { 6081return; 6082} 6083make_partial ( selfdict , rettv ); 6084} 6085 6086/// Make a copy of an item 6087/// 6088/// Lists and Dictionaries are also copied. 6089/// 6090/// @param[in] conv If not NULL, convert all copied strings. 6091/// @param[in] from Value to copy. 6092/// @param[out] to Location where to copy to. 6093/// @param[in] deep If true, use copy the container and all of the contained 6094/// containers (nested). 6095/// @param[in] copyID If non-zero then when container is referenced more then 6096/// once then copy of it that was already done is used. E.g. 6097/// when copying list `list = [list2, list2]` (`list[0] is 6098/// list[1]`) var_item_copy with zero copyID will emit 6099/// a copy with (`copy[0] isnot copy[1]`), with non-zero it 6100/// will emit a copy with (`copy[0] is copy[1]`) like in the 6101/// original list. Not used when deep is false. 6102int var_item_copy (const vimconv_T * const conv , typval_T * const from , typval_T * const to , 6103const bool deep , const int copyID ) 6104FUNC_ATTR_NONNULL_ARG ( 2 , 3 ) 6105{ 6106static int recurse = 0 ; 6107int ret = OK ; 6108 6109if ( recurse >= DICT_MAXNEST ) { 6110emsg ( _ ( e_variable_nested_too_deep_for_making_copy )); 6111return FAIL ; 6112} 6113recurse ++ ; 6114 6115switch ( from -> v_type ) { 6116case VAR_NUMBER : 6117case VAR_FLOAT : 6118case VAR_FUNC : 6119case VAR_PARTIAL : 6120case VAR_BOOL : 6121case VAR_SPECIAL : 6122tv_copy ( from , to ); 6123break; 6124case VAR_STRING : 6125if ( conv == NULL || conv -> vc_type == CONV_NONE 6126|| from -> vval . v_string == NULL ) { 6127tv_copy ( from , to ); 6128} else { 6129to -> v_type = VAR_STRING ; 6130to -> v_lock = VAR_UNLOCKED ; 6131if (( to -> vval . v_string = string_convert (( vimconv_T * ) conv , 6132from -> vval . v_string , 6133NULL )) 6134== NULL ) { 6135to -> vval . v_string = xstrdup ( from -> vval . v_string ); 6136} 6137} 6138break; 6139case VAR_LIST : 6140to -> v_type = VAR_LIST ; 6141to -> v_lock = VAR_UNLOCKED ; 6142if ( from -> vval . v_list == NULL ) { 6143to -> vval . v_list = NULL ; 6144} else if ( copyID != 0 && tv_list_copyid ( from -> vval . v_list ) == copyID ) { 6145// Use the copy made earlier. 6146to -> vval . v_list = tv_list_latest_copy ( from -> vval . v_list ); 6147tv_list_ref ( to -> vval . v_list ); 6148} else { 6149to -> vval . v_list = tv_list_copy ( conv , from -> vval . v_list , deep , copyID ); 6150} 6151if ( to -> vval . v_list == NULL && from -> vval . v_list != NULL ) { 6152ret = FAIL ; 6153} 6154break; 6155case VAR_BLOB : 6156tv_blob_copy ( from -> vval . v_blob , to ); 6157break; 6158case VAR_DICT : 6159to -> v_type = VAR_DICT ; 6160to -> v_lock = VAR_UNLOCKED ; 6161if ( from -> vval . v_dict == NULL ) { 6162to -> vval . v_dict = NULL ; 6163} else if ( copyID != 0 && from -> vval . v_dict -> dv_copyID == copyID ) { 6164// use the copy made earlier 6165to -> vval . v_dict = from -> vval . v_dict -> dv_copydict ; 6166to -> vval . v_dict -> dv_refcount ++ ; 6167} else { 6168to -> vval . v_dict = tv_dict_copy ( conv , from -> vval . v_dict , deep , copyID ); 6169} 6170if ( to -> vval . v_dict == NULL && from -> vval . v_dict != NULL ) { 6171ret = FAIL ; 6172} 6173break; 6174case VAR_UNKNOWN : 6175internal_error ( "var_item_copy(UNKNOWN)" ); 6176ret = FAIL ; 6177} 6178recurse -- ; 6179return ret ; 6180} 6181 6182/// ":echo expr1 ..." print each argument separated with a space, add a 6183/// newline at the end. 6184/// ":echon expr1 ..." print each argument plain. 6185void ex_echo ( exarg_T * eap ) 6186{ 6187char * arg = eap -> arg ; 6188typval_T rettv ; 6189bool atstart = true; 6190bool need_clear = true; 6191const int did_emsg_before = did_emsg ; 6192const int called_emsg_before = called_emsg ; 6193evalarg_T evalarg ; 6194 6195fill_evalarg_from_eap ( & evalarg , eap , eap -> skip ); 6196 6197if ( eap -> skip ) { 6198emsg_skip ++ ; 6199} 6200while ( * arg != NUL && * arg != '|' && * arg != '\n' && ! got_int ) { 6201// If eval1() causes an error message the text from the command may 6202// still need to be cleared. E.g., "echo 22,44". 6203need_clr_eos = true; 6204 6205{ 6206char * p = arg ; 6207if ( eval1 ( & arg , & rettv , & evalarg ) == FAIL ) { 6208// Report the invalid expression unless the expression evaluation 6209// has been cancelled due to an aborting error, an interrupt, or an 6210// exception. 6211if (! aborting () && did_emsg == did_emsg_before 6212&& called_emsg == called_emsg_before ) { 6213semsg ( _ ( e_invexpr2 ), p ); 6214} 6215need_clr_eos = false; 6216break; 6217} 6218need_clr_eos = false; 6219} 6220 6221if (! eap -> skip ) { 6222if ( atstart ) { 6223atstart = false; 6224msg_ext_set_append ( eap -> cmdidx == CMD_echon ); 6225msg_ext_no_fast (); 6226msg_ext_set_kind ( "echo" ); 6227// Call msg_start() after eval1(), evaluating the expression 6228// may cause a message to appear. 6229if ( eap -> cmdidx == CMD_echo ) { 6230if (! msg_didout ) { 6231// Mark the saved text as finishing the line, so that what 6232// follows is displayed on a new line when scrolling back 6233// at the more prompt. 6234msg_sb_eol (); 6235} 6236msg_start (); 6237} 6238} else if ( eap -> cmdidx == CMD_echo ) { 6239msg_puts_hl ( " " , echo_hl_id , false); 6240} 6241char * tofree = encode_tv2echo ( & rettv , NULL ); 6242msg_multiline ( cstr_as_string ( tofree ), echo_hl_id , true, false, & need_clear ); 6243xfree ( tofree ); 6244} 6245tv_clear ( & rettv ); 6246arg = skipwhite ( arg ); 6247} 6248eap -> nextcmd = check_nextcmd ( arg ); 6249clear_evalarg ( & evalarg , eap ); 6250msg_ext_set_append (false); 6251 6252if ( eap -> skip ) { 6253emsg_skip -- ; 6254} else { 6255// remove text that may still be there from the command 6256if ( ui_has ( kUIMessages ) && ( * eap -> arg == NUL || * eap -> arg == '|' || * eap -> arg == '\n' )) { 6257msg_puts_len ( "" , 0 , 0 , false); // emit "empty" kind msg_show 6258} else if ( need_clear ) { 6259msg_clr_eos (); 6260} 6261if ( eap -> cmdidx == CMD_echo ) { 6262msg_end (); 6263} 6264} 6265} 6266 6267/// ":echohl {name}". 6268void ex_echohl ( exarg_T * eap ) 6269{ 6270echo_hl_id = syn_name2id ( eap -> arg ); 6271} 6272 6273/// Returns the :echo highlight id 6274int get_echo_hl_id ( void ) 6275{ 6276return echo_hl_id ; 6277} 6278 6279/// ":execute expr1 ..." execute the result of an expression. 6280/// ":echomsg expr1 ..." Print a message 6281/// ":echoerr expr1 ..." Print an error 6282/// Each gets spaces around each argument and a newline at the end for 6283/// echo commands 6284void ex_execute ( exarg_T * eap ) 6285{ 6286char * arg = eap -> arg ; 6287typval_T rettv ; 6288int ret = OK ; 6289garray_T ga ; 6290 6291ga_init ( & ga , 1 , 80 ); 6292 6293if ( eap -> skip ) { 6294emsg_skip ++ ; 6295} 6296while ( * arg != NUL && * arg != '|' && * arg != '\n' ) { 6297ret = eval1_emsg ( & arg , & rettv , eap ); 6298if ( ret == FAIL ) { 6299break; 6300} 6301 6302if (! eap -> skip ) { 6303const char * const argstr = eap -> cmdidx == CMD_execute 6304? tv_get_string ( & rettv ) 6305: rettv . v_type == VAR_STRING 6306? encode_tv2echo ( & rettv , NULL ) 6307: encode_tv2string ( & rettv , NULL ); 6308const size_t len = strlen ( argstr ); 6309ga_grow ( & ga , ( int ) len + 2 ); 6310if (! GA_EMPTY ( & ga )) { 6311(( char * )( ga . ga_data ))[ ga . ga_len ++ ] = ' ' ; 6312} 6313memcpy (( char * )( ga . ga_data ) + ga . ga_len , argstr , len + 1 ); 6314if ( eap -> cmdidx != CMD_execute ) { 6315xfree (( void * ) argstr ); 6316} 6317ga . ga_len += ( int ) len ; 6318} 6319 6320tv_clear ( & rettv ); 6321arg = skipwhite ( arg ); 6322} 6323 6324if ( ret != FAIL && ga . ga_data != NULL ) { 6325if ( eap -> cmdidx == CMD_echomsg ) { 6326msg_ext_no_fast (); 6327msg_ext_set_kind ( "echomsg" ); 6328msg ( ga . ga_data , echo_hl_id ); 6329} else if ( eap -> cmdidx == CMD_echoerr ) { 6330// We don't want to abort following commands, restore did_emsg. 6331int save_did_emsg = did_emsg ; 6332msg_ext_no_fast (); 6333emsg_multiline ( ga . ga_data , "echoerr" , HLF_E , true); 6334if (! force_abort ) { 6335did_emsg = save_did_emsg ; 6336} 6337} else if ( eap -> cmdidx == CMD_execute ) { 6338do_cmdline ( ga . ga_data , eap -> ea_getline , eap -> cookie , DOCMD_NOWAIT | DOCMD_VERBOSE ); 6339} 6340} 6341 6342ga_clear ( & ga ); 6343 6344if ( eap -> skip ) { 6345emsg_skip -- ; 6346} 6347 6348eap -> nextcmd = check_nextcmd ( arg ); 6349} 6350 6351/// Skip over the name of an option variable: "&option", "&g:option" or "&l:option". 6352/// 6353/// @param[in,out] arg Points to the "&" or '+' when called, to "option" when returning. 6354/// @param[out] opt_idxp Set to option index in options[] table. 6355/// @param[out] opt_flags Option flags. 6356/// 6357/// @return NULL when no option name found. Otherwise pointer to the char after the option name. 6358const char * find_option_var_end (const char ** const arg , OptIndex * const opt_idxp , 6359int * const opt_flags ) 6360{ 6361const char * p = * arg ; 6362 6363p ++ ; 6364if ( * p == 'g' && p [ 1 ] == ':' ) { 6365* opt_flags = OPT_GLOBAL ; 6366p += 2 ; 6367} else if ( * p == 'l' && p [ 1 ] == ':' ) { 6368* opt_flags = OPT_LOCAL ; 6369p += 2 ; 6370} else { 6371* opt_flags = 0 ; 6372} 6373 6374const char * end = find_option_end ( p , opt_idxp ); 6375* arg = end == NULL ? * arg : p ; 6376return end ; 6377} 6378 6379var_flavour_T var_flavour ( char * varname ) 6380FUNC_ATTR_PURE 6381{ 6382char * p = varname ; 6383 6384if ( ASCII_ISUPPER ( * p )) { 6385while ( * ( ++ p )) { 6386if ( ASCII_ISLOWER ( * p )) { 6387return VAR_FLAVOUR_SESSION ; 6388} 6389} 6390return VAR_FLAVOUR_SHADA ; 6391} 6392return VAR_FLAVOUR_DEFAULT ; 6393} 6394 6395void var_set_global (const char * const name , typval_T vartv ) 6396{ 6397funccal_entry_T funccall_entry ; 6398 6399save_funccal ( & funccall_entry ); 6400set_var ( name , strlen ( name ), & vartv , false); 6401restore_funccal (); 6402} 6403 6404/// Display script name where an item was last set. 6405/// Should only be invoked when 'verbose' is non-zero. 6406void last_set_msg ( sctx_T script_ctx ) 6407{ 6408if ( script_ctx . sc_sid == 0 ) { 6409return; 6410} 6411 6412bool should_free ; 6413char * p = get_scriptname ( script_ctx , & should_free ); 6414msg_ext_skip_verbose = true; // no verbose kind for last set messages: too noisy 6415 6416verbose_enter (); 6417msg_puts ( _ ( "\n\tLast set from " )); 6418msg_puts ( p ); 6419if ( script_ctx . sc_lnum > 0 ) { 6420msg_puts ( _ ( line_msg )); 6421msg_outnum ( script_ctx . sc_lnum ); 6422} else if ( script_is_lua ( script_ctx . sc_sid )) { 6423msg_puts ( _ ( " (run Nvim with -V1 for more details)" )); 6424} 6425if ( should_free ) { 6426xfree ( p ); 6427} 6428verbose_leave (); 6429} 6430 6431/// Perform a substitution on "str" with pattern "pat" and substitute "sub". 6432/// When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL. 6433/// "flags" can be "g" to do a global substitute. 6434/// 6435/// @param ret_len length of returned buffer 6436/// 6437/// @return an allocated string, NULL for error. 6438char * do_string_sub ( char * str , size_t len , char * pat , char * sub , typval_T * expr , const char * flags , 6439size_t * ret_len ) 6440{ 6441regmatch_T regmatch ; 6442garray_T ga ; 6443 6444// Make 'cpoptions' empty, so that the 'l' flag doesn't work here 6445char * save_cpo = p_cpo ; 6446p_cpo = empty_string_option ; 6447 6448ga_init ( & ga , 1 , 200 ); 6449 6450regmatch . rm_ic = p_ic ; 6451regmatch . regprog = vim_regcomp ( pat , RE_MAGIC + RE_STRING ); 6452if ( regmatch . regprog != NULL ) { 6453char * tail = str ; 6454char * end = str + len ; 6455bool do_all = ( flags [ 0 ] == 'g' ); 6456int sublen ; 6457char * zero_width = NULL ; 6458 6459while ( vim_regexec_nl ( & regmatch , str , ( colnr_T )( tail - str ))) { 6460// Skip empty match except for first match. 6461if ( regmatch . startp [ 0 ] == regmatch . endp [ 0 ]) { 6462if ( zero_width == regmatch . startp [ 0 ]) { 6463// avoid getting stuck on a match with an empty string 6464int i = utfc_ptr2len ( tail ); 6465memmove (( char * ) ga . ga_data + ga . ga_len , tail , ( size_t ) i ); 6466ga . ga_len += i ; 6467tail += i ; 6468continue; 6469} 6470zero_width = regmatch . startp [ 0 ]; 6471} 6472 6473// Get some space for a temporary buffer to do the substitution 6474// into. It will contain: 6475// - The text up to where the match is. 6476// - The substituted text. 6477// - The text after the match. 6478sublen = vim_regsub ( & regmatch , sub , expr , tail , 0 , REGSUB_MAGIC ); 6479if ( sublen <= 0 ) { 6480ga_clear ( & ga ); 6481break; 6482} 6483ga_grow ( & ga , ( int )(( end - tail ) + sublen - 6484( regmatch . endp [ 0 ] - regmatch . startp [ 0 ]))); 6485 6486// copy the text up to where the match is 6487int i = ( int )( regmatch . startp [ 0 ] - tail ); 6488memmove (( char * ) ga . ga_data + ga . ga_len , tail , ( size_t ) i ); 6489// add the substituted text 6490vim_regsub ( & regmatch , sub , expr , 6491( char * ) ga . ga_data + ga . ga_len + i , sublen , 6492REGSUB_COPY | REGSUB_MAGIC ); 6493ga . ga_len += i + sublen - 1 ; 6494tail = regmatch . endp [ 0 ]; 6495if ( * tail == NUL ) { 6496break; 6497} 6498if (! do_all ) { 6499break; 6500} 6501} 6502 6503if ( ga . ga_data != NULL ) { 6504STRCPY (( char * ) ga . ga_data + ga . ga_len , tail ); 6505ga . ga_len += ( int )( end - tail ); 6506} 6507 6508vim_regfree ( regmatch . regprog ); 6509} 6510 6511if ( ga . ga_data != NULL ) { 6512str = ga . ga_data ; 6513len = ( size_t ) ga . ga_len ; 6514} 6515char * ret = xstrnsave ( str , len ); 6516ga_clear ( & ga ); 6517if ( p_cpo == empty_string_option ) { 6518p_cpo = save_cpo ; 6519} else { 6520// Darn, evaluating {sub} expression or {expr} changed the value. 6521// If it's still empty it was changed and restored, need to restore in 6522// the complicated way. 6523if ( * p_cpo == NUL ) { 6524set_option_value_give_err ( kOptCpoptions , CSTR_AS_OBJ ( save_cpo ), 0 ); 6525} 6526free_string_option ( save_cpo ); 6527} 6528 6529if ( ret_len != NULL ) { 6530* ret_len = len ; 6531} 6532 6533return ret ; 6534} 6535 6536/// Common code for getting job callbacks for `jobstart`. 6537/// 6538/// @return true/false on success/failure. 6539bool common_job_callbacks ( dict_T * vopts , CallbackReader * on_stdout , CallbackReader * on_stderr , 6540Callback * on_exit ) 6541{ 6542if ( tv_dict_get_callback ( vopts , S_LEN ( "on_stdout" ), & on_stdout -> cb ) 6543&& tv_dict_get_callback ( vopts , S_LEN ( "on_stderr" ), & on_stderr -> cb ) 6544&& tv_dict_get_callback ( vopts , S_LEN ( "on_exit" ), on_exit )) { 6545on_stdout -> buffered = tv_dict_get_number ( vopts , "stdout_buffered" ); 6546on_stderr -> buffered = tv_dict_get_number ( vopts , "stderr_buffered" ); 6547if ( on_stdout -> buffered && on_stdout -> cb . type == kCallbackNone ) { 6548on_stdout -> self = vopts ; 6549} 6550if ( on_stderr -> buffered && on_stderr -> cb . type == kCallbackNone ) { 6551on_stderr -> self = vopts ; 6552} 6553vopts -> dv_refcount ++ ; 6554return true; 6555} 6556 6557callback_reader_free ( on_stdout ); 6558callback_reader_free ( on_stderr ); 6559callback_free ( on_exit ); 6560return false; 6561} 6562 6563Channel * find_job ( uint64_t id , bool show_error ) 6564{ 6565Channel * data = find_channel ( id ); 6566if (! data || data -> streamtype != kChannelStreamProc 6567|| proc_is_stopped ( & data -> stream . proc )) { 6568if ( show_error ) { 6569if ( data && data -> streamtype != kChannelStreamProc ) { 6570emsg ( _ ( e_invchanjob )); 6571} else { 6572emsg ( _ ( e_invchan )); 6573} 6574} 6575return NULL ; 6576} 6577return data ; 6578} 6579 6580void script_host_eval ( char * name , typval_T * argvars , typval_T * rettv ) 6581{ 6582if ( check_secure ()) { 6583return; 6584} 6585 6586if ( argvars [ 0 ]. v_type != VAR_STRING ) { 6587emsg ( _ ( e_invarg )); 6588return; 6589} 6590 6591list_T * args = tv_list_alloc ( 1 ); 6592tv_list_append_string ( args , argvars [ 0 ]. vval . v_string , -1 ); 6593* rettv = eval_call_provider ( name , "eval" , args , false); 6594} 6595 6596/// @param discard Clears the value returned by the provider and returns 6597/// an empty typval_T. 6598typval_T eval_call_provider ( char * provider , char * method , list_T * arguments , bool discard ) 6599{ 6600if (! eval_has_provider ( provider , false)) { 6601semsg ( "E319: No \"%s\" provider found. Run \":checkhealth vim.provider\"" , 6602provider ); 6603return ( typval_T ){ 6604. v_type = VAR_NUMBER , 6605. v_lock = VAR_UNLOCKED , 6606. vval . v_number = 0 6607}; 6608} 6609 6610char func [ 256 ]; 6611int name_len = snprintf ( func , sizeof( func ), "provider#%s#Call" , provider ); 6612 6613// Save caller scope information 6614struct caller_scope saved_provider_caller_scope = provider_caller_scope ; 6615provider_caller_scope = (struct caller_scope ) { 6616. script_ctx = current_sctx , 6617. es_entry = (( estack_T * ) exestack . ga_data )[ exestack . ga_len - 1 ], 6618. autocmd_fname = autocmd_fname , 6619. autocmd_match = autocmd_match , 6620. autocmd_fname_full = autocmd_fname_full , 6621. autocmd_bufnr = autocmd_bufnr , 6622. funccalp = ( void * ) get_current_funccal () 6623}; 6624funccal_entry_T funccal_entry ; 6625save_funccal ( & funccal_entry ); 6626provider_call_nesting ++ ; 6627 6628typval_T argvars [ 3 ] = { 6629{ . v_type = VAR_STRING , . vval . v_string = method , 6630. v_lock = VAR_UNLOCKED }, 6631{ . v_type = VAR_LIST , . vval . v_list = arguments , . v_lock = VAR_UNLOCKED }, 6632{ . v_type = VAR_UNKNOWN } 6633}; 6634typval_T rettv = { . v_type = VAR_UNKNOWN , . v_lock = VAR_UNLOCKED }; 6635tv_list_ref ( arguments ); 6636 6637funcexe_T funcexe = FUNCEXE_INIT ; 6638funcexe . fe_firstline = curwin -> w_cursor . lnum ; 6639funcexe . fe_lastline = curwin -> w_cursor . lnum ; 6640funcexe . fe_evaluate = true; 6641call_func ( func , name_len , & rettv , 2 , argvars , & funcexe ); 6642 6643tv_list_unref ( arguments ); 6644// Restore caller scope information 6645restore_funccal (); 6646provider_caller_scope = saved_provider_caller_scope ; 6647provider_call_nesting -- ; 6648assert ( provider_call_nesting >= 0 ); 6649 6650if ( discard ) { 6651tv_clear ( & rettv ); 6652} 6653 6654return rettv ; 6655} 6656 6657/// Checks if provider for feature `feat` is enabled. 6658bool eval_has_provider (const char * feat , bool throw_if_fast ) 6659{ 6660if (! strequal ( feat , "clipboard" ) 6661&& ! strequal ( feat , "python3" ) 6662&& ! strequal ( feat , "python3_compiled" ) 6663&& ! strequal ( feat , "python3_dynamic" ) 6664&& ! strequal ( feat , "perl" ) 6665&& ! strequal ( feat , "ruby" ) 6666&& ! strequal ( feat , "node" )) { 6667// Avoid autoload for non-provider has() features. 6668return false; 6669} 6670 6671if ( throw_if_fast && ! nlua_is_deferred_safe ()) { 6672semsg ( e_fast_api_disabled , "Vimscript function" ); 6673return false; 6674} 6675 6676char name [ 32 ]; // Normalized: "python3_compiled" => "python3". 6677snprintf ( name , sizeof( name ), "%s" , feat ); 6678strchrsub ( name , '_' , NUL ); // Chop any "_xx" suffix. 6679 6680char buf [ 256 ]; 6681typval_T tv ; 6682// Get the g:loaded_xx_provider variable. 6683int len = snprintf ( buf , sizeof( buf ), "g:loaded_%s_provider" , name ); 6684if ( eval_variable ( buf , len , & tv , NULL , false, true) == FAIL ) { 6685// Trigger autoload once. 6686len = snprintf ( buf , sizeof( buf ), "provider#%s#bogus" , name ); 6687script_autoload ( buf , ( size_t ) len , false); 6688 6689// Retry the (non-autoload-style) variable. 6690len = snprintf ( buf , sizeof( buf ), "g:loaded_%s_provider" , name ); 6691if ( eval_variable ( buf , len , & tv , NULL , false, true) == FAIL ) { 6692// Show a hint if Call() is defined but g:loaded_xx_provider is missing. 6693snprintf ( buf , sizeof( buf ), "provider#%s#Call" , name ); 6694if (!! find_func ( buf ) && p_lpl ) { 6695semsg ( "provider: %s: missing required variable g:loaded_%s_provider" , 6696name , name ); 6697} 6698return false; 6699} 6700} 6701 6702bool ok = ( tv . v_type == VAR_NUMBER ) 6703? 2 == tv . vval . v_number // Value of 2 means "loaded and working". 6704: false; 6705 6706if ( ok ) { 6707// Call() must be defined if provider claims to be working. 6708snprintf ( buf , sizeof( buf ), "provider#%s#Call" , name ); 6709if (! find_func ( buf )) { 6710semsg ( "provider: %s: g:loaded_%s_provider=2 but %s is not defined" , 6711name , name , buf ); 6712ok = false; 6713} 6714} 6715 6716return ok ; 6717} 6718 6719/// Writes "<sourcing_name>:<sourcing_lnum>" to `buf[bufsize]`. 6720void eval_fmt_source_name_line ( char * buf , size_t bufsize ) 6721{ 6722if ( SOURCING_NAME ) { 6723snprintf ( buf , bufsize , "%s:%" PRIdLINENR , SOURCING_NAME , SOURCING_LNUM ); 6724} else { 6725snprintf ( buf , bufsize , "?" ); 6726} 6727} 6728 6729/// Gets the current user-input in prompt buffer `buf`, or NULL if buffer is not a prompt buffer. 6730char * prompt_get_input ( buf_T * buf ) 6731{ 6732if (! bt_prompt ( buf )) { 6733return NULL ; 6734} 6735linenr_T lnum_start = buf -> b_prompt_start . mark . lnum ; 6736linenr_T lnum_last = buf -> b_ml . ml_line_count ; 6737 6738char * text = ml_get_buf ( buf , lnum_start ); 6739if (( int ) strlen ( text ) >= buf -> b_prompt_start . mark . col ) { 6740text += buf -> b_prompt_start . mark . col ; 6741} 6742 6743char * full_text = xstrdup ( text ); 6744for ( linenr_T i = lnum_start + 1 ; i <= lnum_last ; i ++ ) { 6745char * half_text = concat_str ( full_text , "\n" ); 6746xfree ( full_text ); 6747full_text = concat_str ( half_text , ml_get_buf ( buf , i )); 6748xfree ( half_text ); 6749} 6750return full_text ; 6751} 6752 6753/// Compare "typ1" and "typ2". Put the result in "typ1". 6754/// 6755/// @param typ1 first operand 6756/// @param typ2 second operand 6757/// @param type operator 6758/// @param ic ignore case 6759int typval_compare ( typval_T * typ1 , typval_T * typ2 , exprtype_T type , bool ic ) 6760FUNC_ATTR_NONNULL_ALL 6761{ 6762varnumber_T n1 , n2 ; 6763const bool type_is = type == EXPR_IS || type == EXPR_ISNOT ; 6764 6765if ( type_is && typ1 -> v_type != typ2 -> v_type ) { 6766// For "is" a different type always means false, for "isnot" 6767// it means true. 6768n1 = type == EXPR_ISNOT ; 6769} else if ( typ1 -> v_type == VAR_BLOB || typ2 -> v_type == VAR_BLOB ) { 6770if ( type_is ) { 6771n1 = typ1 -> v_type == typ2 -> v_type 6772&& typ1 -> vval . v_blob == typ2 -> vval . v_blob ; 6773if ( type == EXPR_ISNOT ) { 6774n1 = ! n1 ; 6775} 6776} else if ( typ1 -> v_type != typ2 -> v_type 6777|| ( type != EXPR_EQUAL && type != EXPR_NEQUAL )) { 6778if ( typ1 -> v_type != typ2 -> v_type ) { 6779emsg ( _ ( "E977: Can only compare Blob with Blob" )); 6780} else { 6781emsg ( _ ( e_invalblob )); 6782} 6783tv_clear ( typ1 ); 6784return FAIL ; 6785} else { 6786// Compare two Blobs for being equal or unequal. 6787n1 = tv_blob_equal ( typ1 -> vval . v_blob , typ2 -> vval . v_blob ); 6788if ( type == EXPR_NEQUAL ) { 6789n1 = ! n1 ; 6790} 6791} 6792} else if ( typ1 -> v_type == VAR_LIST || typ2 -> v_type == VAR_LIST ) { 6793if ( type_is ) { 6794n1 = typ1 -> v_type == typ2 -> v_type 6795&& typ1 -> vval . v_list == typ2 -> vval . v_list ; 6796if ( type == EXPR_ISNOT ) { 6797n1 = ! n1 ; 6798} 6799} else if ( typ1 -> v_type != typ2 -> v_type 6800|| ( type != EXPR_EQUAL && type != EXPR_NEQUAL )) { 6801if ( typ1 -> v_type != typ2 -> v_type ) { 6802emsg ( _ ( "E691: Can only compare List with List" )); 6803} else { 6804emsg ( _ ( "E692: Invalid operation for List" )); 6805} 6806tv_clear ( typ1 ); 6807return FAIL ; 6808} else { 6809// Compare two Lists for being equal or unequal. 6810n1 = tv_list_equal ( typ1 -> vval . v_list , typ2 -> vval . v_list , ic ); 6811if ( type == EXPR_NEQUAL ) { 6812n1 = ! n1 ; 6813} 6814} 6815} else if ( typ1 -> v_type == VAR_DICT || typ2 -> v_type == VAR_DICT ) { 6816if ( type_is ) { 6817n1 = typ1 -> v_type == typ2 -> v_type 6818&& typ1 -> vval . v_dict == typ2 -> vval . v_dict ; 6819if ( type == EXPR_ISNOT ) { 6820n1 = ! n1 ; 6821} 6822} else if ( typ1 -> v_type != typ2 -> v_type 6823|| ( type != EXPR_EQUAL && type != EXPR_NEQUAL )) { 6824if ( typ1 -> v_type != typ2 -> v_type ) { 6825emsg ( _ ( "E735: Can only compare Dictionary with Dictionary" )); 6826} else { 6827emsg ( _ ( "E736: Invalid operation for Dictionary" )); 6828} 6829tv_clear ( typ1 ); 6830return FAIL ; 6831} else { 6832// Compare two Dictionaries for being equal or unequal. 6833n1 = tv_dict_equal ( typ1 -> vval . v_dict , typ2 -> vval . v_dict , ic ); 6834if ( type == EXPR_NEQUAL ) { 6835n1 = ! n1 ; 6836} 6837} 6838} else if ( tv_is_func ( * typ1 ) || tv_is_func ( * typ2 )) { 6839if ( type != EXPR_EQUAL && type != EXPR_NEQUAL 6840&& type != EXPR_IS && type != EXPR_ISNOT ) { 6841emsg ( _ ( "E694: Invalid operation for Funcrefs" )); 6842tv_clear ( typ1 ); 6843return FAIL ; 6844} 6845if (( typ1 -> v_type == VAR_PARTIAL && typ1 -> vval . v_partial == NULL ) 6846|| ( typ2 -> v_type == VAR_PARTIAL && typ2 -> vval . v_partial == NULL )) { 6847// When both partials are NULL, then they are equal. 6848// Otherwise they are not equal. 6849n1 = ( typ1 -> vval . v_partial == typ2 -> vval . v_partial ); 6850} else if ( type_is ) { 6851if ( typ1 -> v_type == VAR_FUNC && typ2 -> v_type == VAR_FUNC ) { 6852// strings are considered the same if their value is 6853// the same 6854n1 = tv_equal ( typ1 , typ2 , ic ); 6855} else if ( typ1 -> v_type == VAR_PARTIAL && typ2 -> v_type == VAR_PARTIAL ) { 6856n1 = typ1 -> vval . v_partial == typ2 -> vval . v_partial ; 6857} else { 6858n1 = false; 6859} 6860} else { 6861n1 = tv_equal ( typ1 , typ2 , ic ); 6862} 6863if ( type == EXPR_NEQUAL || type == EXPR_ISNOT ) { 6864n1 = ! n1 ; 6865} 6866} else if (( typ1 -> v_type == VAR_FLOAT || typ2 -> v_type == VAR_FLOAT ) 6867&& type != EXPR_MATCH && type != EXPR_NOMATCH ) { 6868// If one of the two variables is a float, compare as a float. 6869// When using "=~" or "!~", always compare as string. 6870const float_T f1 = tv_get_float ( typ1 ); 6871const float_T f2 = tv_get_float ( typ2 ); 6872n1 = false; 6873switch ( type ) { 6874case EXPR_IS : 6875case EXPR_EQUAL : 6876n1 = f1 == f2 ; break; 6877case EXPR_ISNOT : 6878case EXPR_NEQUAL : 6879n1 = f1 != f2 ; break; 6880case EXPR_GREATER : 6881n1 = f1 > f2 ; break; 6882case EXPR_GEQUAL : 6883n1 = f1 >= f2 ; break; 6884case EXPR_SMALLER : 6885n1 = f1 < f2 ; break; 6886case EXPR_SEQUAL : 6887n1 = f1 <= f2 ; break; 6888case EXPR_UNKNOWN : 6889case EXPR_MATCH : 6890case EXPR_NOMATCH : 6891break; // avoid gcc warning 6892} 6893} else if (( typ1 -> v_type == VAR_NUMBER || typ2 -> v_type == VAR_NUMBER ) 6894&& type != EXPR_MATCH && type != EXPR_NOMATCH ) { 6895// If one of the two variables is a number, compare as a number. 6896// When using "=~" or "!~", always compare as string. 6897n1 = tv_get_number ( typ1 ); 6898n2 = tv_get_number ( typ2 ); 6899switch ( type ) { 6900case EXPR_IS : 6901case EXPR_EQUAL : 6902n1 = n1 == n2 ; break; 6903case EXPR_ISNOT : 6904case EXPR_NEQUAL : 6905n1 = n1 != n2 ; break; 6906case EXPR_GREATER : 6907n1 = n1 > n2 ; break; 6908case EXPR_GEQUAL : 6909n1 = n1 >= n2 ; break; 6910case EXPR_SMALLER : 6911n1 = n1 < n2 ; break; 6912case EXPR_SEQUAL : 6913n1 = n1 <= n2 ; break; 6914case EXPR_UNKNOWN : 6915case EXPR_MATCH : 6916case EXPR_NOMATCH : 6917break; // avoid gcc warning 6918} 6919} else { 6920char buf1 [ NUMBUFLEN ]; 6921char buf2 [ NUMBUFLEN ]; 6922const char * const s1 = tv_get_string_buf ( typ1 , buf1 ); 6923const char * const s2 = tv_get_string_buf ( typ2 , buf2 ); 6924int i ; 6925if ( type != EXPR_MATCH && type != EXPR_NOMATCH ) { 6926i = mb_strcmp_ic ( ic , s1 , s2 ); 6927} else { 6928i = 0 ; 6929} 6930n1 = false; 6931switch ( type ) { 6932case EXPR_IS : 6933case EXPR_EQUAL : 6934n1 = i == 0 ; break; 6935case EXPR_ISNOT : 6936case EXPR_NEQUAL : 6937n1 = i != 0 ; break; 6938case EXPR_GREATER : 6939n1 = i > 0 ; break; 6940case EXPR_GEQUAL : 6941n1 = i >= 0 ; break; 6942case EXPR_SMALLER : 6943n1 = i < 0 ; break; 6944case EXPR_SEQUAL : 6945n1 = i <= 0 ; break; 6946 6947case EXPR_MATCH : 6948case EXPR_NOMATCH : 6949n1 = pattern_match ( s2 , s1 , ic ); 6950if ( type == EXPR_NOMATCH ) { 6951n1 = ! n1 ; 6952} 6953break; 6954case EXPR_UNKNOWN : 6955break; // avoid gcc warning 6956} 6957} 6958tv_clear ( typ1 ); 6959typ1 -> v_type = VAR_NUMBER ; 6960typ1 -> vval . v_number = n1 ; 6961return OK ; 6962} 6963 6964/// Convert any type to a string, never give an error. 6965/// When "quotes" is true add quotes to a string. 6966/// Returns an allocated string. 6967char * typval_tostring ( typval_T * arg , bool quotes ) 6968{ 6969if ( arg == NULL ) { 6970return xstrdup ( "(does not exist)" ); 6971} 6972if (! quotes && arg -> v_type == VAR_STRING ) { 6973return xstrdup ( arg -> vval . v_string == NULL ? "" : arg -> vval . v_string ); 6974} 6975return encode_tv2string ( arg , NULL ); 6976}