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