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