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