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