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