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