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