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