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