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