xref: /vim-8.2.3635/src/eval.c (revision 130cbfc3)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * eval.c: Expression evaluation.
12  */
13 #define USING_FLOAT_STUFF
14 
15 #include "vim.h"
16 
17 #if defined(FEAT_EVAL) || defined(PROTO)
18 
19 #ifdef VMS
20 # include <float.h>
21 #endif
22 
23 #define NAMESPACE_CHAR	(char_u *)"abglstvw"
24 
25 /*
26  * When recursively copying lists and dicts we need to remember which ones we
27  * have done to avoid endless recursiveness.  This unique ID is used for that.
28  * The last bit is used for previous_funccal, ignored when comparing.
29  */
30 static int current_copyID = 0;
31 
32 /*
33  * Info used by a ":for" loop.
34  */
35 typedef struct
36 {
37     int		fi_semicolon;	// TRUE if ending in '; var]'
38     int		fi_varcount;	// nr of variables in the list
39     int		fi_break_count;	// nr of line breaks encountered
40     listwatch_T	fi_lw;		// keep an eye on the item used.
41     list_T	*fi_list;	// list being used
42     int		fi_bi;		// index of blob
43     blob_T	*fi_blob;	// blob being used
44     char_u	*fi_string;	// copy of string being used
45     int		fi_byte_idx;	// byte index in fi_string
46 } forinfo_T;
47 
48 static int tv_op(typval_T *tv1, typval_T *tv2, char_u  *op);
49 static int eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
50 static int eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
51 static int eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
52 static int eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg);
53 static int eval6(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);
54 static int eval7(char_u **arg, typval_T *rettv, evalarg_T *evalarg, int want_string);
55 static int eval7_leader(typval_T *rettv, int numeric_only, char_u *start_leader, char_u **end_leaderp);
56 
57 static int free_unref_items(int copyID);
58 static char_u *make_expanded_name(char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end);
59 
60 /*
61  * Return "n1" divided by "n2", taking care of dividing by zero.
62  * If "failed" is not NULL set it to TRUE when dividing by zero fails.
63  */
64 	varnumber_T
65 num_divide(varnumber_T n1, varnumber_T n2, int *failed)
66 {
67     varnumber_T	result;
68 
69     if (n2 == 0)
70     {
71 	if (in_vim9script())
72 	{
73 	    emsg(_(e_divide_by_zero));
74 	    if (failed != NULL)
75 		*failed = TRUE;
76 	}
77 	if (n1 == 0)
78 	    result = VARNUM_MIN; // similar to NaN
79 	else if (n1 < 0)
80 	    result = -VARNUM_MAX;
81 	else
82 	    result = VARNUM_MAX;
83     }
84     else
85 	result = n1 / n2;
86 
87     return result;
88 }
89 
90 /*
91  * Return "n1" modulus "n2", taking care of dividing by zero.
92  * If "failed" is not NULL set it to TRUE when dividing by zero fails.
93  */
94 	varnumber_T
95 num_modulus(varnumber_T n1, varnumber_T n2, int *failed)
96 {
97     if (n2 == 0 && in_vim9script())
98     {
99 	emsg(_(e_divide_by_zero));
100 	if (failed != NULL)
101 	    *failed = TRUE;
102     }
103     return (n2 == 0) ? 0 : (n1 % n2);
104 }
105 
106 #if defined(EBCDIC) || defined(PROTO)
107 /*
108  * Compare struct fst by function name.
109  */
110     static int
111 compare_func_name(const void *s1, const void *s2)
112 {
113     struct fst *p1 = (struct fst *)s1;
114     struct fst *p2 = (struct fst *)s2;
115 
116     return STRCMP(p1->f_name, p2->f_name);
117 }
118 
119 /*
120  * Sort the function table by function name.
121  * The sorting of the table above is ASCII dependent.
122  * On machines using EBCDIC we have to sort it.
123  */
124     static void
125 sortFunctions(void)
126 {
127     int		funcCnt = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
128 
129     qsort(functions, (size_t)funcCnt, sizeof(struct fst), compare_func_name);
130 }
131 #endif
132 
133 /*
134  * Initialize the global and v: variables.
135  */
136     void
137 eval_init(void)
138 {
139     evalvars_init();
140     func_init();
141 
142 #ifdef EBCDIC
143     /*
144      * Sort the function table, to enable binary search.
145      */
146     sortFunctions();
147 #endif
148 }
149 
150 #if defined(EXITFREE) || defined(PROTO)
151     void
152 eval_clear(void)
153 {
154     evalvars_clear();
155     free_scriptnames();  // must come after evalvars_clear().
156     free_locales();
157 
158     // autoloaded script names
159     free_autoload_scriptnames();
160 
161     // unreferenced lists and dicts
162     (void)garbage_collect(FALSE);
163 
164     // functions not garbage collected
165     free_all_functions();
166 }
167 #endif
168 
169     void
170 fill_evalarg_from_eap(evalarg_T *evalarg, exarg_T *eap, int skip)
171 {
172     CLEAR_FIELD(*evalarg);
173     evalarg->eval_flags = skip ? 0 : EVAL_EVALUATE;
174     if (eap != NULL && getline_equal(eap->getline, eap->cookie, getsourceline))
175     {
176 	evalarg->eval_getline = eap->getline;
177 	evalarg->eval_cookie = eap->cookie;
178     }
179 }
180 
181 /*
182  * Top level evaluation function, returning a boolean.
183  * Sets "error" to TRUE if there was an error.
184  * Return TRUE or FALSE.
185  */
186     int
187 eval_to_bool(
188     char_u	*arg,
189     int		*error,
190     exarg_T	*eap,
191     int		skip)	    // only parse, don't execute
192 {
193     typval_T	tv;
194     varnumber_T	retval = FALSE;
195     evalarg_T	evalarg;
196 
197     fill_evalarg_from_eap(&evalarg, eap, skip);
198 
199     if (skip)
200 	++emsg_skip;
201     if (eval0(arg, &tv, eap, &evalarg) == FAIL)
202 	*error = TRUE;
203     else
204     {
205 	*error = FALSE;
206 	if (!skip)
207 	{
208 	    if (in_vim9script())
209 		retval = tv_get_bool_chk(&tv, error);
210 	    else
211 		retval = (tv_get_number_chk(&tv, error) != 0);
212 	    clear_tv(&tv);
213 	}
214     }
215     if (skip)
216 	--emsg_skip;
217     clear_evalarg(&evalarg, eap);
218 
219     return (int)retval;
220 }
221 
222 /*
223  * Call eval1() and give an error message if not done at a lower level.
224  */
225     static int
226 eval1_emsg(char_u **arg, typval_T *rettv, exarg_T *eap)
227 {
228     char_u	*start = *arg;
229     int		ret;
230     int		did_emsg_before = did_emsg;
231     int		called_emsg_before = called_emsg;
232     evalarg_T	evalarg;
233 
234     fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
235 
236     ret = eval1(arg, rettv, &evalarg);
237     if (ret == FAIL)
238     {
239 	// Report the invalid expression unless the expression evaluation has
240 	// been cancelled due to an aborting error, an interrupt, or an
241 	// exception, or we already gave a more specific error.
242 	// Also check called_emsg for when using assert_fails().
243 	if (!aborting() && did_emsg == did_emsg_before
244 					  && called_emsg == called_emsg_before)
245 	    semsg(_(e_invexpr2), start);
246     }
247     clear_evalarg(&evalarg, eap);
248     return ret;
249 }
250 
251 /*
252  * Return whether a typval is a valid expression to pass to eval_expr_typval()
253  * or eval_expr_to_bool().  An empty string returns FALSE;
254  */
255     int
256 eval_expr_valid_arg(typval_T *tv)
257 {
258     return tv->v_type != VAR_UNKNOWN
259 	    && (tv->v_type != VAR_STRING
260 		  || (tv->vval.v_string != NULL && *tv->vval.v_string != NUL));
261 }
262 
263 /*
264  * Evaluate an expression, which can be a function, partial or string.
265  * Pass arguments "argv[argc]".
266  * Return the result in "rettv" and OK or FAIL.
267  */
268     int
269 eval_expr_typval(typval_T *expr, typval_T *argv, int argc, typval_T *rettv)
270 {
271     char_u	*s;
272     char_u	buf[NUMBUFLEN];
273     funcexe_T	funcexe;
274 
275     if (expr->v_type == VAR_FUNC)
276     {
277 	s = expr->vval.v_string;
278 	if (s == NULL || *s == NUL)
279 	    return FAIL;
280 	CLEAR_FIELD(funcexe);
281 	funcexe.evaluate = TRUE;
282 	if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
283 	    return FAIL;
284     }
285     else if (expr->v_type == VAR_PARTIAL)
286     {
287 	partial_T   *partial = expr->vval.v_partial;
288 
289 	if (partial == NULL)
290 	    return FAIL;
291 
292 	if (partial->pt_func != NULL
293 			  && partial->pt_func->uf_def_status != UF_NOT_COMPILED)
294 	{
295 	    if (call_def_function(partial->pt_func, argc, argv,
296 						       partial, rettv) == FAIL)
297 		return FAIL;
298 	}
299 	else
300 	{
301 	    s = partial_name(partial);
302 	    if (s == NULL || *s == NUL)
303 		return FAIL;
304 	    CLEAR_FIELD(funcexe);
305 	    funcexe.evaluate = TRUE;
306 	    funcexe.partial = partial;
307 	    if (call_func(s, -1, rettv, argc, argv, &funcexe) == FAIL)
308 		return FAIL;
309 	}
310     }
311     else
312     {
313 	s = tv_get_string_buf_chk(expr, buf);
314 	if (s == NULL)
315 	    return FAIL;
316 	s = skipwhite(s);
317 	if (eval1_emsg(&s, rettv, NULL) == FAIL)
318 	    return FAIL;
319 	if (*skipwhite(s) != NUL)  // check for trailing chars after expr
320 	{
321 	    clear_tv(rettv);
322 	    semsg(_(e_invexpr2), s);
323 	    return FAIL;
324 	}
325     }
326     return OK;
327 }
328 
329 /*
330  * Like eval_to_bool() but using a typval_T instead of a string.
331  * Works for string, funcref and partial.
332  */
333     int
334 eval_expr_to_bool(typval_T *expr, int *error)
335 {
336     typval_T	rettv;
337     int		res;
338 
339     if (eval_expr_typval(expr, NULL, 0, &rettv) == FAIL)
340     {
341 	*error = TRUE;
342 	return FALSE;
343     }
344     res = (tv_get_bool_chk(&rettv, error) != 0);
345     clear_tv(&rettv);
346     return res;
347 }
348 
349 /*
350  * Top level evaluation function, returning a string.  If "skip" is TRUE,
351  * only parsing to "nextcmd" is done, without reporting errors.  Return
352  * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
353  */
354     char_u *
355 eval_to_string_skip(
356     char_u	*arg,
357     exarg_T	*eap,
358     int		skip)	    // only parse, don't execute
359 {
360     typval_T	tv;
361     char_u	*retval;
362     evalarg_T	evalarg;
363 
364     fill_evalarg_from_eap(&evalarg, eap, skip);
365     if (skip)
366 	++emsg_skip;
367     if (eval0(arg, &tv, eap, &evalarg) == FAIL || skip)
368 	retval = NULL;
369     else
370     {
371 	retval = vim_strsave(tv_get_string(&tv));
372 	clear_tv(&tv);
373     }
374     if (skip)
375 	--emsg_skip;
376     clear_evalarg(&evalarg, eap);
377 
378     return retval;
379 }
380 
381 /*
382  * Skip over an expression at "*pp".
383  * Return FAIL for an error, OK otherwise.
384  */
385     int
386 skip_expr(char_u **pp, evalarg_T *evalarg)
387 {
388     typval_T	rettv;
389 
390     *pp = skipwhite(*pp);
391     return eval1(pp, &rettv, evalarg);
392 }
393 
394 /*
395  * Skip over an expression at "*pp".
396  * If in Vim9 script and line breaks are encountered, the lines are
397  * concatenated.  "evalarg->eval_tofree" will be set accordingly.
398  * "arg" is advanced to just after the expression.
399  * "start" is set to the start of the expression, "end" to just after the end.
400  * Also when the expression is copied to allocated memory.
401  * Return FAIL for an error, OK otherwise.
402  */
403     int
404 skip_expr_concatenate(
405 	char_u	    **arg,
406 	char_u	    **start,
407 	char_u	    **end,
408 	evalarg_T   *evalarg)
409 {
410     typval_T	rettv;
411     int		res;
412     int		vim9script = in_vim9script();
413     garray_T    *gap = evalarg == NULL ? NULL : &evalarg->eval_ga;
414     int		save_flags = evalarg == NULL ? 0 : evalarg->eval_flags;
415     int		evaluate = evalarg == NULL
416 			       ? FALSE : (evalarg->eval_flags & EVAL_EVALUATE);
417 
418     if (vim9script && evaluate
419 	       && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))
420     {
421 	ga_init2(gap, sizeof(char_u *), 10);
422 	// leave room for "start"
423 	if (ga_grow(gap, 1) == OK)
424 	    ++gap->ga_len;
425     }
426     *start = *arg;
427 
428     // Don't evaluate the expression.
429     if (evalarg != NULL)
430 	evalarg->eval_flags &= ~EVAL_EVALUATE;
431     *arg = skipwhite(*arg);
432     res = eval1(arg, &rettv, evalarg);
433     *end = *arg;
434     if (evalarg != NULL)
435 	evalarg->eval_flags = save_flags;
436 
437     if (vim9script && evaluate
438 	    && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL))
439     {
440 	if (evalarg->eval_ga.ga_len == 1)
441 	{
442 	    // just one line, no need to concatenate
443 	    ga_clear(gap);
444 	    gap->ga_itemsize = 0;
445 	}
446 	else
447 	{
448 	    char_u	    *p;
449 	    size_t	    endoff = STRLEN(*arg);
450 
451 	    // Line breaks encountered, concatenate all the lines.
452 	    *((char_u **)gap->ga_data) = *start;
453 	    p = ga_concat_strings(gap, "");
454 
455 	    // free the lines only when using getsourceline()
456 	    if (evalarg->eval_cookie != NULL)
457 	    {
458 		// Do not free the first line, the caller can still use it.
459 		*((char_u **)gap->ga_data) = NULL;
460 		// Do not free the last line, "arg" points into it, free it
461 		// later.
462 		vim_free(evalarg->eval_tofree);
463 		evalarg->eval_tofree =
464 				    ((char_u **)gap->ga_data)[gap->ga_len - 1];
465 		((char_u **)gap->ga_data)[gap->ga_len - 1] = NULL;
466 		ga_clear_strings(gap);
467 	    }
468 	    else
469 		ga_clear(gap);
470 	    gap->ga_itemsize = 0;
471 	    if (p == NULL)
472 		return FAIL;
473 	    *start = p;
474 	    vim_free(evalarg->eval_tofree_lambda);
475 	    evalarg->eval_tofree_lambda = p;
476 	    // Compute "end" relative to the end.
477 	    *end = *start + STRLEN(*start) - endoff;
478 	}
479     }
480 
481     return res;
482 }
483 
484 /*
485  * Convert "tv" to a string.
486  * When "convert" is TRUE convert a List into a sequence of lines and convert
487  * a Float to a String.
488  * Returns an allocated string (NULL when out of memory).
489  */
490     char_u *
491 typval2string(typval_T *tv, int convert)
492 {
493     garray_T	ga;
494     char_u	*retval;
495 #ifdef FEAT_FLOAT
496     char_u	numbuf[NUMBUFLEN];
497 #endif
498 
499     if (convert && tv->v_type == VAR_LIST)
500     {
501 	ga_init2(&ga, (int)sizeof(char), 80);
502 	if (tv->vval.v_list != NULL)
503 	{
504 	    list_join(&ga, tv->vval.v_list, (char_u *)"\n", TRUE, FALSE, 0);
505 	    if (tv->vval.v_list->lv_len > 0)
506 		ga_append(&ga, NL);
507 	}
508 	ga_append(&ga, NUL);
509 	retval = (char_u *)ga.ga_data;
510     }
511 #ifdef FEAT_FLOAT
512     else if (convert && tv->v_type == VAR_FLOAT)
513     {
514 	vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
515 	retval = vim_strsave(numbuf);
516     }
517 #endif
518     else
519 	retval = vim_strsave(tv_get_string(tv));
520     return retval;
521 }
522 
523 /*
524  * Top level evaluation function, returning a string.  Does not handle line
525  * breaks.
526  * When "convert" is TRUE convert a List into a sequence of lines and convert
527  * a Float to a String.
528  * Return pointer to allocated memory, or NULL for failure.
529  */
530     char_u *
531 eval_to_string_eap(
532     char_u	*arg,
533     int		convert,
534     exarg_T	*eap)
535 {
536     typval_T	tv;
537     char_u	*retval;
538     evalarg_T	evalarg;
539 
540     fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
541     if (eval0(arg, &tv, NULL, &evalarg) == FAIL)
542 	retval = NULL;
543     else
544     {
545 	retval = typval2string(&tv, convert);
546 	clear_tv(&tv);
547     }
548     clear_evalarg(&evalarg, NULL);
549 
550     return retval;
551 }
552 
553     char_u *
554 eval_to_string(
555     char_u	*arg,
556     int		convert)
557 {
558     return eval_to_string_eap(arg, convert, NULL);
559 }
560 
561 /*
562  * Call eval_to_string() without using current local variables and using
563  * textwinlock.  When "use_sandbox" is TRUE use the sandbox.
564  * Use legacy Vim script syntax.
565  */
566     char_u *
567 eval_to_string_safe(
568     char_u	*arg,
569     int		use_sandbox)
570 {
571     char_u	*retval;
572     funccal_entry_T funccal_entry;
573     int		save_sc_version = current_sctx.sc_version;
574 
575     current_sctx.sc_version = 1;
576     save_funccal(&funccal_entry);
577     if (use_sandbox)
578 	++sandbox;
579     ++textwinlock;
580     retval = eval_to_string(arg, FALSE);
581     if (use_sandbox)
582 	--sandbox;
583     --textwinlock;
584     restore_funccal();
585     current_sctx.sc_version = save_sc_version;
586     return retval;
587 }
588 
589 /*
590  * Top level evaluation function, returning a number.
591  * Evaluates "expr" silently.
592  * Returns -1 for an error.
593  */
594     varnumber_T
595 eval_to_number(char_u *expr)
596 {
597     typval_T	rettv;
598     varnumber_T	retval;
599     char_u	*p = skipwhite(expr);
600 
601     ++emsg_off;
602 
603     if (eval1(&p, &rettv, &EVALARG_EVALUATE) == FAIL)
604 	retval = -1;
605     else
606     {
607 	retval = tv_get_number_chk(&rettv, NULL);
608 	clear_tv(&rettv);
609     }
610     --emsg_off;
611 
612     return retval;
613 }
614 
615 /*
616  * Top level evaluation function.
617  * Returns an allocated typval_T with the result.
618  * Returns NULL when there is an error.
619  */
620     typval_T *
621 eval_expr(char_u *arg, exarg_T *eap)
622 {
623     typval_T	*tv;
624     evalarg_T	evalarg;
625 
626     fill_evalarg_from_eap(&evalarg, eap, eap != NULL && eap->skip);
627 
628     tv = ALLOC_ONE(typval_T);
629     if (tv != NULL && eval0(arg, tv, eap, &evalarg) == FAIL)
630 	VIM_CLEAR(tv);
631 
632     clear_evalarg(&evalarg, eap);
633     return tv;
634 }
635 
636 /*
637  * Call some Vim script function and return the result in "*rettv".
638  * Uses argv[0] to argv[argc - 1] for the function arguments.  argv[argc]
639  * should have type VAR_UNKNOWN.
640  * Returns OK or FAIL.
641  */
642     int
643 call_vim_function(
644     char_u      *func,
645     int		argc,
646     typval_T	*argv,
647     typval_T	*rettv)
648 {
649     int		ret;
650     funcexe_T	funcexe;
651 
652     rettv->v_type = VAR_UNKNOWN;		// clear_tv() uses this
653     CLEAR_FIELD(funcexe);
654     funcexe.firstline = curwin->w_cursor.lnum;
655     funcexe.lastline = curwin->w_cursor.lnum;
656     funcexe.evaluate = TRUE;
657     ret = call_func(func, -1, rettv, argc, argv, &funcexe);
658     if (ret == FAIL)
659 	clear_tv(rettv);
660 
661     return ret;
662 }
663 
664 /*
665  * Call Vim script function "func" and return the result as a number.
666  * Returns -1 when calling the function fails.
667  * Uses argv[0] to argv[argc - 1] for the function arguments. argv[argc] should
668  * have type VAR_UNKNOWN.
669  */
670     varnumber_T
671 call_func_retnr(
672     char_u      *func,
673     int		argc,
674     typval_T	*argv)
675 {
676     typval_T	rettv;
677     varnumber_T	retval;
678 
679     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
680 	return -1;
681 
682     retval = tv_get_number_chk(&rettv, NULL);
683     clear_tv(&rettv);
684     return retval;
685 }
686 
687 /*
688  * Call Vim script function like call_func_retnr() and drop the result.
689  * Returns FAIL when calling the function fails.
690  */
691     int
692 call_func_noret(
693     char_u      *func,
694     int		argc,
695     typval_T	*argv)
696 {
697     typval_T	rettv;
698 
699     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
700 	return FAIL;
701     clear_tv(&rettv);
702     return OK;
703 }
704 
705 /*
706  * Call Vim script function "func" and return the result as a string.
707  * Uses "argv" and "argc" as call_func_retnr().
708  * Returns NULL when calling the function fails.
709  */
710     void *
711 call_func_retstr(
712     char_u      *func,
713     int		argc,
714     typval_T	*argv)
715 {
716     typval_T	rettv;
717     char_u	*retval;
718 
719     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
720 	return NULL;
721 
722     retval = vim_strsave(tv_get_string(&rettv));
723     clear_tv(&rettv);
724     return retval;
725 }
726 
727 /*
728  * Call Vim script function "func" and return the result as a List.
729  * Uses "argv" and "argc" as call_func_retnr().
730  * Returns NULL when there is something wrong.
731  */
732     void *
733 call_func_retlist(
734     char_u      *func,
735     int		argc,
736     typval_T	*argv)
737 {
738     typval_T	rettv;
739 
740     if (call_vim_function(func, argc, argv, &rettv) == FAIL)
741 	return NULL;
742 
743     if (rettv.v_type != VAR_LIST)
744     {
745 	clear_tv(&rettv);
746 	return NULL;
747     }
748 
749     return rettv.vval.v_list;
750 }
751 
752 #ifdef FEAT_FOLDING
753 /*
754  * Evaluate "arg", which is 'foldexpr'.
755  * Note: caller must set "curwin" to match "arg".
756  * Returns the foldlevel, and any character preceding it in "*cp".  Doesn't
757  * give error messages.
758  */
759     int
760 eval_foldexpr(char_u *arg, int *cp)
761 {
762     typval_T	tv;
763     varnumber_T	retval;
764     char_u	*s;
765     int		use_sandbox = was_set_insecurely((char_u *)"foldexpr",
766 								   OPT_LOCAL);
767 
768     ++emsg_off;
769     if (use_sandbox)
770 	++sandbox;
771     ++textwinlock;
772     *cp = NUL;
773     if (eval0(arg, &tv, NULL, &EVALARG_EVALUATE) == FAIL)
774 	retval = 0;
775     else
776     {
777 	// If the result is a number, just return the number.
778 	if (tv.v_type == VAR_NUMBER)
779 	    retval = tv.vval.v_number;
780 	else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
781 	    retval = 0;
782 	else
783 	{
784 	    // If the result is a string, check if there is a non-digit before
785 	    // the number.
786 	    s = tv.vval.v_string;
787 	    if (!VIM_ISDIGIT(*s) && *s != '-')
788 		*cp = *s++;
789 	    retval = atol((char *)s);
790 	}
791 	clear_tv(&tv);
792     }
793     --emsg_off;
794     if (use_sandbox)
795 	--sandbox;
796     --textwinlock;
797     clear_evalarg(&EVALARG_EVALUATE, NULL);
798 
799     return (int)retval;
800 }
801 #endif
802 
803 /*
804  * Get an lval: variable, Dict item or List item that can be assigned a value
805  * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
806  * "name.key", "name.key[expr]" etc.
807  * Indexing only works if "name" is an existing List or Dictionary.
808  * "name" points to the start of the name.
809  * If "rettv" is not NULL it points to the value to be assigned.
810  * "unlet" is TRUE for ":unlet": slightly different behavior when something is
811  * wrong; must end in space or cmd separator.
812  *
813  * flags:
814  *  GLV_QUIET:       do not give error messages
815  *  GLV_READ_ONLY:   will not change the variable
816  *  GLV_NO_AUTOLOAD: do not use script autoloading
817  *
818  * Returns a pointer to just after the name, including indexes.
819  * When an evaluation error occurs "lp->ll_name" is NULL;
820  * Returns NULL for a parsing error.  Still need to free items in "lp"!
821  */
822     char_u *
823 get_lval(
824     char_u	*name,
825     typval_T	*rettv,
826     lval_T	*lp,
827     int		unlet,
828     int		skip,
829     int		flags,	    // GLV_ values
830     int		fne_flags)  // flags for find_name_end()
831 {
832     char_u	*p;
833     char_u	*expr_start, *expr_end;
834     int		cc;
835     dictitem_T	*v;
836     typval_T	var1;
837     typval_T	var2;
838     int		empty1 = FALSE;
839     listitem_T	*ni;
840     char_u	*key = NULL;
841     int		len;
842     hashtab_T	*ht = NULL;
843     int		quiet = flags & GLV_QUIET;
844     int		writing;
845 
846     // Clear everything in "lp".
847     CLEAR_POINTER(lp);
848 
849     if (skip || (flags & GLV_COMPILING))
850     {
851 	// When skipping or compiling just find the end of the name.
852 	lp->ll_name = name;
853 	lp->ll_name_end = find_name_end(name, NULL, NULL,
854 						      FNE_INCL_BR | fne_flags);
855 	return lp->ll_name_end;
856     }
857 
858     // Find the end of the name.
859     p = find_name_end(name, &expr_start, &expr_end, fne_flags);
860     lp->ll_name_end = p;
861     if (expr_start != NULL)
862     {
863 	// Don't expand the name when we already know there is an error.
864 	if (unlet && !VIM_ISWHITE(*p) && !ends_excmd(*p)
865 						    && *p != '[' && *p != '.')
866 	{
867 	    semsg(_(e_trailing_arg), p);
868 	    return NULL;
869 	}
870 
871 	lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
872 	if (lp->ll_exp_name == NULL)
873 	{
874 	    // Report an invalid expression in braces, unless the
875 	    // expression evaluation has been cancelled due to an
876 	    // aborting error, an interrupt, or an exception.
877 	    if (!aborting() && !quiet)
878 	    {
879 		emsg_severe = TRUE;
880 		semsg(_(e_invarg2), name);
881 		return NULL;
882 	    }
883 	}
884 	lp->ll_name = lp->ll_exp_name;
885     }
886     else
887     {
888 	lp->ll_name = name;
889 
890 	if (in_vim9script())
891 	{
892 	    // "a: type" is declaring variable "a" with a type, not "a:".
893 	    if (p == name + 2 && p[-1] == ':')
894 	    {
895 		--p;
896 		lp->ll_name_end = p;
897 	    }
898 	    if (*p == ':')
899 	    {
900 		scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
901 		char_u	 *tp = skipwhite(p + 1);
902 
903 		// parse the type after the name
904 		lp->ll_type = parse_type(&tp, &si->sn_type_list, !quiet);
905 		if (lp->ll_type == NULL && !quiet)
906 		    return NULL;
907 		lp->ll_name_end = tp;
908 	    }
909 	}
910     }
911 
912     // Without [idx] or .key we are done.
913     if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
914 	return p;
915 
916     cc = *p;
917     *p = NUL;
918     // When we would write to the variable pass &ht and prevent autoload.
919     writing = !(flags & GLV_READ_ONLY);
920     v = find_var(lp->ll_name, writing ? &ht : NULL,
921 					 (flags & GLV_NO_AUTOLOAD) || writing);
922     if (v == NULL && !quiet)
923 	semsg(_(e_undefined_variable_str), lp->ll_name);
924     *p = cc;
925     if (v == NULL)
926 	return NULL;
927 
928     if (in_vim9script() && (flags & GLV_NO_DECL) == 0)
929     {
930 	if (!quiet)
931 	    semsg(_(e_variable_already_declared), lp->ll_name);
932 	return NULL;
933     }
934 
935     /*
936      * Loop until no more [idx] or .key is following.
937      */
938     lp->ll_tv = &v->di_tv;
939     var1.v_type = VAR_UNKNOWN;
940     var2.v_type = VAR_UNKNOWN;
941     while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
942     {
943 	if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
944 		&& !(lp->ll_tv->v_type == VAR_DICT)
945 		&& !(lp->ll_tv->v_type == VAR_BLOB
946 					   && lp->ll_tv->vval.v_blob != NULL))
947 	{
948 	    if (!quiet)
949 		emsg(_("E689: Can only index a List, Dictionary or Blob"));
950 	    return NULL;
951 	}
952 	if (lp->ll_range)
953 	{
954 	    if (!quiet)
955 		emsg(_("E708: [:] must come last"));
956 	    return NULL;
957 	}
958 
959 	if (in_vim9script() && lp->ll_valtype == NULL
960 		&& lp->ll_tv == &v->di_tv
961 		&& ht != NULL && ht == get_script_local_ht())
962 	{
963 	    svar_T  *sv = find_typval_in_script(lp->ll_tv);
964 
965 	    // Vim9 script local variable: get the type
966 	    if (sv != NULL)
967 		lp->ll_valtype = sv->sv_type;
968 	}
969 
970 	len = -1;
971 	if (*p == '.')
972 	{
973 	    key = p + 1;
974 	    for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
975 		;
976 	    if (len == 0)
977 	    {
978 		if (!quiet)
979 		    emsg(_(e_emptykey));
980 		return NULL;
981 	    }
982 	    p = key + len;
983 	}
984 	else
985 	{
986 	    // Get the index [expr] or the first index [expr: ].
987 	    p = skipwhite(p + 1);
988 	    if (*p == ':')
989 		empty1 = TRUE;
990 	    else
991 	    {
992 		empty1 = FALSE;
993 		if (eval1(&p, &var1, &EVALARG_EVALUATE) == FAIL)  // recursive!
994 		    return NULL;
995 		if (tv_get_string_chk(&var1) == NULL)
996 		{
997 		    // not a number or string
998 		    clear_tv(&var1);
999 		    return NULL;
1000 		}
1001 		p = skipwhite(p);
1002 	    }
1003 
1004 	    // Optionally get the second index [ :expr].
1005 	    if (*p == ':')
1006 	    {
1007 		if (lp->ll_tv->v_type == VAR_DICT)
1008 		{
1009 		    if (!quiet)
1010 			emsg(_(e_cannot_slice_dictionary));
1011 		    clear_tv(&var1);
1012 		    return NULL;
1013 		}
1014 		if (rettv != NULL
1015 			&& !(rettv->v_type == VAR_LIST
1016 						 && rettv->vval.v_list != NULL)
1017 			&& !(rettv->v_type == VAR_BLOB
1018 						&& rettv->vval.v_blob != NULL))
1019 		{
1020 		    if (!quiet)
1021 			emsg(_("E709: [:] requires a List or Blob value"));
1022 		    clear_tv(&var1);
1023 		    return NULL;
1024 		}
1025 		p = skipwhite(p + 1);
1026 		if (*p == ']')
1027 		    lp->ll_empty2 = TRUE;
1028 		else
1029 		{
1030 		    lp->ll_empty2 = FALSE;
1031 		    // recursive!
1032 		    if (eval1(&p, &var2, &EVALARG_EVALUATE) == FAIL)
1033 		    {
1034 			clear_tv(&var1);
1035 			return NULL;
1036 		    }
1037 		    if (tv_get_string_chk(&var2) == NULL)
1038 		    {
1039 			// not a number or string
1040 			clear_tv(&var1);
1041 			clear_tv(&var2);
1042 			return NULL;
1043 		    }
1044 		}
1045 		lp->ll_range = TRUE;
1046 	    }
1047 	    else
1048 		lp->ll_range = FALSE;
1049 
1050 	    if (*p != ']')
1051 	    {
1052 		if (!quiet)
1053 		    emsg(_(e_missbrac));
1054 		clear_tv(&var1);
1055 		clear_tv(&var2);
1056 		return NULL;
1057 	    }
1058 
1059 	    // Skip to past ']'.
1060 	    ++p;
1061 	}
1062 
1063 	if (lp->ll_tv->v_type == VAR_DICT)
1064 	{
1065 	    if (len == -1)
1066 	    {
1067 		// "[key]": get key from "var1"
1068 		key = tv_get_string_chk(&var1);	// is number or string
1069 		if (key == NULL)
1070 		{
1071 		    clear_tv(&var1);
1072 		    return NULL;
1073 		}
1074 	    }
1075 	    lp->ll_list = NULL;
1076 
1077 	    // a NULL dict is equivalent with an empty dict
1078 	    if (lp->ll_tv->vval.v_dict == NULL)
1079 	    {
1080 		lp->ll_tv->vval.v_dict = dict_alloc();
1081 		if (lp->ll_tv->vval.v_dict == NULL)
1082 		{
1083 		    clear_tv(&var1);
1084 		    return NULL;
1085 		}
1086 		++lp->ll_tv->vval.v_dict->dv_refcount;
1087 	    }
1088 	    lp->ll_dict = lp->ll_tv->vval.v_dict;
1089 
1090 	    lp->ll_di = dict_find(lp->ll_dict, key, len);
1091 
1092 	    // When assigning to a scope dictionary check that a function and
1093 	    // variable name is valid (only variable name unless it is l: or
1094 	    // g: dictionary). Disallow overwriting a builtin function.
1095 	    if (rettv != NULL && lp->ll_dict->dv_scope != 0)
1096 	    {
1097 		int prevval;
1098 		int wrong;
1099 
1100 		if (len != -1)
1101 		{
1102 		    prevval = key[len];
1103 		    key[len] = NUL;
1104 		}
1105 		else
1106 		    prevval = 0; // avoid compiler warning
1107 		wrong = (lp->ll_dict->dv_scope == VAR_DEF_SCOPE
1108 			       && rettv->v_type == VAR_FUNC
1109 			       && var_wrong_func_name(key, lp->ll_di == NULL))
1110 			|| !valid_varname(key, TRUE);
1111 		if (len != -1)
1112 		    key[len] = prevval;
1113 		if (wrong)
1114 		{
1115 		    clear_tv(&var1);
1116 		    return NULL;
1117 		}
1118 	    }
1119 
1120 	    if (lp->ll_valtype != NULL)
1121 		// use the type of the member
1122 		lp->ll_valtype = lp->ll_valtype->tt_member;
1123 
1124 	    if (lp->ll_di == NULL)
1125 	    {
1126 		// Can't add "v:" or "a:" variable.
1127 		if (lp->ll_dict == get_vimvar_dict()
1128 			 || &lp->ll_dict->dv_hashtab == get_funccal_args_ht())
1129 		{
1130 		    semsg(_(e_illvar), name);
1131 		    clear_tv(&var1);
1132 		    return NULL;
1133 		}
1134 
1135 		// Key does not exist in dict: may need to add it.
1136 		if (*p == '[' || *p == '.' || unlet)
1137 		{
1138 		    if (!quiet)
1139 			semsg(_(e_dictkey), key);
1140 		    clear_tv(&var1);
1141 		    return NULL;
1142 		}
1143 		if (len == -1)
1144 		    lp->ll_newkey = vim_strsave(key);
1145 		else
1146 		    lp->ll_newkey = vim_strnsave(key, len);
1147 		clear_tv(&var1);
1148 		if (lp->ll_newkey == NULL)
1149 		    p = NULL;
1150 		break;
1151 	    }
1152 	    // existing variable, need to check if it can be changed
1153 	    else if ((flags & GLV_READ_ONLY) == 0
1154 			&& (var_check_ro(lp->ll_di->di_flags, name, FALSE)
1155 			  || var_check_lock(lp->ll_di->di_flags, name, FALSE)))
1156 	    {
1157 		clear_tv(&var1);
1158 		return NULL;
1159 	    }
1160 
1161 	    clear_tv(&var1);
1162 	    lp->ll_tv = &lp->ll_di->di_tv;
1163 	}
1164 	else if (lp->ll_tv->v_type == VAR_BLOB)
1165 	{
1166 	    long bloblen = blob_len(lp->ll_tv->vval.v_blob);
1167 
1168 	    /*
1169 	     * Get the number and item for the only or first index of the List.
1170 	     */
1171 	    if (empty1)
1172 		lp->ll_n1 = 0;
1173 	    else
1174 		// is number or string
1175 		lp->ll_n1 = (long)tv_get_number(&var1);
1176 	    clear_tv(&var1);
1177 
1178 	    if (lp->ll_n1 < 0
1179 		    || lp->ll_n1 > bloblen
1180 		    || (lp->ll_range && lp->ll_n1 == bloblen))
1181 	    {
1182 		if (!quiet)
1183 		    semsg(_(e_blobidx), lp->ll_n1);
1184 		clear_tv(&var2);
1185 		return NULL;
1186 	    }
1187 	    if (lp->ll_range && !lp->ll_empty2)
1188 	    {
1189 		lp->ll_n2 = (long)tv_get_number(&var2);
1190 		clear_tv(&var2);
1191 		if (lp->ll_n2 < 0
1192 			|| lp->ll_n2 >= bloblen
1193 			|| lp->ll_n2 < lp->ll_n1)
1194 		{
1195 		    if (!quiet)
1196 			semsg(_(e_blobidx), lp->ll_n2);
1197 		    return NULL;
1198 		}
1199 	    }
1200 	    lp->ll_blob = lp->ll_tv->vval.v_blob;
1201 	    lp->ll_tv = NULL;
1202 	    break;
1203 	}
1204 	else
1205 	{
1206 	    /*
1207 	     * Get the number and item for the only or first index of the List.
1208 	     */
1209 	    if (empty1)
1210 		lp->ll_n1 = 0;
1211 	    else
1212 		// is number or string
1213 		lp->ll_n1 = (long)tv_get_number(&var1);
1214 	    clear_tv(&var1);
1215 
1216 	    lp->ll_dict = NULL;
1217 	    lp->ll_list = lp->ll_tv->vval.v_list;
1218 	    lp->ll_li = list_find_index(lp->ll_list, &lp->ll_n1);
1219 	    if (lp->ll_li == NULL)
1220 	    {
1221 		clear_tv(&var2);
1222 		if (!quiet)
1223 		    semsg(_(e_listidx), lp->ll_n1);
1224 		return NULL;
1225 	    }
1226 
1227 	    if (lp->ll_valtype != NULL)
1228 		// use the type of the member
1229 		lp->ll_valtype = lp->ll_valtype->tt_member;
1230 
1231 	    /*
1232 	     * May need to find the item or absolute index for the second
1233 	     * index of a range.
1234 	     * When no index given: "lp->ll_empty2" is TRUE.
1235 	     * Otherwise "lp->ll_n2" is set to the second index.
1236 	     */
1237 	    if (lp->ll_range && !lp->ll_empty2)
1238 	    {
1239 		lp->ll_n2 = (long)tv_get_number(&var2);
1240 						    // is number or string
1241 		clear_tv(&var2);
1242 		if (lp->ll_n2 < 0)
1243 		{
1244 		    ni = list_find(lp->ll_list, lp->ll_n2);
1245 		    if (ni == NULL)
1246 		    {
1247 			if (!quiet)
1248 			    semsg(_(e_listidx), lp->ll_n2);
1249 			return NULL;
1250 		    }
1251 		    lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
1252 		}
1253 
1254 		// Check that lp->ll_n2 isn't before lp->ll_n1.
1255 		if (lp->ll_n1 < 0)
1256 		    lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
1257 		if (lp->ll_n2 < lp->ll_n1)
1258 		{
1259 		    if (!quiet)
1260 			semsg(_(e_listidx), lp->ll_n2);
1261 		    return NULL;
1262 		}
1263 	    }
1264 
1265 	    lp->ll_tv = &lp->ll_li->li_tv;
1266 	}
1267     }
1268 
1269     clear_tv(&var1);
1270     lp->ll_name_end = p;
1271     return p;
1272 }
1273 
1274 /*
1275  * Clear lval "lp" that was filled by get_lval().
1276  */
1277     void
1278 clear_lval(lval_T *lp)
1279 {
1280     vim_free(lp->ll_exp_name);
1281     vim_free(lp->ll_newkey);
1282 }
1283 
1284 /*
1285  * Set a variable that was parsed by get_lval() to "rettv".
1286  * "endp" points to just after the parsed name.
1287  * "op" is NULL, "+" for "+=", "-" for "-=", "*" for "*=", "/" for "/=",
1288  * "%" for "%=", "." for ".=" or "=" for "=".
1289  */
1290     void
1291 set_var_lval(
1292     lval_T	*lp,
1293     char_u	*endp,
1294     typval_T	*rettv,
1295     int		copy,
1296     int		flags,	    // ASSIGN_CONST, ASSIGN_NO_DECL
1297     char_u	*op,
1298     int		var_idx)    // index for "let [a, b] = list"
1299 {
1300     int		cc;
1301     listitem_T	*ri;
1302     dictitem_T	*di;
1303 
1304     if (lp->ll_tv == NULL)
1305     {
1306 	cc = *endp;
1307 	*endp = NUL;
1308 	if (lp->ll_blob != NULL)
1309 	{
1310 	    int	    error = FALSE, val;
1311 
1312 	    if (op != NULL && *op != '=')
1313 	    {
1314 		semsg(_(e_letwrong), op);
1315 		return;
1316 	    }
1317 	    if (value_check_lock(lp->ll_blob->bv_lock, lp->ll_name, FALSE))
1318 		return;
1319 
1320 	    if (lp->ll_range && rettv->v_type == VAR_BLOB)
1321 	    {
1322 		int	il, ir;
1323 
1324 		if (lp->ll_empty2)
1325 		    lp->ll_n2 = blob_len(lp->ll_blob) - 1;
1326 
1327 		if (lp->ll_n2 - lp->ll_n1 + 1 != blob_len(rettv->vval.v_blob))
1328 		{
1329 		    emsg(_("E972: Blob value does not have the right number of bytes"));
1330 		    return;
1331 		}
1332 		if (lp->ll_empty2)
1333 		    lp->ll_n2 = blob_len(lp->ll_blob);
1334 
1335 		ir = 0;
1336 		for (il = lp->ll_n1; il <= lp->ll_n2; il++)
1337 		    blob_set(lp->ll_blob, il,
1338 			    blob_get(rettv->vval.v_blob, ir++));
1339 	    }
1340 	    else
1341 	    {
1342 		val = (int)tv_get_number_chk(rettv, &error);
1343 		if (!error)
1344 		{
1345 		    garray_T *gap = &lp->ll_blob->bv_ga;
1346 
1347 		    // Allow for appending a byte.  Setting a byte beyond
1348 		    // the end is an error otherwise.
1349 		    if (lp->ll_n1 < gap->ga_len
1350 			    || (lp->ll_n1 == gap->ga_len
1351 				&& ga_grow(&lp->ll_blob->bv_ga, 1) == OK))
1352 		    {
1353 			blob_set(lp->ll_blob, lp->ll_n1, val);
1354 			if (lp->ll_n1 == gap->ga_len)
1355 			    ++gap->ga_len;
1356 		    }
1357 		    // error for invalid range was already given in get_lval()
1358 		}
1359 	    }
1360 	}
1361 	else if (op != NULL && *op != '=')
1362 	{
1363 	    typval_T tv;
1364 
1365 	    if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
1366 	    {
1367 		emsg(_(e_cannot_mod));
1368 		*endp = cc;
1369 		return;
1370 	    }
1371 
1372 	    // handle +=, -=, *=, /=, %= and .=
1373 	    di = NULL;
1374 	    if (eval_variable(lp->ll_name, (int)STRLEN(lp->ll_name),
1375 					     &tv, &di, EVAL_VAR_VERBOSE) == OK)
1376 	    {
1377 		if ((di == NULL
1378 			 || (!var_check_ro(di->di_flags, lp->ll_name, FALSE)
1379 			   && !tv_check_lock(&di->di_tv, lp->ll_name, FALSE)))
1380 			&& tv_op(&tv, rettv, op) == OK)
1381 		    set_var(lp->ll_name, &tv, FALSE);
1382 		clear_tv(&tv);
1383 	    }
1384 	}
1385 	else
1386 	{
1387 	    if (lp->ll_type != NULL
1388 		       && check_typval_arg_type(lp->ll_type, rettv, 0) == FAIL)
1389 		return;
1390 	    set_var_const(lp->ll_name, lp->ll_type, rettv, copy,
1391 							       flags, var_idx);
1392 	}
1393 	*endp = cc;
1394     }
1395     else if (value_check_lock(lp->ll_newkey == NULL
1396 		? lp->ll_tv->v_lock
1397 		: lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name, FALSE))
1398 	;
1399     else if (lp->ll_range)
1400     {
1401 	listitem_T *ll_li = lp->ll_li;
1402 	int	    ll_n1 = lp->ll_n1;
1403 
1404 	if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
1405 	{
1406 	    emsg(_("E996: Cannot lock a range"));
1407 	    return;
1408 	}
1409 
1410 	/*
1411 	 * Check whether any of the list items is locked
1412 	 */
1413 	for (ri = rettv->vval.v_list->lv_first; ri != NULL && ll_li != NULL; )
1414 	{
1415 	    if (value_check_lock(ll_li->li_tv.v_lock, lp->ll_name, FALSE))
1416 		return;
1417 	    ri = ri->li_next;
1418 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == ll_n1))
1419 		break;
1420 	    ll_li = ll_li->li_next;
1421 	    ++ll_n1;
1422 	}
1423 
1424 	/*
1425 	 * Assign the List values to the list items.
1426 	 */
1427 	for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
1428 	{
1429 	    if (op != NULL && *op != '=')
1430 		tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
1431 	    else
1432 	    {
1433 		clear_tv(&lp->ll_li->li_tv);
1434 		copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
1435 	    }
1436 	    ri = ri->li_next;
1437 	    if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
1438 		break;
1439 	    if (lp->ll_li->li_next == NULL)
1440 	    {
1441 		// Need to add an empty item.
1442 		if (list_append_number(lp->ll_list, 0) == FAIL)
1443 		{
1444 		    ri = NULL;
1445 		    break;
1446 		}
1447 	    }
1448 	    lp->ll_li = lp->ll_li->li_next;
1449 	    ++lp->ll_n1;
1450 	}
1451 	if (ri != NULL)
1452 	    emsg(_(e_list_value_has_more_items_than_targets));
1453 	else if (lp->ll_empty2
1454 		? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
1455 		: lp->ll_n1 != lp->ll_n2)
1456 	    emsg(_(e_list_value_does_not_have_enough_items));
1457     }
1458     else
1459     {
1460 	/*
1461 	 * Assign to a List or Dictionary item.
1462 	 */
1463 	if (flags & (ASSIGN_CONST | ASSIGN_FINAL))
1464 	{
1465 	    emsg(_("E996: Cannot lock a list or dict"));
1466 	    return;
1467 	}
1468 
1469 	if (lp->ll_valtype != NULL
1470 		    && check_typval_arg_type(lp->ll_valtype, rettv, 0) == FAIL)
1471 	    return;
1472 
1473 	if (lp->ll_newkey != NULL)
1474 	{
1475 	    if (op != NULL && *op != '=')
1476 	    {
1477 		semsg(_(e_dictkey), lp->ll_newkey);
1478 		return;
1479 	    }
1480 
1481 	    // Need to add an item to the Dictionary.
1482 	    di = dictitem_alloc(lp->ll_newkey);
1483 	    if (di == NULL)
1484 		return;
1485 	    if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
1486 	    {
1487 		vim_free(di);
1488 		return;
1489 	    }
1490 	    lp->ll_tv = &di->di_tv;
1491 	}
1492 	else if (op != NULL && *op != '=')
1493 	{
1494 	    tv_op(lp->ll_tv, rettv, op);
1495 	    return;
1496 	}
1497 	else
1498 	    clear_tv(lp->ll_tv);
1499 
1500 	/*
1501 	 * Assign the value to the variable or list item.
1502 	 */
1503 	if (copy)
1504 	    copy_tv(rettv, lp->ll_tv);
1505 	else
1506 	{
1507 	    *lp->ll_tv = *rettv;
1508 	    lp->ll_tv->v_lock = 0;
1509 	    init_tv(rettv);
1510 	}
1511     }
1512 }
1513 
1514 /*
1515  * Handle "tv1 += tv2", "tv1 -= tv2", "tv1 *= tv2", "tv1 /= tv2", "tv1 %= tv2"
1516  * and "tv1 .= tv2"
1517  * Returns OK or FAIL.
1518  */
1519     static int
1520 tv_op(typval_T *tv1, typval_T *tv2, char_u *op)
1521 {
1522     varnumber_T	n;
1523     char_u	numbuf[NUMBUFLEN];
1524     char_u	*s;
1525     int		failed = FALSE;
1526 
1527     // Can't do anything with a Funcref, Dict, v:true on the right.
1528     if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT
1529 		      && tv2->v_type != VAR_BOOL && tv2->v_type != VAR_SPECIAL)
1530     {
1531 	switch (tv1->v_type)
1532 	{
1533 	    case VAR_UNKNOWN:
1534 	    case VAR_ANY:
1535 	    case VAR_VOID:
1536 	    case VAR_DICT:
1537 	    case VAR_FUNC:
1538 	    case VAR_PARTIAL:
1539 	    case VAR_BOOL:
1540 	    case VAR_SPECIAL:
1541 	    case VAR_JOB:
1542 	    case VAR_CHANNEL:
1543 		break;
1544 
1545 	    case VAR_BLOB:
1546 		if (*op != '+' || tv2->v_type != VAR_BLOB)
1547 		    break;
1548 		// BLOB += BLOB
1549 		if (tv1->vval.v_blob != NULL && tv2->vval.v_blob != NULL)
1550 		{
1551 		    blob_T  *b1 = tv1->vval.v_blob;
1552 		    blob_T  *b2 = tv2->vval.v_blob;
1553 		    int	i, len = blob_len(b2);
1554 		    for (i = 0; i < len; i++)
1555 			ga_append(&b1->bv_ga, blob_get(b2, i));
1556 		}
1557 		return OK;
1558 
1559 	    case VAR_LIST:
1560 		if (*op != '+' || tv2->v_type != VAR_LIST)
1561 		    break;
1562 		// List += List
1563 		if (tv2->vval.v_list != NULL)
1564 		{
1565 		    if (tv1->vval.v_list == NULL)
1566 		    {
1567 			tv1->vval.v_list = tv2->vval.v_list;
1568 			++tv1->vval.v_list->lv_refcount;
1569 		    }
1570 		    else
1571 			list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
1572 		}
1573 		return OK;
1574 
1575 	    case VAR_NUMBER:
1576 	    case VAR_STRING:
1577 		if (tv2->v_type == VAR_LIST)
1578 		    break;
1579 		if (vim_strchr((char_u *)"+-*/%", *op) != NULL)
1580 		{
1581 		    // nr += nr , nr -= nr , nr *=nr , nr /= nr , nr %= nr
1582 		    n = tv_get_number(tv1);
1583 #ifdef FEAT_FLOAT
1584 		    if (tv2->v_type == VAR_FLOAT)
1585 		    {
1586 			float_T f = n;
1587 
1588 			if (*op == '%')
1589 			    break;
1590 			switch (*op)
1591 			{
1592 			    case '+': f += tv2->vval.v_float; break;
1593 			    case '-': f -= tv2->vval.v_float; break;
1594 			    case '*': f *= tv2->vval.v_float; break;
1595 			    case '/': f /= tv2->vval.v_float; break;
1596 			}
1597 			clear_tv(tv1);
1598 			tv1->v_type = VAR_FLOAT;
1599 			tv1->vval.v_float = f;
1600 		    }
1601 		    else
1602 #endif
1603 		    {
1604 			switch (*op)
1605 			{
1606 			    case '+': n += tv_get_number(tv2); break;
1607 			    case '-': n -= tv_get_number(tv2); break;
1608 			    case '*': n *= tv_get_number(tv2); break;
1609 			    case '/': n = num_divide(n, tv_get_number(tv2),
1610 							       &failed); break;
1611 			    case '%': n = num_modulus(n, tv_get_number(tv2),
1612 							       &failed); break;
1613 			}
1614 			clear_tv(tv1);
1615 			tv1->v_type = VAR_NUMBER;
1616 			tv1->vval.v_number = n;
1617 		    }
1618 		}
1619 		else
1620 		{
1621 		    if (tv2->v_type == VAR_FLOAT)
1622 			break;
1623 
1624 		    // str .= str
1625 		    s = tv_get_string(tv1);
1626 		    s = concat_str(s, tv_get_string_buf(tv2, numbuf));
1627 		    clear_tv(tv1);
1628 		    tv1->v_type = VAR_STRING;
1629 		    tv1->vval.v_string = s;
1630 		}
1631 		return failed ? FAIL : OK;
1632 
1633 	    case VAR_FLOAT:
1634 #ifdef FEAT_FLOAT
1635 		{
1636 		    float_T f;
1637 
1638 		    if (*op == '%' || *op == '.'
1639 				   || (tv2->v_type != VAR_FLOAT
1640 				    && tv2->v_type != VAR_NUMBER
1641 				    && tv2->v_type != VAR_STRING))
1642 			break;
1643 		    if (tv2->v_type == VAR_FLOAT)
1644 			f = tv2->vval.v_float;
1645 		    else
1646 			f = tv_get_number(tv2);
1647 		    switch (*op)
1648 		    {
1649 			case '+': tv1->vval.v_float += f; break;
1650 			case '-': tv1->vval.v_float -= f; break;
1651 			case '*': tv1->vval.v_float *= f; break;
1652 			case '/': tv1->vval.v_float /= f; break;
1653 		    }
1654 		}
1655 #endif
1656 		return OK;
1657 	}
1658     }
1659 
1660     semsg(_(e_letwrong), op);
1661     return FAIL;
1662 }
1663 
1664 /*
1665  * Evaluate the expression used in a ":for var in expr" command.
1666  * "arg" points to "var".
1667  * Set "*errp" to TRUE for an error, FALSE otherwise;
1668  * Return a pointer that holds the info.  Null when there is an error.
1669  */
1670     void *
1671 eval_for_line(
1672     char_u	*arg,
1673     int		*errp,
1674     exarg_T	*eap,
1675     evalarg_T	*evalarg)
1676 {
1677     forinfo_T	*fi;
1678     char_u	*expr;
1679     typval_T	tv;
1680     list_T	*l;
1681     int		skip = !(evalarg->eval_flags & EVAL_EVALUATE);
1682 
1683     *errp = TRUE;	// default: there is an error
1684 
1685     fi = ALLOC_CLEAR_ONE(forinfo_T);
1686     if (fi == NULL)
1687 	return NULL;
1688 
1689     expr = skip_var_list(arg, TRUE, &fi->fi_varcount, &fi->fi_semicolon, FALSE);
1690     if (expr == NULL)
1691 	return fi;
1692 
1693     expr = skipwhite_and_linebreak(expr, evalarg);
1694     if (expr[0] != 'i' || expr[1] != 'n'
1695 				  || !(expr[2] == NUL || VIM_ISWHITE(expr[2])))
1696     {
1697 	emsg(_(e_missing_in));
1698 	return fi;
1699     }
1700 
1701     if (skip)
1702 	++emsg_skip;
1703     expr = skipwhite_and_linebreak(expr + 2, evalarg);
1704     if (eval0(expr, &tv, eap, evalarg) == OK)
1705     {
1706 	*errp = FALSE;
1707 	if (!skip)
1708 	{
1709 	    if (tv.v_type == VAR_LIST)
1710 	    {
1711 		l = tv.vval.v_list;
1712 		if (l == NULL)
1713 		{
1714 		    // a null list is like an empty list: do nothing
1715 		    clear_tv(&tv);
1716 		}
1717 		else
1718 		{
1719 		    // Need a real list here.
1720 		    CHECK_LIST_MATERIALIZE(l);
1721 
1722 		    // No need to increment the refcount, it's already set for
1723 		    // the list being used in "tv".
1724 		    fi->fi_list = l;
1725 		    list_add_watch(l, &fi->fi_lw);
1726 		    fi->fi_lw.lw_item = l->lv_first;
1727 		}
1728 	    }
1729 	    else if (tv.v_type == VAR_BLOB)
1730 	    {
1731 		fi->fi_bi = 0;
1732 		if (tv.vval.v_blob != NULL)
1733 		{
1734 		    typval_T btv;
1735 
1736 		    // Make a copy, so that the iteration still works when the
1737 		    // blob is changed.
1738 		    blob_copy(tv.vval.v_blob, &btv);
1739 		    fi->fi_blob = btv.vval.v_blob;
1740 		}
1741 		clear_tv(&tv);
1742 	    }
1743 	    else if (tv.v_type == VAR_STRING)
1744 	    {
1745 		fi->fi_byte_idx = 0;
1746 		fi->fi_string = tv.vval.v_string;
1747 		tv.vval.v_string = NULL;
1748 		if (fi->fi_string == NULL)
1749 		    fi->fi_string = vim_strsave((char_u *)"");
1750 	    }
1751 	    else
1752 	    {
1753 		emsg(_(e_listreq));
1754 		clear_tv(&tv);
1755 	    }
1756 	}
1757     }
1758     if (skip)
1759 	--emsg_skip;
1760     fi->fi_break_count = evalarg->eval_break_count;
1761 
1762     return fi;
1763 }
1764 
1765 /*
1766  * Used when looping over a :for line, skip the "in expr" part.
1767  */
1768     void
1769 skip_for_lines(void *fi_void, evalarg_T *evalarg)
1770 {
1771     forinfo_T	*fi = (forinfo_T *)fi_void;
1772     int		i;
1773 
1774     for (i = 0; i < fi->fi_break_count; ++i)
1775 	eval_next_line(evalarg);
1776 }
1777 
1778 /*
1779  * Use the first item in a ":for" list.  Advance to the next.
1780  * Assign the values to the variable (list).  "arg" points to the first one.
1781  * Return TRUE when a valid item was found, FALSE when at end of list or
1782  * something wrong.
1783  */
1784     int
1785 next_for_item(void *fi_void, char_u *arg)
1786 {
1787     forinfo_T	*fi = (forinfo_T *)fi_void;
1788     int		result;
1789     int		flag = in_vim9script() ? ASSIGN_DECL : 0;
1790     listitem_T	*item;
1791 
1792     if (fi->fi_blob != NULL)
1793     {
1794 	typval_T	tv;
1795 
1796 	if (fi->fi_bi >= blob_len(fi->fi_blob))
1797 	    return FALSE;
1798 	tv.v_type = VAR_NUMBER;
1799 	tv.v_lock = VAR_FIXED;
1800 	tv.vval.v_number = blob_get(fi->fi_blob, fi->fi_bi);
1801 	++fi->fi_bi;
1802 	return ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,
1803 					    fi->fi_varcount, flag, NULL) == OK;
1804     }
1805 
1806     if (fi->fi_string != NULL)
1807     {
1808 	typval_T	tv;
1809 	int		len;
1810 
1811 	len = mb_ptr2len(fi->fi_string + fi->fi_byte_idx);
1812 	if (len == 0)
1813 	    return FALSE;
1814 	tv.v_type = VAR_STRING;
1815 	tv.v_lock = VAR_FIXED;
1816 	tv.vval.v_string = vim_strnsave(fi->fi_string + fi->fi_byte_idx, len);
1817 	fi->fi_byte_idx += len;
1818 	result = ex_let_vars(arg, &tv, TRUE, fi->fi_semicolon,
1819 					    fi->fi_varcount, flag, NULL) == OK;
1820 	vim_free(tv.vval.v_string);
1821 	return result;
1822     }
1823 
1824     item = fi->fi_lw.lw_item;
1825     if (item == NULL)
1826 	result = FALSE;
1827     else
1828     {
1829 	fi->fi_lw.lw_item = item->li_next;
1830 	result = (ex_let_vars(arg, &item->li_tv, TRUE, fi->fi_semicolon,
1831 					   fi->fi_varcount, flag, NULL) == OK);
1832     }
1833     return result;
1834 }
1835 
1836 /*
1837  * Free the structure used to store info used by ":for".
1838  */
1839     void
1840 free_for_info(void *fi_void)
1841 {
1842     forinfo_T    *fi = (forinfo_T *)fi_void;
1843 
1844     if (fi == NULL)
1845 	return;
1846     if (fi->fi_list != NULL)
1847     {
1848 	list_rem_watch(fi->fi_list, &fi->fi_lw);
1849 	list_unref(fi->fi_list);
1850     }
1851     else if (fi->fi_blob != NULL)
1852 	blob_unref(fi->fi_blob);
1853     else
1854 	vim_free(fi->fi_string);
1855     vim_free(fi);
1856 }
1857 
1858     void
1859 set_context_for_expression(
1860     expand_T	*xp,
1861     char_u	*arg,
1862     cmdidx_T	cmdidx)
1863 {
1864     int		has_expr = cmdidx != CMD_let && cmdidx != CMD_var;
1865     int		c;
1866     char_u	*p;
1867 
1868     if (cmdidx == CMD_let || cmdidx == CMD_var
1869 				 || cmdidx == CMD_const || cmdidx == CMD_final)
1870     {
1871 	xp->xp_context = EXPAND_USER_VARS;
1872 	if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
1873 	{
1874 	    // ":let var1 var2 ...": find last space.
1875 	    for (p = arg + STRLEN(arg); p >= arg; )
1876 	    {
1877 		xp->xp_pattern = p;
1878 		MB_PTR_BACK(arg, p);
1879 		if (VIM_ISWHITE(*p))
1880 		    break;
1881 	    }
1882 	    return;
1883 	}
1884     }
1885     else
1886 	xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
1887 							  : EXPAND_EXPRESSION;
1888     while ((xp->xp_pattern = vim_strpbrk(arg,
1889 				  (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
1890     {
1891 	c = *xp->xp_pattern;
1892 	if (c == '&')
1893 	{
1894 	    c = xp->xp_pattern[1];
1895 	    if (c == '&')
1896 	    {
1897 		++xp->xp_pattern;
1898 		xp->xp_context = has_expr ? EXPAND_EXPRESSION : EXPAND_NOTHING;
1899 	    }
1900 	    else if (c != ' ')
1901 	    {
1902 		xp->xp_context = EXPAND_SETTINGS;
1903 		if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
1904 		    xp->xp_pattern += 2;
1905 
1906 	    }
1907 	}
1908 	else if (c == '$')
1909 	{
1910 	    // environment variable
1911 	    xp->xp_context = EXPAND_ENV_VARS;
1912 	}
1913 	else if (c == '=')
1914 	{
1915 	    has_expr = TRUE;
1916 	    xp->xp_context = EXPAND_EXPRESSION;
1917 	}
1918 	else if (c == '#'
1919 		&& xp->xp_context == EXPAND_EXPRESSION)
1920 	{
1921 	    // Autoload function/variable contains '#'.
1922 	    break;
1923 	}
1924 	else if ((c == '<' || c == '#')
1925 		&& xp->xp_context == EXPAND_FUNCTIONS
1926 		&& vim_strchr(xp->xp_pattern, '(') == NULL)
1927 	{
1928 	    // Function name can start with "<SNR>" and contain '#'.
1929 	    break;
1930 	}
1931 	else if (has_expr)
1932 	{
1933 	    if (c == '"')	    // string
1934 	    {
1935 		while ((c = *++xp->xp_pattern) != NUL && c != '"')
1936 		    if (c == '\\' && xp->xp_pattern[1] != NUL)
1937 			++xp->xp_pattern;
1938 		xp->xp_context = EXPAND_NOTHING;
1939 	    }
1940 	    else if (c == '\'')	    // literal string
1941 	    {
1942 		// Trick: '' is like stopping and starting a literal string.
1943 		while ((c = *++xp->xp_pattern) != NUL && c != '\'')
1944 		    /* skip */ ;
1945 		xp->xp_context = EXPAND_NOTHING;
1946 	    }
1947 	    else if (c == '|')
1948 	    {
1949 		if (xp->xp_pattern[1] == '|')
1950 		{
1951 		    ++xp->xp_pattern;
1952 		    xp->xp_context = EXPAND_EXPRESSION;
1953 		}
1954 		else
1955 		    xp->xp_context = EXPAND_COMMANDS;
1956 	    }
1957 	    else
1958 		xp->xp_context = EXPAND_EXPRESSION;
1959 	}
1960 	else
1961 	    // Doesn't look like something valid, expand as an expression
1962 	    // anyway.
1963 	    xp->xp_context = EXPAND_EXPRESSION;
1964 	arg = xp->xp_pattern;
1965 	if (*arg != NUL)
1966 	    while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
1967 		/* skip */ ;
1968     }
1969 
1970     // ":exe one two" completes "two"
1971     if ((cmdidx == CMD_execute
1972 		|| cmdidx == CMD_echo
1973 		|| cmdidx == CMD_echon
1974 		|| cmdidx == CMD_echomsg)
1975 	    && xp->xp_context == EXPAND_EXPRESSION)
1976     {
1977 	for (;;)
1978 	{
1979 	    char_u *n = skiptowhite(arg);
1980 
1981 	    if (n == arg || IS_WHITE_OR_NUL(*skipwhite(n)))
1982 		break;
1983 	    arg = skipwhite(n);
1984 	}
1985     }
1986 
1987     xp->xp_pattern = arg;
1988 }
1989 
1990 /*
1991  * Return TRUE if "pat" matches "text".
1992  * Does not use 'cpo' and always uses 'magic'.
1993  */
1994     int
1995 pattern_match(char_u *pat, char_u *text, int ic)
1996 {
1997     int		matches = FALSE;
1998     char_u	*save_cpo;
1999     regmatch_T	regmatch;
2000 
2001     // avoid 'l' flag in 'cpoptions'
2002     save_cpo = p_cpo;
2003     p_cpo = empty_option;
2004     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
2005     if (regmatch.regprog != NULL)
2006     {
2007 	regmatch.rm_ic = ic;
2008 	matches = vim_regexec_nl(&regmatch, text, (colnr_T)0);
2009 	vim_regfree(regmatch.regprog);
2010     }
2011     p_cpo = save_cpo;
2012     return matches;
2013 }
2014 
2015 /*
2016  * Handle a name followed by "(".  Both for just "name(arg)" and for
2017  * "expr->name(arg)".
2018  * Returns OK or FAIL.
2019  */
2020     static int
2021 eval_func(
2022 	char_u	    **arg,	// points to "(", will be advanced
2023 	evalarg_T   *evalarg,
2024 	char_u	    *name,
2025 	int	    name_len,
2026 	typval_T    *rettv,
2027 	int	    flags,
2028 	typval_T    *basetv)	// "expr" for "expr->name(arg)"
2029 {
2030     int		evaluate = flags & EVAL_EVALUATE;
2031     char_u	*s = name;
2032     int		len = name_len;
2033     partial_T	*partial;
2034     int		ret = OK;
2035     type_T	*type = NULL;
2036 
2037     if (!evaluate)
2038 	check_vars(s, len);
2039 
2040     // If "s" is the name of a variable of type VAR_FUNC
2041     // use its contents.
2042     s = deref_func_name(s, &len, &partial,
2043 				    in_vim9script() ? &type : NULL, !evaluate);
2044 
2045     // Need to make a copy, in case evaluating the arguments makes
2046     // the name invalid.
2047     s = vim_strsave(s);
2048     if (s == NULL || (flags & EVAL_CONSTANT))
2049 	ret = FAIL;
2050     else
2051     {
2052 	funcexe_T funcexe;
2053 
2054 	// Invoke the function.
2055 	CLEAR_FIELD(funcexe);
2056 	funcexe.firstline = curwin->w_cursor.lnum;
2057 	funcexe.lastline = curwin->w_cursor.lnum;
2058 	funcexe.evaluate = evaluate;
2059 	funcexe.partial = partial;
2060 	funcexe.basetv = basetv;
2061 	funcexe.check_type = type;
2062 	ret = get_func_tv(s, len, rettv, arg, evalarg, &funcexe);
2063     }
2064     vim_free(s);
2065 
2066     // If evaluate is FALSE rettv->v_type was not set in
2067     // get_func_tv, but it's needed in handle_subscript() to parse
2068     // what follows. So set it here.
2069     if (rettv->v_type == VAR_UNKNOWN && !evaluate && **arg == '(')
2070     {
2071 	rettv->vval.v_string = NULL;
2072 	rettv->v_type = VAR_FUNC;
2073     }
2074 
2075     // Stop the expression evaluation when immediately
2076     // aborting on error, or when an interrupt occurred or
2077     // an exception was thrown but not caught.
2078     if (evaluate && aborting())
2079     {
2080 	if (ret == OK)
2081 	    clear_tv(rettv);
2082 	ret = FAIL;
2083     }
2084     return ret;
2085 }
2086 
2087 /*
2088  * Get the next line source line without advancing.  But do skip over comment
2089  * lines.
2090  */
2091     static char_u *
2092 getline_peek_skip_comments(evalarg_T *evalarg)
2093 {
2094     for (;;)
2095     {
2096 	char_u *next = getline_peek(evalarg->eval_getline,
2097 							 evalarg->eval_cookie);
2098 	char_u *p;
2099 
2100 	if (next == NULL)
2101 	    break;
2102 	p = skipwhite(next);
2103 	if (*p != NUL && !vim9_comment_start(p))
2104 	    return next;
2105 	(void)eval_next_line(evalarg);
2106     }
2107     return NULL;
2108 }
2109 
2110 /*
2111  * If inside Vim9 script, "arg" points to the end of a line (ignoring a #
2112  * comment) and there is a next line, return the next line (skipping blanks)
2113  * and set "getnext".
2114  * Otherwise just return "arg" unmodified and set "getnext" to FALSE.
2115  * "arg" must point somewhere inside a line, not at the start.
2116  */
2117     char_u *
2118 eval_next_non_blank(char_u *arg, evalarg_T *evalarg, int *getnext)
2119 {
2120     char_u *p = skipwhite(arg);
2121 
2122     *getnext = FALSE;
2123     if (in_vim9script()
2124 	    && evalarg != NULL
2125 	    && (evalarg->eval_cookie != NULL || evalarg->eval_cctx != NULL)
2126 	    && (*p == NUL || (VIM_ISWHITE(p[-1]) && vim9_comment_start(p))))
2127     {
2128 	char_u *next;
2129 
2130 	if (evalarg->eval_cookie != NULL)
2131 	    next = getline_peek_skip_comments(evalarg);
2132 	else
2133 	    next = peek_next_line_from_context(evalarg->eval_cctx);
2134 
2135 	if (next != NULL)
2136 	{
2137 	    *getnext = TRUE;
2138 	    return skipwhite(next);
2139 	}
2140     }
2141     return p;
2142 }
2143 
2144 /*
2145  * To be called after eval_next_non_blank() sets "getnext" to TRUE.
2146  */
2147     char_u *
2148 eval_next_line(evalarg_T *evalarg)
2149 {
2150     garray_T	*gap = &evalarg->eval_ga;
2151     char_u	*line;
2152 
2153     if (evalarg->eval_cookie != NULL)
2154 	line = evalarg->eval_getline(0, evalarg->eval_cookie, 0,
2155 							   GETLINE_CONCAT_ALL);
2156     else
2157 	line = next_line_from_context(evalarg->eval_cctx, TRUE);
2158     ++evalarg->eval_break_count;
2159     if (gap->ga_itemsize > 0 && ga_grow(gap, 1) == OK)
2160     {
2161 	// Going to concatenate the lines after parsing.
2162 	((char_u **)gap->ga_data)[gap->ga_len] = line;
2163 	++gap->ga_len;
2164     }
2165     else if (evalarg->eval_cookie != NULL)
2166     {
2167 	vim_free(evalarg->eval_tofree);
2168 	evalarg->eval_tofree = line;
2169     }
2170     return skipwhite(line);
2171 }
2172 
2173 /*
2174  * Call eval_next_non_blank() and get the next line if needed.
2175  */
2176     char_u *
2177 skipwhite_and_linebreak(char_u *arg, evalarg_T *evalarg)
2178 {
2179     int	    getnext;
2180     char_u  *p = skipwhite(arg);
2181 
2182     if (evalarg == NULL)
2183 	return skipwhite(arg);
2184     eval_next_non_blank(p, evalarg, &getnext);
2185     if (getnext)
2186 	return eval_next_line(evalarg);
2187     return p;
2188 }
2189 
2190 /*
2191  * After using "evalarg" filled from "eap": free the memory.
2192  */
2193     void
2194 clear_evalarg(evalarg_T *evalarg, exarg_T *eap)
2195 {
2196     if (evalarg != NULL)
2197     {
2198 	if (evalarg->eval_tofree != NULL)
2199 	{
2200 	    if (eap != NULL)
2201 	    {
2202 		// We may need to keep the original command line, e.g. for
2203 		// ":let" it has the variable names.  But we may also need the
2204 		// new one, "nextcmd" points into it.  Keep both.
2205 		vim_free(eap->cmdline_tofree);
2206 		eap->cmdline_tofree = *eap->cmdlinep;
2207 		*eap->cmdlinep = evalarg->eval_tofree;
2208 	    }
2209 	    else
2210 		vim_free(evalarg->eval_tofree);
2211 	    evalarg->eval_tofree = NULL;
2212 	}
2213 
2214 	VIM_CLEAR(evalarg->eval_tofree_cmdline);
2215 	VIM_CLEAR(evalarg->eval_tofree_lambda);
2216     }
2217 }
2218 
2219 /*
2220  * The "evaluate" argument: When FALSE, the argument is only parsed but not
2221  * executed.  The function may return OK, but the rettv will be of type
2222  * VAR_UNKNOWN.  The function still returns FAIL for a syntax error.
2223  */
2224 
2225 /*
2226  * Handle zero level expression.
2227  * This calls eval1() and handles error message and nextcmd.
2228  * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
2229  * Note: "rettv.v_lock" is not set.
2230  * "evalarg" can be NULL, EVALARG_EVALUATE or a pointer.
2231  * Return OK or FAIL.
2232  */
2233     int
2234 eval0(
2235     char_u	*arg,
2236     typval_T	*rettv,
2237     exarg_T	*eap,
2238     evalarg_T	*evalarg)
2239 {
2240     int		ret;
2241     char_u	*p;
2242     int		did_emsg_before = did_emsg;
2243     int		called_emsg_before = called_emsg;
2244     int		flags = evalarg == NULL ? 0 : evalarg->eval_flags;
2245 
2246     p = skipwhite(arg);
2247     ret = eval1(&p, rettv, evalarg);
2248     p = skipwhite(p);
2249 
2250     if (ret == FAIL || !ends_excmd2(arg, p))
2251     {
2252 	if (ret != FAIL)
2253 	    clear_tv(rettv);
2254 	/*
2255 	 * Report the invalid expression unless the expression evaluation has
2256 	 * been cancelled due to an aborting error, an interrupt, or an
2257 	 * exception, or we already gave a more specific error.
2258 	 * Also check called_emsg for when using assert_fails().
2259 	 */
2260 	if (!aborting()
2261 		&& did_emsg == did_emsg_before
2262 		&& called_emsg == called_emsg_before
2263 		&& (flags & EVAL_CONSTANT) == 0
2264 		&& (!in_vim9script() || !vim9_bad_comment(p)))
2265 	    semsg(_(e_invexpr2), arg);
2266 
2267 	// Some of the expression may not have been consumed.  Do not check for
2268 	// a next command to avoid more errors, unless "|" is following, which
2269 	// could only be a command separator.
2270 	if (eap != NULL && skipwhite(p)[0] == '|' && skipwhite(p)[1] != '|')
2271 	    eap->nextcmd = check_nextcmd(p);
2272 	return FAIL;
2273     }
2274 
2275     if (eap != NULL)
2276 	eap->nextcmd = check_nextcmd(p);
2277 
2278     return ret;
2279 }
2280 
2281 /*
2282  * Handle top level expression:
2283  *	expr2 ? expr1 : expr1
2284  *	expr2 ?? expr1
2285  *
2286  * "arg" must point to the first non-white of the expression.
2287  * "arg" is advanced to just after the recognized expression.
2288  *
2289  * Note: "rettv.v_lock" is not set.
2290  *
2291  * Return OK or FAIL.
2292  */
2293     int
2294 eval1(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
2295 {
2296     char_u  *p;
2297     int	    getnext;
2298 
2299     CLEAR_POINTER(rettv);
2300 
2301     /*
2302      * Get the first variable.
2303      */
2304     if (eval2(arg, rettv, evalarg) == FAIL)
2305 	return FAIL;
2306 
2307     p = eval_next_non_blank(*arg, evalarg, &getnext);
2308     if (*p == '?')
2309     {
2310 	int		op_falsy = p[1] == '?';
2311 	int		result;
2312 	typval_T	var2;
2313 	evalarg_T	*evalarg_used = evalarg;
2314 	evalarg_T	local_evalarg;
2315 	int		orig_flags;
2316 	int		evaluate;
2317 	int		vim9script = in_vim9script();
2318 
2319 	if (evalarg == NULL)
2320 	{
2321 	    CLEAR_FIELD(local_evalarg);
2322 	    evalarg_used = &local_evalarg;
2323 	}
2324 	orig_flags = evalarg_used->eval_flags;
2325 	evaluate = evalarg_used->eval_flags & EVAL_EVALUATE;
2326 
2327 	if (getnext)
2328 	    *arg = eval_next_line(evalarg_used);
2329 	else
2330 	{
2331 	    if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
2332 	    {
2333 		error_white_both(p, op_falsy ? 2 : 1);
2334 		clear_tv(rettv);
2335 		return FAIL;
2336 	    }
2337 	    *arg = p;
2338 	}
2339 
2340 	result = FALSE;
2341 	if (evaluate)
2342 	{
2343 	    int		error = FALSE;
2344 
2345 	    if (op_falsy)
2346 		result = tv2bool(rettv);
2347 	    else if (vim9script)
2348 		result = tv_get_bool_chk(rettv, &error);
2349 	    else if (tv_get_number_chk(rettv, &error) != 0)
2350 		result = TRUE;
2351 	    if (error || !op_falsy || !result)
2352 		clear_tv(rettv);
2353 	    if (error)
2354 		return FAIL;
2355 	}
2356 
2357 	/*
2358 	 * Get the second variable.  Recursive!
2359 	 */
2360 	if (op_falsy)
2361 	    ++*arg;
2362 	if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))
2363 	{
2364 	    error_white_both(p, op_falsy ? 2 : 1);
2365 	    clear_tv(rettv);
2366 	    return FAIL;
2367 	}
2368 	*arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);
2369 	evalarg_used->eval_flags = (op_falsy ? !result : result)
2370 				    ? orig_flags : orig_flags & ~EVAL_EVALUATE;
2371 	if (eval1(arg, &var2, evalarg_used) == FAIL)
2372 	{
2373 	    evalarg_used->eval_flags = orig_flags;
2374 	    return FAIL;
2375 	}
2376 	if (!op_falsy || !result)
2377 	    *rettv = var2;
2378 
2379 	if (!op_falsy)
2380 	{
2381 	    /*
2382 	     * Check for the ":".
2383 	     */
2384 	    p = eval_next_non_blank(*arg, evalarg_used, &getnext);
2385 	    if (*p != ':')
2386 	    {
2387 		emsg(_(e_missing_colon));
2388 		if (evaluate && result)
2389 		    clear_tv(rettv);
2390 		evalarg_used->eval_flags = orig_flags;
2391 		return FAIL;
2392 	    }
2393 	    if (getnext)
2394 		*arg = eval_next_line(evalarg_used);
2395 	    else
2396 	    {
2397 		if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
2398 		{
2399 		    error_white_both(p, 1);
2400 		    clear_tv(rettv);
2401 		    evalarg_used->eval_flags = orig_flags;
2402 		    return FAIL;
2403 		}
2404 		*arg = p;
2405 	    }
2406 
2407 	    /*
2408 	     * Get the third variable.  Recursive!
2409 	     */
2410 	    if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[1]))
2411 	    {
2412 		error_white_both(p, 1);
2413 		clear_tv(rettv);
2414 		evalarg_used->eval_flags = orig_flags;
2415 		return FAIL;
2416 	    }
2417 	    *arg = skipwhite_and_linebreak(*arg + 1, evalarg_used);
2418 	    evalarg_used->eval_flags = !result ? orig_flags
2419 						 : orig_flags & ~EVAL_EVALUATE;
2420 	    if (eval1(arg, &var2, evalarg_used) == FAIL)
2421 	    {
2422 		if (evaluate && result)
2423 		    clear_tv(rettv);
2424 		evalarg_used->eval_flags = orig_flags;
2425 		return FAIL;
2426 	    }
2427 	    if (evaluate && !result)
2428 		*rettv = var2;
2429 	}
2430 
2431 	if (evalarg == NULL)
2432 	    clear_evalarg(&local_evalarg, NULL);
2433 	else
2434 	    evalarg->eval_flags = orig_flags;
2435     }
2436 
2437     return OK;
2438 }
2439 
2440 /*
2441  * Handle first level expression:
2442  *	expr2 || expr2 || expr2	    logical OR
2443  *
2444  * "arg" must point to the first non-white of the expression.
2445  * "arg" is advanced to just after the recognized expression.
2446  *
2447  * Return OK or FAIL.
2448  */
2449     static int
2450 eval2(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
2451 {
2452     char_u	*p;
2453     int		getnext;
2454 
2455     /*
2456      * Get the first variable.
2457      */
2458     if (eval3(arg, rettv, evalarg) == FAIL)
2459 	return FAIL;
2460 
2461     /*
2462      * Handle the  "||" operator.
2463      */
2464     p = eval_next_non_blank(*arg, evalarg, &getnext);
2465     if (p[0] == '|' && p[1] == '|')
2466     {
2467 	evalarg_T   *evalarg_used = evalarg;
2468 	evalarg_T   local_evalarg;
2469 	int	    evaluate;
2470 	int	    orig_flags;
2471 	long	    result = FALSE;
2472 	typval_T    var2;
2473 	int	    error = FALSE;
2474 	int	    vim9script = in_vim9script();
2475 
2476 	if (evalarg == NULL)
2477 	{
2478 	    CLEAR_FIELD(local_evalarg);
2479 	    evalarg_used = &local_evalarg;
2480 	}
2481 	orig_flags = evalarg_used->eval_flags;
2482 	evaluate = orig_flags & EVAL_EVALUATE;
2483 	if (evaluate)
2484 	{
2485 	    if (vim9script)
2486 		result = tv_get_bool_chk(rettv, &error);
2487 	    else if (tv_get_number_chk(rettv, &error) != 0)
2488 		result = TRUE;
2489 	    clear_tv(rettv);
2490 	    if (error)
2491 		return FAIL;
2492 	}
2493 
2494 	/*
2495 	 * Repeat until there is no following "||".
2496 	 */
2497 	while (p[0] == '|' && p[1] == '|')
2498 	{
2499 	    if (getnext)
2500 		*arg = eval_next_line(evalarg_used);
2501 	    else
2502 	    {
2503 		if (evaluate && in_vim9script() && !VIM_ISWHITE(p[-1]))
2504 		{
2505 		    error_white_both(p, 2);
2506 		    clear_tv(rettv);
2507 		    return FAIL;
2508 		}
2509 		*arg = p;
2510 	    }
2511 
2512 	    /*
2513 	     * Get the second variable.
2514 	     */
2515 	    if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[2]))
2516 	    {
2517 		error_white_both(p, 2);
2518 		clear_tv(rettv);
2519 		return FAIL;
2520 	    }
2521 	    *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);
2522 	    evalarg_used->eval_flags = !result ? orig_flags
2523 						 : orig_flags & ~EVAL_EVALUATE;
2524 	    if (eval3(arg, &var2, evalarg_used) == FAIL)
2525 		return FAIL;
2526 
2527 	    /*
2528 	     * Compute the result.
2529 	     */
2530 	    if (evaluate && !result)
2531 	    {
2532 		if (vim9script)
2533 		    result = tv_get_bool_chk(&var2, &error);
2534 		else if (tv_get_number_chk(&var2, &error) != 0)
2535 		    result = TRUE;
2536 		clear_tv(&var2);
2537 		if (error)
2538 		    return FAIL;
2539 	    }
2540 	    if (evaluate)
2541 	    {
2542 		if (vim9script)
2543 		{
2544 		    rettv->v_type = VAR_BOOL;
2545 		    rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;
2546 		}
2547 		else
2548 		{
2549 		    rettv->v_type = VAR_NUMBER;
2550 		    rettv->vval.v_number = result;
2551 		}
2552 	    }
2553 
2554 	    p = eval_next_non_blank(*arg, evalarg_used, &getnext);
2555 	}
2556 
2557 	if (evalarg == NULL)
2558 	    clear_evalarg(&local_evalarg, NULL);
2559 	else
2560 	    evalarg->eval_flags = orig_flags;
2561     }
2562 
2563     return OK;
2564 }
2565 
2566 /*
2567  * Handle second level expression:
2568  *	expr3 && expr3 && expr3	    logical AND
2569  *
2570  * "arg" must point to the first non-white of the expression.
2571  * "arg" is advanced to just after the recognized expression.
2572  *
2573  * Return OK or FAIL.
2574  */
2575     static int
2576 eval3(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
2577 {
2578     char_u	*p;
2579     int		getnext;
2580 
2581     /*
2582      * Get the first variable.
2583      */
2584     if (eval4(arg, rettv, evalarg) == FAIL)
2585 	return FAIL;
2586 
2587     /*
2588      * Handle the "&&" operator.
2589      */
2590     p = eval_next_non_blank(*arg, evalarg, &getnext);
2591     if (p[0] == '&' && p[1] == '&')
2592     {
2593 	evalarg_T   *evalarg_used = evalarg;
2594 	evalarg_T   local_evalarg;
2595 	int	    orig_flags;
2596 	int	    evaluate;
2597 	long	    result = TRUE;
2598 	typval_T    var2;
2599 	int	    error = FALSE;
2600 	int	    vim9script = in_vim9script();
2601 
2602 	if (evalarg == NULL)
2603 	{
2604 	    CLEAR_FIELD(local_evalarg);
2605 	    evalarg_used = &local_evalarg;
2606 	}
2607 	orig_flags = evalarg_used->eval_flags;
2608 	evaluate = orig_flags & EVAL_EVALUATE;
2609 	if (evaluate)
2610 	{
2611 	    if (vim9script)
2612 		result = tv_get_bool_chk(rettv, &error);
2613 	    else if (tv_get_number_chk(rettv, &error) == 0)
2614 		result = FALSE;
2615 	    clear_tv(rettv);
2616 	    if (error)
2617 		return FAIL;
2618 	}
2619 
2620 	/*
2621 	 * Repeat until there is no following "&&".
2622 	 */
2623 	while (p[0] == '&' && p[1] == '&')
2624 	{
2625 	    if (getnext)
2626 		*arg = eval_next_line(evalarg_used);
2627 	    else
2628 	    {
2629 		if (evaluate && vim9script && !VIM_ISWHITE(p[-1]))
2630 		{
2631 		    error_white_both(p, 2);
2632 		    clear_tv(rettv);
2633 		    return FAIL;
2634 		}
2635 		*arg = p;
2636 	    }
2637 
2638 	    /*
2639 	     * Get the second variable.
2640 	     */
2641 	    if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[2]))
2642 	    {
2643 		error_white_both(p, 2);
2644 		clear_tv(rettv);
2645 		return FAIL;
2646 	    }
2647 	    *arg = skipwhite_and_linebreak(*arg + 2, evalarg_used);
2648 	    evalarg_used->eval_flags = result ? orig_flags
2649 						 : orig_flags & ~EVAL_EVALUATE;
2650 	    CLEAR_FIELD(var2);
2651 	    if (eval4(arg, &var2, evalarg_used) == FAIL)
2652 		return FAIL;
2653 
2654 	    /*
2655 	     * Compute the result.
2656 	     */
2657 	    if (evaluate && result)
2658 	    {
2659 		if (vim9script)
2660 		    result = tv_get_bool_chk(&var2, &error);
2661 		else if (tv_get_number_chk(&var2, &error) == 0)
2662 		    result = FALSE;
2663 		clear_tv(&var2);
2664 		if (error)
2665 		    return FAIL;
2666 	    }
2667 	    if (evaluate)
2668 	    {
2669 		if (vim9script)
2670 		{
2671 		    rettv->v_type = VAR_BOOL;
2672 		    rettv->vval.v_number = result ? VVAL_TRUE : VVAL_FALSE;
2673 		}
2674 		else
2675 		{
2676 		    rettv->v_type = VAR_NUMBER;
2677 		    rettv->vval.v_number = result;
2678 		}
2679 	    }
2680 
2681 	    p = eval_next_non_blank(*arg, evalarg_used, &getnext);
2682 	}
2683 
2684 	if (evalarg == NULL)
2685 	    clear_evalarg(&local_evalarg, NULL);
2686 	else
2687 	    evalarg->eval_flags = orig_flags;
2688     }
2689 
2690     return OK;
2691 }
2692 
2693 /*
2694  * Handle third level expression:
2695  *	var1 == var2
2696  *	var1 =~ var2
2697  *	var1 != var2
2698  *	var1 !~ var2
2699  *	var1 > var2
2700  *	var1 >= var2
2701  *	var1 < var2
2702  *	var1 <= var2
2703  *	var1 is var2
2704  *	var1 isnot var2
2705  *
2706  * "arg" must point to the first non-white of the expression.
2707  * "arg" is advanced to just after the recognized expression.
2708  *
2709  * Return OK or FAIL.
2710  */
2711     static int
2712 eval4(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
2713 {
2714     char_u	*p;
2715     int		getnext;
2716     exprtype_T	type = EXPR_UNKNOWN;
2717     int		len = 2;
2718     int		type_is = FALSE;
2719 
2720     /*
2721      * Get the first variable.
2722      */
2723     if (eval5(arg, rettv, evalarg) == FAIL)
2724 	return FAIL;
2725 
2726     p = eval_next_non_blank(*arg, evalarg, &getnext);
2727     type = get_compare_type(p, &len, &type_is);
2728 
2729     /*
2730      * If there is a comparative operator, use it.
2731      */
2732     if (type != EXPR_UNKNOWN)
2733     {
2734 	typval_T    var2;
2735 	int	    ic;
2736 	int	    vim9script = in_vim9script();
2737 	int	    evaluate = evalarg == NULL
2738 				   ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
2739 
2740 	if (getnext)
2741 	    *arg = eval_next_line(evalarg);
2742 	else if (evaluate && vim9script && !VIM_ISWHITE(**arg))
2743 	{
2744 	    error_white_both(p, len);
2745 	    clear_tv(rettv);
2746 	    return FAIL;
2747 	}
2748 
2749 	if (vim9script && type_is && (p[len] == '?' || p[len] == '#'))
2750 	{
2751 	    semsg(_(e_invexpr2), p);
2752 	    clear_tv(rettv);
2753 	    return FAIL;
2754 	}
2755 
2756 	// extra question mark appended: ignore case
2757 	if (p[len] == '?')
2758 	{
2759 	    ic = TRUE;
2760 	    ++len;
2761 	}
2762 	// extra '#' appended: match case
2763 	else if (p[len] == '#')
2764 	{
2765 	    ic = FALSE;
2766 	    ++len;
2767 	}
2768 	// nothing appended: use 'ignorecase' if not in Vim script
2769 	else
2770 	    ic = vim9script ? FALSE : p_ic;
2771 
2772 	/*
2773 	 * Get the second variable.
2774 	 */
2775 	if (evaluate && vim9script && !IS_WHITE_OR_NUL(p[len]))
2776 	{
2777 	    error_white_both(p, len);
2778 	    clear_tv(rettv);
2779 	    return FAIL;
2780 	}
2781 	*arg = skipwhite_and_linebreak(p + len, evalarg);
2782 	if (eval5(arg, &var2, evalarg) == FAIL)
2783 	{
2784 	    clear_tv(rettv);
2785 	    return FAIL;
2786 	}
2787 	if (evaluate)
2788 	{
2789 	    int ret;
2790 
2791 	    if (vim9script && check_compare_types(type, rettv, &var2) == FAIL)
2792 	    {
2793 		ret = FAIL;
2794 		clear_tv(rettv);
2795 	    }
2796 	    else
2797 		ret = typval_compare(rettv, &var2, type, ic);
2798 	    clear_tv(&var2);
2799 	    return ret;
2800 	}
2801     }
2802 
2803     return OK;
2804 }
2805 
2806 /*
2807  * Make a copy of blob "tv1" and append blob "tv2".
2808  */
2809     void
2810 eval_addblob(typval_T *tv1, typval_T *tv2)
2811 {
2812     blob_T  *b1 = tv1->vval.v_blob;
2813     blob_T  *b2 = tv2->vval.v_blob;
2814     blob_T  *b = blob_alloc();
2815     int	    i;
2816 
2817     if (b != NULL)
2818     {
2819 	for (i = 0; i < blob_len(b1); i++)
2820 	    ga_append(&b->bv_ga, blob_get(b1, i));
2821 	for (i = 0; i < blob_len(b2); i++)
2822 	    ga_append(&b->bv_ga, blob_get(b2, i));
2823 
2824 	clear_tv(tv1);
2825 	rettv_blob_set(tv1, b);
2826     }
2827 }
2828 
2829 /*
2830  * Make a copy of list "tv1" and append list "tv2".
2831  */
2832     int
2833 eval_addlist(typval_T *tv1, typval_T *tv2)
2834 {
2835     typval_T var3;
2836 
2837     // concatenate Lists
2838     if (list_concat(tv1->vval.v_list, tv2->vval.v_list, &var3) == FAIL)
2839     {
2840 	clear_tv(tv1);
2841 	clear_tv(tv2);
2842 	return FAIL;
2843     }
2844     clear_tv(tv1);
2845     *tv1 = var3;
2846     return OK;
2847 }
2848 
2849 /*
2850  * Handle fourth level expression:
2851  *	+	number addition
2852  *	-	number subtraction
2853  *	.	string concatenation (if script version is 1)
2854  *	..	string concatenation
2855  *
2856  * "arg" must point to the first non-white of the expression.
2857  * "arg" is advanced to just after the recognized expression.
2858  *
2859  * Return OK or FAIL.
2860  */
2861     static int
2862 eval5(char_u **arg, typval_T *rettv, evalarg_T *evalarg)
2863 {
2864     /*
2865      * Get the first variable.
2866      */
2867     if (eval6(arg, rettv, evalarg, FALSE) == FAIL)
2868 	return FAIL;
2869 
2870     /*
2871      * Repeat computing, until no '+', '-' or '.' is following.
2872      */
2873     for (;;)
2874     {
2875 	int	    evaluate;
2876 	int	    getnext;
2877 	char_u	    *p;
2878 	int	    op;
2879 	int	    oplen;
2880 	int	    concat;
2881 	typval_T    var2;
2882 	int	    vim9script = in_vim9script();
2883 
2884 	// "." is only string concatenation when scriptversion is 1
2885 	// "+=", "-=" and "..=" are assignments
2886 	p = eval_next_non_blank(*arg, evalarg, &getnext);
2887 	op = *p;
2888 	concat = op == '.' && (*(p + 1) == '.' || current_sctx.sc_version < 2);
2889 	if ((op != '+' && op != '-' && !concat) || p[1] == '='
2890 					       || (p[1] == '.' && p[2] == '='))
2891 	    break;
2892 
2893 	evaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
2894 	oplen = (concat && p[1] == '.') ? 2 : 1;
2895 	if (getnext)
2896 	    *arg = eval_next_line(evalarg);
2897 	else
2898 	{
2899 	    if (evaluate && vim9script && !VIM_ISWHITE(**arg))
2900 	    {
2901 		error_white_both(p, oplen);
2902 		clear_tv(rettv);
2903 		return FAIL;
2904 	    }
2905 	    *arg = p;
2906 	}
2907 	if ((op != '+' || (rettv->v_type != VAR_LIST
2908 						 && rettv->v_type != VAR_BLOB))
2909 #ifdef FEAT_FLOAT
2910 		&& (op == '.' || rettv->v_type != VAR_FLOAT)
2911 #endif
2912 		&& evaluate)
2913 	{
2914 	    int		error = FALSE;
2915 
2916 	    // For "list + ...", an illegal use of the first operand as
2917 	    // a number cannot be determined before evaluating the 2nd
2918 	    // operand: if this is also a list, all is ok.
2919 	    // For "something . ...", "something - ..." or "non-list + ...",
2920 	    // we know that the first operand needs to be a string or number
2921 	    // without evaluating the 2nd operand.  So check before to avoid
2922 	    // side effects after an error.
2923 	    if (op != '.')
2924 		tv_get_number_chk(rettv, &error);
2925 	    if ((op == '.' && tv_get_string_chk(rettv) == NULL) || error)
2926 	    {
2927 		clear_tv(rettv);
2928 		return FAIL;
2929 	    }
2930 	}
2931 
2932 	/*
2933 	 * Get the second variable.
2934 	 */
2935 	if (evaluate && vim9script && !IS_WHITE_OR_NUL((*arg)[oplen]))
2936 	{
2937 	    error_white_both(p, oplen);
2938 	    clear_tv(rettv);
2939 	    return FAIL;
2940 	}
2941 	*arg = skipwhite_and_linebreak(*arg + oplen, evalarg);
2942 	if (eval6(arg, &var2, evalarg, !vim9script && op == '.') == FAIL)
2943 	{
2944 	    clear_tv(rettv);
2945 	    return FAIL;
2946 	}
2947 
2948 	if (evaluate)
2949 	{
2950 	    /*
2951 	     * Compute the result.
2952 	     */
2953 	    if (op == '.')
2954 	    {
2955 		char_u	buf1[NUMBUFLEN], buf2[NUMBUFLEN];
2956 		char_u	*s1 = tv_get_string_buf(rettv, buf1);
2957 		char_u	*s2 = NULL;
2958 
2959 		if (vim9script && (var2.v_type == VAR_VOID
2960 			|| var2.v_type == VAR_CHANNEL
2961 			|| var2.v_type == VAR_JOB))
2962 		    emsg(_(e_inval_string));
2963 #ifdef FEAT_FLOAT
2964 		else if (vim9script && var2.v_type == VAR_FLOAT)
2965 		{
2966 		    vim_snprintf((char *)buf2, NUMBUFLEN, "%g",
2967 							    var2.vval.v_float);
2968 		    s2 = buf2;
2969 		}
2970 #endif
2971 		else
2972 		    s2 = tv_get_string_buf_chk(&var2, buf2);
2973 		if (s2 == NULL)		// type error ?
2974 		{
2975 		    clear_tv(rettv);
2976 		    clear_tv(&var2);
2977 		    return FAIL;
2978 		}
2979 		p = concat_str(s1, s2);
2980 		clear_tv(rettv);
2981 		rettv->v_type = VAR_STRING;
2982 		rettv->vval.v_string = p;
2983 	    }
2984 	    else if (op == '+' && rettv->v_type == VAR_BLOB
2985 						   && var2.v_type == VAR_BLOB)
2986 		eval_addblob(rettv, &var2);
2987 	    else if (op == '+' && rettv->v_type == VAR_LIST
2988 						   && var2.v_type == VAR_LIST)
2989 	    {
2990 		if (eval_addlist(rettv, &var2) == FAIL)
2991 		    return FAIL;
2992 	    }
2993 	    else
2994 	    {
2995 		int		error = FALSE;
2996 		varnumber_T	n1, n2;
2997 #ifdef FEAT_FLOAT
2998 		float_T	    f1 = 0, f2 = 0;
2999 
3000 		if (rettv->v_type == VAR_FLOAT)
3001 		{
3002 		    f1 = rettv->vval.v_float;
3003 		    n1 = 0;
3004 		}
3005 		else
3006 #endif
3007 		{
3008 		    n1 = tv_get_number_chk(rettv, &error);
3009 		    if (error)
3010 		    {
3011 			// This can only happen for "list + non-list" or
3012 			// "blob + non-blob".  For "non-list + ..." or
3013 			// "something - ...", we returned before evaluating the
3014 			// 2nd operand.
3015 			clear_tv(rettv);
3016 			clear_tv(&var2);
3017 			return FAIL;
3018 		    }
3019 #ifdef FEAT_FLOAT
3020 		    if (var2.v_type == VAR_FLOAT)
3021 			f1 = n1;
3022 #endif
3023 		}
3024 #ifdef FEAT_FLOAT
3025 		if (var2.v_type == VAR_FLOAT)
3026 		{
3027 		    f2 = var2.vval.v_float;
3028 		    n2 = 0;
3029 		}
3030 		else
3031 #endif
3032 		{
3033 		    n2 = tv_get_number_chk(&var2, &error);
3034 		    if (error)
3035 		    {
3036 			clear_tv(rettv);
3037 			clear_tv(&var2);
3038 			return FAIL;
3039 		    }
3040 #ifdef FEAT_FLOAT
3041 		    if (rettv->v_type == VAR_FLOAT)
3042 			f2 = n2;
3043 #endif
3044 		}
3045 		clear_tv(rettv);
3046 
3047 #ifdef FEAT_FLOAT
3048 		// If there is a float on either side the result is a float.
3049 		if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
3050 		{
3051 		    if (op == '+')
3052 			f1 = f1 + f2;
3053 		    else
3054 			f1 = f1 - f2;
3055 		    rettv->v_type = VAR_FLOAT;
3056 		    rettv->vval.v_float = f1;
3057 		}
3058 		else
3059 #endif
3060 		{
3061 		    if (op == '+')
3062 			n1 = n1 + n2;
3063 		    else
3064 			n1 = n1 - n2;
3065 		    rettv->v_type = VAR_NUMBER;
3066 		    rettv->vval.v_number = n1;
3067 		}
3068 	    }
3069 	    clear_tv(&var2);
3070 	}
3071     }
3072     return OK;
3073 }
3074 
3075 /*
3076  * Handle fifth level expression:
3077  *	*	number multiplication
3078  *	/	number division
3079  *	%	number modulo
3080  *
3081  * "arg" must point to the first non-white of the expression.
3082  * "arg" is advanced to just after the recognized expression.
3083  *
3084  * Return OK or FAIL.
3085  */
3086     static int
3087 eval6(
3088     char_u	**arg,
3089     typval_T	*rettv,
3090     evalarg_T	*evalarg,
3091     int		want_string)  // after "." operator
3092 {
3093 #ifdef FEAT_FLOAT
3094     int	    use_float = FALSE;
3095 #endif
3096 
3097     /*
3098      * Get the first variable.
3099      */
3100     if (eval7(arg, rettv, evalarg, want_string) == FAIL)
3101 	return FAIL;
3102 
3103     /*
3104      * Repeat computing, until no '*', '/' or '%' is following.
3105      */
3106     for (;;)
3107     {
3108 	int	    evaluate;
3109 	int	    getnext;
3110 	typval_T    var2;
3111 	char_u	    *p;
3112 	int	    op;
3113 	varnumber_T n1, n2;
3114 #ifdef FEAT_FLOAT
3115 	float_T	    f1, f2;
3116 #endif
3117 	int	    error;
3118 
3119 	// "*=", "/=" and "%=" are assignments
3120 	p = eval_next_non_blank(*arg, evalarg, &getnext);
3121 	op = *p;
3122 	if ((op != '*' && op != '/' && op != '%') || p[1] == '=')
3123 	    break;
3124 
3125 	evaluate = evalarg == NULL ? 0 : (evalarg->eval_flags & EVAL_EVALUATE);
3126 	if (getnext)
3127 	    *arg = eval_next_line(evalarg);
3128 	else
3129 	{
3130 	    if (evaluate && in_vim9script() && !VIM_ISWHITE(**arg))
3131 	    {
3132 		error_white_both(p, 1);
3133 		clear_tv(rettv);
3134 		return FAIL;
3135 	    }
3136 	    *arg = p;
3137 	}
3138 
3139 #ifdef FEAT_FLOAT
3140 	f1 = 0;
3141 	f2 = 0;
3142 #endif
3143 	error = FALSE;
3144 	if (evaluate)
3145 	{
3146 #ifdef FEAT_FLOAT
3147 	    if (rettv->v_type == VAR_FLOAT)
3148 	    {
3149 		f1 = rettv->vval.v_float;
3150 		use_float = TRUE;
3151 		n1 = 0;
3152 	    }
3153 	    else
3154 #endif
3155 		n1 = tv_get_number_chk(rettv, &error);
3156 	    clear_tv(rettv);
3157 	    if (error)
3158 		return FAIL;
3159 	}
3160 	else
3161 	    n1 = 0;
3162 
3163 	/*
3164 	 * Get the second variable.
3165 	 */
3166 	if (evaluate && in_vim9script() && !IS_WHITE_OR_NUL((*arg)[1]))
3167 	{
3168 	    error_white_both(*arg, 1);
3169 	    clear_tv(rettv);
3170 	    return FAIL;
3171 	}
3172 	*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
3173 	if (eval7(arg, &var2, evalarg, FALSE) == FAIL)
3174 	    return FAIL;
3175 
3176 	if (evaluate)
3177 	{
3178 #ifdef FEAT_FLOAT
3179 	    if (var2.v_type == VAR_FLOAT)
3180 	    {
3181 		if (!use_float)
3182 		{
3183 		    f1 = n1;
3184 		    use_float = TRUE;
3185 		}
3186 		f2 = var2.vval.v_float;
3187 		n2 = 0;
3188 	    }
3189 	    else
3190 #endif
3191 	    {
3192 		n2 = tv_get_number_chk(&var2, &error);
3193 		clear_tv(&var2);
3194 		if (error)
3195 		    return FAIL;
3196 #ifdef FEAT_FLOAT
3197 		if (use_float)
3198 		    f2 = n2;
3199 #endif
3200 	    }
3201 
3202 	    /*
3203 	     * Compute the result.
3204 	     * When either side is a float the result is a float.
3205 	     */
3206 #ifdef FEAT_FLOAT
3207 	    if (use_float)
3208 	    {
3209 		if (op == '*')
3210 		    f1 = f1 * f2;
3211 		else if (op == '/')
3212 		{
3213 # ifdef VMS
3214 		    // VMS crashes on divide by zero, work around it
3215 		    if (f2 == 0.0)
3216 		    {
3217 			if (f1 == 0)
3218 			    f1 = -1 * __F_FLT_MAX - 1L;   // similar to NaN
3219 			else if (f1 < 0)
3220 			    f1 = -1 * __F_FLT_MAX;
3221 			else
3222 			    f1 = __F_FLT_MAX;
3223 		    }
3224 		    else
3225 			f1 = f1 / f2;
3226 # else
3227 		    // We rely on the floating point library to handle divide
3228 		    // by zero to result in "inf" and not a crash.
3229 		    f1 = f1 / f2;
3230 # endif
3231 		}
3232 		else
3233 		{
3234 		    emsg(_(e_modulus));
3235 		    return FAIL;
3236 		}
3237 		rettv->v_type = VAR_FLOAT;
3238 		rettv->vval.v_float = f1;
3239 	    }
3240 	    else
3241 #endif
3242 	    {
3243 		int	    failed = FALSE;
3244 
3245 		if (op == '*')
3246 		    n1 = n1 * n2;
3247 		else if (op == '/')
3248 		    n1 = num_divide(n1, n2, &failed);
3249 		else
3250 		    n1 = num_modulus(n1, n2, &failed);
3251 		if (failed)
3252 		    return FAIL;
3253 
3254 		rettv->v_type = VAR_NUMBER;
3255 		rettv->vval.v_number = n1;
3256 	    }
3257 	}
3258     }
3259 
3260     return OK;
3261 }
3262 
3263     int
3264 eval_leader(char_u **arg, int vim9)
3265 {
3266     char_u	*s = *arg;
3267     char_u	*p = *arg;
3268 
3269     while (*p == '!' || *p == '-' || *p == '+')
3270     {
3271 	char_u *n = skipwhite(p + 1);
3272 
3273 	// ++, --, -+ and +- are not accepted in Vim9 script
3274 	if (vim9 && (*p == '-' || *p == '+') && (*n == '-' || *n == '+'))
3275 	{
3276 	    semsg(_(e_invexpr2), s);
3277 	    return FAIL;
3278 	}
3279 	p = n;
3280     }
3281     *arg = p;
3282     return OK;
3283 }
3284 
3285 /*
3286  * Handle sixth level expression:
3287  *  number		number constant
3288  *  0zFFFFFFFF		Blob constant
3289  *  "string"		string constant
3290  *  'string'		literal string constant
3291  *  &option-name	option value
3292  *  @r			register contents
3293  *  identifier		variable value
3294  *  function()		function call
3295  *  $VAR		environment variable
3296  *  (expression)	nested expression
3297  *  [expr, expr]	List
3298  *  {arg, arg -> expr}	Lambda
3299  *  {key: val, key: val}   Dictionary
3300  *  #{key: val, key: val}  Dictionary with literal keys
3301  *
3302  *  Also handle:
3303  *  ! in front		logical NOT
3304  *  - in front		unary minus
3305  *  + in front		unary plus (ignored)
3306  *  trailing []		subscript in String or List
3307  *  trailing .name	entry in Dictionary
3308  *  trailing ->name()	method call
3309  *
3310  * "arg" must point to the first non-white of the expression.
3311  * "arg" is advanced to just after the recognized expression.
3312  *
3313  * Return OK or FAIL.
3314  */
3315     static int
3316 eval7(
3317     char_u	**arg,
3318     typval_T	*rettv,
3319     evalarg_T	*evalarg,
3320     int		want_string)	// after "." operator
3321 {
3322     int		evaluate = evalarg != NULL
3323 				      && (evalarg->eval_flags & EVAL_EVALUATE);
3324     int		len;
3325     char_u	*s;
3326     char_u	*start_leader, *end_leader;
3327     int		ret = OK;
3328     char_u	*alias;
3329 
3330     /*
3331      * Initialise variable so that clear_tv() can't mistake this for a
3332      * string and free a string that isn't there.
3333      */
3334     rettv->v_type = VAR_UNKNOWN;
3335 
3336     /*
3337      * Skip '!', '-' and '+' characters.  They are handled later.
3338      */
3339     start_leader = *arg;
3340     if (eval_leader(arg, in_vim9script()) == FAIL)
3341 	return FAIL;
3342     end_leader = *arg;
3343 
3344     if (**arg == '.' && (!isdigit(*(*arg + 1))
3345 #ifdef FEAT_FLOAT
3346 	    || current_sctx.sc_version < 2
3347 #endif
3348 	    ))
3349     {
3350 	semsg(_(e_invexpr2), *arg);
3351 	++*arg;
3352 	return FAIL;
3353     }
3354 
3355     switch (**arg)
3356     {
3357     /*
3358      * Number constant.
3359      */
3360     case '0':
3361     case '1':
3362     case '2':
3363     case '3':
3364     case '4':
3365     case '5':
3366     case '6':
3367     case '7':
3368     case '8':
3369     case '9':
3370     case '.':	ret = eval_number(arg, rettv, evaluate, want_string);
3371 
3372 		// Apply prefixed "-" and "+" now.  Matters especially when
3373 		// "->" follows.
3374 		if (ret == OK && evaluate && end_leader > start_leader
3375 						  && rettv->v_type != VAR_BLOB)
3376 		    ret = eval7_leader(rettv, TRUE, start_leader, &end_leader);
3377 		break;
3378 
3379     /*
3380      * String constant: "string".
3381      */
3382     case '"':	ret = eval_string(arg, rettv, evaluate);
3383 		break;
3384 
3385     /*
3386      * Literal string constant: 'str''ing'.
3387      */
3388     case '\'':	ret = eval_lit_string(arg, rettv, evaluate);
3389 		break;
3390 
3391     /*
3392      * List: [expr, expr]
3393      */
3394     case '[':	ret = eval_list(arg, rettv, evalarg, TRUE);
3395 		break;
3396 
3397     /*
3398      * Dictionary: #{key: val, key: val}
3399      */
3400     case '#':	if (in_vim9script())
3401 		{
3402 		    ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;
3403 		}
3404 		else if ((*arg)[1] == '{')
3405 		{
3406 		    ++*arg;
3407 		    ret = eval_dict(arg, rettv, evalarg, TRUE);
3408 		}
3409 		else
3410 		    ret = NOTDONE;
3411 		break;
3412 
3413     /*
3414      * Lambda: {arg, arg -> expr}
3415      * Dictionary: {'key': val, 'key': val}
3416      */
3417     case '{':	if (in_vim9script())
3418 		    ret = NOTDONE;
3419 		else
3420 		    ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg);
3421 		if (ret == NOTDONE)
3422 		    ret = eval_dict(arg, rettv, evalarg, FALSE);
3423 		break;
3424 
3425     /*
3426      * Option value: &name
3427      */
3428     case '&':	ret = eval_option(arg, rettv, evaluate);
3429 		break;
3430 
3431     /*
3432      * Environment variable: $VAR.
3433      */
3434     case '$':	ret = eval_env_var(arg, rettv, evaluate);
3435 		break;
3436 
3437     /*
3438      * Register contents: @r.
3439      */
3440     case '@':	++*arg;
3441 		if (evaluate)
3442 		{
3443 		    if (in_vim9script() && IS_WHITE_OR_NUL(**arg))
3444 			semsg(_(e_syntax_error_at_str), *arg);
3445 		    else if (in_vim9script() && !valid_yank_reg(**arg, FALSE))
3446 			emsg_invreg(**arg);
3447 		    else
3448 		    {
3449 			rettv->v_type = VAR_STRING;
3450 			rettv->vval.v_string = get_reg_contents(**arg,
3451 								GREG_EXPR_SRC);
3452 		    }
3453 		}
3454 		if (**arg != NUL)
3455 		    ++*arg;
3456 		break;
3457 
3458     /*
3459      * nested expression: (expression).
3460      * lambda: (arg) => expr
3461      */
3462     case '(':	ret = NOTDONE;
3463 		if (in_vim9script())
3464 		{
3465 		    ret = get_lambda_tv(arg, rettv, TRUE, evalarg);
3466 		    if (ret == OK && evaluate)
3467 		    {
3468 			ufunc_T *ufunc = rettv->vval.v_partial->pt_func;
3469 
3470 			// compile it here to get the return type
3471 			if (compile_def_function(ufunc,
3472 					 TRUE, PROFILING(ufunc), NULL) == FAIL)
3473 			{
3474 			    clear_tv(rettv);
3475 			    ret = FAIL;
3476 			}
3477 		    }
3478 		}
3479 		if (ret == NOTDONE)
3480 		{
3481 		    *arg = skipwhite_and_linebreak(*arg + 1, evalarg);
3482 		    ret = eval1(arg, rettv, evalarg);	// recursive!
3483 
3484 		    *arg = skipwhite_and_linebreak(*arg, evalarg);
3485 		    if (**arg == ')')
3486 			++*arg;
3487 		    else if (ret == OK)
3488 		    {
3489 			emsg(_(e_missing_close));
3490 			clear_tv(rettv);
3491 			ret = FAIL;
3492 		    }
3493 		}
3494 		break;
3495 
3496     default:	ret = NOTDONE;
3497 		break;
3498     }
3499 
3500     if (ret == NOTDONE)
3501     {
3502 	/*
3503 	 * Must be a variable or function name.
3504 	 * Can also be a curly-braces kind of name: {expr}.
3505 	 */
3506 	s = *arg;
3507 	len = get_name_len(arg, &alias, evaluate, TRUE);
3508 	if (alias != NULL)
3509 	    s = alias;
3510 
3511 	if (len <= 0)
3512 	    ret = FAIL;
3513 	else
3514 	{
3515 	    int	    flags = evalarg == NULL ? 0 : evalarg->eval_flags;
3516 
3517 	    if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(')
3518 	    {
3519 		// "name(..."  recursive!
3520 		*arg = skipwhite(*arg);
3521 		ret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);
3522 	    }
3523 	    else if (flags & EVAL_CONSTANT)
3524 		ret = FAIL;
3525 	    else if (evaluate)
3526 	    {
3527 		// get the value of "true", "false" or a variable
3528 		if (len == 4 && in_vim9script() && STRNCMP(s, "true", 4) == 0)
3529 		{
3530 		    rettv->v_type = VAR_BOOL;
3531 		    rettv->vval.v_number = VVAL_TRUE;
3532 		    ret = OK;
3533 		}
3534 		else if (len == 5 && in_vim9script()
3535 						&& STRNCMP(s, "false", 5) == 0)
3536 		{
3537 		    rettv->v_type = VAR_BOOL;
3538 		    rettv->vval.v_number = VVAL_FALSE;
3539 		    ret = OK;
3540 		}
3541 		else if (len == 4 && in_vim9script()
3542 						&& STRNCMP(s, "null", 4) == 0)
3543 		{
3544 		    rettv->v_type = VAR_SPECIAL;
3545 		    rettv->vval.v_number = VVAL_NULL;
3546 		    ret = OK;
3547 		}
3548 		else
3549 		    ret = eval_variable(s, len, rettv, NULL,
3550 					   EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);
3551 	    }
3552 	    else
3553 	    {
3554 		// skip the name
3555 		check_vars(s, len);
3556 		ret = OK;
3557 	    }
3558 	}
3559 	vim_free(alias);
3560     }
3561 
3562     // Handle following '[', '(' and '.' for expr[expr], expr.name,
3563     // expr(expr), expr->name(expr)
3564     if (ret == OK)
3565 	ret = handle_subscript(arg, rettv, evalarg, TRUE);
3566 
3567     /*
3568      * Apply logical NOT and unary '-', from right to left, ignore '+'.
3569      */
3570     if (ret == OK && evaluate && end_leader > start_leader)
3571 	ret = eval7_leader(rettv, FALSE, start_leader, &end_leader);
3572     return ret;
3573 }
3574 
3575 /*
3576  * Apply the leading "!" and "-" before an eval7 expression to "rettv".
3577  * When "numeric_only" is TRUE only handle "+" and "-".
3578  * Adjusts "end_leaderp" until it is at "start_leader".
3579  */
3580     static int
3581 eval7_leader(
3582 	typval_T    *rettv,
3583 	int	    numeric_only,
3584 	char_u	    *start_leader,
3585 	char_u	    **end_leaderp)
3586 {
3587     char_u	*end_leader = *end_leaderp;
3588     int		ret = OK;
3589     int		error = FALSE;
3590     varnumber_T val = 0;
3591     vartype_T	type = rettv->v_type;
3592 #ifdef FEAT_FLOAT
3593     float_T	    f = 0.0;
3594 
3595     if (rettv->v_type == VAR_FLOAT)
3596 	f = rettv->vval.v_float;
3597     else
3598 #endif
3599     {
3600 	while (VIM_ISWHITE(end_leader[-1]))
3601 	    --end_leader;
3602 	if (in_vim9script() && end_leader[-1] == '!')
3603 	    val = tv2bool(rettv);
3604 	else
3605 	    val = tv_get_number_chk(rettv, &error);
3606     }
3607     if (error)
3608     {
3609 	clear_tv(rettv);
3610 	ret = FAIL;
3611     }
3612     else
3613     {
3614 	while (end_leader > start_leader)
3615 	{
3616 	    --end_leader;
3617 	    if (*end_leader == '!')
3618 	    {
3619 		if (numeric_only)
3620 		{
3621 		    ++end_leader;
3622 		    break;
3623 		}
3624 #ifdef FEAT_FLOAT
3625 		if (rettv->v_type == VAR_FLOAT)
3626 		{
3627 		    if (in_vim9script())
3628 		    {
3629 			rettv->v_type = VAR_BOOL;
3630 			val = f == 0.0 ? VVAL_TRUE : VVAL_FALSE;
3631 		    }
3632 		    else
3633 			f = !f;
3634 		}
3635 		else
3636 #endif
3637 		{
3638 		    val = !val;
3639 		    type = VAR_BOOL;
3640 		}
3641 	    }
3642 	    else if (*end_leader == '-')
3643 	    {
3644 #ifdef FEAT_FLOAT
3645 		if (rettv->v_type == VAR_FLOAT)
3646 		    f = -f;
3647 		else
3648 #endif
3649 		{
3650 		    val = -val;
3651 		    type = VAR_NUMBER;
3652 		}
3653 	    }
3654 	}
3655 #ifdef FEAT_FLOAT
3656 	if (rettv->v_type == VAR_FLOAT)
3657 	{
3658 	    clear_tv(rettv);
3659 	    rettv->vval.v_float = f;
3660 	}
3661 	else
3662 #endif
3663 	{
3664 	    clear_tv(rettv);
3665 	    if (in_vim9script())
3666 		rettv->v_type = type;
3667 	    else
3668 		rettv->v_type = VAR_NUMBER;
3669 	    rettv->vval.v_number = val;
3670 	}
3671     }
3672     *end_leaderp = end_leader;
3673     return ret;
3674 }
3675 
3676 /*
3677  * Call the function referred to in "rettv".
3678  */
3679     static int
3680 call_func_rettv(
3681 	char_u	    **arg,
3682 	evalarg_T   *evalarg,
3683 	typval_T    *rettv,
3684 	int	    evaluate,
3685 	dict_T	    *selfdict,
3686 	typval_T    *basetv)
3687 {
3688     partial_T	*pt = NULL;
3689     funcexe_T	funcexe;
3690     typval_T	functv;
3691     char_u	*s;
3692     int		ret;
3693 
3694     // need to copy the funcref so that we can clear rettv
3695     if (evaluate)
3696     {
3697 	functv = *rettv;
3698 	rettv->v_type = VAR_UNKNOWN;
3699 
3700 	// Invoke the function.  Recursive!
3701 	if (functv.v_type == VAR_PARTIAL)
3702 	{
3703 	    pt = functv.vval.v_partial;
3704 	    s = partial_name(pt);
3705 	}
3706 	else
3707 	    s = functv.vval.v_string;
3708     }
3709     else
3710 	s = (char_u *)"";
3711 
3712     CLEAR_FIELD(funcexe);
3713     funcexe.firstline = curwin->w_cursor.lnum;
3714     funcexe.lastline = curwin->w_cursor.lnum;
3715     funcexe.evaluate = evaluate;
3716     funcexe.partial = pt;
3717     funcexe.selfdict = selfdict;
3718     funcexe.basetv = basetv;
3719     ret = get_func_tv(s, -1, rettv, arg, evalarg, &funcexe);
3720 
3721     // Clear the funcref afterwards, so that deleting it while
3722     // evaluating the arguments is possible (see test55).
3723     if (evaluate)
3724 	clear_tv(&functv);
3725 
3726     return ret;
3727 }
3728 
3729 /*
3730  * Evaluate "->method()".
3731  * "*arg" points to "method".
3732  * Returns FAIL or OK. "*arg" is advanced to after the ')'.
3733  */
3734     static int
3735 eval_lambda(
3736     char_u	**arg,
3737     typval_T	*rettv,
3738     evalarg_T	*evalarg,
3739     int		verbose)	// give error messages
3740 {
3741     int		evaluate = evalarg != NULL
3742 				      && (evalarg->eval_flags & EVAL_EVALUATE);
3743     typval_T	base = *rettv;
3744     int		ret;
3745 
3746     rettv->v_type = VAR_UNKNOWN;
3747 
3748     if (**arg == '{')
3749     {
3750 	// ->{lambda}()
3751 	ret = get_lambda_tv(arg, rettv, FALSE, evalarg);
3752     }
3753     else
3754     {
3755 	// ->(lambda)()
3756 	++*arg;
3757 	ret = eval1(arg, rettv, evalarg);
3758 	*arg = skipwhite_and_linebreak(*arg, evalarg);
3759 	if (**arg != ')')
3760 	{
3761 	    emsg(_(e_missing_close));
3762 	    ret = FAIL;
3763 	}
3764 	++*arg;
3765     }
3766     if (ret != OK)
3767 	return FAIL;
3768     else if (**arg != '(')
3769     {
3770 	if (verbose)
3771 	{
3772 	    if (*skipwhite(*arg) == '(')
3773 		emsg(_(e_nowhitespace));
3774 	    else
3775 		semsg(_(e_missing_paren), "lambda");
3776 	}
3777 	clear_tv(rettv);
3778 	ret = FAIL;
3779     }
3780     else
3781 	ret = call_func_rettv(arg, evalarg, rettv, evaluate, NULL, &base);
3782 
3783     // Clear the funcref afterwards, so that deleting it while
3784     // evaluating the arguments is possible (see test55).
3785     if (evaluate)
3786 	clear_tv(&base);
3787 
3788     return ret;
3789 }
3790 
3791 /*
3792  * Evaluate "->method()".
3793  * "*arg" points to "method".
3794  * Returns FAIL or OK. "*arg" is advanced to after the ')'.
3795  */
3796     static int
3797 eval_method(
3798     char_u	**arg,
3799     typval_T	*rettv,
3800     evalarg_T	*evalarg,
3801     int		verbose)	// give error messages
3802 {
3803     char_u	*name;
3804     long	len;
3805     char_u	*alias;
3806     typval_T	base = *rettv;
3807     int		ret;
3808     int		evaluate = evalarg != NULL
3809 				      && (evalarg->eval_flags & EVAL_EVALUATE);
3810 
3811     rettv->v_type = VAR_UNKNOWN;
3812 
3813     name = *arg;
3814     len = get_name_len(arg, &alias, evaluate, TRUE);
3815     if (alias != NULL)
3816 	name = alias;
3817 
3818     if (len <= 0)
3819     {
3820 	if (verbose)
3821 	    emsg(_("E260: Missing name after ->"));
3822 	ret = FAIL;
3823     }
3824     else
3825     {
3826 	*arg = skipwhite(*arg);
3827 	if (**arg != '(')
3828 	{
3829 	    if (verbose)
3830 		semsg(_(e_missing_paren), name);
3831 	    ret = FAIL;
3832 	}
3833 	else if (VIM_ISWHITE((*arg)[-1]))
3834 	{
3835 	    if (verbose)
3836 		emsg(_(e_nowhitespace));
3837 	    ret = FAIL;
3838 	}
3839 	else
3840 	    ret = eval_func(arg, evalarg, name, len, rettv,
3841 					  evaluate ? EVAL_EVALUATE : 0, &base);
3842     }
3843 
3844     // Clear the funcref afterwards, so that deleting it while
3845     // evaluating the arguments is possible (see test55).
3846     if (evaluate)
3847 	clear_tv(&base);
3848 
3849     return ret;
3850 }
3851 
3852 /*
3853  * Evaluate an "[expr]" or "[expr:expr]" index.  Also "dict.key".
3854  * "*arg" points to the '[' or '.'.
3855  * Returns FAIL or OK. "*arg" is advanced to after the ']'.
3856  */
3857     static int
3858 eval_index(
3859     char_u	**arg,
3860     typval_T	*rettv,
3861     evalarg_T	*evalarg,
3862     int		verbose)	// give error messages
3863 {
3864     int		evaluate = evalarg != NULL
3865 				      && (evalarg->eval_flags & EVAL_EVALUATE);
3866     int		empty1 = FALSE, empty2 = FALSE;
3867     typval_T	var1, var2;
3868     int		range = FALSE;
3869     char_u	*key = NULL;
3870     int		keylen = -1;
3871     int		vim9 = in_vim9script();
3872 
3873     if (check_can_index(rettv, evaluate, verbose) == FAIL)
3874 	return FAIL;
3875 
3876     init_tv(&var1);
3877     init_tv(&var2);
3878     if (**arg == '.')
3879     {
3880 	/*
3881 	 * dict.name
3882 	 */
3883 	key = *arg + 1;
3884 	for (keylen = 0; eval_isdictc(key[keylen]); ++keylen)
3885 	    ;
3886 	if (keylen == 0)
3887 	    return FAIL;
3888 	*arg = key + keylen;
3889     }
3890     else
3891     {
3892 	/*
3893 	 * something[idx]
3894 	 *
3895 	 * Get the (first) variable from inside the [].
3896 	 */
3897 	*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
3898 	if (**arg == ':')
3899 	    empty1 = TRUE;
3900 	else if (eval1(arg, &var1, evalarg) == FAIL)	// recursive!
3901 	    return FAIL;
3902 	else if (vim9 && **arg == ':')
3903 	{
3904 	    semsg(_(e_white_space_required_before_and_after_str_at_str),
3905 								    ":", *arg);
3906 	    clear_tv(&var1);
3907 	    return FAIL;
3908 	}
3909 	else if (evaluate)
3910 	{
3911 #ifdef FEAT_FLOAT
3912 	    // allow for indexing with float
3913 	    if (vim9 && rettv->v_type == VAR_DICT
3914 						   && var1.v_type == VAR_FLOAT)
3915 	    {
3916 		var1.vval.v_string = typval_tostring(&var1, TRUE);
3917 		var1.v_type = VAR_STRING;
3918 	    }
3919 #endif
3920 	    if (tv_get_string_chk(&var1) == NULL)
3921 	    {
3922 		// not a number or string
3923 		clear_tv(&var1);
3924 		return FAIL;
3925 	    }
3926 	}
3927 
3928 	/*
3929 	 * Get the second variable from inside the [:].
3930 	 */
3931 	*arg = skipwhite_and_linebreak(*arg, evalarg);
3932 	if (**arg == ':')
3933 	{
3934 	    range = TRUE;
3935 	    ++*arg;
3936 	    if (vim9 && !IS_WHITE_OR_NUL(**arg) && **arg != ']')
3937 	    {
3938 		semsg(_(e_white_space_required_before_and_after_str_at_str),
3939 								":", *arg - 1);
3940 		if (!empty1)
3941 		    clear_tv(&var1);
3942 		return FAIL;
3943 	    }
3944 	    *arg = skipwhite_and_linebreak(*arg, evalarg);
3945 	    if (**arg == ']')
3946 		empty2 = TRUE;
3947 	    else if (eval1(arg, &var2, evalarg) == FAIL)	// recursive!
3948 	    {
3949 		if (!empty1)
3950 		    clear_tv(&var1);
3951 		return FAIL;
3952 	    }
3953 	    else if (evaluate && tv_get_string_chk(&var2) == NULL)
3954 	    {
3955 		// not a number or string
3956 		if (!empty1)
3957 		    clear_tv(&var1);
3958 		clear_tv(&var2);
3959 		return FAIL;
3960 	    }
3961 	}
3962 
3963 	// Check for the ']'.
3964 	*arg = skipwhite_and_linebreak(*arg, evalarg);
3965 	if (**arg != ']')
3966 	{
3967 	    if (verbose)
3968 		emsg(_(e_missbrac));
3969 	    clear_tv(&var1);
3970 	    if (range)
3971 		clear_tv(&var2);
3972 	    return FAIL;
3973 	}
3974 	*arg = *arg + 1;	// skip over the ']'
3975     }
3976 
3977     if (evaluate)
3978     {
3979 	int res = eval_index_inner(rettv, range,
3980 		empty1 ? NULL : &var1, empty2 ? NULL : &var2, FALSE,
3981 		key, keylen, verbose);
3982 
3983 	if (!empty1)
3984 	    clear_tv(&var1);
3985 	if (range)
3986 	    clear_tv(&var2);
3987 	return res;
3988     }
3989     return OK;
3990 }
3991 
3992 /*
3993  * Check if "rettv" can have an [index] or [sli:ce]
3994  */
3995     int
3996 check_can_index(typval_T *rettv, int evaluate, int verbose)
3997 {
3998     switch (rettv->v_type)
3999     {
4000 	case VAR_FUNC:
4001 	case VAR_PARTIAL:
4002 	    if (verbose)
4003 		emsg(_("E695: Cannot index a Funcref"));
4004 	    return FAIL;
4005 	case VAR_FLOAT:
4006 #ifdef FEAT_FLOAT
4007 	    if (verbose)
4008 		emsg(_(e_float_as_string));
4009 	    return FAIL;
4010 #endif
4011 	case VAR_BOOL:
4012 	case VAR_SPECIAL:
4013 	case VAR_JOB:
4014 	case VAR_CHANNEL:
4015 	    if (verbose)
4016 		emsg(_(e_cannot_index_special_variable));
4017 	    return FAIL;
4018 	case VAR_UNKNOWN:
4019 	case VAR_ANY:
4020 	case VAR_VOID:
4021 	    if (evaluate)
4022 	    {
4023 		emsg(_(e_cannot_index_special_variable));
4024 		return FAIL;
4025 	    }
4026 	    // FALLTHROUGH
4027 
4028 	case VAR_STRING:
4029 	case VAR_LIST:
4030 	case VAR_DICT:
4031 	case VAR_BLOB:
4032 	    break;
4033 	case VAR_NUMBER:
4034 	    if (in_vim9script())
4035 		emsg(_(e_cannot_index_number));
4036 	    break;
4037     }
4038     return OK;
4039 }
4040 
4041 /*
4042  * slice() function
4043  */
4044     void
4045 f_slice(typval_T *argvars, typval_T *rettv)
4046 {
4047     if (check_can_index(argvars, TRUE, FALSE) == OK)
4048     {
4049 	copy_tv(argvars, rettv);
4050 	eval_index_inner(rettv, TRUE, argvars + 1,
4051 		argvars[2].v_type == VAR_UNKNOWN ? NULL : argvars + 2,
4052 		TRUE, NULL, 0, FALSE);
4053     }
4054 }
4055 
4056 /*
4057  * Apply index or range to "rettv".
4058  * "var1" is the first index, NULL for [:expr].
4059  * "var2" is the second index, NULL for [expr] and [expr: ]
4060  * "exclusive" is TRUE for slice(): second index is exclusive, use character
4061  * index for string.
4062  * Alternatively, "key" is not NULL, then key[keylen] is the dict index.
4063  */
4064     int
4065 eval_index_inner(
4066 	typval_T    *rettv,
4067 	int	    is_range,
4068 	typval_T    *var1,
4069 	typval_T    *var2,
4070 	int	    exclusive,
4071 	char_u	    *key,
4072 	int	    keylen,
4073 	int	    verbose)
4074 {
4075     varnumber_T	    n1, n2 = 0;
4076     long	    len;
4077 
4078     n1 = 0;
4079     if (var1 != NULL && rettv->v_type != VAR_DICT)
4080 	n1 = tv_get_number(var1);
4081 
4082     if (is_range)
4083     {
4084 	if (rettv->v_type == VAR_DICT)
4085 	{
4086 	    if (verbose)
4087 		emsg(_(e_cannot_slice_dictionary));
4088 	    return FAIL;
4089 	}
4090 	if (var2 != NULL)
4091 	    n2 = tv_get_number(var2);
4092 	else
4093 	    n2 = VARNUM_MAX;
4094     }
4095 
4096     switch (rettv->v_type)
4097     {
4098 	case VAR_UNKNOWN:
4099 	case VAR_ANY:
4100 	case VAR_VOID:
4101 	case VAR_FUNC:
4102 	case VAR_PARTIAL:
4103 	case VAR_FLOAT:
4104 	case VAR_BOOL:
4105 	case VAR_SPECIAL:
4106 	case VAR_JOB:
4107 	case VAR_CHANNEL:
4108 	    break; // not evaluating, skipping over subscript
4109 
4110 	case VAR_NUMBER:
4111 	case VAR_STRING:
4112 	    {
4113 		char_u	*s = tv_get_string(rettv);
4114 
4115 		len = (long)STRLEN(s);
4116 		if (in_vim9script() || exclusive)
4117 		{
4118 		    if (is_range)
4119 			s = string_slice(s, n1, n2, exclusive);
4120 		    else
4121 			s = char_from_string(s, n1);
4122 		}
4123 		else if (is_range)
4124 		{
4125 		    // The resulting variable is a substring.  If the indexes
4126 		    // are out of range the result is empty.
4127 		    if (n1 < 0)
4128 		    {
4129 			n1 = len + n1;
4130 			if (n1 < 0)
4131 			    n1 = 0;
4132 		    }
4133 		    if (n2 < 0)
4134 			n2 = len + n2;
4135 		    else if (n2 >= len)
4136 			n2 = len;
4137 		    if (n1 >= len || n2 < 0 || n1 > n2)
4138 			s = NULL;
4139 		    else
4140 			s = vim_strnsave(s + n1, n2 - n1 + 1);
4141 		}
4142 		else
4143 		{
4144 		    // The resulting variable is a string of a single
4145 		    // character.  If the index is too big or negative the
4146 		    // result is empty.
4147 		    if (n1 >= len || n1 < 0)
4148 			s = NULL;
4149 		    else
4150 			s = vim_strnsave(s + n1, 1);
4151 		}
4152 		clear_tv(rettv);
4153 		rettv->v_type = VAR_STRING;
4154 		rettv->vval.v_string = s;
4155 	    }
4156 	    break;
4157 
4158 	case VAR_BLOB:
4159 	    len = blob_len(rettv->vval.v_blob);
4160 	    if (is_range)
4161 	    {
4162 		// The resulting variable is a sub-blob.  If the indexes
4163 		// are out of range the result is empty.
4164 		if (n1 < 0)
4165 		{
4166 		    n1 = len + n1;
4167 		    if (n1 < 0)
4168 			n1 = 0;
4169 		}
4170 		if (n2 < 0)
4171 		    n2 = len + n2;
4172 		else if (n2 >= len)
4173 		    n2 = len - (exclusive ? 0 : 1);
4174 		if (exclusive)
4175 		    --n2;
4176 		if (n1 >= len || n2 < 0 || n1 > n2)
4177 		{
4178 		    clear_tv(rettv);
4179 		    rettv->v_type = VAR_BLOB;
4180 		    rettv->vval.v_blob = NULL;
4181 		}
4182 		else
4183 		{
4184 		    blob_T  *blob = blob_alloc();
4185 		    long    i;
4186 
4187 		    if (blob != NULL)
4188 		    {
4189 			if (ga_grow(&blob->bv_ga, n2 - n1 + 1) == FAIL)
4190 			{
4191 			    blob_free(blob);
4192 			    return FAIL;
4193 			}
4194 			blob->bv_ga.ga_len = n2 - n1 + 1;
4195 			for (i = n1; i <= n2; i++)
4196 			    blob_set(blob, i - n1,
4197 					  blob_get(rettv->vval.v_blob, i));
4198 
4199 			clear_tv(rettv);
4200 			rettv_blob_set(rettv, blob);
4201 		    }
4202 		}
4203 	    }
4204 	    else
4205 	    {
4206 		// The resulting variable is a byte value.
4207 		// If the index is too big or negative that is an error.
4208 		if (n1 < 0)
4209 		    n1 = len + n1;
4210 		if (n1 < len && n1 >= 0)
4211 		{
4212 		    int v = blob_get(rettv->vval.v_blob, n1);
4213 
4214 		    clear_tv(rettv);
4215 		    rettv->v_type = VAR_NUMBER;
4216 		    rettv->vval.v_number = v;
4217 		}
4218 		else
4219 		    semsg(_(e_blobidx), n1);
4220 	    }
4221 	    break;
4222 
4223 	case VAR_LIST:
4224 	    if (var1 == NULL)
4225 		n1 = 0;
4226 	    if (var2 == NULL)
4227 		n2 = VARNUM_MAX;
4228 	    if (list_slice_or_index(rettv->vval.v_list,
4229 			  is_range, n1, n2, exclusive, rettv, verbose) == FAIL)
4230 		return FAIL;
4231 	    break;
4232 
4233 	case VAR_DICT:
4234 	    {
4235 		dictitem_T	*item;
4236 		typval_T	tmp;
4237 
4238 		if (key == NULL)
4239 		{
4240 		    key = tv_get_string_chk(var1);
4241 		    if (key == NULL)
4242 			return FAIL;
4243 		}
4244 
4245 		item = dict_find(rettv->vval.v_dict, key, (int)keylen);
4246 
4247 		if (item == NULL && verbose)
4248 		    semsg(_(e_dictkey), key);
4249 		if (item == NULL)
4250 		    return FAIL;
4251 
4252 		copy_tv(&item->di_tv, &tmp);
4253 		clear_tv(rettv);
4254 		*rettv = tmp;
4255 	    }
4256 	    break;
4257     }
4258     return OK;
4259 }
4260 
4261 /*
4262  * Return the function name of partial "pt".
4263  */
4264     char_u *
4265 partial_name(partial_T *pt)
4266 {
4267     if (pt->pt_name != NULL)
4268 	return pt->pt_name;
4269     if (pt->pt_func != NULL)
4270 	return pt->pt_func->uf_name;
4271     return (char_u *)"";
4272 }
4273 
4274     static void
4275 partial_free(partial_T *pt)
4276 {
4277     int i;
4278 
4279     for (i = 0; i < pt->pt_argc; ++i)
4280 	clear_tv(&pt->pt_argv[i]);
4281     vim_free(pt->pt_argv);
4282     dict_unref(pt->pt_dict);
4283     if (pt->pt_name != NULL)
4284     {
4285 	func_unref(pt->pt_name);
4286 	vim_free(pt->pt_name);
4287     }
4288     else
4289 	func_ptr_unref(pt->pt_func);
4290 
4291     // Decrease the reference count for the context of a closure.  If down
4292     // to the minimum it may be time to free it.
4293     if (pt->pt_funcstack != NULL)
4294     {
4295 	--pt->pt_funcstack->fs_refcount;
4296 	funcstack_check_refcount(pt->pt_funcstack);
4297     }
4298 
4299     vim_free(pt);
4300 }
4301 
4302 /*
4303  * Unreference a closure: decrement the reference count and free it when it
4304  * becomes zero.
4305  */
4306     void
4307 partial_unref(partial_T *pt)
4308 {
4309     if (pt != NULL)
4310     {
4311 	if (--pt->pt_refcount <= 0)
4312 	    partial_free(pt);
4313 
4314 	// If the reference count goes down to one, the funcstack may be the
4315 	// only reference and can be freed if no other partials reference it.
4316 	else if (pt->pt_refcount == 1 && pt->pt_funcstack != NULL)
4317 	    funcstack_check_refcount(pt->pt_funcstack);
4318     }
4319 }
4320 
4321 /*
4322  * Return the next (unique) copy ID.
4323  * Used for serializing nested structures.
4324  */
4325     int
4326 get_copyID(void)
4327 {
4328     current_copyID += COPYID_INC;
4329     return current_copyID;
4330 }
4331 
4332 /*
4333  * Garbage collection for lists and dictionaries.
4334  *
4335  * We use reference counts to be able to free most items right away when they
4336  * are no longer used.  But for composite items it's possible that it becomes
4337  * unused while the reference count is > 0: When there is a recursive
4338  * reference.  Example:
4339  *	:let l = [1, 2, 3]
4340  *	:let d = {9: l}
4341  *	:let l[1] = d
4342  *
4343  * Since this is quite unusual we handle this with garbage collection: every
4344  * once in a while find out which lists and dicts are not referenced from any
4345  * variable.
4346  *
4347  * Here is a good reference text about garbage collection (refers to Python
4348  * but it applies to all reference-counting mechanisms):
4349  *	http://python.ca/nas/python/gc/
4350  */
4351 
4352 /*
4353  * Do garbage collection for lists and dicts.
4354  * When "testing" is TRUE this is called from test_garbagecollect_now().
4355  * Return TRUE if some memory was freed.
4356  */
4357     int
4358 garbage_collect(int testing)
4359 {
4360     int		copyID;
4361     int		abort = FALSE;
4362     buf_T	*buf;
4363     win_T	*wp;
4364     int		did_free = FALSE;
4365     tabpage_T	*tp;
4366 
4367     if (!testing)
4368     {
4369 	// Only do this once.
4370 	want_garbage_collect = FALSE;
4371 	may_garbage_collect = FALSE;
4372 	garbage_collect_at_exit = FALSE;
4373     }
4374 
4375     // The execution stack can grow big, limit the size.
4376     if (exestack.ga_maxlen - exestack.ga_len > 500)
4377     {
4378 	size_t	new_len;
4379 	char_u	*pp;
4380 	int	n;
4381 
4382 	// Keep 150% of the current size, with a minimum of the growth size.
4383 	n = exestack.ga_len / 2;
4384 	if (n < exestack.ga_growsize)
4385 	    n = exestack.ga_growsize;
4386 
4387 	// Don't make it bigger though.
4388 	if (exestack.ga_len + n < exestack.ga_maxlen)
4389 	{
4390 	    new_len = exestack.ga_itemsize * (exestack.ga_len + n);
4391 	    pp = vim_realloc(exestack.ga_data, new_len);
4392 	    if (pp == NULL)
4393 		return FAIL;
4394 	    exestack.ga_maxlen = exestack.ga_len + n;
4395 	    exestack.ga_data = pp;
4396 	}
4397     }
4398 
4399     // We advance by two because we add one for items referenced through
4400     // previous_funccal.
4401     copyID = get_copyID();
4402 
4403     /*
4404      * 1. Go through all accessible variables and mark all lists and dicts
4405      *    with copyID.
4406      */
4407 
4408     // Don't free variables in the previous_funccal list unless they are only
4409     // referenced through previous_funccal.  This must be first, because if
4410     // the item is referenced elsewhere the funccal must not be freed.
4411     abort = abort || set_ref_in_previous_funccal(copyID);
4412 
4413     // script-local variables
4414     abort = abort || garbage_collect_scriptvars(copyID);
4415 
4416     // buffer-local variables
4417     FOR_ALL_BUFFERS(buf)
4418 	abort = abort || set_ref_in_item(&buf->b_bufvar.di_tv, copyID,
4419 								  NULL, NULL);
4420 
4421     // window-local variables
4422     FOR_ALL_TAB_WINDOWS(tp, wp)
4423 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4424 								  NULL, NULL);
4425     if (aucmd_win != NULL)
4426 	abort = abort || set_ref_in_item(&aucmd_win->w_winvar.di_tv, copyID,
4427 								  NULL, NULL);
4428 #ifdef FEAT_PROP_POPUP
4429     FOR_ALL_POPUPWINS(wp)
4430 	abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4431 								  NULL, NULL);
4432     FOR_ALL_TABPAGES(tp)
4433 	FOR_ALL_POPUPWINS_IN_TAB(tp, wp)
4434 		abort = abort || set_ref_in_item(&wp->w_winvar.di_tv, copyID,
4435 								  NULL, NULL);
4436 #endif
4437 
4438     // tabpage-local variables
4439     FOR_ALL_TABPAGES(tp)
4440 	abort = abort || set_ref_in_item(&tp->tp_winvar.di_tv, copyID,
4441 								  NULL, NULL);
4442     // global variables
4443     abort = abort || garbage_collect_globvars(copyID);
4444 
4445     // function-local variables
4446     abort = abort || set_ref_in_call_stack(copyID);
4447 
4448     // named functions (matters for closures)
4449     abort = abort || set_ref_in_functions(copyID);
4450 
4451     // function call arguments, if v:testing is set.
4452     abort = abort || set_ref_in_func_args(copyID);
4453 
4454     // v: vars
4455     abort = abort || garbage_collect_vimvars(copyID);
4456 
4457     // callbacks in buffers
4458     abort = abort || set_ref_in_buffers(copyID);
4459 
4460 #ifdef FEAT_LUA
4461     abort = abort || set_ref_in_lua(copyID);
4462 #endif
4463 
4464 #ifdef FEAT_PYTHON
4465     abort = abort || set_ref_in_python(copyID);
4466 #endif
4467 
4468 #ifdef FEAT_PYTHON3
4469     abort = abort || set_ref_in_python3(copyID);
4470 #endif
4471 
4472 #ifdef FEAT_JOB_CHANNEL
4473     abort = abort || set_ref_in_channel(copyID);
4474     abort = abort || set_ref_in_job(copyID);
4475 #endif
4476 #ifdef FEAT_NETBEANS_INTG
4477     abort = abort || set_ref_in_nb_channel(copyID);
4478 #endif
4479 
4480 #ifdef FEAT_TIMERS
4481     abort = abort || set_ref_in_timer(copyID);
4482 #endif
4483 
4484 #ifdef FEAT_QUICKFIX
4485     abort = abort || set_ref_in_quickfix(copyID);
4486 #endif
4487 
4488 #ifdef FEAT_TERMINAL
4489     abort = abort || set_ref_in_term(copyID);
4490 #endif
4491 
4492 #ifdef FEAT_PROP_POPUP
4493     abort = abort || set_ref_in_popups(copyID);
4494 #endif
4495 
4496     if (!abort)
4497     {
4498 	/*
4499 	 * 2. Free lists and dictionaries that are not referenced.
4500 	 */
4501 	did_free = free_unref_items(copyID);
4502 
4503 	/*
4504 	 * 3. Check if any funccal can be freed now.
4505 	 *    This may call us back recursively.
4506 	 */
4507 	free_unref_funccal(copyID, testing);
4508     }
4509     else if (p_verbose > 0)
4510     {
4511 	verb_msg(_("Not enough memory to set references, garbage collection aborted!"));
4512     }
4513 
4514     return did_free;
4515 }
4516 
4517 /*
4518  * Free lists, dictionaries, channels and jobs that are no longer referenced.
4519  */
4520     static int
4521 free_unref_items(int copyID)
4522 {
4523     int		did_free = FALSE;
4524 
4525     // Let all "free" functions know that we are here.  This means no
4526     // dictionaries, lists, channels or jobs are to be freed, because we will
4527     // do that here.
4528     in_free_unref_items = TRUE;
4529 
4530     /*
4531      * PASS 1: free the contents of the items.  We don't free the items
4532      * themselves yet, so that it is possible to decrement refcount counters
4533      */
4534 
4535     // Go through the list of dicts and free items without the copyID.
4536     did_free |= dict_free_nonref(copyID);
4537 
4538     // Go through the list of lists and free items without the copyID.
4539     did_free |= list_free_nonref(copyID);
4540 
4541 #ifdef FEAT_JOB_CHANNEL
4542     // Go through the list of jobs and free items without the copyID. This
4543     // must happen before doing channels, because jobs refer to channels, but
4544     // the reference from the channel to the job isn't tracked.
4545     did_free |= free_unused_jobs_contents(copyID, COPYID_MASK);
4546 
4547     // Go through the list of channels and free items without the copyID.
4548     did_free |= free_unused_channels_contents(copyID, COPYID_MASK);
4549 #endif
4550 
4551     /*
4552      * PASS 2: free the items themselves.
4553      */
4554     dict_free_items(copyID);
4555     list_free_items(copyID);
4556 
4557 #ifdef FEAT_JOB_CHANNEL
4558     // Go through the list of jobs and free items without the copyID. This
4559     // must happen before doing channels, because jobs refer to channels, but
4560     // the reference from the channel to the job isn't tracked.
4561     free_unused_jobs(copyID, COPYID_MASK);
4562 
4563     // Go through the list of channels and free items without the copyID.
4564     free_unused_channels(copyID, COPYID_MASK);
4565 #endif
4566 
4567     in_free_unref_items = FALSE;
4568 
4569     return did_free;
4570 }
4571 
4572 /*
4573  * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
4574  * "list_stack" is used to add lists to be marked.  Can be NULL.
4575  *
4576  * Returns TRUE if setting references failed somehow.
4577  */
4578     int
4579 set_ref_in_ht(hashtab_T *ht, int copyID, list_stack_T **list_stack)
4580 {
4581     int		todo;
4582     int		abort = FALSE;
4583     hashitem_T	*hi;
4584     hashtab_T	*cur_ht;
4585     ht_stack_T	*ht_stack = NULL;
4586     ht_stack_T	*tempitem;
4587 
4588     cur_ht = ht;
4589     for (;;)
4590     {
4591 	if (!abort)
4592 	{
4593 	    // Mark each item in the hashtab.  If the item contains a hashtab
4594 	    // it is added to ht_stack, if it contains a list it is added to
4595 	    // list_stack.
4596 	    todo = (int)cur_ht->ht_used;
4597 	    for (hi = cur_ht->ht_array; todo > 0; ++hi)
4598 		if (!HASHITEM_EMPTY(hi))
4599 		{
4600 		    --todo;
4601 		    abort = abort || set_ref_in_item(&HI2DI(hi)->di_tv, copyID,
4602 						       &ht_stack, list_stack);
4603 		}
4604 	}
4605 
4606 	if (ht_stack == NULL)
4607 	    break;
4608 
4609 	// take an item from the stack
4610 	cur_ht = ht_stack->ht;
4611 	tempitem = ht_stack;
4612 	ht_stack = ht_stack->prev;
4613 	free(tempitem);
4614     }
4615 
4616     return abort;
4617 }
4618 
4619 /*
4620  * Mark a dict and its items with "copyID".
4621  * Returns TRUE if setting references failed somehow.
4622  */
4623     int
4624 set_ref_in_dict(dict_T *d, int copyID)
4625 {
4626     if (d != NULL && d->dv_copyID != copyID)
4627     {
4628 	d->dv_copyID = copyID;
4629 	return set_ref_in_ht(&d->dv_hashtab, copyID, NULL);
4630     }
4631     return FALSE;
4632 }
4633 
4634 /*
4635  * Mark a list and its items with "copyID".
4636  * Returns TRUE if setting references failed somehow.
4637  */
4638     int
4639 set_ref_in_list(list_T *ll, int copyID)
4640 {
4641     if (ll != NULL && ll->lv_copyID != copyID)
4642     {
4643 	ll->lv_copyID = copyID;
4644 	return set_ref_in_list_items(ll, copyID, NULL);
4645     }
4646     return FALSE;
4647 }
4648 
4649 /*
4650  * Mark all lists and dicts referenced through list "l" with "copyID".
4651  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
4652  *
4653  * Returns TRUE if setting references failed somehow.
4654  */
4655     int
4656 set_ref_in_list_items(list_T *l, int copyID, ht_stack_T **ht_stack)
4657 {
4658     listitem_T	 *li;
4659     int		 abort = FALSE;
4660     list_T	 *cur_l;
4661     list_stack_T *list_stack = NULL;
4662     list_stack_T *tempitem;
4663 
4664     cur_l = l;
4665     for (;;)
4666     {
4667 	if (!abort && cur_l->lv_first != &range_list_item)
4668 	    // Mark each item in the list.  If the item contains a hashtab
4669 	    // it is added to ht_stack, if it contains a list it is added to
4670 	    // list_stack.
4671 	    for (li = cur_l->lv_first; !abort && li != NULL; li = li->li_next)
4672 		abort = abort || set_ref_in_item(&li->li_tv, copyID,
4673 						       ht_stack, &list_stack);
4674 	if (list_stack == NULL)
4675 	    break;
4676 
4677 	// take an item from the stack
4678 	cur_l = list_stack->list;
4679 	tempitem = list_stack;
4680 	list_stack = list_stack->prev;
4681 	free(tempitem);
4682     }
4683 
4684     return abort;
4685 }
4686 
4687 /*
4688  * Mark all lists and dicts referenced through typval "tv" with "copyID".
4689  * "list_stack" is used to add lists to be marked.  Can be NULL.
4690  * "ht_stack" is used to add hashtabs to be marked.  Can be NULL.
4691  *
4692  * Returns TRUE if setting references failed somehow.
4693  */
4694     int
4695 set_ref_in_item(
4696     typval_T	    *tv,
4697     int		    copyID,
4698     ht_stack_T	    **ht_stack,
4699     list_stack_T    **list_stack)
4700 {
4701     int		abort = FALSE;
4702 
4703     if (tv->v_type == VAR_DICT)
4704     {
4705 	dict_T	*dd = tv->vval.v_dict;
4706 
4707 	if (dd != NULL && dd->dv_copyID != copyID)
4708 	{
4709 	    // Didn't see this dict yet.
4710 	    dd->dv_copyID = copyID;
4711 	    if (ht_stack == NULL)
4712 	    {
4713 		abort = set_ref_in_ht(&dd->dv_hashtab, copyID, list_stack);
4714 	    }
4715 	    else
4716 	    {
4717 		ht_stack_T *newitem = ALLOC_ONE(ht_stack_T);
4718 
4719 		if (newitem == NULL)
4720 		    abort = TRUE;
4721 		else
4722 		{
4723 		    newitem->ht = &dd->dv_hashtab;
4724 		    newitem->prev = *ht_stack;
4725 		    *ht_stack = newitem;
4726 		}
4727 	    }
4728 	}
4729     }
4730     else if (tv->v_type == VAR_LIST)
4731     {
4732 	list_T	*ll = tv->vval.v_list;
4733 
4734 	if (ll != NULL && ll->lv_copyID != copyID)
4735 	{
4736 	    // Didn't see this list yet.
4737 	    ll->lv_copyID = copyID;
4738 	    if (list_stack == NULL)
4739 	    {
4740 		abort = set_ref_in_list_items(ll, copyID, ht_stack);
4741 	    }
4742 	    else
4743 	    {
4744 		list_stack_T *newitem = ALLOC_ONE(list_stack_T);
4745 
4746 		if (newitem == NULL)
4747 		    abort = TRUE;
4748 		else
4749 		{
4750 		    newitem->list = ll;
4751 		    newitem->prev = *list_stack;
4752 		    *list_stack = newitem;
4753 		}
4754 	    }
4755 	}
4756     }
4757     else if (tv->v_type == VAR_FUNC)
4758     {
4759 	abort = set_ref_in_func(tv->vval.v_string, NULL, copyID);
4760     }
4761     else if (tv->v_type == VAR_PARTIAL)
4762     {
4763 	partial_T	*pt = tv->vval.v_partial;
4764 	int		i;
4765 
4766 	if (pt != NULL && pt->pt_copyID != copyID)
4767 	{
4768 	    // Didn't see this partial yet.
4769 	    pt->pt_copyID = copyID;
4770 
4771 	    abort = set_ref_in_func(pt->pt_name, pt->pt_func, copyID);
4772 
4773 	    if (pt->pt_dict != NULL)
4774 	    {
4775 		typval_T dtv;
4776 
4777 		dtv.v_type = VAR_DICT;
4778 		dtv.vval.v_dict = pt->pt_dict;
4779 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4780 	    }
4781 
4782 	    for (i = 0; i < pt->pt_argc; ++i)
4783 		abort = abort || set_ref_in_item(&pt->pt_argv[i], copyID,
4784 							ht_stack, list_stack);
4785 	    if (pt->pt_funcstack != NULL)
4786 	    {
4787 		typval_T    *stack = pt->pt_funcstack->fs_ga.ga_data;
4788 
4789 		for (i = 0; i < pt->pt_funcstack->fs_ga.ga_len; ++i)
4790 		    abort = abort || set_ref_in_item(stack + i, copyID,
4791 							 ht_stack, list_stack);
4792 	    }
4793 
4794 	}
4795     }
4796 #ifdef FEAT_JOB_CHANNEL
4797     else if (tv->v_type == VAR_JOB)
4798     {
4799 	job_T	    *job = tv->vval.v_job;
4800 	typval_T    dtv;
4801 
4802 	if (job != NULL && job->jv_copyID != copyID)
4803 	{
4804 	    job->jv_copyID = copyID;
4805 	    if (job->jv_channel != NULL)
4806 	    {
4807 		dtv.v_type = VAR_CHANNEL;
4808 		dtv.vval.v_channel = job->jv_channel;
4809 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4810 	    }
4811 	    if (job->jv_exit_cb.cb_partial != NULL)
4812 	    {
4813 		dtv.v_type = VAR_PARTIAL;
4814 		dtv.vval.v_partial = job->jv_exit_cb.cb_partial;
4815 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4816 	    }
4817 	}
4818     }
4819     else if (tv->v_type == VAR_CHANNEL)
4820     {
4821 	channel_T   *ch =tv->vval.v_channel;
4822 	ch_part_T   part;
4823 	typval_T    dtv;
4824 	jsonq_T	    *jq;
4825 	cbq_T	    *cq;
4826 
4827 	if (ch != NULL && ch->ch_copyID != copyID)
4828 	{
4829 	    ch->ch_copyID = copyID;
4830 	    for (part = PART_SOCK; part < PART_COUNT; ++part)
4831 	    {
4832 		for (jq = ch->ch_part[part].ch_json_head.jq_next; jq != NULL;
4833 							     jq = jq->jq_next)
4834 		    set_ref_in_item(jq->jq_value, copyID, ht_stack, list_stack);
4835 		for (cq = ch->ch_part[part].ch_cb_head.cq_next; cq != NULL;
4836 							     cq = cq->cq_next)
4837 		    if (cq->cq_callback.cb_partial != NULL)
4838 		    {
4839 			dtv.v_type = VAR_PARTIAL;
4840 			dtv.vval.v_partial = cq->cq_callback.cb_partial;
4841 			set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4842 		    }
4843 		if (ch->ch_part[part].ch_callback.cb_partial != NULL)
4844 		{
4845 		    dtv.v_type = VAR_PARTIAL;
4846 		    dtv.vval.v_partial =
4847 				      ch->ch_part[part].ch_callback.cb_partial;
4848 		    set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4849 		}
4850 	    }
4851 	    if (ch->ch_callback.cb_partial != NULL)
4852 	    {
4853 		dtv.v_type = VAR_PARTIAL;
4854 		dtv.vval.v_partial = ch->ch_callback.cb_partial;
4855 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4856 	    }
4857 	    if (ch->ch_close_cb.cb_partial != NULL)
4858 	    {
4859 		dtv.v_type = VAR_PARTIAL;
4860 		dtv.vval.v_partial = ch->ch_close_cb.cb_partial;
4861 		set_ref_in_item(&dtv, copyID, ht_stack, list_stack);
4862 	    }
4863 	}
4864     }
4865 #endif
4866     return abort;
4867 }
4868 
4869 /*
4870  * Return a string with the string representation of a variable.
4871  * If the memory is allocated "tofree" is set to it, otherwise NULL.
4872  * "numbuf" is used for a number.
4873  * When "copyID" is not NULL replace recursive lists and dicts with "...".
4874  * When both "echo_style" and "composite_val" are FALSE, put quotes around
4875  * strings as "string()", otherwise does not put quotes around strings, as
4876  * ":echo" displays values.
4877  * When "restore_copyID" is FALSE, repeated items in dictionaries and lists
4878  * are replaced with "...".
4879  * May return NULL.
4880  */
4881     char_u *
4882 echo_string_core(
4883     typval_T	*tv,
4884     char_u	**tofree,
4885     char_u	*numbuf,
4886     int		copyID,
4887     int		echo_style,
4888     int		restore_copyID,
4889     int		composite_val)
4890 {
4891     static int	recurse = 0;
4892     char_u	*r = NULL;
4893 
4894     if (recurse >= DICT_MAXNEST)
4895     {
4896 	if (!did_echo_string_emsg)
4897 	{
4898 	    // Only give this message once for a recursive call to avoid
4899 	    // flooding the user with errors.  And stop iterating over lists
4900 	    // and dicts.
4901 	    did_echo_string_emsg = TRUE;
4902 	    emsg(_("E724: variable nested too deep for displaying"));
4903 	}
4904 	*tofree = NULL;
4905 	return (char_u *)"{E724}";
4906     }
4907     ++recurse;
4908 
4909     switch (tv->v_type)
4910     {
4911 	case VAR_STRING:
4912 	    if (echo_style && !composite_val)
4913 	    {
4914 		*tofree = NULL;
4915 		r = tv->vval.v_string;
4916 		if (r == NULL)
4917 		    r = (char_u *)"";
4918 	    }
4919 	    else
4920 	    {
4921 		*tofree = string_quote(tv->vval.v_string, FALSE);
4922 		r = *tofree;
4923 	    }
4924 	    break;
4925 
4926 	case VAR_FUNC:
4927 	    if (echo_style)
4928 	    {
4929 		*tofree = NULL;
4930 		r = tv->vval.v_string;
4931 	    }
4932 	    else
4933 	    {
4934 		*tofree = string_quote(tv->vval.v_string, TRUE);
4935 		r = *tofree;
4936 	    }
4937 	    break;
4938 
4939 	case VAR_PARTIAL:
4940 	    {
4941 		partial_T   *pt = tv->vval.v_partial;
4942 		char_u	    *fname = string_quote(pt == NULL ? NULL
4943 						    : partial_name(pt), FALSE);
4944 		garray_T    ga;
4945 		int	    i;
4946 		char_u	    *tf;
4947 
4948 		ga_init2(&ga, 1, 100);
4949 		ga_concat(&ga, (char_u *)"function(");
4950 		if (fname != NULL)
4951 		{
4952 		    ga_concat(&ga, fname);
4953 		    vim_free(fname);
4954 		}
4955 		if (pt != NULL && pt->pt_argc > 0)
4956 		{
4957 		    ga_concat(&ga, (char_u *)", [");
4958 		    for (i = 0; i < pt->pt_argc; ++i)
4959 		    {
4960 			if (i > 0)
4961 			    ga_concat(&ga, (char_u *)", ");
4962 			ga_concat(&ga,
4963 			     tv2string(&pt->pt_argv[i], &tf, numbuf, copyID));
4964 			vim_free(tf);
4965 		    }
4966 		    ga_concat(&ga, (char_u *)"]");
4967 		}
4968 		if (pt != NULL && pt->pt_dict != NULL)
4969 		{
4970 		    typval_T dtv;
4971 
4972 		    ga_concat(&ga, (char_u *)", ");
4973 		    dtv.v_type = VAR_DICT;
4974 		    dtv.vval.v_dict = pt->pt_dict;
4975 		    ga_concat(&ga, tv2string(&dtv, &tf, numbuf, copyID));
4976 		    vim_free(tf);
4977 		}
4978 		ga_concat(&ga, (char_u *)")");
4979 
4980 		*tofree = ga.ga_data;
4981 		r = *tofree;
4982 		break;
4983 	    }
4984 
4985 	case VAR_BLOB:
4986 	    r = blob2string(tv->vval.v_blob, tofree, numbuf);
4987 	    break;
4988 
4989 	case VAR_LIST:
4990 	    if (tv->vval.v_list == NULL)
4991 	    {
4992 		// NULL list is equivalent to empty list.
4993 		*tofree = NULL;
4994 		r = (char_u *)"[]";
4995 	    }
4996 	    else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID
4997 		    && tv->vval.v_list->lv_len > 0)
4998 	    {
4999 		*tofree = NULL;
5000 		r = (char_u *)"[...]";
5001 	    }
5002 	    else
5003 	    {
5004 		int old_copyID = tv->vval.v_list->lv_copyID;
5005 
5006 		tv->vval.v_list->lv_copyID = copyID;
5007 		*tofree = list2string(tv, copyID, restore_copyID);
5008 		if (restore_copyID)
5009 		    tv->vval.v_list->lv_copyID = old_copyID;
5010 		r = *tofree;
5011 	    }
5012 	    break;
5013 
5014 	case VAR_DICT:
5015 	    if (tv->vval.v_dict == NULL)
5016 	    {
5017 		// NULL dict is equivalent to empty dict.
5018 		*tofree = NULL;
5019 		r = (char_u *)"{}";
5020 	    }
5021 	    else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID
5022 		    && tv->vval.v_dict->dv_hashtab.ht_used != 0)
5023 	    {
5024 		*tofree = NULL;
5025 		r = (char_u *)"{...}";
5026 	    }
5027 	    else
5028 	    {
5029 		int old_copyID = tv->vval.v_dict->dv_copyID;
5030 
5031 		tv->vval.v_dict->dv_copyID = copyID;
5032 		*tofree = dict2string(tv, copyID, restore_copyID);
5033 		if (restore_copyID)
5034 		    tv->vval.v_dict->dv_copyID = old_copyID;
5035 		r = *tofree;
5036 	    }
5037 	    break;
5038 
5039 	case VAR_NUMBER:
5040 	case VAR_UNKNOWN:
5041 	case VAR_ANY:
5042 	case VAR_VOID:
5043 	    *tofree = NULL;
5044 	    r = tv_get_string_buf(tv, numbuf);
5045 	    break;
5046 
5047 	case VAR_JOB:
5048 	case VAR_CHANNEL:
5049 	    *tofree = NULL;
5050 	    r = tv_get_string_buf(tv, numbuf);
5051 	    if (composite_val)
5052 	    {
5053 		*tofree = string_quote(r, FALSE);
5054 		r = *tofree;
5055 	    }
5056 	    break;
5057 
5058 	case VAR_FLOAT:
5059 #ifdef FEAT_FLOAT
5060 	    *tofree = NULL;
5061 	    vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
5062 	    r = numbuf;
5063 	    break;
5064 #endif
5065 
5066 	case VAR_BOOL:
5067 	case VAR_SPECIAL:
5068 	    *tofree = NULL;
5069 	    r = (char_u *)get_var_special_name(tv->vval.v_number);
5070 	    break;
5071     }
5072 
5073     if (--recurse == 0)
5074 	did_echo_string_emsg = FALSE;
5075     return r;
5076 }
5077 
5078 /*
5079  * Return a string with the string representation of a variable.
5080  * If the memory is allocated "tofree" is set to it, otherwise NULL.
5081  * "numbuf" is used for a number.
5082  * Does not put quotes around strings, as ":echo" displays values.
5083  * When "copyID" is not NULL replace recursive lists and dicts with "...".
5084  * May return NULL.
5085  */
5086     char_u *
5087 echo_string(
5088     typval_T	*tv,
5089     char_u	**tofree,
5090     char_u	*numbuf,
5091     int		copyID)
5092 {
5093     return echo_string_core(tv, tofree, numbuf, copyID, TRUE, FALSE, FALSE);
5094 }
5095 
5096 /*
5097  * Return string "str" in ' quotes, doubling ' characters.
5098  * If "str" is NULL an empty string is assumed.
5099  * If "function" is TRUE make it function('string').
5100  */
5101     char_u *
5102 string_quote(char_u *str, int function)
5103 {
5104     unsigned	len;
5105     char_u	*p, *r, *s;
5106 
5107     len = (function ? 13 : 3);
5108     if (str != NULL)
5109     {
5110 	len += (unsigned)STRLEN(str);
5111 	for (p = str; *p != NUL; MB_PTR_ADV(p))
5112 	    if (*p == '\'')
5113 		++len;
5114     }
5115     s = r = alloc(len);
5116     if (r != NULL)
5117     {
5118 	if (function)
5119 	{
5120 	    STRCPY(r, "function('");
5121 	    r += 10;
5122 	}
5123 	else
5124 	    *r++ = '\'';
5125 	if (str != NULL)
5126 	    for (p = str; *p != NUL; )
5127 	    {
5128 		if (*p == '\'')
5129 		    *r++ = '\'';
5130 		MB_COPY_CHAR(p, r);
5131 	    }
5132 	*r++ = '\'';
5133 	if (function)
5134 	    *r++ = ')';
5135 	*r++ = NUL;
5136     }
5137     return s;
5138 }
5139 
5140 #if defined(FEAT_FLOAT) || defined(PROTO)
5141 /*
5142  * Convert the string "text" to a floating point number.
5143  * This uses strtod().  setlocale(LC_NUMERIC, "C") has been used to make sure
5144  * this always uses a decimal point.
5145  * Returns the length of the text that was consumed.
5146  */
5147     int
5148 string2float(
5149     char_u	*text,
5150     float_T	*value)	    // result stored here
5151 {
5152     char	*s = (char *)text;
5153     float_T	f;
5154 
5155     // MS-Windows does not deal with "inf" and "nan" properly.
5156     if (STRNICMP(text, "inf", 3) == 0)
5157     {
5158 	*value = INFINITY;
5159 	return 3;
5160     }
5161     if (STRNICMP(text, "-inf", 3) == 0)
5162     {
5163 	*value = -INFINITY;
5164 	return 4;
5165     }
5166     if (STRNICMP(text, "nan", 3) == 0)
5167     {
5168 	*value = NAN;
5169 	return 3;
5170     }
5171     f = strtod(s, &s);
5172     *value = f;
5173     return (int)((char_u *)s - text);
5174 }
5175 #endif
5176 
5177 /*
5178  * Convert the specified byte index of line 'lnum' in buffer 'buf' to a
5179  * character index.  Works only for loaded buffers. Returns -1 on failure.
5180  * The index of the first byte and the first character is zero.
5181  */
5182     int
5183 buf_byteidx_to_charidx(buf_T *buf, int lnum, int byteidx)
5184 {
5185     char_u	*str;
5186     char_u	*t;
5187     int		count;
5188 
5189     if (buf == NULL || buf->b_ml.ml_mfp == NULL)
5190 	return -1;
5191 
5192     if (lnum > buf->b_ml.ml_line_count)
5193 	lnum = buf->b_ml.ml_line_count;
5194 
5195     str = ml_get_buf(buf, lnum, FALSE);
5196     if (str == NULL)
5197 	return -1;
5198 
5199     if (*str == NUL)
5200 	return 0;
5201 
5202     // count the number of characters
5203     t = str;
5204     for (count = 0; *t != NUL && t <= str + byteidx; count++)
5205 	t += mb_ptr2len(t);
5206 
5207     // In insert mode, when the cursor is at the end of a non-empty line,
5208     // byteidx points to the NUL character immediately past the end of the
5209     // string. In this case, add one to the character count.
5210     if (*t == NUL && byteidx != 0 && t == str + byteidx)
5211 	count++;
5212 
5213     return count - 1;
5214 }
5215 
5216 /*
5217  * Convert the specified character index of line 'lnum' in buffer 'buf' to a
5218  * byte index.  Works only for loaded buffers. Returns -1 on failure.
5219  * The index of the first byte and the first character is zero.
5220  */
5221     int
5222 buf_charidx_to_byteidx(buf_T *buf, int lnum, int charidx)
5223 {
5224     char_u	*str;
5225     char_u	*t;
5226 
5227     if (buf == NULL || buf->b_ml.ml_mfp == NULL)
5228 	return -1;
5229 
5230     if (lnum > buf->b_ml.ml_line_count)
5231 	lnum = buf->b_ml.ml_line_count;
5232 
5233     str = ml_get_buf(buf, lnum, FALSE);
5234     if (str == NULL)
5235 	return -1;
5236 
5237     // Convert the character offset to a byte offset
5238     t = str;
5239     while (*t != NUL && --charidx > 0)
5240 	t += mb_ptr2len(t);
5241 
5242     return t - str;
5243 }
5244 
5245 /*
5246  * Translate a String variable into a position.
5247  * Returns NULL when there is an error.
5248  */
5249     pos_T *
5250 var2fpos(
5251     typval_T	*varp,
5252     int		dollar_lnum,	// TRUE when $ is last line
5253     int		*fnum,		// set to fnum for '0, 'A, etc.
5254     int		charcol)	// return character column
5255 {
5256     char_u		*name;
5257     static pos_T	pos;
5258     pos_T		*pp;
5259 
5260     // Argument can be [lnum, col, coladd].
5261     if (varp->v_type == VAR_LIST)
5262     {
5263 	list_T		*l;
5264 	int		len;
5265 	int		error = FALSE;
5266 	listitem_T	*li;
5267 
5268 	l = varp->vval.v_list;
5269 	if (l == NULL)
5270 	    return NULL;
5271 
5272 	// Get the line number
5273 	pos.lnum = list_find_nr(l, 0L, &error);
5274 	if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
5275 	    return NULL;	// invalid line number
5276 	if (charcol)
5277 	    len = (long)mb_charlen(ml_get(pos.lnum));
5278 	else
5279 	    len = (long)STRLEN(ml_get(pos.lnum));
5280 
5281 	// Get the column number
5282 	// We accept "$" for the column number: last column.
5283 	li = list_find(l, 1L);
5284 	if (li != NULL && li->li_tv.v_type == VAR_STRING
5285 		&& li->li_tv.vval.v_string != NULL
5286 		&& STRCMP(li->li_tv.vval.v_string, "$") == 0)
5287 	{
5288 	    pos.col = len + 1;
5289 	}
5290 	else
5291 	{
5292 	    pos.col = list_find_nr(l, 1L, &error);
5293 	    if (error)
5294 		return NULL;
5295 	}
5296 
5297 	// Accept a position up to the NUL after the line.
5298 	if (pos.col == 0 || (int)pos.col > len + 1)
5299 	    return NULL;	// invalid column number
5300 	--pos.col;
5301 
5302 	// Get the virtual offset.  Defaults to zero.
5303 	pos.coladd = list_find_nr(l, 2L, &error);
5304 	if (error)
5305 	    pos.coladd = 0;
5306 
5307 	return &pos;
5308     }
5309 
5310     if (in_vim9script() && check_for_string_arg(varp, 0) == FAIL)
5311 	return NULL;
5312 
5313     name = tv_get_string_chk(varp);
5314     if (name == NULL)
5315 	return NULL;
5316     if (name[0] == '.')				// cursor
5317     {
5318 	pos = curwin->w_cursor;
5319 	if (charcol)
5320 	    pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);
5321 	return &pos;
5322     }
5323     if (name[0] == 'v' && name[1] == NUL)	// Visual start
5324     {
5325 	if (VIsual_active)
5326 	    pos = VIsual;
5327 	else
5328 	    pos = curwin->w_cursor;
5329 	if (charcol)
5330 	    pos.col = buf_byteidx_to_charidx(curbuf, pos.lnum, pos.col);
5331 	return &pos;
5332     }
5333     if (name[0] == '\'')			// mark
5334     {
5335 	pp = getmark_buf_fnum(curbuf, name[1], FALSE, fnum);
5336 	if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
5337 	    return NULL;
5338 	if (charcol)
5339 	    pp->col = buf_byteidx_to_charidx(curbuf, pp->lnum, pp->col);
5340 	return pp;
5341     }
5342 
5343     pos.coladd = 0;
5344 
5345     if (name[0] == 'w' && dollar_lnum)
5346     {
5347 	pos.col = 0;
5348 	if (name[1] == '0')		// "w0": first visible line
5349 	{
5350 	    update_topline();
5351 	    // In silent Ex mode topline is zero, but that's not a valid line
5352 	    // number; use one instead.
5353 	    pos.lnum = curwin->w_topline > 0 ? curwin->w_topline : 1;
5354 	    return &pos;
5355 	}
5356 	else if (name[1] == '$')	// "w$": last visible line
5357 	{
5358 	    validate_botline();
5359 	    // In silent Ex mode botline is zero, return zero then.
5360 	    pos.lnum = curwin->w_botline > 0 ? curwin->w_botline - 1 : 0;
5361 	    return &pos;
5362 	}
5363     }
5364     else if (name[0] == '$')		// last column or line
5365     {
5366 	if (dollar_lnum)
5367 	{
5368 	    pos.lnum = curbuf->b_ml.ml_line_count;
5369 	    pos.col = 0;
5370 	}
5371 	else
5372 	{
5373 	    pos.lnum = curwin->w_cursor.lnum;
5374 	    if (charcol)
5375 		pos.col = (colnr_T)mb_charlen(ml_get_curline());
5376 	    else
5377 		pos.col = (colnr_T)STRLEN(ml_get_curline());
5378 	}
5379 	return &pos;
5380     }
5381     return NULL;
5382 }
5383 
5384 /*
5385  * Convert list in "arg" into a position and optional file number.
5386  * When "fnump" is NULL there is no file number, only 3 items.
5387  * Note that the column is passed on as-is, the caller may want to decrement
5388  * it to use 1 for the first column.
5389  * Return FAIL when conversion is not possible, doesn't check the position for
5390  * validity.
5391  */
5392     int
5393 list2fpos(
5394     typval_T	*arg,
5395     pos_T	*posp,
5396     int		*fnump,
5397     colnr_T	*curswantp,
5398     int		charcol)
5399 {
5400     list_T	*l = arg->vval.v_list;
5401     long	i = 0;
5402     long	n;
5403 
5404     // List must be: [fnum, lnum, col, coladd, curswant], where "fnum" is only
5405     // there when "fnump" isn't NULL; "coladd" and "curswant" are optional.
5406     if (arg->v_type != VAR_LIST
5407 	    || l == NULL
5408 	    || l->lv_len < (fnump == NULL ? 2 : 3)
5409 	    || l->lv_len > (fnump == NULL ? 4 : 5))
5410 	return FAIL;
5411 
5412     if (fnump != NULL)
5413     {
5414 	n = list_find_nr(l, i++, NULL);	// fnum
5415 	if (n < 0)
5416 	    return FAIL;
5417 	if (n == 0)
5418 	    n = curbuf->b_fnum;		// current buffer
5419 	*fnump = n;
5420     }
5421 
5422     n = list_find_nr(l, i++, NULL);	// lnum
5423     if (n < 0)
5424 	return FAIL;
5425     posp->lnum = n;
5426 
5427     n = list_find_nr(l, i++, NULL);	// col
5428     if (n < 0)
5429 	return FAIL;
5430     // If character position is specified, then convert to byte position
5431     if (charcol)
5432     {
5433 	buf_T	*buf;
5434 
5435 	// Get the text for the specified line in a loaded buffer
5436 	buf = buflist_findnr(fnump == NULL ? curbuf->b_fnum : *fnump);
5437 	if (buf == NULL || buf->b_ml.ml_mfp == NULL)
5438 	    return FAIL;
5439 
5440 	n = buf_charidx_to_byteidx(buf, posp->lnum, n) + 1;
5441     }
5442     posp->col = n;
5443 
5444     n = list_find_nr(l, i, NULL);	// off
5445     if (n < 0)
5446 	posp->coladd = 0;
5447     else
5448 	posp->coladd = n;
5449 
5450     if (curswantp != NULL)
5451 	*curswantp = list_find_nr(l, i + 1, NULL);  // curswant
5452 
5453     return OK;
5454 }
5455 
5456 /*
5457  * Get the length of an environment variable name.
5458  * Advance "arg" to the first character after the name.
5459  * Return 0 for error.
5460  */
5461     int
5462 get_env_len(char_u **arg)
5463 {
5464     char_u	*p;
5465     int		len;
5466 
5467     for (p = *arg; vim_isIDc(*p); ++p)
5468 	;
5469     if (p == *arg)	    // no name found
5470 	return 0;
5471 
5472     len = (int)(p - *arg);
5473     *arg = p;
5474     return len;
5475 }
5476 
5477 /*
5478  * Get the length of the name of a function or internal variable.
5479  * "arg" is advanced to after the name.
5480  * Return 0 if something is wrong.
5481  */
5482     int
5483 get_id_len(char_u **arg)
5484 {
5485     char_u	*p;
5486     int		len;
5487 
5488     // Find the end of the name.
5489     for (p = *arg; eval_isnamec(*p); ++p)
5490     {
5491 	if (*p == ':')
5492 	{
5493 	    // "s:" is start of "s:var", but "n:" is not and can be used in
5494 	    // slice "[n:]".  Also "xx:" is not a namespace.
5495 	    len = (int)(p - *arg);
5496 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, **arg) == NULL)
5497 		    || len > 1)
5498 		break;
5499 	}
5500     }
5501     if (p == *arg)	    // no name found
5502 	return 0;
5503 
5504     len = (int)(p - *arg);
5505     *arg = p;
5506 
5507     return len;
5508 }
5509 
5510 /*
5511  * Get the length of the name of a variable or function.
5512  * Only the name is recognized, does not handle ".key" or "[idx]".
5513  * "arg" is advanced to the first non-white character after the name.
5514  * Return -1 if curly braces expansion failed.
5515  * Return 0 if something else is wrong.
5516  * If the name contains 'magic' {}'s, expand them and return the
5517  * expanded name in an allocated string via 'alias' - caller must free.
5518  */
5519     int
5520 get_name_len(
5521     char_u	**arg,
5522     char_u	**alias,
5523     int		evaluate,
5524     int		verbose)
5525 {
5526     int		len;
5527     char_u	*p;
5528     char_u	*expr_start;
5529     char_u	*expr_end;
5530 
5531     *alias = NULL;  // default to no alias
5532 
5533     if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
5534 						  && (*arg)[2] == (int)KE_SNR)
5535     {
5536 	// hard coded <SNR>, already translated
5537 	*arg += 3;
5538 	return get_id_len(arg) + 3;
5539     }
5540     len = eval_fname_script(*arg);
5541     if (len > 0)
5542     {
5543 	// literal "<SID>", "s:" or "<SNR>"
5544 	*arg += len;
5545     }
5546 
5547     /*
5548      * Find the end of the name; check for {} construction.
5549      */
5550     p = find_name_end(*arg, &expr_start, &expr_end,
5551 					       len > 0 ? 0 : FNE_CHECK_START);
5552     if (expr_start != NULL)
5553     {
5554 	char_u	*temp_string;
5555 
5556 	if (!evaluate)
5557 	{
5558 	    len += (int)(p - *arg);
5559 	    *arg = skipwhite(p);
5560 	    return len;
5561 	}
5562 
5563 	/*
5564 	 * Include any <SID> etc in the expanded string:
5565 	 * Thus the -len here.
5566 	 */
5567 	temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
5568 	if (temp_string == NULL)
5569 	    return -1;
5570 	*alias = temp_string;
5571 	*arg = skipwhite(p);
5572 	return (int)STRLEN(temp_string);
5573     }
5574 
5575     len += get_id_len(arg);
5576     // Only give an error when there is something, otherwise it will be
5577     // reported at a higher level.
5578     if (len == 0 && verbose && **arg != NUL)
5579 	semsg(_(e_invexpr2), *arg);
5580 
5581     return len;
5582 }
5583 
5584 /*
5585  * Find the end of a variable or function name, taking care of magic braces.
5586  * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
5587  * start and end of the first magic braces item.
5588  * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
5589  * Return a pointer to just after the name.  Equal to "arg" if there is no
5590  * valid name.
5591  */
5592     char_u *
5593 find_name_end(
5594     char_u	*arg,
5595     char_u	**expr_start,
5596     char_u	**expr_end,
5597     int		flags)
5598 {
5599     int		mb_nest = 0;
5600     int		br_nest = 0;
5601     char_u	*p;
5602     int		len;
5603     int		vim9script = in_vim9script();
5604 
5605     if (expr_start != NULL)
5606     {
5607 	*expr_start = NULL;
5608 	*expr_end = NULL;
5609     }
5610 
5611     // Quick check for valid starting character.
5612     if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg)
5613 						&& (*arg != '{' || vim9script))
5614 	return arg;
5615 
5616     for (p = arg; *p != NUL
5617 		    && (eval_isnamec(*p)
5618 			|| (*p == '{' && !vim9script)
5619 			|| ((flags & FNE_INCL_BR) && (*p == '['
5620 					 || (*p == '.' && eval_isdictc(p[1]))))
5621 			|| mb_nest != 0
5622 			|| br_nest != 0); MB_PTR_ADV(p))
5623     {
5624 	if (*p == '\'')
5625 	{
5626 	    // skip over 'string' to avoid counting [ and ] inside it.
5627 	    for (p = p + 1; *p != NUL && *p != '\''; MB_PTR_ADV(p))
5628 		;
5629 	    if (*p == NUL)
5630 		break;
5631 	}
5632 	else if (*p == '"')
5633 	{
5634 	    // skip over "str\"ing" to avoid counting [ and ] inside it.
5635 	    for (p = p + 1; *p != NUL && *p != '"'; MB_PTR_ADV(p))
5636 		if (*p == '\\' && p[1] != NUL)
5637 		    ++p;
5638 	    if (*p == NUL)
5639 		break;
5640 	}
5641 	else if (br_nest == 0 && mb_nest == 0 && *p == ':')
5642 	{
5643 	    // "s:" is start of "s:var", but "n:" is not and can be used in
5644 	    // slice "[n:]".  Also "xx:" is not a namespace. But {ns}: is.
5645 	    len = (int)(p - arg);
5646 	    if ((len == 1 && vim_strchr(NAMESPACE_CHAR, *arg) == NULL)
5647 		    || (len > 1 && p[-1] != '}'))
5648 		break;
5649 	}
5650 
5651 	if (mb_nest == 0)
5652 	{
5653 	    if (*p == '[')
5654 		++br_nest;
5655 	    else if (*p == ']')
5656 		--br_nest;
5657 	}
5658 
5659 	if (br_nest == 0 && !vim9script)
5660 	{
5661 	    if (*p == '{')
5662 	    {
5663 		mb_nest++;
5664 		if (expr_start != NULL && *expr_start == NULL)
5665 		    *expr_start = p;
5666 	    }
5667 	    else if (*p == '}')
5668 	    {
5669 		mb_nest--;
5670 		if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
5671 		    *expr_end = p;
5672 	    }
5673 	}
5674     }
5675 
5676     return p;
5677 }
5678 
5679 /*
5680  * Expands out the 'magic' {}'s in a variable/function name.
5681  * Note that this can call itself recursively, to deal with
5682  * constructs like foo{bar}{baz}{bam}
5683  * The four pointer arguments point to "foo{expre}ss{ion}bar"
5684  *			"in_start"      ^
5685  *			"expr_start"	   ^
5686  *			"expr_end"		 ^
5687  *			"in_end"			    ^
5688  *
5689  * Returns a new allocated string, which the caller must free.
5690  * Returns NULL for failure.
5691  */
5692     static char_u *
5693 make_expanded_name(
5694     char_u	*in_start,
5695     char_u	*expr_start,
5696     char_u	*expr_end,
5697     char_u	*in_end)
5698 {
5699     char_u	c1;
5700     char_u	*retval = NULL;
5701     char_u	*temp_result;
5702 
5703     if (expr_end == NULL || in_end == NULL)
5704 	return NULL;
5705     *expr_start	= NUL;
5706     *expr_end = NUL;
5707     c1 = *in_end;
5708     *in_end = NUL;
5709 
5710     temp_result = eval_to_string(expr_start + 1, FALSE);
5711     if (temp_result != NULL)
5712     {
5713 	retval = alloc(STRLEN(temp_result) + (expr_start - in_start)
5714 						   + (in_end - expr_end) + 1);
5715 	if (retval != NULL)
5716 	{
5717 	    STRCPY(retval, in_start);
5718 	    STRCAT(retval, temp_result);
5719 	    STRCAT(retval, expr_end + 1);
5720 	}
5721     }
5722     vim_free(temp_result);
5723 
5724     *in_end = c1;		// put char back for error messages
5725     *expr_start = '{';
5726     *expr_end = '}';
5727 
5728     if (retval != NULL)
5729     {
5730 	temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
5731 	if (expr_start != NULL)
5732 	{
5733 	    // Further expansion!
5734 	    temp_result = make_expanded_name(retval, expr_start,
5735 						       expr_end, temp_result);
5736 	    vim_free(retval);
5737 	    retval = temp_result;
5738 	}
5739     }
5740 
5741     return retval;
5742 }
5743 
5744 /*
5745  * Return TRUE if character "c" can be used in a variable or function name.
5746  * Does not include '{' or '}' for magic braces.
5747  */
5748     int
5749 eval_isnamec(int c)
5750 {
5751     return ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR;
5752 }
5753 
5754 /*
5755  * Return TRUE if character "c" can be used as the first character in a
5756  * variable or function name (excluding '{' and '}').
5757  */
5758     int
5759 eval_isnamec1(int c)
5760 {
5761     return ASCII_ISALPHA(c) || c == '_';
5762 }
5763 
5764 /*
5765  * Return TRUE if character "c" can be used as the first character of a
5766  * dictionary key.
5767  */
5768     int
5769 eval_isdictc(int c)
5770 {
5771     return ASCII_ISALNUM(c) || c == '_';
5772 }
5773 
5774 /*
5775  * Handle:
5776  * - expr[expr], expr[expr:expr] subscript
5777  * - ".name" lookup
5778  * - function call with Funcref variable: func(expr)
5779  * - method call: var->method()
5780  *
5781  * Can all be combined in any order: dict.func(expr)[idx]['func'](expr)->len()
5782  */
5783     int
5784 handle_subscript(
5785     char_u	**arg,
5786     typval_T	*rettv,
5787     evalarg_T	*evalarg,
5788     int		verbose)	// give error messages
5789 {
5790     int		evaluate = evalarg != NULL
5791 				      && (evalarg->eval_flags & EVAL_EVALUATE);
5792     int		ret = OK;
5793     dict_T	*selfdict = NULL;
5794     int		check_white = TRUE;
5795     int		getnext;
5796     char_u	*p;
5797 
5798     while (ret == OK)
5799     {
5800 	// When at the end of the line and ".name" or "->{" or "->X" follows in
5801 	// the next line then consume the line break.
5802 	p = eval_next_non_blank(*arg, evalarg, &getnext);
5803 	if (getnext
5804 	    && ((rettv->v_type == VAR_DICT && *p == '.' && eval_isdictc(p[1]))
5805 		|| (p[0] == '-' && p[1] == '>'
5806 				     && (p[2] == '{' || ASCII_ISALPHA(p[2])))))
5807 	{
5808 	    *arg = eval_next_line(evalarg);
5809 	    p = *arg;
5810 	    check_white = FALSE;
5811 	}
5812 
5813 	if (rettv->v_type == VAR_ANY)
5814 	{
5815 	    char_u	*exp_name;
5816 	    int		cc;
5817 	    int		idx;
5818 	    ufunc_T	*ufunc;
5819 	    type_T	*type;
5820 
5821 	    // Found script from "import * as {name}", script item name must
5822 	    // follow.
5823 	    if (**arg != '.')
5824 	    {
5825 		if (verbose)
5826 		    semsg(_(e_expected_str_but_got_str), "'.'", *arg);
5827 		ret = FAIL;
5828 		break;
5829 	    }
5830 	    ++*arg;
5831 	    if (IS_WHITE_OR_NUL(**arg))
5832 	    {
5833 		if (verbose)
5834 		    emsg(_(e_no_white_space_allowed_after_dot));
5835 		ret = FAIL;
5836 		break;
5837 	    }
5838 
5839 	    // isolate the name
5840 	    exp_name = *arg;
5841 	    while (eval_isnamec(**arg))
5842 		++*arg;
5843 	    cc = **arg;
5844 	    **arg = NUL;
5845 
5846 	    idx = find_exported(rettv->vval.v_number, exp_name, &ufunc, &type,
5847 						  evalarg->eval_cctx, verbose);
5848 	    **arg = cc;
5849 	    *arg = skipwhite(*arg);
5850 
5851 	    if (idx < 0 && ufunc == NULL)
5852 	    {
5853 		ret = FAIL;
5854 		break;
5855 	    }
5856 	    if (idx >= 0)
5857 	    {
5858 		scriptitem_T    *si = SCRIPT_ITEM(rettv->vval.v_number);
5859 		svar_T		*sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
5860 
5861 		copy_tv(sv->sv_tv, rettv);
5862 	    }
5863 	    else
5864 	    {
5865 		rettv->v_type = VAR_FUNC;
5866 		rettv->vval.v_string = vim_strsave(ufunc->uf_name);
5867 	    }
5868 	}
5869 
5870 	if ((**arg == '(' && (!evaluate || rettv->v_type == VAR_FUNC
5871 			    || rettv->v_type == VAR_PARTIAL))
5872 		    && (!check_white || !VIM_ISWHITE(*(*arg - 1))))
5873 	{
5874 	    ret = call_func_rettv(arg, evalarg, rettv, evaluate,
5875 							       selfdict, NULL);
5876 
5877 	    // Stop the expression evaluation when immediately aborting on
5878 	    // error, or when an interrupt occurred or an exception was thrown
5879 	    // but not caught.
5880 	    if (aborting())
5881 	    {
5882 		if (ret == OK)
5883 		    clear_tv(rettv);
5884 		ret = FAIL;
5885 	    }
5886 	    dict_unref(selfdict);
5887 	    selfdict = NULL;
5888 	}
5889 	else if (p[0] == '-' && p[1] == '>')
5890 	{
5891 	    *arg = skipwhite(p + 2);
5892 	    if (ret == OK)
5893 	    {
5894 		if ((**arg == '{' && !in_vim9script()) || **arg == '(')
5895 		    // expr->{lambda}() or expr->(lambda)()
5896 		    ret = eval_lambda(arg, rettv, evalarg, verbose);
5897 		else
5898 		    // expr->name()
5899 		    ret = eval_method(arg, rettv, evalarg, verbose);
5900 	    }
5901 	}
5902 	// "." is ".name" lookup when we found a dict or when evaluating and
5903 	// scriptversion is at least 2, where string concatenation is "..".
5904 	else if (**arg == '['
5905 		|| (**arg == '.' && (rettv->v_type == VAR_DICT
5906 			|| (!evaluate
5907 			    && (*arg)[1] != '.'
5908 			    && current_sctx.sc_version >= 2))))
5909 	{
5910 	    dict_unref(selfdict);
5911 	    if (rettv->v_type == VAR_DICT)
5912 	    {
5913 		selfdict = rettv->vval.v_dict;
5914 		if (selfdict != NULL)
5915 		    ++selfdict->dv_refcount;
5916 	    }
5917 	    else
5918 		selfdict = NULL;
5919 	    if (eval_index(arg, rettv, evalarg, verbose) == FAIL)
5920 	    {
5921 		clear_tv(rettv);
5922 		ret = FAIL;
5923 	    }
5924 	}
5925 	else
5926 	    break;
5927     }
5928 
5929     // Turn "dict.Func" into a partial for "Func" bound to "dict".
5930     // Don't do this when "Func" is already a partial that was bound
5931     // explicitly (pt_auto is FALSE).
5932     if (selfdict != NULL
5933 	    && (rettv->v_type == VAR_FUNC
5934 		|| (rettv->v_type == VAR_PARTIAL
5935 		    && (rettv->vval.v_partial->pt_auto
5936 			|| rettv->vval.v_partial->pt_dict == NULL))))
5937 	selfdict = make_partial(selfdict, rettv);
5938 
5939     dict_unref(selfdict);
5940     return ret;
5941 }
5942 
5943 /*
5944  * Make a copy of an item.
5945  * Lists and Dictionaries are also copied.  A deep copy if "deep" is set.
5946  * For deepcopy() "copyID" is zero for a full copy or the ID for when a
5947  * reference to an already copied list/dict can be used.
5948  * Returns FAIL or OK.
5949  */
5950     int
5951 item_copy(
5952     typval_T	*from,
5953     typval_T	*to,
5954     int		deep,
5955     int		copyID)
5956 {
5957     static int	recurse = 0;
5958     int		ret = OK;
5959 
5960     if (recurse >= DICT_MAXNEST)
5961     {
5962 	emsg(_("E698: variable nested too deep for making a copy"));
5963 	return FAIL;
5964     }
5965     ++recurse;
5966 
5967     switch (from->v_type)
5968     {
5969 	case VAR_NUMBER:
5970 	case VAR_FLOAT:
5971 	case VAR_STRING:
5972 	case VAR_FUNC:
5973 	case VAR_PARTIAL:
5974 	case VAR_BOOL:
5975 	case VAR_SPECIAL:
5976 	case VAR_JOB:
5977 	case VAR_CHANNEL:
5978 	    copy_tv(from, to);
5979 	    break;
5980 	case VAR_LIST:
5981 	    to->v_type = VAR_LIST;
5982 	    to->v_lock = 0;
5983 	    if (from->vval.v_list == NULL)
5984 		to->vval.v_list = NULL;
5985 	    else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
5986 	    {
5987 		// use the copy made earlier
5988 		to->vval.v_list = from->vval.v_list->lv_copylist;
5989 		++to->vval.v_list->lv_refcount;
5990 	    }
5991 	    else
5992 		to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
5993 	    if (to->vval.v_list == NULL)
5994 		ret = FAIL;
5995 	    break;
5996 	case VAR_BLOB:
5997 	    ret = blob_copy(from->vval.v_blob, to);
5998 	    break;
5999 	case VAR_DICT:
6000 	    to->v_type = VAR_DICT;
6001 	    to->v_lock = 0;
6002 	    if (from->vval.v_dict == NULL)
6003 		to->vval.v_dict = NULL;
6004 	    else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
6005 	    {
6006 		// use the copy made earlier
6007 		to->vval.v_dict = from->vval.v_dict->dv_copydict;
6008 		++to->vval.v_dict->dv_refcount;
6009 	    }
6010 	    else
6011 		to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
6012 	    if (to->vval.v_dict == NULL)
6013 		ret = FAIL;
6014 	    break;
6015 	case VAR_UNKNOWN:
6016 	case VAR_ANY:
6017 	case VAR_VOID:
6018 	    internal_error_no_abort("item_copy(UNKNOWN)");
6019 	    ret = FAIL;
6020     }
6021     --recurse;
6022     return ret;
6023 }
6024 
6025     void
6026 echo_one(typval_T *rettv, int with_space, int *atstart, int *needclr)
6027 {
6028     char_u	*tofree;
6029     char_u	numbuf[NUMBUFLEN];
6030     char_u	*p = echo_string(rettv, &tofree, numbuf, get_copyID());
6031 
6032     if (*atstart)
6033     {
6034 	*atstart = FALSE;
6035 	// Call msg_start() after eval1(), evaluating the expression
6036 	// may cause a message to appear.
6037 	if (with_space)
6038 	{
6039 	    // Mark the saved text as finishing the line, so that what
6040 	    // follows is displayed on a new line when scrolling back
6041 	    // at the more prompt.
6042 	    msg_sb_eol();
6043 	    msg_start();
6044 	}
6045     }
6046     else if (with_space)
6047 	msg_puts_attr(" ", echo_attr);
6048 
6049     if (p != NULL)
6050 	for ( ; *p != NUL && !got_int; ++p)
6051 	{
6052 	    if (*p == '\n' || *p == '\r' || *p == TAB)
6053 	    {
6054 		if (*p != TAB && *needclr)
6055 		{
6056 		    // remove any text still there from the command
6057 		    msg_clr_eos();
6058 		    *needclr = FALSE;
6059 		}
6060 		msg_putchar_attr(*p, echo_attr);
6061 	    }
6062 	    else
6063 	    {
6064 		if (has_mbyte)
6065 		{
6066 		    int i = (*mb_ptr2len)(p);
6067 
6068 		    (void)msg_outtrans_len_attr(p, i, echo_attr);
6069 		    p += i - 1;
6070 		}
6071 		else
6072 		    (void)msg_outtrans_len_attr(p, 1, echo_attr);
6073 	    }
6074 	}
6075     vim_free(tofree);
6076 }
6077 
6078 /*
6079  * ":echo expr1 ..."	print each argument separated with a space, add a
6080  *			newline at the end.
6081  * ":echon expr1 ..."	print each argument plain.
6082  */
6083     void
6084 ex_echo(exarg_T *eap)
6085 {
6086     char_u	*arg = eap->arg;
6087     typval_T	rettv;
6088     char_u	*p;
6089     int		needclr = TRUE;
6090     int		atstart = TRUE;
6091     int		did_emsg_before = did_emsg;
6092     int		called_emsg_before = called_emsg;
6093     evalarg_T	evalarg;
6094 
6095     fill_evalarg_from_eap(&evalarg, eap, eap->skip);
6096 
6097     if (eap->skip)
6098 	++emsg_skip;
6099     while ((!ends_excmd2(eap->cmd, arg) || *arg == '"') && !got_int)
6100     {
6101 	// If eval1() causes an error message the text from the command may
6102 	// still need to be cleared. E.g., "echo 22,44".
6103 	need_clr_eos = needclr;
6104 
6105 	p = arg;
6106 	if (eval1(&arg, &rettv, &evalarg) == FAIL)
6107 	{
6108 	    /*
6109 	     * Report the invalid expression unless the expression evaluation
6110 	     * has been cancelled due to an aborting error, an interrupt, or an
6111 	     * exception.
6112 	     */
6113 	    if (!aborting() && did_emsg == did_emsg_before
6114 					  && called_emsg == called_emsg_before)
6115 		semsg(_(e_invexpr2), p);
6116 	    need_clr_eos = FALSE;
6117 	    break;
6118 	}
6119 	need_clr_eos = FALSE;
6120 
6121 	if (!eap->skip)
6122 	    echo_one(&rettv, eap->cmdidx == CMD_echo, &atstart, &needclr);
6123 
6124 	clear_tv(&rettv);
6125 	arg = skipwhite(arg);
6126     }
6127     eap->nextcmd = check_nextcmd(arg);
6128     clear_evalarg(&evalarg, eap);
6129 
6130     if (eap->skip)
6131 	--emsg_skip;
6132     else
6133     {
6134 	// remove text that may still be there from the command
6135 	if (needclr)
6136 	    msg_clr_eos();
6137 	if (eap->cmdidx == CMD_echo)
6138 	    msg_end();
6139     }
6140 }
6141 
6142 /*
6143  * ":echohl {name}".
6144  */
6145     void
6146 ex_echohl(exarg_T *eap)
6147 {
6148     echo_attr = syn_name2attr(eap->arg);
6149 }
6150 
6151 /*
6152  * Returns the :echo attribute
6153  */
6154     int
6155 get_echo_attr(void)
6156 {
6157     return echo_attr;
6158 }
6159 
6160 /*
6161  * ":execute expr1 ..."	execute the result of an expression.
6162  * ":echomsg expr1 ..."	Print a message
6163  * ":echoerr expr1 ..."	Print an error
6164  * ":echoconsole expr1 ..." Print a message on stdout
6165  * Each gets spaces around each argument and a newline at the end for
6166  * echo commands
6167  */
6168     void
6169 ex_execute(exarg_T *eap)
6170 {
6171     char_u	*arg = eap->arg;
6172     typval_T	rettv;
6173     int		ret = OK;
6174     char_u	*p;
6175     garray_T	ga;
6176     int		len;
6177 
6178     ga_init2(&ga, 1, 80);
6179 
6180     if (eap->skip)
6181 	++emsg_skip;
6182     while (!ends_excmd2(eap->cmd, arg) || *arg == '"')
6183     {
6184 	ret = eval1_emsg(&arg, &rettv, eap);
6185 	if (ret == FAIL)
6186 	    break;
6187 
6188 	if (!eap->skip)
6189 	{
6190 	    char_u   buf[NUMBUFLEN];
6191 
6192 	    if (eap->cmdidx == CMD_execute)
6193 	    {
6194 		if (rettv.v_type == VAR_CHANNEL || rettv.v_type == VAR_JOB)
6195 		{
6196 		    emsg(_(e_inval_string));
6197 		    p = NULL;
6198 		}
6199 		else
6200 		    p = tv_get_string_buf(&rettv, buf);
6201 	    }
6202 	    else
6203 		p = tv_stringify(&rettv, buf);
6204 	    if (p == NULL)
6205 	    {
6206 		clear_tv(&rettv);
6207 		ret = FAIL;
6208 		break;
6209 	    }
6210 	    len = (int)STRLEN(p);
6211 	    if (ga_grow(&ga, len + 2) == FAIL)
6212 	    {
6213 		clear_tv(&rettv);
6214 		ret = FAIL;
6215 		break;
6216 	    }
6217 	    if (ga.ga_len)
6218 		((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
6219 	    STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
6220 	    ga.ga_len += len;
6221 	}
6222 
6223 	clear_tv(&rettv);
6224 	arg = skipwhite(arg);
6225     }
6226 
6227     if (ret != FAIL && ga.ga_data != NULL)
6228     {
6229 	if (eap->cmdidx == CMD_echomsg || eap->cmdidx == CMD_echoerr)
6230 	{
6231 	    // Mark the already saved text as finishing the line, so that what
6232 	    // follows is displayed on a new line when scrolling back at the
6233 	    // more prompt.
6234 	    msg_sb_eol();
6235 	}
6236 
6237 	if (eap->cmdidx == CMD_echomsg)
6238 	{
6239 	    msg_attr(ga.ga_data, echo_attr);
6240 	    out_flush();
6241 	}
6242 	else if (eap->cmdidx == CMD_echoconsole)
6243 	{
6244 	    ui_write(ga.ga_data, (int)STRLEN(ga.ga_data), TRUE);
6245 	    ui_write((char_u *)"\r\n", 2, TRUE);
6246 	}
6247 	else if (eap->cmdidx == CMD_echoerr)
6248 	{
6249 	    int		save_did_emsg = did_emsg;
6250 
6251 	    // We don't want to abort following commands, restore did_emsg.
6252 	    emsg(ga.ga_data);
6253 	    if (!force_abort)
6254 		did_emsg = save_did_emsg;
6255 	}
6256 	else if (eap->cmdidx == CMD_execute)
6257 	    do_cmdline((char_u *)ga.ga_data,
6258 		       eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
6259     }
6260 
6261     ga_clear(&ga);
6262 
6263     if (eap->skip)
6264 	--emsg_skip;
6265 
6266     eap->nextcmd = check_nextcmd(arg);
6267 }
6268 
6269 /*
6270  * Skip over the name of an option: "&option", "&g:option" or "&l:option".
6271  * "arg" points to the "&" or '+' when called, to "option" when returning.
6272  * Returns NULL when no option name found.  Otherwise pointer to the char
6273  * after the option name.
6274  */
6275     char_u *
6276 find_option_end(char_u **arg, int *opt_flags)
6277 {
6278     char_u	*p = *arg;
6279 
6280     ++p;
6281     if (*p == 'g' && p[1] == ':')
6282     {
6283 	*opt_flags = OPT_GLOBAL;
6284 	p += 2;
6285     }
6286     else if (*p == 'l' && p[1] == ':')
6287     {
6288 	*opt_flags = OPT_LOCAL;
6289 	p += 2;
6290     }
6291     else
6292 	*opt_flags = 0;
6293 
6294     if (!ASCII_ISALPHA(*p))
6295 	return NULL;
6296     *arg = p;
6297 
6298     if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
6299 	p += 4;	    // termcap option
6300     else
6301 	while (ASCII_ISALPHA(*p))
6302 	    ++p;
6303     return p;
6304 }
6305 
6306 /*
6307  * Display script name where an item was last set.
6308  * Should only be invoked when 'verbose' is non-zero.
6309  */
6310     void
6311 last_set_msg(sctx_T script_ctx)
6312 {
6313     char_u *p;
6314 
6315     if (script_ctx.sc_sid != 0)
6316     {
6317 	p = home_replace_save(NULL, get_scriptname(script_ctx.sc_sid));
6318 	if (p != NULL)
6319 	{
6320 	    verbose_enter();
6321 	    msg_puts(_("\n\tLast set from "));
6322 	    msg_puts((char *)p);
6323 	    if (script_ctx.sc_lnum > 0)
6324 	    {
6325 		msg_puts(_(line_msg));
6326 		msg_outnum((long)script_ctx.sc_lnum);
6327 	    }
6328 	    verbose_leave();
6329 	    vim_free(p);
6330 	}
6331     }
6332 }
6333 
6334 #endif // FEAT_EVAL
6335 
6336 /*
6337  * Perform a substitution on "str" with pattern "pat" and substitute "sub".
6338  * When "sub" is NULL "expr" is used, must be a VAR_FUNC or VAR_PARTIAL.
6339  * "flags" can be "g" to do a global substitute.
6340  * Returns an allocated string, NULL for error.
6341  */
6342     char_u *
6343 do_string_sub(
6344     char_u	*str,
6345     char_u	*pat,
6346     char_u	*sub,
6347     typval_T	*expr,
6348     char_u	*flags)
6349 {
6350     int		sublen;
6351     regmatch_T	regmatch;
6352     int		i;
6353     int		do_all;
6354     char_u	*tail;
6355     char_u	*end;
6356     garray_T	ga;
6357     char_u	*ret;
6358     char_u	*save_cpo;
6359     char_u	*zero_width = NULL;
6360 
6361     // Make 'cpoptions' empty, so that the 'l' flag doesn't work here
6362     save_cpo = p_cpo;
6363     p_cpo = empty_option;
6364 
6365     ga_init2(&ga, 1, 200);
6366 
6367     do_all = (flags[0] == 'g');
6368 
6369     regmatch.rm_ic = p_ic;
6370     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
6371     if (regmatch.regprog != NULL)
6372     {
6373 	tail = str;
6374 	end = str + STRLEN(str);
6375 	while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
6376 	{
6377 	    // Skip empty match except for first match.
6378 	    if (regmatch.startp[0] == regmatch.endp[0])
6379 	    {
6380 		if (zero_width == regmatch.startp[0])
6381 		{
6382 		    // avoid getting stuck on a match with an empty string
6383 		    i = mb_ptr2len(tail);
6384 		    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail,
6385 								   (size_t)i);
6386 		    ga.ga_len += i;
6387 		    tail += i;
6388 		    continue;
6389 		}
6390 		zero_width = regmatch.startp[0];
6391 	    }
6392 
6393 	    /*
6394 	     * Get some space for a temporary buffer to do the substitution
6395 	     * into.  It will contain:
6396 	     * - The text up to where the match is.
6397 	     * - The substituted text.
6398 	     * - The text after the match.
6399 	     */
6400 	    sublen = vim_regsub(&regmatch, sub, expr, tail, FALSE, TRUE, FALSE);
6401 	    if (ga_grow(&ga, (int)((end - tail) + sublen -
6402 			    (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
6403 	    {
6404 		ga_clear(&ga);
6405 		break;
6406 	    }
6407 
6408 	    // copy the text up to where the match is
6409 	    i = (int)(regmatch.startp[0] - tail);
6410 	    mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
6411 	    // add the substituted text
6412 	    (void)vim_regsub(&regmatch, sub, expr, (char_u *)ga.ga_data
6413 					  + ga.ga_len + i, TRUE, TRUE, FALSE);
6414 	    ga.ga_len += i + sublen - 1;
6415 	    tail = regmatch.endp[0];
6416 	    if (*tail == NUL)
6417 		break;
6418 	    if (!do_all)
6419 		break;
6420 	}
6421 
6422 	if (ga.ga_data != NULL)
6423 	    STRCPY((char *)ga.ga_data + ga.ga_len, tail);
6424 
6425 	vim_regfree(regmatch.regprog);
6426     }
6427 
6428     ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
6429     ga_clear(&ga);
6430     if (p_cpo == empty_option)
6431 	p_cpo = save_cpo;
6432     else
6433     {
6434 	// Darn, evaluating {sub} expression or {expr} changed the value.
6435 	// If it's still empty it was changed and restored, need to restore in
6436 	// the complicated way.
6437 	if (*p_cpo == NUL)
6438 	    set_option_value((char_u *)"cpo", 0L, save_cpo, 0);
6439 	free_string_option(save_cpo);
6440     }
6441 
6442     return ret;
6443 }
6444