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