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