robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

zeertzjqMerge pull request #41243 from janlazo/vim-8.2.15909f600c8914

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