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