xref: /vim-8.2.3635/src/vim9compile.c (revision 844fb64a)
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  * vim9compile.c: :def and dealing with instructions
12  */
13 
14 #define USING_FLOAT_STUFF
15 #include "vim.h"
16 
17 #if defined(FEAT_EVAL) || defined(PROTO)
18 
19 #ifdef VMS
20 # include <float.h>
21 #endif
22 
23 #define DEFINE_VIM9_GLOBALS
24 #include "vim9.h"
25 
26 // values for ctx_skip
27 typedef enum {
28     SKIP_NOT,		// condition is a constant, produce code
29     SKIP_YES,		// condition is a constant, do NOT produce code
30     SKIP_UNKNOWN	// condition is not a constant, produce code
31 } skip_T;
32 
33 /*
34  * Chain of jump instructions where the end label needs to be set.
35  */
36 typedef struct endlabel_S endlabel_T;
37 struct endlabel_S {
38     endlabel_T	*el_next;	    // chain end_label locations
39     int		el_end_label;	    // instruction idx where to set end
40 };
41 
42 /*
43  * info specific for the scope of :if / elseif / else
44  */
45 typedef struct {
46     int		is_seen_else;
47     int		is_seen_skip_not;   // a block was unconditionally executed
48     int		is_had_return;	    // every block ends in :return
49     int		is_if_label;	    // instruction idx at IF or ELSEIF
50     endlabel_T	*is_end_label;	    // instructions to set end label
51 } ifscope_T;
52 
53 /*
54  * info specific for the scope of :while
55  */
56 typedef struct {
57     int		ws_top_label;	    // instruction idx at WHILE
58     endlabel_T	*ws_end_label;	    // instructions to set end
59 } whilescope_T;
60 
61 /*
62  * info specific for the scope of :for
63  */
64 typedef struct {
65     int		fs_top_label;	    // instruction idx at FOR
66     endlabel_T	*fs_end_label;	    // break instructions
67 } forscope_T;
68 
69 /*
70  * info specific for the scope of :try
71  */
72 typedef struct {
73     int		ts_try_label;	    // instruction idx at TRY
74     endlabel_T	*ts_end_label;	    // jump to :finally or :endtry
75     int		ts_catch_label;	    // instruction idx of last CATCH
76     int		ts_caught_all;	    // "catch" without argument encountered
77 } tryscope_T;
78 
79 typedef enum {
80     NO_SCOPE,
81     IF_SCOPE,
82     WHILE_SCOPE,
83     FOR_SCOPE,
84     TRY_SCOPE,
85     BLOCK_SCOPE
86 } scopetype_T;
87 
88 /*
89  * Info for one scope, pointed to by "ctx_scope".
90  */
91 typedef struct scope_S scope_T;
92 struct scope_S {
93     scope_T	*se_outer;	    // scope containing this one
94     scopetype_T se_type;
95     int		se_local_count;	    // ctx_locals.ga_len before scope
96     skip_T	se_skip_save;	    // ctx_skip before the block
97     union {
98 	ifscope_T	se_if;
99 	whilescope_T	se_while;
100 	forscope_T	se_for;
101 	tryscope_T	se_try;
102     } se_u;
103 };
104 
105 /*
106  * Entry for "ctx_locals".  Used for arguments and local variables.
107  */
108 typedef struct {
109     char_u	*lv_name;
110     type_T	*lv_type;
111     int		lv_idx;		// index of the variable on the stack
112     int		lv_from_outer;	// nesting level, using ctx_outer scope
113     int		lv_const;	// when TRUE cannot be assigned to
114     int		lv_arg;		// when TRUE this is an argument
115 } lvar_T;
116 
117 // Destination for an assignment or ":unlet" with an index.
118 typedef enum {
119     dest_local,
120     dest_option,
121     dest_env,
122     dest_global,
123     dest_buffer,
124     dest_window,
125     dest_tab,
126     dest_vimvar,
127     dest_script,
128     dest_reg,
129     dest_expr,
130 } assign_dest_T;
131 
132 // Used by compile_lhs() to store information about the LHS of an assignment
133 // and one argument of ":unlet" with an index.
134 typedef struct {
135     assign_dest_T   lhs_dest;	    // type of destination
136 
137     char_u	    *lhs_name;	    // allocated name excluding the last
138 				    // "[expr]" or ".name".
139     size_t	    lhs_varlen;	    // length of the variable without
140 				    // "[expr]" or ".name"
141     char_u	    *lhs_whole;	    // allocated name including the last
142 				    // "[expr]" or ".name" for :redir
143     size_t	    lhs_varlen_total; // length of the variable including
144 				      // any "[expr]" or ".name"
145     char_u	    *lhs_dest_end;  // end of the destination, including
146 				    // "[expr]" or ".name".
147 
148     int		    lhs_has_index;  // has "[expr]" or ".name"
149 
150     int		    lhs_new_local;  // create new local variable
151     int		    lhs_opt_flags;  // for when destination is an option
152     int		    lhs_vimvaridx;  // for when destination is a v:var
153 
154     lvar_T	    lhs_local_lvar; // used for existing local destination
155     lvar_T	    lhs_arg_lvar;   // used for argument destination
156     lvar_T	    *lhs_lvar;	    // points to destination lvar
157     int		    lhs_scriptvar_sid;
158     int		    lhs_scriptvar_idx;
159 
160     int		    lhs_has_type;   // type was specified
161     type_T	    *lhs_type;
162     type_T	    *lhs_member_type;
163 
164     int		    lhs_append;	    // used by ISN_REDIREND
165 } lhs_T;
166 
167 /*
168  * Context for compiling lines of Vim script.
169  * Stores info about the local variables and condition stack.
170  */
171 struct cctx_S {
172     ufunc_T	*ctx_ufunc;	    // current function
173     int		ctx_lnum;	    // line number in current function
174     char_u	*ctx_line_start;    // start of current line or NULL
175     garray_T	ctx_instr;	    // generated instructions
176 
177     int		ctx_prev_lnum;	    // line number below previous command, for
178 				    // debugging
179 
180     compiletype_T ctx_compile_type;
181 
182     garray_T	ctx_locals;	    // currently visible local variables
183 
184     int		ctx_has_closure;    // set to one if a closures was created in
185 				    // the function
186 
187     garray_T	ctx_imports;	    // imported items
188 
189     skip_T	ctx_skip;
190     scope_T	*ctx_scope;	    // current scope, NULL at toplevel
191     int		ctx_had_return;	    // last seen statement was "return"
192 
193     cctx_T	*ctx_outer;	    // outer scope for lambda or nested
194 				    // function
195     int		ctx_outer_used;	    // var in ctx_outer was used
196 
197     garray_T	ctx_type_stack;	    // type of each item on the stack
198     garray_T	*ctx_type_list;	    // list of pointers to allocated types
199 
200     int		ctx_has_cmdmod;	    // ISN_CMDMOD was generated
201 
202     lhs_T	ctx_redir_lhs;	    // LHS for ":redir => var", valid when
203 				    // lhs_name is not NULL
204 };
205 
206 static void delete_def_function_contents(dfunc_T *dfunc, int mark_deleted);
207 
208 /*
209  * Lookup variable "name" in the local scope and return it in "lvar".
210  * "lvar->lv_from_outer" is incremented accordingly.
211  * If "lvar" is NULL only check if the variable can be found.
212  * Return FAIL if not found.
213  */
214     static int
lookup_local(char_u * name,size_t len,lvar_T * lvar,cctx_T * cctx)215 lookup_local(char_u *name, size_t len, lvar_T *lvar, cctx_T *cctx)
216 {
217     int	    idx;
218     lvar_T  *lvp;
219 
220     if (len == 0)
221 	return FAIL;
222 
223     // Find local in current function scope.
224     for (idx = 0; idx < cctx->ctx_locals.ga_len; ++idx)
225     {
226 	lvp = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
227 	if (STRNCMP(name, lvp->lv_name, len) == 0
228 					       && STRLEN(lvp->lv_name) == len)
229 	{
230 	    if (lvar != NULL)
231 	    {
232 		*lvar = *lvp;
233 		lvar->lv_from_outer = 0;
234 	    }
235 	    return OK;
236 	}
237     }
238 
239     // Find local in outer function scope.
240     if (cctx->ctx_outer != NULL)
241     {
242 	if (lookup_local(name, len, lvar, cctx->ctx_outer) == OK)
243 	{
244 	    if (lvar != NULL)
245 	    {
246 		cctx->ctx_outer_used = TRUE;
247 		++lvar->lv_from_outer;
248 	    }
249 	    return OK;
250 	}
251     }
252 
253     return FAIL;
254 }
255 
256 /*
257  * Lookup an argument in the current function and an enclosing function.
258  * Returns the argument index in "idxp"
259  * Returns the argument type in "type"
260  * Sets "gen_load_outer" to TRUE if found in outer scope.
261  * Returns OK when found, FAIL otherwise.
262  */
263     static int
arg_exists(char_u * name,size_t len,int * idxp,type_T ** type,int * gen_load_outer,cctx_T * cctx)264 arg_exists(
265 	char_u	*name,
266 	size_t	len,
267 	int	*idxp,
268 	type_T	**type,
269 	int	*gen_load_outer,
270 	cctx_T	*cctx)
271 {
272     int	    idx;
273     char_u  *va_name;
274 
275     if (len == 0)
276 	return FAIL;
277     for (idx = 0; idx < cctx->ctx_ufunc->uf_args_visible; ++idx)
278     {
279 	char_u *arg = FUNCARG(cctx->ctx_ufunc, idx);
280 
281 	if (STRNCMP(name, arg, len) == 0 && arg[len] == NUL)
282 	{
283 	    if (idxp != NULL)
284 	    {
285 		// Arguments are located above the frame pointer.  One further
286 		// if there is a vararg argument
287 		*idxp = idx - (cctx->ctx_ufunc->uf_args.ga_len
288 							    + STACK_FRAME_SIZE)
289 			      + (cctx->ctx_ufunc->uf_va_name != NULL ? -1 : 0);
290 
291 		if (cctx->ctx_ufunc->uf_arg_types != NULL)
292 		    *type = cctx->ctx_ufunc->uf_arg_types[idx];
293 		else
294 		    *type = &t_any;
295 	    }
296 	    return OK;
297 	}
298     }
299 
300     va_name = cctx->ctx_ufunc->uf_va_name;
301     if (va_name != NULL
302 		    && STRNCMP(name, va_name, len) == 0 && va_name[len] == NUL)
303     {
304 	if (idxp != NULL)
305 	{
306 	    // varargs is always the last argument
307 	    *idxp = -STACK_FRAME_SIZE - 1;
308 	    *type = cctx->ctx_ufunc->uf_va_type;
309 	}
310 	return OK;
311     }
312 
313     if (cctx->ctx_outer != NULL)
314     {
315 	// Lookup the name for an argument of the outer function.
316 	if (arg_exists(name, len, idxp, type, gen_load_outer, cctx->ctx_outer)
317 									 == OK)
318 	{
319 	    if (gen_load_outer != NULL)
320 		++*gen_load_outer;
321 	    return OK;
322 	}
323     }
324 
325     return FAIL;
326 }
327 
328 /*
329  * Lookup a script-local variable in the current script, possibly defined in a
330  * block that contains the function "cctx->ctx_ufunc".
331  * "cctx" is NULL at the script level.
332  * If "len" is <= 0 "name" must be NUL terminated.
333  * Return NULL when not found.
334  */
335     static sallvar_T *
find_script_var(char_u * name,size_t len,cctx_T * cctx)336 find_script_var(char_u *name, size_t len, cctx_T *cctx)
337 {
338     scriptitem_T    *si = SCRIPT_ITEM(current_sctx.sc_sid);
339     hashitem_T	    *hi;
340     int		    cc;
341     sallvar_T	    *sav;
342     sallvar_T	    *found_sav;
343     ufunc_T	    *ufunc;
344 
345     // Find the list of all script variables with the right name.
346     if (len > 0)
347     {
348 	cc = name[len];
349 	name[len] = NUL;
350     }
351     hi = hash_find(&si->sn_all_vars.dv_hashtab, name);
352     if (len > 0)
353 	name[len] = cc;
354     if (HASHITEM_EMPTY(hi))
355 	return NULL;
356 
357     sav = HI2SAV(hi);
358     if (sav->sav_block_id == 0)
359 	// variable defined in the top script scope is always visible
360 	return sav;
361 
362     if (cctx == NULL)
363     {
364 	// Not in a function scope, find variable with block id equal to or
365 	// smaller than the current block id.
366 	while (sav != NULL)
367 	{
368 	    if (sav->sav_block_id <= si->sn_current_block_id)
369 		break;
370 	    sav = sav->sav_next;
371 	}
372 	return sav;
373     }
374 
375     // Go over the variables with this name and find one that was visible
376     // from the function.
377     ufunc = cctx->ctx_ufunc;
378     found_sav = sav;
379     while (sav != NULL)
380     {
381 	int idx;
382 
383 	// Go over the blocks that this function was defined in.  If the
384 	// variable block ID matches it was visible to the function.
385 	for (idx = 0; idx < ufunc->uf_block_depth; ++idx)
386 	    if (ufunc->uf_block_ids[idx] == sav->sav_block_id)
387 		return sav;
388 	sav = sav->sav_next;
389     }
390 
391     // Not found, assume variable at script level was visible.
392     return found_sav;
393 }
394 
395 /*
396  * Return TRUE if the script context is Vim9 script.
397  */
398     static int
script_is_vim9()399 script_is_vim9()
400 {
401     return SCRIPT_ITEM(current_sctx.sc_sid)->sn_version == SCRIPT_VERSION_VIM9;
402 }
403 
404 /*
405  * Lookup a variable (without s: prefix) in the current script.
406  * "cctx" is NULL at the script level.
407  * Returns OK or FAIL.
408  */
409     static int
script_var_exists(char_u * name,size_t len,cctx_T * cctx)410 script_var_exists(char_u *name, size_t len, cctx_T *cctx)
411 {
412     if (current_sctx.sc_sid <= 0)
413 	return FAIL;
414     if (script_is_vim9())
415     {
416 	// Check script variables that were visible where the function was
417 	// defined.
418 	if (find_script_var(name, len, cctx) != NULL)
419 	    return OK;
420     }
421     else
422     {
423 	hashtab_T	*ht = &SCRIPT_VARS(current_sctx.sc_sid);
424 	dictitem_T	*di;
425 	int		cc;
426 
427 	// Check script variables that are currently visible
428 	cc = name[len];
429 	name[len] = NUL;
430 	di = find_var_in_ht(ht, 0, name, TRUE);
431 	name[len] = cc;
432 	if (di != NULL)
433 	    return OK;
434     }
435 
436     return FAIL;
437 }
438 
439 /*
440  * Return TRUE if "name" is a local variable, argument, script variable or
441  * imported.
442  */
443     static int
variable_exists(char_u * name,size_t len,cctx_T * cctx)444 variable_exists(char_u *name, size_t len, cctx_T *cctx)
445 {
446     return (cctx != NULL
447 		&& (lookup_local(name, len, NULL, cctx) == OK
448 		    || arg_exists(name, len, NULL, NULL, NULL, cctx) == OK))
449 	    || script_var_exists(name, len, cctx) == OK
450 	    || find_imported(name, len, cctx) != NULL;
451 }
452 
453 /*
454  * Return TRUE if "name" is a local variable, argument, script variable,
455  * imported or function.
456  */
457     static int
item_exists(char_u * name,size_t len,int cmd UNUSED,cctx_T * cctx)458 item_exists(char_u *name, size_t len, int cmd UNUSED, cctx_T *cctx)
459 {
460     int	    is_global;
461     char_u  *p;
462 
463     if (variable_exists(name, len, cctx))
464 	return TRUE;
465 
466     // This is similar to what is in lookup_scriptitem():
467     // Find a function, so that a following "->" works.
468     // Require "(" or "->" to follow, "Cmd" is a user command while "Cmd()" is
469     // a function call.
470     p = skipwhite(name + len);
471 
472     if (name[len] == '(' || (p[0] == '-' && p[1] == '>'))
473     {
474 	// Do not check for an internal function, since it might also be a
475 	// valid command, such as ":split" versus "split()".
476 	// Skip "g:" before a function name.
477 	is_global = (name[0] == 'g' && name[1] == ':');
478 	return find_func(is_global ? name + 2 : name, is_global, cctx) != NULL;
479     }
480     return FALSE;
481 }
482 
483 /*
484  * Check if "p[len]" is already defined, either in script "import_sid" or in
485  * compilation context "cctx".  "cctx" is NULL at the script level.
486  * Does not check the global namespace.
487  * If "is_arg" is TRUE the error message is for an argument name.
488  * Return FAIL and give an error if it defined.
489  */
490     int
check_defined(char_u * p,size_t len,cctx_T * cctx,int is_arg)491 check_defined(char_u *p, size_t len, cctx_T *cctx, int is_arg)
492 {
493     int		c = p[len];
494     ufunc_T	*ufunc = NULL;
495 
496     // underscore argument is OK
497     if (len == 1 && *p == '_')
498 	return OK;
499 
500     if (script_var_exists(p, len, cctx) == OK)
501     {
502 	if (is_arg)
503 	    semsg(_(e_argument_already_declared_in_script_str), p);
504 	else
505 	    semsg(_(e_variable_already_declared_in_script_str), p);
506 	return FAIL;
507     }
508 
509     p[len] = NUL;
510     if ((cctx != NULL
511 		&& (lookup_local(p, len, NULL, cctx) == OK
512 		    || arg_exists(p, len, NULL, NULL, NULL, cctx) == OK))
513 	    || find_imported(p, len, cctx) != NULL
514 	    || (ufunc = find_func_even_dead(p, FALSE, cctx)) != NULL)
515     {
516 	// A local or script-local function can shadow a global function.
517 	if (ufunc == NULL || ((ufunc->uf_flags & FC_DEAD) == 0
518 		    && (!func_is_global(ufunc)
519 					     || (p[0] == 'g' && p[1] == ':'))))
520 	{
521 	    if (is_arg)
522 		semsg(_(e_argument_name_shadows_existing_variable_str), p);
523 	    else
524 		semsg(_(e_name_already_defined_str), p);
525 	    p[len] = c;
526 	    return FAIL;
527 	}
528     }
529     p[len] = c;
530     return OK;
531 }
532 
533 
534 /////////////////////////////////////////////////////////////////////
535 // Following generate_ functions expect the caller to call ga_grow().
536 
537 #define RETURN_NULL_IF_SKIP(cctx) if (cctx->ctx_skip == SKIP_YES) return NULL
538 #define RETURN_OK_IF_SKIP(cctx) if (cctx->ctx_skip == SKIP_YES) return OK
539 
540 /*
541  * Generate an instruction without arguments.
542  * Returns a pointer to the new instruction, NULL if failed.
543  */
544     static isn_T *
generate_instr(cctx_T * cctx,isntype_T isn_type)545 generate_instr(cctx_T *cctx, isntype_T isn_type)
546 {
547     garray_T	*instr = &cctx->ctx_instr;
548     isn_T	*isn;
549 
550     RETURN_NULL_IF_SKIP(cctx);
551     if (GA_GROW_FAILS(instr, 1))
552 	return NULL;
553     isn = ((isn_T *)instr->ga_data) + instr->ga_len;
554     isn->isn_type = isn_type;
555     isn->isn_lnum = cctx->ctx_lnum + 1;
556     ++instr->ga_len;
557 
558     return isn;
559 }
560 
561 /*
562  * Generate an instruction without arguments.
563  * "drop" will be removed from the stack.
564  * Returns a pointer to the new instruction, NULL if failed.
565  */
566     static isn_T *
generate_instr_drop(cctx_T * cctx,isntype_T isn_type,int drop)567 generate_instr_drop(cctx_T *cctx, isntype_T isn_type, int drop)
568 {
569     garray_T	*stack = &cctx->ctx_type_stack;
570 
571     RETURN_NULL_IF_SKIP(cctx);
572     stack->ga_len -= drop;
573     return generate_instr(cctx, isn_type);
574 }
575 
576 /*
577  * Generate instruction "isn_type" and put "type" on the type stack.
578  */
579     static isn_T *
generate_instr_type(cctx_T * cctx,isntype_T isn_type,type_T * type)580 generate_instr_type(cctx_T *cctx, isntype_T isn_type, type_T *type)
581 {
582     isn_T	*isn;
583     garray_T	*stack = &cctx->ctx_type_stack;
584 
585     if ((isn = generate_instr(cctx, isn_type)) == NULL)
586 	return NULL;
587 
588     if (GA_GROW_FAILS(stack, 1))
589 	return NULL;
590     ((type_T **)stack->ga_data)[stack->ga_len] = type == NULL ? &t_any : type;
591     ++stack->ga_len;
592 
593     return isn;
594 }
595 
596 /*
597  * Generate an ISN_DEBUG instruction.
598  */
599     static isn_T *
generate_instr_debug(cctx_T * cctx)600 generate_instr_debug(cctx_T *cctx)
601 {
602     isn_T	*isn;
603     dfunc_T	*dfunc = ((dfunc_T *)def_functions.ga_data)
604 					       + cctx->ctx_ufunc->uf_dfunc_idx;
605 
606     if ((isn = generate_instr(cctx, ISN_DEBUG)) == NULL)
607 	return NULL;
608     isn->isn_arg.debug.dbg_var_names_len = dfunc->df_var_names.ga_len;
609     isn->isn_arg.debug.dbg_break_lnum = cctx->ctx_prev_lnum;
610     return isn;
611 }
612 
613 /*
614  * If type at "offset" isn't already VAR_STRING then generate ISN_2STRING.
615  * But only for simple types.
616  * When "tolerant" is TRUE convert most types to string, e.g. a List.
617  */
618     static int
may_generate_2STRING(int offset,int tolerant,cctx_T * cctx)619 may_generate_2STRING(int offset, int tolerant, cctx_T *cctx)
620 {
621     isn_T	*isn;
622     isntype_T	isntype = ISN_2STRING;
623     garray_T	*stack = &cctx->ctx_type_stack;
624     type_T	**type;
625 
626     RETURN_OK_IF_SKIP(cctx);
627     type = ((type_T **)stack->ga_data) + stack->ga_len + offset;
628     switch ((*type)->tt_type)
629     {
630 	// nothing to be done
631 	case VAR_STRING: return OK;
632 
633 	// conversion possible
634 	case VAR_SPECIAL:
635 	case VAR_BOOL:
636 	case VAR_NUMBER:
637 	case VAR_FLOAT:
638 			 break;
639 
640 	// conversion possible (with runtime check)
641 	case VAR_ANY:
642 	case VAR_UNKNOWN:
643 			 isntype = ISN_2STRING_ANY;
644 			 break;
645 
646 	// conversion possible when tolerant
647 	case VAR_LIST:
648 			 if (tolerant)
649 			 {
650 			     isntype = ISN_2STRING_ANY;
651 			     break;
652 			 }
653 			 // FALLTHROUGH
654 
655 	// conversion not possible
656 	case VAR_VOID:
657 	case VAR_BLOB:
658 	case VAR_FUNC:
659 	case VAR_PARTIAL:
660 	case VAR_DICT:
661 	case VAR_JOB:
662 	case VAR_CHANNEL:
663 	case VAR_INSTR:
664 			 to_string_error((*type)->tt_type);
665 			 return FAIL;
666     }
667 
668     *type = &t_string;
669     if ((isn = generate_instr(cctx, isntype)) == NULL)
670 	return FAIL;
671     isn->isn_arg.tostring.offset = offset;
672     isn->isn_arg.tostring.tolerant = tolerant;
673 
674     return OK;
675 }
676 
677     static int
check_number_or_float(vartype_T type1,vartype_T type2,char_u * op)678 check_number_or_float(vartype_T type1, vartype_T type2, char_u *op)
679 {
680     if (!((type1 == VAR_NUMBER || type1 == VAR_FLOAT || type1 == VAR_ANY)
681 	    && (type2 == VAR_NUMBER || type2 == VAR_FLOAT
682 							 || type2 == VAR_ANY)))
683     {
684 	if (*op == '+')
685 	    emsg(_(e_wrong_argument_type_for_plus));
686 	else
687 	    semsg(_(e_char_requires_number_or_float_arguments), *op);
688 	return FAIL;
689     }
690     return OK;
691 }
692 
693 /*
694  * Generate instruction for "+".  For a list this creates a new list.
695  */
696     static int
generate_add_instr(cctx_T * cctx,vartype_T vartype,type_T * type1,type_T * type2,exprtype_T expr_type)697 generate_add_instr(
698 	cctx_T *cctx,
699 	vartype_T vartype,
700 	type_T *type1,
701 	type_T *type2,
702 	exprtype_T expr_type)
703 {
704     garray_T	*stack = &cctx->ctx_type_stack;
705     isn_T	*isn = generate_instr_drop(cctx,
706 		      vartype == VAR_NUMBER ? ISN_OPNR
707 		    : vartype == VAR_LIST ? ISN_ADDLIST
708 		    : vartype == VAR_BLOB ? ISN_ADDBLOB
709 #ifdef FEAT_FLOAT
710 		    : vartype == VAR_FLOAT ? ISN_OPFLOAT
711 #endif
712 		    : ISN_OPANY, 1);
713 
714     if (vartype != VAR_LIST && vartype != VAR_BLOB
715 	    && type1->tt_type != VAR_ANY
716 	    && type2->tt_type != VAR_ANY
717 	    && check_number_or_float(
718 			type1->tt_type, type2->tt_type, (char_u *)"+") == FAIL)
719 	return FAIL;
720 
721     if (isn != NULL)
722     {
723 	if (isn->isn_type == ISN_ADDLIST)
724 	    isn->isn_arg.op.op_type = expr_type;
725 	else
726 	    isn->isn_arg.op.op_type = EXPR_ADD;
727     }
728 
729     // When concatenating two lists with different member types the member type
730     // becomes "any".
731     if (vartype == VAR_LIST
732 	    && type1->tt_type == VAR_LIST && type2->tt_type == VAR_LIST
733 	    && type1->tt_member != type2->tt_member)
734 	(((type_T **)stack->ga_data)[stack->ga_len - 1]) = &t_list_any;
735 
736     return isn == NULL ? FAIL : OK;
737 }
738 
739 /*
740  * Get the type to use for an instruction for an operation on "type1" and
741  * "type2".  If they are matching use a type-specific instruction. Otherwise
742  * fall back to runtime type checking.
743  */
744     static vartype_T
operator_type(type_T * type1,type_T * type2)745 operator_type(type_T *type1, type_T *type2)
746 {
747     if (type1->tt_type == type2->tt_type
748 	    && (type1->tt_type == VAR_NUMBER
749 		|| type1->tt_type == VAR_LIST
750 #ifdef FEAT_FLOAT
751 		|| type1->tt_type == VAR_FLOAT
752 #endif
753 		|| type1->tt_type == VAR_BLOB))
754 	return type1->tt_type;
755     return VAR_ANY;
756 }
757 
758 /*
759  * Generate an instruction with two arguments.  The instruction depends on the
760  * type of the arguments.
761  */
762     static int
generate_two_op(cctx_T * cctx,char_u * op)763 generate_two_op(cctx_T *cctx, char_u *op)
764 {
765     garray_T	*stack = &cctx->ctx_type_stack;
766     type_T	*type1;
767     type_T	*type2;
768     vartype_T	vartype;
769     isn_T	*isn;
770 
771     RETURN_OK_IF_SKIP(cctx);
772 
773     // Get the known type of the two items on the stack.
774     type1 = ((type_T **)stack->ga_data)[stack->ga_len - 2];
775     type2 = ((type_T **)stack->ga_data)[stack->ga_len - 1];
776     vartype = operator_type(type1, type2);
777 
778     switch (*op)
779     {
780 	case '+':
781 		  if (generate_add_instr(cctx, vartype, type1, type2,
782 							    EXPR_COPY) == FAIL)
783 		      return FAIL;
784 		  break;
785 
786 	case '-':
787 	case '*':
788 	case '/': if (check_number_or_float(type1->tt_type, type2->tt_type,
789 								   op) == FAIL)
790 		      return FAIL;
791 		  if (vartype == VAR_NUMBER)
792 		      isn = generate_instr_drop(cctx, ISN_OPNR, 1);
793 #ifdef FEAT_FLOAT
794 		  else if (vartype == VAR_FLOAT)
795 		      isn = generate_instr_drop(cctx, ISN_OPFLOAT, 1);
796 #endif
797 		  else
798 		      isn = generate_instr_drop(cctx, ISN_OPANY, 1);
799 		  if (isn != NULL)
800 		      isn->isn_arg.op.op_type = *op == '*'
801 				 ? EXPR_MULT : *op == '/'? EXPR_DIV : EXPR_SUB;
802 		  break;
803 
804 	case '%': if ((type1->tt_type != VAR_ANY
805 					       && type1->tt_type != VAR_NUMBER)
806 			  || (type2->tt_type != VAR_ANY
807 					      && type2->tt_type != VAR_NUMBER))
808 		  {
809 		      emsg(_(e_percent_requires_number_arguments));
810 		      return FAIL;
811 		  }
812 		  isn = generate_instr_drop(cctx,
813 			      vartype == VAR_NUMBER ? ISN_OPNR : ISN_OPANY, 1);
814 		  if (isn != NULL)
815 		      isn->isn_arg.op.op_type = EXPR_REM;
816 		  break;
817     }
818 
819     // correct type of result
820     if (vartype == VAR_ANY)
821     {
822 	type_T *type = &t_any;
823 
824 #ifdef FEAT_FLOAT
825 	// float+number and number+float results in float
826 	if ((type1->tt_type == VAR_NUMBER || type1->tt_type == VAR_FLOAT)
827 		&& (type2->tt_type == VAR_NUMBER || type2->tt_type == VAR_FLOAT))
828 	    type = &t_float;
829 #endif
830 	((type_T **)stack->ga_data)[stack->ga_len - 1] = type;
831     }
832 
833     return OK;
834 }
835 
836 /*
837  * Get the instruction to use for comparing "type1" with "type2"
838  * Return ISN_DROP when failed.
839  */
840     static isntype_T
get_compare_isn(exprtype_T exprtype,vartype_T type1,vartype_T type2)841 get_compare_isn(exprtype_T exprtype, vartype_T type1, vartype_T type2)
842 {
843     isntype_T	isntype = ISN_DROP;
844 
845     if (type1 == VAR_UNKNOWN)
846 	type1 = VAR_ANY;
847     if (type2 == VAR_UNKNOWN)
848 	type2 = VAR_ANY;
849 
850     if (type1 == type2)
851     {
852 	switch (type1)
853 	{
854 	    case VAR_BOOL: isntype = ISN_COMPAREBOOL; break;
855 	    case VAR_SPECIAL: isntype = ISN_COMPARESPECIAL; break;
856 	    case VAR_NUMBER: isntype = ISN_COMPARENR; break;
857 	    case VAR_FLOAT: isntype = ISN_COMPAREFLOAT; break;
858 	    case VAR_STRING: isntype = ISN_COMPARESTRING; break;
859 	    case VAR_BLOB: isntype = ISN_COMPAREBLOB; break;
860 	    case VAR_LIST: isntype = ISN_COMPARELIST; break;
861 	    case VAR_DICT: isntype = ISN_COMPAREDICT; break;
862 	    case VAR_FUNC: isntype = ISN_COMPAREFUNC; break;
863 	    default: isntype = ISN_COMPAREANY; break;
864 	}
865     }
866     else if (type1 == VAR_ANY || type2 == VAR_ANY
867 	    || ((type1 == VAR_NUMBER || type1 == VAR_FLOAT)
868 	      && (type2 == VAR_NUMBER || type2 == VAR_FLOAT)))
869 	isntype = ISN_COMPAREANY;
870 
871     if ((exprtype == EXPR_IS || exprtype == EXPR_ISNOT)
872 	    && (isntype == ISN_COMPAREBOOL
873 	    || isntype == ISN_COMPARESPECIAL
874 	    || isntype == ISN_COMPARENR
875 	    || isntype == ISN_COMPAREFLOAT))
876     {
877 	semsg(_(e_cannot_use_str_with_str),
878 		exprtype == EXPR_IS ? "is" : "isnot" , vartype_name(type1));
879 	return ISN_DROP;
880     }
881     if (isntype == ISN_DROP
882 	    || ((exprtype != EXPR_EQUAL && exprtype != EXPR_NEQUAL
883 		    && (type1 == VAR_BOOL || type1 == VAR_SPECIAL
884 		       || type2 == VAR_BOOL || type2 == VAR_SPECIAL)))
885 	    || ((exprtype != EXPR_EQUAL && exprtype != EXPR_NEQUAL
886 				 && exprtype != EXPR_IS && exprtype != EXPR_ISNOT
887 		    && (type1 == VAR_BLOB || type2 == VAR_BLOB
888 			|| type1 == VAR_LIST || type2 == VAR_LIST))))
889     {
890 	semsg(_(e_cannot_compare_str_with_str),
891 		vartype_name(type1), vartype_name(type2));
892 	return ISN_DROP;
893     }
894     return isntype;
895 }
896 
897     int
check_compare_types(exprtype_T type,typval_T * tv1,typval_T * tv2)898 check_compare_types(exprtype_T type, typval_T *tv1, typval_T *tv2)
899 {
900     if (get_compare_isn(type, tv1->v_type, tv2->v_type) == ISN_DROP)
901 	return FAIL;
902     return OK;
903 }
904 
905 /*
906  * Generate an ISN_COMPARE* instruction with a boolean result.
907  */
908     static int
generate_COMPARE(cctx_T * cctx,exprtype_T exprtype,int ic)909 generate_COMPARE(cctx_T *cctx, exprtype_T exprtype, int ic)
910 {
911     isntype_T	isntype;
912     isn_T	*isn;
913     garray_T	*stack = &cctx->ctx_type_stack;
914     vartype_T	type1;
915     vartype_T	type2;
916 
917     RETURN_OK_IF_SKIP(cctx);
918 
919     // Get the known type of the two items on the stack.  If they are matching
920     // use a type-specific instruction. Otherwise fall back to runtime type
921     // checking.
922     type1 = ((type_T **)stack->ga_data)[stack->ga_len - 2]->tt_type;
923     type2 = ((type_T **)stack->ga_data)[stack->ga_len - 1]->tt_type;
924     isntype = get_compare_isn(exprtype, type1, type2);
925     if (isntype == ISN_DROP)
926 	return FAIL;
927 
928     if ((isn = generate_instr(cctx, isntype)) == NULL)
929 	return FAIL;
930     isn->isn_arg.op.op_type = exprtype;
931     isn->isn_arg.op.op_ic = ic;
932 
933     // takes two arguments, puts one bool back
934     if (stack->ga_len >= 2)
935     {
936 	--stack->ga_len;
937 	((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_bool;
938     }
939 
940     return OK;
941 }
942 
943 /*
944  * Generate an ISN_2BOOL instruction.
945  * "offset" is the offset in the type stack.
946  */
947     static int
generate_2BOOL(cctx_T * cctx,int invert,int offset)948 generate_2BOOL(cctx_T *cctx, int invert, int offset)
949 {
950     isn_T	*isn;
951     garray_T	*stack = &cctx->ctx_type_stack;
952 
953     RETURN_OK_IF_SKIP(cctx);
954     if ((isn = generate_instr(cctx, ISN_2BOOL)) == NULL)
955 	return FAIL;
956     isn->isn_arg.tobool.invert = invert;
957     isn->isn_arg.tobool.offset = offset;
958 
959     // type becomes bool
960     ((type_T **)stack->ga_data)[stack->ga_len + offset] = &t_bool;
961 
962     return OK;
963 }
964 
965 /*
966  * Generate an ISN_COND2BOOL instruction.
967  */
968     static int
generate_COND2BOOL(cctx_T * cctx)969 generate_COND2BOOL(cctx_T *cctx)
970 {
971     isn_T	*isn;
972     garray_T	*stack = &cctx->ctx_type_stack;
973 
974     RETURN_OK_IF_SKIP(cctx);
975     if ((isn = generate_instr(cctx, ISN_COND2BOOL)) == NULL)
976 	return FAIL;
977 
978     // type becomes bool
979     ((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_bool;
980 
981     return OK;
982 }
983 
984     static int
generate_TYPECHECK(cctx_T * cctx,type_T * expected,int offset,int argidx)985 generate_TYPECHECK(
986 	cctx_T	    *cctx,
987 	type_T	    *expected,
988 	int	    offset,
989 	int	    argidx)
990 {
991     isn_T	*isn;
992     garray_T	*stack = &cctx->ctx_type_stack;
993 
994     RETURN_OK_IF_SKIP(cctx);
995     if ((isn = generate_instr(cctx, ISN_CHECKTYPE)) == NULL)
996 	return FAIL;
997     isn->isn_arg.type.ct_type = alloc_type(expected);
998     isn->isn_arg.type.ct_off = (int8_T)offset;
999     isn->isn_arg.type.ct_arg_idx = (int8_T)argidx;
1000 
1001     // type becomes expected
1002     ((type_T **)stack->ga_data)[stack->ga_len + offset] = expected;
1003 
1004     return OK;
1005 }
1006 
1007     static int
generate_SETTYPE(cctx_T * cctx,type_T * expected)1008 generate_SETTYPE(
1009 	cctx_T	    *cctx,
1010 	type_T	    *expected)
1011 {
1012     isn_T	*isn;
1013 
1014     RETURN_OK_IF_SKIP(cctx);
1015     if ((isn = generate_instr(cctx, ISN_SETTYPE)) == NULL)
1016 	return FAIL;
1017     isn->isn_arg.type.ct_type = alloc_type(expected);
1018     return OK;
1019 }
1020 
1021 /*
1022  * Return TRUE if "actual" could be "expected" and a runtime typecheck is to be
1023  * used.  Return FALSE if the types will never match.
1024  */
1025     static int
use_typecheck(type_T * actual,type_T * expected)1026 use_typecheck(type_T *actual, type_T *expected)
1027 {
1028     if (actual->tt_type == VAR_ANY
1029 	    || actual->tt_type == VAR_UNKNOWN
1030 	    || (actual->tt_type == VAR_FUNC
1031 		&& (expected->tt_type == VAR_FUNC
1032 					   || expected->tt_type == VAR_PARTIAL)
1033 		&& (actual->tt_member == &t_any || actual->tt_argcount < 0)
1034 		&& ((actual->tt_member == &t_void)
1035 					 == (expected->tt_member == &t_void))))
1036 	return TRUE;
1037     if ((actual->tt_type == VAR_LIST || actual->tt_type == VAR_DICT)
1038 				       && actual->tt_type == expected->tt_type)
1039 	// This takes care of a nested list or dict.
1040 	return use_typecheck(actual->tt_member, expected->tt_member);
1041     return FALSE;
1042 }
1043 
1044 /*
1045  * Check that
1046  * - "actual" matches "expected" type or
1047  * - "actual" is a type that can be "expected" type: add a runtime check; or
1048  * - return FAIL.
1049  * If "actual_is_const" is TRUE then the type won't change at runtime, do not
1050  * generate a TYPECHECK.
1051  */
1052     static int
need_type_where(type_T * actual,type_T * expected,int offset,where_T where,cctx_T * cctx,int silent,int actual_is_const)1053 need_type_where(
1054 	type_T	*actual,
1055 	type_T	*expected,
1056 	int	offset,
1057 	where_T	where,
1058 	cctx_T	*cctx,
1059 	int	silent,
1060 	int	actual_is_const)
1061 {
1062     if (expected == &t_bool && actual != &t_bool
1063 					&& (actual->tt_flags & TTFLAG_BOOL_OK))
1064     {
1065 	// Using "0", "1" or the result of an expression with "&&" or "||" as a
1066 	// boolean is OK but requires a conversion.
1067 	generate_2BOOL(cctx, FALSE, offset);
1068 	return OK;
1069     }
1070 
1071     if (check_type(expected, actual, FALSE, where) == OK)
1072 	return OK;
1073 
1074     // If the actual type can be the expected type add a runtime check.
1075     // If it's a constant a runtime check makes no sense.
1076     if ((!actual_is_const || actual == &t_any)
1077 					    && use_typecheck(actual, expected))
1078     {
1079 	generate_TYPECHECK(cctx, expected, offset, where.wt_index);
1080 	return OK;
1081     }
1082 
1083     if (!silent)
1084 	type_mismatch_where(expected, actual, where);
1085     return FAIL;
1086 }
1087 
1088     int
need_type(type_T * actual,type_T * expected,int offset,int arg_idx,cctx_T * cctx,int silent,int actual_is_const)1089 need_type(
1090 	type_T	*actual,
1091 	type_T	*expected,
1092 	int	offset,
1093 	int	arg_idx,
1094 	cctx_T	*cctx,
1095 	int	silent,
1096 	int	actual_is_const)
1097 {
1098     where_T where = WHERE_INIT;
1099 
1100     where.wt_index = arg_idx;
1101     return need_type_where(actual, expected, offset, where,
1102 						cctx, silent, actual_is_const);
1103 }
1104 
1105 /*
1106  * Check that the top of the type stack has a type that can be used as a
1107  * condition.  Give an error and return FAIL if not.
1108  */
1109     static int
bool_on_stack(cctx_T * cctx)1110 bool_on_stack(cctx_T *cctx)
1111 {
1112     garray_T	*stack = &cctx->ctx_type_stack;
1113     type_T	*type;
1114 
1115     type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
1116     if (type == &t_bool)
1117 	return OK;
1118 
1119     if (type == &t_any || type == &t_number || type == &t_number_bool)
1120 	// Number 0 and 1 are OK to use as a bool.  "any" could also be a bool.
1121 	// This requires a runtime type check.
1122 	return generate_COND2BOOL(cctx);
1123 
1124     return need_type(type, &t_bool, -1, 0, cctx, FALSE, FALSE);
1125 }
1126 
1127 /*
1128  * Generate an ISN_PUSHNR instruction.
1129  */
1130     static int
generate_PUSHNR(cctx_T * cctx,varnumber_T number)1131 generate_PUSHNR(cctx_T *cctx, varnumber_T number)
1132 {
1133     isn_T	*isn;
1134     garray_T	*stack = &cctx->ctx_type_stack;
1135 
1136     RETURN_OK_IF_SKIP(cctx);
1137     if ((isn = generate_instr_type(cctx, ISN_PUSHNR, &t_number)) == NULL)
1138 	return FAIL;
1139     isn->isn_arg.number = number;
1140 
1141     if (number == 0 || number == 1)
1142 	// A 0 or 1 number can also be used as a bool.
1143 	((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_number_bool;
1144     return OK;
1145 }
1146 
1147 /*
1148  * Generate an ISN_PUSHBOOL instruction.
1149  */
1150     static int
generate_PUSHBOOL(cctx_T * cctx,varnumber_T number)1151 generate_PUSHBOOL(cctx_T *cctx, varnumber_T number)
1152 {
1153     isn_T	*isn;
1154 
1155     RETURN_OK_IF_SKIP(cctx);
1156     if ((isn = generate_instr_type(cctx, ISN_PUSHBOOL, &t_bool)) == NULL)
1157 	return FAIL;
1158     isn->isn_arg.number = number;
1159 
1160     return OK;
1161 }
1162 
1163 /*
1164  * Generate an ISN_PUSHSPEC instruction.
1165  */
1166     static int
generate_PUSHSPEC(cctx_T * cctx,varnumber_T number)1167 generate_PUSHSPEC(cctx_T *cctx, varnumber_T number)
1168 {
1169     isn_T	*isn;
1170 
1171     RETURN_OK_IF_SKIP(cctx);
1172     if ((isn = generate_instr_type(cctx, ISN_PUSHSPEC, &t_special)) == NULL)
1173 	return FAIL;
1174     isn->isn_arg.number = number;
1175 
1176     return OK;
1177 }
1178 
1179 #ifdef FEAT_FLOAT
1180 /*
1181  * Generate an ISN_PUSHF instruction.
1182  */
1183     static int
generate_PUSHF(cctx_T * cctx,float_T fnumber)1184 generate_PUSHF(cctx_T *cctx, float_T fnumber)
1185 {
1186     isn_T	*isn;
1187 
1188     RETURN_OK_IF_SKIP(cctx);
1189     if ((isn = generate_instr_type(cctx, ISN_PUSHF, &t_float)) == NULL)
1190 	return FAIL;
1191     isn->isn_arg.fnumber = fnumber;
1192 
1193     return OK;
1194 }
1195 #endif
1196 
1197 /*
1198  * Generate an ISN_PUSHS instruction.
1199  * Consumes "*str".  When freed *str is set to NULL, unless "str" is NULL.
1200  */
1201     static int
generate_PUSHS(cctx_T * cctx,char_u ** str)1202 generate_PUSHS(cctx_T *cctx, char_u **str)
1203 {
1204     isn_T	*isn;
1205 
1206     if (cctx->ctx_skip == SKIP_YES)
1207     {
1208 	if (str != NULL)
1209 	    VIM_CLEAR(*str);
1210 	return OK;
1211     }
1212     if ((isn = generate_instr_type(cctx, ISN_PUSHS, &t_string)) == NULL)
1213     {
1214 	if (str != NULL)
1215 	    VIM_CLEAR(*str);
1216 	return FAIL;
1217     }
1218     isn->isn_arg.string = str == NULL ? NULL : *str;
1219 
1220     return OK;
1221 }
1222 
1223 /*
1224  * Generate an ISN_PUSHCHANNEL instruction.
1225  * Consumes "channel".
1226  */
1227     static int
generate_PUSHCHANNEL(cctx_T * cctx,channel_T * channel)1228 generate_PUSHCHANNEL(cctx_T *cctx, channel_T *channel)
1229 {
1230     isn_T	*isn;
1231 
1232     RETURN_OK_IF_SKIP(cctx);
1233     if ((isn = generate_instr_type(cctx, ISN_PUSHCHANNEL, &t_channel)) == NULL)
1234 	return FAIL;
1235     isn->isn_arg.channel = channel;
1236 
1237     return OK;
1238 }
1239 
1240 /*
1241  * Generate an ISN_PUSHJOB instruction.
1242  * Consumes "job".
1243  */
1244     static int
generate_PUSHJOB(cctx_T * cctx,job_T * job)1245 generate_PUSHJOB(cctx_T *cctx, job_T *job)
1246 {
1247     isn_T	*isn;
1248 
1249     RETURN_OK_IF_SKIP(cctx);
1250     if ((isn = generate_instr_type(cctx, ISN_PUSHJOB, &t_channel)) == NULL)
1251 	return FAIL;
1252     isn->isn_arg.job = job;
1253 
1254     return OK;
1255 }
1256 
1257 /*
1258  * Generate an ISN_PUSHBLOB instruction.
1259  * Consumes "blob".
1260  */
1261     static int
generate_PUSHBLOB(cctx_T * cctx,blob_T * blob)1262 generate_PUSHBLOB(cctx_T *cctx, blob_T *blob)
1263 {
1264     isn_T	*isn;
1265 
1266     RETURN_OK_IF_SKIP(cctx);
1267     if ((isn = generate_instr_type(cctx, ISN_PUSHBLOB, &t_blob)) == NULL)
1268 	return FAIL;
1269     isn->isn_arg.blob = blob;
1270 
1271     return OK;
1272 }
1273 
1274 /*
1275  * Generate an ISN_PUSHFUNC instruction with name "name".
1276  * Consumes "name".
1277  */
1278     static int
generate_PUSHFUNC(cctx_T * cctx,char_u * name,type_T * type)1279 generate_PUSHFUNC(cctx_T *cctx, char_u *name, type_T *type)
1280 {
1281     isn_T	*isn;
1282 
1283     RETURN_OK_IF_SKIP(cctx);
1284     if ((isn = generate_instr_type(cctx, ISN_PUSHFUNC, type)) == NULL)
1285 	return FAIL;
1286     isn->isn_arg.string = name == NULL ? NULL : vim_strsave(name);
1287 
1288     return OK;
1289 }
1290 
1291 /*
1292  * Generate an ISN_GETITEM instruction with "index".
1293  * "with_op" is TRUE for "+=" and other operators, the stack has the current
1294  * value below the list with values.
1295  */
1296     static int
generate_GETITEM(cctx_T * cctx,int index,int with_op)1297 generate_GETITEM(cctx_T *cctx, int index, int with_op)
1298 {
1299     isn_T	*isn;
1300     garray_T	*stack = &cctx->ctx_type_stack;
1301     type_T	*type = ((type_T **)stack->ga_data)[stack->ga_len
1302 							  - (with_op ? 2 : 1)];
1303     type_T	*item_type = &t_any;
1304 
1305     RETURN_OK_IF_SKIP(cctx);
1306 
1307     if (type->tt_type != VAR_LIST)
1308     {
1309 	// cannot happen, caller has checked the type
1310 	emsg(_(e_listreq));
1311 	return FAIL;
1312     }
1313     item_type = type->tt_member;
1314     if ((isn = generate_instr(cctx, ISN_GETITEM)) == NULL)
1315 	return FAIL;
1316     isn->isn_arg.getitem.gi_index = index;
1317     isn->isn_arg.getitem.gi_with_op = with_op;
1318 
1319     // add the item type to the type stack
1320     if (GA_GROW_FAILS(stack, 1))
1321 	return FAIL;
1322     ((type_T **)stack->ga_data)[stack->ga_len] = item_type;
1323     ++stack->ga_len;
1324     return OK;
1325 }
1326 
1327 /*
1328  * Generate an ISN_SLICE instruction with "count".
1329  */
1330     static int
generate_SLICE(cctx_T * cctx,int count)1331 generate_SLICE(cctx_T *cctx, int count)
1332 {
1333     isn_T	*isn;
1334 
1335     RETURN_OK_IF_SKIP(cctx);
1336     if ((isn = generate_instr(cctx, ISN_SLICE)) == NULL)
1337 	return FAIL;
1338     isn->isn_arg.number = count;
1339     return OK;
1340 }
1341 
1342 /*
1343  * Generate an ISN_CHECKLEN instruction with "min_len".
1344  */
1345     static int
generate_CHECKLEN(cctx_T * cctx,int min_len,int more_OK)1346 generate_CHECKLEN(cctx_T *cctx, int min_len, int more_OK)
1347 {
1348     isn_T	*isn;
1349 
1350     RETURN_OK_IF_SKIP(cctx);
1351 
1352     if ((isn = generate_instr(cctx, ISN_CHECKLEN)) == NULL)
1353 	return FAIL;
1354     isn->isn_arg.checklen.cl_min_len = min_len;
1355     isn->isn_arg.checklen.cl_more_OK = more_OK;
1356 
1357     return OK;
1358 }
1359 
1360 /*
1361  * Generate an ISN_STORE instruction.
1362  */
1363     static int
generate_STORE(cctx_T * cctx,isntype_T isn_type,int idx,char_u * name)1364 generate_STORE(cctx_T *cctx, isntype_T isn_type, int idx, char_u *name)
1365 {
1366     isn_T	*isn;
1367 
1368     RETURN_OK_IF_SKIP(cctx);
1369     if ((isn = generate_instr_drop(cctx, isn_type, 1)) == NULL)
1370 	return FAIL;
1371     if (name != NULL)
1372 	isn->isn_arg.string = vim_strsave(name);
1373     else
1374 	isn->isn_arg.number = idx;
1375 
1376     return OK;
1377 }
1378 
1379 /*
1380  * Generate an ISN_STOREOUTER instruction.
1381  */
1382     static int
generate_STOREOUTER(cctx_T * cctx,int idx,int level)1383 generate_STOREOUTER(cctx_T *cctx, int idx, int level)
1384 {
1385     isn_T	*isn;
1386 
1387     RETURN_OK_IF_SKIP(cctx);
1388     if ((isn = generate_instr_drop(cctx, ISN_STOREOUTER, 1)) == NULL)
1389 	return FAIL;
1390     isn->isn_arg.outer.outer_idx = idx;
1391     isn->isn_arg.outer.outer_depth = level;
1392 
1393     return OK;
1394 }
1395 
1396 /*
1397  * Generate an ISN_STORENR instruction (short for ISN_PUSHNR + ISN_STORE)
1398  */
1399     static int
generate_STORENR(cctx_T * cctx,int idx,varnumber_T value)1400 generate_STORENR(cctx_T *cctx, int idx, varnumber_T value)
1401 {
1402     isn_T	*isn;
1403 
1404     RETURN_OK_IF_SKIP(cctx);
1405     if ((isn = generate_instr(cctx, ISN_STORENR)) == NULL)
1406 	return FAIL;
1407     isn->isn_arg.storenr.stnr_idx = idx;
1408     isn->isn_arg.storenr.stnr_val = value;
1409 
1410     return OK;
1411 }
1412 
1413 /*
1414  * Generate an ISN_STOREOPT instruction
1415  */
1416     static int
generate_STOREOPT(cctx_T * cctx,char_u * name,int opt_flags)1417 generate_STOREOPT(cctx_T *cctx, char_u *name, int opt_flags)
1418 {
1419     isn_T	*isn;
1420 
1421     RETURN_OK_IF_SKIP(cctx);
1422     if ((isn = generate_instr_drop(cctx, ISN_STOREOPT, 1)) == NULL)
1423 	return FAIL;
1424     isn->isn_arg.storeopt.so_name = vim_strsave(name);
1425     isn->isn_arg.storeopt.so_flags = opt_flags;
1426 
1427     return OK;
1428 }
1429 
1430 /*
1431  * Generate an ISN_LOAD or similar instruction.
1432  */
1433     static int
generate_LOAD(cctx_T * cctx,isntype_T isn_type,int idx,char_u * name,type_T * type)1434 generate_LOAD(
1435 	cctx_T	    *cctx,
1436 	isntype_T   isn_type,
1437 	int	    idx,
1438 	char_u	    *name,
1439 	type_T	    *type)
1440 {
1441     isn_T	*isn;
1442 
1443     RETURN_OK_IF_SKIP(cctx);
1444     if ((isn = generate_instr_type(cctx, isn_type, type)) == NULL)
1445 	return FAIL;
1446     if (name != NULL)
1447 	isn->isn_arg.string = vim_strsave(name);
1448     else
1449 	isn->isn_arg.number = idx;
1450 
1451     return OK;
1452 }
1453 
1454 /*
1455  * Generate an ISN_LOADOUTER instruction
1456  */
1457     static int
generate_LOADOUTER(cctx_T * cctx,int idx,int nesting,type_T * type)1458 generate_LOADOUTER(
1459 	cctx_T	    *cctx,
1460 	int	    idx,
1461 	int	    nesting,
1462 	type_T	    *type)
1463 {
1464     isn_T	*isn;
1465 
1466     RETURN_OK_IF_SKIP(cctx);
1467     if ((isn = generate_instr_type(cctx, ISN_LOADOUTER, type)) == NULL)
1468 	return FAIL;
1469     isn->isn_arg.outer.outer_idx = idx;
1470     isn->isn_arg.outer.outer_depth = nesting;
1471 
1472     return OK;
1473 }
1474 
1475 /*
1476  * Generate an ISN_LOADV instruction for v:var.
1477  */
1478     static int
generate_LOADV(cctx_T * cctx,char_u * name,int error)1479 generate_LOADV(
1480 	cctx_T	    *cctx,
1481 	char_u	    *name,
1482 	int	    error)
1483 {
1484     int	    di_flags;
1485     int	    vidx = find_vim_var(name, &di_flags);
1486     type_T  *type;
1487 
1488     RETURN_OK_IF_SKIP(cctx);
1489     if (vidx < 0)
1490     {
1491 	if (error)
1492 	    semsg(_(e_variable_not_found_str), name);
1493 	return FAIL;
1494     }
1495     type = typval2type_vimvar(get_vim_var_tv(vidx), cctx->ctx_type_list);
1496 
1497     return generate_LOAD(cctx, ISN_LOADV, vidx, NULL, type);
1498 }
1499 
1500 /*
1501  * Generate an ISN_UNLET instruction.
1502  */
1503     static int
generate_UNLET(cctx_T * cctx,isntype_T isn_type,char_u * name,int forceit)1504 generate_UNLET(cctx_T *cctx, isntype_T isn_type, char_u *name, int forceit)
1505 {
1506     isn_T	*isn;
1507 
1508     RETURN_OK_IF_SKIP(cctx);
1509     if ((isn = generate_instr(cctx, isn_type)) == NULL)
1510 	return FAIL;
1511     isn->isn_arg.unlet.ul_name = vim_strsave(name);
1512     isn->isn_arg.unlet.ul_forceit = forceit;
1513 
1514     return OK;
1515 }
1516 
1517 /*
1518  * Generate an ISN_LOCKCONST instruction.
1519  */
1520     static int
generate_LOCKCONST(cctx_T * cctx)1521 generate_LOCKCONST(cctx_T *cctx)
1522 {
1523     isn_T	*isn;
1524 
1525     RETURN_OK_IF_SKIP(cctx);
1526     if ((isn = generate_instr(cctx, ISN_LOCKCONST)) == NULL)
1527 	return FAIL;
1528     return OK;
1529 }
1530 
1531 /*
1532  * Generate an ISN_LOADS instruction.
1533  */
1534     static int
generate_OLDSCRIPT(cctx_T * cctx,isntype_T isn_type,char_u * name,int sid,type_T * type)1535 generate_OLDSCRIPT(
1536 	cctx_T	    *cctx,
1537 	isntype_T   isn_type,
1538 	char_u	    *name,
1539 	int	    sid,
1540 	type_T	    *type)
1541 {
1542     isn_T	*isn;
1543 
1544     RETURN_OK_IF_SKIP(cctx);
1545     if (isn_type == ISN_LOADS)
1546 	isn = generate_instr_type(cctx, isn_type, type);
1547     else
1548 	isn = generate_instr_drop(cctx, isn_type, 1);
1549     if (isn == NULL)
1550 	return FAIL;
1551     isn->isn_arg.loadstore.ls_name = vim_strsave(name);
1552     isn->isn_arg.loadstore.ls_sid = sid;
1553 
1554     return OK;
1555 }
1556 
1557 /*
1558  * Generate an ISN_LOADSCRIPT or ISN_STORESCRIPT instruction.
1559  */
1560     static int
generate_VIM9SCRIPT(cctx_T * cctx,isntype_T isn_type,int sid,int idx,type_T * type)1561 generate_VIM9SCRIPT(
1562 	cctx_T	    *cctx,
1563 	isntype_T   isn_type,
1564 	int	    sid,
1565 	int	    idx,
1566 	type_T	    *type)
1567 {
1568     isn_T	*isn;
1569     scriptref_T	*sref;
1570     scriptitem_T *si = SCRIPT_ITEM(sid);
1571 
1572     RETURN_OK_IF_SKIP(cctx);
1573     if (isn_type == ISN_LOADSCRIPT)
1574 	isn = generate_instr_type(cctx, isn_type, type);
1575     else
1576 	isn = generate_instr_drop(cctx, isn_type, 1);
1577     if (isn == NULL)
1578 	return FAIL;
1579 
1580     // This requires three arguments, which doesn't fit in an instruction, thus
1581     // we need to allocate a struct for this.
1582     sref = ALLOC_ONE(scriptref_T);
1583     if (sref == NULL)
1584 	return FAIL;
1585     isn->isn_arg.script.scriptref = sref;
1586     sref->sref_sid = sid;
1587     sref->sref_idx = idx;
1588     sref->sref_seq = si->sn_script_seq;
1589     sref->sref_type = type;
1590     return OK;
1591 }
1592 
1593 /*
1594  * Generate an ISN_NEWLIST instruction.
1595  */
1596     static int
generate_NEWLIST(cctx_T * cctx,int count)1597 generate_NEWLIST(cctx_T *cctx, int count)
1598 {
1599     isn_T	*isn;
1600     garray_T	*stack = &cctx->ctx_type_stack;
1601     type_T	*type;
1602     type_T	*member;
1603 
1604     RETURN_OK_IF_SKIP(cctx);
1605     if ((isn = generate_instr(cctx, ISN_NEWLIST)) == NULL)
1606 	return FAIL;
1607     isn->isn_arg.number = count;
1608 
1609     // get the member type from all the items on the stack.
1610     if (count == 0)
1611 	member = &t_unknown;
1612     else
1613 	member = get_member_type_from_stack(
1614 	    ((type_T **)stack->ga_data) + stack->ga_len, count, 1,
1615 							  cctx->ctx_type_list);
1616     type = get_list_type(member, cctx->ctx_type_list);
1617 
1618     // drop the value types
1619     stack->ga_len -= count;
1620 
1621     // add the list type to the type stack
1622     if (GA_GROW_FAILS(stack, 1))
1623 	return FAIL;
1624     ((type_T **)stack->ga_data)[stack->ga_len] = type;
1625     ++stack->ga_len;
1626 
1627     return OK;
1628 }
1629 
1630 /*
1631  * Generate an ISN_NEWDICT instruction.
1632  */
1633     static int
generate_NEWDICT(cctx_T * cctx,int count)1634 generate_NEWDICT(cctx_T *cctx, int count)
1635 {
1636     isn_T	*isn;
1637     garray_T	*stack = &cctx->ctx_type_stack;
1638     type_T	*type;
1639     type_T	*member;
1640 
1641     RETURN_OK_IF_SKIP(cctx);
1642     if ((isn = generate_instr(cctx, ISN_NEWDICT)) == NULL)
1643 	return FAIL;
1644     isn->isn_arg.number = count;
1645 
1646     if (count == 0)
1647 	member = &t_void;
1648     else
1649 	member = get_member_type_from_stack(
1650 	    ((type_T **)stack->ga_data) + stack->ga_len, count, 2,
1651 							  cctx->ctx_type_list);
1652     type = get_dict_type(member, cctx->ctx_type_list);
1653 
1654     // drop the key and value types
1655     stack->ga_len -= 2 * count;
1656 
1657     // add the dict type to the type stack
1658     if (GA_GROW_FAILS(stack, 1))
1659 	return FAIL;
1660     ((type_T **)stack->ga_data)[stack->ga_len] = type;
1661     ++stack->ga_len;
1662 
1663     return OK;
1664 }
1665 
1666 /*
1667  * Generate an ISN_FUNCREF instruction.
1668  */
1669     static int
generate_FUNCREF(cctx_T * cctx,ufunc_T * ufunc)1670 generate_FUNCREF(cctx_T *cctx, ufunc_T *ufunc)
1671 {
1672     isn_T	*isn;
1673     garray_T	*stack = &cctx->ctx_type_stack;
1674 
1675     RETURN_OK_IF_SKIP(cctx);
1676     if ((isn = generate_instr(cctx, ISN_FUNCREF)) == NULL)
1677 	return FAIL;
1678     isn->isn_arg.funcref.fr_func = ufunc->uf_dfunc_idx;
1679     cctx->ctx_has_closure = 1;
1680 
1681     // If the referenced function is a closure, it may use items further up in
1682     // the nested context, including this one.
1683     if (ufunc->uf_flags & FC_CLOSURE)
1684 	cctx->ctx_ufunc->uf_flags |= FC_CLOSURE;
1685 
1686     if (GA_GROW_FAILS(stack, 1))
1687 	return FAIL;
1688     ((type_T **)stack->ga_data)[stack->ga_len] =
1689 	       ufunc->uf_func_type == NULL ? &t_func_any : ufunc->uf_func_type;
1690     ++stack->ga_len;
1691 
1692     return OK;
1693 }
1694 
1695 /*
1696  * Generate an ISN_NEWFUNC instruction.
1697  * "lambda_name" and "func_name" must be in allocated memory and will be
1698  * consumed.
1699  */
1700     static int
generate_NEWFUNC(cctx_T * cctx,char_u * lambda_name,char_u * func_name)1701 generate_NEWFUNC(cctx_T *cctx, char_u *lambda_name, char_u *func_name)
1702 {
1703     isn_T	*isn;
1704 
1705     if (cctx->ctx_skip == SKIP_YES)
1706     {
1707 	vim_free(lambda_name);
1708 	vim_free(func_name);
1709 	return OK;
1710     }
1711     if ((isn = generate_instr(cctx, ISN_NEWFUNC)) == NULL)
1712     {
1713 	vim_free(lambda_name);
1714 	vim_free(func_name);
1715 	return FAIL;
1716     }
1717     isn->isn_arg.newfunc.nf_lambda = lambda_name;
1718     isn->isn_arg.newfunc.nf_global = func_name;
1719 
1720     return OK;
1721 }
1722 
1723 /*
1724  * Generate an ISN_DEF instruction: list functions
1725  */
1726     static int
generate_DEF(cctx_T * cctx,char_u * name,size_t len)1727 generate_DEF(cctx_T *cctx, char_u *name, size_t len)
1728 {
1729     isn_T	*isn;
1730 
1731     RETURN_OK_IF_SKIP(cctx);
1732     if ((isn = generate_instr(cctx, ISN_DEF)) == NULL)
1733 	return FAIL;
1734     if (len > 0)
1735     {
1736 	isn->isn_arg.string = vim_strnsave(name, len);
1737 	if (isn->isn_arg.string == NULL)
1738 	    return FAIL;
1739     }
1740     return OK;
1741 }
1742 
1743 /*
1744  * Generate an ISN_JUMP instruction.
1745  */
1746     static int
generate_JUMP(cctx_T * cctx,jumpwhen_T when,int where)1747 generate_JUMP(cctx_T *cctx, jumpwhen_T when, int where)
1748 {
1749     isn_T	*isn;
1750     garray_T	*stack = &cctx->ctx_type_stack;
1751 
1752     RETURN_OK_IF_SKIP(cctx);
1753     if ((isn = generate_instr(cctx, ISN_JUMP)) == NULL)
1754 	return FAIL;
1755     isn->isn_arg.jump.jump_when = when;
1756     isn->isn_arg.jump.jump_where = where;
1757 
1758     if (when != JUMP_ALWAYS && stack->ga_len > 0)
1759 	--stack->ga_len;
1760 
1761     return OK;
1762 }
1763 
1764 /*
1765  * Generate an ISN_JUMP_IF_ARG_SET instruction.
1766  */
1767     static int
generate_JUMP_IF_ARG_SET(cctx_T * cctx,int arg_off)1768 generate_JUMP_IF_ARG_SET(cctx_T *cctx, int arg_off)
1769 {
1770     isn_T	*isn;
1771 
1772     RETURN_OK_IF_SKIP(cctx);
1773     if ((isn = generate_instr(cctx, ISN_JUMP_IF_ARG_SET)) == NULL)
1774 	return FAIL;
1775     isn->isn_arg.jumparg.jump_arg_off = arg_off;
1776     // jump_where is set later
1777     return OK;
1778 }
1779 
1780     static int
generate_FOR(cctx_T * cctx,int loop_idx)1781 generate_FOR(cctx_T *cctx, int loop_idx)
1782 {
1783     isn_T	*isn;
1784     garray_T	*stack = &cctx->ctx_type_stack;
1785 
1786     RETURN_OK_IF_SKIP(cctx);
1787     if ((isn = generate_instr(cctx, ISN_FOR)) == NULL)
1788 	return FAIL;
1789     isn->isn_arg.forloop.for_idx = loop_idx;
1790 
1791     if (GA_GROW_FAILS(stack, 1))
1792 	return FAIL;
1793     // type doesn't matter, will be stored next
1794     ((type_T **)stack->ga_data)[stack->ga_len] = &t_any;
1795     ++stack->ga_len;
1796 
1797     return OK;
1798 }
1799 /*
1800  * Generate an ISN_TRYCONT instruction.
1801  */
1802     static int
generate_TRYCONT(cctx_T * cctx,int levels,int where)1803 generate_TRYCONT(cctx_T *cctx, int levels, int where)
1804 {
1805     isn_T	*isn;
1806 
1807     RETURN_OK_IF_SKIP(cctx);
1808     if ((isn = generate_instr(cctx, ISN_TRYCONT)) == NULL)
1809 	return FAIL;
1810     isn->isn_arg.trycont.tct_levels = levels;
1811     isn->isn_arg.trycont.tct_where = where;
1812 
1813     return OK;
1814 }
1815 
1816 
1817 /*
1818  * Generate an ISN_BCALL instruction.
1819  * "method_call" is TRUE for "value->method()"
1820  * Return FAIL if the number of arguments is wrong.
1821  */
1822     static int
generate_BCALL(cctx_T * cctx,int func_idx,int argcount,int method_call)1823 generate_BCALL(cctx_T *cctx, int func_idx, int argcount, int method_call)
1824 {
1825     isn_T	*isn;
1826     garray_T	*stack = &cctx->ctx_type_stack;
1827     int		argoff;
1828     type_T	**argtypes = NULL;
1829     type_T	*shuffled_argtypes[MAX_FUNC_ARGS];
1830     type_T	*maptype = NULL;
1831 
1832     RETURN_OK_IF_SKIP(cctx);
1833     argoff = check_internal_func(func_idx, argcount);
1834     if (argoff < 0)
1835 	return FAIL;
1836 
1837     if (method_call && argoff > 1)
1838     {
1839 	if ((isn = generate_instr(cctx, ISN_SHUFFLE)) == NULL)
1840 	    return FAIL;
1841 	isn->isn_arg.shuffle.shfl_item = argcount;
1842 	isn->isn_arg.shuffle.shfl_up = argoff - 1;
1843     }
1844 
1845     if (argcount > 0)
1846     {
1847 	// Check the types of the arguments.
1848 	argtypes = ((type_T **)stack->ga_data) + stack->ga_len - argcount;
1849 	if (method_call && argoff > 1)
1850 	{
1851 	    int i;
1852 
1853 	    for (i = 0; i < argcount; ++i)
1854 		shuffled_argtypes[i] = (i < argoff - 1)
1855 			    ? argtypes[i + 1]
1856 			    : (i == argoff - 1) ? argtypes[0] : argtypes[i];
1857 	    argtypes = shuffled_argtypes;
1858 	}
1859 	if (internal_func_check_arg_types(argtypes, func_idx, argcount,
1860 								 cctx) == FAIL)
1861 	    return FAIL;
1862 	if (internal_func_is_map(func_idx))
1863 	    maptype = *argtypes;
1864     }
1865 
1866     if ((isn = generate_instr(cctx, ISN_BCALL)) == NULL)
1867 	return FAIL;
1868     isn->isn_arg.bfunc.cbf_idx = func_idx;
1869     isn->isn_arg.bfunc.cbf_argcount = argcount;
1870 
1871     // Drop the argument types and push the return type.
1872     stack->ga_len -= argcount;
1873     if (GA_GROW_FAILS(stack, 1))
1874 	return FAIL;
1875     ((type_T **)stack->ga_data)[stack->ga_len] =
1876 			  internal_func_ret_type(func_idx, argcount, argtypes);
1877     ++stack->ga_len;
1878 
1879     if (maptype != NULL && maptype->tt_member != NULL
1880 					       && maptype->tt_member != &t_any)
1881 	// Check that map() didn't change the item types.
1882 	generate_TYPECHECK(cctx, maptype, -1, 1);
1883 
1884     return OK;
1885 }
1886 
1887 /*
1888  * Generate an ISN_LISTAPPEND instruction.  Works like add().
1889  * Argument count is already checked.
1890  */
1891     static int
generate_LISTAPPEND(cctx_T * cctx)1892 generate_LISTAPPEND(cctx_T *cctx)
1893 {
1894     garray_T	*stack = &cctx->ctx_type_stack;
1895     type_T	*list_type;
1896     type_T	*item_type;
1897     type_T	*expected;
1898 
1899     // Caller already checked that list_type is a list.
1900     list_type = ((type_T **)stack->ga_data)[stack->ga_len - 2];
1901     item_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
1902     expected = list_type->tt_member;
1903     if (need_type(item_type, expected, -1, 0, cctx, FALSE, FALSE) == FAIL)
1904 	return FAIL;
1905 
1906     if (generate_instr(cctx, ISN_LISTAPPEND) == NULL)
1907 	return FAIL;
1908 
1909     --stack->ga_len;	    // drop the argument
1910     return OK;
1911 }
1912 
1913 /*
1914  * Generate an ISN_BLOBAPPEND instruction.  Works like add().
1915  * Argument count is already checked.
1916  */
1917     static int
generate_BLOBAPPEND(cctx_T * cctx)1918 generate_BLOBAPPEND(cctx_T *cctx)
1919 {
1920     garray_T	*stack = &cctx->ctx_type_stack;
1921     type_T	*item_type;
1922 
1923     // Caller already checked that blob_type is a blob.
1924     item_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
1925     if (need_type(item_type, &t_number, -1, 0, cctx, FALSE, FALSE) == FAIL)
1926 	return FAIL;
1927 
1928     if (generate_instr(cctx, ISN_BLOBAPPEND) == NULL)
1929 	return FAIL;
1930 
1931     --stack->ga_len;	    // drop the argument
1932     return OK;
1933 }
1934 
1935 /*
1936  * Return TRUE if "ufunc" should be compiled, taking into account whether
1937  * "profile" indicates profiling is to be done.
1938  */
1939     int
func_needs_compiling(ufunc_T * ufunc,compiletype_T compile_type)1940 func_needs_compiling(ufunc_T *ufunc, compiletype_T compile_type)
1941 {
1942     switch (ufunc->uf_def_status)
1943     {
1944 	case UF_TO_BE_COMPILED:
1945 	    return TRUE;
1946 
1947 	case UF_COMPILED:
1948 	{
1949 	    dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
1950 							 + ufunc->uf_dfunc_idx;
1951 
1952 	    switch (compile_type)
1953 	    {
1954 		case CT_PROFILE:
1955 #ifdef FEAT_PROFILE
1956 		    return dfunc->df_instr_prof == NULL;
1957 #endif
1958 		case CT_NONE:
1959 		    return dfunc->df_instr == NULL;
1960 		case CT_DEBUG:
1961 		    return dfunc->df_instr_debug == NULL;
1962 	    }
1963 	}
1964 
1965 	case UF_NOT_COMPILED:
1966 	case UF_COMPILE_ERROR:
1967 	case UF_COMPILING:
1968 	    break;
1969     }
1970     return FALSE;
1971 }
1972 
1973 /*
1974  * Generate an ISN_DCALL or ISN_UCALL instruction.
1975  * Return FAIL if the number of arguments is wrong.
1976  */
1977     static int
generate_CALL(cctx_T * cctx,ufunc_T * ufunc,int pushed_argcount)1978 generate_CALL(cctx_T *cctx, ufunc_T *ufunc, int pushed_argcount)
1979 {
1980     isn_T	*isn;
1981     garray_T	*stack = &cctx->ctx_type_stack;
1982     int		regular_args = ufunc->uf_args.ga_len;
1983     int		argcount = pushed_argcount;
1984 
1985     RETURN_OK_IF_SKIP(cctx);
1986     if (argcount > regular_args && !has_varargs(ufunc))
1987     {
1988 	semsg(_(e_toomanyarg), printable_func_name(ufunc));
1989 	return FAIL;
1990     }
1991     if (argcount < regular_args - ufunc->uf_def_args.ga_len)
1992     {
1993 	semsg(_(e_toofewarg), printable_func_name(ufunc));
1994 	return FAIL;
1995     }
1996 
1997     if (ufunc->uf_def_status != UF_NOT_COMPILED
1998 	    && ufunc->uf_def_status != UF_COMPILE_ERROR)
1999     {
2000 	int		i;
2001 
2002 	for (i = 0; i < argcount; ++i)
2003 	{
2004 	    type_T *expected;
2005 	    type_T *actual;
2006 
2007 	    actual = ((type_T **)stack->ga_data)[stack->ga_len - argcount + i];
2008 	    if (actual == &t_special
2009 			      && i >= regular_args - ufunc->uf_def_args.ga_len)
2010 	    {
2011 		// assume v:none used for default argument value
2012 		continue;
2013 	    }
2014 	    if (i < regular_args)
2015 	    {
2016 		if (ufunc->uf_arg_types == NULL)
2017 		    continue;
2018 		expected = ufunc->uf_arg_types[i];
2019 	    }
2020 	    else if (ufunc->uf_va_type == NULL
2021 					   || ufunc->uf_va_type == &t_list_any)
2022 		// possibly a lambda or "...: any"
2023 		expected = &t_any;
2024 	    else
2025 		expected = ufunc->uf_va_type->tt_member;
2026 	    if (need_type(actual, expected, -argcount + i, i + 1, cctx,
2027 							  TRUE, FALSE) == FAIL)
2028 	    {
2029 		arg_type_mismatch(expected, actual, i + 1);
2030 		return FAIL;
2031 	    }
2032 	}
2033 	if (func_needs_compiling(ufunc, COMPILE_TYPE(ufunc))
2034 		&& compile_def_function(ufunc, ufunc->uf_ret_type == NULL,
2035 					    COMPILE_TYPE(ufunc), NULL) == FAIL)
2036 	    return FAIL;
2037     }
2038     if (ufunc->uf_def_status == UF_COMPILE_ERROR)
2039     {
2040 	emsg_funcname(_(e_call_to_function_that_failed_to_compile_str),
2041 							       ufunc->uf_name);
2042 	return FAIL;
2043     }
2044 
2045     if ((isn = generate_instr(cctx,
2046 		    ufunc->uf_def_status != UF_NOT_COMPILED ? ISN_DCALL
2047 							 : ISN_UCALL)) == NULL)
2048 	return FAIL;
2049     if (isn->isn_type == ISN_DCALL)
2050     {
2051 	isn->isn_arg.dfunc.cdf_idx = ufunc->uf_dfunc_idx;
2052 	isn->isn_arg.dfunc.cdf_argcount = argcount;
2053     }
2054     else
2055     {
2056 	// A user function may be deleted and redefined later, can't use the
2057 	// ufunc pointer, need to look it up again at runtime.
2058 	isn->isn_arg.ufunc.cuf_name = vim_strsave(ufunc->uf_name);
2059 	isn->isn_arg.ufunc.cuf_argcount = argcount;
2060     }
2061 
2062     stack->ga_len -= argcount; // drop the arguments
2063     if (GA_GROW_FAILS(stack, 1))
2064 	return FAIL;
2065     // add return value
2066     ((type_T **)stack->ga_data)[stack->ga_len] = ufunc->uf_ret_type;
2067     ++stack->ga_len;
2068 
2069     return OK;
2070 }
2071 
2072 /*
2073  * Generate an ISN_UCALL instruction when the function isn't defined yet.
2074  */
2075     static int
generate_UCALL(cctx_T * cctx,char_u * name,int argcount)2076 generate_UCALL(cctx_T *cctx, char_u *name, int argcount)
2077 {
2078     isn_T	*isn;
2079     garray_T	*stack = &cctx->ctx_type_stack;
2080 
2081     RETURN_OK_IF_SKIP(cctx);
2082     if ((isn = generate_instr(cctx, ISN_UCALL)) == NULL)
2083 	return FAIL;
2084     isn->isn_arg.ufunc.cuf_name = vim_strsave(name);
2085     isn->isn_arg.ufunc.cuf_argcount = argcount;
2086 
2087     stack->ga_len -= argcount; // drop the arguments
2088     if (GA_GROW_FAILS(stack, 1))
2089 	return FAIL;
2090     // add return value
2091     ((type_T **)stack->ga_data)[stack->ga_len] = &t_any;
2092     ++stack->ga_len;
2093 
2094     return OK;
2095 }
2096 
2097 /*
2098  * Generate an ISN_PCALL instruction.
2099  * "type" is the type of the FuncRef.
2100  */
2101     static int
generate_PCALL(cctx_T * cctx,int argcount,char_u * name,type_T * type,int at_top)2102 generate_PCALL(
2103 	cctx_T	*cctx,
2104 	int	argcount,
2105 	char_u	*name,
2106 	type_T	*type,
2107 	int	at_top)
2108 {
2109     isn_T	*isn;
2110     garray_T	*stack = &cctx->ctx_type_stack;
2111     type_T	*ret_type;
2112 
2113     RETURN_OK_IF_SKIP(cctx);
2114 
2115     if (type->tt_type == VAR_ANY)
2116 	ret_type = &t_any;
2117     else if (type->tt_type == VAR_FUNC || type->tt_type == VAR_PARTIAL)
2118     {
2119 	if (type->tt_argcount != -1)
2120 	{
2121 	    int	    varargs = (type->tt_flags & TTFLAG_VARARGS) ? 1 : 0;
2122 
2123 	    if (argcount < type->tt_min_argcount - varargs)
2124 	    {
2125 		semsg(_(e_toofewarg), name);
2126 		return FAIL;
2127 	    }
2128 	    if (!varargs && argcount > type->tt_argcount)
2129 	    {
2130 		semsg(_(e_toomanyarg), name);
2131 		return FAIL;
2132 	    }
2133 	    if (type->tt_args != NULL)
2134 	    {
2135 		int i;
2136 
2137 		for (i = 0; i < argcount; ++i)
2138 		{
2139 		    int	    offset = -argcount + i - (at_top ? 0 : 1);
2140 		    type_T *actual = ((type_T **)stack->ga_data)[
2141 						       stack->ga_len + offset];
2142 		    type_T *expected;
2143 
2144 		    if (varargs && i >= type->tt_argcount - 1)
2145 			expected = type->tt_args[
2146 					     type->tt_argcount - 1]->tt_member;
2147 		    else if (i >= type->tt_min_argcount
2148 						       && actual == &t_special)
2149 			expected = &t_any;
2150 		    else
2151 			expected = type->tt_args[i];
2152 		    if (need_type(actual, expected, offset, i + 1,
2153 						    cctx, TRUE, FALSE) == FAIL)
2154 		    {
2155 			arg_type_mismatch(expected, actual, i + 1);
2156 			return FAIL;
2157 		    }
2158 		}
2159 	    }
2160 	}
2161 	ret_type = type->tt_member;
2162 	if (ret_type == &t_unknown)
2163 	    // return type not known yet, use a runtime check
2164 	    ret_type = &t_any;
2165     }
2166     else
2167     {
2168 	semsg(_(e_not_callable_type_str), name);
2169 	return FAIL;
2170     }
2171 
2172     if ((isn = generate_instr(cctx, ISN_PCALL)) == NULL)
2173 	return FAIL;
2174     isn->isn_arg.pfunc.cpf_top = at_top;
2175     isn->isn_arg.pfunc.cpf_argcount = argcount;
2176 
2177     stack->ga_len -= argcount; // drop the arguments
2178 
2179     // drop the funcref/partial, get back the return value
2180     ((type_T **)stack->ga_data)[stack->ga_len - 1] = ret_type;
2181 
2182     // If partial is above the arguments it must be cleared and replaced with
2183     // the return value.
2184     if (at_top && generate_instr(cctx, ISN_PCALL_END) == NULL)
2185 	return FAIL;
2186 
2187     return OK;
2188 }
2189 
2190 /*
2191  * Generate an ISN_STRINGMEMBER instruction.
2192  */
2193     static int
generate_STRINGMEMBER(cctx_T * cctx,char_u * name,size_t len)2194 generate_STRINGMEMBER(cctx_T *cctx, char_u *name, size_t len)
2195 {
2196     isn_T	*isn;
2197     garray_T	*stack = &cctx->ctx_type_stack;
2198     type_T	*type;
2199 
2200     RETURN_OK_IF_SKIP(cctx);
2201     if ((isn = generate_instr(cctx, ISN_STRINGMEMBER)) == NULL)
2202 	return FAIL;
2203     isn->isn_arg.string = vim_strnsave(name, len);
2204 
2205     // check for dict type
2206     type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
2207     if (type->tt_type != VAR_DICT && type != &t_any)
2208     {
2209 	char *tofree;
2210 
2211 	semsg(_(e_expected_dictionary_for_using_key_str_but_got_str),
2212 					       name, type_name(type, &tofree));
2213 	vim_free(tofree);
2214 	return FAIL;
2215     }
2216     // change dict type to dict member type
2217     if (type->tt_type == VAR_DICT)
2218     {
2219 	((type_T **)stack->ga_data)[stack->ga_len - 1] =
2220 		      type->tt_member == &t_unknown ? &t_any : type->tt_member;
2221     }
2222 
2223     return OK;
2224 }
2225 
2226 /*
2227  * Generate an ISN_ECHO instruction.
2228  */
2229     static int
generate_ECHO(cctx_T * cctx,int with_white,int count)2230 generate_ECHO(cctx_T *cctx, int with_white, int count)
2231 {
2232     isn_T	*isn;
2233 
2234     RETURN_OK_IF_SKIP(cctx);
2235     if ((isn = generate_instr_drop(cctx, ISN_ECHO, count)) == NULL)
2236 	return FAIL;
2237     isn->isn_arg.echo.echo_with_white = with_white;
2238     isn->isn_arg.echo.echo_count = count;
2239 
2240     return OK;
2241 }
2242 
2243 /*
2244  * Generate an ISN_EXECUTE/ISN_ECHOMSG/ISN_ECHOERR instruction.
2245  */
2246     static int
generate_MULT_EXPR(cctx_T * cctx,isntype_T isn_type,int count)2247 generate_MULT_EXPR(cctx_T *cctx, isntype_T isn_type, int count)
2248 {
2249     isn_T	*isn;
2250 
2251     if ((isn = generate_instr_drop(cctx, isn_type, count)) == NULL)
2252 	return FAIL;
2253     isn->isn_arg.number = count;
2254 
2255     return OK;
2256 }
2257 
2258 /*
2259  * Generate an ISN_PUT instruction.
2260  */
2261     static int
generate_PUT(cctx_T * cctx,int regname,linenr_T lnum)2262 generate_PUT(cctx_T *cctx, int regname, linenr_T lnum)
2263 {
2264     isn_T	*isn;
2265 
2266     RETURN_OK_IF_SKIP(cctx);
2267     if ((isn = generate_instr(cctx, ISN_PUT)) == NULL)
2268 	return FAIL;
2269     isn->isn_arg.put.put_regname = regname;
2270     isn->isn_arg.put.put_lnum = lnum;
2271     return OK;
2272 }
2273 
2274     static int
generate_EXEC(cctx_T * cctx,isntype_T isntype,char_u * line)2275 generate_EXEC(cctx_T *cctx, isntype_T isntype, char_u *line)
2276 {
2277     isn_T	*isn;
2278 
2279     RETURN_OK_IF_SKIP(cctx);
2280     if ((isn = generate_instr(cctx, isntype)) == NULL)
2281 	return FAIL;
2282     isn->isn_arg.string = vim_strsave(line);
2283     return OK;
2284 }
2285 
2286     static int
generate_LEGACY_EVAL(cctx_T * cctx,char_u * line)2287 generate_LEGACY_EVAL(cctx_T *cctx, char_u *line)
2288 {
2289     isn_T	*isn;
2290     garray_T	*stack = &cctx->ctx_type_stack;
2291 
2292     RETURN_OK_IF_SKIP(cctx);
2293     if ((isn = generate_instr(cctx, ISN_LEGACY_EVAL)) == NULL)
2294 	return FAIL;
2295     isn->isn_arg.string = vim_strsave(line);
2296 
2297     if (GA_GROW_FAILS(stack, 1))
2298 	return FAIL;
2299     ((type_T **)stack->ga_data)[stack->ga_len] = &t_any;
2300     ++stack->ga_len;
2301 
2302     return OK;
2303 }
2304 
2305     static int
generate_EXECCONCAT(cctx_T * cctx,int count)2306 generate_EXECCONCAT(cctx_T *cctx, int count)
2307 {
2308     isn_T	*isn;
2309 
2310     if ((isn = generate_instr_drop(cctx, ISN_EXECCONCAT, count)) == NULL)
2311 	return FAIL;
2312     isn->isn_arg.number = count;
2313     return OK;
2314 }
2315 
2316 /*
2317  * Generate ISN_RANGE.  Consumes "range".  Return OK/FAIL.
2318  */
2319     static int
generate_RANGE(cctx_T * cctx,char_u * range)2320 generate_RANGE(cctx_T *cctx, char_u *range)
2321 {
2322     isn_T	*isn;
2323     garray_T	*stack = &cctx->ctx_type_stack;
2324 
2325     if ((isn = generate_instr(cctx, ISN_RANGE)) == NULL)
2326 	return FAIL;
2327     isn->isn_arg.string = range;
2328 
2329     if (GA_GROW_FAILS(stack, 1))
2330 	return FAIL;
2331     ((type_T **)stack->ga_data)[stack->ga_len] = &t_number;
2332     ++stack->ga_len;
2333     return OK;
2334 }
2335 
2336     static int
generate_UNPACK(cctx_T * cctx,int var_count,int semicolon)2337 generate_UNPACK(cctx_T *cctx, int var_count, int semicolon)
2338 {
2339     isn_T	*isn;
2340 
2341     RETURN_OK_IF_SKIP(cctx);
2342     if ((isn = generate_instr(cctx, ISN_UNPACK)) == NULL)
2343 	return FAIL;
2344     isn->isn_arg.unpack.unp_count = var_count;
2345     isn->isn_arg.unpack.unp_semicolon = semicolon;
2346     return OK;
2347 }
2348 
2349 /*
2350  * Generate an instruction for any command modifiers.
2351  */
2352     static int
generate_cmdmods(cctx_T * cctx,cmdmod_T * cmod)2353 generate_cmdmods(cctx_T *cctx, cmdmod_T *cmod)
2354 {
2355     isn_T	*isn;
2356 
2357     if (has_cmdmod(cmod, FALSE))
2358     {
2359 	cctx->ctx_has_cmdmod = TRUE;
2360 
2361 	if ((isn = generate_instr(cctx, ISN_CMDMOD)) == NULL)
2362 	    return FAIL;
2363 	isn->isn_arg.cmdmod.cf_cmdmod = ALLOC_ONE(cmdmod_T);
2364 	if (isn->isn_arg.cmdmod.cf_cmdmod == NULL)
2365 	    return FAIL;
2366 	mch_memmove(isn->isn_arg.cmdmod.cf_cmdmod, cmod, sizeof(cmdmod_T));
2367 	// filter program now belongs to the instruction
2368 	cmod->cmod_filter_regmatch.regprog = NULL;
2369     }
2370 
2371     return OK;
2372 }
2373 
2374     static int
generate_undo_cmdmods(cctx_T * cctx)2375 generate_undo_cmdmods(cctx_T *cctx)
2376 {
2377     if (cctx->ctx_has_cmdmod && generate_instr(cctx, ISN_CMDMOD_REV) == NULL)
2378 	return FAIL;
2379     cctx->ctx_has_cmdmod = FALSE;
2380     return OK;
2381 }
2382 
2383     static int
misplaced_cmdmod(cctx_T * cctx)2384 misplaced_cmdmod(cctx_T *cctx)
2385 {
2386     garray_T	*instr = &cctx->ctx_instr;
2387 
2388     if (cctx->ctx_has_cmdmod
2389 	    && ((isn_T *)instr->ga_data)[instr->ga_len - 1].isn_type
2390 								 == ISN_CMDMOD)
2391     {
2392 	emsg(_(e_misplaced_command_modifier));
2393 	return TRUE;
2394     }
2395     return FALSE;
2396 }
2397 
2398 /*
2399  * Get the index of the current instruction.
2400  * This compensates for a preceding ISN_CMDMOD and ISN_PROF_START.
2401  */
2402     static int
current_instr_idx(cctx_T * cctx)2403 current_instr_idx(cctx_T *cctx)
2404 {
2405     garray_T	*instr = &cctx->ctx_instr;
2406     int		idx = instr->ga_len;
2407 
2408     while (idx > 0)
2409     {
2410 	if (cctx->ctx_has_cmdmod && ((isn_T *)instr->ga_data)[idx - 1]
2411 						       .isn_type == ISN_CMDMOD)
2412 	{
2413 	    --idx;
2414 	    continue;
2415 	}
2416 #ifdef FEAT_PROFILE
2417 	if (((isn_T *)instr->ga_data)[idx - 1].isn_type == ISN_PROF_START)
2418 	{
2419 	    --idx;
2420 	    continue;
2421 	}
2422 #endif
2423 	if (((isn_T *)instr->ga_data)[idx - 1].isn_type == ISN_DEBUG)
2424 	{
2425 	    --idx;
2426 	    continue;
2427 	}
2428 	break;
2429     }
2430     return idx;
2431 }
2432 
2433 #ifdef FEAT_PROFILE
2434     static void
may_generate_prof_end(cctx_T * cctx,int prof_lnum)2435 may_generate_prof_end(cctx_T *cctx, int prof_lnum)
2436 {
2437     if (cctx->ctx_compile_type == CT_PROFILE && prof_lnum >= 0)
2438 	generate_instr(cctx, ISN_PROF_END);
2439 }
2440 #endif
2441 
2442 /*
2443  * Reserve space for a local variable.
2444  * Return the variable or NULL if it failed.
2445  */
2446     static lvar_T *
reserve_local(cctx_T * cctx,char_u * name,size_t len,int isConst,type_T * type)2447 reserve_local(
2448 	cctx_T	*cctx,
2449 	char_u	*name,
2450 	size_t	len,
2451 	int	isConst,
2452 	type_T	*type)
2453 {
2454     lvar_T  *lvar;
2455     dfunc_T *dfunc;
2456 
2457     if (arg_exists(name, len, NULL, NULL, NULL, cctx) == OK)
2458     {
2459 	emsg_namelen(_(e_str_is_used_as_argument), name, (int)len);
2460 	return NULL;
2461     }
2462 
2463     if (GA_GROW_FAILS(&cctx->ctx_locals, 1))
2464 	return NULL;
2465     lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + cctx->ctx_locals.ga_len++;
2466     CLEAR_POINTER(lvar);
2467 
2468     // Every local variable uses the next entry on the stack.  We could re-use
2469     // the last ones when leaving a scope, but then variables used in a closure
2470     // might get overwritten.  To keep things simple do not re-use stack
2471     // entries.  This is less efficient, but memory is cheap these days.
2472     dfunc = ((dfunc_T *)def_functions.ga_data) + cctx->ctx_ufunc->uf_dfunc_idx;
2473     lvar->lv_idx = dfunc->df_var_names.ga_len;
2474 
2475     lvar->lv_name = vim_strnsave(name, len == 0 ? STRLEN(name) : len);
2476     lvar->lv_const = isConst;
2477     lvar->lv_type = type;
2478 
2479     // Remember the name for debugging.
2480     if (GA_GROW_FAILS(&dfunc->df_var_names, 1))
2481 	return NULL;
2482     ((char_u **)dfunc->df_var_names.ga_data)[lvar->lv_idx] =
2483 						    vim_strsave(lvar->lv_name);
2484     ++dfunc->df_var_names.ga_len;
2485 
2486     return lvar;
2487 }
2488 
2489 /*
2490  * Remove local variables above "new_top".
2491  */
2492     static void
unwind_locals(cctx_T * cctx,int new_top)2493 unwind_locals(cctx_T *cctx, int new_top)
2494 {
2495     if (cctx->ctx_locals.ga_len > new_top)
2496     {
2497 	int	idx;
2498 	lvar_T	*lvar;
2499 
2500 	for (idx = new_top; idx < cctx->ctx_locals.ga_len; ++idx)
2501 	{
2502 	    lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
2503 	    vim_free(lvar->lv_name);
2504 	}
2505     }
2506     cctx->ctx_locals.ga_len = new_top;
2507 }
2508 
2509 /*
2510  * Free all local variables.
2511  */
2512     static void
free_locals(cctx_T * cctx)2513 free_locals(cctx_T *cctx)
2514 {
2515     unwind_locals(cctx, 0);
2516     ga_clear(&cctx->ctx_locals);
2517 }
2518 
2519 /*
2520  * If "check_writable" is ASSIGN_CONST give an error if the variable was
2521  * defined with :final or :const, if "check_writable" is ASSIGN_FINAL give an
2522  * error if the variable was defined with :const.
2523  */
2524     static int
check_item_writable(svar_T * sv,int check_writable,char_u * name)2525 check_item_writable(svar_T *sv, int check_writable, char_u *name)
2526 {
2527     if ((check_writable == ASSIGN_CONST && sv->sv_const != 0)
2528 	    || (check_writable == ASSIGN_FINAL
2529 					      && sv->sv_const == ASSIGN_CONST))
2530     {
2531 	semsg(_(e_cannot_change_readonly_variable_str), name);
2532 	return FAIL;
2533     }
2534     return OK;
2535 }
2536 
2537 /*
2538  * Find "name" in script-local items of script "sid".
2539  * Pass "check_writable" to check_item_writable().
2540  * Returns the index in "sn_var_vals" if found.
2541  * If found but not in "sn_var_vals" returns -1.
2542  * If not found or the variable is not writable returns -2.
2543  */
2544     int
get_script_item_idx(int sid,char_u * name,int check_writable,cctx_T * cctx)2545 get_script_item_idx(int sid, char_u *name, int check_writable, cctx_T *cctx)
2546 {
2547     hashtab_T	    *ht;
2548     dictitem_T	    *di;
2549     scriptitem_T    *si = SCRIPT_ITEM(sid);
2550     svar_T	    *sv;
2551     int		    idx;
2552 
2553     if (!SCRIPT_ID_VALID(sid))
2554 	return -1;
2555     if (sid == current_sctx.sc_sid)
2556     {
2557 	sallvar_T *sav = find_script_var(name, 0, cctx);
2558 
2559 	if (sav == NULL)
2560 	    return -2;
2561 	idx = sav->sav_var_vals_idx;
2562 	sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
2563 	if (check_item_writable(sv, check_writable, name) == FAIL)
2564 	    return -2;
2565 	return idx;
2566     }
2567 
2568     // First look the name up in the hashtable.
2569     ht = &SCRIPT_VARS(sid);
2570     di = find_var_in_ht(ht, 0, name, TRUE);
2571     if (di == NULL)
2572 	return -2;
2573 
2574     // Now find the svar_T index in sn_var_vals.
2575     for (idx = 0; idx < si->sn_var_vals.ga_len; ++idx)
2576     {
2577 	sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
2578 	if (sv->sv_tv == &di->di_tv)
2579 	{
2580 	    if (check_item_writable(sv, check_writable, name) == FAIL)
2581 		return -2;
2582 	    return idx;
2583 	}
2584     }
2585     return -1;
2586 }
2587 
2588 /*
2589  * Find "name" in imported items of the current script or in "cctx" if not
2590  * NULL.
2591  */
2592     imported_T *
find_imported(char_u * name,size_t len,cctx_T * cctx)2593 find_imported(char_u *name, size_t len, cctx_T *cctx)
2594 {
2595     int		    idx;
2596 
2597     if (!SCRIPT_ID_VALID(current_sctx.sc_sid))
2598 	return NULL;
2599     if (cctx != NULL)
2600 	for (idx = 0; idx < cctx->ctx_imports.ga_len; ++idx)
2601 	{
2602 	    imported_T *import = ((imported_T *)cctx->ctx_imports.ga_data)
2603 									 + idx;
2604 
2605 	    if (len == 0 ? STRCMP(name, import->imp_name) == 0
2606 			 : STRLEN(import->imp_name) == len
2607 				  && STRNCMP(name, import->imp_name, len) == 0)
2608 		return import;
2609 	}
2610 
2611     return find_imported_in_script(name, len, current_sctx.sc_sid);
2612 }
2613 
2614     imported_T *
find_imported_in_script(char_u * name,size_t len,int sid)2615 find_imported_in_script(char_u *name, size_t len, int sid)
2616 {
2617     scriptitem_T    *si;
2618     int		    idx;
2619 
2620     if (!SCRIPT_ID_VALID(sid))
2621 	return NULL;
2622     si = SCRIPT_ITEM(sid);
2623     for (idx = 0; idx < si->sn_imports.ga_len; ++idx)
2624     {
2625 	imported_T *import = ((imported_T *)si->sn_imports.ga_data) + idx;
2626 
2627 	if (len == 0 ? STRCMP(name, import->imp_name) == 0
2628 		     : STRLEN(import->imp_name) == len
2629 				  && STRNCMP(name, import->imp_name, len) == 0)
2630 	    return import;
2631     }
2632     return NULL;
2633 }
2634 
2635 /*
2636  * Free all imported variables.
2637  */
2638     static void
free_imported(cctx_T * cctx)2639 free_imported(cctx_T *cctx)
2640 {
2641     int idx;
2642 
2643     for (idx = 0; idx < cctx->ctx_imports.ga_len; ++idx)
2644     {
2645 	imported_T *import = ((imported_T *)cctx->ctx_imports.ga_data) + idx;
2646 
2647 	vim_free(import->imp_name);
2648     }
2649     ga_clear(&cctx->ctx_imports);
2650 }
2651 
2652 /*
2653  * Return a pointer to the next line that isn't empty or only contains a
2654  * comment. Skips over white space.
2655  * Returns NULL if there is none.
2656  */
2657     char_u *
peek_next_line_from_context(cctx_T * cctx)2658 peek_next_line_from_context(cctx_T *cctx)
2659 {
2660     int lnum = cctx->ctx_lnum;
2661 
2662     while (++lnum < cctx->ctx_ufunc->uf_lines.ga_len)
2663     {
2664 	char_u *line = ((char_u **)cctx->ctx_ufunc->uf_lines.ga_data)[lnum];
2665 	char_u *p;
2666 
2667 	// ignore NULLs inserted for continuation lines
2668 	if (line != NULL)
2669 	{
2670 	    p = skipwhite(line);
2671 	    if (vim9_bad_comment(p))
2672 		return NULL;
2673 	    if (*p != NUL && !vim9_comment_start(p))
2674 		return p;
2675 	}
2676     }
2677     return NULL;
2678 }
2679 
2680 /*
2681  * Called when checking for a following operator at "arg".  When the rest of
2682  * the line is empty or only a comment, peek the next line.  If there is a next
2683  * line return a pointer to it and set "nextp".
2684  * Otherwise skip over white space.
2685  */
2686     static char_u *
may_peek_next_line(cctx_T * cctx,char_u * arg,char_u ** nextp)2687 may_peek_next_line(cctx_T *cctx, char_u *arg, char_u **nextp)
2688 {
2689     char_u *p = skipwhite(arg);
2690 
2691     *nextp = NULL;
2692     if (*p == NUL || (VIM_ISWHITE(*arg) && vim9_comment_start(p)))
2693     {
2694 	*nextp = peek_next_line_from_context(cctx);
2695 	if (*nextp != NULL)
2696 	    return *nextp;
2697     }
2698     return p;
2699 }
2700 
2701 /*
2702  * Get the next line of the function from "cctx".
2703  * Skips over empty lines.  Skips over comment lines if "skip_comment" is TRUE.
2704  * Returns NULL when at the end.
2705  */
2706     char_u *
next_line_from_context(cctx_T * cctx,int skip_comment)2707 next_line_from_context(cctx_T *cctx, int skip_comment)
2708 {
2709     char_u	*line;
2710 
2711     do
2712     {
2713 	++cctx->ctx_lnum;
2714 	if (cctx->ctx_lnum >= cctx->ctx_ufunc->uf_lines.ga_len)
2715 	{
2716 	    line = NULL;
2717 	    break;
2718 	}
2719 	line = ((char_u **)cctx->ctx_ufunc->uf_lines.ga_data)[cctx->ctx_lnum];
2720 	cctx->ctx_line_start = line;
2721 	SOURCING_LNUM = cctx->ctx_lnum + 1;
2722     } while (line == NULL || *skipwhite(line) == NUL
2723 		     || (skip_comment && vim9_comment_start(skipwhite(line))));
2724     return line;
2725 }
2726 
2727 /*
2728  * Skip over white space at "whitep" and assign to "*arg".
2729  * If "*arg" is at the end of the line, advance to the next line.
2730  * Also when "whitep" points to white space and "*arg" is on a "#".
2731  * Return FAIL if beyond the last line, "*arg" is unmodified then.
2732  */
2733     static int
may_get_next_line(char_u * whitep,char_u ** arg,cctx_T * cctx)2734 may_get_next_line(char_u *whitep, char_u **arg, cctx_T *cctx)
2735 {
2736     *arg = skipwhite(whitep);
2737     if (vim9_bad_comment(*arg))
2738 	return FAIL;
2739     if (**arg == NUL || (VIM_ISWHITE(*whitep) && vim9_comment_start(*arg)))
2740     {
2741 	char_u *next = next_line_from_context(cctx, TRUE);
2742 
2743 	if (next == NULL)
2744 	    return FAIL;
2745 	*arg = skipwhite(next);
2746     }
2747     return OK;
2748 }
2749 
2750 /*
2751  * Idem, and give an error when failed.
2752  */
2753     static int
may_get_next_line_error(char_u * whitep,char_u ** arg,cctx_T * cctx)2754 may_get_next_line_error(char_u *whitep, char_u **arg, cctx_T *cctx)
2755 {
2756     if (may_get_next_line(whitep, arg, cctx) == FAIL)
2757     {
2758 	SOURCING_LNUM = cctx->ctx_lnum + 1;
2759 	emsg(_(e_line_incomplete));
2760 	return FAIL;
2761     }
2762     return OK;
2763 }
2764 
2765 
2766 // Structure passed between the compile_expr* functions to keep track of
2767 // constants that have been parsed but for which no code was produced yet.  If
2768 // possible expressions on these constants are applied at compile time.  If
2769 // that is not possible, the code to push the constants needs to be generated
2770 // before other instructions.
2771 // Using 50 should be more than enough of 5 levels of ().
2772 #define PPSIZE 50
2773 typedef struct {
2774     typval_T	pp_tv[PPSIZE];	// stack of ppconst constants
2775     int		pp_used;	// active entries in pp_tv[]
2776     int		pp_is_const;	// all generated code was constants, used for a
2777 				// list or dict with constant members
2778 } ppconst_T;
2779 
2780 static int compile_expr0_ext(char_u **arg,  cctx_T *cctx, int *is_const);
2781 static int compile_expr0(char_u **arg,  cctx_T *cctx);
2782 static int compile_expr1(char_u **arg,  cctx_T *cctx, ppconst_T *ppconst);
2783 
2784 /*
2785  * Generate a PUSH instruction for "tv".
2786  * "tv" will be consumed or cleared.
2787  * Nothing happens if "tv" is NULL or of type VAR_UNKNOWN;
2788  */
2789     static int
generate_tv_PUSH(cctx_T * cctx,typval_T * tv)2790 generate_tv_PUSH(cctx_T *cctx, typval_T *tv)
2791 {
2792     if (tv != NULL)
2793     {
2794 	switch (tv->v_type)
2795 	{
2796 	    case VAR_UNKNOWN:
2797 		break;
2798 	    case VAR_BOOL:
2799 		generate_PUSHBOOL(cctx, tv->vval.v_number);
2800 		break;
2801 	    case VAR_SPECIAL:
2802 		generate_PUSHSPEC(cctx, tv->vval.v_number);
2803 		break;
2804 	    case VAR_NUMBER:
2805 		generate_PUSHNR(cctx, tv->vval.v_number);
2806 		break;
2807 #ifdef FEAT_FLOAT
2808 	    case VAR_FLOAT:
2809 		generate_PUSHF(cctx, tv->vval.v_float);
2810 		break;
2811 #endif
2812 	    case VAR_BLOB:
2813 		generate_PUSHBLOB(cctx, tv->vval.v_blob);
2814 		tv->vval.v_blob = NULL;
2815 		break;
2816 	    case VAR_STRING:
2817 		generate_PUSHS(cctx, &tv->vval.v_string);
2818 		tv->vval.v_string = NULL;
2819 		break;
2820 	    default:
2821 		iemsg("constant type not supported");
2822 		clear_tv(tv);
2823 		return FAIL;
2824 	}
2825 	tv->v_type = VAR_UNKNOWN;
2826     }
2827     return OK;
2828 }
2829 
2830 /*
2831  * Generate code for any ppconst entries.
2832  */
2833     static int
generate_ppconst(cctx_T * cctx,ppconst_T * ppconst)2834 generate_ppconst(cctx_T *cctx, ppconst_T *ppconst)
2835 {
2836     int	    i;
2837     int	    ret = OK;
2838     int	    save_skip = cctx->ctx_skip;
2839 
2840     cctx->ctx_skip = SKIP_NOT;
2841     for (i = 0; i < ppconst->pp_used; ++i)
2842 	if (generate_tv_PUSH(cctx, &ppconst->pp_tv[i]) == FAIL)
2843 	    ret = FAIL;
2844     ppconst->pp_used = 0;
2845     cctx->ctx_skip = save_skip;
2846     return ret;
2847 }
2848 
2849 /*
2850  * Check that the last item of "ppconst" is a bool, if there is an item.
2851  */
2852     static int
check_ppconst_bool(ppconst_T * ppconst)2853 check_ppconst_bool(ppconst_T *ppconst)
2854 {
2855     if (ppconst->pp_used > 0)
2856     {
2857 	typval_T    *tv = &ppconst->pp_tv[ppconst->pp_used - 1];
2858 	where_T	    where = WHERE_INIT;
2859 
2860 	return check_typval_type(&t_bool, tv, where);
2861     }
2862     return OK;
2863 }
2864 
2865 /*
2866  * Clear ppconst constants.  Used when failing.
2867  */
2868     static void
clear_ppconst(ppconst_T * ppconst)2869 clear_ppconst(ppconst_T *ppconst)
2870 {
2871     int	    i;
2872 
2873     for (i = 0; i < ppconst->pp_used; ++i)
2874 	clear_tv(&ppconst->pp_tv[i]);
2875     ppconst->pp_used = 0;
2876 }
2877 
2878 /*
2879  * Compile getting a member from a list/dict/string/blob.  Stack has the
2880  * indexable value and the index or the two indexes of a slice.
2881  * "keeping_dict" is used for dict[func](arg) to pass dict to func.
2882  */
2883     static int
compile_member(int is_slice,int * keeping_dict,cctx_T * cctx)2884 compile_member(int is_slice, int *keeping_dict, cctx_T *cctx)
2885 {
2886     type_T	**typep;
2887     garray_T	*stack = &cctx->ctx_type_stack;
2888     vartype_T	vartype;
2889     type_T	*idxtype;
2890 
2891     // We can index a list, dict and blob.  If we don't know the type
2892     // we can use the index value type.  If we still don't know use an "ANY"
2893     // instruction.
2894     typep = ((type_T **)stack->ga_data) + stack->ga_len
2895 						  - (is_slice ? 3 : 2);
2896     vartype = (*typep)->tt_type;
2897     idxtype = ((type_T **)stack->ga_data)[stack->ga_len - 1];
2898     // If the index is a string, the variable must be a Dict.
2899     if (*typep == &t_any && idxtype == &t_string)
2900 	vartype = VAR_DICT;
2901     if (vartype == VAR_STRING || vartype == VAR_LIST || vartype == VAR_BLOB)
2902     {
2903 	if (need_type(idxtype, &t_number, -1, 0, cctx, FALSE, FALSE) == FAIL)
2904 	    return FAIL;
2905 	if (is_slice)
2906 	{
2907 	    idxtype = ((type_T **)stack->ga_data)[stack->ga_len - 2];
2908 	    if (need_type(idxtype, &t_number, -2, 0, cctx,
2909 							 FALSE, FALSE) == FAIL)
2910 		return FAIL;
2911 	}
2912     }
2913 
2914     if (vartype == VAR_DICT)
2915     {
2916 	if (is_slice)
2917 	{
2918 	    emsg(_(e_cannot_slice_dictionary));
2919 	    return FAIL;
2920 	}
2921 	if ((*typep)->tt_type == VAR_DICT)
2922 	{
2923 	    *typep = (*typep)->tt_member;
2924 	    if (*typep == &t_unknown)
2925 		// empty dict was used
2926 		*typep = &t_any;
2927 	}
2928 	else
2929 	{
2930 	    if (need_type(*typep, &t_dict_any, -2, 0, cctx,
2931 							 FALSE, FALSE) == FAIL)
2932 		return FAIL;
2933 	    *typep = &t_any;
2934 	}
2935 	if (may_generate_2STRING(-1, FALSE, cctx) == FAIL)
2936 	    return FAIL;
2937 	if (generate_instr_drop(cctx, ISN_MEMBER, 1) == FAIL)
2938 	    return FAIL;
2939 	if (keeping_dict != NULL)
2940 	    *keeping_dict = TRUE;
2941     }
2942     else if (vartype == VAR_STRING)
2943     {
2944 	*typep = &t_string;
2945 	if ((is_slice
2946 		? generate_instr_drop(cctx, ISN_STRSLICE, 2)
2947 		: generate_instr_drop(cctx, ISN_STRINDEX, 1)) == FAIL)
2948 	    return FAIL;
2949     }
2950     else if (vartype == VAR_BLOB)
2951     {
2952 	if (is_slice)
2953 	{
2954 	    *typep = &t_blob;
2955 	    if (generate_instr_drop(cctx, ISN_BLOBSLICE, 2) == FAIL)
2956 		return FAIL;
2957 	}
2958 	else
2959 	{
2960 	    *typep = &t_number;
2961 	    if (generate_instr_drop(cctx, ISN_BLOBINDEX, 1) == FAIL)
2962 		return FAIL;
2963 	}
2964     }
2965     else if (vartype == VAR_LIST || *typep == &t_any)
2966     {
2967 	if (is_slice)
2968 	{
2969 	    if (generate_instr_drop(cctx,
2970 		     vartype == VAR_LIST ?  ISN_LISTSLICE : ISN_ANYSLICE,
2971 							    2) == FAIL)
2972 		return FAIL;
2973 	}
2974 	else
2975 	{
2976 	    if ((*typep)->tt_type == VAR_LIST)
2977 	    {
2978 		*typep = (*typep)->tt_member;
2979 		if (*typep == &t_unknown)
2980 		    // empty list was used
2981 		    *typep = &t_any;
2982 	    }
2983 	    if (generate_instr_drop(cctx,
2984 			vartype == VAR_LIST ?  ISN_LISTINDEX : ISN_ANYINDEX, 1)
2985 								       == FAIL)
2986 		return FAIL;
2987 	}
2988     }
2989     else
2990     {
2991 	emsg(_(e_string_list_dict_or_blob_required));
2992 	return FAIL;
2993     }
2994     return OK;
2995 }
2996 
2997 /*
2998  * Generate an instruction to load script-local variable "name", without the
2999  * leading "s:".
3000  * Also finds imported variables.
3001  */
3002     static int
compile_load_scriptvar(cctx_T * cctx,char_u * name,char_u * start,char_u ** end,int error)3003 compile_load_scriptvar(
3004 	cctx_T *cctx,
3005 	char_u *name,	    // variable NUL terminated
3006 	char_u *start,	    // start of variable
3007 	char_u **end,	    // end of variable
3008 	int    error)	    // when TRUE may give error
3009 {
3010     scriptitem_T    *si;
3011     int		    idx;
3012     imported_T	    *import;
3013 
3014     if (!SCRIPT_ID_VALID(current_sctx.sc_sid))
3015 	return FAIL;
3016     si = SCRIPT_ITEM(current_sctx.sc_sid);
3017     idx = get_script_item_idx(current_sctx.sc_sid, name, 0, cctx);
3018     if (idx == -1 || si->sn_version != SCRIPT_VERSION_VIM9)
3019     {
3020 	// variable is not in sn_var_vals: old style script.
3021 	return generate_OLDSCRIPT(cctx, ISN_LOADS, name, current_sctx.sc_sid,
3022 								       &t_any);
3023     }
3024     if (idx >= 0)
3025     {
3026 	svar_T		*sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
3027 
3028 	generate_VIM9SCRIPT(cctx, ISN_LOADSCRIPT,
3029 					current_sctx.sc_sid, idx, sv->sv_type);
3030 	return OK;
3031     }
3032 
3033     import = find_imported(name, 0, cctx);
3034     if (import != NULL)
3035     {
3036 	if (import->imp_flags & IMP_FLAGS_STAR)
3037 	{
3038 	    char_u	*p = skipwhite(*end);
3039 	    char_u	*exp_name;
3040 	    int		cc;
3041 	    ufunc_T	*ufunc;
3042 	    type_T	*type;
3043 
3044 	    // Used "import * as Name", need to lookup the member.
3045 	    if (*p != '.')
3046 	    {
3047 		semsg(_(e_expected_dot_after_name_str), start);
3048 		return FAIL;
3049 	    }
3050 	    ++p;
3051 	    if (VIM_ISWHITE(*p))
3052 	    {
3053 		emsg(_(e_no_white_space_allowed_after_dot));
3054 		return FAIL;
3055 	    }
3056 
3057 	    // isolate one name
3058 	    exp_name = p;
3059 	    while (eval_isnamec(*p))
3060 		++p;
3061 	    cc = *p;
3062 	    *p = NUL;
3063 
3064 	    idx = find_exported(import->imp_sid, exp_name, &ufunc, &type,
3065 								   cctx, TRUE);
3066 	    *p = cc;
3067 	    p = skipwhite(p);
3068 	    *end = p;
3069 
3070 	    if (idx < 0)
3071 	    {
3072 		if (*p == '(' && ufunc != NULL)
3073 		{
3074 		    generate_PUSHFUNC(cctx, ufunc->uf_name, import->imp_type);
3075 		    return OK;
3076 		}
3077 		return FAIL;
3078 	    }
3079 
3080 	    generate_VIM9SCRIPT(cctx, ISN_LOADSCRIPT,
3081 		    import->imp_sid,
3082 		    idx,
3083 		    type);
3084 	}
3085 	else if (import->imp_funcname != NULL)
3086 	    generate_PUSHFUNC(cctx, import->imp_funcname, import->imp_type);
3087 	else
3088 	    generate_VIM9SCRIPT(cctx, ISN_LOADSCRIPT,
3089 		    import->imp_sid,
3090 		    import->imp_var_vals_idx,
3091 		    import->imp_type);
3092 	return OK;
3093     }
3094 
3095     if (error)
3096 	semsg(_(e_item_not_found_str), name);
3097     return FAIL;
3098 }
3099 
3100     static int
generate_funcref(cctx_T * cctx,char_u * name)3101 generate_funcref(cctx_T *cctx, char_u *name)
3102 {
3103     ufunc_T *ufunc = find_func(name, FALSE, cctx);
3104 
3105     if (ufunc == NULL)
3106 	return FAIL;
3107 
3108     // Need to compile any default values to get the argument types.
3109     if (func_needs_compiling(ufunc, COMPILE_TYPE(ufunc))
3110 	    && compile_def_function(ufunc, TRUE, COMPILE_TYPE(ufunc), NULL)
3111 								       == FAIL)
3112 	return FAIL;
3113     return generate_PUSHFUNC(cctx, ufunc->uf_name, ufunc->uf_func_type);
3114 }
3115 
3116 /*
3117  * Compile a variable name into a load instruction.
3118  * "end" points to just after the name.
3119  * "is_expr" is TRUE when evaluating an expression, might be a funcref.
3120  * When "error" is FALSE do not give an error when not found.
3121  */
3122     static int
compile_load(char_u ** arg,char_u * end_arg,cctx_T * cctx,int is_expr,int error)3123 compile_load(
3124 	char_u **arg,
3125 	char_u *end_arg,
3126 	cctx_T	*cctx,
3127 	int	is_expr,
3128 	int	error)
3129 {
3130     type_T	*type;
3131     char_u	*name = NULL;
3132     char_u	*end = end_arg;
3133     int		res = FAIL;
3134     int		prev_called_emsg = called_emsg;
3135 
3136     if (*(*arg + 1) == ':')
3137     {
3138 	if (end <= *arg + 2)
3139 	{
3140 	    isntype_T  isn_type;
3141 
3142 	    // load dictionary of namespace
3143 	    switch (**arg)
3144 	    {
3145 		case 'g': isn_type = ISN_LOADGDICT; break;
3146 		case 'w': isn_type = ISN_LOADWDICT; break;
3147 		case 't': isn_type = ISN_LOADTDICT; break;
3148 		case 'b': isn_type = ISN_LOADBDICT; break;
3149 		default:
3150 		    semsg(_(e_namespace_not_supported_str), *arg);
3151 		    goto theend;
3152 	    }
3153 	    if (generate_instr_type(cctx, isn_type, &t_dict_any) == NULL)
3154 		goto theend;
3155 	    res = OK;
3156 	}
3157 	else
3158 	{
3159 	    isntype_T  isn_type = ISN_DROP;
3160 
3161 	    // load namespaced variable
3162 	    name = vim_strnsave(*arg + 2, end - (*arg + 2));
3163 	    if (name == NULL)
3164 		return FAIL;
3165 
3166 	    switch (**arg)
3167 	    {
3168 		case 'v': res = generate_LOADV(cctx, name, error);
3169 			  break;
3170 		case 's': if (is_expr && ASCII_ISUPPER(*name)
3171 				       && find_func(name, FALSE, cctx) != NULL)
3172 			      res = generate_funcref(cctx, name);
3173 			  else
3174 			      res = compile_load_scriptvar(cctx, name,
3175 							    NULL, &end, error);
3176 			  break;
3177 		case 'g': if (vim_strchr(name, AUTOLOAD_CHAR) == NULL)
3178 			  {
3179 			      if (is_expr && ASCII_ISUPPER(*name)
3180 				       && find_func(name, FALSE, cctx) != NULL)
3181 				  res = generate_funcref(cctx, name);
3182 			      else
3183 				  isn_type = ISN_LOADG;
3184 			  }
3185 			  else
3186 			  {
3187 			      isn_type = ISN_LOADAUTO;
3188 			      vim_free(name);
3189 			      name = vim_strnsave(*arg, end - *arg);
3190 			      if (name == NULL)
3191 				  return FAIL;
3192 			  }
3193 			  break;
3194 		case 'w': isn_type = ISN_LOADW; break;
3195 		case 't': isn_type = ISN_LOADT; break;
3196 		case 'b': isn_type = ISN_LOADB; break;
3197 		default:  // cannot happen, just in case
3198 			  semsg(_(e_namespace_not_supported_str), *arg);
3199 			  goto theend;
3200 	    }
3201 	    if (isn_type != ISN_DROP)
3202 	    {
3203 		// Global, Buffer-local, Window-local and Tabpage-local
3204 		// variables can be defined later, thus we don't check if it
3205 		// exists, give an error at runtime.
3206 		res = generate_LOAD(cctx, isn_type, 0, name, &t_any);
3207 	    }
3208 	}
3209     }
3210     else
3211     {
3212 	size_t	    len = end - *arg;
3213 	int	    idx;
3214 	int	    gen_load = FALSE;
3215 	int	    gen_load_outer = 0;
3216 
3217 	name = vim_strnsave(*arg, end - *arg);
3218 	if (name == NULL)
3219 	    return FAIL;
3220 
3221 	if (vim_strchr(name, AUTOLOAD_CHAR) != NULL)
3222 	{
3223 	    script_autoload(name, FALSE);
3224 	    res = generate_LOAD(cctx, ISN_LOADAUTO, 0, name, &t_any);
3225 	}
3226 	else if (arg_exists(*arg, len, &idx, &type, &gen_load_outer, cctx)
3227 									 == OK)
3228 	{
3229 	    if (gen_load_outer == 0)
3230 		gen_load = TRUE;
3231 	}
3232 	else
3233 	{
3234 	    lvar_T lvar;
3235 
3236 	    if (lookup_local(*arg, len, &lvar, cctx) == OK)
3237 	    {
3238 		type = lvar.lv_type;
3239 		idx = lvar.lv_idx;
3240 		if (lvar.lv_from_outer != 0)
3241 		    gen_load_outer = lvar.lv_from_outer;
3242 		else
3243 		    gen_load = TRUE;
3244 	    }
3245 	    else
3246 	    {
3247 		// "var" can be script-local even without using "s:" if it
3248 		// already exists in a Vim9 script or when it's imported.
3249 		if (script_var_exists(*arg, len, cctx) == OK
3250 			|| find_imported(name, 0, cctx) != NULL)
3251 		   res = compile_load_scriptvar(cctx, name, *arg, &end, FALSE);
3252 
3253 		// When evaluating an expression and the name starts with an
3254 		// uppercase letter it can be a user defined function.
3255 		// generate_funcref() will fail if the function can't be found.
3256 		if (res == FAIL && is_expr && ASCII_ISUPPER(*name))
3257 		    res = generate_funcref(cctx, name);
3258 	    }
3259 	}
3260 	if (gen_load)
3261 	    res = generate_LOAD(cctx, ISN_LOAD, idx, NULL, type);
3262 	if (gen_load_outer > 0)
3263 	{
3264 	    res = generate_LOADOUTER(cctx, idx, gen_load_outer, type);
3265 	    cctx->ctx_outer_used = TRUE;
3266 	}
3267     }
3268 
3269     *arg = end;
3270 
3271 theend:
3272     if (res == FAIL && error && called_emsg == prev_called_emsg)
3273 	semsg(_(e_variable_not_found_str), name);
3274     vim_free(name);
3275     return res;
3276 }
3277 
3278     static void
clear_instr_ga(garray_T * gap)3279 clear_instr_ga(garray_T *gap)
3280 {
3281     int idx;
3282 
3283     for (idx = 0; idx < gap->ga_len; ++idx)
3284 	delete_instr(((isn_T *)gap->ga_data) + idx);
3285     ga_clear(gap);
3286 }
3287 
3288 /*
3289  * Compile a string in a ISN_PUSHS instruction into an ISN_INSTR.
3290  * Returns FAIL if compilation fails.
3291  */
3292     static int
compile_string(isn_T * isn,cctx_T * cctx)3293 compile_string(isn_T *isn, cctx_T *cctx)
3294 {
3295     char_u	*s = isn->isn_arg.string;
3296     garray_T	save_ga = cctx->ctx_instr;
3297     int		expr_res;
3298     int		trailing_error;
3299     int		instr_count;
3300     isn_T	*instr = NULL;
3301 
3302     // Remove the string type from the stack.
3303     --cctx->ctx_type_stack.ga_len;
3304 
3305     // Temporarily reset the list of instructions so that the jump labels are
3306     // correct.
3307     cctx->ctx_instr.ga_len = 0;
3308     cctx->ctx_instr.ga_maxlen = 0;
3309     cctx->ctx_instr.ga_data = NULL;
3310     expr_res = compile_expr0(&s, cctx);
3311     s = skipwhite(s);
3312     trailing_error = *s != NUL;
3313 
3314     if (expr_res == FAIL || trailing_error
3315 				       || GA_GROW_FAILS(&cctx->ctx_instr, 1))
3316     {
3317 	if (trailing_error)
3318 	    semsg(_(e_trailing_arg), s);
3319 	clear_instr_ga(&cctx->ctx_instr);
3320 	cctx->ctx_instr = save_ga;
3321 	++cctx->ctx_type_stack.ga_len;
3322 	return FAIL;
3323     }
3324 
3325     // Move the generated instructions into the ISN_INSTR instruction, then
3326     // restore the list of instructions.
3327     instr_count = cctx->ctx_instr.ga_len;
3328     instr = cctx->ctx_instr.ga_data;
3329     instr[instr_count].isn_type = ISN_FINISH;
3330 
3331     cctx->ctx_instr = save_ga;
3332     vim_free(isn->isn_arg.string);
3333     isn->isn_type = ISN_INSTR;
3334     isn->isn_arg.instr = instr;
3335     return OK;
3336 }
3337 
3338 /*
3339  * Compile the argument expressions.
3340  * "arg" points to just after the "(" and is advanced to after the ")"
3341  */
3342     static int
compile_arguments(char_u ** arg,cctx_T * cctx,int * argcount,int is_searchpair)3343 compile_arguments(char_u **arg, cctx_T *cctx, int *argcount, int is_searchpair)
3344 {
3345     char_u  *p = *arg;
3346     char_u  *whitep = *arg;
3347     int	    must_end = FALSE;
3348     int	    instr_count;
3349 
3350     for (;;)
3351     {
3352 	if (may_get_next_line(whitep, &p, cctx) == FAIL)
3353 	    goto failret;
3354 	if (*p == ')')
3355 	{
3356 	    *arg = p + 1;
3357 	    return OK;
3358 	}
3359 	if (must_end)
3360 	{
3361 	    semsg(_(e_missing_comma_before_argument_str), p);
3362 	    return FAIL;
3363 	}
3364 
3365 	instr_count = cctx->ctx_instr.ga_len;
3366 	if (compile_expr0(&p, cctx) == FAIL)
3367 	    return FAIL;
3368 	++*argcount;
3369 
3370 	if (is_searchpair && *argcount == 5
3371 		&& cctx->ctx_instr.ga_len == instr_count + 1)
3372 	{
3373 	    isn_T *isn = ((isn_T *)cctx->ctx_instr.ga_data) + instr_count;
3374 
3375 	    // {skip} argument of searchpair() can be compiled if not empty
3376 	    if (isn->isn_type == ISN_PUSHS && *isn->isn_arg.string != NUL)
3377 		compile_string(isn, cctx);
3378 	}
3379 
3380 	if (*p != ',' && *skipwhite(p) == ',')
3381 	{
3382 	    semsg(_(e_no_white_space_allowed_before_str_str), ",", p);
3383 	    p = skipwhite(p);
3384 	}
3385 	if (*p == ',')
3386 	{
3387 	    ++p;
3388 	    if (*p != NUL && !VIM_ISWHITE(*p))
3389 		semsg(_(e_white_space_required_after_str_str), ",", p - 1);
3390 	}
3391 	else
3392 	    must_end = TRUE;
3393 	whitep = p;
3394 	p = skipwhite(p);
3395     }
3396 failret:
3397     emsg(_(e_missing_close));
3398     return FAIL;
3399 }
3400 
3401 /*
3402  * Compile a function call:  name(arg1, arg2)
3403  * "arg" points to "name", "arg + varlen" to the "(".
3404  * "argcount_init" is 1 for "value->method()"
3405  * Instructions:
3406  *	EVAL arg1
3407  *	EVAL arg2
3408  *	BCALL / DCALL / UCALL
3409  */
3410     static int
compile_call(char_u ** arg,size_t varlen,cctx_T * cctx,ppconst_T * ppconst,int argcount_init)3411 compile_call(
3412 	char_u	    **arg,
3413 	size_t	    varlen,
3414 	cctx_T	    *cctx,
3415 	ppconst_T   *ppconst,
3416 	int	    argcount_init)
3417 {
3418     char_u	*name = *arg;
3419     char_u	*p;
3420     int		argcount = argcount_init;
3421     char_u	namebuf[100];
3422     char_u	fname_buf[FLEN_FIXED + 1];
3423     char_u	*tofree = NULL;
3424     int		error = FCERR_NONE;
3425     ufunc_T	*ufunc = NULL;
3426     int		res = FAIL;
3427     int		is_autoload;
3428     int		is_searchpair;
3429 
3430     // We can evaluate "has('name')" at compile time.
3431     // We always evaluate "exists_compiled()" at compile time.
3432     if ((varlen == 3 && STRNCMP(*arg, "has", 3) == 0)
3433 	    || (varlen == 15 && STRNCMP(*arg, "exists_compiled", 6) == 0))
3434     {
3435 	char_u	    *s = skipwhite(*arg + varlen + 1);
3436 	typval_T    argvars[2];
3437 	int	    is_has = **arg == 'h';
3438 
3439 	argvars[0].v_type = VAR_UNKNOWN;
3440 	if (*s == '"')
3441 	    (void)eval_string(&s, &argvars[0], TRUE);
3442 	else if (*s == '\'')
3443 	    (void)eval_lit_string(&s, &argvars[0], TRUE);
3444 	s = skipwhite(s);
3445 	if (*s == ')' && argvars[0].v_type == VAR_STRING
3446 	       && ((is_has && !dynamic_feature(argvars[0].vval.v_string))
3447 		    || !is_has))
3448 	{
3449 	    typval_T	*tv = &ppconst->pp_tv[ppconst->pp_used];
3450 
3451 	    *arg = s + 1;
3452 	    argvars[1].v_type = VAR_UNKNOWN;
3453 	    tv->v_type = VAR_NUMBER;
3454 	    tv->vval.v_number = 0;
3455 	    if (is_has)
3456 		f_has(argvars, tv);
3457 	    else
3458 		f_exists(argvars, tv);
3459 	    clear_tv(&argvars[0]);
3460 	    ++ppconst->pp_used;
3461 	    return OK;
3462 	}
3463 	clear_tv(&argvars[0]);
3464 	if (!is_has)
3465 	{
3466 	    emsg(_(e_argument_of_exists_compiled_must_be_literal_string));
3467 	    return FAIL;
3468 	}
3469     }
3470 
3471     if (generate_ppconst(cctx, ppconst) == FAIL)
3472 	return FAIL;
3473 
3474     if (varlen >= sizeof(namebuf))
3475     {
3476 	semsg(_(e_name_too_long_str), name);
3477 	return FAIL;
3478     }
3479     vim_strncpy(namebuf, *arg, varlen);
3480     name = fname_trans_sid(namebuf, fname_buf, &tofree, &error);
3481 
3482     // We handle the "skip" argument of searchpair() and searchpairpos()
3483     // differently.
3484     is_searchpair = (varlen == 6 && STRNCMP(*arg, "search", 6) == 0)
3485 	         || (varlen == 9 && STRNCMP(*arg, "searchpos", 9) == 0)
3486 	        || (varlen == 10 && STRNCMP(*arg, "searchpair", 10) == 0)
3487 	        || (varlen == 13 && STRNCMP(*arg, "searchpairpos", 13) == 0);
3488 
3489     *arg = skipwhite(*arg + varlen + 1);
3490     if (compile_arguments(arg, cctx, &argcount, is_searchpair) == FAIL)
3491 	goto theend;
3492 
3493     is_autoload = vim_strchr(name, AUTOLOAD_CHAR) != NULL;
3494     if (ASCII_ISLOWER(*name) && name[1] != ':' && !is_autoload)
3495     {
3496 	int	    idx;
3497 
3498 	// builtin function
3499 	idx = find_internal_func(name);
3500 	if (idx >= 0)
3501 	{
3502 	    if (STRCMP(name, "flatten") == 0)
3503 	    {
3504 		emsg(_(e_cannot_use_flatten_in_vim9_script));
3505 		goto theend;
3506 	    }
3507 
3508 	    if (STRCMP(name, "add") == 0 && argcount == 2)
3509 	    {
3510 		garray_T    *stack = &cctx->ctx_type_stack;
3511 		type_T	    *type = ((type_T **)stack->ga_data)[
3512 							    stack->ga_len - 2];
3513 
3514 		// add() can be compiled to instructions if we know the type
3515 		if (type->tt_type == VAR_LIST)
3516 		{
3517 		    // inline "add(list, item)" so that the type can be checked
3518 		    res = generate_LISTAPPEND(cctx);
3519 		    idx = -1;
3520 		}
3521 		else if (type->tt_type == VAR_BLOB)
3522 		{
3523 		    // inline "add(blob, nr)" so that the type can be checked
3524 		    res = generate_BLOBAPPEND(cctx);
3525 		    idx = -1;
3526 		}
3527 	    }
3528 
3529 	    if (idx >= 0)
3530 		res = generate_BCALL(cctx, idx, argcount, argcount_init == 1);
3531 	}
3532 	else
3533 	    semsg(_(e_unknownfunc), namebuf);
3534 	goto theend;
3535     }
3536 
3537     // An argument or local variable can be a function reference, this
3538     // overrules a function name.
3539     if (lookup_local(namebuf, varlen, NULL, cctx) == FAIL
3540 	    && arg_exists(namebuf, varlen, NULL, NULL, NULL, cctx) != OK)
3541     {
3542 	// If we can find the function by name generate the right call.
3543 	// Skip global functions here, a local funcref takes precedence.
3544 	ufunc = find_func(name, FALSE, cctx);
3545 	if (ufunc != NULL && !func_is_global(ufunc))
3546 	{
3547 	    res = generate_CALL(cctx, ufunc, argcount);
3548 	    goto theend;
3549 	}
3550     }
3551 
3552     // If the name is a variable, load it and use PCALL.
3553     // Not for g:Func(), we don't know if it is a variable or not.
3554     // Not for eome#Func(), it will be loaded later.
3555     p = namebuf;
3556     if (STRNCMP(namebuf, "g:", 2) != 0 && !is_autoload
3557 	    && compile_load(&p, namebuf + varlen, cctx, FALSE, FALSE) == OK)
3558     {
3559 	garray_T    *stack = &cctx->ctx_type_stack;
3560 	type_T	    *type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
3561 
3562 	res = generate_PCALL(cctx, argcount, namebuf, type, FALSE);
3563 	goto theend;
3564     }
3565 
3566     // If we can find a global function by name generate the right call.
3567     if (ufunc != NULL)
3568     {
3569 	res = generate_CALL(cctx, ufunc, argcount);
3570 	goto theend;
3571     }
3572 
3573     // A global function may be defined only later.  Need to figure out at
3574     // runtime.  Also handles a FuncRef at runtime.
3575     if (STRNCMP(namebuf, "g:", 2) == 0 || is_autoload)
3576 	res = generate_UCALL(cctx, name, argcount);
3577     else
3578 	semsg(_(e_unknownfunc), namebuf);
3579 
3580 theend:
3581     vim_free(tofree);
3582     return res;
3583 }
3584 
3585 // like NAMESPACE_CHAR but with 'a' and 'l'.
3586 #define VIM9_NAMESPACE_CHAR	(char_u *)"bgstvw"
3587 
3588 /*
3589  * Find the end of a variable or function name.  Unlike find_name_end() this
3590  * does not recognize magic braces.
3591  * When "use_namespace" is TRUE recognize "b:", "s:", etc.
3592  * Return a pointer to just after the name.  Equal to "arg" if there is no
3593  * valid name.
3594  */
3595     char_u *
to_name_end(char_u * arg,int use_namespace)3596 to_name_end(char_u *arg, int use_namespace)
3597 {
3598     char_u	*p;
3599 
3600     // Quick check for valid starting character.
3601     if (!eval_isnamec1(*arg))
3602 	return arg;
3603 
3604     for (p = arg + 1; *p != NUL && eval_isnamec(*p); MB_PTR_ADV(p))
3605 	// Include a namespace such as "s:var" and "v:var".  But "n:" is not
3606 	// and can be used in slice "[n:]".
3607 	if (*p == ':' && (p != arg + 1
3608 			     || !use_namespace
3609 			     || vim_strchr(VIM9_NAMESPACE_CHAR, *arg) == NULL))
3610 	    break;
3611     return p;
3612 }
3613 
3614 /*
3615  * Like to_name_end() but also skip over a list or dict constant.
3616  * Also accept "<SNR>123_Func".
3617  * This intentionally does not handle line continuation.
3618  */
3619     char_u *
to_name_const_end(char_u * arg)3620 to_name_const_end(char_u *arg)
3621 {
3622     char_u	*p = arg;
3623     typval_T	rettv;
3624 
3625     if (STRNCMP(p, "<SNR>", 5) == 0)
3626 	p = skipdigits(p + 5);
3627     p = to_name_end(p, TRUE);
3628     if (p == arg && *arg == '[')
3629     {
3630 
3631 	// Can be "[1, 2, 3]->Func()".
3632 	if (eval_list(&p, &rettv, NULL, FALSE) == FAIL)
3633 	    p = arg;
3634     }
3635     return p;
3636 }
3637 
3638 /*
3639  * parse a list: [expr, expr]
3640  * "*arg" points to the '['.
3641  * ppconst->pp_is_const is set if all items are a constant.
3642  */
3643     static int
compile_list(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)3644 compile_list(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
3645 {
3646     char_u	*p = skipwhite(*arg + 1);
3647     char_u	*whitep = *arg + 1;
3648     int		count = 0;
3649     int		is_const;
3650     int		is_all_const = TRUE;	// reset when non-const encountered
3651 
3652     for (;;)
3653     {
3654 	if (may_get_next_line(whitep, &p, cctx) == FAIL)
3655 	{
3656 	    semsg(_(e_list_end), *arg);
3657 	    return FAIL;
3658 	}
3659 	if (*p == ',')
3660 	{
3661 	    semsg(_(e_no_white_space_allowed_before_str_str), ",", p);
3662 	    return FAIL;
3663 	}
3664 	if (*p == ']')
3665 	{
3666 	    ++p;
3667 	    break;
3668 	}
3669 	if (compile_expr0_ext(&p, cctx, &is_const) == FAIL)
3670 	    return FAIL;
3671 	if (!is_const)
3672 	    is_all_const = FALSE;
3673 	++count;
3674 	if (*p == ',')
3675 	{
3676 	    ++p;
3677 	    if (*p != ']' && !IS_WHITE_OR_NUL(*p))
3678 	    {
3679 		semsg(_(e_white_space_required_after_str_str), ",", p - 1);
3680 		return FAIL;
3681 	    }
3682 	}
3683 	whitep = p;
3684 	p = skipwhite(p);
3685     }
3686     *arg = p;
3687 
3688     ppconst->pp_is_const = is_all_const;
3689     return generate_NEWLIST(cctx, count);
3690 }
3691 
3692 /*
3693  * Parse a lambda: "(arg, arg) => expr"
3694  * "*arg" points to the '('.
3695  * Returns OK/FAIL when a lambda is recognized, NOTDONE if it's not a lambda.
3696  */
3697     static int
compile_lambda(char_u ** arg,cctx_T * cctx)3698 compile_lambda(char_u **arg, cctx_T *cctx)
3699 {
3700     int		r;
3701     typval_T	rettv;
3702     ufunc_T	*ufunc;
3703     evalarg_T	evalarg;
3704 
3705     init_evalarg(&evalarg);
3706     evalarg.eval_flags = EVAL_EVALUATE;
3707     evalarg.eval_cctx = cctx;
3708 
3709     // Get the funcref in "rettv".
3710     r = get_lambda_tv(arg, &rettv, TRUE, &evalarg);
3711     if (r != OK)
3712     {
3713 	clear_evalarg(&evalarg, NULL);
3714 	return r;
3715     }
3716 
3717     // "rettv" will now be a partial referencing the function.
3718     ufunc = rettv.vval.v_partial->pt_func;
3719     ++ufunc->uf_refcount;
3720     clear_tv(&rettv);
3721 
3722     // Compile it here to get the return type.  The return type is optional,
3723     // when it's missing use t_unknown.  This is recognized in
3724     // compile_return().
3725     if (ufunc->uf_ret_type->tt_type == VAR_VOID)
3726 	ufunc->uf_ret_type = &t_unknown;
3727     compile_def_function(ufunc, FALSE, cctx->ctx_compile_type, cctx);
3728 
3729 #ifdef FEAT_PROFILE
3730     // When the outer function is compiled for profiling, the lambda may be
3731     // called without profiling.  Compile it here in the right context.
3732     if (cctx->ctx_compile_type == CT_PROFILE)
3733 	compile_def_function(ufunc, FALSE, CT_NONE, cctx);
3734 #endif
3735 
3736     // The last entry in evalarg.eval_tofree_ga is a copy of the last line and
3737     // "*arg" may point into it.  Point into the original line to avoid a
3738     // dangling pointer.
3739     if (evalarg.eval_using_cmdline)
3740     {
3741 	garray_T    *gap = &evalarg.eval_tofree_ga;
3742 	size_t	    off = *arg - ((char_u **)gap->ga_data)[gap->ga_len - 1];
3743 
3744 	*arg = ((char_u **)cctx->ctx_ufunc->uf_lines.ga_data)[cctx->ctx_lnum]
3745 									 + off;
3746     }
3747 
3748     clear_evalarg(&evalarg, NULL);
3749 
3750     if (ufunc->uf_def_status == UF_COMPILED)
3751     {
3752 	// The return type will now be known.
3753 	set_function_type(ufunc);
3754 
3755 	// The function reference count will be 1.  When the ISN_FUNCREF
3756 	// instruction is deleted the reference count is decremented and the
3757 	// function is freed.
3758 	return generate_FUNCREF(cctx, ufunc);
3759     }
3760 
3761     func_ptr_unref(ufunc);
3762     return FAIL;
3763 }
3764 
3765 /*
3766  * Get a lambda and compile it.  Uses Vim9 syntax.
3767  */
3768     int
get_lambda_tv_and_compile(char_u ** arg,typval_T * rettv,int types_optional,evalarg_T * evalarg)3769 get_lambda_tv_and_compile(
3770 	char_u	    **arg,
3771 	typval_T    *rettv,
3772 	int	    types_optional,
3773 	evalarg_T   *evalarg)
3774 {
3775     int		r;
3776     ufunc_T	*ufunc;
3777     int		save_sc_version = current_sctx.sc_version;
3778 
3779     // Get the funcref in "rettv".
3780     current_sctx.sc_version = SCRIPT_VERSION_VIM9;
3781     r = get_lambda_tv(arg, rettv, types_optional, evalarg);
3782     current_sctx.sc_version = save_sc_version;
3783     if (r != OK)
3784 	return r;
3785 
3786     // "rettv" will now be a partial referencing the function.
3787     ufunc = rettv->vval.v_partial->pt_func;
3788 
3789     // Compile it here to get the return type.  The return type is optional,
3790     // when it's missing use t_unknown.  This is recognized in
3791     // compile_return().
3792     if (ufunc->uf_ret_type == NULL || ufunc->uf_ret_type->tt_type == VAR_VOID)
3793 	ufunc->uf_ret_type = &t_unknown;
3794     compile_def_function(ufunc, FALSE, CT_NONE, NULL);
3795 
3796     if (ufunc->uf_def_status == UF_COMPILED)
3797     {
3798 	// The return type will now be known.
3799 	set_function_type(ufunc);
3800 	return OK;
3801     }
3802     clear_tv(rettv);
3803     return FAIL;
3804 }
3805 
3806 /*
3807  * parse a dict: {key: val, [key]: val}
3808  * "*arg" points to the '{'.
3809  * ppconst->pp_is_const is set if all item values are a constant.
3810  */
3811     static int
compile_dict(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)3812 compile_dict(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
3813 {
3814     garray_T	*instr = &cctx->ctx_instr;
3815     int		count = 0;
3816     dict_T	*d = dict_alloc();
3817     dictitem_T	*item;
3818     char_u	*whitep = *arg + 1;
3819     char_u	*p;
3820     int		is_const;
3821     int		is_all_const = TRUE;	// reset when non-const encountered
3822 
3823     if (d == NULL)
3824 	return FAIL;
3825     if (generate_ppconst(cctx, ppconst) == FAIL)
3826 	return FAIL;
3827     for (;;)
3828     {
3829 	char_u	    *key = NULL;
3830 
3831 	if (may_get_next_line(whitep, arg, cctx) == FAIL)
3832 	{
3833 	    *arg = NULL;
3834 	    goto failret;
3835 	}
3836 
3837 	if (**arg == '}')
3838 	    break;
3839 
3840 	if (**arg == '[')
3841 	{
3842 	    isn_T	*isn;
3843 
3844 	    // {[expr]: value} uses an evaluated key.
3845 	    *arg = skipwhite(*arg + 1);
3846 	    if (compile_expr0(arg, cctx) == FAIL)
3847 		return FAIL;
3848 	    isn = ((isn_T *)instr->ga_data) + instr->ga_len - 1;
3849 	    if (isn->isn_type == ISN_PUSHNR)
3850 	    {
3851 		char buf[NUMBUFLEN];
3852 
3853 		// Convert to string at compile time.
3854 		vim_snprintf(buf, NUMBUFLEN, "%lld", isn->isn_arg.number);
3855 		isn->isn_type = ISN_PUSHS;
3856 		isn->isn_arg.string = vim_strsave((char_u *)buf);
3857 	    }
3858 	    if (isn->isn_type == ISN_PUSHS)
3859 		key = isn->isn_arg.string;
3860 	    else if (may_generate_2STRING(-1, FALSE, cctx) == FAIL)
3861 		return FAIL;
3862 	    *arg = skipwhite(*arg);
3863 	    if (**arg != ']')
3864 	    {
3865 		emsg(_(e_missing_matching_bracket_after_dict_key));
3866 		return FAIL;
3867 	    }
3868 	    ++*arg;
3869 	}
3870 	else
3871 	{
3872 	    // {"name": value},
3873 	    // {'name': value},
3874 	    // {name: value} use "name" as a literal key
3875 	    key = get_literal_key(arg);
3876 	    if (key == NULL)
3877 		return FAIL;
3878 	    if (generate_PUSHS(cctx, &key) == FAIL)
3879 		return FAIL;
3880 	}
3881 
3882 	// Check for duplicate keys, if using string keys.
3883 	if (key != NULL)
3884 	{
3885 	    item = dict_find(d, key, -1);
3886 	    if (item != NULL)
3887 	    {
3888 		semsg(_(e_duplicate_key), key);
3889 		goto failret;
3890 	    }
3891 	    item = dictitem_alloc(key);
3892 	    if (item != NULL)
3893 	    {
3894 		item->di_tv.v_type = VAR_UNKNOWN;
3895 		item->di_tv.v_lock = 0;
3896 		if (dict_add(d, item) == FAIL)
3897 		    dictitem_free(item);
3898 	    }
3899 	}
3900 
3901 	if (**arg != ':')
3902 	{
3903 	    if (*skipwhite(*arg) == ':')
3904 		semsg(_(e_no_white_space_allowed_before_str_str), ":", *arg);
3905 	    else
3906 		semsg(_(e_missing_dict_colon), *arg);
3907 	    return FAIL;
3908 	}
3909 	whitep = *arg + 1;
3910 	if (!IS_WHITE_OR_NUL(*whitep))
3911 	{
3912 	    semsg(_(e_white_space_required_after_str_str), ":", *arg);
3913 	    return FAIL;
3914 	}
3915 
3916 	if (may_get_next_line(whitep, arg, cctx) == FAIL)
3917 	{
3918 	    *arg = NULL;
3919 	    goto failret;
3920 	}
3921 
3922 	if (compile_expr0_ext(arg, cctx, &is_const) == FAIL)
3923 	    return FAIL;
3924 	if (!is_const)
3925 	    is_all_const = FALSE;
3926 	++count;
3927 
3928 	whitep = *arg;
3929 	if (may_get_next_line(whitep, arg, cctx) == FAIL)
3930 	{
3931 	    *arg = NULL;
3932 	    goto failret;
3933 	}
3934 	if (**arg == '}')
3935 	    break;
3936 	if (**arg != ',')
3937 	{
3938 	    semsg(_(e_missing_dict_comma), *arg);
3939 	    goto failret;
3940 	}
3941 	if (IS_WHITE_OR_NUL(*whitep))
3942 	{
3943 	    semsg(_(e_no_white_space_allowed_before_str_str), ",", whitep);
3944 	    return FAIL;
3945 	}
3946 	whitep = *arg + 1;
3947 	if (!IS_WHITE_OR_NUL(*whitep))
3948 	{
3949 	    semsg(_(e_white_space_required_after_str_str), ",", *arg);
3950 	    return FAIL;
3951 	}
3952 	*arg = skipwhite(whitep);
3953     }
3954 
3955     *arg = *arg + 1;
3956 
3957     // Allow for following comment, after at least one space.
3958     p = skipwhite(*arg);
3959     if (VIM_ISWHITE(**arg) && vim9_comment_start(p))
3960 	*arg += STRLEN(*arg);
3961 
3962     dict_unref(d);
3963     ppconst->pp_is_const = is_all_const;
3964     return generate_NEWDICT(cctx, count);
3965 
3966 failret:
3967     if (*arg == NULL)
3968     {
3969 	semsg(_(e_missing_dict_end), _("[end of lines]"));
3970 	*arg = (char_u *)"";
3971     }
3972     dict_unref(d);
3973     return FAIL;
3974 }
3975 
3976 /*
3977  * Compile "&option".
3978  */
3979     static int
compile_get_option(char_u ** arg,cctx_T * cctx)3980 compile_get_option(char_u **arg, cctx_T *cctx)
3981 {
3982     typval_T	rettv;
3983     char_u	*start = *arg;
3984     int		ret;
3985 
3986     // parse the option and get the current value to get the type.
3987     rettv.v_type = VAR_UNKNOWN;
3988     ret = eval_option(arg, &rettv, TRUE);
3989     if (ret == OK)
3990     {
3991 	// include the '&' in the name, eval_option() expects it.
3992 	char_u	*name = vim_strnsave(start, *arg - start);
3993 	type_T	*type = rettv.v_type == VAR_BOOL ? &t_bool
3994 			  : rettv.v_type == VAR_NUMBER ? &t_number : &t_string;
3995 
3996 	ret = generate_LOAD(cctx, ISN_LOADOPT, 0, name, type);
3997 	vim_free(name);
3998     }
3999     clear_tv(&rettv);
4000 
4001     return ret;
4002 }
4003 
4004 /*
4005  * Compile "$VAR".
4006  */
4007     static int
compile_get_env(char_u ** arg,cctx_T * cctx)4008 compile_get_env(char_u **arg, cctx_T *cctx)
4009 {
4010     char_u	*start = *arg;
4011     int		len;
4012     int		ret;
4013     char_u	*name;
4014 
4015     ++*arg;
4016     len = get_env_len(arg);
4017     if (len == 0)
4018     {
4019 	semsg(_(e_syntax_error_at_str), start - 1);
4020 	return FAIL;
4021     }
4022 
4023     // include the '$' in the name, eval_env_var() expects it.
4024     name = vim_strnsave(start, len + 1);
4025     ret = generate_LOAD(cctx, ISN_LOADENV, 0, name, &t_string);
4026     vim_free(name);
4027     return ret;
4028 }
4029 
4030 /*
4031  * Compile "@r".
4032  */
4033     static int
compile_get_register(char_u ** arg,cctx_T * cctx)4034 compile_get_register(char_u **arg, cctx_T *cctx)
4035 {
4036     int		ret;
4037 
4038     ++*arg;
4039     if (**arg == NUL)
4040     {
4041 	semsg(_(e_syntax_error_at_str), *arg - 1);
4042 	return FAIL;
4043     }
4044     if (!valid_yank_reg(**arg, FALSE))
4045     {
4046 	emsg_invreg(**arg);
4047 	return FAIL;
4048     }
4049     ret = generate_LOAD(cctx, ISN_LOADREG, **arg, NULL, &t_string);
4050     ++*arg;
4051     return ret;
4052 }
4053 
4054 /*
4055  * Apply leading '!', '-' and '+' to constant "rettv".
4056  * When "numeric_only" is TRUE do not apply '!'.
4057  */
4058     static int
apply_leader(typval_T * rettv,int numeric_only,char_u * start,char_u ** end)4059 apply_leader(typval_T *rettv, int numeric_only, char_u *start, char_u **end)
4060 {
4061     char_u *p = *end;
4062 
4063     // this works from end to start
4064     while (p > start)
4065     {
4066 	--p;
4067 	if (*p == '-' || *p == '+')
4068 	{
4069 	    // only '-' has an effect, for '+' we only check the type
4070 #ifdef FEAT_FLOAT
4071 	    if (rettv->v_type == VAR_FLOAT)
4072 	    {
4073 		if (*p == '-')
4074 		    rettv->vval.v_float = -rettv->vval.v_float;
4075 	    }
4076 	    else
4077 #endif
4078 	    {
4079 		varnumber_T	val;
4080 		int		error = FALSE;
4081 
4082 		// tv_get_number_chk() accepts a string, but we don't want that
4083 		// here
4084 		if (check_not_string(rettv) == FAIL)
4085 		    return FAIL;
4086 		val = tv_get_number_chk(rettv, &error);
4087 		clear_tv(rettv);
4088 		if (error)
4089 		    return FAIL;
4090 		if (*p == '-')
4091 		    val = -val;
4092 		rettv->v_type = VAR_NUMBER;
4093 		rettv->vval.v_number = val;
4094 	    }
4095 	}
4096 	else if (numeric_only)
4097 	{
4098 	    ++p;
4099 	    break;
4100 	}
4101 	else if (*p == '!')
4102 	{
4103 	    int v = tv2bool(rettv);
4104 
4105 	    // '!' is permissive in the type.
4106 	    clear_tv(rettv);
4107 	    rettv->v_type = VAR_BOOL;
4108 	    rettv->vval.v_number = v ? VVAL_FALSE : VVAL_TRUE;
4109 	}
4110     }
4111     *end = p;
4112     return OK;
4113 }
4114 
4115 /*
4116  * Recognize v: variables that are constants and set "rettv".
4117  */
4118     static void
get_vim_constant(char_u ** arg,typval_T * rettv)4119 get_vim_constant(char_u **arg, typval_T *rettv)
4120 {
4121     if (STRNCMP(*arg, "v:true", 6) == 0)
4122     {
4123 	rettv->v_type = VAR_BOOL;
4124 	rettv->vval.v_number = VVAL_TRUE;
4125 	*arg += 6;
4126     }
4127     else if (STRNCMP(*arg, "v:false", 7) == 0)
4128     {
4129 	rettv->v_type = VAR_BOOL;
4130 	rettv->vval.v_number = VVAL_FALSE;
4131 	*arg += 7;
4132     }
4133     else if (STRNCMP(*arg, "v:null", 6) == 0)
4134     {
4135 	rettv->v_type = VAR_SPECIAL;
4136 	rettv->vval.v_number = VVAL_NULL;
4137 	*arg += 6;
4138     }
4139     else if (STRNCMP(*arg, "v:none", 6) == 0)
4140     {
4141 	rettv->v_type = VAR_SPECIAL;
4142 	rettv->vval.v_number = VVAL_NONE;
4143 	*arg += 6;
4144     }
4145 }
4146 
4147     exprtype_T
get_compare_type(char_u * p,int * len,int * type_is)4148 get_compare_type(char_u *p, int *len, int *type_is)
4149 {
4150     exprtype_T	type = EXPR_UNKNOWN;
4151     int		i;
4152 
4153     switch (p[0])
4154     {
4155 	case '=':   if (p[1] == '=')
4156 			type = EXPR_EQUAL;
4157 		    else if (p[1] == '~')
4158 			type = EXPR_MATCH;
4159 		    break;
4160 	case '!':   if (p[1] == '=')
4161 			type = EXPR_NEQUAL;
4162 		    else if (p[1] == '~')
4163 			type = EXPR_NOMATCH;
4164 		    break;
4165 	case '>':   if (p[1] != '=')
4166 		    {
4167 			type = EXPR_GREATER;
4168 			*len = 1;
4169 		    }
4170 		    else
4171 			type = EXPR_GEQUAL;
4172 		    break;
4173 	case '<':   if (p[1] != '=')
4174 		    {
4175 			type = EXPR_SMALLER;
4176 			*len = 1;
4177 		    }
4178 		    else
4179 			type = EXPR_SEQUAL;
4180 		    break;
4181 	case 'i':   if (p[1] == 's')
4182 		    {
4183 			// "is" and "isnot"; but not a prefix of a name
4184 			if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4185 			    *len = 5;
4186 			i = p[*len];
4187 			if (!isalnum(i) && i != '_')
4188 			{
4189 			    type = *len == 2 ? EXPR_IS : EXPR_ISNOT;
4190 			    *type_is = TRUE;
4191 			}
4192 		    }
4193 		    break;
4194     }
4195     return type;
4196 }
4197 
4198 /*
4199  * Skip over an expression, ignoring most errors.
4200  */
4201     static void
skip_expr_cctx(char_u ** arg,cctx_T * cctx)4202 skip_expr_cctx(char_u **arg, cctx_T *cctx)
4203 {
4204     evalarg_T	evalarg;
4205 
4206     init_evalarg(&evalarg);
4207     evalarg.eval_cctx = cctx;
4208     skip_expr(arg, &evalarg);
4209     clear_evalarg(&evalarg, NULL);
4210 }
4211 
4212 /*
4213  * Compile code to apply '-', '+' and '!'.
4214  * When "numeric_only" is TRUE do not apply '!'.
4215  */
4216     static int
compile_leader(cctx_T * cctx,int numeric_only,char_u * start,char_u ** end)4217 compile_leader(cctx_T *cctx, int numeric_only, char_u *start, char_u **end)
4218 {
4219     char_u	*p = *end;
4220 
4221     // this works from end to start
4222     while (p > start)
4223     {
4224 	--p;
4225 	while (VIM_ISWHITE(*p))
4226 	    --p;
4227 	if (*p == '-' || *p == '+')
4228 	{
4229 	    int		negate = *p == '-';
4230 	    isn_T	*isn;
4231 	    garray_T    *stack = &cctx->ctx_type_stack;
4232 	    type_T	*type;
4233 
4234 	    type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
4235 	    if (need_type(type, &t_number, -1, 0, cctx, FALSE, FALSE) == FAIL)
4236 		return FAIL;
4237 
4238 	    while (p > start && (p[-1] == '-' || p[-1] == '+'))
4239 	    {
4240 		--p;
4241 		if (*p == '-')
4242 		    negate = !negate;
4243 	    }
4244 	    // only '-' has an effect, for '+' we only check the type
4245 	    if (negate)
4246 	    {
4247 		isn = generate_instr(cctx, ISN_NEGATENR);
4248 		if (isn == NULL)
4249 		    return FAIL;
4250 	    }
4251 	}
4252 	else if (numeric_only)
4253 	{
4254 	    ++p;
4255 	    break;
4256 	}
4257 	else
4258 	{
4259 	    int  invert = *p == '!';
4260 
4261 	    while (p > start && (p[-1] == '!' || VIM_ISWHITE(p[-1])))
4262 	    {
4263 		if (p[-1] == '!')
4264 		    invert = !invert;
4265 		--p;
4266 	    }
4267 	    if (generate_2BOOL(cctx, invert, -1) == FAIL)
4268 		return FAIL;
4269 	}
4270     }
4271     *end = p;
4272     return OK;
4273 }
4274 
4275 /*
4276  * Compile "(expression)": recursive!
4277  * Return FAIL/OK.
4278  */
4279     static int
compile_parenthesis(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)4280 compile_parenthesis(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
4281 {
4282     int	    ret;
4283     char_u  *p = *arg + 1;
4284 
4285     if (may_get_next_line_error(p, arg, cctx) == FAIL)
4286 	return FAIL;
4287     if (ppconst->pp_used <= PPSIZE - 10)
4288     {
4289 	ret = compile_expr1(arg, cctx, ppconst);
4290     }
4291     else
4292     {
4293 	// Not enough space in ppconst, flush constants.
4294 	if (generate_ppconst(cctx, ppconst) == FAIL)
4295 	    return FAIL;
4296 	ret = compile_expr0(arg, cctx);
4297     }
4298     if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
4299 	return FAIL;
4300     if (**arg == ')')
4301 	++*arg;
4302     else if (ret == OK)
4303     {
4304 	emsg(_(e_missing_close));
4305 	ret = FAIL;
4306     }
4307     return ret;
4308 }
4309 
4310 /*
4311  * Compile whatever comes after "name" or "name()".
4312  * Advances "*arg" only when something was recognized.
4313  */
4314     static int
compile_subscript(char_u ** arg,cctx_T * cctx,char_u * start_leader,char_u ** end_leader,ppconst_T * ppconst)4315 compile_subscript(
4316 	char_u **arg,
4317 	cctx_T *cctx,
4318 	char_u *start_leader,
4319 	char_u **end_leader,
4320 	ppconst_T *ppconst)
4321 {
4322     char_u	*name_start = *end_leader;
4323     int		keeping_dict = FALSE;
4324 
4325     for (;;)
4326     {
4327 	char_u *p = skipwhite(*arg);
4328 
4329 	if (*p == NUL || (VIM_ISWHITE(**arg) && vim9_comment_start(p)))
4330 	{
4331 	    char_u *next = peek_next_line_from_context(cctx);
4332 
4333 	    // If a following line starts with "->{" or "->X" advance to that
4334 	    // line, so that a line break before "->" is allowed.
4335 	    // Also if a following line starts with ".x".
4336 	    if (next != NULL &&
4337 		    ((next[0] == '-' && next[1] == '>'
4338 				 && (next[2] == '{'
4339 				       || ASCII_ISALPHA(*skipwhite(next + 2))))
4340 		    || (next[0] == '.' && eval_isdictc(next[1]))))
4341 	    {
4342 		next = next_line_from_context(cctx, TRUE);
4343 		if (next == NULL)
4344 		    return FAIL;
4345 		*arg = next;
4346 		p = skipwhite(*arg);
4347 	    }
4348 	}
4349 
4350 	// Do not skip over white space to find the "(", "execute 'x' (expr)"
4351 	// is not a function call.
4352 	if (**arg == '(')
4353 	{
4354 	    garray_T    *stack = &cctx->ctx_type_stack;
4355 	    type_T	*type;
4356 	    int		argcount = 0;
4357 
4358 	    if (generate_ppconst(cctx, ppconst) == FAIL)
4359 		return FAIL;
4360 	    ppconst->pp_is_const = FALSE;
4361 
4362 	    // funcref(arg)
4363 	    type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
4364 
4365 	    *arg = skipwhite(p + 1);
4366 	    if (compile_arguments(arg, cctx, &argcount, FALSE) == FAIL)
4367 		return FAIL;
4368 	    if (generate_PCALL(cctx, argcount, name_start, type, TRUE) == FAIL)
4369 		return FAIL;
4370 	    if (keeping_dict)
4371 	    {
4372 		keeping_dict = FALSE;
4373 		if (generate_instr(cctx, ISN_CLEARDICT) == NULL)
4374 		    return FAIL;
4375 	    }
4376 	}
4377 	else if (*p == '-' && p[1] == '>')
4378 	{
4379 	    char_u *pstart = p;
4380 
4381 	    if (generate_ppconst(cctx, ppconst) == FAIL)
4382 		return FAIL;
4383 	    ppconst->pp_is_const = FALSE;
4384 
4385 	    // something->method()
4386 	    // Apply the '!', '-' and '+' first:
4387 	    //   -1.0->func() works like (-1.0)->func()
4388 	    if (compile_leader(cctx, TRUE, start_leader, end_leader) == FAIL)
4389 		return FAIL;
4390 
4391 	    p += 2;
4392 	    *arg = skipwhite(p);
4393 	    // No line break supported right after "->".
4394 	    if (**arg == '(')
4395 	    {
4396 		int	    argcount = 1;
4397 		garray_T    *stack = &cctx->ctx_type_stack;
4398 		int	    type_idx_start = stack->ga_len;
4399 		type_T	    *type;
4400 		int	    expr_isn_start = cctx->ctx_instr.ga_len;
4401 		int	    expr_isn_end;
4402 		int	    arg_isn_count;
4403 
4404 		// Funcref call:  list->(Refs[2])(arg)
4405 		// or lambda:	  list->((arg) => expr)(arg)
4406 		//
4407 		// Fist compile the function expression.
4408 		if (compile_parenthesis(arg, cctx, ppconst) == FAIL)
4409 		    return FAIL;
4410 
4411 		// Remember the next instruction index, where the instructions
4412 		// for arguments are being written.
4413 		expr_isn_end = cctx->ctx_instr.ga_len;
4414 
4415 		// Compile the arguments.
4416 		if (**arg != '(')
4417 		{
4418 		    if (*skipwhite(*arg) == '(')
4419 			emsg(_(e_nowhitespace));
4420 		    else
4421 			semsg(_(e_missing_paren), *arg);
4422 		    return FAIL;
4423 		}
4424 		*arg = skipwhite(*arg + 1);
4425 		if (compile_arguments(arg, cctx, &argcount, FALSE) == FAIL)
4426 		    return FAIL;
4427 
4428 		// Move the instructions for the arguments to before the
4429 		// instructions of the expression and move the type of the
4430 		// expression after the argument types.  This is what ISN_PCALL
4431 		// expects.
4432 		stack = &cctx->ctx_type_stack;
4433 		arg_isn_count = cctx->ctx_instr.ga_len - expr_isn_end;
4434 		if (arg_isn_count > 0)
4435 		{
4436 		    int	    expr_isn_count = expr_isn_end - expr_isn_start;
4437 		    isn_T   *isn = ALLOC_MULT(isn_T, expr_isn_count);
4438 
4439 		    if (isn == NULL)
4440 			return FAIL;
4441 		    mch_memmove(isn, ((isn_T *)cctx->ctx_instr.ga_data)
4442 							      + expr_isn_start,
4443 					       sizeof(isn_T) * expr_isn_count);
4444 		    mch_memmove(((isn_T *)cctx->ctx_instr.ga_data)
4445 							      + expr_isn_start,
4446 			     ((isn_T *)cctx->ctx_instr.ga_data) + expr_isn_end,
4447 						sizeof(isn_T) * arg_isn_count);
4448 		    mch_memmove(((isn_T *)cctx->ctx_instr.ga_data)
4449 					      + expr_isn_start + arg_isn_count,
4450 					  isn, sizeof(isn_T) * expr_isn_count);
4451 		    vim_free(isn);
4452 
4453 		    type = ((type_T **)stack->ga_data)[type_idx_start];
4454 		    mch_memmove(((type_T **)stack->ga_data) + type_idx_start,
4455 			      ((type_T **)stack->ga_data) + type_idx_start + 1,
4456 			      sizeof(type_T *)
4457 				       * (stack->ga_len - type_idx_start - 1));
4458 		    ((type_T **)stack->ga_data)[stack->ga_len - 1] = type;
4459 		}
4460 
4461 		type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
4462 		if (generate_PCALL(cctx, argcount, p - 2, type, FALSE) == FAIL)
4463 		    return FAIL;
4464 	    }
4465 	    else
4466 	    {
4467 		// method call:  list->method()
4468 		p = *arg;
4469 		if (!eval_isnamec1(*p))
4470 		{
4471 		    semsg(_(e_trailing_arg), pstart);
4472 		    return FAIL;
4473 		}
4474 		if (ASCII_ISALPHA(*p) && p[1] == ':')
4475 		    p += 2;
4476 		for ( ; eval_isnamec(*p); ++p)
4477 		    ;
4478 		if (*p != '(')
4479 		{
4480 		    semsg(_(e_missing_paren), *arg);
4481 		    return FAIL;
4482 		}
4483 		if (compile_call(arg, p - *arg, cctx, ppconst, 1) == FAIL)
4484 		    return FAIL;
4485 	    }
4486 	    if (keeping_dict)
4487 	    {
4488 		keeping_dict = FALSE;
4489 		if (generate_instr(cctx, ISN_CLEARDICT) == NULL)
4490 		    return FAIL;
4491 	    }
4492 	}
4493 	else if (**arg == '[')
4494 	{
4495 	    int		is_slice = FALSE;
4496 
4497 	    // list index: list[123]
4498 	    // dict member: dict[key]
4499 	    // string index: text[123]
4500 	    // blob index: blob[123]
4501 	    if (generate_ppconst(cctx, ppconst) == FAIL)
4502 		return FAIL;
4503 	    ppconst->pp_is_const = FALSE;
4504 
4505 	    ++p;
4506 	    if (may_get_next_line_error(p, arg, cctx) == FAIL)
4507 		return FAIL;
4508 	    if (**arg == ':')
4509 	    {
4510 		// missing first index is equal to zero
4511 		generate_PUSHNR(cctx, 0);
4512 	    }
4513 	    else
4514 	    {
4515 		if (compile_expr0(arg, cctx) == FAIL)
4516 		    return FAIL;
4517 		if (**arg == ':')
4518 		{
4519 		    semsg(_(e_white_space_required_before_and_after_str_at_str),
4520 								    ":", *arg);
4521 		    return FAIL;
4522 		}
4523 		if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
4524 		    return FAIL;
4525 		*arg = skipwhite(*arg);
4526 	    }
4527 	    if (**arg == ':')
4528 	    {
4529 		is_slice = TRUE;
4530 		++*arg;
4531 		if (!IS_WHITE_OR_NUL(**arg) && **arg != ']')
4532 		{
4533 		    semsg(_(e_white_space_required_before_and_after_str_at_str),
4534 								    ":", *arg);
4535 		    return FAIL;
4536 		}
4537 		if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
4538 		    return FAIL;
4539 		if (**arg == ']')
4540 		    // missing second index is equal to end of string
4541 		    generate_PUSHNR(cctx, -1);
4542 		else
4543 		{
4544 		    if (compile_expr0(arg, cctx) == FAIL)
4545 			return FAIL;
4546 		    if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
4547 			return FAIL;
4548 		    *arg = skipwhite(*arg);
4549 		}
4550 	    }
4551 
4552 	    if (**arg != ']')
4553 	    {
4554 		emsg(_(e_missbrac));
4555 		return FAIL;
4556 	    }
4557 	    *arg = *arg + 1;
4558 
4559 	    if (keeping_dict)
4560 	    {
4561 		keeping_dict = FALSE;
4562 		if (generate_instr(cctx, ISN_CLEARDICT) == NULL)
4563 		    return FAIL;
4564 	    }
4565 	    if (compile_member(is_slice, &keeping_dict, cctx) == FAIL)
4566 		return FAIL;
4567 	}
4568 	else if (*p == '.' && p[1] != '.')
4569 	{
4570 	    // dictionary member: dict.name
4571 	    if (generate_ppconst(cctx, ppconst) == FAIL)
4572 		return FAIL;
4573 	    ppconst->pp_is_const = FALSE;
4574 
4575 	    *arg = p + 1;
4576 	    if (IS_WHITE_OR_NUL(**arg))
4577 	    {
4578 		emsg(_(e_missing_name_after_dot));
4579 		return FAIL;
4580 	    }
4581 	    p = *arg;
4582 	    if (eval_isdictc(*p))
4583 		while (eval_isnamec(*p))
4584 		    MB_PTR_ADV(p);
4585 	    if (p == *arg)
4586 	    {
4587 		semsg(_(e_syntax_error_at_str), *arg);
4588 		return FAIL;
4589 	    }
4590 	    if (keeping_dict && generate_instr(cctx, ISN_CLEARDICT) == NULL)
4591 		return FAIL;
4592 	    if (generate_STRINGMEMBER(cctx, *arg, p - *arg) == FAIL)
4593 		return FAIL;
4594 	    keeping_dict = TRUE;
4595 	    *arg = p;
4596 	}
4597 	else
4598 	    break;
4599     }
4600 
4601     // Turn "dict.Func" into a partial for "Func" bound to "dict".
4602     // This needs to be done at runtime to be able to check the type.
4603     if (keeping_dict && generate_instr(cctx, ISN_USEDICT) == NULL)
4604 	return FAIL;
4605 
4606     return OK;
4607 }
4608 
4609 /*
4610  * Compile an expression at "*arg" and add instructions to "cctx->ctx_instr".
4611  * "arg" is advanced until after the expression, skipping white space.
4612  *
4613  * If the value is a constant "ppconst->pp_used" will be non-zero.
4614  * Before instructions are generated, any values in "ppconst" will generated.
4615  *
4616  * This is the compiling equivalent of eval1(), eval2(), etc.
4617  */
4618 
4619 /*
4620  *  number		number constant
4621  *  0zFFFFFFFF		Blob constant
4622  *  "string"		string constant
4623  *  'string'		literal string constant
4624  *  &option-name	option value
4625  *  @r			register contents
4626  *  identifier		variable value
4627  *  function()		function call
4628  *  $VAR		environment variable
4629  *  (expression)	nested expression
4630  *  [expr, expr]	List
4631  *  {key: val, [key]: val}   Dictionary
4632  *
4633  *  Also handle:
4634  *  ! in front		logical NOT
4635  *  - in front		unary minus
4636  *  + in front		unary plus (ignored)
4637  *  trailing (arg)	funcref/partial call
4638  *  trailing []		subscript in String or List
4639  *  trailing .name	entry in Dictionary
4640  *  trailing ->name()	method call
4641  */
4642     static int
compile_expr7(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)4643 compile_expr7(
4644 	char_u **arg,
4645 	cctx_T *cctx,
4646 	ppconst_T *ppconst)
4647 {
4648     char_u	*start_leader, *end_leader;
4649     int		ret = OK;
4650     typval_T	*rettv = &ppconst->pp_tv[ppconst->pp_used];
4651     int		used_before = ppconst->pp_used;
4652 
4653     ppconst->pp_is_const = FALSE;
4654 
4655     /*
4656      * Skip '!', '-' and '+' characters.  They are handled later.
4657      */
4658     start_leader = *arg;
4659     if (eval_leader(arg, TRUE) == FAIL)
4660 	return FAIL;
4661     end_leader = *arg;
4662 
4663     rettv->v_type = VAR_UNKNOWN;
4664     switch (**arg)
4665     {
4666 	/*
4667 	 * Number constant.
4668 	 */
4669 	case '0':	// also for blob starting with 0z
4670 	case '1':
4671 	case '2':
4672 	case '3':
4673 	case '4':
4674 	case '5':
4675 	case '6':
4676 	case '7':
4677 	case '8':
4678 	case '9':
4679 	case '.':   if (eval_number(arg, rettv, TRUE, FALSE) == FAIL)
4680 			return FAIL;
4681 		    // Apply "-" and "+" just before the number now, right to
4682 		    // left.  Matters especially when "->" follows.  Stops at
4683 		    // '!'.
4684 		    if (apply_leader(rettv, TRUE,
4685 					    start_leader, &end_leader) == FAIL)
4686 		    {
4687 			clear_tv(rettv);
4688 			return FAIL;
4689 		    }
4690 		    break;
4691 
4692 	/*
4693 	 * String constant: "string".
4694 	 */
4695 	case '"':   if (eval_string(arg, rettv, TRUE) == FAIL)
4696 			return FAIL;
4697 		    break;
4698 
4699 	/*
4700 	 * Literal string constant: 'str''ing'.
4701 	 */
4702 	case '\'':  if (eval_lit_string(arg, rettv, TRUE) == FAIL)
4703 			return FAIL;
4704 		    break;
4705 
4706 	/*
4707 	 * Constant Vim variable.
4708 	 */
4709 	case 'v':   get_vim_constant(arg, rettv);
4710 		    ret = NOTDONE;
4711 		    break;
4712 
4713 	/*
4714 	 * "true" constant
4715 	 */
4716 	case 't':   if (STRNCMP(*arg, "true", 4) == 0
4717 						   && !eval_isnamec((*arg)[4]))
4718 		    {
4719 			*arg += 4;
4720 			rettv->v_type = VAR_BOOL;
4721 			rettv->vval.v_number = VVAL_TRUE;
4722 		    }
4723 		    else
4724 			ret = NOTDONE;
4725 		    break;
4726 
4727 	/*
4728 	 * "false" constant
4729 	 */
4730 	case 'f':   if (STRNCMP(*arg, "false", 5) == 0
4731 						   && !eval_isnamec((*arg)[5]))
4732 		    {
4733 			*arg += 5;
4734 			rettv->v_type = VAR_BOOL;
4735 			rettv->vval.v_number = VVAL_FALSE;
4736 		    }
4737 		    else
4738 			ret = NOTDONE;
4739 		    break;
4740 
4741 	/*
4742 	 * "null" constant
4743 	 */
4744 	case 'n':   if (STRNCMP(*arg, "null", 4) == 0
4745 						   && !eval_isnamec((*arg)[4]))
4746 		    {
4747 			*arg += 4;
4748 			rettv->v_type = VAR_SPECIAL;
4749 			rettv->vval.v_number = VVAL_NULL;
4750 		    }
4751 		    else
4752 			ret = NOTDONE;
4753 		    break;
4754 
4755 	/*
4756 	 * List: [expr, expr]
4757 	 */
4758 	case '[':   if (generate_ppconst(cctx, ppconst) == FAIL)
4759 			return FAIL;
4760 		    ret = compile_list(arg, cctx, ppconst);
4761 		    break;
4762 
4763 	/*
4764 	 * Dictionary: {'key': val, 'key': val}
4765 	 */
4766 	case '{':   if (generate_ppconst(cctx, ppconst) == FAIL)
4767 			return FAIL;
4768 		    ret = compile_dict(arg, cctx, ppconst);
4769 		    break;
4770 
4771 	/*
4772 	 * Option value: &name
4773 	 */
4774 	case '&':	if (generate_ppconst(cctx, ppconst) == FAIL)
4775 			    return FAIL;
4776 			ret = compile_get_option(arg, cctx);
4777 			break;
4778 
4779 	/*
4780 	 * Environment variable: $VAR.
4781 	 */
4782 	case '$':	if (generate_ppconst(cctx, ppconst) == FAIL)
4783 			    return FAIL;
4784 			ret = compile_get_env(arg, cctx);
4785 			break;
4786 
4787 	/*
4788 	 * Register contents: @r.
4789 	 */
4790 	case '@':	if (generate_ppconst(cctx, ppconst) == FAIL)
4791 			    return FAIL;
4792 			ret = compile_get_register(arg, cctx);
4793 			break;
4794 	/*
4795 	 * nested expression: (expression).
4796 	 * lambda: (arg, arg) => expr
4797 	 * funcref: (arg, arg) => { statement }
4798 	 */
4799 	case '(':   // if compile_lambda returns NOTDONE then it must be (expr)
4800 		    ret = compile_lambda(arg, cctx);
4801 		    if (ret == NOTDONE)
4802 			ret = compile_parenthesis(arg, cctx, ppconst);
4803 		    break;
4804 
4805 	default:    ret = NOTDONE;
4806 		    break;
4807     }
4808     if (ret == FAIL)
4809 	return FAIL;
4810 
4811     if (rettv->v_type != VAR_UNKNOWN && used_before == ppconst->pp_used)
4812     {
4813 	if (cctx->ctx_skip == SKIP_YES)
4814 	    clear_tv(rettv);
4815 	else
4816 	    // A constant expression can possibly be handled compile time,
4817 	    // return the value instead of generating code.
4818 	    ++ppconst->pp_used;
4819     }
4820     else if (ret == NOTDONE)
4821     {
4822 	char_u	    *p;
4823 	int	    r;
4824 
4825 	if (!eval_isnamec1(**arg))
4826 	{
4827 	    if (!vim9_bad_comment(*arg))
4828 	    {
4829 		if (ends_excmd(*skipwhite(*arg)))
4830 		    semsg(_(e_empty_expression_str), *arg);
4831 		else
4832 		    semsg(_(e_name_expected_str), *arg);
4833 	    }
4834 	    return FAIL;
4835 	}
4836 
4837 	// "name" or "name()"
4838 	p = to_name_end(*arg, TRUE);
4839 	if (p - *arg == (size_t)1 && **arg == '_')
4840 	{
4841 	    emsg(_(e_cannot_use_underscore_here));
4842 	    return FAIL;
4843 	}
4844 
4845 	if (*p == '(')
4846 	{
4847 	    r = compile_call(arg, p - *arg, cctx, ppconst, 0);
4848 	}
4849 	else
4850 	{
4851 	    if (cctx->ctx_skip != SKIP_YES
4852 				    && generate_ppconst(cctx, ppconst) == FAIL)
4853 		return FAIL;
4854 	    r = compile_load(arg, p, cctx, TRUE, TRUE);
4855 	}
4856 	if (r == FAIL)
4857 	    return FAIL;
4858     }
4859 
4860     // Handle following "[]", ".member", etc.
4861     // Then deal with prefixed '-', '+' and '!', if not done already.
4862     if (compile_subscript(arg, cctx, start_leader, &end_leader,
4863 							     ppconst) == FAIL)
4864 	return FAIL;
4865     if (ppconst->pp_used > 0)
4866     {
4867 	// apply the '!', '-' and '+' before the constant
4868 	rettv = &ppconst->pp_tv[ppconst->pp_used - 1];
4869 	if (apply_leader(rettv, FALSE, start_leader, &end_leader) == FAIL)
4870 	    return FAIL;
4871 	return OK;
4872     }
4873     if (compile_leader(cctx, FALSE, start_leader, &end_leader) == FAIL)
4874 	return FAIL;
4875     return OK;
4876 }
4877 
4878 /*
4879  * Give the "white on both sides" error, taking the operator from "p[len]".
4880  */
4881     void
error_white_both(char_u * op,int len)4882 error_white_both(char_u *op, int len)
4883 {
4884     char_u	buf[10];
4885 
4886     vim_strncpy(buf, op, len);
4887     semsg(_(e_white_space_required_before_and_after_str_at_str), buf, op);
4888 }
4889 
4890 /*
4891  * <type>expr7: runtime type check / conversion
4892  */
4893     static int
compile_expr7t(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)4894 compile_expr7t(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
4895 {
4896     type_T *want_type = NULL;
4897 
4898     // Recognize <type>
4899     if (**arg == '<' && eval_isnamec1((*arg)[1]))
4900     {
4901 	++*arg;
4902 	want_type = parse_type(arg, cctx->ctx_type_list, TRUE);
4903 	if (want_type == NULL)
4904 	    return FAIL;
4905 
4906 	if (**arg != '>')
4907 	{
4908 	    if (*skipwhite(*arg) == '>')
4909 		semsg(_(e_no_white_space_allowed_before_str_str), ">", *arg);
4910 	    else
4911 		emsg(_(e_missing_gt));
4912 	    return FAIL;
4913 	}
4914 	++*arg;
4915 	if (may_get_next_line_error(*arg, arg, cctx) == FAIL)
4916 	    return FAIL;
4917     }
4918 
4919     if (compile_expr7(arg, cctx, ppconst) == FAIL)
4920 	return FAIL;
4921 
4922     if (want_type != NULL)
4923     {
4924 	garray_T    *stack = &cctx->ctx_type_stack;
4925 	type_T	    *actual;
4926 	where_T	    where = WHERE_INIT;
4927 
4928 	generate_ppconst(cctx, ppconst);
4929 	actual = ((type_T **)stack->ga_data)[stack->ga_len - 1];
4930 	if (check_type(want_type, actual, FALSE, where) == FAIL)
4931 	{
4932 	    if (need_type(actual, want_type, -1, 0, cctx, FALSE, FALSE) == FAIL)
4933 		return FAIL;
4934 	}
4935     }
4936 
4937     return OK;
4938 }
4939 
4940 /*
4941  *	*	number multiplication
4942  *	/	number division
4943  *	%	number modulo
4944  */
4945     static int
compile_expr6(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)4946 compile_expr6(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
4947 {
4948     char_u	*op;
4949     char_u	*next;
4950     int		ppconst_used = ppconst->pp_used;
4951 
4952     // get the first expression
4953     if (compile_expr7t(arg, cctx, ppconst) == FAIL)
4954 	return FAIL;
4955 
4956     /*
4957      * Repeat computing, until no "*", "/" or "%" is following.
4958      */
4959     for (;;)
4960     {
4961 	op = may_peek_next_line(cctx, *arg, &next);
4962 	if (*op != '*' && *op != '/' && *op != '%')
4963 	    break;
4964 	if (next != NULL)
4965 	{
4966 	    *arg = next_line_from_context(cctx, TRUE);
4967 	    op = skipwhite(*arg);
4968 	}
4969 
4970 	if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(op[1]))
4971 	{
4972 	    error_white_both(op, 1);
4973 	    return FAIL;
4974 	}
4975 	if (may_get_next_line_error(op + 1, arg, cctx) == FAIL)
4976 	    return FAIL;
4977 
4978 	// get the second expression
4979 	if (compile_expr7t(arg, cctx, ppconst) == FAIL)
4980 	    return FAIL;
4981 
4982 	if (ppconst->pp_used == ppconst_used + 2
4983 		&& ppconst->pp_tv[ppconst_used].v_type == VAR_NUMBER
4984 		&& ppconst->pp_tv[ppconst_used + 1].v_type == VAR_NUMBER)
4985 	{
4986 	    typval_T	    *tv1 = &ppconst->pp_tv[ppconst_used];
4987 	    typval_T	    *tv2 = &ppconst->pp_tv[ppconst_used + 1];
4988 	    varnumber_T	    res = 0;
4989 	    int		    failed = FALSE;
4990 
4991 	    // both are numbers: compute the result
4992 	    switch (*op)
4993 	    {
4994 		case '*': res = tv1->vval.v_number * tv2->vval.v_number;
4995 			  break;
4996 		case '/': res = num_divide(tv1->vval.v_number,
4997 						  tv2->vval.v_number, &failed);
4998 			  break;
4999 		case '%': res = num_modulus(tv1->vval.v_number,
5000 						  tv2->vval.v_number, &failed);
5001 			  break;
5002 	    }
5003 	    if (failed)
5004 		return FAIL;
5005 	    tv1->vval.v_number = res;
5006 	    --ppconst->pp_used;
5007 	}
5008 	else
5009 	{
5010 	    generate_ppconst(cctx, ppconst);
5011 	    generate_two_op(cctx, op);
5012 	}
5013     }
5014 
5015     return OK;
5016 }
5017 
5018 /*
5019  *      +	number addition or list/blobl concatenation
5020  *      -	number subtraction
5021  *      ..	string concatenation
5022  */
5023     static int
compile_expr5(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)5024 compile_expr5(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
5025 {
5026     char_u	*op;
5027     char_u	*next;
5028     int		oplen;
5029     int		ppconst_used = ppconst->pp_used;
5030 
5031     // get the first variable
5032     if (compile_expr6(arg, cctx, ppconst) == FAIL)
5033 	return FAIL;
5034 
5035     /*
5036      * Repeat computing, until no "+", "-" or ".." is following.
5037      */
5038     for (;;)
5039     {
5040 	op = may_peek_next_line(cctx, *arg, &next);
5041 	if (*op != '+' && *op != '-' && !(*op == '.' && *(op + 1) == '.'))
5042 	    break;
5043 	if (op[0] == op[1] && *op != '.' && next)
5044 	    // Finding "++" or "--" on the next line is a separate command.
5045 	    // But ".." is concatenation.
5046 	    break;
5047 	oplen = (*op == '.' ? 2 : 1);
5048 	if (next != NULL)
5049 	{
5050 	    *arg = next_line_from_context(cctx, TRUE);
5051 	    op = skipwhite(*arg);
5052 	}
5053 
5054 	if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(op[oplen]))
5055 	{
5056 	    error_white_both(op, oplen);
5057 	    return FAIL;
5058 	}
5059 
5060 	if (may_get_next_line_error(op + oplen, arg, cctx) == FAIL)
5061 	    return FAIL;
5062 
5063 	// get the second expression
5064 	if (compile_expr6(arg, cctx, ppconst) == FAIL)
5065 	    return FAIL;
5066 
5067 	if (ppconst->pp_used == ppconst_used + 2
5068 		&& (*op == '.'
5069 		    ? (ppconst->pp_tv[ppconst_used].v_type == VAR_STRING
5070 		    && ppconst->pp_tv[ppconst_used + 1].v_type == VAR_STRING)
5071 		    : (ppconst->pp_tv[ppconst_used].v_type == VAR_NUMBER
5072 		    && ppconst->pp_tv[ppconst_used + 1].v_type == VAR_NUMBER)))
5073 	{
5074 	    typval_T *tv1 = &ppconst->pp_tv[ppconst_used];
5075 	    typval_T *tv2 = &ppconst->pp_tv[ppconst_used + 1];
5076 
5077 	    // concat/subtract/add constant numbers
5078 	    if (*op == '+')
5079 		tv1->vval.v_number = tv1->vval.v_number + tv2->vval.v_number;
5080 	    else if (*op == '-')
5081 		tv1->vval.v_number = tv1->vval.v_number - tv2->vval.v_number;
5082 	    else
5083 	    {
5084 		// concatenate constant strings
5085 		char_u *s1 = tv1->vval.v_string;
5086 		char_u *s2 = tv2->vval.v_string;
5087 		size_t len1 = STRLEN(s1);
5088 
5089 		tv1->vval.v_string = alloc((int)(len1 + STRLEN(s2) + 1));
5090 		if (tv1->vval.v_string == NULL)
5091 		{
5092 		    clear_ppconst(ppconst);
5093 		    return FAIL;
5094 		}
5095 		mch_memmove(tv1->vval.v_string, s1, len1);
5096 		STRCPY(tv1->vval.v_string + len1, s2);
5097 		vim_free(s1);
5098 		vim_free(s2);
5099 	    }
5100 	    --ppconst->pp_used;
5101 	}
5102 	else
5103 	{
5104 	    generate_ppconst(cctx, ppconst);
5105 	    ppconst->pp_is_const = FALSE;
5106 	    if (*op == '.')
5107 	    {
5108 		if (may_generate_2STRING(-2, FALSE, cctx) == FAIL
5109 			|| may_generate_2STRING(-1, FALSE, cctx) == FAIL)
5110 		    return FAIL;
5111 		generate_instr_drop(cctx, ISN_CONCAT, 1);
5112 	    }
5113 	    else
5114 		generate_two_op(cctx, op);
5115 	}
5116     }
5117 
5118     return OK;
5119 }
5120 
5121 /*
5122  * expr5a == expr5b
5123  * expr5a =~ expr5b
5124  * expr5a != expr5b
5125  * expr5a !~ expr5b
5126  * expr5a > expr5b
5127  * expr5a >= expr5b
5128  * expr5a < expr5b
5129  * expr5a <= expr5b
5130  * expr5a is expr5b
5131  * expr5a isnot expr5b
5132  *
5133  * Produces instructions:
5134  *	EVAL expr5a		Push result of "expr5a"
5135  *	EVAL expr5b		Push result of "expr5b"
5136  *	COMPARE			one of the compare instructions
5137  */
5138     static int
compile_expr4(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)5139 compile_expr4(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
5140 {
5141     exprtype_T	type = EXPR_UNKNOWN;
5142     char_u	*p;
5143     char_u	*next;
5144     int		len = 2;
5145     int		type_is = FALSE;
5146     int		ppconst_used = ppconst->pp_used;
5147 
5148     // get the first variable
5149     if (compile_expr5(arg, cctx, ppconst) == FAIL)
5150 	return FAIL;
5151 
5152     p = may_peek_next_line(cctx, *arg, &next);
5153     type = get_compare_type(p, &len, &type_is);
5154 
5155     /*
5156      * If there is a comparative operator, use it.
5157      */
5158     if (type != EXPR_UNKNOWN)
5159     {
5160 	int ic = FALSE;  // Default: do not ignore case
5161 
5162 	if (next != NULL)
5163 	{
5164 	    *arg = next_line_from_context(cctx, TRUE);
5165 	    p = skipwhite(*arg);
5166 	}
5167 	if (type_is && (p[len] == '?' || p[len] == '#'))
5168 	{
5169 	    semsg(_(e_invalid_expression_str), *arg);
5170 	    return FAIL;
5171 	}
5172 	// extra question mark appended: ignore case
5173 	if (p[len] == '?')
5174 	{
5175 	    ic = TRUE;
5176 	    ++len;
5177 	}
5178 	// extra '#' appended: match case (ignored)
5179 	else if (p[len] == '#')
5180 	    ++len;
5181 	// nothing appended: match case
5182 
5183 	if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(p[len]))
5184 	{
5185 	    error_white_both(p, len);
5186 	    return FAIL;
5187 	}
5188 
5189 	// get the second variable
5190 	if (may_get_next_line_error(p + len, arg, cctx) == FAIL)
5191 	    return FAIL;
5192 
5193 	if (compile_expr5(arg, cctx, ppconst) == FAIL)
5194 	    return FAIL;
5195 
5196 	if (ppconst->pp_used == ppconst_used + 2)
5197 	{
5198 	    typval_T *	tv1 = &ppconst->pp_tv[ppconst->pp_used - 2];
5199 	    typval_T	*tv2 = &ppconst->pp_tv[ppconst->pp_used - 1];
5200 	    int		ret;
5201 
5202 	    // Both sides are a constant, compute the result now.
5203 	    // First check for a valid combination of types, this is more
5204 	    // strict than typval_compare().
5205 	    if (check_compare_types(type, tv1, tv2) == FAIL)
5206 		ret = FAIL;
5207 	    else
5208 	    {
5209 		ret = typval_compare(tv1, tv2, type, ic);
5210 		tv1->v_type = VAR_BOOL;
5211 		tv1->vval.v_number = tv1->vval.v_number
5212 						      ? VVAL_TRUE : VVAL_FALSE;
5213 		clear_tv(tv2);
5214 		--ppconst->pp_used;
5215 	    }
5216 	    return ret;
5217 	}
5218 
5219 	generate_ppconst(cctx, ppconst);
5220 	return generate_COMPARE(cctx, type, ic);
5221     }
5222 
5223     return OK;
5224 }
5225 
5226 static int compile_expr3(char_u **arg,  cctx_T *cctx, ppconst_T *ppconst);
5227 
5228 /*
5229  * Compile || or &&.
5230  */
5231     static int
compile_and_or(char_u ** arg,cctx_T * cctx,char * op,ppconst_T * ppconst,int ppconst_used UNUSED)5232 compile_and_or(
5233 	char_u **arg,
5234 	cctx_T	*cctx,
5235 	char	*op,
5236 	ppconst_T *ppconst,
5237 	int	ppconst_used UNUSED)
5238 {
5239     char_u	*next;
5240     char_u	*p = may_peek_next_line(cctx, *arg, &next);
5241     int		opchar = *op;
5242 
5243     if (p[0] == opchar && p[1] == opchar)
5244     {
5245 	garray_T	*instr = &cctx->ctx_instr;
5246 	garray_T	end_ga;
5247 	int		save_skip = cctx->ctx_skip;
5248 
5249 	/*
5250 	 * Repeat until there is no following "||" or "&&"
5251 	 */
5252 	ga_init2(&end_ga, sizeof(int), 10);
5253 	while (p[0] == opchar && p[1] == opchar)
5254 	{
5255 	    long	start_lnum = SOURCING_LNUM;
5256 	    long	save_sourcing_lnum;
5257 	    int		start_ctx_lnum = cctx->ctx_lnum;
5258 	    int		save_lnum;
5259 	    int		const_used;
5260 	    int		status;
5261 	    jumpwhen_T	jump_when = opchar == '|'
5262 				      ? JUMP_IF_COND_TRUE : JUMP_IF_COND_FALSE;
5263 
5264 	    if (next != NULL)
5265 	    {
5266 		*arg = next_line_from_context(cctx, TRUE);
5267 		p = skipwhite(*arg);
5268 	    }
5269 
5270 	    if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(p[2]))
5271 	    {
5272 		semsg(_(e_white_space_required_before_and_after_str_at_str),
5273 									op, p);
5274 		ga_clear(&end_ga);
5275 		return FAIL;
5276 	    }
5277 
5278 	    save_sourcing_lnum = SOURCING_LNUM;
5279 	    SOURCING_LNUM = start_lnum;
5280 	    save_lnum = cctx->ctx_lnum;
5281 	    cctx->ctx_lnum = start_ctx_lnum;
5282 
5283 	    status = check_ppconst_bool(ppconst);
5284 	    if (status != FAIL)
5285 	    {
5286 		// Use the last ppconst if possible.
5287 		if (ppconst->pp_used > 0)
5288 		{
5289 		    typval_T	*tv = &ppconst->pp_tv[ppconst->pp_used - 1];
5290 		    int		is_true = tv2bool(tv);
5291 
5292 		    if ((is_true && opchar == '|')
5293 						|| (!is_true && opchar == '&'))
5294 		    {
5295 			// For "false && expr" and "true || expr" the "expr"
5296 			// does not need to be evaluated.
5297 			cctx->ctx_skip = SKIP_YES;
5298 			clear_tv(tv);
5299 			tv->v_type = VAR_BOOL;
5300 			tv->vval.v_number = is_true ? VVAL_TRUE : VVAL_FALSE;
5301 		    }
5302 		    else
5303 		    {
5304 			// For "true && expr" and "false || expr" only "expr"
5305 			// needs to be evaluated.
5306 			--ppconst->pp_used;
5307 			jump_when = JUMP_NEVER;
5308 		    }
5309 		}
5310 		else
5311 		{
5312 		    // Every part must evaluate to a bool.
5313 		    status = bool_on_stack(cctx);
5314 		}
5315 	    }
5316 	    if (status != FAIL)
5317 		status = ga_grow(&end_ga, 1);
5318 	    cctx->ctx_lnum = save_lnum;
5319 	    if (status == FAIL)
5320 	    {
5321 		ga_clear(&end_ga);
5322 		return FAIL;
5323 	    }
5324 
5325 	    if (jump_when != JUMP_NEVER)
5326 	    {
5327 		if (cctx->ctx_skip != SKIP_YES)
5328 		{
5329 		    *(((int *)end_ga.ga_data) + end_ga.ga_len) = instr->ga_len;
5330 		    ++end_ga.ga_len;
5331 		}
5332 		generate_JUMP(cctx, jump_when, 0);
5333 	    }
5334 
5335 	    // eval the next expression
5336 	    SOURCING_LNUM = save_sourcing_lnum;
5337 	    if (may_get_next_line_error(p + 2, arg, cctx) == FAIL)
5338 	    {
5339 		ga_clear(&end_ga);
5340 		return FAIL;
5341 	    }
5342 
5343 	    const_used = ppconst->pp_used;
5344 	    if ((opchar == '|' ? compile_expr3(arg, cctx, ppconst)
5345 				  : compile_expr4(arg, cctx, ppconst)) == FAIL)
5346 	    {
5347 		ga_clear(&end_ga);
5348 		return FAIL;
5349 	    }
5350 
5351 	    // "0 || 1" results in true, "1 && 0" results in false.
5352 	    if (ppconst->pp_used == const_used + 1)
5353 	    {
5354 		typval_T	*tv = &ppconst->pp_tv[ppconst->pp_used - 1];
5355 
5356 		if (tv->v_type == VAR_NUMBER
5357 			 && (tv->vval.v_number == 1 || tv->vval.v_number == 0))
5358 		{
5359 		    tv->vval.v_number = tv->vval.v_number == 1
5360 						      ? VVAL_TRUE : VVAL_FALSE;
5361 		    tv->v_type = VAR_BOOL;
5362 		}
5363 	    }
5364 
5365 	    p = may_peek_next_line(cctx, *arg, &next);
5366 	}
5367 
5368 	if (check_ppconst_bool(ppconst) == FAIL)
5369 	{
5370 	    ga_clear(&end_ga);
5371 	    return FAIL;
5372 	}
5373 
5374 	if (cctx->ctx_skip != SKIP_YES && ppconst->pp_used == 0)
5375 	    // Every part must evaluate to a bool.
5376 	    if (bool_on_stack(cctx) == FAIL)
5377 	    {
5378 		ga_clear(&end_ga);
5379 		return FAIL;
5380 	    }
5381 
5382 	if (end_ga.ga_len > 0)
5383 	{
5384 	    // Fill in the end label in all jumps.
5385 	    generate_ppconst(cctx, ppconst);
5386 	    while (end_ga.ga_len > 0)
5387 	    {
5388 		isn_T	*isn;
5389 
5390 		--end_ga.ga_len;
5391 		isn = ((isn_T *)instr->ga_data)
5392 				  + *(((int *)end_ga.ga_data) + end_ga.ga_len);
5393 		isn->isn_arg.jump.jump_where = instr->ga_len;
5394 	    }
5395 	}
5396 	ga_clear(&end_ga);
5397 
5398 	cctx->ctx_skip = save_skip;
5399     }
5400 
5401     return OK;
5402 }
5403 
5404 /*
5405  * expr4a && expr4a && expr4a	    logical AND
5406  *
5407  * Produces instructions:
5408  *	EVAL expr4a		Push result of "expr4a"
5409  *	COND2BOOL		convert to bool if needed
5410  *	JUMP_IF_COND_FALSE end
5411  *	EVAL expr4b		Push result of "expr4b"
5412  *	JUMP_IF_COND_FALSE end
5413  *	EVAL expr4c		Push result of "expr4c"
5414  * end:
5415  */
5416     static int
compile_expr3(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)5417 compile_expr3(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
5418 {
5419     int		ppconst_used = ppconst->pp_used;
5420 
5421     // get the first variable
5422     if (compile_expr4(arg, cctx, ppconst) == FAIL)
5423 	return FAIL;
5424 
5425     // || and && work almost the same
5426     return compile_and_or(arg, cctx, "&&", ppconst, ppconst_used);
5427 }
5428 
5429 /*
5430  * expr3a || expr3b || expr3c	    logical OR
5431  *
5432  * Produces instructions:
5433  *	EVAL expr3a		Push result of "expr3a"
5434  *	COND2BOOL		convert to bool if needed
5435  *	JUMP_IF_COND_TRUE end
5436  *	EVAL expr3b		Push result of "expr3b"
5437  *	JUMP_IF_COND_TRUE end
5438  *	EVAL expr3c		Push result of "expr3c"
5439  * end:
5440  */
5441     static int
compile_expr2(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)5442 compile_expr2(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
5443 {
5444     int		ppconst_used = ppconst->pp_used;
5445 
5446     // eval the first expression
5447     if (compile_expr3(arg, cctx, ppconst) == FAIL)
5448 	return FAIL;
5449 
5450     // || and && work almost the same
5451     return compile_and_or(arg, cctx, "||", ppconst, ppconst_used);
5452 }
5453 
5454 /*
5455  * Toplevel expression: expr2 ? expr1a : expr1b
5456  * Produces instructions:
5457  *	EVAL expr2		Push result of "expr2"
5458  *      JUMP_IF_FALSE alt	jump if false
5459  *      EVAL expr1a
5460  *      JUMP_ALWAYS end
5461  * alt:	EVAL expr1b
5462  * end:
5463  *
5464  * Toplevel expression: expr2 ?? expr1
5465  * Produces instructions:
5466  *	EVAL expr2		    Push result of "expr2"
5467  *      JUMP_AND_KEEP_IF_TRUE end   jump if true
5468  *      EVAL expr1
5469  * end:
5470  */
5471     static int
compile_expr1(char_u ** arg,cctx_T * cctx,ppconst_T * ppconst)5472 compile_expr1(char_u **arg, cctx_T *cctx, ppconst_T *ppconst)
5473 {
5474     char_u	*p;
5475     int		ppconst_used = ppconst->pp_used;
5476     char_u	*next;
5477 
5478     // Ignore all kinds of errors when not producing code.
5479     if (cctx->ctx_skip == SKIP_YES)
5480     {
5481 	skip_expr_cctx(arg, cctx);
5482 	return OK;
5483     }
5484 
5485     // Evaluate the first expression.
5486     if (compile_expr2(arg, cctx, ppconst) == FAIL)
5487 	return FAIL;
5488 
5489     p = may_peek_next_line(cctx, *arg, &next);
5490     if (*p == '?')
5491     {
5492 	int		op_falsy = p[1] == '?';
5493 	garray_T	*instr = &cctx->ctx_instr;
5494 	garray_T	*stack = &cctx->ctx_type_stack;
5495 	int		alt_idx = instr->ga_len;
5496 	int		end_idx = 0;
5497 	isn_T		*isn;
5498 	type_T		*type1 = NULL;
5499 	int		has_const_expr = FALSE;
5500 	int		const_value = FALSE;
5501 	int		save_skip = cctx->ctx_skip;
5502 
5503 	if (next != NULL)
5504 	{
5505 	    *arg = next_line_from_context(cctx, TRUE);
5506 	    p = skipwhite(*arg);
5507 	}
5508 
5509 	if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(p[1 + op_falsy]))
5510 	{
5511 	    semsg(_(e_white_space_required_before_and_after_str_at_str),
5512 						     op_falsy ? "??" : "?", p);
5513 	    return FAIL;
5514 	}
5515 
5516 	if (ppconst->pp_used == ppconst_used + 1)
5517 	{
5518 	    // the condition is a constant, we know whether the ? or the :
5519 	    // expression is to be evaluated.
5520 	    has_const_expr = TRUE;
5521 	    if (op_falsy)
5522 		const_value = tv2bool(&ppconst->pp_tv[ppconst_used]);
5523 	    else
5524 	    {
5525 		int error = FALSE;
5526 
5527 		const_value = tv_get_bool_chk(&ppconst->pp_tv[ppconst_used],
5528 								       &error);
5529 		if (error)
5530 		    return FAIL;
5531 	    }
5532 	    cctx->ctx_skip = save_skip == SKIP_YES ||
5533 		 (op_falsy ? const_value : !const_value) ? SKIP_YES : SKIP_NOT;
5534 
5535 	    if (op_falsy && cctx->ctx_skip == SKIP_YES)
5536 		// "left ?? right" and "left" is truthy: produce "left"
5537 		generate_ppconst(cctx, ppconst);
5538 	    else
5539 	    {
5540 		clear_tv(&ppconst->pp_tv[ppconst_used]);
5541 		--ppconst->pp_used;
5542 	    }
5543 	}
5544 	else
5545 	{
5546 	    generate_ppconst(cctx, ppconst);
5547 	    if (op_falsy)
5548 		end_idx = instr->ga_len;
5549 	    generate_JUMP(cctx, op_falsy
5550 				   ? JUMP_AND_KEEP_IF_TRUE : JUMP_IF_FALSE, 0);
5551 	    if (op_falsy)
5552 		type1 = ((type_T **)stack->ga_data)[stack->ga_len];
5553 	}
5554 
5555 	// evaluate the second expression; any type is accepted
5556 	if (may_get_next_line_error(p + 1 + op_falsy, arg, cctx) == FAIL)
5557 	    return FAIL;
5558 	if (compile_expr1(arg, cctx, ppconst) == FAIL)
5559 	    return FAIL;
5560 
5561 	if (!has_const_expr)
5562 	{
5563 	    generate_ppconst(cctx, ppconst);
5564 
5565 	    if (!op_falsy)
5566 	    {
5567 		// remember the type and drop it
5568 		--stack->ga_len;
5569 		type1 = ((type_T **)stack->ga_data)[stack->ga_len];
5570 
5571 		end_idx = instr->ga_len;
5572 		generate_JUMP(cctx, JUMP_ALWAYS, 0);
5573 
5574 		// jump here from JUMP_IF_FALSE
5575 		isn = ((isn_T *)instr->ga_data) + alt_idx;
5576 		isn->isn_arg.jump.jump_where = instr->ga_len;
5577 	    }
5578 	}
5579 
5580 	if (!op_falsy)
5581 	{
5582 	    // Check for the ":".
5583 	    p = may_peek_next_line(cctx, *arg, &next);
5584 	    if (*p != ':')
5585 	    {
5586 		emsg(_(e_missing_colon));
5587 		return FAIL;
5588 	    }
5589 	    if (next != NULL)
5590 	    {
5591 		*arg = next_line_from_context(cctx, TRUE);
5592 		p = skipwhite(*arg);
5593 	    }
5594 
5595 	    if (!IS_WHITE_OR_NUL(**arg) || !IS_WHITE_OR_NUL(p[1]))
5596 	    {
5597 		semsg(_(e_white_space_required_before_and_after_str_at_str),
5598 								       ":", p);
5599 		return FAIL;
5600 	    }
5601 
5602 	    // evaluate the third expression
5603 	    if (has_const_expr)
5604 		cctx->ctx_skip = save_skip == SKIP_YES || const_value
5605 							 ? SKIP_YES : SKIP_NOT;
5606 	    if (may_get_next_line_error(p + 1, arg, cctx) == FAIL)
5607 		return FAIL;
5608 	    if (compile_expr1(arg, cctx, ppconst) == FAIL)
5609 		return FAIL;
5610 	}
5611 
5612 	if (!has_const_expr)
5613 	{
5614 	    type_T	**typep;
5615 
5616 	    generate_ppconst(cctx, ppconst);
5617 
5618 	    // If the types differ, the result has a more generic type.
5619 	    typep = ((type_T **)stack->ga_data) + stack->ga_len - 1;
5620 	    common_type(type1, *typep, typep, cctx->ctx_type_list);
5621 
5622 	    // jump here from JUMP_ALWAYS or JUMP_AND_KEEP_IF_TRUE
5623 	    isn = ((isn_T *)instr->ga_data) + end_idx;
5624 	    isn->isn_arg.jump.jump_where = instr->ga_len;
5625 	}
5626 
5627 	cctx->ctx_skip = save_skip;
5628     }
5629     return OK;
5630 }
5631 
5632 /*
5633  * Toplevel expression.
5634  * Sets "is_const" (if not NULL) to indicate the value is a constant.
5635  * Returns OK or FAIL.
5636  */
5637     static int
compile_expr0_ext(char_u ** arg,cctx_T * cctx,int * is_const)5638 compile_expr0_ext(char_u **arg,  cctx_T *cctx, int *is_const)
5639 {
5640     ppconst_T	ppconst;
5641 
5642     CLEAR_FIELD(ppconst);
5643     if (compile_expr1(arg, cctx, &ppconst) == FAIL)
5644     {
5645 	clear_ppconst(&ppconst);
5646 	return FAIL;
5647     }
5648     if (is_const != NULL)
5649 	*is_const = ppconst.pp_used > 0 || ppconst.pp_is_const;
5650     if (generate_ppconst(cctx, &ppconst) == FAIL)
5651 	return FAIL;
5652     return OK;
5653 }
5654 
5655 /*
5656  * Toplevel expression.
5657  */
5658     static int
compile_expr0(char_u ** arg,cctx_T * cctx)5659 compile_expr0(char_u **arg,  cctx_T *cctx)
5660 {
5661     return compile_expr0_ext(arg, cctx, NULL);
5662 }
5663 
5664 /*
5665  * Compile "return [expr]".
5666  * When "legacy" is TRUE evaluate [expr] with legacy syntax
5667  */
5668     static char_u *
compile_return(char_u * arg,int check_return_type,int legacy,cctx_T * cctx)5669 compile_return(char_u *arg, int check_return_type, int legacy, cctx_T *cctx)
5670 {
5671     char_u	*p = arg;
5672     garray_T	*stack = &cctx->ctx_type_stack;
5673     type_T	*stack_type;
5674 
5675     if (*p != NUL && *p != '|' && *p != '\n')
5676     {
5677 	if (legacy)
5678 	{
5679 	    int save_flags = cmdmod.cmod_flags;
5680 
5681 	    generate_LEGACY_EVAL(cctx, p);
5682 	    if (need_type(&t_any, cctx->ctx_ufunc->uf_ret_type, -1,
5683 						0, cctx, FALSE, FALSE) == FAIL)
5684 		return NULL;
5685 	    cmdmod.cmod_flags |= CMOD_LEGACY;
5686 	    (void)skip_expr(&p, NULL);
5687 	    cmdmod.cmod_flags = save_flags;
5688 	}
5689 	else
5690 	{
5691 	    // compile return argument into instructions
5692 	    if (compile_expr0(&p, cctx) == FAIL)
5693 		return NULL;
5694 	}
5695 
5696 	if (cctx->ctx_skip != SKIP_YES)
5697 	{
5698 	    // "check_return_type" with uf_ret_type set to &t_unknown is used
5699 	    // for an inline function without a specified return type.  Set the
5700 	    // return type here.
5701 	    stack_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
5702 	    if ((check_return_type && (cctx->ctx_ufunc->uf_ret_type == NULL
5703 				|| cctx->ctx_ufunc->uf_ret_type == &t_unknown
5704 				|| cctx->ctx_ufunc->uf_ret_type == &t_any))
5705 		    || (!check_return_type
5706 				&& cctx->ctx_ufunc->uf_ret_type == &t_unknown))
5707 	    {
5708 		cctx->ctx_ufunc->uf_ret_type = stack_type;
5709 	    }
5710 	    else
5711 	    {
5712 		if (cctx->ctx_ufunc->uf_ret_type->tt_type == VAR_VOID
5713 			&& stack_type->tt_type != VAR_VOID
5714 			&& stack_type->tt_type != VAR_UNKNOWN)
5715 		{
5716 		    emsg(_(e_returning_value_in_function_without_return_type));
5717 		    return NULL;
5718 		}
5719 		if (need_type(stack_type, cctx->ctx_ufunc->uf_ret_type, -1,
5720 						0, cctx, FALSE, FALSE) == FAIL)
5721 		    return NULL;
5722 	    }
5723 	}
5724     }
5725     else
5726     {
5727 	// "check_return_type" cannot be TRUE, only used for a lambda which
5728 	// always has an argument.
5729 	if (cctx->ctx_ufunc->uf_ret_type->tt_type != VAR_VOID
5730 		&& cctx->ctx_ufunc->uf_ret_type->tt_type != VAR_UNKNOWN)
5731 	{
5732 	    emsg(_(e_missing_return_value));
5733 	    return NULL;
5734 	}
5735 
5736 	// No argument, return zero.
5737 	generate_PUSHNR(cctx, 0);
5738     }
5739 
5740     // Undo any command modifiers.
5741     generate_undo_cmdmods(cctx);
5742 
5743     if (cctx->ctx_skip != SKIP_YES && generate_instr(cctx, ISN_RETURN) == NULL)
5744 	return NULL;
5745 
5746     // "return val | endif" is possible
5747     return skipwhite(p);
5748 }
5749 
5750 /*
5751  * Get a line from the compilation context, compatible with exarg_T getline().
5752  * Return a pointer to the line in allocated memory.
5753  * Return NULL for end-of-file or some error.
5754  */
5755     static char_u *
exarg_getline(int c UNUSED,void * cookie,int indent UNUSED,getline_opt_T options UNUSED)5756 exarg_getline(
5757 	int c UNUSED,
5758 	void *cookie,
5759 	int indent UNUSED,
5760 	getline_opt_T options UNUSED)
5761 {
5762     cctx_T  *cctx = (cctx_T *)cookie;
5763     char_u  *p;
5764 
5765     for (;;)
5766     {
5767 	if (cctx->ctx_lnum >= cctx->ctx_ufunc->uf_lines.ga_len - 1)
5768 	    return NULL;
5769 	++cctx->ctx_lnum;
5770 	p = ((char_u **)cctx->ctx_ufunc->uf_lines.ga_data)[cctx->ctx_lnum];
5771 	// Comment lines result in NULL pointers, skip them.
5772 	if (p != NULL)
5773 	    return vim_strsave(p);
5774     }
5775 }
5776 
5777     void
fill_exarg_from_cctx(exarg_T * eap,cctx_T * cctx)5778 fill_exarg_from_cctx(exarg_T *eap, cctx_T *cctx)
5779 {
5780     eap->getline = exarg_getline;
5781     eap->cookie = cctx;
5782 }
5783 
5784 /*
5785  * Compile a nested :def command.
5786  */
5787     static char_u *
compile_nested_function(exarg_T * eap,cctx_T * cctx)5788 compile_nested_function(exarg_T *eap, cctx_T *cctx)
5789 {
5790     int		is_global = *eap->arg == 'g' && eap->arg[1] == ':';
5791     char_u	*name_start = eap->arg;
5792     char_u	*name_end = to_name_end(eap->arg, TRUE);
5793     char_u	*lambda_name;
5794     ufunc_T	*ufunc;
5795     int		r = FAIL;
5796     compiletype_T   compile_type;
5797 
5798     if (eap->forceit)
5799     {
5800 	emsg(_(e_cannot_use_bang_with_nested_def));
5801 	return NULL;
5802     }
5803 
5804     if (*name_start == '/')
5805     {
5806 	name_end = skip_regexp(name_start + 1, '/', TRUE);
5807 	if (*name_end == '/')
5808 	    ++name_end;
5809 	set_nextcmd(eap, name_end);
5810     }
5811     if (name_end == name_start || *skipwhite(name_end) != '(')
5812     {
5813 	if (!ends_excmd2(name_start, name_end))
5814 	{
5815 	    semsg(_(e_invalid_command_str), eap->cmd);
5816 	    return NULL;
5817 	}
5818 
5819 	// "def" or "def Name": list functions
5820 	if (generate_DEF(cctx, name_start, name_end - name_start) == FAIL)
5821 	    return NULL;
5822 	return eap->nextcmd == NULL ? (char_u *)"" : eap->nextcmd;
5823     }
5824 
5825     // Only g:Func() can use a namespace.
5826     if (name_start[1] == ':' && !is_global)
5827     {
5828 	semsg(_(e_namespace_not_supported_str), name_start);
5829 	return NULL;
5830     }
5831     if (check_defined(name_start, name_end - name_start, cctx, FALSE) == FAIL)
5832 	return NULL;
5833 
5834     eap->arg = name_end;
5835     fill_exarg_from_cctx(eap, cctx);
5836 
5837     eap->forceit = FALSE;
5838     lambda_name = vim_strsave(get_lambda_name());
5839     if (lambda_name == NULL)
5840 	return NULL;
5841     ufunc = define_function(eap, lambda_name);
5842 
5843     if (ufunc == NULL)
5844     {
5845 	r = eap->skip ? OK : FAIL;
5846 	goto theend;
5847     }
5848 
5849     // copy over the block scope IDs before compiling
5850     if (!is_global && cctx->ctx_ufunc->uf_block_depth > 0)
5851     {
5852 	int block_depth = cctx->ctx_ufunc->uf_block_depth;
5853 
5854 	ufunc->uf_block_ids = ALLOC_MULT(int, block_depth);
5855 	if (ufunc->uf_block_ids != NULL)
5856 	{
5857 	    mch_memmove(ufunc->uf_block_ids, cctx->ctx_ufunc->uf_block_ids,
5858 						    sizeof(int) * block_depth);
5859 	    ufunc->uf_block_depth = block_depth;
5860 	}
5861     }
5862 
5863     compile_type = COMPILE_TYPE(ufunc);
5864 #ifdef FEAT_PROFILE
5865     // If the outer function is profiled, also compile the nested function for
5866     // profiling.
5867     if (cctx->ctx_compile_type == CT_PROFILE)
5868 	compile_type = CT_PROFILE;
5869 #endif
5870     if (func_needs_compiling(ufunc, compile_type)
5871 	    && compile_def_function(ufunc, TRUE, compile_type, cctx) == FAIL)
5872     {
5873 	func_ptr_unref(ufunc);
5874 	goto theend;
5875     }
5876 
5877 #ifdef FEAT_PROFILE
5878     // When the outer function is compiled for profiling, the nested function
5879     // may be called without profiling.  Compile it here in the right context.
5880     if (compile_type == CT_PROFILE && func_needs_compiling(ufunc, CT_NONE))
5881 	compile_def_function(ufunc, FALSE, CT_NONE, cctx);
5882 #endif
5883 
5884     if (is_global)
5885     {
5886 	char_u *func_name = vim_strnsave(name_start + 2,
5887 						    name_end - name_start - 2);
5888 
5889 	if (func_name == NULL)
5890 	    r = FAIL;
5891 	else
5892 	{
5893 	    r = generate_NEWFUNC(cctx, lambda_name, func_name);
5894 	    lambda_name = NULL;
5895 	}
5896     }
5897     else
5898     {
5899 	// Define a local variable for the function reference.
5900 	lvar_T	*lvar = reserve_local(cctx, name_start, name_end - name_start,
5901 						    TRUE, ufunc->uf_func_type);
5902 
5903 	if (lvar == NULL)
5904 	    goto theend;
5905 	if (generate_FUNCREF(cctx, ufunc) == FAIL)
5906 	    goto theend;
5907 	r = generate_STORE(cctx, ISN_STORE, lvar->lv_idx, NULL);
5908     }
5909 
5910 theend:
5911     vim_free(lambda_name);
5912     return r == FAIL ? NULL : (char_u *)"";
5913 }
5914 
5915 /*
5916  * Return the length of an assignment operator, or zero if there isn't one.
5917  */
5918     int
assignment_len(char_u * p,int * heredoc)5919 assignment_len(char_u *p, int *heredoc)
5920 {
5921     if (*p == '=')
5922     {
5923 	if (p[1] == '<' && p[2] == '<')
5924 	{
5925 	    *heredoc = TRUE;
5926 	    return 3;
5927 	}
5928 	return 1;
5929     }
5930     if (vim_strchr((char_u *)"+-*/%", *p) != NULL && p[1] == '=')
5931 	return 2;
5932     if (STRNCMP(p, "..=", 3) == 0)
5933 	return 3;
5934     return 0;
5935 }
5936 
5937 /*
5938  * Generate the load instruction for "name".
5939  */
5940     static void
generate_loadvar(cctx_T * cctx,assign_dest_T dest,char_u * name,lvar_T * lvar,type_T * type)5941 generate_loadvar(
5942 	cctx_T		*cctx,
5943 	assign_dest_T	dest,
5944 	char_u		*name,
5945 	lvar_T		*lvar,
5946 	type_T		*type)
5947 {
5948     switch (dest)
5949     {
5950 	case dest_option:
5951 	    generate_LOAD(cctx, ISN_LOADOPT, 0, name, type);
5952 	    break;
5953 	case dest_global:
5954 	    if (vim_strchr(name, AUTOLOAD_CHAR) == NULL)
5955 		generate_LOAD(cctx, ISN_LOADG, 0, name + 2, type);
5956 	    else
5957 		generate_LOAD(cctx, ISN_LOADAUTO, 0, name, type);
5958 	    break;
5959 	case dest_buffer:
5960 	    generate_LOAD(cctx, ISN_LOADB, 0, name + 2, type);
5961 	    break;
5962 	case dest_window:
5963 	    generate_LOAD(cctx, ISN_LOADW, 0, name + 2, type);
5964 	    break;
5965 	case dest_tab:
5966 	    generate_LOAD(cctx, ISN_LOADT, 0, name + 2, type);
5967 	    break;
5968 	case dest_script:
5969 	    compile_load_scriptvar(cctx,
5970 		    name + (name[1] == ':' ? 2 : 0), NULL, NULL, TRUE);
5971 	    break;
5972 	case dest_env:
5973 	    // Include $ in the name here
5974 	    generate_LOAD(cctx, ISN_LOADENV, 0, name, type);
5975 	    break;
5976 	case dest_reg:
5977 	    generate_LOAD(cctx, ISN_LOADREG, name[1], NULL, &t_string);
5978 	    break;
5979 	case dest_vimvar:
5980 	    generate_LOADV(cctx, name + 2, TRUE);
5981 	    break;
5982 	case dest_local:
5983 	    if (lvar->lv_from_outer > 0)
5984 		generate_LOADOUTER(cctx, lvar->lv_idx, lvar->lv_from_outer,
5985 									 type);
5986 	    else
5987 		generate_LOAD(cctx, ISN_LOAD, lvar->lv_idx, NULL, type);
5988 	    break;
5989 	case dest_expr:
5990 	    // list or dict value should already be on the stack.
5991 	    break;
5992     }
5993 }
5994 
5995 /*
5996  * Skip over "[expr]" or ".member".
5997  * Does not check for any errors.
5998  */
5999     static char_u *
skip_index(char_u * start)6000 skip_index(char_u *start)
6001 {
6002     char_u *p = start;
6003 
6004     if (*p == '[')
6005     {
6006 	p = skipwhite(p + 1);
6007 	(void)skip_expr(&p, NULL);
6008 	p = skipwhite(p);
6009 	if (*p == ']')
6010 	    return p + 1;
6011 	return p;
6012     }
6013     // if (*p == '.')
6014     return to_name_end(p + 1, TRUE);
6015 }
6016 
6017     void
vim9_declare_error(char_u * name)6018 vim9_declare_error(char_u *name)
6019 {
6020     char *scope = "";
6021 
6022     switch (*name)
6023     {
6024 	case 'g': scope = _("global"); break;
6025 	case 'b': scope = _("buffer"); break;
6026 	case 'w': scope = _("window"); break;
6027 	case 't': scope = _("tab"); break;
6028 	case 'v': scope = "v:"; break;
6029 	case '$': semsg(_(e_cannot_declare_an_environment_variable), name);
6030 		  return;
6031 	case '&': semsg(_(e_cannot_declare_an_option), name);
6032 		  return;
6033 	case '@': semsg(_(e_cannot_declare_a_register_str), name);
6034 		  return;
6035 	default: return;
6036     }
6037     semsg(_(e_cannot_declare_a_scope_variable), scope, name);
6038 }
6039 
6040 /*
6041  * For one assignment figure out the type of destination.  Return it in "dest".
6042  * When not recognized "dest" is not set.
6043  * For an option "opt_flags" is set.
6044  * For a v:var "vimvaridx" is set.
6045  * "type" is set to the destination type if known, unchanted otherwise.
6046  * Return FAIL if an error message was given.
6047  */
6048     static int
get_var_dest(char_u * name,assign_dest_T * dest,int cmdidx,int * opt_flags,int * vimvaridx,type_T ** type,cctx_T * cctx)6049 get_var_dest(
6050 	char_u		*name,
6051 	assign_dest_T	*dest,
6052 	int		cmdidx,
6053 	int		*opt_flags,
6054 	int		*vimvaridx,
6055 	type_T		**type,
6056 	cctx_T		*cctx)
6057 {
6058     char_u *p;
6059 
6060     if (*name == '&')
6061     {
6062 	int		cc;
6063 	long		numval;
6064 	getoption_T	opt_type;
6065 
6066 	*dest = dest_option;
6067 	if (cmdidx == CMD_final || cmdidx == CMD_const)
6068 	{
6069 	    emsg(_(e_const_option));
6070 	    return FAIL;
6071 	}
6072 	p = name;
6073 	p = find_option_end(&p, opt_flags);
6074 	if (p == NULL)
6075 	{
6076 	    // cannot happen?
6077 	    emsg(_(e_unexpected_characters_in_assignment));
6078 	    return FAIL;
6079 	}
6080 	cc = *p;
6081 	*p = NUL;
6082 	opt_type = get_option_value(skip_option_env_lead(name),
6083 						    &numval, NULL, *opt_flags);
6084 	*p = cc;
6085 	switch (opt_type)
6086 	{
6087 	    case gov_unknown:
6088 		    semsg(_(e_unknown_option), name);
6089 		    return FAIL;
6090 	    case gov_string:
6091 	    case gov_hidden_string:
6092 		    *type = &t_string;
6093 		    break;
6094 	    case gov_bool:
6095 	    case gov_hidden_bool:
6096 		    *type = &t_bool;
6097 		    break;
6098 	    case gov_number:
6099 	    case gov_hidden_number:
6100 		    *type = &t_number;
6101 		    break;
6102 	}
6103     }
6104     else if (*name == '$')
6105     {
6106 	*dest = dest_env;
6107 	*type = &t_string;
6108     }
6109     else if (*name == '@')
6110     {
6111 	if (name[1] != '@'
6112 			&& (!valid_yank_reg(name[1], FALSE) || name[1] == '.'))
6113 	{
6114 	    emsg_invreg(name[1]);
6115 	    return FAIL;
6116 	}
6117 	*dest = dest_reg;
6118 	*type = name[1] == '#' ? &t_number_or_string : &t_string;
6119     }
6120     else if (STRNCMP(name, "g:", 2) == 0)
6121     {
6122 	*dest = dest_global;
6123     }
6124     else if (STRNCMP(name, "b:", 2) == 0)
6125     {
6126 	*dest = dest_buffer;
6127     }
6128     else if (STRNCMP(name, "w:", 2) == 0)
6129     {
6130 	*dest = dest_window;
6131     }
6132     else if (STRNCMP(name, "t:", 2) == 0)
6133     {
6134 	*dest = dest_tab;
6135     }
6136     else if (STRNCMP(name, "v:", 2) == 0)
6137     {
6138 	typval_T	*vtv;
6139 	int		di_flags;
6140 
6141 	*vimvaridx = find_vim_var(name + 2, &di_flags);
6142 	if (*vimvaridx < 0)
6143 	{
6144 	    semsg(_(e_variable_not_found_str), name);
6145 	    return FAIL;
6146 	}
6147 	// We use the current value of "sandbox" here, is that OK?
6148 	if (var_check_ro(di_flags, name, FALSE))
6149 	    return FAIL;
6150 	*dest = dest_vimvar;
6151 	vtv = get_vim_var_tv(*vimvaridx);
6152 	*type = typval2type_vimvar(vtv, cctx->ctx_type_list);
6153     }
6154     return OK;
6155 }
6156 
6157 /*
6158  * Generate a STORE instruction for "dest", not being "dest_local".
6159  * Return FAIL when out of memory.
6160  */
6161     static int
generate_store_var(cctx_T * cctx,assign_dest_T dest,int opt_flags,int vimvaridx,int scriptvar_idx,int scriptvar_sid,type_T * type,char_u * name)6162 generate_store_var(
6163 	cctx_T		*cctx,
6164 	assign_dest_T	dest,
6165 	int		opt_flags,
6166 	int		vimvaridx,
6167 	int		scriptvar_idx,
6168 	int		scriptvar_sid,
6169 	type_T		*type,
6170 	char_u		*name)
6171 {
6172     switch (dest)
6173     {
6174 	case dest_option:
6175 	    return generate_STOREOPT(cctx, skip_option_env_lead(name),
6176 								    opt_flags);
6177 	case dest_global:
6178 	    // include g: with the name, easier to execute that way
6179 	    return generate_STORE(cctx, vim_strchr(name, AUTOLOAD_CHAR) == NULL
6180 					? ISN_STOREG : ISN_STOREAUTO, 0, name);
6181 	case dest_buffer:
6182 	    // include b: with the name, easier to execute that way
6183 	    return generate_STORE(cctx, ISN_STOREB, 0, name);
6184 	case dest_window:
6185 	    // include w: with the name, easier to execute that way
6186 	    return generate_STORE(cctx, ISN_STOREW, 0, name);
6187 	case dest_tab:
6188 	    // include t: with the name, easier to execute that way
6189 	    return generate_STORE(cctx, ISN_STORET, 0, name);
6190 	case dest_env:
6191 	    return generate_STORE(cctx, ISN_STOREENV, 0, name + 1);
6192 	case dest_reg:
6193 	    return generate_STORE(cctx, ISN_STOREREG,
6194 					 name[1] == '@' ? '"' : name[1], NULL);
6195 	case dest_vimvar:
6196 	    return generate_STORE(cctx, ISN_STOREV, vimvaridx, NULL);
6197 	case dest_script:
6198 	    if (scriptvar_idx < 0)
6199 		// "s:" may be included in the name.
6200 		return generate_OLDSCRIPT(cctx, ISN_STORES, name,
6201 							  scriptvar_sid, type);
6202 	    return generate_VIM9SCRIPT(cctx, ISN_STORESCRIPT,
6203 					   scriptvar_sid, scriptvar_idx, type);
6204 	case dest_local:
6205 	case dest_expr:
6206 	    // cannot happen
6207 	    break;
6208     }
6209     return FAIL;
6210 }
6211 
6212     static int
generate_store_lhs(cctx_T * cctx,lhs_T * lhs,int instr_count)6213 generate_store_lhs(cctx_T *cctx, lhs_T *lhs, int instr_count)
6214 {
6215     if (lhs->lhs_dest != dest_local)
6216 	return generate_store_var(cctx, lhs->lhs_dest,
6217 			    lhs->lhs_opt_flags, lhs->lhs_vimvaridx,
6218 			    lhs->lhs_scriptvar_idx, lhs->lhs_scriptvar_sid,
6219 			    lhs->lhs_type, lhs->lhs_name);
6220 
6221     if (lhs->lhs_lvar != NULL)
6222     {
6223 	garray_T	*instr = &cctx->ctx_instr;
6224 	isn_T		*isn = ((isn_T *)instr->ga_data) + instr->ga_len - 1;
6225 
6226 	// optimization: turn "var = 123" from ISN_PUSHNR + ISN_STORE into
6227 	// ISN_STORENR
6228 	if (lhs->lhs_lvar->lv_from_outer == 0
6229 		&& instr->ga_len == instr_count + 1
6230 		&& isn->isn_type == ISN_PUSHNR)
6231 	{
6232 	    varnumber_T val = isn->isn_arg.number;
6233 	    garray_T    *stack = &cctx->ctx_type_stack;
6234 
6235 	    isn->isn_type = ISN_STORENR;
6236 	    isn->isn_arg.storenr.stnr_idx = lhs->lhs_lvar->lv_idx;
6237 	    isn->isn_arg.storenr.stnr_val = val;
6238 	    if (stack->ga_len > 0)
6239 		--stack->ga_len;
6240 	}
6241 	else if (lhs->lhs_lvar->lv_from_outer > 0)
6242 	    generate_STOREOUTER(cctx, lhs->lhs_lvar->lv_idx,
6243 						 lhs->lhs_lvar->lv_from_outer);
6244 	else
6245 	    generate_STORE(cctx, ISN_STORE, lhs->lhs_lvar->lv_idx, NULL);
6246     }
6247     return OK;
6248 }
6249 
6250     static int
is_decl_command(int cmdidx)6251 is_decl_command(int cmdidx)
6252 {
6253     return cmdidx == CMD_let || cmdidx == CMD_var
6254 				 || cmdidx == CMD_final || cmdidx == CMD_const;
6255 }
6256 
6257 /*
6258  * Figure out the LHS type and other properties for an assignment or one item
6259  * of ":unlet" with an index.
6260  * Returns OK or FAIL.
6261  */
6262     static int
compile_lhs(char_u * var_start,lhs_T * lhs,int cmdidx,int heredoc,int oplen,cctx_T * cctx)6263 compile_lhs(
6264 	char_u	*var_start,
6265 	lhs_T	*lhs,
6266 	int	cmdidx,
6267 	int	heredoc,
6268 	int	oplen,
6269 	cctx_T	*cctx)
6270 {
6271     char_u	*var_end;
6272     int		is_decl = is_decl_command(cmdidx);
6273 
6274     CLEAR_POINTER(lhs);
6275     lhs->lhs_dest = dest_local;
6276     lhs->lhs_vimvaridx = -1;
6277     lhs->lhs_scriptvar_idx = -1;
6278 
6279     // "dest_end" is the end of the destination, including "[expr]" or
6280     // ".name".
6281     // "var_end" is the end of the variable/option/etc. name.
6282     lhs->lhs_dest_end = skip_var_one(var_start, FALSE);
6283     if (*var_start == '@')
6284 	var_end = var_start + 2;
6285     else
6286     {
6287 	// skip over the leading "&", "&l:", "&g:" and "$"
6288 	var_end = skip_option_env_lead(var_start);
6289 	var_end = to_name_end(var_end, TRUE);
6290     }
6291 
6292     // "a: type" is declaring variable "a" with a type, not dict "a:".
6293     if (is_decl && lhs->lhs_dest_end == var_start + 2
6294 					       && lhs->lhs_dest_end[-1] == ':')
6295 	--lhs->lhs_dest_end;
6296     if (is_decl && var_end == var_start + 2 && var_end[-1] == ':')
6297 	--var_end;
6298 
6299     // compute the length of the destination without "[expr]" or ".name"
6300     lhs->lhs_varlen = var_end - var_start;
6301     lhs->lhs_varlen_total = lhs->lhs_varlen;
6302     lhs->lhs_name = vim_strnsave(var_start, lhs->lhs_varlen);
6303     if (lhs->lhs_name == NULL)
6304 	return FAIL;
6305 
6306     if (lhs->lhs_dest_end > var_start + lhs->lhs_varlen)
6307 	// Something follows after the variable: "var[idx]" or "var.key".
6308 	lhs->lhs_has_index = TRUE;
6309 
6310     if (heredoc)
6311 	lhs->lhs_type = &t_list_string;
6312     else
6313 	lhs->lhs_type = &t_any;
6314 
6315     if (cctx->ctx_skip != SKIP_YES)
6316     {
6317 	int	    declare_error = FALSE;
6318 
6319 	if (get_var_dest(lhs->lhs_name, &lhs->lhs_dest, cmdidx,
6320 				      &lhs->lhs_opt_flags, &lhs->lhs_vimvaridx,
6321 						 &lhs->lhs_type, cctx) == FAIL)
6322 	    return FAIL;
6323 	if (lhs->lhs_dest != dest_local
6324 				 && cmdidx != CMD_const && cmdidx != CMD_final)
6325 	{
6326 	    // Specific kind of variable recognized.
6327 	    declare_error = is_decl;
6328 	}
6329 	else
6330 	{
6331 	    // No specific kind of variable recognized, just a name.
6332 	    if (check_reserved_name(lhs->lhs_name) == FAIL)
6333 		return FAIL;
6334 
6335 	    if (lookup_local(var_start, lhs->lhs_varlen,
6336 					     &lhs->lhs_local_lvar, cctx) == OK)
6337 		lhs->lhs_lvar = &lhs->lhs_local_lvar;
6338 	    else
6339 	    {
6340 		CLEAR_FIELD(lhs->lhs_arg_lvar);
6341 		if (arg_exists(var_start, lhs->lhs_varlen,
6342 			 &lhs->lhs_arg_lvar.lv_idx, &lhs->lhs_arg_lvar.lv_type,
6343 			    &lhs->lhs_arg_lvar.lv_from_outer, cctx) == OK)
6344 		{
6345 		    if (is_decl)
6346 		    {
6347 			semsg(_(e_str_is_used_as_argument), lhs->lhs_name);
6348 			return FAIL;
6349 		    }
6350 		    lhs->lhs_lvar = &lhs->lhs_arg_lvar;
6351 		}
6352 	    }
6353 	    if (lhs->lhs_lvar != NULL)
6354 	    {
6355 		if (is_decl)
6356 		{
6357 		    semsg(_(e_variable_already_declared), lhs->lhs_name);
6358 		    return FAIL;
6359 		}
6360 	    }
6361 	    else
6362 	    {
6363 		int script_namespace = lhs->lhs_varlen > 1
6364 				       && STRNCMP(var_start, "s:", 2) == 0;
6365 		int script_var = (script_namespace
6366 			? script_var_exists(var_start + 2, lhs->lhs_varlen - 2,
6367 									  cctx)
6368 			  : script_var_exists(var_start, lhs->lhs_varlen,
6369 								  cctx)) == OK;
6370 		imported_T  *import =
6371 			       find_imported(var_start, lhs->lhs_varlen, cctx);
6372 
6373 		if (script_namespace || script_var || import != NULL)
6374 		{
6375 		    char_u	*rawname = lhs->lhs_name
6376 					   + (lhs->lhs_name[1] == ':' ? 2 : 0);
6377 
6378 		    if (is_decl)
6379 		    {
6380 			if (script_namespace)
6381 			    semsg(_(e_cannot_declare_script_variable_in_function),
6382 								lhs->lhs_name);
6383 			else
6384 			    semsg(_(e_variable_already_declared_in_script_str),
6385 								lhs->lhs_name);
6386 			return FAIL;
6387 		    }
6388 		    else if (cctx->ctx_ufunc->uf_script_ctx_version
6389 							 == SCRIPT_VERSION_VIM9
6390 				    && script_namespace
6391 				    && !script_var && import == NULL)
6392 		    {
6393 			semsg(_(e_unknown_variable_str), lhs->lhs_name);
6394 			return FAIL;
6395 		    }
6396 
6397 		    lhs->lhs_dest = dest_script;
6398 
6399 		    // existing script-local variables should have a type
6400 		    lhs->lhs_scriptvar_sid = current_sctx.sc_sid;
6401 		    if (import != NULL)
6402 			lhs->lhs_scriptvar_sid = import->imp_sid;
6403 		    if (SCRIPT_ID_VALID(lhs->lhs_scriptvar_sid))
6404 		    {
6405 			// Check writable only when no index follows.
6406 			lhs->lhs_scriptvar_idx = get_script_item_idx(
6407 					       lhs->lhs_scriptvar_sid, rawname,
6408 			      lhs->lhs_has_index ? ASSIGN_FINAL : ASSIGN_CONST,
6409 									 cctx);
6410 			if (lhs->lhs_scriptvar_idx >= 0)
6411 			{
6412 			    scriptitem_T *si = SCRIPT_ITEM(
6413 						       lhs->lhs_scriptvar_sid);
6414 			    svar_T	 *sv =
6415 					    ((svar_T *)si->sn_var_vals.ga_data)
6416 						      + lhs->lhs_scriptvar_idx;
6417 			    lhs->lhs_type = sv->sv_type;
6418 			}
6419 		    }
6420 		}
6421 		else if (check_defined(var_start, lhs->lhs_varlen, cctx, FALSE)
6422 								       == FAIL)
6423 		    return FAIL;
6424 	    }
6425 	}
6426 
6427 	if (declare_error)
6428 	{
6429 	    vim9_declare_error(lhs->lhs_name);
6430 	    return FAIL;
6431 	}
6432     }
6433 
6434     // handle "a:name" as a name, not index "name" on "a"
6435     if (lhs->lhs_varlen > 1 || var_start[lhs->lhs_varlen] != ':')
6436 	var_end = lhs->lhs_dest_end;
6437 
6438     if (lhs->lhs_dest != dest_option)
6439     {
6440 	if (is_decl && *var_end == ':')
6441 	{
6442 	    char_u *p;
6443 
6444 	    // parse optional type: "let var: type = expr"
6445 	    if (!VIM_ISWHITE(var_end[1]))
6446 	    {
6447 		semsg(_(e_white_space_required_after_str_str), ":", var_end);
6448 		return FAIL;
6449 	    }
6450 	    p = skipwhite(var_end + 1);
6451 	    lhs->lhs_type = parse_type(&p, cctx->ctx_type_list, TRUE);
6452 	    if (lhs->lhs_type == NULL)
6453 		return FAIL;
6454 	    lhs->lhs_has_type = TRUE;
6455 	}
6456 	else if (lhs->lhs_lvar != NULL)
6457 	    lhs->lhs_type = lhs->lhs_lvar->lv_type;
6458     }
6459 
6460     if (oplen == 3 && !heredoc
6461 		   && lhs->lhs_dest != dest_global
6462 		   && !lhs->lhs_has_index
6463 		   && lhs->lhs_type->tt_type != VAR_STRING
6464 		   && lhs->lhs_type->tt_type != VAR_ANY)
6465     {
6466 	emsg(_(e_can_only_concatenate_to_string));
6467 	return FAIL;
6468     }
6469 
6470     if (lhs->lhs_lvar == NULL && lhs->lhs_dest == dest_local
6471 						 && cctx->ctx_skip != SKIP_YES)
6472     {
6473 	if (oplen > 1 && !heredoc)
6474 	{
6475 	    // +=, /=, etc. require an existing variable
6476 	    semsg(_(e_cannot_use_operator_on_new_variable), lhs->lhs_name);
6477 	    return FAIL;
6478 	}
6479 	if (!is_decl)
6480 	{
6481 	    semsg(_(e_unknown_variable_str), lhs->lhs_name);
6482 	    return FAIL;
6483 	}
6484 
6485 	// Check the name is valid for a funcref.
6486 	if ((lhs->lhs_type->tt_type == VAR_FUNC
6487 				      || lhs->lhs_type->tt_type == VAR_PARTIAL)
6488 		&& var_wrong_func_name(lhs->lhs_name, TRUE))
6489 	    return FAIL;
6490 
6491 	// New local variable.
6492 	lhs->lhs_lvar = reserve_local(cctx, var_start, lhs->lhs_varlen,
6493 		    cmdidx == CMD_final || cmdidx == CMD_const, lhs->lhs_type);
6494 	if (lhs->lhs_lvar == NULL)
6495 	    return FAIL;
6496 	lhs->lhs_new_local = TRUE;
6497     }
6498 
6499     lhs->lhs_member_type = lhs->lhs_type;
6500     if (lhs->lhs_has_index)
6501     {
6502 	// Something follows after the variable: "var[idx]" or "var.key".
6503 	// TODO: should we also handle "->func()" here?
6504 	if (is_decl)
6505 	{
6506 	    emsg(_(e_cannot_use_index_when_declaring_variable));
6507 	    return FAIL;
6508 	}
6509 
6510 	if (var_start[lhs->lhs_varlen] == '['
6511 					  || var_start[lhs->lhs_varlen] == '.')
6512 	{
6513 	    char_u	*after = var_start + lhs->lhs_varlen;
6514 	    char_u	*p;
6515 
6516 	    // Only the last index is used below, if there are others
6517 	    // before it generate code for the expression.  Thus for
6518 	    // "ll[1][2]" the expression is "ll[1]" and "[2]" is the index.
6519 	    for (;;)
6520 	    {
6521 		p = skip_index(after);
6522 		if (*p != '[' && *p != '.')
6523 		{
6524 		    lhs->lhs_varlen_total = p - var_start;
6525 		    break;
6526 		}
6527 		after = p;
6528 	    }
6529 	    if (after > var_start + lhs->lhs_varlen)
6530 	    {
6531 		lhs->lhs_varlen = after - var_start;
6532 		lhs->lhs_dest = dest_expr;
6533 		// We don't know the type before evaluating the expression,
6534 		// use "any" until then.
6535 		lhs->lhs_type = &t_any;
6536 	    }
6537 
6538 	    if (lhs->lhs_type->tt_member == NULL)
6539 		lhs->lhs_member_type = &t_any;
6540 	    else
6541 		lhs->lhs_member_type = lhs->lhs_type->tt_member;
6542 	}
6543 	else
6544 	{
6545 	    semsg("Not supported yet: %s", var_start);
6546 	    return FAIL;
6547 	}
6548     }
6549     return OK;
6550 }
6551 
6552 /*
6553  * Figure out the LHS and check a few errors.
6554  */
6555     static int
compile_assign_lhs(char_u * var_start,lhs_T * lhs,int cmdidx,int is_decl,int heredoc,int oplen,cctx_T * cctx)6556 compile_assign_lhs(
6557 	char_u	*var_start,
6558 	lhs_T	*lhs,
6559 	int	cmdidx,
6560 	int	is_decl,
6561 	int	heredoc,
6562 	int	oplen,
6563 	cctx_T	*cctx)
6564 {
6565     if (compile_lhs(var_start, lhs, cmdidx, heredoc, oplen, cctx) == FAIL)
6566 	return FAIL;
6567 
6568     if (!lhs->lhs_has_index && lhs->lhs_lvar == &lhs->lhs_arg_lvar)
6569     {
6570 	semsg(_(e_cannot_assign_to_argument), lhs->lhs_name);
6571 	return FAIL;
6572     }
6573     if (!is_decl && lhs->lhs_lvar != NULL
6574 			   && lhs->lhs_lvar->lv_const && !lhs->lhs_has_index)
6575     {
6576 	semsg(_(e_cannot_assign_to_constant), lhs->lhs_name);
6577 	return FAIL;
6578     }
6579     return OK;
6580 }
6581 
6582 /*
6583  * Return TRUE if "lhs" has a range index: "[expr : expr]".
6584  */
6585     static int
has_list_index(char_u * idx_start,cctx_T * cctx)6586 has_list_index(char_u *idx_start, cctx_T *cctx)
6587 {
6588     char_u  *p = idx_start;
6589     int	    save_skip;
6590 
6591     if (*p != '[')
6592 	return FALSE;
6593 
6594     p = skipwhite(p + 1);
6595     if (*p == ':')
6596 	return TRUE;
6597 
6598     save_skip = cctx->ctx_skip;
6599     cctx->ctx_skip = SKIP_YES;
6600     (void)compile_expr0(&p, cctx);
6601     cctx->ctx_skip = save_skip;
6602     return *skipwhite(p) == ':';
6603 }
6604 
6605 /*
6606  * For an assignment with an index, compile the "idx" in "var[idx]" or "key" in
6607  * "var.key".
6608  */
6609     static int
compile_assign_index(char_u * var_start,lhs_T * lhs,int * range,cctx_T * cctx)6610 compile_assign_index(
6611 	char_u	*var_start,
6612 	lhs_T	*lhs,
6613 	int	*range,
6614 	cctx_T	*cctx)
6615 {
6616     size_t	varlen = lhs->lhs_varlen;
6617     char_u	*p;
6618     int		r = OK;
6619     int		need_white_before = TRUE;
6620     int		empty_second;
6621 
6622     p = var_start + varlen;
6623     if (*p == '[')
6624     {
6625 	p = skipwhite(p + 1);
6626 	if (*p == ':')
6627 	{
6628 	    // empty first index, push zero
6629 	    r = generate_PUSHNR(cctx, 0);
6630 	    need_white_before = FALSE;
6631 	}
6632 	else
6633 	    r = compile_expr0(&p, cctx);
6634 
6635 	if (r == OK && *skipwhite(p) == ':')
6636 	{
6637 	    // unlet var[idx : idx]
6638 	    // blob[idx : idx] = value
6639 	    *range = TRUE;
6640 	    p = skipwhite(p);
6641 	    empty_second = *skipwhite(p + 1) == ']';
6642 	    if ((need_white_before && !IS_WHITE_OR_NUL(p[-1]))
6643 		    || (!empty_second && !IS_WHITE_OR_NUL(p[1])))
6644 	    {
6645 		semsg(_(e_white_space_required_before_and_after_str_at_str),
6646 								      ":", p);
6647 		return FAIL;
6648 	    }
6649 	    p = skipwhite(p + 1);
6650 	    if (*p == ']')
6651 		// empty second index, push "none"
6652 		r = generate_PUSHSPEC(cctx, VVAL_NONE);
6653 	    else
6654 		r = compile_expr0(&p, cctx);
6655 	}
6656 
6657 	if (r == OK && *skipwhite(p) != ']')
6658 	{
6659 	    // this should not happen
6660 	    emsg(_(e_missbrac));
6661 	    r = FAIL;
6662 	}
6663     }
6664     else // if (*p == '.')
6665     {
6666 	char_u *key_end = to_name_end(p + 1, TRUE);
6667 	char_u *key = vim_strnsave(p + 1, key_end - p - 1);
6668 
6669 	r = generate_PUSHS(cctx, &key);
6670     }
6671     return r;
6672 }
6673 
6674 /*
6675  * For a LHS with an index, load the variable to be indexed.
6676  */
6677     static int
compile_load_lhs(lhs_T * lhs,char_u * var_start,type_T * rhs_type,cctx_T * cctx)6678 compile_load_lhs(
6679 	lhs_T	*lhs,
6680 	char_u	*var_start,
6681 	type_T	*rhs_type,
6682 	cctx_T	*cctx)
6683 {
6684     if (lhs->lhs_dest == dest_expr)
6685     {
6686 	size_t	    varlen = lhs->lhs_varlen;
6687 	int	    c = var_start[varlen];
6688 	int	    lines_len = cctx->ctx_ufunc->uf_lines.ga_len;
6689 	char_u	    *p = var_start;
6690 	garray_T    *stack = &cctx->ctx_type_stack;
6691 	int	    res;
6692 
6693 	// Evaluate "ll[expr]" of "ll[expr][idx]".  End the line with a NUL and
6694 	// limit the lines array length to avoid skipping to a following line.
6695 	var_start[varlen] = NUL;
6696 	cctx->ctx_ufunc->uf_lines.ga_len = cctx->ctx_lnum + 1;
6697 	res = compile_expr0(&p, cctx);
6698 	var_start[varlen] = c;
6699 	cctx->ctx_ufunc->uf_lines.ga_len = lines_len;
6700 	if (res == FAIL || p != var_start + varlen)
6701 	{
6702 	    // this should not happen
6703 	    if (res != FAIL)
6704 		emsg(_(e_missbrac));
6705 	    return FAIL;
6706 	}
6707 
6708 	lhs->lhs_type = stack->ga_len == 0 ? &t_void
6709 			      : ((type_T **)stack->ga_data)[stack->ga_len - 1];
6710 	// now we can properly check the type
6711 	if (rhs_type != NULL && lhs->lhs_type->tt_member != NULL
6712 		&& rhs_type != &t_void
6713 		&& need_type(rhs_type, lhs->lhs_type->tt_member, -2, 0, cctx,
6714 							 FALSE, FALSE) == FAIL)
6715 	    return FAIL;
6716     }
6717     else
6718 	generate_loadvar(cctx, lhs->lhs_dest, lhs->lhs_name,
6719 						 lhs->lhs_lvar, lhs->lhs_type);
6720     return OK;
6721 }
6722 
6723 /*
6724  * Produce code for loading "lhs" and also take care of an index.
6725  * Return OK/FAIL.
6726  */
6727     static int
compile_load_lhs_with_index(lhs_T * lhs,char_u * var_start,cctx_T * cctx)6728 compile_load_lhs_with_index(lhs_T *lhs, char_u *var_start, cctx_T *cctx)
6729 {
6730     compile_load_lhs(lhs, var_start, NULL, cctx);
6731 
6732     if (lhs->lhs_has_index)
6733     {
6734 	int range = FALSE;
6735 
6736 	// Get member from list or dict.  First compile the
6737 	// index value.
6738 	if (compile_assign_index(var_start, lhs, &range, cctx) == FAIL)
6739 	    return FAIL;
6740 	if (range)
6741 	{
6742 	    semsg(_(e_cannot_use_range_with_assignment_operator_str),
6743 								    var_start);
6744 	    return FAIL;
6745 	}
6746 
6747 	// Get the member.
6748 	if (compile_member(FALSE, NULL, cctx) == FAIL)
6749 	    return FAIL;
6750     }
6751     return OK;
6752 }
6753 
6754 /*
6755  * Assignment to a list or dict member, or ":unlet" for the item, using the
6756  * information in "lhs".
6757  * Returns OK or FAIL.
6758  */
6759     static int
compile_assign_unlet(char_u * var_start,lhs_T * lhs,int is_assign,type_T * rhs_type,cctx_T * cctx)6760 compile_assign_unlet(
6761 	char_u	*var_start,
6762 	lhs_T	*lhs,
6763 	int	is_assign,
6764 	type_T	*rhs_type,
6765 	cctx_T	*cctx)
6766 {
6767     vartype_T	dest_type;
6768     garray_T    *stack = &cctx->ctx_type_stack;
6769     int		range = FALSE;
6770 
6771     if (compile_assign_index(var_start, lhs, &range, cctx) == FAIL)
6772 	return FAIL;
6773     if (is_assign && range
6774 	    && lhs->lhs_type->tt_type != VAR_LIST
6775 	    && lhs->lhs_type != &t_blob
6776 	    && lhs->lhs_type != &t_any)
6777     {
6778 	semsg(_(e_cannot_use_range_with_assignment_str), var_start);
6779 	return FAIL;
6780     }
6781 
6782     if (lhs->lhs_type == &t_any)
6783     {
6784 	// Index on variable of unknown type: check at runtime.
6785 	dest_type = VAR_ANY;
6786     }
6787     else
6788     {
6789 	dest_type = lhs->lhs_type->tt_type;
6790 	if (dest_type == VAR_DICT && range)
6791 	{
6792 	    emsg(e_cannot_use_range_with_dictionary);
6793 	    return FAIL;
6794 	}
6795 	if (dest_type == VAR_DICT
6796 			      && may_generate_2STRING(-1, FALSE, cctx) == FAIL)
6797 	    return FAIL;
6798 	if (dest_type == VAR_LIST || dest_type == VAR_BLOB)
6799 	{
6800 	    type_T *type;
6801 
6802 	    if (range)
6803 	    {
6804 		type = ((type_T **)stack->ga_data)[stack->ga_len - 2];
6805 		if (need_type(type, &t_number,
6806 					    -1, 0, cctx, FALSE, FALSE) == FAIL)
6807 		return FAIL;
6808 	    }
6809 	    type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
6810 	    if ((dest_type != VAR_BLOB && type != &t_special)
6811 		    && need_type(type, &t_number,
6812 					    -1, 0, cctx, FALSE, FALSE) == FAIL)
6813 		return FAIL;
6814 	}
6815     }
6816 
6817     // Load the dict or list.  On the stack we then have:
6818     // - value (for assignment, not for :unlet)
6819     // - index
6820     // - for [a : b] second index
6821     // - variable
6822     if (compile_load_lhs(lhs, var_start, rhs_type, cctx) == FAIL)
6823 	return FAIL;
6824 
6825     if (dest_type == VAR_LIST || dest_type == VAR_DICT
6826 			      || dest_type == VAR_BLOB || dest_type == VAR_ANY)
6827     {
6828 	if (is_assign)
6829 	{
6830 	    if (range)
6831 	    {
6832 		if (generate_instr_drop(cctx, ISN_STORERANGE, 4) == NULL)
6833 		    return FAIL;
6834 	    }
6835 	    else
6836 	    {
6837 		isn_T	*isn = generate_instr_drop(cctx, ISN_STOREINDEX, 3);
6838 
6839 		if (isn == NULL)
6840 		    return FAIL;
6841 		isn->isn_arg.vartype = dest_type;
6842 	    }
6843 	}
6844 	else if (range)
6845 	{
6846 	    if (generate_instr_drop(cctx, ISN_UNLETRANGE, 3) == NULL)
6847 		return FAIL;
6848 	}
6849 	else
6850 	{
6851 	    if (generate_instr_drop(cctx, ISN_UNLETINDEX, 2) == NULL)
6852 		return FAIL;
6853 	}
6854     }
6855     else
6856     {
6857 	emsg(_(e_indexable_type_required));
6858 	return FAIL;
6859     }
6860 
6861     return OK;
6862 }
6863 
6864 /*
6865  * Compile declaration and assignment:
6866  * "let name"
6867  * "var name = expr"
6868  * "final name = expr"
6869  * "const name = expr"
6870  * "name = expr"
6871  * "arg" points to "name".
6872  * "++arg" and "--arg"
6873  * Return NULL for an error.
6874  * Return "arg" if it does not look like a variable list.
6875  */
6876     static char_u *
compile_assignment(char_u * arg,exarg_T * eap,cmdidx_T cmdidx,cctx_T * cctx)6877 compile_assignment(char_u *arg, exarg_T *eap, cmdidx_T cmdidx, cctx_T *cctx)
6878 {
6879     char_u	*var_start;
6880     char_u	*p;
6881     char_u	*end = arg;
6882     char_u	*ret = NULL;
6883     int		var_count = 0;
6884     int		var_idx;
6885     int		semicolon = 0;
6886     int		did_generate_slice = FALSE;
6887     garray_T	*instr = &cctx->ctx_instr;
6888     garray_T    *stack = &cctx->ctx_type_stack;
6889     char_u	*op;
6890     int		oplen = 0;
6891     int		heredoc = FALSE;
6892     int		incdec = FALSE;
6893     type_T	*rhs_type = &t_any;
6894     char_u	*sp;
6895     int		is_decl = is_decl_command(cmdidx);
6896     lhs_T	lhs;
6897     long	start_lnum = SOURCING_LNUM;
6898 
6899     // Skip over the "var" or "[var, var]" to get to any "=".
6900     p = skip_var_list(arg, TRUE, &var_count, &semicolon, TRUE);
6901     if (p == NULL)
6902 	return *arg == '[' ? arg : NULL;
6903 
6904     if (var_count > 0 && is_decl)
6905     {
6906 	// TODO: should we allow this, and figure out type inference from list
6907 	// members?
6908 	emsg(_(e_cannot_use_list_for_declaration));
6909 	return NULL;
6910     }
6911     lhs.lhs_name = NULL;
6912 
6913     sp = p;
6914     p = skipwhite(p);
6915     op = p;
6916     oplen = assignment_len(p, &heredoc);
6917 
6918     if (var_count > 0 && oplen == 0)
6919 	// can be something like "[1, 2]->func()"
6920 	return arg;
6921 
6922     if (oplen > 0 && (!VIM_ISWHITE(*sp) || !IS_WHITE_OR_NUL(op[oplen])))
6923     {
6924 	error_white_both(op, oplen);
6925 	return NULL;
6926     }
6927     if (eap->cmdidx == CMD_increment || eap->cmdidx == CMD_decrement)
6928     {
6929 	if (VIM_ISWHITE(eap->cmd[2]))
6930 	{
6931 	    semsg(_(e_no_white_space_allowed_after_str_str),
6932 			 eap->cmdidx == CMD_increment ? "++" : "--", eap->cmd);
6933 	    return NULL;
6934 	}
6935 	op = (char_u *)(eap->cmdidx == CMD_increment ? "+=" : "-=");
6936 	oplen = 2;
6937 	incdec = TRUE;
6938     }
6939 
6940     if (heredoc)
6941     {
6942 	list_T	   *l;
6943 	listitem_T *li;
6944 
6945 	// [let] varname =<< [trim] {end}
6946 	eap->getline = exarg_getline;
6947 	eap->cookie = cctx;
6948 	l = heredoc_get(eap, op + 3, FALSE);
6949 	if (l == NULL)
6950 	    return NULL;
6951 
6952 	if (cctx->ctx_skip != SKIP_YES)
6953 	{
6954 	    // Push each line and the create the list.
6955 	    FOR_ALL_LIST_ITEMS(l, li)
6956 	    {
6957 		generate_PUSHS(cctx, &li->li_tv.vval.v_string);
6958 		li->li_tv.vval.v_string = NULL;
6959 	    }
6960 	    generate_NEWLIST(cctx, l->lv_len);
6961 	}
6962 	list_free(l);
6963 	p += STRLEN(p);
6964 	end = p;
6965     }
6966     else if (var_count > 0)
6967     {
6968 	char_u *wp;
6969 
6970 	// for "[var, var] = expr" evaluate the expression here, loop over the
6971 	// list of variables below.
6972 	// A line break may follow the "=".
6973 
6974 	wp = op + oplen;
6975 	if (may_get_next_line_error(wp, &p, cctx) == FAIL)
6976 	    return FAIL;
6977 	if (compile_expr0(&p, cctx) == FAIL)
6978 	    return NULL;
6979 	end = p;
6980 
6981 	if (cctx->ctx_skip != SKIP_YES)
6982 	{
6983 	    type_T	*stacktype;
6984 
6985 	    stacktype = stack->ga_len == 0 ? &t_void
6986 			      : ((type_T **)stack->ga_data)[stack->ga_len - 1];
6987 	    if (stacktype->tt_type == VAR_VOID)
6988 	    {
6989 		emsg(_(e_cannot_use_void_value));
6990 		goto theend;
6991 	    }
6992 	    if (need_type(stacktype, &t_list_any, -1, 0, cctx,
6993 							 FALSE, FALSE) == FAIL)
6994 		goto theend;
6995 	    // TODO: check the length of a constant list here
6996 	    generate_CHECKLEN(cctx, semicolon ? var_count - 1 : var_count,
6997 								    semicolon);
6998 	    if (stacktype->tt_member != NULL)
6999 		rhs_type = stacktype->tt_member;
7000 	}
7001     }
7002 
7003     /*
7004      * Loop over variables in "[var, var] = expr".
7005      * For "var = expr" and "let var: type" this is done only once.
7006      */
7007     if (var_count > 0)
7008 	var_start = skipwhite(arg + 1);  // skip over the "["
7009     else
7010 	var_start = arg;
7011     for (var_idx = 0; var_idx == 0 || var_idx < var_count; var_idx++)
7012     {
7013 	int	instr_count = -1;
7014 	int	save_lnum;
7015 
7016 	if (var_start[0] == '_' && !eval_isnamec(var_start[1]))
7017 	{
7018 	    // Ignore underscore in "[a, _, b] = list".
7019 	    if (var_count > 0)
7020 	    {
7021 		var_start = skipwhite(var_start + 2);
7022 		continue;
7023 	    }
7024 	    emsg(_(e_cannot_use_underscore_here));
7025 	    goto theend;
7026 	}
7027 	vim_free(lhs.lhs_name);
7028 
7029 	/*
7030 	 * Figure out the LHS type and other properties.
7031 	 */
7032 	if (compile_assign_lhs(var_start, &lhs, cmdidx,
7033 					is_decl, heredoc, oplen, cctx) == FAIL)
7034 	    goto theend;
7035 	if (heredoc)
7036 	{
7037 	    SOURCING_LNUM = start_lnum;
7038 	    if (lhs.lhs_has_type
7039 		    && need_type(&t_list_string, lhs.lhs_type,
7040 					    -1, 0, cctx, FALSE, FALSE) == FAIL)
7041 		goto theend;
7042 	}
7043 	else
7044 	{
7045 	    if (cctx->ctx_skip == SKIP_YES)
7046 	    {
7047 		if (oplen > 0 && var_count == 0)
7048 		{
7049 		    // skip over the "=" and the expression
7050 		    p = skipwhite(op + oplen);
7051 		    (void)compile_expr0(&p, cctx);
7052 		}
7053 	    }
7054 	    else if (oplen > 0)
7055 	    {
7056 		int	is_const = FALSE;
7057 		char_u	*wp;
7058 
7059 		// for "+=", "*=", "..=" etc. first load the current value
7060 		if (*op != '='
7061 			&& compile_load_lhs_with_index(&lhs, var_start,
7062 								 cctx) == FAIL)
7063 		    goto theend;
7064 
7065 		// For "var = expr" evaluate the expression.
7066 		if (var_count == 0)
7067 		{
7068 		    int	r;
7069 
7070 		    // Compile the expression.
7071 		    instr_count = instr->ga_len;
7072 		    if (incdec)
7073 		    {
7074 			r = generate_PUSHNR(cctx, 1);
7075 		    }
7076 		    else
7077 		    {
7078 			// Temporarily hide the new local variable here, it is
7079 			// not available to this expression.
7080 			if (lhs.lhs_new_local)
7081 			    --cctx->ctx_locals.ga_len;
7082 			wp = op + oplen;
7083 			if (may_get_next_line_error(wp, &p, cctx) == FAIL)
7084 			{
7085 			    if (lhs.lhs_new_local)
7086 				++cctx->ctx_locals.ga_len;
7087 			    goto theend;
7088 			}
7089 			r = compile_expr0_ext(&p, cctx, &is_const);
7090 			if (lhs.lhs_new_local)
7091 			    ++cctx->ctx_locals.ga_len;
7092 			if (r == FAIL)
7093 			    goto theend;
7094 		    }
7095 		}
7096 		else if (semicolon && var_idx == var_count - 1)
7097 		{
7098 		    // For "[var; var] = expr" get the rest of the list
7099 		    did_generate_slice = TRUE;
7100 		    if (generate_SLICE(cctx, var_count - 1) == FAIL)
7101 			goto theend;
7102 		}
7103 		else
7104 		{
7105 		    // For "[var, var] = expr" get the "var_idx" item from the
7106 		    // list.
7107 		    if (generate_GETITEM(cctx, var_idx, *op != '=') == FAIL)
7108 			goto theend;
7109 		}
7110 
7111 		rhs_type = stack->ga_len == 0 ? &t_void
7112 			      : ((type_T **)stack->ga_data)[stack->ga_len - 1];
7113 		if (lhs.lhs_lvar != NULL && (is_decl || !lhs.lhs_has_type))
7114 		{
7115 		    if ((rhs_type->tt_type == VAR_FUNC
7116 				|| rhs_type->tt_type == VAR_PARTIAL)
7117 			    && !lhs.lhs_has_index
7118 			    && var_wrong_func_name(lhs.lhs_name, TRUE))
7119 			goto theend;
7120 
7121 		    if (lhs.lhs_new_local && !lhs.lhs_has_type)
7122 		    {
7123 			if (rhs_type->tt_type == VAR_VOID)
7124 			{
7125 			    emsg(_(e_cannot_use_void_value));
7126 			    goto theend;
7127 			}
7128 			else
7129 			{
7130 			    // An empty list or dict has a &t_unknown member,
7131 			    // for a variable that implies &t_any.
7132 			    if (rhs_type == &t_list_empty)
7133 				lhs.lhs_lvar->lv_type = &t_list_any;
7134 			    else if (rhs_type == &t_dict_empty)
7135 				lhs.lhs_lvar->lv_type = &t_dict_any;
7136 			    else if (rhs_type == &t_unknown)
7137 				lhs.lhs_lvar->lv_type = &t_any;
7138 			    else
7139 				lhs.lhs_lvar->lv_type = rhs_type;
7140 			}
7141 		    }
7142 		    else if (*op == '=')
7143 		    {
7144 			type_T *use_type = lhs.lhs_lvar->lv_type;
7145 			where_T where = WHERE_INIT;
7146 
7147 			// Without operator check type here, otherwise below.
7148 			// Use the line number of the assignment.
7149 			SOURCING_LNUM = start_lnum;
7150 			where.wt_index = var_count > 0 ? var_idx + 1 : 0;
7151 			where.wt_variable = var_count > 0;
7152 			// If assigning to a list or dict member, use the
7153 			// member type.  Not for "list[:] =".
7154 			if (lhs.lhs_has_index
7155 				&& !has_list_index(var_start + lhs.lhs_varlen,
7156 									 cctx))
7157 			    use_type = lhs.lhs_member_type;
7158 			if (need_type_where(rhs_type, use_type, -1, where,
7159 				    cctx, FALSE, is_const) == FAIL)
7160 			    goto theend;
7161 		    }
7162 		}
7163 		else
7164 		{
7165 		    type_T *lhs_type = lhs.lhs_member_type;
7166 
7167 		    // Special case: assigning to @# can use a number or a
7168 		    // string.
7169 		    // Also: can assign a number to a float.
7170 		    if ((lhs_type == &t_number_or_string
7171 				|| lhs_type == &t_float)
7172 			    && rhs_type->tt_type == VAR_NUMBER)
7173 			lhs_type = &t_number;
7174 		    if (*p != '=' && need_type(rhs_type, lhs_type,
7175 					    -1, 0, cctx, FALSE, FALSE) == FAIL)
7176 		    goto theend;
7177 		}
7178 	    }
7179 	    else if (cmdidx == CMD_final)
7180 	    {
7181 		emsg(_(e_final_requires_a_value));
7182 		goto theend;
7183 	    }
7184 	    else if (cmdidx == CMD_const)
7185 	    {
7186 		emsg(_(e_const_requires_a_value));
7187 		goto theend;
7188 	    }
7189 	    else if (!lhs.lhs_has_type || lhs.lhs_dest == dest_option)
7190 	    {
7191 		emsg(_(e_type_or_initialization_required));
7192 		goto theend;
7193 	    }
7194 	    else
7195 	    {
7196 		// variables are always initialized
7197 		if (GA_GROW_FAILS(instr, 1))
7198 		    goto theend;
7199 		switch (lhs.lhs_member_type->tt_type)
7200 		{
7201 		    case VAR_BOOL:
7202 			generate_PUSHBOOL(cctx, VVAL_FALSE);
7203 			break;
7204 		    case VAR_FLOAT:
7205 #ifdef FEAT_FLOAT
7206 			generate_PUSHF(cctx, 0.0);
7207 #endif
7208 			break;
7209 		    case VAR_STRING:
7210 			generate_PUSHS(cctx, NULL);
7211 			break;
7212 		    case VAR_BLOB:
7213 			generate_PUSHBLOB(cctx, blob_alloc());
7214 			break;
7215 		    case VAR_FUNC:
7216 			generate_PUSHFUNC(cctx, NULL, &t_func_void);
7217 			break;
7218 		    case VAR_LIST:
7219 			generate_NEWLIST(cctx, 0);
7220 			break;
7221 		    case VAR_DICT:
7222 			generate_NEWDICT(cctx, 0);
7223 			break;
7224 		    case VAR_JOB:
7225 			generate_PUSHJOB(cctx, NULL);
7226 			break;
7227 		    case VAR_CHANNEL:
7228 			generate_PUSHCHANNEL(cctx, NULL);
7229 			break;
7230 		    case VAR_NUMBER:
7231 		    case VAR_UNKNOWN:
7232 		    case VAR_ANY:
7233 		    case VAR_PARTIAL:
7234 		    case VAR_VOID:
7235 		    case VAR_INSTR:
7236 		    case VAR_SPECIAL:  // cannot happen
7237 			generate_PUSHNR(cctx, 0);
7238 			break;
7239 		}
7240 	    }
7241 	    if (var_count == 0)
7242 		end = p;
7243 	}
7244 
7245 	// no need to parse more when skipping
7246 	if (cctx->ctx_skip == SKIP_YES)
7247 	    break;
7248 
7249 	if (oplen > 0 && *op != '=')
7250 	{
7251 	    type_T	    *expected;
7252 	    type_T	    *stacktype = NULL;
7253 
7254 	    if (*op == '.')
7255 	    {
7256 		if (may_generate_2STRING(-1, FALSE, cctx) == FAIL)
7257 		    goto theend;
7258 	    }
7259 	    else
7260 	    {
7261 		expected = lhs.lhs_member_type;
7262 		stacktype = ((type_T **)stack->ga_data)[stack->ga_len - 1];
7263 		if (
7264 #ifdef FEAT_FLOAT
7265 		    // If variable is float operation with number is OK.
7266 		    !(expected == &t_float && (stacktype == &t_number
7267 			    || stacktype == &t_number_bool)) &&
7268 #endif
7269 		    need_type(stacktype, expected, -1, 0, cctx,
7270 							 FALSE, FALSE) == FAIL)
7271 		    goto theend;
7272 	    }
7273 
7274 	    if (*op == '.')
7275 	    {
7276 		if (generate_instr_drop(cctx, ISN_CONCAT, 1) == NULL)
7277 		    goto theend;
7278 	    }
7279 	    else if (*op == '+')
7280 	    {
7281 		if (generate_add_instr(cctx,
7282 			    operator_type(lhs.lhs_member_type, stacktype),
7283 				       lhs.lhs_member_type, stacktype,
7284 							  EXPR_APPEND) == FAIL)
7285 		    goto theend;
7286 	    }
7287 	    else if (generate_two_op(cctx, op) == FAIL)
7288 		goto theend;
7289 	}
7290 
7291 	// Use the line number of the assignment for store instruction.
7292 	save_lnum = cctx->ctx_lnum;
7293 	cctx->ctx_lnum = start_lnum - 1;
7294 
7295 	if (lhs.lhs_has_index)
7296 	{
7297 	    // Use the info in "lhs" to store the value at the index in the
7298 	    // list or dict.
7299 	    if (compile_assign_unlet(var_start, &lhs, TRUE, rhs_type, cctx)
7300 								       == FAIL)
7301 	    {
7302 		cctx->ctx_lnum = save_lnum;
7303 		goto theend;
7304 	    }
7305 	}
7306 	else
7307 	{
7308 	    if (is_decl && cmdidx == CMD_const && (lhs.lhs_dest == dest_script
7309 						|| lhs.lhs_dest == dest_global
7310 						|| lhs.lhs_dest == dest_local))
7311 		// ":const var": lock the value, but not referenced variables
7312 		generate_LOCKCONST(cctx);
7313 
7314 	    if (is_decl
7315 		    && (lhs.lhs_type->tt_type == VAR_DICT
7316 					  || lhs.lhs_type->tt_type == VAR_LIST)
7317 		    && lhs.lhs_type->tt_member != NULL
7318 		    && !(lhs.lhs_type->tt_member == &t_any
7319 			    && oplen > 0
7320 			    && rhs_type != NULL
7321 			    && rhs_type->tt_type == lhs.lhs_type->tt_type
7322 			    && rhs_type->tt_member != &t_unknown)
7323 		    && lhs.lhs_type->tt_member != &t_unknown)
7324 		// Set the type in the list or dict, so that it can be checked,
7325 		// also in legacy script.  Not for "list<any> = val", then the
7326 		// type of "val" is used.
7327 		generate_SETTYPE(cctx, lhs.lhs_type);
7328 
7329 	    if (generate_store_lhs(cctx, &lhs, instr_count) == FAIL)
7330 	    {
7331 		cctx->ctx_lnum = save_lnum;
7332 		goto theend;
7333 	    }
7334 	}
7335 	cctx->ctx_lnum = save_lnum;
7336 
7337 	if (var_idx + 1 < var_count)
7338 	    var_start = skipwhite(lhs.lhs_dest_end + 1);
7339     }
7340 
7341     // For "[var, var] = expr" drop the "expr" value.
7342     // Also for "[var, var; _] = expr".
7343     if (var_count > 0 && (!semicolon || !did_generate_slice))
7344     {
7345 	if (generate_instr_drop(cctx, ISN_DROP, 1) == NULL)
7346 	    goto theend;
7347     }
7348 
7349     ret = skipwhite(end);
7350 
7351 theend:
7352     vim_free(lhs.lhs_name);
7353     return ret;
7354 }
7355 
7356 /*
7357  * Check for an assignment at "eap->cmd", compile it if found.
7358  * Return NOTDONE if there is none, FAIL for failure, OK if done.
7359  */
7360     static int
may_compile_assignment(exarg_T * eap,char_u ** line,cctx_T * cctx)7361 may_compile_assignment(exarg_T *eap, char_u **line, cctx_T *cctx)
7362 {
7363     char_u  *pskip;
7364     char_u  *p;
7365 
7366     // Assuming the command starts with a variable or function name,
7367     // find what follows.
7368     // Skip over "var.member", "var[idx]" and the like.
7369     // Also "&opt = val", "$ENV = val" and "@r = val".
7370     pskip = (*eap->cmd == '&' || *eap->cmd == '$' || *eap->cmd == '@')
7371 						 ? eap->cmd + 1 : eap->cmd;
7372     p = to_name_end(pskip, TRUE);
7373     if (p > eap->cmd && *p != NUL)
7374     {
7375 	char_u *var_end;
7376 	int	oplen;
7377 	int	heredoc;
7378 
7379 	if (eap->cmd[0] == '@')
7380 	    var_end = eap->cmd + 2;
7381 	else
7382 	    var_end = find_name_end(pskip, NULL, NULL,
7383 					FNE_CHECK_START | FNE_INCL_BR);
7384 	oplen = assignment_len(skipwhite(var_end), &heredoc);
7385 	if (oplen > 0)
7386 	{
7387 	    size_t len = p - eap->cmd;
7388 
7389 	    // Recognize an assignment if we recognize the variable
7390 	    // name:
7391 	    // "g:var = expr"
7392 	    // "local = expr"  where "local" is a local var.
7393 	    // "script = expr"  where "script" is a script-local var.
7394 	    // "import = expr"  where "import" is an imported var
7395 	    // "&opt = expr"
7396 	    // "$ENV = expr"
7397 	    // "@r = expr"
7398 	    if (*eap->cmd == '&'
7399 		    || *eap->cmd == '$'
7400 		    || *eap->cmd == '@'
7401 		    || ((len) > 2 && eap->cmd[1] == ':')
7402 		    || variable_exists(eap->cmd, len, cctx))
7403 	    {
7404 		*line = compile_assignment(eap->cmd, eap, CMD_SIZE, cctx);
7405 		if (*line == NULL || *line == eap->cmd)
7406 		    return FAIL;
7407 		return OK;
7408 	    }
7409 	}
7410     }
7411 
7412     if (*eap->cmd == '[')
7413     {
7414 	// [var, var] = expr
7415 	*line = compile_assignment(eap->cmd, eap, CMD_SIZE, cctx);
7416 	if (*line == NULL)
7417 	    return FAIL;
7418 	if (*line != eap->cmd)
7419 	    return OK;
7420     }
7421     return NOTDONE;
7422 }
7423 
7424 /*
7425  * Check if "name" can be "unlet".
7426  */
7427     int
check_vim9_unlet(char_u * name)7428 check_vim9_unlet(char_u *name)
7429 {
7430     if (name[1] != ':' || vim_strchr((char_u *)"gwtb", *name) == NULL)
7431     {
7432 	// "unlet s:var" is allowed in legacy script.
7433 	if (*name == 's' && !script_is_vim9())
7434 	    return OK;
7435 	semsg(_(e_cannot_unlet_str), name);
7436 	return FAIL;
7437     }
7438     return OK;
7439 }
7440 
7441 /*
7442  * Callback passed to ex_unletlock().
7443  */
7444     static int
compile_unlet(lval_T * lvp,char_u * name_end,exarg_T * eap,int deep UNUSED,void * coookie)7445 compile_unlet(
7446     lval_T  *lvp,
7447     char_u  *name_end,
7448     exarg_T *eap,
7449     int	    deep UNUSED,
7450     void    *coookie)
7451 {
7452     cctx_T	*cctx = coookie;
7453     char_u	*p = lvp->ll_name;
7454     int		cc = *name_end;
7455     int		ret = OK;
7456 
7457     if (cctx->ctx_skip == SKIP_YES)
7458 	return OK;
7459 
7460     *name_end = NUL;
7461     if (*p == '$')
7462     {
7463 	// :unlet $ENV_VAR
7464 	ret = generate_UNLET(cctx, ISN_UNLETENV, p + 1, eap->forceit);
7465     }
7466     else if (vim_strchr(p, '.') != NULL || vim_strchr(p, '[') != NULL)
7467     {
7468 	lhs_T	    lhs;
7469 
7470 	// This is similar to assigning: lookup the list/dict, compile the
7471 	// idx/key.  Then instead of storing the value unlet the item.
7472 	// unlet {list}[idx]
7473 	// unlet {dict}[key]  dict.key
7474 	//
7475 	// Figure out the LHS type and other properties.
7476 	//
7477 	ret = compile_lhs(p, &lhs, CMD_unlet, FALSE, 0, cctx);
7478 
7479 	// : unlet an indexed item
7480 	if (!lhs.lhs_has_index)
7481 	{
7482 	    iemsg("called compile_lhs() without an index");
7483 	    ret = FAIL;
7484 	}
7485 	else
7486 	{
7487 	    // Use the info in "lhs" to unlet the item at the index in the
7488 	    // list or dict.
7489 	    ret = compile_assign_unlet(p, &lhs, FALSE, &t_void, cctx);
7490 	}
7491 
7492 	vim_free(lhs.lhs_name);
7493     }
7494     else if (check_vim9_unlet(p) == FAIL)
7495     {
7496 	ret = FAIL;
7497     }
7498     else
7499     {
7500 	// Normal name.  Only supports g:, w:, t: and b: namespaces.
7501 	ret = generate_UNLET(cctx, ISN_UNLET, p, eap->forceit);
7502     }
7503 
7504     *name_end = cc;
7505     return ret;
7506 }
7507 
7508 /*
7509  * Callback passed to ex_unletlock().
7510  */
7511     static int
compile_lock_unlock(lval_T * lvp,char_u * name_end,exarg_T * eap,int deep UNUSED,void * coookie)7512 compile_lock_unlock(
7513     lval_T  *lvp,
7514     char_u  *name_end,
7515     exarg_T *eap,
7516     int	    deep UNUSED,
7517     void    *coookie)
7518 {
7519     cctx_T	*cctx = coookie;
7520     int		cc = *name_end;
7521     char_u	*p = lvp->ll_name;
7522     int		ret = OK;
7523     size_t	len;
7524     char_u	*buf;
7525     isntype_T	isn = ISN_EXEC;
7526 
7527     if (cctx->ctx_skip == SKIP_YES)
7528 	return OK;
7529 
7530     // Cannot use :lockvar and :unlockvar on local variables.
7531     if (p[1] != ':')
7532     {
7533 	char_u *end = find_name_end(p, NULL, NULL, FNE_CHECK_START);
7534 
7535 	if (lookup_local(p, end - p, NULL, cctx) == OK)
7536 	{
7537 	    char_u *s = p;
7538 
7539 	    if (*end != '.' && *end != '[')
7540 	    {
7541 		emsg(_(e_cannot_lock_unlock_local_variable));
7542 		return FAIL;
7543 	    }
7544 
7545 	    // For "d.member" put the local variable on the stack, it will be
7546 	    // passed to ex_lockvar() indirectly.
7547 	    if (compile_load(&s, end, cctx, FALSE, FALSE) == FAIL)
7548 		return FAIL;
7549 	    isn = ISN_LOCKUNLOCK;
7550 	}
7551     }
7552 
7553     // Checking is done at runtime.
7554     *name_end = NUL;
7555     len = name_end - p + 20;
7556     buf = alloc(len);
7557     if (buf == NULL)
7558 	ret = FAIL;
7559     else
7560     {
7561 	vim_snprintf((char *)buf, len, "%s %s",
7562 		eap->cmdidx == CMD_lockvar ? "lockvar" : "unlockvar",
7563 		p);
7564 	ret = generate_EXEC(cctx, isn, buf);
7565 
7566 	vim_free(buf);
7567 	*name_end = cc;
7568     }
7569     return ret;
7570 }
7571 
7572 /*
7573  * compile "unlet var", "lock var" and "unlock var"
7574  * "arg" points to "var".
7575  */
7576     static char_u *
compile_unletlock(char_u * arg,exarg_T * eap,cctx_T * cctx)7577 compile_unletlock(char_u *arg, exarg_T *eap, cctx_T *cctx)
7578 {
7579     ex_unletlock(eap, arg, 0, GLV_NO_AUTOLOAD | GLV_COMPILING,
7580 	    eap->cmdidx == CMD_unlet ? compile_unlet : compile_lock_unlock,
7581 	    cctx);
7582     return eap->nextcmd == NULL ? (char_u *)"" : eap->nextcmd;
7583 }
7584 
7585 /*
7586  * generate a jump to the ":endif"/":endfor"/":endwhile"/":finally"/":endtry".
7587  */
7588     static int
compile_jump_to_end(endlabel_T ** el,jumpwhen_T when,cctx_T * cctx)7589 compile_jump_to_end(endlabel_T **el, jumpwhen_T when, cctx_T *cctx)
7590 {
7591     garray_T	*instr = &cctx->ctx_instr;
7592     endlabel_T  *endlabel = ALLOC_CLEAR_ONE(endlabel_T);
7593 
7594     if (endlabel == NULL)
7595 	return FAIL;
7596     endlabel->el_next = *el;
7597     *el = endlabel;
7598     endlabel->el_end_label = instr->ga_len;
7599 
7600     generate_JUMP(cctx, when, 0);
7601     return OK;
7602 }
7603 
7604     static void
compile_fill_jump_to_end(endlabel_T ** el,int jump_where,cctx_T * cctx)7605 compile_fill_jump_to_end(endlabel_T **el, int jump_where, cctx_T *cctx)
7606 {
7607     garray_T	*instr = &cctx->ctx_instr;
7608 
7609     while (*el != NULL)
7610     {
7611 	endlabel_T  *cur = (*el);
7612 	isn_T	    *isn;
7613 
7614 	isn = ((isn_T *)instr->ga_data) + cur->el_end_label;
7615 	isn->isn_arg.jump.jump_where = jump_where;
7616 	*el = cur->el_next;
7617 	vim_free(cur);
7618     }
7619 }
7620 
7621     static void
compile_free_jump_to_end(endlabel_T ** el)7622 compile_free_jump_to_end(endlabel_T **el)
7623 {
7624     while (*el != NULL)
7625     {
7626 	endlabel_T  *cur = (*el);
7627 
7628 	*el = cur->el_next;
7629 	vim_free(cur);
7630     }
7631 }
7632 
7633 /*
7634  * Create a new scope and set up the generic items.
7635  */
7636     static scope_T *
new_scope(cctx_T * cctx,scopetype_T type)7637 new_scope(cctx_T *cctx, scopetype_T type)
7638 {
7639     scope_T *scope = ALLOC_CLEAR_ONE(scope_T);
7640 
7641     if (scope == NULL)
7642 	return NULL;
7643     scope->se_outer = cctx->ctx_scope;
7644     cctx->ctx_scope = scope;
7645     scope->se_type = type;
7646     scope->se_local_count = cctx->ctx_locals.ga_len;
7647     return scope;
7648 }
7649 
7650 /*
7651  * Free the current scope and go back to the outer scope.
7652  */
7653     static void
drop_scope(cctx_T * cctx)7654 drop_scope(cctx_T *cctx)
7655 {
7656     scope_T *scope = cctx->ctx_scope;
7657 
7658     if (scope == NULL)
7659     {
7660 	iemsg("calling drop_scope() without a scope");
7661 	return;
7662     }
7663     cctx->ctx_scope = scope->se_outer;
7664     switch (scope->se_type)
7665     {
7666 	case IF_SCOPE:
7667 	    compile_free_jump_to_end(&scope->se_u.se_if.is_end_label); break;
7668 	case FOR_SCOPE:
7669 	    compile_free_jump_to_end(&scope->se_u.se_for.fs_end_label); break;
7670 	case WHILE_SCOPE:
7671 	    compile_free_jump_to_end(&scope->se_u.se_while.ws_end_label); break;
7672 	case TRY_SCOPE:
7673 	    compile_free_jump_to_end(&scope->se_u.se_try.ts_end_label); break;
7674 	case NO_SCOPE:
7675 	case BLOCK_SCOPE:
7676 	    break;
7677     }
7678     vim_free(scope);
7679 }
7680 
7681 /*
7682  * compile "if expr"
7683  *
7684  * "if expr" Produces instructions:
7685  *	EVAL expr		Push result of "expr"
7686  *	JUMP_IF_FALSE end
7687  *	... body ...
7688  * end:
7689  *
7690  * "if expr | else" Produces instructions:
7691  *	EVAL expr		Push result of "expr"
7692  *	JUMP_IF_FALSE else
7693  *	... body ...
7694  *	JUMP_ALWAYS end
7695  * else:
7696  *	... body ...
7697  * end:
7698  *
7699  * "if expr1 | elseif expr2 | else" Produces instructions:
7700  *	EVAL expr		Push result of "expr"
7701  *	JUMP_IF_FALSE elseif
7702  *	... body ...
7703  *	JUMP_ALWAYS end
7704  * elseif:
7705  *	EVAL expr		Push result of "expr"
7706  *	JUMP_IF_FALSE else
7707  *	... body ...
7708  *	JUMP_ALWAYS end
7709  * else:
7710  *	... body ...
7711  * end:
7712  */
7713     static char_u *
compile_if(char_u * arg,cctx_T * cctx)7714 compile_if(char_u *arg, cctx_T *cctx)
7715 {
7716     char_u	*p = arg;
7717     garray_T	*instr = &cctx->ctx_instr;
7718     int		instr_count = instr->ga_len;
7719     scope_T	*scope;
7720     skip_T	skip_save = cctx->ctx_skip;
7721     ppconst_T	ppconst;
7722 
7723     CLEAR_FIELD(ppconst);
7724     if (compile_expr1(&p, cctx, &ppconst) == FAIL)
7725     {
7726 	clear_ppconst(&ppconst);
7727 	return NULL;
7728     }
7729     if (!ends_excmd2(arg, skipwhite(p)))
7730     {
7731 	semsg(_(e_trailing_arg), p);
7732 	return NULL;
7733     }
7734     if (cctx->ctx_skip == SKIP_YES)
7735 	clear_ppconst(&ppconst);
7736     else if (instr->ga_len == instr_count && ppconst.pp_used == 1)
7737     {
7738 	int error = FALSE;
7739 	int v;
7740 
7741 	// The expression results in a constant.
7742 	v = tv_get_bool_chk(&ppconst.pp_tv[0], &error);
7743 	clear_ppconst(&ppconst);
7744 	if (error)
7745 	    return NULL;
7746 	cctx->ctx_skip = v ? SKIP_NOT : SKIP_YES;
7747     }
7748     else
7749     {
7750 	// Not a constant, generate instructions for the expression.
7751 	cctx->ctx_skip = SKIP_UNKNOWN;
7752 	if (generate_ppconst(cctx, &ppconst) == FAIL)
7753 	    return NULL;
7754 	if (bool_on_stack(cctx) == FAIL)
7755 	    return NULL;
7756     }
7757 
7758     // CMDMOD_REV must come before the jump
7759     generate_undo_cmdmods(cctx);
7760 
7761     scope = new_scope(cctx, IF_SCOPE);
7762     if (scope == NULL)
7763 	return NULL;
7764     scope->se_skip_save = skip_save;
7765     // "is_had_return" will be reset if any block does not end in :return
7766     scope->se_u.se_if.is_had_return = TRUE;
7767 
7768     if (cctx->ctx_skip == SKIP_UNKNOWN)
7769     {
7770 	// "where" is set when ":elseif", "else" or ":endif" is found
7771 	scope->se_u.se_if.is_if_label = instr->ga_len;
7772 	generate_JUMP(cctx, JUMP_IF_FALSE, 0);
7773     }
7774     else
7775 	scope->se_u.se_if.is_if_label = -1;
7776 
7777 #ifdef FEAT_PROFILE
7778     if (cctx->ctx_compile_type == CT_PROFILE && cctx->ctx_skip == SKIP_YES
7779 						      && skip_save != SKIP_YES)
7780     {
7781 	// generated a profile start, need to generate a profile end, since it
7782 	// won't be done after returning
7783 	cctx->ctx_skip = SKIP_NOT;
7784 	generate_instr(cctx, ISN_PROF_END);
7785 	cctx->ctx_skip = SKIP_YES;
7786     }
7787 #endif
7788 
7789     return p;
7790 }
7791 
7792     static char_u *
compile_elseif(char_u * arg,cctx_T * cctx)7793 compile_elseif(char_u *arg, cctx_T *cctx)
7794 {
7795     char_u	*p = arg;
7796     garray_T	*instr = &cctx->ctx_instr;
7797     int		instr_count = instr->ga_len;
7798     isn_T	*isn;
7799     scope_T	*scope = cctx->ctx_scope;
7800     ppconst_T	ppconst;
7801     skip_T	save_skip = cctx->ctx_skip;
7802 
7803     if (scope == NULL || scope->se_type != IF_SCOPE)
7804     {
7805 	emsg(_(e_elseif_without_if));
7806 	return NULL;
7807     }
7808     unwind_locals(cctx, scope->se_local_count);
7809     if (!cctx->ctx_had_return)
7810 	scope->se_u.se_if.is_had_return = FALSE;
7811 
7812     if (cctx->ctx_skip == SKIP_NOT)
7813     {
7814 	// previous block was executed, this one and following will not
7815 	cctx->ctx_skip = SKIP_YES;
7816 	scope->se_u.se_if.is_seen_skip_not = TRUE;
7817     }
7818     if (scope->se_u.se_if.is_seen_skip_not)
7819     {
7820 	// A previous block was executed, skip over expression and bail out.
7821 	// Do not count the "elseif" for profiling and cmdmod
7822 	instr->ga_len = current_instr_idx(cctx);
7823 
7824 	skip_expr_cctx(&p, cctx);
7825 	return p;
7826     }
7827 
7828     if (cctx->ctx_skip == SKIP_UNKNOWN)
7829     {
7830 	int	    moved_cmdmod = FALSE;
7831 	int	    saved_debug = FALSE;
7832 	isn_T	    debug_isn;
7833 
7834 	// Move any CMDMOD instruction to after the jump
7835 	if (((isn_T *)instr->ga_data)[instr->ga_len - 1].isn_type == ISN_CMDMOD)
7836 	{
7837 	    if (GA_GROW_FAILS(instr, 1))
7838 		return NULL;
7839 	    ((isn_T *)instr->ga_data)[instr->ga_len] =
7840 				  ((isn_T *)instr->ga_data)[instr->ga_len - 1];
7841 	    --instr->ga_len;
7842 	    moved_cmdmod = TRUE;
7843 	}
7844 
7845 	// Remove the already generated ISN_DEBUG, it is written below the
7846 	// ISN_FOR instruction.
7847 	if (cctx->ctx_compile_type == CT_DEBUG && instr->ga_len > 0
7848 		&& ((isn_T *)instr->ga_data)[instr->ga_len - 1]
7849 							.isn_type == ISN_DEBUG)
7850 	{
7851 	    --instr->ga_len;
7852 	    debug_isn = ((isn_T *)instr->ga_data)[instr->ga_len];
7853 	    saved_debug = TRUE;
7854 	}
7855 
7856 	if (compile_jump_to_end(&scope->se_u.se_if.is_end_label,
7857 						    JUMP_ALWAYS, cctx) == FAIL)
7858 	    return NULL;
7859 	// previous "if" or "elseif" jumps here
7860 	isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
7861 	isn->isn_arg.jump.jump_where = instr->ga_len;
7862 
7863 	if (moved_cmdmod)
7864 	    ++instr->ga_len;
7865 
7866 	if (saved_debug)
7867 	{
7868 	    // move the debug instruction here
7869 	    if (GA_GROW_FAILS(instr, 1))
7870 		return NULL;
7871 	    ((isn_T *)instr->ga_data)[instr->ga_len] = debug_isn;
7872 	    ++instr->ga_len;
7873 	}
7874     }
7875 
7876     // compile "expr"; if we know it evaluates to FALSE skip the block
7877     CLEAR_FIELD(ppconst);
7878     if (cctx->ctx_skip == SKIP_YES)
7879     {
7880 	cctx->ctx_skip = SKIP_UNKNOWN;
7881 #ifdef FEAT_PROFILE
7882 	if (cctx->ctx_compile_type == CT_PROFILE)
7883 	{
7884 	    // the previous block was skipped, need to profile this line
7885 	    generate_instr(cctx, ISN_PROF_START);
7886 	    instr_count = instr->ga_len;
7887 	}
7888 #endif
7889 	if (cctx->ctx_compile_type == CT_DEBUG)
7890 	{
7891 	    // the previous block was skipped, may want to debug this line
7892 	    generate_instr_debug(cctx);
7893 	    instr_count = instr->ga_len;
7894 	}
7895     }
7896     if (compile_expr1(&p, cctx, &ppconst) == FAIL)
7897     {
7898 	clear_ppconst(&ppconst);
7899 	return NULL;
7900     }
7901     cctx->ctx_skip = save_skip;
7902     if (!ends_excmd2(arg, skipwhite(p)))
7903     {
7904 	semsg(_(e_trailing_arg), p);
7905 	return NULL;
7906     }
7907     if (scope->se_skip_save == SKIP_YES)
7908 	clear_ppconst(&ppconst);
7909     else if (instr->ga_len == instr_count && ppconst.pp_used == 1)
7910     {
7911 	int error = FALSE;
7912 	int v;
7913 
7914 	// The expression results in a constant.
7915 	// TODO: how about nesting?
7916 	v = tv_get_bool_chk(&ppconst.pp_tv[0], &error);
7917 	if (error)
7918 	    return NULL;
7919 	cctx->ctx_skip = v ? SKIP_NOT : SKIP_YES;
7920 	clear_ppconst(&ppconst);
7921 	scope->se_u.se_if.is_if_label = -1;
7922     }
7923     else
7924     {
7925 	// Not a constant, generate instructions for the expression.
7926 	cctx->ctx_skip = SKIP_UNKNOWN;
7927 	if (generate_ppconst(cctx, &ppconst) == FAIL)
7928 	    return NULL;
7929 	if (bool_on_stack(cctx) == FAIL)
7930 	    return NULL;
7931 
7932 	// CMDMOD_REV must come before the jump
7933 	generate_undo_cmdmods(cctx);
7934 
7935 	// "where" is set when ":elseif", "else" or ":endif" is found
7936 	scope->se_u.se_if.is_if_label = instr->ga_len;
7937 	generate_JUMP(cctx, JUMP_IF_FALSE, 0);
7938     }
7939 
7940     return p;
7941 }
7942 
7943     static char_u *
compile_else(char_u * arg,cctx_T * cctx)7944 compile_else(char_u *arg, cctx_T *cctx)
7945 {
7946     char_u	*p = arg;
7947     garray_T	*instr = &cctx->ctx_instr;
7948     isn_T	*isn;
7949     scope_T	*scope = cctx->ctx_scope;
7950 
7951     if (scope == NULL || scope->se_type != IF_SCOPE)
7952     {
7953 	emsg(_(e_else_without_if));
7954 	return NULL;
7955     }
7956     unwind_locals(cctx, scope->se_local_count);
7957     if (!cctx->ctx_had_return)
7958 	scope->se_u.se_if.is_had_return = FALSE;
7959     scope->se_u.se_if.is_seen_else = TRUE;
7960 
7961 #ifdef FEAT_PROFILE
7962     if (cctx->ctx_compile_type == CT_PROFILE)
7963     {
7964 	if (cctx->ctx_skip == SKIP_NOT
7965 		&& ((isn_T *)instr->ga_data)[instr->ga_len - 1]
7966 						   .isn_type == ISN_PROF_START)
7967 	    // the previous block was executed, do not count "else" for
7968 	    // profiling
7969 	    --instr->ga_len;
7970 	if (cctx->ctx_skip == SKIP_YES && !scope->se_u.se_if.is_seen_skip_not)
7971 	{
7972 	    // the previous block was not executed, this one will, do count the
7973 	    // "else" for profiling
7974 	    cctx->ctx_skip = SKIP_NOT;
7975 	    generate_instr(cctx, ISN_PROF_END);
7976 	    generate_instr(cctx, ISN_PROF_START);
7977 	    cctx->ctx_skip = SKIP_YES;
7978 	}
7979     }
7980 #endif
7981 
7982     if (!scope->se_u.se_if.is_seen_skip_not && scope->se_skip_save != SKIP_YES)
7983     {
7984 	// jump from previous block to the end, unless the else block is empty
7985 	if (cctx->ctx_skip == SKIP_UNKNOWN)
7986 	{
7987 	    if (!cctx->ctx_had_return
7988 		    && compile_jump_to_end(&scope->se_u.se_if.is_end_label,
7989 						    JUMP_ALWAYS, cctx) == FAIL)
7990 		return NULL;
7991 	}
7992 
7993 	if (cctx->ctx_skip == SKIP_UNKNOWN)
7994 	{
7995 	    if (scope->se_u.se_if.is_if_label >= 0)
7996 	    {
7997 		// previous "if" or "elseif" jumps here
7998 		isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
7999 		isn->isn_arg.jump.jump_where = instr->ga_len;
8000 		scope->se_u.se_if.is_if_label = -1;
8001 	    }
8002 	}
8003 
8004 	if (cctx->ctx_skip != SKIP_UNKNOWN)
8005 	    cctx->ctx_skip = cctx->ctx_skip == SKIP_YES ? SKIP_NOT : SKIP_YES;
8006     }
8007 
8008     return p;
8009 }
8010 
8011     static char_u *
compile_endif(char_u * arg,cctx_T * cctx)8012 compile_endif(char_u *arg, cctx_T *cctx)
8013 {
8014     scope_T	*scope = cctx->ctx_scope;
8015     ifscope_T	*ifscope;
8016     garray_T	*instr = &cctx->ctx_instr;
8017     isn_T	*isn;
8018 
8019     if (misplaced_cmdmod(cctx))
8020 	return NULL;
8021 
8022     if (scope == NULL || scope->se_type != IF_SCOPE)
8023     {
8024 	emsg(_(e_endif_without_if));
8025 	return NULL;
8026     }
8027     ifscope = &scope->se_u.se_if;
8028     unwind_locals(cctx, scope->se_local_count);
8029     if (!cctx->ctx_had_return)
8030 	ifscope->is_had_return = FALSE;
8031 
8032     if (scope->se_u.se_if.is_if_label >= 0)
8033     {
8034 	// previous "if" or "elseif" jumps here
8035 	isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
8036 	isn->isn_arg.jump.jump_where = instr->ga_len;
8037     }
8038     // Fill in the "end" label in jumps at the end of the blocks.
8039     compile_fill_jump_to_end(&ifscope->is_end_label, instr->ga_len, cctx);
8040 
8041 #ifdef FEAT_PROFILE
8042     // even when skipping we count the endif as executed, unless the block it's
8043     // in is skipped
8044     if (cctx->ctx_compile_type == CT_PROFILE && cctx->ctx_skip == SKIP_YES
8045 					    && scope->se_skip_save != SKIP_YES)
8046     {
8047 	cctx->ctx_skip = SKIP_NOT;
8048 	generate_instr(cctx, ISN_PROF_START);
8049     }
8050 #endif
8051     cctx->ctx_skip = scope->se_skip_save;
8052 
8053     // If all the blocks end in :return and there is an :else then the
8054     // had_return flag is set.
8055     cctx->ctx_had_return = ifscope->is_had_return && ifscope->is_seen_else;
8056 
8057     drop_scope(cctx);
8058     return arg;
8059 }
8060 
8061 /*
8062  * Compile "for var in expr":
8063  *
8064  * Produces instructions:
8065  *       PUSHNR -1
8066  *       STORE loop-idx		Set index to -1
8067  *       EVAL expr		result of "expr" on top of stack
8068  * top:  FOR loop-idx, end	Increment index, use list on bottom of stack
8069  *				- if beyond end, jump to "end"
8070  *				- otherwise get item from list and push it
8071  *       STORE var		Store item in "var"
8072  *       ... body ...
8073  *       JUMP top		Jump back to repeat
8074  * end:	 DROP			Drop the result of "expr"
8075  *
8076  * Compile "for [var1, var2] in expr" - as above, but instead of "STORE var":
8077  *	 UNPACK 2		Split item in 2
8078  *       STORE var1		Store item in "var1"
8079  *       STORE var2		Store item in "var2"
8080  */
8081     static char_u *
compile_for(char_u * arg_start,cctx_T * cctx)8082 compile_for(char_u *arg_start, cctx_T *cctx)
8083 {
8084     char_u	*arg;
8085     char_u	*arg_end;
8086     char_u	*name = NULL;
8087     char_u	*p;
8088     char_u	*wp;
8089     int		var_count = 0;
8090     int		var_list = FALSE;
8091     int		semicolon = FALSE;
8092     size_t	varlen;
8093     garray_T	*stack = &cctx->ctx_type_stack;
8094     garray_T	*instr = &cctx->ctx_instr;
8095     scope_T	*scope;
8096     lvar_T	*loop_lvar;	// loop iteration variable
8097     lvar_T	*var_lvar;	// variable for "var"
8098     type_T	*vartype;
8099     type_T	*item_type = &t_any;
8100     int		idx;
8101     int		prev_lnum = cctx->ctx_prev_lnum;
8102 
8103     p = skip_var_list(arg_start, TRUE, &var_count, &semicolon, FALSE);
8104     if (p == NULL)
8105 	return NULL;
8106     if (var_count == 0)
8107 	var_count = 1;
8108     else
8109 	var_list = TRUE;  // can also be a list of one variable
8110 
8111     // consume "in"
8112     wp = p;
8113     if (may_get_next_line_error(wp, &p, cctx) == FAIL)
8114 	return NULL;
8115     if (STRNCMP(p, "in", 2) != 0 || !IS_WHITE_OR_NUL(p[2]))
8116     {
8117 	if (*p == ':' && wp != p)
8118 	    semsg(_(e_no_white_space_allowed_before_colon_str), p);
8119 	else
8120 	    emsg(_(e_missing_in));
8121 	return NULL;
8122     }
8123     wp = p + 2;
8124     if (may_get_next_line_error(wp, &p, cctx) == FAIL)
8125 	return NULL;
8126 
8127     // Remove the already generated ISN_DEBUG, it is written below the ISN_FOR
8128     // instruction.
8129     if (cctx->ctx_compile_type == CT_DEBUG && instr->ga_len > 0
8130 	    && ((isn_T *)instr->ga_data)[instr->ga_len - 1]
8131 							.isn_type == ISN_DEBUG)
8132     {
8133 	--instr->ga_len;
8134 	prev_lnum = ((isn_T *)instr->ga_data)[instr->ga_len]
8135 						 .isn_arg.debug.dbg_break_lnum;
8136     }
8137 
8138     scope = new_scope(cctx, FOR_SCOPE);
8139     if (scope == NULL)
8140 	return NULL;
8141 
8142     // Reserve a variable to store the loop iteration counter and initialize it
8143     // to -1.
8144     loop_lvar = reserve_local(cctx, (char_u *)"", 0, FALSE, &t_number);
8145     if (loop_lvar == NULL)
8146     {
8147 	// out of memory
8148 	drop_scope(cctx);
8149 	return NULL;
8150     }
8151     generate_STORENR(cctx, loop_lvar->lv_idx, -1);
8152 
8153     // compile "expr", it remains on the stack until "endfor"
8154     arg = p;
8155     if (compile_expr0(&arg, cctx) == FAIL)
8156     {
8157 	drop_scope(cctx);
8158 	return NULL;
8159     }
8160     arg_end = arg;
8161 
8162     if (cctx->ctx_skip != SKIP_YES)
8163     {
8164 	// If we know the type of "var" and it is a not a supported type we can
8165 	// give an error now.
8166 	vartype = ((type_T **)stack->ga_data)[stack->ga_len - 1];
8167 	if (vartype->tt_type != VAR_LIST && vartype->tt_type != VAR_STRING
8168 		&& vartype->tt_type != VAR_BLOB && vartype->tt_type != VAR_ANY)
8169 	{
8170 	    semsg(_(e_for_loop_on_str_not_supported),
8171 					       vartype_name(vartype->tt_type));
8172 	    drop_scope(cctx);
8173 	    return NULL;
8174 	}
8175 
8176 	if (vartype->tt_type == VAR_STRING)
8177 	    item_type = &t_string;
8178 	else if (vartype->tt_type == VAR_BLOB)
8179 	    item_type = &t_number;
8180 	else if (vartype->tt_type == VAR_LIST
8181 				     && vartype->tt_member->tt_type != VAR_ANY)
8182 	{
8183 	    if (!var_list)
8184 		item_type = vartype->tt_member;
8185 	    else if (vartype->tt_member->tt_type == VAR_LIST
8186 			  && vartype->tt_member->tt_member->tt_type != VAR_ANY)
8187 		// TODO: should get the type for each lhs
8188 		item_type = vartype->tt_member->tt_member;
8189 	}
8190 
8191 	// CMDMOD_REV must come before the FOR instruction.
8192 	generate_undo_cmdmods(cctx);
8193 
8194 	// "for_end" is set when ":endfor" is found
8195 	scope->se_u.se_for.fs_top_label = current_instr_idx(cctx);
8196 
8197 	generate_FOR(cctx, loop_lvar->lv_idx);
8198 
8199 	arg = arg_start;
8200 	if (var_list)
8201 	{
8202 	    generate_UNPACK(cctx, var_count, semicolon);
8203 	    arg = skipwhite(arg + 1);	// skip white after '['
8204 
8205 	    // the list item is replaced by a number of items
8206 	    if (GA_GROW_FAILS(stack, var_count - 1))
8207 	    {
8208 		drop_scope(cctx);
8209 		return NULL;
8210 	    }
8211 	    --stack->ga_len;
8212 	    for (idx = 0; idx < var_count; ++idx)
8213 	    {
8214 		((type_T **)stack->ga_data)[stack->ga_len] =
8215 				 (semicolon && idx == 0) ? vartype : item_type;
8216 		++stack->ga_len;
8217 	    }
8218 	}
8219 
8220 	for (idx = 0; idx < var_count; ++idx)
8221 	{
8222 	    assign_dest_T	dest = dest_local;
8223 	    int		opt_flags = 0;
8224 	    int		vimvaridx = -1;
8225 	    type_T		*type = &t_any;
8226 	    type_T		*lhs_type = &t_any;
8227 	    where_T		where = WHERE_INIT;
8228 
8229 	    p = skip_var_one(arg, FALSE);
8230 	    varlen = p - arg;
8231 	    name = vim_strnsave(arg, varlen);
8232 	    if (name == NULL)
8233 		goto failed;
8234 	    if (*p == ':')
8235 	    {
8236 		p = skipwhite(p + 1);
8237 		lhs_type = parse_type(&p, cctx->ctx_type_list, TRUE);
8238 	    }
8239 
8240 	    // TODO: script var not supported?
8241 	    if (get_var_dest(name, &dest, CMD_for, &opt_flags,
8242 					      &vimvaridx, &type, cctx) == FAIL)
8243 		goto failed;
8244 	    if (dest != dest_local)
8245 	    {
8246 		if (generate_store_var(cctx, dest, opt_flags, vimvaridx,
8247 						     0, 0, type, name) == FAIL)
8248 		    goto failed;
8249 	    }
8250 	    else if (varlen == 1 && *arg == '_')
8251 	    {
8252 		// Assigning to "_": drop the value.
8253 		if (generate_instr_drop(cctx, ISN_DROP, 1) == NULL)
8254 		    goto failed;
8255 	    }
8256 	    else
8257 	    {
8258 		if (lookup_local(arg, varlen, NULL, cctx) == OK)
8259 		{
8260 		    semsg(_(e_variable_already_declared), arg);
8261 		    goto failed;
8262 		}
8263 
8264 		if (STRNCMP(name, "s:", 2) == 0)
8265 		{
8266 		    semsg(_(e_cannot_declare_script_variable_in_function), name);
8267 		    goto failed;
8268 		}
8269 
8270 		// Reserve a variable to store "var".
8271 		where.wt_index = var_list ? idx + 1 : 0;
8272 		where.wt_variable = TRUE;
8273 		if (lhs_type == &t_any)
8274 		    lhs_type = item_type;
8275 		else if (item_type != &t_unknown
8276 			    && (item_type == &t_any
8277 			      ? need_type(item_type, lhs_type,
8278 						     -1, 0, cctx, FALSE, FALSE)
8279 			      : check_type(lhs_type, item_type, TRUE, where))
8280 			    == FAIL)
8281 		    goto failed;
8282 		var_lvar = reserve_local(cctx, arg, varlen, TRUE, lhs_type);
8283 		if (var_lvar == NULL)
8284 		    // out of memory or used as an argument
8285 		    goto failed;
8286 
8287 		if (semicolon && idx == var_count - 1)
8288 		    var_lvar->lv_type = vartype;
8289 		else
8290 		    var_lvar->lv_type = item_type;
8291 		generate_STORE(cctx, ISN_STORE, var_lvar->lv_idx, NULL);
8292 	    }
8293 
8294 	    if (*p == ',' || *p == ';')
8295 		++p;
8296 	    arg = skipwhite(p);
8297 	    vim_free(name);
8298 	}
8299 
8300 	if (cctx->ctx_compile_type == CT_DEBUG)
8301 	{
8302 	    int save_prev_lnum = cctx->ctx_prev_lnum;
8303 
8304 	    // Add ISN_DEBUG here, so that the loop variables can be inspected.
8305 	    // Use the prev_lnum from the ISN_DEBUG instruction removed above.
8306 	    cctx->ctx_prev_lnum = prev_lnum;
8307 	    generate_instr_debug(cctx);
8308 	    cctx->ctx_prev_lnum = save_prev_lnum;
8309 	}
8310     }
8311 
8312     return arg_end;
8313 
8314 failed:
8315     vim_free(name);
8316     drop_scope(cctx);
8317     return NULL;
8318 }
8319 
8320 /*
8321  * compile "endfor"
8322  */
8323     static char_u *
compile_endfor(char_u * arg,cctx_T * cctx)8324 compile_endfor(char_u *arg, cctx_T *cctx)
8325 {
8326     garray_T	*instr = &cctx->ctx_instr;
8327     scope_T	*scope = cctx->ctx_scope;
8328     forscope_T	*forscope;
8329     isn_T	*isn;
8330 
8331     if (misplaced_cmdmod(cctx))
8332 	return NULL;
8333 
8334     if (scope == NULL || scope->se_type != FOR_SCOPE)
8335     {
8336 	emsg(_(e_for));
8337 	return NULL;
8338     }
8339     forscope = &scope->se_u.se_for;
8340     cctx->ctx_scope = scope->se_outer;
8341     if (cctx->ctx_skip != SKIP_YES)
8342     {
8343 	unwind_locals(cctx, scope->se_local_count);
8344 
8345 	// At end of ":for" scope jump back to the FOR instruction.
8346 	generate_JUMP(cctx, JUMP_ALWAYS, forscope->fs_top_label);
8347 
8348 	// Fill in the "end" label in the FOR statement so it can jump here.
8349 	isn = ((isn_T *)instr->ga_data) + forscope->fs_top_label;
8350 	isn->isn_arg.forloop.for_end = instr->ga_len;
8351 
8352 	// Fill in the "end" label any BREAK statements
8353 	compile_fill_jump_to_end(&forscope->fs_end_label, instr->ga_len, cctx);
8354 
8355 	// Below the ":for" scope drop the "expr" list from the stack.
8356 	if (generate_instr_drop(cctx, ISN_DROP, 1) == NULL)
8357 	    return NULL;
8358     }
8359 
8360     vim_free(scope);
8361 
8362     return arg;
8363 }
8364 
8365 /*
8366  * compile "while expr"
8367  *
8368  * Produces instructions:
8369  * top:  EVAL expr		Push result of "expr"
8370  *       JUMP_IF_FALSE end	jump if false
8371  *       ... body ...
8372  *       JUMP top		Jump back to repeat
8373  * end:
8374  *
8375  */
8376     static char_u *
compile_while(char_u * arg,cctx_T * cctx)8377 compile_while(char_u *arg, cctx_T *cctx)
8378 {
8379     char_u	*p = arg;
8380     scope_T	*scope;
8381 
8382     scope = new_scope(cctx, WHILE_SCOPE);
8383     if (scope == NULL)
8384 	return NULL;
8385 
8386     // "endwhile" jumps back here, one before when profiling or using cmdmods
8387     scope->se_u.se_while.ws_top_label = current_instr_idx(cctx);
8388 
8389     // compile "expr"
8390     if (compile_expr0(&p, cctx) == FAIL)
8391 	return NULL;
8392 
8393     if (!ends_excmd2(arg, skipwhite(p)))
8394     {
8395 	semsg(_(e_trailing_arg), p);
8396 	return NULL;
8397     }
8398 
8399     if (cctx->ctx_skip != SKIP_YES)
8400     {
8401 	if (bool_on_stack(cctx) == FAIL)
8402 	    return FAIL;
8403 
8404 	// CMDMOD_REV must come before the jump
8405 	generate_undo_cmdmods(cctx);
8406 
8407 	// "while_end" is set when ":endwhile" is found
8408 	if (compile_jump_to_end(&scope->se_u.se_while.ws_end_label,
8409 						  JUMP_IF_FALSE, cctx) == FAIL)
8410 	    return FAIL;
8411     }
8412 
8413     return p;
8414 }
8415 
8416 /*
8417  * compile "endwhile"
8418  */
8419     static char_u *
compile_endwhile(char_u * arg,cctx_T * cctx)8420 compile_endwhile(char_u *arg, cctx_T *cctx)
8421 {
8422     scope_T	*scope = cctx->ctx_scope;
8423     garray_T	*instr = &cctx->ctx_instr;
8424 
8425     if (misplaced_cmdmod(cctx))
8426 	return NULL;
8427     if (scope == NULL || scope->se_type != WHILE_SCOPE)
8428     {
8429 	emsg(_(e_while));
8430 	return NULL;
8431     }
8432     cctx->ctx_scope = scope->se_outer;
8433     if (cctx->ctx_skip != SKIP_YES)
8434     {
8435 	unwind_locals(cctx, scope->se_local_count);
8436 
8437 #ifdef FEAT_PROFILE
8438 	// count the endwhile before jumping
8439 	may_generate_prof_end(cctx, cctx->ctx_lnum);
8440 #endif
8441 
8442 	// At end of ":for" scope jump back to the FOR instruction.
8443 	generate_JUMP(cctx, JUMP_ALWAYS, scope->se_u.se_while.ws_top_label);
8444 
8445 	// Fill in the "end" label in the WHILE statement so it can jump here.
8446 	// And in any jumps for ":break"
8447 	compile_fill_jump_to_end(&scope->se_u.se_while.ws_end_label,
8448 							  instr->ga_len, cctx);
8449     }
8450 
8451     vim_free(scope);
8452 
8453     return arg;
8454 }
8455 
8456 /*
8457  * compile "continue"
8458  */
8459     static char_u *
compile_continue(char_u * arg,cctx_T * cctx)8460 compile_continue(char_u *arg, cctx_T *cctx)
8461 {
8462     scope_T	*scope = cctx->ctx_scope;
8463     int		try_scopes = 0;
8464     int		loop_label;
8465 
8466     for (;;)
8467     {
8468 	if (scope == NULL)
8469 	{
8470 	    emsg(_(e_continue));
8471 	    return NULL;
8472 	}
8473 	if (scope->se_type == FOR_SCOPE)
8474 	{
8475 	    loop_label = scope->se_u.se_for.fs_top_label;
8476 	    break;
8477 	}
8478 	if (scope->se_type == WHILE_SCOPE)
8479 	{
8480 	    loop_label = scope->se_u.se_while.ws_top_label;
8481 	    break;
8482 	}
8483 	if (scope->se_type == TRY_SCOPE)
8484 	    ++try_scopes;
8485 	scope = scope->se_outer;
8486     }
8487 
8488     if (try_scopes > 0)
8489 	// Inside one or more try/catch blocks we first need to jump to the
8490 	// "finally" or "endtry" to cleanup.
8491 	generate_TRYCONT(cctx, try_scopes, loop_label);
8492     else
8493 	// Jump back to the FOR or WHILE instruction.
8494 	generate_JUMP(cctx, JUMP_ALWAYS, loop_label);
8495 
8496     return arg;
8497 }
8498 
8499 /*
8500  * compile "break"
8501  */
8502     static char_u *
compile_break(char_u * arg,cctx_T * cctx)8503 compile_break(char_u *arg, cctx_T *cctx)
8504 {
8505     scope_T	*scope = cctx->ctx_scope;
8506     endlabel_T	**el;
8507 
8508     for (;;)
8509     {
8510 	if (scope == NULL)
8511 	{
8512 	    emsg(_(e_break));
8513 	    return NULL;
8514 	}
8515 	if (scope->se_type == FOR_SCOPE || scope->se_type == WHILE_SCOPE)
8516 	    break;
8517 	scope = scope->se_outer;
8518     }
8519 
8520     // Jump to the end of the FOR or WHILE loop.
8521     if (scope->se_type == FOR_SCOPE)
8522 	el = &scope->se_u.se_for.fs_end_label;
8523     else
8524 	el = &scope->se_u.se_while.ws_end_label;
8525     if (compile_jump_to_end(el, JUMP_ALWAYS, cctx) == FAIL)
8526 	return FAIL;
8527 
8528     return arg;
8529 }
8530 
8531 /*
8532  * compile "{" start of block
8533  */
8534     static char_u *
compile_block(char_u * arg,cctx_T * cctx)8535 compile_block(char_u *arg, cctx_T *cctx)
8536 {
8537     if (new_scope(cctx, BLOCK_SCOPE) == NULL)
8538 	return NULL;
8539     return skipwhite(arg + 1);
8540 }
8541 
8542 /*
8543  * compile end of block: drop one scope
8544  */
8545     static void
compile_endblock(cctx_T * cctx)8546 compile_endblock(cctx_T *cctx)
8547 {
8548     scope_T	*scope = cctx->ctx_scope;
8549 
8550     cctx->ctx_scope = scope->se_outer;
8551     unwind_locals(cctx, scope->se_local_count);
8552     vim_free(scope);
8553 }
8554 
8555 /*
8556  * compile "try"
8557  * Creates a new scope for the try-endtry, pointing to the first catch and
8558  * finally.
8559  * Creates another scope for the "try" block itself.
8560  * TRY instruction sets up exception handling at runtime.
8561  *
8562  *	"try"
8563  *	    TRY -> catch1, -> finally  push trystack entry
8564  *	    ... try block
8565  *	"throw {exception}"
8566  *	    EVAL {exception}
8567  *	    THROW		create exception
8568  *	    ... try block
8569  *	" catch {expr}"
8570  *	    JUMP -> finally
8571  * catch1:  PUSH exception
8572  *	    EVAL {expr}
8573  *	    MATCH
8574  *	    JUMP nomatch -> catch2
8575  *	    CATCH   remove exception
8576  *	    ... catch block
8577  *	" catch"
8578  *	    JUMP -> finally
8579  * catch2:  CATCH   remove exception
8580  *	    ... catch block
8581  *	" finally"
8582  * finally:
8583  *	    ... finally block
8584  *	" endtry"
8585  *	    ENDTRY  pop trystack entry, may rethrow
8586  */
8587     static char_u *
compile_try(char_u * arg,cctx_T * cctx)8588 compile_try(char_u *arg, cctx_T *cctx)
8589 {
8590     garray_T	*instr = &cctx->ctx_instr;
8591     scope_T	*try_scope;
8592     scope_T	*scope;
8593 
8594     if (misplaced_cmdmod(cctx))
8595 	return NULL;
8596 
8597     // scope that holds the jumps that go to catch/finally/endtry
8598     try_scope = new_scope(cctx, TRY_SCOPE);
8599     if (try_scope == NULL)
8600 	return NULL;
8601 
8602     if (cctx->ctx_skip != SKIP_YES)
8603     {
8604 	isn_T	*isn;
8605 
8606 	// "try_catch" is set when the first ":catch" is found or when no catch
8607 	// is found and ":finally" is found.
8608 	// "try_finally" is set when ":finally" is found
8609 	// "try_endtry" is set when ":endtry" is found
8610 	try_scope->se_u.se_try.ts_try_label = instr->ga_len;
8611 	if ((isn = generate_instr(cctx, ISN_TRY)) == NULL)
8612 	    return NULL;
8613 	isn->isn_arg.try.try_ref = ALLOC_CLEAR_ONE(tryref_T);
8614 	if (isn->isn_arg.try.try_ref == NULL)
8615 	    return NULL;
8616     }
8617 
8618     // scope for the try block itself
8619     scope = new_scope(cctx, BLOCK_SCOPE);
8620     if (scope == NULL)
8621 	return NULL;
8622 
8623     return arg;
8624 }
8625 
8626 /*
8627  * compile "catch {expr}"
8628  */
8629     static char_u *
compile_catch(char_u * arg,cctx_T * cctx UNUSED)8630 compile_catch(char_u *arg, cctx_T *cctx UNUSED)
8631 {
8632     scope_T	*scope = cctx->ctx_scope;
8633     garray_T	*instr = &cctx->ctx_instr;
8634     char_u	*p;
8635     isn_T	*isn;
8636 
8637     if (misplaced_cmdmod(cctx))
8638 	return NULL;
8639 
8640     // end block scope from :try or :catch
8641     if (scope != NULL && scope->se_type == BLOCK_SCOPE)
8642 	compile_endblock(cctx);
8643     scope = cctx->ctx_scope;
8644 
8645     // Error if not in a :try scope
8646     if (scope == NULL || scope->se_type != TRY_SCOPE)
8647     {
8648 	emsg(_(e_catch));
8649 	return NULL;
8650     }
8651 
8652     if (scope->se_u.se_try.ts_caught_all)
8653     {
8654 	emsg(_(e_catch_unreachable_after_catch_all));
8655 	return NULL;
8656     }
8657 
8658     if (cctx->ctx_skip != SKIP_YES)
8659     {
8660 #ifdef FEAT_PROFILE
8661 	// the profile-start should be after the jump
8662 	if (cctx->ctx_compile_type == CT_PROFILE
8663 		&& instr->ga_len > 0
8664 		&& ((isn_T *)instr->ga_data)[instr->ga_len - 1]
8665 						   .isn_type == ISN_PROF_START)
8666 	    --instr->ga_len;
8667 #endif
8668 	// Jump from end of previous block to :finally or :endtry
8669 	if (compile_jump_to_end(&scope->se_u.se_try.ts_end_label,
8670 						    JUMP_ALWAYS, cctx) == FAIL)
8671 	    return NULL;
8672 
8673 	// End :try or :catch scope: set value in ISN_TRY instruction
8674 	isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
8675 	if (isn->isn_arg.try.try_ref->try_catch == 0)
8676 	    isn->isn_arg.try.try_ref->try_catch = instr->ga_len;
8677 	if (scope->se_u.se_try.ts_catch_label != 0)
8678 	{
8679 	    // Previous catch without match jumps here
8680 	    isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_catch_label;
8681 	    isn->isn_arg.jump.jump_where = instr->ga_len;
8682 	}
8683 #ifdef FEAT_PROFILE
8684 	if (cctx->ctx_compile_type == CT_PROFILE)
8685 	{
8686 	    // a "throw" that jumps here needs to be counted
8687 	    generate_instr(cctx, ISN_PROF_END);
8688 	    // the "catch" is also counted
8689 	    generate_instr(cctx, ISN_PROF_START);
8690 	}
8691 #endif
8692 	if (cctx->ctx_compile_type == CT_DEBUG)
8693 	    generate_instr_debug(cctx);
8694     }
8695 
8696     p = skipwhite(arg);
8697     if (ends_excmd2(arg, p))
8698     {
8699 	scope->se_u.se_try.ts_caught_all = TRUE;
8700 	scope->se_u.se_try.ts_catch_label = 0;
8701     }
8702     else
8703     {
8704 	char_u *end;
8705 	char_u *pat;
8706 	char_u *tofree = NULL;
8707 	int	dropped = 0;
8708 	int	len;
8709 
8710 	// Push v:exception, push {expr} and MATCH
8711 	generate_instr_type(cctx, ISN_PUSHEXC, &t_string);
8712 
8713 	end = skip_regexp_ex(p + 1, *p, TRUE, &tofree, &dropped, NULL);
8714 	if (*end != *p)
8715 	{
8716 	    semsg(_(e_separator_mismatch_str), p);
8717 	    vim_free(tofree);
8718 	    return FAIL;
8719 	}
8720 	if (tofree == NULL)
8721 	    len = (int)(end - (p + 1));
8722 	else
8723 	    len = (int)(end - tofree);
8724 	pat = vim_strnsave(tofree == NULL ? p + 1 : tofree, len);
8725 	vim_free(tofree);
8726 	p += len + 2 + dropped;
8727 	if (pat == NULL)
8728 	    return FAIL;
8729 	if (generate_PUSHS(cctx, &pat) == FAIL)
8730 	    return FAIL;
8731 
8732 	if (generate_COMPARE(cctx, EXPR_MATCH, FALSE) == FAIL)
8733 	    return NULL;
8734 
8735 	scope->se_u.se_try.ts_catch_label = instr->ga_len;
8736 	if (generate_JUMP(cctx, JUMP_IF_FALSE, 0) == FAIL)
8737 	    return NULL;
8738     }
8739 
8740     if (cctx->ctx_skip != SKIP_YES && generate_instr(cctx, ISN_CATCH) == NULL)
8741 	return NULL;
8742 
8743     if (new_scope(cctx, BLOCK_SCOPE) == NULL)
8744 	return NULL;
8745     return p;
8746 }
8747 
8748     static char_u *
compile_finally(char_u * arg,cctx_T * cctx)8749 compile_finally(char_u *arg, cctx_T *cctx)
8750 {
8751     scope_T	*scope = cctx->ctx_scope;
8752     garray_T	*instr = &cctx->ctx_instr;
8753     isn_T	*isn;
8754     int		this_instr;
8755 
8756     if (misplaced_cmdmod(cctx))
8757 	return NULL;
8758 
8759     // end block scope from :try or :catch
8760     if (scope != NULL && scope->se_type == BLOCK_SCOPE)
8761 	compile_endblock(cctx);
8762     scope = cctx->ctx_scope;
8763 
8764     // Error if not in a :try scope
8765     if (scope == NULL || scope->se_type != TRY_SCOPE)
8766     {
8767 	emsg(_(e_finally));
8768 	return NULL;
8769     }
8770 
8771     if (cctx->ctx_skip != SKIP_YES)
8772     {
8773 	// End :catch or :finally scope: set value in ISN_TRY instruction
8774 	isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
8775 	if (isn->isn_arg.try.try_ref->try_finally != 0)
8776 	{
8777 	    emsg(_(e_finally_dup));
8778 	    return NULL;
8779 	}
8780 
8781 	this_instr = instr->ga_len;
8782 #ifdef FEAT_PROFILE
8783 	if (cctx->ctx_compile_type == CT_PROFILE
8784 		&& ((isn_T *)instr->ga_data)[this_instr - 1]
8785 						       .isn_type == ISN_PROF_START)
8786 	{
8787 	    // jump to the profile start of the "finally"
8788 	    --this_instr;
8789 
8790 	    // jump to the profile end above it
8791 	    if (this_instr > 0 && ((isn_T *)instr->ga_data)[this_instr - 1]
8792 							 .isn_type == ISN_PROF_END)
8793 		--this_instr;
8794 	}
8795 #endif
8796 
8797 	// Fill in the "end" label in jumps at the end of the blocks.
8798 	compile_fill_jump_to_end(&scope->se_u.se_try.ts_end_label,
8799 								this_instr, cctx);
8800 
8801 	// If there is no :catch then an exception jumps to :finally.
8802 	if (isn->isn_arg.try.try_ref->try_catch == 0)
8803 	    isn->isn_arg.try.try_ref->try_catch = this_instr;
8804 	isn->isn_arg.try.try_ref->try_finally = this_instr;
8805 	if (scope->se_u.se_try.ts_catch_label != 0)
8806 	{
8807 	    // Previous catch without match jumps here
8808 	    isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_catch_label;
8809 	    isn->isn_arg.jump.jump_where = this_instr;
8810 	    scope->se_u.se_try.ts_catch_label = 0;
8811 	}
8812 	if (generate_instr(cctx, ISN_FINALLY) == NULL)
8813 	    return NULL;
8814 
8815 	// TODO: set index in ts_finally_label jumps
8816     }
8817 
8818     return arg;
8819 }
8820 
8821     static char_u *
compile_endtry(char_u * arg,cctx_T * cctx)8822 compile_endtry(char_u *arg, cctx_T *cctx)
8823 {
8824     scope_T	*scope = cctx->ctx_scope;
8825     garray_T	*instr = &cctx->ctx_instr;
8826     isn_T	*try_isn;
8827 
8828     if (misplaced_cmdmod(cctx))
8829 	return NULL;
8830 
8831     // end block scope from :catch or :finally
8832     if (scope != NULL && scope->se_type == BLOCK_SCOPE)
8833 	compile_endblock(cctx);
8834     scope = cctx->ctx_scope;
8835 
8836     // Error if not in a :try scope
8837     if (scope == NULL || scope->se_type != TRY_SCOPE)
8838     {
8839 	if (scope == NULL)
8840 	    emsg(_(e_no_endtry));
8841 	else if (scope->se_type == WHILE_SCOPE)
8842 	    emsg(_(e_endwhile));
8843 	else if (scope->se_type == FOR_SCOPE)
8844 	    emsg(_(e_endfor));
8845 	else
8846 	    emsg(_(e_endif));
8847 	return NULL;
8848     }
8849 
8850     try_isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
8851     if (cctx->ctx_skip != SKIP_YES)
8852     {
8853 	if (try_isn->isn_arg.try.try_ref->try_catch == 0
8854 				      && try_isn->isn_arg.try.try_ref->try_finally == 0)
8855 	{
8856 	    emsg(_(e_missing_catch_or_finally));
8857 	    return NULL;
8858 	}
8859 
8860 #ifdef FEAT_PROFILE
8861 	if (cctx->ctx_compile_type == CT_PROFILE
8862 		&& ((isn_T *)instr->ga_data)[instr->ga_len - 1]
8863 						.isn_type == ISN_PROF_START)
8864 	    // move the profile start after "endtry" so that it's not counted when
8865 	    // the exception is rethrown.
8866 	    --instr->ga_len;
8867 #endif
8868 
8869 	// Fill in the "end" label in jumps at the end of the blocks, if not
8870 	// done by ":finally".
8871 	compile_fill_jump_to_end(&scope->se_u.se_try.ts_end_label,
8872 							  instr->ga_len, cctx);
8873 
8874 	if (scope->se_u.se_try.ts_catch_label != 0)
8875 	{
8876 	    // Last catch without match jumps here
8877 	    isn_T *isn = ((isn_T *)instr->ga_data)
8878 					   + scope->se_u.se_try.ts_catch_label;
8879 	    isn->isn_arg.jump.jump_where = instr->ga_len;
8880 	}
8881     }
8882 
8883     compile_endblock(cctx);
8884 
8885     if (cctx->ctx_skip != SKIP_YES)
8886     {
8887 	// End :catch or :finally scope: set instruction index in ISN_TRY
8888 	// instruction
8889 	try_isn->isn_arg.try.try_ref->try_endtry = instr->ga_len;
8890 	if (cctx->ctx_skip != SKIP_YES
8891 				   && generate_instr(cctx, ISN_ENDTRY) == NULL)
8892 	    return NULL;
8893 #ifdef FEAT_PROFILE
8894 	if (cctx->ctx_compile_type == CT_PROFILE)
8895 	    generate_instr(cctx, ISN_PROF_START);
8896 #endif
8897     }
8898     return arg;
8899 }
8900 
8901 /*
8902  * compile "throw {expr}"
8903  */
8904     static char_u *
compile_throw(char_u * arg,cctx_T * cctx UNUSED)8905 compile_throw(char_u *arg, cctx_T *cctx UNUSED)
8906 {
8907     char_u *p = skipwhite(arg);
8908 
8909     if (compile_expr0(&p, cctx) == FAIL)
8910 	return NULL;
8911     if (cctx->ctx_skip == SKIP_YES)
8912 	return p;
8913     if (may_generate_2STRING(-1, FALSE, cctx) == FAIL)
8914 	return NULL;
8915     if (generate_instr_drop(cctx, ISN_THROW, 1) == NULL)
8916 	return NULL;
8917 
8918     return p;
8919 }
8920 
8921     static char_u *
compile_eval(char_u * arg,cctx_T * cctx)8922 compile_eval(char_u *arg, cctx_T *cctx)
8923 {
8924     char_u	*p = arg;
8925     int		name_only;
8926     long	lnum = SOURCING_LNUM;
8927 
8928     // find_ex_command() will consider a variable name an expression, assuming
8929     // that something follows on the next line.  Check that something actually
8930     // follows, otherwise it's probably a misplaced command.
8931     name_only = cmd_is_name_only(arg);
8932 
8933     if (compile_expr0(&p, cctx) == FAIL)
8934 	return NULL;
8935 
8936     if (name_only && lnum == SOURCING_LNUM)
8937     {
8938 	semsg(_(e_expression_without_effect_str), arg);
8939 	return NULL;
8940     }
8941 
8942     // drop the result
8943     generate_instr_drop(cctx, ISN_DROP, 1);
8944 
8945     return skipwhite(p);
8946 }
8947 
8948 /*
8949  * compile "echo expr"
8950  * compile "echomsg expr"
8951  * compile "echoerr expr"
8952  * compile "echoconsole expr"
8953  * compile "execute expr"
8954  */
8955     static char_u *
compile_mult_expr(char_u * arg,int cmdidx,cctx_T * cctx)8956 compile_mult_expr(char_u *arg, int cmdidx, cctx_T *cctx)
8957 {
8958     char_u	*p = arg;
8959     char_u	*prev = arg;
8960     char_u	*expr_start;
8961     int		count = 0;
8962     int		start_ctx_lnum = cctx->ctx_lnum;
8963     garray_T	*stack = &cctx->ctx_type_stack;
8964     type_T	*type;
8965 
8966     for (;;)
8967     {
8968 	if (ends_excmd2(prev, p))
8969 	    break;
8970 	expr_start = p;
8971 	if (compile_expr0(&p, cctx) == FAIL)
8972 	    return NULL;
8973 
8974 	if (cctx->ctx_skip != SKIP_YES)
8975 	{
8976 	    // check for non-void type
8977 	    type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
8978 	    if (type->tt_type == VAR_VOID)
8979 	    {
8980 		semsg(_(e_expression_does_not_result_in_value_str), expr_start);
8981 		return NULL;
8982 	    }
8983 	}
8984 
8985 	++count;
8986 	prev = p;
8987 	p = skipwhite(p);
8988     }
8989 
8990     if (count > 0)
8991     {
8992 	long save_lnum = cctx->ctx_lnum;
8993 
8994 	// Use the line number where the command started.
8995 	cctx->ctx_lnum = start_ctx_lnum;
8996 
8997 	if (cmdidx == CMD_echo || cmdidx == CMD_echon)
8998 	    generate_ECHO(cctx, cmdidx == CMD_echo, count);
8999 	else if (cmdidx == CMD_execute)
9000 	    generate_MULT_EXPR(cctx, ISN_EXECUTE, count);
9001 	else if (cmdidx == CMD_echomsg)
9002 	    generate_MULT_EXPR(cctx, ISN_ECHOMSG, count);
9003 	else if (cmdidx == CMD_echoconsole)
9004 	    generate_MULT_EXPR(cctx, ISN_ECHOCONSOLE, count);
9005 	else
9006 	    generate_MULT_EXPR(cctx, ISN_ECHOERR, count);
9007 
9008 	cctx->ctx_lnum = save_lnum;
9009     }
9010     return p;
9011 }
9012 
9013 /*
9014  * If "eap" has a range that is not a constant generate an ISN_RANGE
9015  * instruction to compute it and return OK.
9016  * Otherwise return FAIL, the caller must deal with any range.
9017  */
9018     static int
compile_variable_range(exarg_T * eap,cctx_T * cctx)9019 compile_variable_range(exarg_T *eap, cctx_T *cctx)
9020 {
9021     char_u *range_end = skip_range(eap->cmd, TRUE, NULL);
9022     char_u *p = skipdigits(eap->cmd);
9023 
9024     if (p == range_end)
9025 	return FAIL;
9026     return generate_RANGE(cctx, vim_strnsave(eap->cmd, range_end - eap->cmd));
9027 }
9028 
9029 /*
9030  * :put r
9031  * :put ={expr}
9032  */
9033     static char_u *
compile_put(char_u * arg,exarg_T * eap,cctx_T * cctx)9034 compile_put(char_u *arg, exarg_T *eap, cctx_T *cctx)
9035 {
9036     char_u	*line = arg;
9037     linenr_T	lnum;
9038     char	*errormsg;
9039     int		above = eap->forceit;
9040 
9041     eap->regname = *line;
9042 
9043     if (eap->regname == '=')
9044     {
9045 	char_u *p = line + 1;
9046 
9047 	if (compile_expr0(&p, cctx) == FAIL)
9048 	    return NULL;
9049 	line = p;
9050     }
9051     else if (eap->regname != NUL)
9052 	++line;
9053 
9054     if (compile_variable_range(eap, cctx) == OK)
9055     {
9056 	lnum = above ? LNUM_VARIABLE_RANGE_ABOVE : LNUM_VARIABLE_RANGE;
9057     }
9058     else
9059     {
9060 	// Either no range or a number.
9061 	// "errormsg" will not be set because the range is ADDR_LINES.
9062 	if (parse_cmd_address(eap, &errormsg, FALSE) == FAIL)
9063 	    // cannot happen
9064 	    return NULL;
9065 	if (eap->addr_count == 0)
9066 	    lnum = -1;
9067 	else
9068 	    lnum = eap->line2;
9069 	if (above)
9070 	    --lnum;
9071     }
9072 
9073     generate_PUT(cctx, eap->regname, lnum);
9074     return line;
9075 }
9076 
9077 /*
9078  * A command that is not compiled, execute with legacy code.
9079  */
9080     static char_u *
compile_exec(char_u * line_arg,exarg_T * eap,cctx_T * cctx)9081 compile_exec(char_u *line_arg, exarg_T *eap, cctx_T *cctx)
9082 {
9083     char_u	*line = line_arg;
9084     char_u	*p;
9085     int		has_expr = FALSE;
9086     char_u	*nextcmd = (char_u *)"";
9087     char_u	*tofree = NULL;
9088 
9089     if (cctx->ctx_skip == SKIP_YES)
9090 	goto theend;
9091 
9092     // If there was a prececing command modifier, drop it and include it in the
9093     // EXEC command.
9094     if (cctx->ctx_has_cmdmod)
9095     {
9096 	garray_T	*instr = &cctx->ctx_instr;
9097 	isn_T		*isn = ((isn_T *)instr->ga_data) + instr->ga_len - 1;
9098 
9099 	if (isn->isn_type == ISN_CMDMOD)
9100 	{
9101 	    vim_regfree(isn->isn_arg.cmdmod.cf_cmdmod
9102 					       ->cmod_filter_regmatch.regprog);
9103 	    vim_free(isn->isn_arg.cmdmod.cf_cmdmod);
9104 	    --instr->ga_len;
9105 	    cctx->ctx_has_cmdmod = FALSE;
9106 	}
9107     }
9108 
9109     if (eap->cmdidx >= 0 && eap->cmdidx < CMD_SIZE)
9110     {
9111 	long	argt = eap->argt;
9112 	int	usefilter = FALSE;
9113 
9114 	has_expr = argt & (EX_XFILE | EX_EXPAND);
9115 
9116 	// If the command can be followed by a bar, find the bar and truncate
9117 	// it, so that the following command can be compiled.
9118 	// The '|' is overwritten with a NUL, it is put back below.
9119 	if ((eap->cmdidx == CMD_write || eap->cmdidx == CMD_read)
9120 							   && *eap->arg == '!')
9121 	    // :w !filter or :r !filter or :r! filter
9122 	    usefilter = TRUE;
9123 	if ((argt & EX_TRLBAR) && !usefilter)
9124 	{
9125 	    eap->argt = argt;
9126 	    separate_nextcmd(eap);
9127 	    if (eap->nextcmd != NULL)
9128 		nextcmd = eap->nextcmd;
9129 	}
9130 	else if (eap->cmdidx == CMD_wincmd)
9131 	{
9132 	    p = eap->arg;
9133 	    if (*p != NUL)
9134 		++p;
9135 	    if (*p == 'g' || *p == Ctrl_G)
9136 		++p;
9137 	    p = skipwhite(p);
9138 	    if (*p == '|')
9139 	    {
9140 		*p = NUL;
9141 		nextcmd = p + 1;
9142 	    }
9143 	}
9144 	else if (eap->cmdidx == CMD_command || eap->cmdidx == CMD_autocmd)
9145 	{
9146 	    // If there is a trailing '{' read lines until the '}'
9147 	    p = eap->arg + STRLEN(eap->arg) - 1;
9148 	    while (p > eap->arg && VIM_ISWHITE(*p))
9149 		--p;
9150 	    if (*p == '{')
9151 	    {
9152 		exarg_T ea;
9153 		int	flags;  // unused
9154 		int	start_lnum = SOURCING_LNUM;
9155 
9156 		CLEAR_FIELD(ea);
9157 		ea.arg = eap->arg;
9158 		fill_exarg_from_cctx(&ea, cctx);
9159 		(void)may_get_cmd_block(&ea, p, &tofree, &flags);
9160 		if (tofree != NULL)
9161 		{
9162 		    *p = NUL;
9163 		    line = concat_str(line, tofree);
9164 		    if (line == NULL)
9165 			goto theend;
9166 		    vim_free(tofree);
9167 		    tofree = line;
9168 		    SOURCING_LNUM = start_lnum;
9169 		}
9170 	    }
9171 	}
9172     }
9173 
9174     if (eap->cmdidx == CMD_syntax && STRNCMP(eap->arg, "include ", 8) == 0)
9175     {
9176 	// expand filename in "syntax include [@group] filename"
9177 	has_expr = TRUE;
9178 	eap->arg = skipwhite(eap->arg + 7);
9179 	if (*eap->arg == '@')
9180 	    eap->arg = skiptowhite(eap->arg);
9181     }
9182 
9183     if ((eap->cmdidx == CMD_global || eap->cmdidx == CMD_vglobal)
9184 						       && STRLEN(eap->arg) > 4)
9185     {
9186 	int delim = *eap->arg;
9187 
9188 	p = skip_regexp_ex(eap->arg + 1, delim, TRUE, NULL, NULL, NULL);
9189 	if (*p == delim)
9190 	{
9191 	    eap->arg = p + 1;
9192 	    has_expr = TRUE;
9193 	}
9194     }
9195 
9196     if (eap->cmdidx == CMD_folddoopen || eap->cmdidx == CMD_folddoclosed)
9197     {
9198 	// TODO: should only expand when appropriate for the command
9199 	eap->arg = skiptowhite(eap->arg);
9200 	has_expr = TRUE;
9201     }
9202 
9203     if (has_expr && (p = (char_u *)strstr((char *)eap->arg, "`=")) != NULL)
9204     {
9205 	int	count = 0;
9206 	char_u	*start = skipwhite(line);
9207 
9208 	// :cmd xxx`=expr1`yyy`=expr2`zzz
9209 	// PUSHS ":cmd xxx"
9210 	// eval expr1
9211 	// PUSHS "yyy"
9212 	// eval expr2
9213 	// PUSHS "zzz"
9214 	// EXECCONCAT 5
9215 	for (;;)
9216 	{
9217 	    if (p > start)
9218 	    {
9219 		char_u *val = vim_strnsave(start, p - start);
9220 
9221 		generate_PUSHS(cctx, &val);
9222 		++count;
9223 	    }
9224 	    p += 2;
9225 	    if (compile_expr0(&p, cctx) == FAIL)
9226 		return NULL;
9227 	    may_generate_2STRING(-1, TRUE, cctx);
9228 	    ++count;
9229 	    p = skipwhite(p);
9230 	    if (*p != '`')
9231 	    {
9232 		emsg(_(e_missing_backtick));
9233 		return NULL;
9234 	    }
9235 	    start = p + 1;
9236 
9237 	    p = (char_u *)strstr((char *)start, "`=");
9238 	    if (p == NULL)
9239 	    {
9240 		if (*skipwhite(start) != NUL)
9241 		{
9242 		    char_u *val = vim_strsave(start);
9243 
9244 		    generate_PUSHS(cctx, &val);
9245 		    ++count;
9246 		}
9247 		break;
9248 	    }
9249 	}
9250 	generate_EXECCONCAT(cctx, count);
9251     }
9252     else
9253 	generate_EXEC(cctx, ISN_EXEC, line);
9254 
9255 theend:
9256     if (*nextcmd != NUL)
9257     {
9258 	// the parser expects a pointer to the bar, put it back
9259 	--nextcmd;
9260 	*nextcmd = '|';
9261     }
9262     vim_free(tofree);
9263 
9264     return nextcmd;
9265 }
9266 
9267 /*
9268  * A script command with heredoc, e.g.
9269  *	ruby << EOF
9270  *	   command
9271  *	EOF
9272  * Has been turned into one long line with NL characters by
9273  * get_function_body():
9274  *	ruby << EOF<NL>   command<NL>EOF
9275  */
9276     static char_u *
compile_script(char_u * line,cctx_T * cctx)9277 compile_script(char_u *line, cctx_T *cctx)
9278 {
9279     if (cctx->ctx_skip != SKIP_YES)
9280     {
9281 	isn_T	*isn;
9282 
9283 	if ((isn = generate_instr(cctx, ISN_EXEC_SPLIT)) == NULL)
9284 	    return NULL;
9285 	isn->isn_arg.string = vim_strsave(line);
9286     }
9287     return (char_u *)"";
9288 }
9289 
9290 
9291 /*
9292  * :s/pat/repl/
9293  */
9294     static char_u *
compile_substitute(char_u * arg,exarg_T * eap,cctx_T * cctx)9295 compile_substitute(char_u *arg, exarg_T *eap, cctx_T *cctx)
9296 {
9297     char_u  *cmd = eap->arg;
9298     char_u  *expr = (char_u *)strstr((char *)cmd, "\\=");
9299 
9300     if (expr != NULL)
9301     {
9302 	int delimiter = *cmd++;
9303 
9304 	// There is a \=expr, find it in the substitute part.
9305 	cmd = skip_regexp_ex(cmd, delimiter, magic_isset(), NULL, NULL, NULL);
9306 	if (cmd[0] == delimiter && cmd[1] == '\\' && cmd[2] == '=')
9307 	{
9308 	    garray_T	save_ga = cctx->ctx_instr;
9309 	    char_u	*end;
9310 	    int		expr_res;
9311 	    int		trailing_error;
9312 	    int		instr_count;
9313 	    isn_T	*instr;
9314 	    isn_T	*isn;
9315 
9316 	    cmd += 3;
9317 	    end = skip_substitute(cmd, delimiter);
9318 
9319 	    // Temporarily reset the list of instructions so that the jump
9320 	    // labels are correct.
9321 	    cctx->ctx_instr.ga_len = 0;
9322 	    cctx->ctx_instr.ga_maxlen = 0;
9323 	    cctx->ctx_instr.ga_data = NULL;
9324 	    expr_res = compile_expr0(&cmd, cctx);
9325 	    if (end[-1] == NUL)
9326 		end[-1] = delimiter;
9327 	    cmd = skipwhite(cmd);
9328 	    trailing_error = *cmd != delimiter && *cmd != NUL;
9329 
9330 	    if (expr_res == FAIL || trailing_error
9331 				       || GA_GROW_FAILS(&cctx->ctx_instr, 1))
9332 	    {
9333 		if (trailing_error)
9334 		    semsg(_(e_trailing_arg), cmd);
9335 		clear_instr_ga(&cctx->ctx_instr);
9336 		cctx->ctx_instr = save_ga;
9337 		return NULL;
9338 	    }
9339 
9340 	    // Move the generated instructions into the ISN_SUBSTITUTE
9341 	    // instructions, then restore the list of instructions before
9342 	    // adding the ISN_SUBSTITUTE instruction.
9343 	    instr_count = cctx->ctx_instr.ga_len;
9344 	    instr = cctx->ctx_instr.ga_data;
9345 	    instr[instr_count].isn_type = ISN_FINISH;
9346 
9347 	    cctx->ctx_instr = save_ga;
9348 	    if ((isn = generate_instr(cctx, ISN_SUBSTITUTE)) == NULL)
9349 	    {
9350 		int idx;
9351 
9352 		for (idx = 0; idx < instr_count; ++idx)
9353 		    delete_instr(instr + idx);
9354 		vim_free(instr);
9355 		return NULL;
9356 	    }
9357 	    isn->isn_arg.subs.subs_cmd = vim_strsave(arg);
9358 	    isn->isn_arg.subs.subs_instr = instr;
9359 
9360 	    // skip over flags
9361 	    if (*end == '&')
9362 		++end;
9363 	    while (ASCII_ISALPHA(*end) || *end == '#')
9364 		++end;
9365 	    return end;
9366 	}
9367     }
9368 
9369     return compile_exec(arg, eap, cctx);
9370 }
9371 
9372     static char_u *
compile_redir(char_u * line,exarg_T * eap,cctx_T * cctx)9373 compile_redir(char_u *line, exarg_T *eap, cctx_T *cctx)
9374 {
9375     char_u *arg = eap->arg;
9376     lhs_T	*lhs = &cctx->ctx_redir_lhs;
9377 
9378     if (lhs->lhs_name != NULL)
9379     {
9380 	if (STRNCMP(arg, "END", 3) == 0)
9381 	{
9382 	    if (lhs->lhs_append)
9383 	    {
9384 		// First load the current variable value.
9385 		if (compile_load_lhs_with_index(lhs, lhs->lhs_whole,
9386 								 cctx) == FAIL)
9387 		    return NULL;
9388 	    }
9389 
9390 	    // Gets the redirected text and put it on the stack, then store it
9391 	    // in the variable.
9392 	    generate_instr_type(cctx, ISN_REDIREND, &t_string);
9393 
9394 	    if (lhs->lhs_append)
9395 		generate_instr_drop(cctx, ISN_CONCAT, 1);
9396 
9397 	    if (lhs->lhs_has_index)
9398 	    {
9399 		// Use the info in "lhs" to store the value at the index in the
9400 		// list or dict.
9401 		if (compile_assign_unlet(lhs->lhs_whole, lhs, TRUE,
9402 						      &t_string, cctx) == FAIL)
9403 		    return NULL;
9404 	    }
9405 	    else if (generate_store_lhs(cctx, lhs, -1) == FAIL)
9406 		return NULL;
9407 
9408 	    VIM_CLEAR(lhs->lhs_name);
9409 	    VIM_CLEAR(lhs->lhs_whole);
9410 	    return arg + 3;
9411 	}
9412 	emsg(_(e_cannot_nest_redir));
9413 	return NULL;
9414     }
9415 
9416     if (arg[0] == '=' && arg[1] == '>')
9417     {
9418 	int	    append = FALSE;
9419 
9420 	// redirect to a variable is compiled
9421 	arg += 2;
9422 	if (*arg == '>')
9423 	{
9424 	    ++arg;
9425 	    append = TRUE;
9426 	}
9427 	arg = skipwhite(arg);
9428 
9429 	if (compile_assign_lhs(arg, lhs, CMD_redir,
9430 						FALSE, FALSE, 1, cctx) == FAIL)
9431 	    return NULL;
9432 	generate_instr(cctx, ISN_REDIRSTART);
9433 	lhs->lhs_append = append;
9434 	if (lhs->lhs_has_index)
9435 	{
9436 	    lhs->lhs_whole = vim_strnsave(arg, lhs->lhs_varlen_total);
9437 	    if (lhs->lhs_whole == NULL)
9438 		return NULL;
9439 	}
9440 
9441 	return arg + lhs->lhs_varlen_total;
9442     }
9443 
9444     // other redirects are handled like at script level
9445     return compile_exec(line, eap, cctx);
9446 }
9447 
9448 #ifdef FEAT_QUICKFIX
9449     static char_u *
compile_cexpr(char_u * line,exarg_T * eap,cctx_T * cctx)9450 compile_cexpr(char_u *line, exarg_T *eap, cctx_T *cctx)
9451 {
9452     isn_T	*isn;
9453     char_u	*p;
9454 
9455     isn = generate_instr(cctx, ISN_CEXPR_AUCMD);
9456     if (isn == NULL)
9457 	return NULL;
9458     isn->isn_arg.number = eap->cmdidx;
9459 
9460     p = eap->arg;
9461     if (compile_expr0(&p, cctx) == FAIL)
9462 	return NULL;
9463 
9464     isn = generate_instr(cctx, ISN_CEXPR_CORE);
9465     if (isn == NULL)
9466 	return NULL;
9467     isn->isn_arg.cexpr.cexpr_ref = ALLOC_ONE(cexprref_T);
9468     if (isn->isn_arg.cexpr.cexpr_ref == NULL)
9469 	return NULL;
9470     isn->isn_arg.cexpr.cexpr_ref->cer_cmdidx = eap->cmdidx;
9471     isn->isn_arg.cexpr.cexpr_ref->cer_forceit = eap->forceit;
9472     isn->isn_arg.cexpr.cexpr_ref->cer_cmdline = vim_strsave(skipwhite(line));
9473 
9474     return p;
9475 }
9476 #endif
9477 
9478 /*
9479  * Check if the separator for a :global or :substitute command is OK.
9480  */
9481     int
check_global_and_subst(char_u * cmd,char_u * arg)9482 check_global_and_subst(char_u *cmd, char_u *arg)
9483 {
9484     if (arg == cmd + 1 && vim_strchr((char_u *)":-.", *arg) != NULL)
9485     {
9486 	semsg(_(e_separator_not_supported_str), arg);
9487 	return FAIL;
9488     }
9489     if (VIM_ISWHITE(cmd[1]))
9490     {
9491 	semsg(_(e_no_white_space_allowed_before_separator_str), cmd);
9492 	return FAIL;
9493     }
9494     return OK;
9495 }
9496 
9497 
9498 /*
9499  * Add a function to the list of :def functions.
9500  * This sets "ufunc->uf_dfunc_idx" but the function isn't compiled yet.
9501  */
9502     static int
add_def_function(ufunc_T * ufunc)9503 add_def_function(ufunc_T *ufunc)
9504 {
9505     dfunc_T *dfunc;
9506 
9507     if (def_functions.ga_len == 0)
9508     {
9509 	// The first position is not used, so that a zero uf_dfunc_idx means it
9510 	// wasn't set.
9511 	if (GA_GROW_FAILS(&def_functions, 1))
9512 	    return FAIL;
9513 	++def_functions.ga_len;
9514     }
9515 
9516     // Add the function to "def_functions".
9517     if (GA_GROW_FAILS(&def_functions, 1))
9518 	return FAIL;
9519     dfunc = ((dfunc_T *)def_functions.ga_data) + def_functions.ga_len;
9520     CLEAR_POINTER(dfunc);
9521     dfunc->df_idx = def_functions.ga_len;
9522     ufunc->uf_dfunc_idx = dfunc->df_idx;
9523     dfunc->df_ufunc = ufunc;
9524     dfunc->df_name = vim_strsave(ufunc->uf_name);
9525     ga_init2(&dfunc->df_var_names, sizeof(char_u *), 10);
9526     ++dfunc->df_refcount;
9527     ++def_functions.ga_len;
9528     return OK;
9529 }
9530 
9531 /*
9532  * After ex_function() has collected all the function lines: parse and compile
9533  * the lines into instructions.
9534  * Adds the function to "def_functions".
9535  * When "check_return_type" is set then set ufunc->uf_ret_type to the type of
9536  * the return statement (used for lambda).  When uf_ret_type is already set
9537  * then check that it matches.
9538  * When "profiling" is true add ISN_PROF_START instructions.
9539  * "outer_cctx" is set for a nested function.
9540  * This can be used recursively through compile_lambda(), which may reallocate
9541  * "def_functions".
9542  * Returns OK or FAIL.
9543  */
9544     int
compile_def_function(ufunc_T * ufunc,int check_return_type,compiletype_T compile_type,cctx_T * outer_cctx)9545 compile_def_function(
9546 	ufunc_T		*ufunc,
9547 	int		check_return_type,
9548 	compiletype_T   compile_type,
9549 	cctx_T		*outer_cctx)
9550 {
9551     char_u	*line = NULL;
9552     char_u	*line_to_free = NULL;
9553     char_u	*p;
9554     char	*errormsg = NULL;	// error message
9555     cctx_T	cctx;
9556     garray_T	*instr;
9557     int		did_emsg_before = did_emsg;
9558     int		did_emsg_silent_before = did_emsg_silent;
9559     int		ret = FAIL;
9560     sctx_T	save_current_sctx = current_sctx;
9561     int		save_estack_compiling = estack_compiling;
9562     int		save_cmod_flags = cmdmod.cmod_flags;
9563     int		do_estack_push;
9564     int		new_def_function = FALSE;
9565 #ifdef FEAT_PROFILE
9566     int		prof_lnum = -1;
9567 #endif
9568     int		debug_lnum = -1;
9569 
9570     // When using a function that was compiled before: Free old instructions.
9571     // The index is reused.  Otherwise add a new entry in "def_functions".
9572     if (ufunc->uf_dfunc_idx > 0)
9573     {
9574 	dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
9575 							 + ufunc->uf_dfunc_idx;
9576 	isn_T	*instr_dest = NULL;
9577 
9578 	switch (compile_type)
9579 	{
9580 	    case CT_PROFILE:
9581 #ifdef FEAT_PROFILE
9582 			    instr_dest = dfunc->df_instr_prof; break;
9583 #endif
9584 	    case CT_NONE:   instr_dest = dfunc->df_instr; break;
9585 	    case CT_DEBUG:  instr_dest = dfunc->df_instr_debug; break;
9586 	}
9587 	if (instr_dest != NULL)
9588 	    // Was compiled in this mode before: Free old instructions.
9589 	    delete_def_function_contents(dfunc, FALSE);
9590 	ga_clear_strings(&dfunc->df_var_names);
9591     }
9592     else
9593     {
9594 	if (add_def_function(ufunc) == FAIL)
9595 	    return FAIL;
9596 	new_def_function = TRUE;
9597     }
9598 
9599     ufunc->uf_def_status = UF_COMPILING;
9600 
9601     CLEAR_FIELD(cctx);
9602 
9603     cctx.ctx_compile_type = compile_type;
9604     cctx.ctx_ufunc = ufunc;
9605     cctx.ctx_lnum = -1;
9606     cctx.ctx_outer = outer_cctx;
9607     ga_init2(&cctx.ctx_locals, sizeof(lvar_T), 10);
9608     ga_init2(&cctx.ctx_type_stack, sizeof(type_T *), 50);
9609     ga_init2(&cctx.ctx_imports, sizeof(imported_T), 10);
9610     cctx.ctx_type_list = &ufunc->uf_type_list;
9611     ga_init2(&cctx.ctx_instr, sizeof(isn_T), 50);
9612     instr = &cctx.ctx_instr;
9613 
9614     // Set the context to the function, it may be compiled when called from
9615     // another script.  Set the script version to the most modern one.
9616     // The line number will be set in next_line_from_context().
9617     current_sctx = ufunc->uf_script_ctx;
9618     current_sctx.sc_version = SCRIPT_VERSION_VIM9;
9619 
9620     // Don't use the flag from ":legacy" here.
9621     cmdmod.cmod_flags &= ~CMOD_LEGACY;
9622 
9623     // Make sure error messages are OK.
9624     do_estack_push = !estack_top_is_ufunc(ufunc, 1);
9625     if (do_estack_push)
9626 	estack_push_ufunc(ufunc, 1);
9627     estack_compiling = TRUE;
9628 
9629     if (ufunc->uf_def_args.ga_len > 0)
9630     {
9631 	int	count = ufunc->uf_def_args.ga_len;
9632 	int	first_def_arg = ufunc->uf_args.ga_len - count;
9633 	int	i;
9634 	char_u	*arg;
9635 	int	off = STACK_FRAME_SIZE + (ufunc->uf_va_name != NULL ? 1 : 0);
9636 	int	did_set_arg_type = FALSE;
9637 
9638 	// Produce instructions for the default values of optional arguments.
9639 	SOURCING_LNUM = 0;  // line number unknown
9640 	for (i = 0; i < count; ++i)
9641 	{
9642 	    garray_T	*stack = &cctx.ctx_type_stack;
9643 	    type_T	*val_type;
9644 	    int		arg_idx = first_def_arg + i;
9645 	    where_T	where = WHERE_INIT;
9646 	    int		r;
9647 	    int		jump_instr_idx = instr->ga_len;
9648 	    isn_T	*isn;
9649 
9650 	    // Use a JUMP_IF_ARG_SET instruction to skip if the value was given.
9651 	    if (generate_JUMP_IF_ARG_SET(&cctx, i - count - off) == FAIL)
9652 		goto erret;
9653 
9654 	    // Make sure later arguments are not found.
9655 	    ufunc->uf_args_visible = arg_idx;
9656 
9657 	    arg = ((char_u **)(ufunc->uf_def_args.ga_data))[i];
9658 	    r = compile_expr0(&arg, &cctx);
9659 
9660 	    if (r == FAIL)
9661 		goto erret;
9662 
9663 	    // If no type specified use the type of the default value.
9664 	    // Otherwise check that the default value type matches the
9665 	    // specified type.
9666 	    val_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
9667 	    where.wt_index = arg_idx + 1;
9668 	    if (ufunc->uf_arg_types[arg_idx] == &t_unknown)
9669 	    {
9670 		did_set_arg_type = TRUE;
9671 		ufunc->uf_arg_types[arg_idx] = val_type;
9672 	    }
9673 	    else if (check_type(ufunc->uf_arg_types[arg_idx], val_type,
9674 							  TRUE, where) == FAIL)
9675 		goto erret;
9676 
9677 	    if (generate_STORE(&cctx, ISN_STORE, i - count - off, NULL) == FAIL)
9678 		goto erret;
9679 
9680 	    // set instruction index in JUMP_IF_ARG_SET to here
9681 	    isn = ((isn_T *)instr->ga_data) + jump_instr_idx;
9682 	    isn->isn_arg.jumparg.jump_where = instr->ga_len;
9683 	}
9684 
9685 	if (did_set_arg_type)
9686 	    set_function_type(ufunc);
9687     }
9688     ufunc->uf_args_visible = ufunc->uf_args.ga_len;
9689 
9690     /*
9691      * Loop over all the lines of the function and generate instructions.
9692      */
9693     for (;;)
9694     {
9695 	exarg_T	    ea;
9696 	int	    starts_with_colon = FALSE;
9697 	char_u	    *cmd;
9698 	cmdmod_T    local_cmdmod;
9699 
9700 	// Bail out on the first error to avoid a flood of errors and report
9701 	// the right line number when inside try/catch.
9702 	if (did_emsg_before != did_emsg)
9703 	    goto erret;
9704 
9705 	if (line != NULL && *line == '|')
9706 	    // the line continues after a '|'
9707 	    ++line;
9708 	else if (line != NULL && *skipwhite(line) != NUL
9709 		&& !(*line == '#' && (line == cctx.ctx_line_start
9710 						    || VIM_ISWHITE(line[-1]))))
9711 	{
9712 	    semsg(_(e_trailing_arg), line);
9713 	    goto erret;
9714 	}
9715 	else if (line != NULL && vim9_bad_comment(skipwhite(line)))
9716 	    goto erret;
9717 	else
9718 	{
9719 	    line = next_line_from_context(&cctx, FALSE);
9720 	    if (cctx.ctx_lnum >= ufunc->uf_lines.ga_len)
9721 	    {
9722 		// beyond the last line
9723 #ifdef FEAT_PROFILE
9724 		if (cctx.ctx_skip != SKIP_YES)
9725 		    may_generate_prof_end(&cctx, prof_lnum);
9726 #endif
9727 		break;
9728 	    }
9729 	    // Make a copy, splitting off nextcmd and removing trailing spaces
9730 	    // may change it.
9731 	    if (line != NULL)
9732 	    {
9733 		line = vim_strsave(line);
9734 		vim_free(line_to_free);
9735 		line_to_free = line;
9736 	    }
9737 	}
9738 
9739 	CLEAR_FIELD(ea);
9740 	ea.cmdlinep = &line;
9741 	ea.cmd = skipwhite(line);
9742 
9743 	if (*ea.cmd == '#')
9744 	{
9745 	    // "#" starts a comment
9746 	    line = (char_u *)"";
9747 	    continue;
9748 	}
9749 
9750 #ifdef FEAT_PROFILE
9751 	if (cctx.ctx_compile_type == CT_PROFILE && cctx.ctx_lnum != prof_lnum
9752 						  && cctx.ctx_skip != SKIP_YES)
9753 	{
9754 	    may_generate_prof_end(&cctx, prof_lnum);
9755 
9756 	    prof_lnum = cctx.ctx_lnum;
9757 	    generate_instr(&cctx, ISN_PROF_START);
9758 	}
9759 #endif
9760 	if (cctx.ctx_compile_type == CT_DEBUG && cctx.ctx_lnum != debug_lnum
9761 						  && cctx.ctx_skip != SKIP_YES)
9762 	{
9763 	    debug_lnum = cctx.ctx_lnum;
9764 	    generate_instr_debug(&cctx);
9765 	}
9766 	cctx.ctx_prev_lnum = cctx.ctx_lnum + 1;
9767 
9768 	// Some things can be recognized by the first character.
9769 	switch (*ea.cmd)
9770 	{
9771 	    case '}':
9772 		{
9773 		    // "}" ends a block scope
9774 		    scopetype_T stype = cctx.ctx_scope == NULL
9775 					  ? NO_SCOPE : cctx.ctx_scope->se_type;
9776 
9777 		    if (stype == BLOCK_SCOPE)
9778 		    {
9779 			compile_endblock(&cctx);
9780 			line = ea.cmd;
9781 		    }
9782 		    else
9783 		    {
9784 			emsg(_(e_using_rcurly_outside_if_block_scope));
9785 			goto erret;
9786 		    }
9787 		    if (line != NULL)
9788 			line = skipwhite(ea.cmd + 1);
9789 		    continue;
9790 		}
9791 
9792 	    case '{':
9793 		// "{" starts a block scope
9794 		// "{'a': 1}->func() is something else
9795 		if (ends_excmd(*skipwhite(ea.cmd + 1)))
9796 		{
9797 		    line = compile_block(ea.cmd, &cctx);
9798 		    continue;
9799 		}
9800 		break;
9801 	}
9802 
9803 	/*
9804 	 * COMMAND MODIFIERS
9805 	 */
9806 	cctx.ctx_has_cmdmod = FALSE;
9807 	if (parse_command_modifiers(&ea, &errormsg, &local_cmdmod, FALSE)
9808 								       == FAIL)
9809 	{
9810 	    if (errormsg != NULL)
9811 		goto erret;
9812 	    // empty line or comment
9813 	    line = (char_u *)"";
9814 	    continue;
9815 	}
9816 	generate_cmdmods(&cctx, &local_cmdmod);
9817 	undo_cmdmod(&local_cmdmod);
9818 
9819 	// Check if there was a colon after the last command modifier or before
9820 	// the current position.
9821 	for (p = ea.cmd; p >= line; --p)
9822 	{
9823 	    if (*p == ':')
9824 		starts_with_colon = TRUE;
9825 	    if (p < ea.cmd && !VIM_ISWHITE(*p))
9826 		break;
9827 	}
9828 
9829 	// Skip ":call" to get to the function name, unless using :legacy
9830 	p = ea.cmd;
9831 	if (!(local_cmdmod.cmod_flags & CMOD_LEGACY))
9832 	{
9833 	    if (checkforcmd(&ea.cmd, "call", 3))
9834 	    {
9835 		if (*ea.cmd == '(')
9836 		    // not for "call()"
9837 		    ea.cmd = p;
9838 		else
9839 		    ea.cmd = skipwhite(ea.cmd);
9840 	    }
9841 
9842 	    if (!starts_with_colon)
9843 	    {
9844 		int	    assign;
9845 
9846 		// Check for assignment after command modifiers.
9847 		assign = may_compile_assignment(&ea, &line, &cctx);
9848 		if (assign == OK)
9849 		    goto nextline;
9850 		if (assign == FAIL)
9851 		    goto erret;
9852 	    }
9853 	}
9854 
9855 	/*
9856 	 * COMMAND after range
9857 	 * 'text'->func() should not be confused with 'a mark
9858 	 * "++nr" and "--nr" are eval commands
9859 	 * in "$ENV->func()" the "$" is not a range
9860 	 */
9861 	cmd = ea.cmd;
9862 	if (!(local_cmdmod.cmod_flags & CMOD_LEGACY)
9863 		&& (*cmd != '$' || starts_with_colon)
9864 		&& (starts_with_colon || !(*cmd == '\''
9865 		       || (cmd[0] == cmd[1] && (*cmd == '+' || *cmd == '-')))))
9866 	{
9867 	    ea.cmd = skip_range(ea.cmd, TRUE, NULL);
9868 	    if (ea.cmd > cmd)
9869 	    {
9870 		if (!starts_with_colon)
9871 		{
9872 		    semsg(_(e_colon_required_before_range_str), cmd);
9873 		    goto erret;
9874 		}
9875 		ea.addr_count = 1;
9876 		if (ends_excmd2(line, ea.cmd))
9877 		{
9878 		    // A range without a command: jump to the line.
9879 		    // TODO: compile to a more efficient command, possibly
9880 		    // calling parse_cmd_address().
9881 		    ea.cmdidx = CMD_SIZE;
9882 		    line = compile_exec(line, &ea, &cctx);
9883 		    goto nextline;
9884 		}
9885 	    }
9886 	}
9887 	p = find_ex_command(&ea, NULL,
9888 		starts_with_colon || (local_cmdmod.cmod_flags & CMOD_LEGACY)
9889 						  ? NULL : item_exists, &cctx);
9890 
9891 	if (p == NULL)
9892 	{
9893 	    if (cctx.ctx_skip != SKIP_YES)
9894 		emsg(_(e_ambiguous_use_of_user_defined_command));
9895 	    goto erret;
9896 	}
9897 
9898 	// When using ":legacy cmd" always use compile_exec().
9899 	if (local_cmdmod.cmod_flags & CMOD_LEGACY)
9900 	{
9901 	    char_u *start = ea.cmd;
9902 
9903 	    switch (ea.cmdidx)
9904 	    {
9905 		case CMD_if:
9906 		case CMD_elseif:
9907 		case CMD_else:
9908 		case CMD_endif:
9909 		case CMD_for:
9910 		case CMD_endfor:
9911 		case CMD_continue:
9912 		case CMD_break:
9913 		case CMD_while:
9914 		case CMD_endwhile:
9915 		case CMD_try:
9916 		case CMD_catch:
9917 		case CMD_finally:
9918 		case CMD_endtry:
9919 			semsg(_(e_cannot_use_legacy_with_command_str), ea.cmd);
9920 			goto erret;
9921 		default: break;
9922 	    }
9923 
9924 	    // ":legacy return expr" needs to be handled differently.
9925 	    if (checkforcmd(&start, "return", 4))
9926 		ea.cmdidx = CMD_return;
9927 	    else
9928 		ea.cmdidx = CMD_legacy;
9929 	}
9930 
9931 	if (p == ea.cmd && ea.cmdidx != CMD_SIZE)
9932 	{
9933 	    if (cctx.ctx_skip == SKIP_YES && ea.cmdidx != CMD_eval)
9934 	    {
9935 		line += STRLEN(line);
9936 		goto nextline;
9937 	    }
9938 	    else if (ea.cmdidx != CMD_eval)
9939 	    {
9940 		// CMD_var cannot happen, compile_assignment() above would be
9941 		// used.  Most likely an assignment to a non-existing variable.
9942 		semsg(_(e_command_not_recognized_str), ea.cmd);
9943 		goto erret;
9944 	    }
9945 	}
9946 
9947 	if (cctx.ctx_had_return
9948 		&& ea.cmdidx != CMD_elseif
9949 		&& ea.cmdidx != CMD_else
9950 		&& ea.cmdidx != CMD_endif
9951 		&& ea.cmdidx != CMD_endfor
9952 		&& ea.cmdidx != CMD_endwhile
9953 		&& ea.cmdidx != CMD_catch
9954 		&& ea.cmdidx != CMD_finally
9955 		&& ea.cmdidx != CMD_endtry)
9956 	{
9957 	    emsg(_(e_unreachable_code_after_return));
9958 	    goto erret;
9959 	}
9960 
9961 	p = skipwhite(p);
9962 	if (ea.cmdidx != CMD_SIZE
9963 			    && ea.cmdidx != CMD_write && ea.cmdidx != CMD_read)
9964 	{
9965 	    if (ea.cmdidx >= 0)
9966 		ea.argt = excmd_get_argt(ea.cmdidx);
9967 	    if ((ea.argt & EX_BANG) && *p == '!')
9968 	    {
9969 		ea.forceit = TRUE;
9970 		p = skipwhite(p + 1);
9971 	    }
9972 	}
9973 
9974 	switch (ea.cmdidx)
9975 	{
9976 	    case CMD_def:
9977 		    ea.arg = p;
9978 		    line = compile_nested_function(&ea, &cctx);
9979 		    break;
9980 
9981 	    case CMD_function:
9982 		    // TODO: should we allow this, e.g. to declare a global
9983 		    // function?
9984 		    emsg(_(e_cannot_use_function_inside_def));
9985 		    goto erret;
9986 
9987 	    case CMD_return:
9988 		    line = compile_return(p, check_return_type,
9989 				 local_cmdmod.cmod_flags & CMOD_LEGACY, &cctx);
9990 		    cctx.ctx_had_return = TRUE;
9991 		    break;
9992 
9993 	    case CMD_let:
9994 		    emsg(_(e_cannot_use_let_in_vim9_script));
9995 		    break;
9996 	    case CMD_var:
9997 	    case CMD_final:
9998 	    case CMD_const:
9999 	    case CMD_increment:
10000 	    case CMD_decrement:
10001 		    line = compile_assignment(p, &ea, ea.cmdidx, &cctx);
10002 		    if (line == p)
10003 			line = NULL;
10004 		    break;
10005 
10006 	    case CMD_unlet:
10007 	    case CMD_unlockvar:
10008 	    case CMD_lockvar:
10009 		    line = compile_unletlock(p, &ea, &cctx);
10010 		    break;
10011 
10012 	    case CMD_import:
10013 		    emsg(_(e_import_can_only_be_used_in_script));
10014 		    line = NULL;
10015 		    break;
10016 
10017 	    case CMD_if:
10018 		    line = compile_if(p, &cctx);
10019 		    break;
10020 	    case CMD_elseif:
10021 		    line = compile_elseif(p, &cctx);
10022 		    cctx.ctx_had_return = FALSE;
10023 		    break;
10024 	    case CMD_else:
10025 		    line = compile_else(p, &cctx);
10026 		    cctx.ctx_had_return = FALSE;
10027 		    break;
10028 	    case CMD_endif:
10029 		    line = compile_endif(p, &cctx);
10030 		    break;
10031 
10032 	    case CMD_while:
10033 		    line = compile_while(p, &cctx);
10034 		    break;
10035 	    case CMD_endwhile:
10036 		    line = compile_endwhile(p, &cctx);
10037 		    cctx.ctx_had_return = FALSE;
10038 		    break;
10039 
10040 	    case CMD_for:
10041 		    line = compile_for(p, &cctx);
10042 		    break;
10043 	    case CMD_endfor:
10044 		    line = compile_endfor(p, &cctx);
10045 		    cctx.ctx_had_return = FALSE;
10046 		    break;
10047 	    case CMD_continue:
10048 		    line = compile_continue(p, &cctx);
10049 		    break;
10050 	    case CMD_break:
10051 		    line = compile_break(p, &cctx);
10052 		    break;
10053 
10054 	    case CMD_try:
10055 		    line = compile_try(p, &cctx);
10056 		    break;
10057 	    case CMD_catch:
10058 		    line = compile_catch(p, &cctx);
10059 		    cctx.ctx_had_return = FALSE;
10060 		    break;
10061 	    case CMD_finally:
10062 		    line = compile_finally(p, &cctx);
10063 		    cctx.ctx_had_return = FALSE;
10064 		    break;
10065 	    case CMD_endtry:
10066 		    line = compile_endtry(p, &cctx);
10067 		    cctx.ctx_had_return = FALSE;
10068 		    break;
10069 	    case CMD_throw:
10070 		    line = compile_throw(p, &cctx);
10071 		    break;
10072 
10073 	    case CMD_eval:
10074 		    line = compile_eval(p, &cctx);
10075 		    break;
10076 
10077 	    case CMD_echo:
10078 	    case CMD_echon:
10079 	    case CMD_execute:
10080 	    case CMD_echomsg:
10081 	    case CMD_echoerr:
10082 	    case CMD_echoconsole:
10083 		    line = compile_mult_expr(p, ea.cmdidx, &cctx);
10084 		    break;
10085 
10086 	    case CMD_put:
10087 		    ea.cmd = cmd;
10088 		    line = compile_put(p, &ea, &cctx);
10089 		    break;
10090 
10091 	    case CMD_substitute:
10092 		    if (check_global_and_subst(ea.cmd, p) == FAIL)
10093 			goto erret;
10094 		    if (cctx.ctx_skip == SKIP_YES)
10095 			line = (char_u *)"";
10096 		    else
10097 		    {
10098 			ea.arg = p;
10099 			line = compile_substitute(line, &ea, &cctx);
10100 		    }
10101 		    break;
10102 
10103 	    case CMD_redir:
10104 		    ea.arg = p;
10105 		    line = compile_redir(line, &ea, &cctx);
10106 		    break;
10107 
10108 	    case CMD_cexpr:
10109 	    case CMD_lexpr:
10110 	    case CMD_caddexpr:
10111 	    case CMD_laddexpr:
10112 	    case CMD_cgetexpr:
10113 	    case CMD_lgetexpr:
10114 #ifdef FEAT_QUICKFIX
10115 		    ea.arg = p;
10116 		    line = compile_cexpr(line, &ea, &cctx);
10117 #else
10118 		    ex_ni(&ea);
10119 		    line = NULL;
10120 #endif
10121 		    break;
10122 
10123 	    case CMD_append:
10124 	    case CMD_change:
10125 	    case CMD_insert:
10126 	    case CMD_k:
10127 	    case CMD_t:
10128 	    case CMD_xit:
10129 		    not_in_vim9(&ea);
10130 		    goto erret;
10131 
10132 	    case CMD_SIZE:
10133 		    if (cctx.ctx_skip != SKIP_YES)
10134 		    {
10135 			semsg(_(e_invalid_command_str), ea.cmd);
10136 			goto erret;
10137 		    }
10138 		    // We don't check for a next command here.
10139 		    line = (char_u *)"";
10140 		    break;
10141 
10142 	    case CMD_lua:
10143 	    case CMD_mzscheme:
10144 	    case CMD_perl:
10145 	    case CMD_py3:
10146 	    case CMD_python3:
10147 	    case CMD_python:
10148 	    case CMD_pythonx:
10149 	    case CMD_ruby:
10150 	    case CMD_tcl:
10151 		    ea.arg = p;
10152 		    if (vim_strchr(line, '\n') == NULL)
10153 			line = compile_exec(line, &ea, &cctx);
10154 		    else
10155 			// heredoc lines have been concatenated with NL
10156 			// characters in get_function_body()
10157 			line = compile_script(line, &cctx);
10158 		    break;
10159 
10160 	    case CMD_global:
10161 		    if (check_global_and_subst(ea.cmd, p) == FAIL)
10162 			goto erret;
10163 		    // FALLTHROUGH
10164 	    default:
10165 		    // Not recognized, execute with do_cmdline_cmd().
10166 		    ea.arg = p;
10167 		    line = compile_exec(line, &ea, &cctx);
10168 		    break;
10169 	}
10170 nextline:
10171 	if (line == NULL)
10172 	    goto erret;
10173 	line = skipwhite(line);
10174 
10175 	// Undo any command modifiers.
10176 	generate_undo_cmdmods(&cctx);
10177 
10178 	if (cctx.ctx_type_stack.ga_len < 0)
10179 	{
10180 	    iemsg("Type stack underflow");
10181 	    goto erret;
10182 	}
10183     }
10184 
10185     if (cctx.ctx_scope != NULL)
10186     {
10187 	if (cctx.ctx_scope->se_type == IF_SCOPE)
10188 	    emsg(_(e_endif));
10189 	else if (cctx.ctx_scope->se_type == WHILE_SCOPE)
10190 	    emsg(_(e_endwhile));
10191 	else if (cctx.ctx_scope->se_type == FOR_SCOPE)
10192 	    emsg(_(e_endfor));
10193 	else
10194 	    emsg(_(e_missing_rcurly));
10195 	goto erret;
10196     }
10197 
10198     if (!cctx.ctx_had_return)
10199     {
10200 	if (ufunc->uf_ret_type->tt_type == VAR_UNKNOWN)
10201 	    ufunc->uf_ret_type = &t_void;
10202 	else if (ufunc->uf_ret_type->tt_type != VAR_VOID)
10203 	{
10204 	    emsg(_(e_missing_return_statement));
10205 	    goto erret;
10206 	}
10207 
10208 	// Return void if there is no return at the end.
10209 	generate_instr(&cctx, ISN_RETURN_VOID);
10210     }
10211 
10212     // When compiled with ":silent!" and there was an error don't consider the
10213     // function compiled.
10214     if (emsg_silent == 0 || did_emsg_silent == did_emsg_silent_before)
10215     {
10216 	dfunc_T	*dfunc = ((dfunc_T *)def_functions.ga_data)
10217 							 + ufunc->uf_dfunc_idx;
10218 	dfunc->df_deleted = FALSE;
10219 	dfunc->df_script_seq = current_sctx.sc_seq;
10220 #ifdef FEAT_PROFILE
10221 	if (cctx.ctx_compile_type == CT_PROFILE)
10222 	{
10223 	    dfunc->df_instr_prof = instr->ga_data;
10224 	    dfunc->df_instr_prof_count = instr->ga_len;
10225 	}
10226 	else
10227 #endif
10228 	if (cctx.ctx_compile_type == CT_DEBUG)
10229 	{
10230 	    dfunc->df_instr_debug = instr->ga_data;
10231 	    dfunc->df_instr_debug_count = instr->ga_len;
10232 	}
10233 	else
10234 	{
10235 	    dfunc->df_instr = instr->ga_data;
10236 	    dfunc->df_instr_count = instr->ga_len;
10237 	}
10238 	dfunc->df_varcount = dfunc->df_var_names.ga_len;
10239 	dfunc->df_has_closure = cctx.ctx_has_closure;
10240 	if (cctx.ctx_outer_used)
10241 	    ufunc->uf_flags |= FC_CLOSURE;
10242 	ufunc->uf_def_status = UF_COMPILED;
10243     }
10244 
10245     ret = OK;
10246 
10247 erret:
10248     if (ufunc->uf_def_status == UF_COMPILING)
10249     {
10250 	dfunc_T	*dfunc = ((dfunc_T *)def_functions.ga_data)
10251 							 + ufunc->uf_dfunc_idx;
10252 
10253 	// Compiling aborted, free the generated instructions.
10254 	clear_instr_ga(instr);
10255 	VIM_CLEAR(dfunc->df_name);
10256 	ga_clear_strings(&dfunc->df_var_names);
10257 
10258 	// If using the last entry in the table and it was added above, we
10259 	// might as well remove it.
10260 	if (!dfunc->df_deleted && new_def_function
10261 			    && ufunc->uf_dfunc_idx == def_functions.ga_len - 1)
10262 	{
10263 	    --def_functions.ga_len;
10264 	    ufunc->uf_dfunc_idx = 0;
10265 	}
10266 	ufunc->uf_def_status = UF_COMPILE_ERROR;
10267 
10268 	while (cctx.ctx_scope != NULL)
10269 	    drop_scope(&cctx);
10270 
10271 	if (errormsg != NULL)
10272 	    emsg(errormsg);
10273 	else if (did_emsg == did_emsg_before)
10274 	    emsg(_(e_compiling_def_function_failed));
10275     }
10276 
10277     if (cctx.ctx_redir_lhs.lhs_name != NULL)
10278     {
10279 	if (ret == OK)
10280 	{
10281 	    emsg(_(e_missing_redir_end));
10282 	    ret = FAIL;
10283 	}
10284 	vim_free(cctx.ctx_redir_lhs.lhs_name);
10285 	vim_free(cctx.ctx_redir_lhs.lhs_whole);
10286     }
10287 
10288     current_sctx = save_current_sctx;
10289     estack_compiling = save_estack_compiling;
10290     cmdmod.cmod_flags =	save_cmod_flags;
10291     if (do_estack_push)
10292 	estack_pop();
10293 
10294     vim_free(line_to_free);
10295     free_imported(&cctx);
10296     free_locals(&cctx);
10297     ga_clear(&cctx.ctx_type_stack);
10298     return ret;
10299 }
10300 
10301     void
set_function_type(ufunc_T * ufunc)10302 set_function_type(ufunc_T *ufunc)
10303 {
10304     int varargs = ufunc->uf_va_name != NULL;
10305     int argcount = ufunc->uf_args.ga_len;
10306 
10307     // Create a type for the function, with the return type and any
10308     // argument types.
10309     // A vararg is included in uf_args.ga_len but not in uf_arg_types.
10310     // The type is included in "tt_args".
10311     if (argcount > 0 || varargs)
10312     {
10313 	if (ufunc->uf_type_list.ga_itemsize == 0)
10314 	    ga_init2(&ufunc->uf_type_list, sizeof(type_T *), 10);
10315 	ufunc->uf_func_type = alloc_func_type(ufunc->uf_ret_type,
10316 					   argcount, &ufunc->uf_type_list);
10317 	// Add argument types to the function type.
10318 	if (func_type_add_arg_types(ufunc->uf_func_type,
10319 				    argcount + varargs,
10320 				    &ufunc->uf_type_list) == FAIL)
10321 	    return;
10322 	ufunc->uf_func_type->tt_argcount = argcount + varargs;
10323 	ufunc->uf_func_type->tt_min_argcount =
10324 				      argcount - ufunc->uf_def_args.ga_len;
10325 	if (ufunc->uf_arg_types == NULL)
10326 	{
10327 	    int i;
10328 
10329 	    // lambda does not have argument types.
10330 	    for (i = 0; i < argcount; ++i)
10331 		ufunc->uf_func_type->tt_args[i] = &t_any;
10332 	}
10333 	else
10334 	    mch_memmove(ufunc->uf_func_type->tt_args,
10335 			 ufunc->uf_arg_types, sizeof(type_T *) * argcount);
10336 	if (varargs)
10337 	{
10338 	    ufunc->uf_func_type->tt_args[argcount] =
10339 		   ufunc->uf_va_type == NULL ? &t_list_any : ufunc->uf_va_type;
10340 	    ufunc->uf_func_type->tt_flags = TTFLAG_VARARGS;
10341 	}
10342     }
10343     else
10344 	// No arguments, can use a predefined type.
10345 	ufunc->uf_func_type = get_func_type(ufunc->uf_ret_type,
10346 					   argcount, &ufunc->uf_type_list);
10347 }
10348 
10349 
10350 /*
10351  * Delete an instruction, free what it contains.
10352  */
10353     void
delete_instr(isn_T * isn)10354 delete_instr(isn_T *isn)
10355 {
10356     switch (isn->isn_type)
10357     {
10358 	case ISN_DEF:
10359 	case ISN_EXEC:
10360 	case ISN_EXEC_SPLIT:
10361 	case ISN_LEGACY_EVAL:
10362 	case ISN_LOADAUTO:
10363 	case ISN_LOADB:
10364 	case ISN_LOADENV:
10365 	case ISN_LOADG:
10366 	case ISN_LOADOPT:
10367 	case ISN_LOADT:
10368 	case ISN_LOADW:
10369 	case ISN_LOCKUNLOCK:
10370 	case ISN_PUSHEXC:
10371 	case ISN_PUSHFUNC:
10372 	case ISN_PUSHS:
10373 	case ISN_RANGE:
10374 	case ISN_STOREAUTO:
10375 	case ISN_STOREB:
10376 	case ISN_STOREENV:
10377 	case ISN_STOREG:
10378 	case ISN_STORET:
10379 	case ISN_STOREW:
10380 	case ISN_STRINGMEMBER:
10381 	    vim_free(isn->isn_arg.string);
10382 	    break;
10383 
10384 	case ISN_SUBSTITUTE:
10385 	    {
10386 		int	idx;
10387 		isn_T	*list = isn->isn_arg.subs.subs_instr;
10388 
10389 		vim_free(isn->isn_arg.subs.subs_cmd);
10390 		for (idx = 0; list[idx].isn_type != ISN_FINISH; ++idx)
10391 		    delete_instr(list + idx);
10392 		vim_free(list);
10393 	    }
10394 	    break;
10395 
10396 	case ISN_INSTR:
10397 	    {
10398 		int	idx;
10399 		isn_T	*list = isn->isn_arg.instr;
10400 
10401 		for (idx = 0; list[idx].isn_type != ISN_FINISH; ++idx)
10402 		    delete_instr(list + idx);
10403 		vim_free(list);
10404 	    }
10405 	    break;
10406 
10407 	case ISN_LOADS:
10408 	case ISN_STORES:
10409 	    vim_free(isn->isn_arg.loadstore.ls_name);
10410 	    break;
10411 
10412 	case ISN_UNLET:
10413 	case ISN_UNLETENV:
10414 	    vim_free(isn->isn_arg.unlet.ul_name);
10415 	    break;
10416 
10417 	case ISN_STOREOPT:
10418 	    vim_free(isn->isn_arg.storeopt.so_name);
10419 	    break;
10420 
10421 	case ISN_PUSHBLOB:   // push blob isn_arg.blob
10422 	    blob_unref(isn->isn_arg.blob);
10423 	    break;
10424 
10425 	case ISN_PUSHJOB:
10426 #ifdef FEAT_JOB_CHANNEL
10427 	    job_unref(isn->isn_arg.job);
10428 #endif
10429 	    break;
10430 
10431 	case ISN_PUSHCHANNEL:
10432 #ifdef FEAT_JOB_CHANNEL
10433 	    channel_unref(isn->isn_arg.channel);
10434 #endif
10435 	    break;
10436 
10437 	case ISN_UCALL:
10438 	    vim_free(isn->isn_arg.ufunc.cuf_name);
10439 	    break;
10440 
10441 	case ISN_FUNCREF:
10442 	    {
10443 		dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
10444 					       + isn->isn_arg.funcref.fr_func;
10445 		ufunc_T *ufunc = dfunc->df_ufunc;
10446 
10447 		if (ufunc != NULL && func_name_refcount(ufunc->uf_name))
10448 		    func_ptr_unref(ufunc);
10449 	    }
10450 	    break;
10451 
10452 	case ISN_DCALL:
10453 	    {
10454 		dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
10455 					       + isn->isn_arg.dfunc.cdf_idx;
10456 
10457 		if (dfunc->df_ufunc != NULL
10458 			       && func_name_refcount(dfunc->df_ufunc->uf_name))
10459 		    func_ptr_unref(dfunc->df_ufunc);
10460 	    }
10461 	    break;
10462 
10463 	case ISN_NEWFUNC:
10464 	    {
10465 		char_u  *lambda = isn->isn_arg.newfunc.nf_lambda;
10466 		ufunc_T *ufunc = find_func_even_dead(lambda, TRUE, NULL);
10467 
10468 		if (ufunc != NULL)
10469 		{
10470 		    unlink_def_function(ufunc);
10471 		    func_ptr_unref(ufunc);
10472 		}
10473 
10474 		vim_free(lambda);
10475 		vim_free(isn->isn_arg.newfunc.nf_global);
10476 	    }
10477 	    break;
10478 
10479 	case ISN_CHECKTYPE:
10480 	case ISN_SETTYPE:
10481 	    free_type(isn->isn_arg.type.ct_type);
10482 	    break;
10483 
10484 	case ISN_CMDMOD:
10485 	    vim_regfree(isn->isn_arg.cmdmod.cf_cmdmod
10486 					       ->cmod_filter_regmatch.regprog);
10487 	    vim_free(isn->isn_arg.cmdmod.cf_cmdmod);
10488 	    break;
10489 
10490 	case ISN_LOADSCRIPT:
10491 	case ISN_STORESCRIPT:
10492 	    vim_free(isn->isn_arg.script.scriptref);
10493 	    break;
10494 
10495 	case ISN_TRY:
10496 	    vim_free(isn->isn_arg.try.try_ref);
10497 	    break;
10498 
10499 	case ISN_CEXPR_CORE:
10500 	    vim_free(isn->isn_arg.cexpr.cexpr_ref->cer_cmdline);
10501 	    vim_free(isn->isn_arg.cexpr.cexpr_ref);
10502 	    break;
10503 
10504 	case ISN_2BOOL:
10505 	case ISN_2STRING:
10506 	case ISN_2STRING_ANY:
10507 	case ISN_ADDBLOB:
10508 	case ISN_ADDLIST:
10509 	case ISN_ANYINDEX:
10510 	case ISN_ANYSLICE:
10511 	case ISN_BCALL:
10512 	case ISN_BLOBAPPEND:
10513 	case ISN_BLOBINDEX:
10514 	case ISN_BLOBSLICE:
10515 	case ISN_CATCH:
10516 	case ISN_CEXPR_AUCMD:
10517 	case ISN_CHECKLEN:
10518 	case ISN_CHECKNR:
10519 	case ISN_CLEARDICT:
10520 	case ISN_CMDMOD_REV:
10521 	case ISN_COMPAREANY:
10522 	case ISN_COMPAREBLOB:
10523 	case ISN_COMPAREBOOL:
10524 	case ISN_COMPAREDICT:
10525 	case ISN_COMPAREFLOAT:
10526 	case ISN_COMPAREFUNC:
10527 	case ISN_COMPARELIST:
10528 	case ISN_COMPARENR:
10529 	case ISN_COMPARESPECIAL:
10530 	case ISN_COMPARESTRING:
10531 	case ISN_CONCAT:
10532 	case ISN_COND2BOOL:
10533 	case ISN_DEBUG:
10534 	case ISN_DROP:
10535 	case ISN_ECHO:
10536 	case ISN_ECHOCONSOLE:
10537 	case ISN_ECHOERR:
10538 	case ISN_ECHOMSG:
10539 	case ISN_ENDTRY:
10540 	case ISN_EXECCONCAT:
10541 	case ISN_EXECUTE:
10542 	case ISN_FINALLY:
10543 	case ISN_FINISH:
10544 	case ISN_FOR:
10545 	case ISN_GETITEM:
10546 	case ISN_JUMP:
10547 	case ISN_JUMP_IF_ARG_SET:
10548 	case ISN_LISTAPPEND:
10549 	case ISN_LISTINDEX:
10550 	case ISN_LISTSLICE:
10551 	case ISN_LOAD:
10552 	case ISN_LOADBDICT:
10553 	case ISN_LOADGDICT:
10554 	case ISN_LOADOUTER:
10555 	case ISN_LOADREG:
10556 	case ISN_LOADTDICT:
10557 	case ISN_LOADV:
10558 	case ISN_LOADWDICT:
10559 	case ISN_LOCKCONST:
10560 	case ISN_MEMBER:
10561 	case ISN_NEGATENR:
10562 	case ISN_NEWDICT:
10563 	case ISN_NEWLIST:
10564 	case ISN_OPANY:
10565 	case ISN_OPFLOAT:
10566 	case ISN_OPNR:
10567 	case ISN_PCALL:
10568 	case ISN_PCALL_END:
10569 	case ISN_PROF_END:
10570 	case ISN_PROF_START:
10571 	case ISN_PUSHBOOL:
10572 	case ISN_PUSHF:
10573 	case ISN_PUSHNR:
10574 	case ISN_PUSHSPEC:
10575 	case ISN_PUT:
10576 	case ISN_REDIREND:
10577 	case ISN_REDIRSTART:
10578 	case ISN_RETURN:
10579 	case ISN_RETURN_VOID:
10580 	case ISN_SHUFFLE:
10581 	case ISN_SLICE:
10582 	case ISN_STORE:
10583 	case ISN_STOREINDEX:
10584 	case ISN_STORENR:
10585 	case ISN_STOREOUTER:
10586 	case ISN_STORERANGE:
10587 	case ISN_STOREREG:
10588 	case ISN_STOREV:
10589 	case ISN_STRINDEX:
10590 	case ISN_STRSLICE:
10591 	case ISN_THROW:
10592 	case ISN_TRYCONT:
10593 	case ISN_UNLETINDEX:
10594 	case ISN_UNLETRANGE:
10595 	case ISN_UNPACK:
10596 	case ISN_USEDICT:
10597 	    // nothing allocated
10598 	    break;
10599     }
10600 }
10601 
10602 /*
10603  * Free all instructions for "dfunc" except df_name.
10604  */
10605     static void
delete_def_function_contents(dfunc_T * dfunc,int mark_deleted)10606 delete_def_function_contents(dfunc_T *dfunc, int mark_deleted)
10607 {
10608     int idx;
10609 
10610     ga_clear(&dfunc->df_def_args_isn);
10611     ga_clear_strings(&dfunc->df_var_names);
10612 
10613     if (dfunc->df_instr != NULL)
10614     {
10615 	for (idx = 0; idx < dfunc->df_instr_count; ++idx)
10616 	    delete_instr(dfunc->df_instr + idx);
10617 	VIM_CLEAR(dfunc->df_instr);
10618 	dfunc->df_instr = NULL;
10619     }
10620     if (dfunc->df_instr_debug != NULL)
10621     {
10622 	for (idx = 0; idx < dfunc->df_instr_debug_count; ++idx)
10623 	    delete_instr(dfunc->df_instr_debug + idx);
10624 	VIM_CLEAR(dfunc->df_instr_debug);
10625 	dfunc->df_instr_debug = NULL;
10626     }
10627 #ifdef FEAT_PROFILE
10628     if (dfunc->df_instr_prof != NULL)
10629     {
10630 	for (idx = 0; idx < dfunc->df_instr_prof_count; ++idx)
10631 	    delete_instr(dfunc->df_instr_prof + idx);
10632 	VIM_CLEAR(dfunc->df_instr_prof);
10633 	dfunc->df_instr_prof = NULL;
10634     }
10635 #endif
10636 
10637     if (mark_deleted)
10638 	dfunc->df_deleted = TRUE;
10639     if (dfunc->df_ufunc != NULL)
10640 	dfunc->df_ufunc->uf_def_status = UF_NOT_COMPILED;
10641 }
10642 
10643 /*
10644  * When a user function is deleted, clear the contents of any associated def
10645  * function, unless another user function still uses it.
10646  * The position in def_functions can be re-used.
10647  */
10648     void
unlink_def_function(ufunc_T * ufunc)10649 unlink_def_function(ufunc_T *ufunc)
10650 {
10651     if (ufunc->uf_dfunc_idx > 0)
10652     {
10653 	dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
10654 							 + ufunc->uf_dfunc_idx;
10655 
10656 	if (--dfunc->df_refcount <= 0)
10657 	    delete_def_function_contents(dfunc, TRUE);
10658 	ufunc->uf_def_status = UF_NOT_COMPILED;
10659 	ufunc->uf_dfunc_idx = 0;
10660 	if (dfunc->df_ufunc == ufunc)
10661 	    dfunc->df_ufunc = NULL;
10662     }
10663 }
10664 
10665 /*
10666  * Used when a user function refers to an existing dfunc.
10667  */
10668     void
link_def_function(ufunc_T * ufunc)10669 link_def_function(ufunc_T *ufunc)
10670 {
10671     if (ufunc->uf_dfunc_idx > 0)
10672     {
10673 	dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
10674 							 + ufunc->uf_dfunc_idx;
10675 
10676 	++dfunc->df_refcount;
10677     }
10678 }
10679 
10680 #if defined(EXITFREE) || defined(PROTO)
10681 /*
10682  * Free all functions defined with ":def".
10683  */
10684     void
free_def_functions(void)10685 free_def_functions(void)
10686 {
10687     int idx;
10688 
10689     for (idx = 0; idx < def_functions.ga_len; ++idx)
10690     {
10691 	dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data) + idx;
10692 
10693 	delete_def_function_contents(dfunc, TRUE);
10694 	vim_free(dfunc->df_name);
10695     }
10696 
10697     ga_clear(&def_functions);
10698 }
10699 #endif
10700 
10701 
10702 #endif // FEAT_EVAL
10703