blob: 570c6a494830490fdf5d8487d7cad7d24eef7d81 [file] [log] [blame]
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001/* 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/*
27 * Chain of jump instructions where the end label needs to be set.
28 */
29typedef struct endlabel_S endlabel_T;
30struct endlabel_S {
31 endlabel_T *el_next; // chain end_label locations
32 int el_end_label; // instruction idx where to set end
33};
34
35/*
36 * info specific for the scope of :if / elseif / else
37 */
38typedef struct {
39 int is_if_label; // instruction idx at IF or ELSEIF
40 endlabel_T *is_end_label; // instructions to set end label
41} ifscope_T;
42
43/*
44 * info specific for the scope of :while
45 */
46typedef struct {
47 int ws_top_label; // instruction idx at WHILE
48 endlabel_T *ws_end_label; // instructions to set end
49} whilescope_T;
50
51/*
52 * info specific for the scope of :for
53 */
54typedef struct {
55 int fs_top_label; // instruction idx at FOR
56 endlabel_T *fs_end_label; // break instructions
57} forscope_T;
58
59/*
60 * info specific for the scope of :try
61 */
62typedef struct {
63 int ts_try_label; // instruction idx at TRY
64 endlabel_T *ts_end_label; // jump to :finally or :endtry
65 int ts_catch_label; // instruction idx of last CATCH
66 int ts_caught_all; // "catch" without argument encountered
67} tryscope_T;
68
69typedef enum {
70 NO_SCOPE,
71 IF_SCOPE,
72 WHILE_SCOPE,
73 FOR_SCOPE,
74 TRY_SCOPE,
75 BLOCK_SCOPE
76} scopetype_T;
77
78/*
79 * Info for one scope, pointed to by "ctx_scope".
80 */
81typedef struct scope_S scope_T;
82struct scope_S {
83 scope_T *se_outer; // scope containing this one
84 scopetype_T se_type;
85 int se_local_count; // ctx_locals.ga_len before scope
86 union {
87 ifscope_T se_if;
88 whilescope_T se_while;
89 forscope_T se_for;
90 tryscope_T se_try;
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +010091 } se_u;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +010092};
93
94/*
95 * Entry for "ctx_locals". Used for arguments and local variables.
96 */
97typedef struct {
98 char_u *lv_name;
99 type_T *lv_type;
100 int lv_const; // when TRUE cannot be assigned to
101 int lv_arg; // when TRUE this is an argument
102} lvar_T;
103
104/*
105 * Context for compiling lines of Vim script.
106 * Stores info about the local variables and condition stack.
107 */
108struct cctx_S {
109 ufunc_T *ctx_ufunc; // current function
110 int ctx_lnum; // line number in current function
111 garray_T ctx_instr; // generated instructions
112
113 garray_T ctx_locals; // currently visible local variables
114 int ctx_max_local; // maximum number of locals at one time
115
116 garray_T ctx_imports; // imported items
117
Bram Moolenaara259d8d2020-01-31 20:10:50 +0100118 int ctx_skip; // when TRUE skip commands, when FALSE skip
119 // commands after "else"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100120 scope_T *ctx_scope; // current scope, NULL at toplevel
121
122 garray_T ctx_type_stack; // type of each item on the stack
123 garray_T *ctx_type_list; // space for adding types
124};
125
126static char e_var_notfound[] = N_("E1001: variable not found: %s");
127static char e_syntax_at[] = N_("E1002: Syntax error at %s");
128
129static int compile_expr1(char_u **arg, cctx_T *cctx);
130static int compile_expr2(char_u **arg, cctx_T *cctx);
131static int compile_expr3(char_u **arg, cctx_T *cctx);
132
133/*
134 * Lookup variable "name" in the local scope and return the index.
135 */
136 static int
137lookup_local(char_u *name, size_t len, cctx_T *cctx)
138{
139 int idx;
140
141 if (len <= 0)
142 return -1;
143 for (idx = 0; idx < cctx->ctx_locals.ga_len; ++idx)
144 {
145 lvar_T *lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
146
147 if (STRNCMP(name, lvar->lv_name, len) == 0
148 && STRLEN(lvar->lv_name) == len)
149 return idx;
150 }
151 return -1;
152}
153
154/*
155 * Lookup an argument in the current function.
156 * Returns the argument index or -1 if not found.
157 */
158 static int
159lookup_arg(char_u *name, size_t len, cctx_T *cctx)
160{
161 int idx;
162
163 if (len <= 0)
164 return -1;
165 for (idx = 0; idx < cctx->ctx_ufunc->uf_args.ga_len; ++idx)
166 {
167 char_u *arg = FUNCARG(cctx->ctx_ufunc, idx);
168
169 if (STRNCMP(name, arg, len) == 0 && STRLEN(arg) == len)
170 return idx;
171 }
172 return -1;
173}
174
175/*
176 * Lookup a vararg argument in the current function.
177 * Returns TRUE if there is a match.
178 */
179 static int
180lookup_vararg(char_u *name, size_t len, cctx_T *cctx)
181{
182 char_u *va_name = cctx->ctx_ufunc->uf_va_name;
183
184 return len > 0 && va_name != NULL
185 && STRNCMP(name, va_name, len) == 0 && STRLEN(va_name) == len;
186}
187
188/*
189 * Lookup a variable in the current script.
190 * Returns OK or FAIL.
191 */
192 static int
193lookup_script(char_u *name, size_t len)
194{
195 int cc;
196 hashtab_T *ht = &SCRIPT_VARS(current_sctx.sc_sid);
197 dictitem_T *di;
198
199 cc = name[len];
200 name[len] = NUL;
201 di = find_var_in_ht(ht, 0, name, TRUE);
202 name[len] = cc;
203 return di == NULL ? FAIL: OK;
204}
205
206 static type_T *
207get_list_type(type_T *member_type, garray_T *type_list)
208{
209 type_T *type;
210
211 // recognize commonly used types
212 if (member_type->tt_type == VAR_UNKNOWN)
213 return &t_list_any;
214 if (member_type->tt_type == VAR_NUMBER)
215 return &t_list_number;
216 if (member_type->tt_type == VAR_STRING)
217 return &t_list_string;
218
219 // Not a common type, create a new entry.
220 if (ga_grow(type_list, 1) == FAIL)
221 return FAIL;
222 type = ((type_T *)type_list->ga_data) + type_list->ga_len;
223 ++type_list->ga_len;
224 type->tt_type = VAR_LIST;
225 type->tt_member = member_type;
226 return type;
227}
228
229 static type_T *
230get_dict_type(type_T *member_type, garray_T *type_list)
231{
232 type_T *type;
233
234 // recognize commonly used types
235 if (member_type->tt_type == VAR_UNKNOWN)
236 return &t_dict_any;
237 if (member_type->tt_type == VAR_NUMBER)
238 return &t_dict_number;
239 if (member_type->tt_type == VAR_STRING)
240 return &t_dict_string;
241
242 // Not a common type, create a new entry.
243 if (ga_grow(type_list, 1) == FAIL)
244 return FAIL;
245 type = ((type_T *)type_list->ga_data) + type_list->ga_len;
246 ++type_list->ga_len;
247 type->tt_type = VAR_DICT;
248 type->tt_member = member_type;
249 return type;
250}
251
252/////////////////////////////////////////////////////////////////////
253// Following generate_ functions expect the caller to call ga_grow().
254
255/*
256 * Generate an instruction without arguments.
257 * Returns a pointer to the new instruction, NULL if failed.
258 */
259 static isn_T *
260generate_instr(cctx_T *cctx, isntype_T isn_type)
261{
262 garray_T *instr = &cctx->ctx_instr;
263 isn_T *isn;
264
265 if (ga_grow(instr, 1) == FAIL)
266 return NULL;
267 isn = ((isn_T *)instr->ga_data) + instr->ga_len;
268 isn->isn_type = isn_type;
269 isn->isn_lnum = cctx->ctx_lnum + 1;
270 ++instr->ga_len;
271
272 return isn;
273}
274
275/*
276 * Generate an instruction without arguments.
277 * "drop" will be removed from the stack.
278 * Returns a pointer to the new instruction, NULL if failed.
279 */
280 static isn_T *
281generate_instr_drop(cctx_T *cctx, isntype_T isn_type, int drop)
282{
283 garray_T *stack = &cctx->ctx_type_stack;
284
285 stack->ga_len -= drop;
286 return generate_instr(cctx, isn_type);
287}
288
289/*
290 * Generate instruction "isn_type" and put "type" on the type stack.
291 */
292 static isn_T *
293generate_instr_type(cctx_T *cctx, isntype_T isn_type, type_T *type)
294{
295 isn_T *isn;
296 garray_T *stack = &cctx->ctx_type_stack;
297
298 if ((isn = generate_instr(cctx, isn_type)) == NULL)
299 return NULL;
300
301 if (ga_grow(stack, 1) == FAIL)
302 return NULL;
303 ((type_T **)stack->ga_data)[stack->ga_len] = type;
304 ++stack->ga_len;
305
306 return isn;
307}
308
309/*
310 * If type at "offset" isn't already VAR_STRING then generate ISN_2STRING.
311 */
312 static int
313may_generate_2STRING(int offset, cctx_T *cctx)
314{
315 isn_T *isn;
316 garray_T *stack = &cctx->ctx_type_stack;
317 type_T **type = ((type_T **)stack->ga_data) + stack->ga_len + offset;
318
319 if ((*type)->tt_type == VAR_STRING)
320 return OK;
321 *type = &t_string;
322
323 if ((isn = generate_instr(cctx, ISN_2STRING)) == NULL)
324 return FAIL;
325 isn->isn_arg.number = offset;
326
327 return OK;
328}
329
330 static int
331check_number_or_float(vartype_T type1, vartype_T type2, char_u *op)
332{
333 if (!((type1 == VAR_NUMBER || type1 == VAR_FLOAT || type1 == VAR_UNKNOWN)
334 && (type2 == VAR_NUMBER || type2 == VAR_FLOAT
335 || type2 == VAR_UNKNOWN)))
336 {
337 if (*op == '+')
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100338 emsg(_("E1035: wrong argument type for +"));
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100339 else
340 semsg(_("E1036: %c requires number or float arguments"), *op);
341 return FAIL;
342 }
343 return OK;
344}
345
346/*
347 * Generate an instruction with two arguments. The instruction depends on the
348 * type of the arguments.
349 */
350 static int
351generate_two_op(cctx_T *cctx, char_u *op)
352{
353 garray_T *stack = &cctx->ctx_type_stack;
354 type_T *type1;
355 type_T *type2;
356 vartype_T vartype;
357 isn_T *isn;
358
359 // Get the known type of the two items on the stack. If they are matching
360 // use a type-specific instruction. Otherwise fall back to runtime type
361 // checking.
362 type1 = ((type_T **)stack->ga_data)[stack->ga_len - 2];
363 type2 = ((type_T **)stack->ga_data)[stack->ga_len - 1];
364 vartype = VAR_UNKNOWN;
365 if (type1->tt_type == type2->tt_type
366 && (type1->tt_type == VAR_NUMBER
367 || type1->tt_type == VAR_LIST
368#ifdef FEAT_FLOAT
369 || type1->tt_type == VAR_FLOAT
370#endif
371 || type1->tt_type == VAR_BLOB))
372 vartype = type1->tt_type;
373
374 switch (*op)
375 {
376 case '+': if (vartype != VAR_LIST && vartype != VAR_BLOB
377 && check_number_or_float(
378 type1->tt_type, type2->tt_type, op) == FAIL)
379 return FAIL;
380 isn = generate_instr_drop(cctx,
381 vartype == VAR_NUMBER ? ISN_OPNR
382 : vartype == VAR_LIST ? ISN_ADDLIST
383 : vartype == VAR_BLOB ? ISN_ADDBLOB
384#ifdef FEAT_FLOAT
385 : vartype == VAR_FLOAT ? ISN_OPFLOAT
386#endif
387 : ISN_OPANY, 1);
388 if (isn != NULL)
389 isn->isn_arg.op.op_type = EXPR_ADD;
390 break;
391
392 case '-':
393 case '*':
394 case '/': if (check_number_or_float(type1->tt_type, type2->tt_type,
395 op) == FAIL)
396 return FAIL;
397 if (vartype == VAR_NUMBER)
398 isn = generate_instr_drop(cctx, ISN_OPNR, 1);
399#ifdef FEAT_FLOAT
400 else if (vartype == VAR_FLOAT)
401 isn = generate_instr_drop(cctx, ISN_OPFLOAT, 1);
402#endif
403 else
404 isn = generate_instr_drop(cctx, ISN_OPANY, 1);
405 if (isn != NULL)
406 isn->isn_arg.op.op_type = *op == '*'
407 ? EXPR_MULT : *op == '/'? EXPR_DIV : EXPR_SUB;
408 break;
409
410 case '%': if ((type1->tt_type != VAR_UNKNOWN
411 && type1->tt_type != VAR_NUMBER)
412 || (type2->tt_type != VAR_UNKNOWN
413 && type2->tt_type != VAR_NUMBER))
414 {
415 emsg(_("E1035: % requires number arguments"));
416 return FAIL;
417 }
418 isn = generate_instr_drop(cctx,
419 vartype == VAR_NUMBER ? ISN_OPNR : ISN_OPANY, 1);
420 if (isn != NULL)
421 isn->isn_arg.op.op_type = EXPR_REM;
422 break;
423 }
424
425 // correct type of result
426 if (vartype == VAR_UNKNOWN)
427 {
428 type_T *type = &t_any;
429
430#ifdef FEAT_FLOAT
431 // float+number and number+float results in float
432 if ((type1->tt_type == VAR_NUMBER || type1->tt_type == VAR_FLOAT)
433 && (type2->tt_type == VAR_NUMBER || type2->tt_type == VAR_FLOAT))
434 type = &t_float;
435#endif
436 ((type_T **)stack->ga_data)[stack->ga_len - 1] = type;
437 }
438
439 return OK;
440}
441
442/*
443 * Generate an ISN_COMPARE* instruction with a boolean result.
444 */
445 static int
446generate_COMPARE(cctx_T *cctx, exptype_T exptype, int ic)
447{
448 isntype_T isntype = ISN_DROP;
449 isn_T *isn;
450 garray_T *stack = &cctx->ctx_type_stack;
451 vartype_T type1;
452 vartype_T type2;
453
454 // Get the known type of the two items on the stack. If they are matching
455 // use a type-specific instruction. Otherwise fall back to runtime type
456 // checking.
457 type1 = ((type_T **)stack->ga_data)[stack->ga_len - 2]->tt_type;
458 type2 = ((type_T **)stack->ga_data)[stack->ga_len - 1]->tt_type;
459 if (type1 == type2)
460 {
461 switch (type1)
462 {
463 case VAR_BOOL: isntype = ISN_COMPAREBOOL; break;
464 case VAR_SPECIAL: isntype = ISN_COMPARESPECIAL; break;
465 case VAR_NUMBER: isntype = ISN_COMPARENR; break;
466 case VAR_FLOAT: isntype = ISN_COMPAREFLOAT; break;
467 case VAR_STRING: isntype = ISN_COMPARESTRING; break;
468 case VAR_BLOB: isntype = ISN_COMPAREBLOB; break;
469 case VAR_LIST: isntype = ISN_COMPARELIST; break;
470 case VAR_DICT: isntype = ISN_COMPAREDICT; break;
471 case VAR_FUNC: isntype = ISN_COMPAREFUNC; break;
472 case VAR_PARTIAL: isntype = ISN_COMPAREPARTIAL; break;
473 default: isntype = ISN_COMPAREANY; break;
474 }
475 }
476 else if (type1 == VAR_UNKNOWN || type2 == VAR_UNKNOWN
477 || ((type1 == VAR_NUMBER || type1 == VAR_FLOAT)
478 && (type2 == VAR_NUMBER || type2 ==VAR_FLOAT)))
479 isntype = ISN_COMPAREANY;
480
481 if ((exptype == EXPR_IS || exptype == EXPR_ISNOT)
482 && (isntype == ISN_COMPAREBOOL
483 || isntype == ISN_COMPARESPECIAL
484 || isntype == ISN_COMPARENR
485 || isntype == ISN_COMPAREFLOAT))
486 {
487 semsg(_("E1037: Cannot use \"%s\" with %s"),
488 exptype == EXPR_IS ? "is" : "isnot" , vartype_name(type1));
489 return FAIL;
490 }
491 if (isntype == ISN_DROP
492 || ((exptype != EXPR_EQUAL && exptype != EXPR_NEQUAL
493 && (type1 == VAR_BOOL || type1 == VAR_SPECIAL
494 || type2 == VAR_BOOL || type2 == VAR_SPECIAL)))
495 || ((exptype != EXPR_EQUAL && exptype != EXPR_NEQUAL
496 && exptype != EXPR_IS && exptype != EXPR_ISNOT
497 && (type1 == VAR_BLOB || type2 == VAR_BLOB
498 || type1 == VAR_LIST || type2 == VAR_LIST))))
499 {
500 semsg(_("E1037: Cannot compare %s with %s"),
501 vartype_name(type1), vartype_name(type2));
502 return FAIL;
503 }
504
505 if ((isn = generate_instr(cctx, isntype)) == NULL)
506 return FAIL;
507 isn->isn_arg.op.op_type = exptype;
508 isn->isn_arg.op.op_ic = ic;
509
510 // takes two arguments, puts one bool back
511 if (stack->ga_len >= 2)
512 {
513 --stack->ga_len;
514 ((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_bool;
515 }
516
517 return OK;
518}
519
520/*
521 * Generate an ISN_2BOOL instruction.
522 */
523 static int
524generate_2BOOL(cctx_T *cctx, int invert)
525{
526 isn_T *isn;
527 garray_T *stack = &cctx->ctx_type_stack;
528
529 if ((isn = generate_instr(cctx, ISN_2BOOL)) == NULL)
530 return FAIL;
531 isn->isn_arg.number = invert;
532
533 // type becomes bool
534 ((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_bool;
535
536 return OK;
537}
538
539 static int
540generate_TYPECHECK(cctx_T *cctx, type_T *vartype, int offset)
541{
542 isn_T *isn;
543 garray_T *stack = &cctx->ctx_type_stack;
544
545 if ((isn = generate_instr(cctx, ISN_CHECKTYPE)) == NULL)
546 return FAIL;
547 isn->isn_arg.type.ct_type = vartype->tt_type; // TODO: whole type
548 isn->isn_arg.type.ct_off = offset;
549
550 // type becomes vartype
551 ((type_T **)stack->ga_data)[stack->ga_len - 1] = vartype;
552
553 return OK;
554}
555
556/*
557 * Generate an ISN_PUSHNR instruction.
558 */
559 static int
560generate_PUSHNR(cctx_T *cctx, varnumber_T number)
561{
562 isn_T *isn;
563
564 if ((isn = generate_instr_type(cctx, ISN_PUSHNR, &t_number)) == NULL)
565 return FAIL;
566 isn->isn_arg.number = number;
567
568 return OK;
569}
570
571/*
572 * Generate an ISN_PUSHBOOL instruction.
573 */
574 static int
575generate_PUSHBOOL(cctx_T *cctx, varnumber_T number)
576{
577 isn_T *isn;
578
579 if ((isn = generate_instr_type(cctx, ISN_PUSHBOOL, &t_bool)) == NULL)
580 return FAIL;
581 isn->isn_arg.number = number;
582
583 return OK;
584}
585
586/*
587 * Generate an ISN_PUSHSPEC instruction.
588 */
589 static int
590generate_PUSHSPEC(cctx_T *cctx, varnumber_T number)
591{
592 isn_T *isn;
593
594 if ((isn = generate_instr_type(cctx, ISN_PUSHSPEC, &t_special)) == NULL)
595 return FAIL;
596 isn->isn_arg.number = number;
597
598 return OK;
599}
600
601#ifdef FEAT_FLOAT
602/*
603 * Generate an ISN_PUSHF instruction.
604 */
605 static int
606generate_PUSHF(cctx_T *cctx, float_T fnumber)
607{
608 isn_T *isn;
609
610 if ((isn = generate_instr_type(cctx, ISN_PUSHF, &t_float)) == NULL)
611 return FAIL;
612 isn->isn_arg.fnumber = fnumber;
613
614 return OK;
615}
616#endif
617
618/*
619 * Generate an ISN_PUSHS instruction.
620 * Consumes "str".
621 */
622 static int
623generate_PUSHS(cctx_T *cctx, char_u *str)
624{
625 isn_T *isn;
626
627 if ((isn = generate_instr_type(cctx, ISN_PUSHS, &t_string)) == NULL)
628 return FAIL;
629 isn->isn_arg.string = str;
630
631 return OK;
632}
633
634/*
635 * Generate an ISN_PUSHBLOB instruction.
636 * Consumes "blob".
637 */
638 static int
639generate_PUSHBLOB(cctx_T *cctx, blob_T *blob)
640{
641 isn_T *isn;
642
643 if ((isn = generate_instr_type(cctx, ISN_PUSHBLOB, &t_blob)) == NULL)
644 return FAIL;
645 isn->isn_arg.blob = blob;
646
647 return OK;
648}
649
650/*
651 * Generate an ISN_STORE instruction.
652 */
653 static int
654generate_STORE(cctx_T *cctx, isntype_T isn_type, int idx, char_u *name)
655{
656 isn_T *isn;
657
658 if ((isn = generate_instr_drop(cctx, isn_type, 1)) == NULL)
659 return FAIL;
660 if (name != NULL)
661 isn->isn_arg.string = vim_strsave(name);
662 else
663 isn->isn_arg.number = idx;
664
665 return OK;
666}
667
668/*
669 * Generate an ISN_STORENR instruction (short for ISN_PUSHNR + ISN_STORE)
670 */
671 static int
672generate_STORENR(cctx_T *cctx, int idx, varnumber_T value)
673{
674 isn_T *isn;
675
676 if ((isn = generate_instr(cctx, ISN_STORENR)) == NULL)
677 return FAIL;
678 isn->isn_arg.storenr.str_idx = idx;
679 isn->isn_arg.storenr.str_val = value;
680
681 return OK;
682}
683
684/*
685 * Generate an ISN_STOREOPT instruction
686 */
687 static int
688generate_STOREOPT(cctx_T *cctx, char_u *name, int opt_flags)
689{
690 isn_T *isn;
691
692 if ((isn = generate_instr(cctx, ISN_STOREOPT)) == NULL)
693 return FAIL;
694 isn->isn_arg.storeopt.so_name = vim_strsave(name);
695 isn->isn_arg.storeopt.so_flags = opt_flags;
696
697 return OK;
698}
699
700/*
701 * Generate an ISN_LOAD or similar instruction.
702 */
703 static int
704generate_LOAD(
705 cctx_T *cctx,
706 isntype_T isn_type,
707 int idx,
708 char_u *name,
709 type_T *type)
710{
711 isn_T *isn;
712
713 if ((isn = generate_instr_type(cctx, isn_type, type)) == NULL)
714 return FAIL;
715 if (name != NULL)
716 isn->isn_arg.string = vim_strsave(name);
717 else
718 isn->isn_arg.number = idx;
719
720 return OK;
721}
722
723/*
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100724 * Generate an ISN_LOADV instruction.
725 */
726 static int
727generate_LOADV(
728 cctx_T *cctx,
729 char_u *name,
730 int error)
731{
732 // load v:var
733 int vidx = find_vim_var(name);
734
735 if (vidx < 0)
736 {
737 if (error)
738 semsg(_(e_var_notfound), name);
739 return FAIL;
740 }
741
742 // TODO: get actual type
743 return generate_LOAD(cctx, ISN_LOADV, vidx, NULL, &t_any);
744}
745
746/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100747 * Generate an ISN_LOADS instruction.
748 */
749 static int
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100750generate_OLDSCRIPT(
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100751 cctx_T *cctx,
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100752 isntype_T isn_type,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100753 char_u *name,
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100754 int sid,
755 type_T *type)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100756{
757 isn_T *isn;
758
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100759 if (isn_type == ISN_LOADS)
760 isn = generate_instr_type(cctx, isn_type, type);
761 else
762 isn = generate_instr_drop(cctx, isn_type, 1);
763 if (isn == NULL)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100764 return FAIL;
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100765 isn->isn_arg.loadstore.ls_name = vim_strsave(name);
766 isn->isn_arg.loadstore.ls_sid = sid;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100767
768 return OK;
769}
770
771/*
772 * Generate an ISN_LOADSCRIPT or ISN_STORESCRIPT instruction.
773 */
774 static int
Bram Moolenaarb283a8a2020-02-02 22:24:04 +0100775generate_VIM9SCRIPT(
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100776 cctx_T *cctx,
777 isntype_T isn_type,
778 int sid,
779 int idx,
780 type_T *type)
781{
782 isn_T *isn;
783
784 if (isn_type == ISN_LOADSCRIPT)
785 isn = generate_instr_type(cctx, isn_type, type);
786 else
787 isn = generate_instr_drop(cctx, isn_type, 1);
788 if (isn == NULL)
789 return FAIL;
790 isn->isn_arg.script.script_sid = sid;
791 isn->isn_arg.script.script_idx = idx;
792 return OK;
793}
794
795/*
796 * Generate an ISN_NEWLIST instruction.
797 */
798 static int
799generate_NEWLIST(cctx_T *cctx, int count)
800{
801 isn_T *isn;
802 garray_T *stack = &cctx->ctx_type_stack;
803 garray_T *type_list = cctx->ctx_type_list;
804 type_T *type;
805 type_T *member;
806
807 if ((isn = generate_instr(cctx, ISN_NEWLIST)) == NULL)
808 return FAIL;
809 isn->isn_arg.number = count;
810
811 // drop the value types
812 stack->ga_len -= count;
813
814 // use the first value type for the list member type
815 if (count > 0)
816 member = ((type_T **)stack->ga_data)[stack->ga_len];
817 else
818 member = &t_any;
819 type = get_list_type(member, type_list);
820
821 // add the list type to the type stack
822 if (ga_grow(stack, 1) == FAIL)
823 return FAIL;
824 ((type_T **)stack->ga_data)[stack->ga_len] = type;
825 ++stack->ga_len;
826
827 return OK;
828}
829
830/*
831 * Generate an ISN_NEWDICT instruction.
832 */
833 static int
834generate_NEWDICT(cctx_T *cctx, int count)
835{
836 isn_T *isn;
837 garray_T *stack = &cctx->ctx_type_stack;
838 garray_T *type_list = cctx->ctx_type_list;
839 type_T *type;
840 type_T *member;
841
842 if ((isn = generate_instr(cctx, ISN_NEWDICT)) == NULL)
843 return FAIL;
844 isn->isn_arg.number = count;
845
846 // drop the key and value types
847 stack->ga_len -= 2 * count;
848
849 // use the first value type for the list member type
850 if (count > 0)
851 member = ((type_T **)stack->ga_data)[stack->ga_len + 1];
852 else
853 member = &t_any;
854 type = get_dict_type(member, type_list);
855
856 // add the dict type to the type stack
857 if (ga_grow(stack, 1) == FAIL)
858 return FAIL;
859 ((type_T **)stack->ga_data)[stack->ga_len] = type;
860 ++stack->ga_len;
861
862 return OK;
863}
864
865/*
866 * Generate an ISN_FUNCREF instruction.
867 */
868 static int
869generate_FUNCREF(cctx_T *cctx, int dfunc_idx)
870{
871 isn_T *isn;
872 garray_T *stack = &cctx->ctx_type_stack;
873
874 if ((isn = generate_instr(cctx, ISN_FUNCREF)) == NULL)
875 return FAIL;
876 isn->isn_arg.number = dfunc_idx;
877
878 if (ga_grow(stack, 1) == FAIL)
879 return FAIL;
880 ((type_T **)stack->ga_data)[stack->ga_len] = &t_partial_any;
881 // TODO: argument and return types
882 ++stack->ga_len;
883
884 return OK;
885}
886
887/*
888 * Generate an ISN_JUMP instruction.
889 */
890 static int
891generate_JUMP(cctx_T *cctx, jumpwhen_T when, int where)
892{
893 isn_T *isn;
894 garray_T *stack = &cctx->ctx_type_stack;
895
896 if ((isn = generate_instr(cctx, ISN_JUMP)) == NULL)
897 return FAIL;
898 isn->isn_arg.jump.jump_when = when;
899 isn->isn_arg.jump.jump_where = where;
900
901 if (when != JUMP_ALWAYS && stack->ga_len > 0)
902 --stack->ga_len;
903
904 return OK;
905}
906
907 static int
908generate_FOR(cctx_T *cctx, int loop_idx)
909{
910 isn_T *isn;
911 garray_T *stack = &cctx->ctx_type_stack;
912
913 if ((isn = generate_instr(cctx, ISN_FOR)) == NULL)
914 return FAIL;
915 isn->isn_arg.forloop.for_idx = loop_idx;
916
917 if (ga_grow(stack, 1) == FAIL)
918 return FAIL;
919 // type doesn't matter, will be stored next
920 ((type_T **)stack->ga_data)[stack->ga_len] = &t_any;
921 ++stack->ga_len;
922
923 return OK;
924}
925
926/*
927 * Generate an ISN_BCALL instruction.
928 * Return FAIL if the number of arguments is wrong.
929 */
930 static int
931generate_BCALL(cctx_T *cctx, int func_idx, int argcount)
932{
933 isn_T *isn;
934 garray_T *stack = &cctx->ctx_type_stack;
935
936 if (check_internal_func(func_idx, argcount) == FAIL)
937 return FAIL;
938
939 if ((isn = generate_instr(cctx, ISN_BCALL)) == NULL)
940 return FAIL;
941 isn->isn_arg.bfunc.cbf_idx = func_idx;
942 isn->isn_arg.bfunc.cbf_argcount = argcount;
943
944 stack->ga_len -= argcount; // drop the arguments
945 if (ga_grow(stack, 1) == FAIL)
946 return FAIL;
947 ((type_T **)stack->ga_data)[stack->ga_len] =
948 internal_func_ret_type(func_idx, argcount);
949 ++stack->ga_len; // add return value
950
951 return OK;
952}
953
954/*
955 * Generate an ISN_DCALL or ISN_UCALL instruction.
956 * Return FAIL if the number of arguments is wrong.
957 */
958 static int
959generate_CALL(cctx_T *cctx, ufunc_T *ufunc, int argcount)
960{
961 isn_T *isn;
962 garray_T *stack = &cctx->ctx_type_stack;
963 int regular_args = ufunc->uf_args.ga_len;
964
965 if (argcount > regular_args && !has_varargs(ufunc))
966 {
967 semsg(_(e_toomanyarg), ufunc->uf_name);
968 return FAIL;
969 }
970 if (argcount < regular_args - ufunc->uf_def_args.ga_len)
971 {
972 semsg(_(e_toofewarg), ufunc->uf_name);
973 return FAIL;
974 }
975
976 // Turn varargs into a list.
977 if (ufunc->uf_va_name != NULL)
978 {
979 int count = argcount - regular_args;
980
981 // TODO: add default values for optional arguments?
982 generate_NEWLIST(cctx, count < 0 ? 0 : count);
983 argcount = regular_args + 1;
984 }
985
986 if ((isn = generate_instr(cctx,
987 ufunc->uf_dfunc_idx >= 0 ? ISN_DCALL : ISN_UCALL)) == NULL)
988 return FAIL;
989 if (ufunc->uf_dfunc_idx >= 0)
990 {
991 isn->isn_arg.dfunc.cdf_idx = ufunc->uf_dfunc_idx;
992 isn->isn_arg.dfunc.cdf_argcount = argcount;
993 }
994 else
995 {
996 // A user function may be deleted and redefined later, can't use the
997 // ufunc pointer, need to look it up again at runtime.
998 isn->isn_arg.ufunc.cuf_name = vim_strsave(ufunc->uf_name);
999 isn->isn_arg.ufunc.cuf_argcount = argcount;
1000 }
1001
1002 stack->ga_len -= argcount; // drop the arguments
1003 if (ga_grow(stack, 1) == FAIL)
1004 return FAIL;
1005 // add return value
1006 ((type_T **)stack->ga_data)[stack->ga_len] = ufunc->uf_ret_type;
1007 ++stack->ga_len;
1008
1009 return OK;
1010}
1011
1012/*
1013 * Generate an ISN_UCALL instruction when the function isn't defined yet.
1014 */
1015 static int
1016generate_UCALL(cctx_T *cctx, char_u *name, int argcount)
1017{
1018 isn_T *isn;
1019 garray_T *stack = &cctx->ctx_type_stack;
1020
1021 if ((isn = generate_instr(cctx, ISN_UCALL)) == NULL)
1022 return FAIL;
1023 isn->isn_arg.ufunc.cuf_name = vim_strsave(name);
1024 isn->isn_arg.ufunc.cuf_argcount = argcount;
1025
1026 stack->ga_len -= argcount; // drop the arguments
1027
1028 // drop the funcref/partial, get back the return value
1029 ((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_any;
1030
1031 return OK;
1032}
1033
1034/*
1035 * Generate an ISN_PCALL instruction.
1036 */
1037 static int
1038generate_PCALL(cctx_T *cctx, int argcount, int at_top)
1039{
1040 isn_T *isn;
1041 garray_T *stack = &cctx->ctx_type_stack;
1042
1043 if ((isn = generate_instr(cctx, ISN_PCALL)) == NULL)
1044 return FAIL;
1045 isn->isn_arg.pfunc.cpf_top = at_top;
1046 isn->isn_arg.pfunc.cpf_argcount = argcount;
1047
1048 stack->ga_len -= argcount; // drop the arguments
1049
1050 // drop the funcref/partial, get back the return value
1051 ((type_T **)stack->ga_data)[stack->ga_len - 1] = &t_any;
1052
1053 return OK;
1054}
1055
1056/*
1057 * Generate an ISN_MEMBER instruction.
1058 */
1059 static int
1060generate_MEMBER(cctx_T *cctx, char_u *name, size_t len)
1061{
1062 isn_T *isn;
1063 garray_T *stack = &cctx->ctx_type_stack;
1064 type_T *type;
1065
1066 if ((isn = generate_instr(cctx, ISN_MEMBER)) == NULL)
1067 return FAIL;
1068 isn->isn_arg.string = vim_strnsave(name, (int)len);
1069
1070 // change dict type to dict member type
1071 type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
1072 ((type_T **)stack->ga_data)[stack->ga_len - 1] = type->tt_member;
1073
1074 return OK;
1075}
1076
1077/*
1078 * Generate an ISN_ECHO instruction.
1079 */
1080 static int
1081generate_ECHO(cctx_T *cctx, int with_white, int count)
1082{
1083 isn_T *isn;
1084
1085 if ((isn = generate_instr_drop(cctx, ISN_ECHO, count)) == NULL)
1086 return FAIL;
1087 isn->isn_arg.echo.echo_with_white = with_white;
1088 isn->isn_arg.echo.echo_count = count;
1089
1090 return OK;
1091}
1092
1093 static int
1094generate_EXEC(cctx_T *cctx, char_u *line)
1095{
1096 isn_T *isn;
1097
1098 if ((isn = generate_instr(cctx, ISN_EXEC)) == NULL)
1099 return FAIL;
1100 isn->isn_arg.string = vim_strsave(line);
1101 return OK;
1102}
1103
1104static char e_white_both[] =
1105 N_("E1004: white space required before and after '%s'");
1106
1107/*
1108 * Reserve space for a local variable.
1109 * Return the index or -1 if it failed.
1110 */
1111 static int
1112reserve_local(cctx_T *cctx, char_u *name, size_t len, int isConst, type_T *type)
1113{
1114 int idx;
1115 lvar_T *lvar;
1116
1117 if (lookup_arg(name, len, cctx) >= 0 || lookup_vararg(name, len, cctx))
1118 {
1119 emsg_namelen(_("E1006: %s is used as an argument"), name, (int)len);
1120 return -1;
1121 }
1122
1123 if (ga_grow(&cctx->ctx_locals, 1) == FAIL)
1124 return -1;
1125 idx = cctx->ctx_locals.ga_len;
1126 if (cctx->ctx_max_local < idx + 1)
1127 cctx->ctx_max_local = idx + 1;
1128 ++cctx->ctx_locals.ga_len;
1129
1130 lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
1131 lvar->lv_name = vim_strnsave(name, (int)(len == 0 ? STRLEN(name) : len));
1132 lvar->lv_const = isConst;
1133 lvar->lv_type = type;
1134
1135 return idx;
1136}
1137
1138/*
1139 * Skip over a type definition and return a pointer to just after it.
1140 */
1141 char_u *
1142skip_type(char_u *start)
1143{
1144 char_u *p = start;
1145
1146 while (ASCII_ISALNUM(*p) || *p == '_')
1147 ++p;
1148
1149 // Skip over "<type>"; this is permissive about white space.
1150 if (*skipwhite(p) == '<')
1151 {
1152 p = skipwhite(p);
1153 p = skip_type(skipwhite(p + 1));
1154 p = skipwhite(p);
1155 if (*p == '>')
1156 ++p;
1157 }
1158 return p;
1159}
1160
1161/*
1162 * Parse the member type: "<type>" and return "type" with the member set.
1163 * Use "type_list" if a new type needs to be added.
1164 * Returns NULL in case of failure.
1165 */
1166 static type_T *
1167parse_type_member(char_u **arg, type_T *type, garray_T *type_list)
1168{
1169 type_T *member_type;
1170
1171 if (**arg != '<')
1172 {
1173 if (*skipwhite(*arg) == '<')
1174 emsg(_("E1007: No white space allowed before <"));
1175 else
1176 emsg(_("E1008: Missing <type>"));
1177 return NULL;
1178 }
1179 *arg = skipwhite(*arg + 1);
1180
1181 member_type = parse_type(arg, type_list);
1182 if (member_type == NULL)
1183 return NULL;
1184
1185 *arg = skipwhite(*arg);
1186 if (**arg != '>')
1187 {
1188 emsg(_("E1009: Missing > after type"));
1189 return NULL;
1190 }
1191 ++*arg;
1192
1193 if (type->tt_type == VAR_LIST)
1194 return get_list_type(member_type, type_list);
1195 return get_dict_type(member_type, type_list);
1196}
1197
1198/*
1199 * Parse a type at "arg" and advance over it.
1200 * Return NULL for failure.
1201 */
1202 type_T *
1203parse_type(char_u **arg, garray_T *type_list)
1204{
1205 char_u *p = *arg;
1206 size_t len;
1207
1208 // skip over the first word
1209 while (ASCII_ISALNUM(*p) || *p == '_')
1210 ++p;
1211 len = p - *arg;
1212
1213 switch (**arg)
1214 {
1215 case 'a':
1216 if (len == 3 && STRNCMP(*arg, "any", len) == 0)
1217 {
1218 *arg += len;
1219 return &t_any;
1220 }
1221 break;
1222 case 'b':
1223 if (len == 4 && STRNCMP(*arg, "bool", len) == 0)
1224 {
1225 *arg += len;
1226 return &t_bool;
1227 }
1228 if (len == 4 && STRNCMP(*arg, "blob", len) == 0)
1229 {
1230 *arg += len;
1231 return &t_blob;
1232 }
1233 break;
1234 case 'c':
1235 if (len == 7 && STRNCMP(*arg, "channel", len) == 0)
1236 {
1237 *arg += len;
1238 return &t_channel;
1239 }
1240 break;
1241 case 'd':
1242 if (len == 4 && STRNCMP(*arg, "dict", len) == 0)
1243 {
1244 *arg += len;
1245 return parse_type_member(arg, &t_dict_any, type_list);
1246 }
1247 break;
1248 case 'f':
1249 if (len == 5 && STRNCMP(*arg, "float", len) == 0)
1250 {
Bram Moolenaara5d59532020-01-26 21:42:03 +01001251#ifdef FEAT_FLOAT
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001252 *arg += len;
1253 return &t_float;
Bram Moolenaara5d59532020-01-26 21:42:03 +01001254#else
1255 emsg(_("E1055: This Vim is not compiled with float support"));
1256 return &t_any;
1257#endif
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001258 }
1259 if (len == 4 && STRNCMP(*arg, "func", len) == 0)
1260 {
1261 *arg += len;
1262 // TODO: arguments and return type
1263 return &t_func_any;
1264 }
1265 break;
1266 case 'j':
1267 if (len == 3 && STRNCMP(*arg, "job", len) == 0)
1268 {
1269 *arg += len;
1270 return &t_job;
1271 }
1272 break;
1273 case 'l':
1274 if (len == 4 && STRNCMP(*arg, "list", len) == 0)
1275 {
1276 *arg += len;
1277 return parse_type_member(arg, &t_list_any, type_list);
1278 }
1279 break;
1280 case 'n':
1281 if (len == 6 && STRNCMP(*arg, "number", len) == 0)
1282 {
1283 *arg += len;
1284 return &t_number;
1285 }
1286 break;
1287 case 'p':
1288 if (len == 4 && STRNCMP(*arg, "partial", len) == 0)
1289 {
1290 *arg += len;
1291 // TODO: arguments and return type
1292 return &t_partial_any;
1293 }
1294 break;
1295 case 's':
1296 if (len == 6 && STRNCMP(*arg, "string", len) == 0)
1297 {
1298 *arg += len;
1299 return &t_string;
1300 }
1301 break;
1302 case 'v':
1303 if (len == 4 && STRNCMP(*arg, "void", len) == 0)
1304 {
1305 *arg += len;
1306 return &t_void;
1307 }
1308 break;
1309 }
1310
1311 semsg(_("E1010: Type not recognized: %s"), *arg);
1312 return &t_any;
1313}
1314
1315/*
1316 * Check if "type1" and "type2" are exactly the same.
1317 */
1318 static int
1319equal_type(type_T *type1, type_T *type2)
1320{
1321 if (type1->tt_type != type2->tt_type)
1322 return FALSE;
1323 switch (type1->tt_type)
1324 {
1325 case VAR_VOID:
1326 case VAR_UNKNOWN:
1327 case VAR_SPECIAL:
1328 case VAR_BOOL:
1329 case VAR_NUMBER:
1330 case VAR_FLOAT:
1331 case VAR_STRING:
1332 case VAR_BLOB:
1333 case VAR_JOB:
1334 case VAR_CHANNEL:
1335 return TRUE; // not composite is always OK
1336 case VAR_LIST:
1337 case VAR_DICT:
1338 return equal_type(type1->tt_member, type2->tt_member);
1339 case VAR_FUNC:
1340 case VAR_PARTIAL:
1341 // TODO; check argument types.
1342 return equal_type(type1->tt_member, type2->tt_member)
1343 && type1->tt_argcount == type2->tt_argcount;
1344 }
1345 return TRUE;
1346}
1347
1348/*
1349 * Find the common type of "type1" and "type2" and put it in "dest".
1350 * "type2" and "dest" may be the same.
1351 */
1352 static void
1353common_type(type_T *type1, type_T *type2, type_T *dest)
1354{
1355 if (equal_type(type1, type2))
1356 {
1357 if (dest != type2)
1358 *dest = *type2;
1359 return;
1360 }
1361
1362 if (type1->tt_type == type2->tt_type)
1363 {
1364 dest->tt_type = type1->tt_type;
1365 if (type1->tt_type == VAR_LIST || type2->tt_type == VAR_DICT)
1366 {
1367 common_type(type1->tt_member, type2->tt_member, dest->tt_member);
1368 return;
1369 }
1370 // TODO: VAR_FUNC and VAR_PARTIAL
1371 }
1372
1373 dest->tt_type = VAR_UNKNOWN; // "any"
1374}
1375
1376 char *
1377vartype_name(vartype_T type)
1378{
1379 switch (type)
1380 {
1381 case VAR_VOID: return "void";
1382 case VAR_UNKNOWN: return "any";
1383 case VAR_SPECIAL: return "special";
1384 case VAR_BOOL: return "bool";
1385 case VAR_NUMBER: return "number";
1386 case VAR_FLOAT: return "float";
1387 case VAR_STRING: return "string";
1388 case VAR_BLOB: return "blob";
1389 case VAR_JOB: return "job";
1390 case VAR_CHANNEL: return "channel";
1391 case VAR_LIST: return "list";
1392 case VAR_DICT: return "dict";
1393 case VAR_FUNC: return "function";
1394 case VAR_PARTIAL: return "partial";
1395 }
1396 return "???";
1397}
1398
1399/*
1400 * Return the name of a type.
1401 * The result may be in allocated memory, in which case "tofree" is set.
1402 */
1403 char *
1404type_name(type_T *type, char **tofree)
1405{
1406 char *name = vartype_name(type->tt_type);
1407
1408 *tofree = NULL;
1409 if (type->tt_type == VAR_LIST || type->tt_type == VAR_DICT)
1410 {
1411 char *member_free;
1412 char *member_name = type_name(type->tt_member, &member_free);
1413 size_t len;
1414
1415 len = STRLEN(name) + STRLEN(member_name) + 3;
1416 *tofree = alloc(len);
1417 if (*tofree != NULL)
1418 {
1419 vim_snprintf(*tofree, len, "%s<%s>", name, member_name);
1420 vim_free(member_free);
1421 return *tofree;
1422 }
1423 }
1424 // TODO: function and partial argument types
1425
1426 return name;
1427}
1428
1429/*
1430 * Find "name" in script-local items of script "sid".
1431 * Returns the index in "sn_var_vals" if found.
1432 * If found but not in "sn_var_vals" returns -1.
1433 * If not found returns -2.
1434 */
1435 int
1436get_script_item_idx(int sid, char_u *name, int check_writable)
1437{
1438 hashtab_T *ht;
1439 dictitem_T *di;
Bram Moolenaar21b9e972020-01-26 19:26:46 +01001440 scriptitem_T *si = SCRIPT_ITEM(sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001441 int idx;
1442
1443 // First look the name up in the hashtable.
1444 if (sid <= 0 || sid > script_items.ga_len)
1445 return -1;
1446 ht = &SCRIPT_VARS(sid);
1447 di = find_var_in_ht(ht, 0, name, TRUE);
1448 if (di == NULL)
1449 return -2;
1450
1451 // Now find the svar_T index in sn_var_vals.
1452 for (idx = 0; idx < si->sn_var_vals.ga_len; ++idx)
1453 {
1454 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
1455
1456 if (sv->sv_tv == &di->di_tv)
1457 {
1458 if (check_writable && sv->sv_const)
1459 semsg(_(e_readonlyvar), name);
1460 return idx;
1461 }
1462 }
1463 return -1;
1464}
1465
1466/*
1467 * Find "name" in imported items of the current script/
1468 */
1469 imported_T *
1470find_imported(char_u *name, cctx_T *cctx)
1471{
Bram Moolenaar21b9e972020-01-26 19:26:46 +01001472 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001473 int idx;
1474
1475 if (cctx != NULL)
1476 for (idx = 0; idx < cctx->ctx_imports.ga_len; ++idx)
1477 {
1478 imported_T *import = ((imported_T *)cctx->ctx_imports.ga_data)
1479 + idx;
1480
1481 if (STRCMP(name, import->imp_name) == 0)
1482 return import;
1483 }
1484
1485 for (idx = 0; idx < si->sn_imports.ga_len; ++idx)
1486 {
1487 imported_T *import = ((imported_T *)si->sn_imports.ga_data) + idx;
1488
1489 if (STRCMP(name, import->imp_name) == 0)
1490 return import;
1491 }
1492 return NULL;
1493}
1494
1495/*
1496 * Generate an instruction to load script-local variable "name".
1497 */
1498 static int
1499compile_load_scriptvar(cctx_T *cctx, char_u *name)
1500{
Bram Moolenaar21b9e972020-01-26 19:26:46 +01001501 scriptitem_T *si = SCRIPT_ITEM(current_sctx.sc_sid);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001502 int idx = get_script_item_idx(current_sctx.sc_sid, name, FALSE);
1503 imported_T *import;
1504
1505 if (idx == -1)
1506 {
1507 // variable exists but is not in sn_var_vals: old style script.
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001508 return generate_OLDSCRIPT(cctx, ISN_LOADS, name, current_sctx.sc_sid,
1509 &t_any);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001510 }
1511 if (idx >= 0)
1512 {
1513 svar_T *sv = ((svar_T *)si->sn_var_vals.ga_data) + idx;
1514
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001515 generate_VIM9SCRIPT(cctx, ISN_LOADSCRIPT,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001516 current_sctx.sc_sid, idx, sv->sv_type);
1517 return OK;
1518 }
1519
1520 import = find_imported(name, cctx);
1521 if (import != NULL)
1522 {
1523 // TODO: check this is a variable, not a function
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001524 generate_VIM9SCRIPT(cctx, ISN_LOADSCRIPT,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001525 import->imp_sid,
1526 import->imp_var_vals_idx,
1527 import->imp_type);
1528 return OK;
1529 }
1530
1531 semsg(_("E1050: Item not found: %s"), name);
1532 return FAIL;
1533}
1534
1535/*
1536 * Compile a variable name into a load instruction.
1537 * "end" points to just after the name.
1538 * When "error" is FALSE do not give an error when not found.
1539 */
1540 static int
1541compile_load(char_u **arg, char_u *end, cctx_T *cctx, int error)
1542{
1543 type_T *type;
1544 char_u *name;
1545 int res = FAIL;
1546
1547 if (*(*arg + 1) == ':')
1548 {
1549 // load namespaced variable
1550 name = vim_strnsave(*arg + 2, end - (*arg + 2));
1551 if (name == NULL)
1552 return FAIL;
1553
1554 if (**arg == 'v')
1555 {
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01001556 res = generate_LOADV(cctx, name, error);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001557 }
1558 else if (**arg == 'g')
1559 {
1560 // Global variables can be defined later, thus we don't check if it
1561 // exists, give error at runtime.
1562 res = generate_LOAD(cctx, ISN_LOADG, 0, name, &t_any);
1563 }
1564 else if (**arg == 's')
1565 {
1566 res = compile_load_scriptvar(cctx, name);
1567 }
1568 else
1569 {
1570 semsg("Namespace not supported yet: %s", **arg);
1571 goto theend;
1572 }
1573 }
1574 else
1575 {
1576 size_t len = end - *arg;
1577 int idx;
1578 int gen_load = FALSE;
1579
1580 name = vim_strnsave(*arg, end - *arg);
1581 if (name == NULL)
1582 return FAIL;
1583
1584 idx = lookup_arg(*arg, len, cctx);
1585 if (idx >= 0)
1586 {
1587 if (cctx->ctx_ufunc->uf_arg_types != NULL)
1588 type = cctx->ctx_ufunc->uf_arg_types[idx];
1589 else
1590 type = &t_any;
1591
1592 // Arguments are located above the frame pointer.
1593 idx -= cctx->ctx_ufunc->uf_args.ga_len + STACK_FRAME_SIZE;
1594 if (cctx->ctx_ufunc->uf_va_name != NULL)
1595 --idx;
1596 gen_load = TRUE;
1597 }
1598 else if (lookup_vararg(*arg, len, cctx))
1599 {
1600 // varargs is always the last argument
1601 idx = -STACK_FRAME_SIZE - 1;
1602 type = cctx->ctx_ufunc->uf_va_type;
1603 gen_load = TRUE;
1604 }
1605 else
1606 {
1607 idx = lookup_local(*arg, len, cctx);
1608 if (idx >= 0)
1609 {
1610 type = (((lvar_T *)cctx->ctx_locals.ga_data) + idx)->lv_type;
1611 gen_load = TRUE;
1612 }
1613 else
1614 {
1615 if ((len == 4 && STRNCMP("true", *arg, 4) == 0)
1616 || (len == 5 && STRNCMP("false", *arg, 5) == 0))
1617 res = generate_PUSHBOOL(cctx, **arg == 't'
1618 ? VVAL_TRUE : VVAL_FALSE);
1619 else
1620 res = compile_load_scriptvar(cctx, name);
1621 }
1622 }
1623 if (gen_load)
1624 res = generate_LOAD(cctx, ISN_LOAD, idx, NULL, type);
1625 }
1626
1627 *arg = end;
1628
1629theend:
1630 if (res == FAIL && error)
1631 semsg(_(e_var_notfound), name);
1632 vim_free(name);
1633 return res;
1634}
1635
1636/*
1637 * Compile the argument expressions.
1638 * "arg" points to just after the "(" and is advanced to after the ")"
1639 */
1640 static int
1641compile_arguments(char_u **arg, cctx_T *cctx, int *argcount)
1642{
1643 char_u *p = *arg;
1644
1645 while (*p != NUL && *p != ')')
1646 {
1647 if (compile_expr1(&p, cctx) == FAIL)
1648 return FAIL;
1649 ++*argcount;
1650 if (*p == ',')
1651 p = skipwhite(p + 1);
1652 }
1653 if (*p != ')')
1654 {
1655 emsg(_(e_missing_close));
1656 return FAIL;
1657 }
1658 *arg = p + 1;
1659 return OK;
1660}
1661
1662/*
1663 * Compile a function call: name(arg1, arg2)
1664 * "arg" points to "name", "arg + varlen" to the "(".
1665 * "argcount_init" is 1 for "value->method()"
1666 * Instructions:
1667 * EVAL arg1
1668 * EVAL arg2
1669 * BCALL / DCALL / UCALL
1670 */
1671 static int
1672compile_call(char_u **arg, size_t varlen, cctx_T *cctx, int argcount_init)
1673{
1674 char_u *name = *arg;
Bram Moolenaar0b76ad52020-01-31 21:20:51 +01001675 char_u *p;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01001676 int argcount = argcount_init;
1677 char_u namebuf[100];
1678 ufunc_T *ufunc;
1679
1680 if (varlen >= sizeof(namebuf))
1681 {
1682 semsg(_("E1011: name too long: %s"), name);
1683 return FAIL;
1684 }
1685 vim_strncpy(namebuf, name, varlen);
1686
1687 *arg = skipwhite(*arg + varlen + 1);
1688 if (compile_arguments(arg, cctx, &argcount) == FAIL)
1689 return FAIL;
1690
1691 if (ASCII_ISLOWER(*name))
1692 {
1693 int idx;
1694
1695 // builtin function
1696 idx = find_internal_func(namebuf);
1697 if (idx >= 0)
1698 return generate_BCALL(cctx, idx, argcount);
1699 semsg(_(e_unknownfunc), namebuf);
1700 }
1701
1702 // User defined function or variable must start with upper case.
1703 if (!ASCII_ISUPPER(*name))
1704 {
1705 semsg(_("E1012: Invalid function name: %s"), namebuf);
1706 return FAIL;
1707 }
1708
1709 // If we can find the function by name generate the right call.
1710 ufunc = find_func(namebuf, cctx);
1711 if (ufunc != NULL)
1712 return generate_CALL(cctx, ufunc, argcount);
1713
1714 // If the name is a variable, load it and use PCALL.
1715 p = namebuf;
1716 if (compile_load(&p, namebuf + varlen, cctx, FALSE) == OK)
1717 return generate_PCALL(cctx, argcount, FALSE);
1718
1719 // The function may be defined only later. Need to figure out at runtime.
1720 return generate_UCALL(cctx, namebuf, argcount);
1721}
1722
1723// like NAMESPACE_CHAR but with 'a' and 'l'.
1724#define VIM9_NAMESPACE_CHAR (char_u *)"bgstvw"
1725
1726/*
1727 * Find the end of a variable or function name. Unlike find_name_end() this
1728 * does not recognize magic braces.
1729 * Return a pointer to just after the name. Equal to "arg" if there is no
1730 * valid name.
1731 */
1732 char_u *
1733to_name_end(char_u *arg)
1734{
1735 char_u *p;
1736
1737 // Quick check for valid starting character.
1738 if (!eval_isnamec1(*arg))
1739 return arg;
1740
1741 for (p = arg + 1; *p != NUL && eval_isnamec(*p); MB_PTR_ADV(p))
1742 // Include a namespace such as "s:var" and "v:var". But "n:" is not
1743 // and can be used in slice "[n:]".
1744 if (*p == ':' && (p != arg + 1
1745 || vim_strchr(VIM9_NAMESPACE_CHAR, *arg) == NULL))
1746 break;
1747 return p;
1748}
1749
1750/*
1751 * Like to_name_end() but also skip over a list or dict constant.
1752 */
1753 char_u *
1754to_name_const_end(char_u *arg)
1755{
1756 char_u *p = to_name_end(arg);
1757 typval_T rettv;
1758
1759 if (p == arg && *arg == '[')
1760 {
1761
1762 // Can be "[1, 2, 3]->Func()".
1763 if (get_list_tv(&p, &rettv, FALSE, FALSE) == FAIL)
1764 p = arg;
1765 }
1766 else if (p == arg && *arg == '#' && arg[1] == '{')
1767 {
1768 ++p;
1769 if (eval_dict(&p, &rettv, FALSE, TRUE) == FAIL)
1770 p = arg;
1771 }
1772 else if (p == arg && *arg == '{')
1773 {
1774 int ret = get_lambda_tv(&p, &rettv, FALSE);
1775
1776 if (ret == NOTDONE)
1777 ret = eval_dict(&p, &rettv, FALSE, FALSE);
1778 if (ret != OK)
1779 p = arg;
1780 }
1781
1782 return p;
1783}
1784
1785 static void
1786type_mismatch(type_T *expected, type_T *actual)
1787{
1788 char *tofree1, *tofree2;
1789
1790 semsg(_("E1013: type mismatch, expected %s but got %s"),
1791 type_name(expected, &tofree1), type_name(actual, &tofree2));
1792 vim_free(tofree1);
1793 vim_free(tofree2);
1794}
1795
1796/*
1797 * Check if the expected and actual types match.
1798 */
1799 static int
1800check_type(type_T *expected, type_T *actual, int give_msg)
1801{
1802 if (expected->tt_type != VAR_UNKNOWN)
1803 {
1804 if (expected->tt_type != actual->tt_type)
1805 {
1806 if (give_msg)
1807 type_mismatch(expected, actual);
1808 return FAIL;
1809 }
1810 if (expected->tt_type == VAR_DICT || expected->tt_type == VAR_LIST)
1811 {
1812 int ret = check_type(expected->tt_member, actual->tt_member,
1813 FALSE);
1814 if (ret == FAIL && give_msg)
1815 type_mismatch(expected, actual);
1816 return ret;
1817 }
1818 }
1819 return OK;
1820}
1821
1822/*
1823 * Check that
1824 * - "actual" is "expected" type or
1825 * - "actual" is a type that can be "expected" type: add a runtime check; or
1826 * - return FAIL.
1827 */
1828 static int
1829need_type(type_T *actual, type_T *expected, int offset, cctx_T *cctx)
1830{
1831 if (equal_type(actual, expected) || expected->tt_type == VAR_UNKNOWN)
1832 return OK;
1833 if (actual->tt_type != VAR_UNKNOWN)
1834 {
1835 type_mismatch(expected, actual);
1836 return FAIL;
1837 }
1838 generate_TYPECHECK(cctx, expected, offset);
1839 return OK;
1840}
1841
1842/*
1843 * parse a list: [expr, expr]
1844 * "*arg" points to the '['.
1845 */
1846 static int
1847compile_list(char_u **arg, cctx_T *cctx)
1848{
1849 char_u *p = skipwhite(*arg + 1);
1850 int count = 0;
1851
1852 while (*p != ']')
1853 {
1854 if (*p == NUL)
1855 return FAIL;
1856 if (compile_expr1(&p, cctx) == FAIL)
1857 break;
1858 ++count;
1859 if (*p == ',')
1860 ++p;
1861 p = skipwhite(p);
1862 }
1863 *arg = p + 1;
1864
1865 generate_NEWLIST(cctx, count);
1866 return OK;
1867}
1868
1869/*
1870 * parse a lambda: {arg, arg -> expr}
1871 * "*arg" points to the '{'.
1872 */
1873 static int
1874compile_lambda(char_u **arg, cctx_T *cctx)
1875{
1876 garray_T *instr = &cctx->ctx_instr;
1877 typval_T rettv;
1878 ufunc_T *ufunc;
1879
1880 // Get the funcref in "rettv".
1881 if (get_lambda_tv(arg, &rettv, TRUE) == FAIL)
1882 return FAIL;
1883 ufunc = rettv.vval.v_partial->pt_func;
1884
1885 // The function will have one line: "return {expr}".
1886 // Compile it into instructions.
1887 compile_def_function(ufunc, TRUE);
1888
1889 if (ufunc->uf_dfunc_idx >= 0)
1890 {
1891 if (ga_grow(instr, 1) == FAIL)
1892 return FAIL;
1893 generate_FUNCREF(cctx, ufunc->uf_dfunc_idx);
1894 return OK;
1895 }
1896 return FAIL;
1897}
1898
1899/*
1900 * Compile a lamda call: expr->{lambda}(args)
1901 * "arg" points to the "{".
1902 */
1903 static int
1904compile_lambda_call(char_u **arg, cctx_T *cctx)
1905{
1906 ufunc_T *ufunc;
1907 typval_T rettv;
1908 int argcount = 1;
1909 int ret = FAIL;
1910
1911 // Get the funcref in "rettv".
1912 if (get_lambda_tv(arg, &rettv, TRUE) == FAIL)
1913 return FAIL;
1914
1915 if (**arg != '(')
1916 {
1917 if (*skipwhite(*arg) == '(')
1918 semsg(_(e_nowhitespace));
1919 else
1920 semsg(_(e_missing_paren), "lambda");
1921 clear_tv(&rettv);
1922 return FAIL;
1923 }
1924
1925 // The function will have one line: "return {expr}".
1926 // Compile it into instructions.
1927 ufunc = rettv.vval.v_partial->pt_func;
1928 ++ufunc->uf_refcount;
1929 compile_def_function(ufunc, TRUE);
1930
1931 // compile the arguments
1932 *arg = skipwhite(*arg + 1);
1933 if (compile_arguments(arg, cctx, &argcount) == OK)
1934 // call the compiled function
1935 ret = generate_CALL(cctx, ufunc, argcount);
1936
1937 clear_tv(&rettv);
1938 return ret;
1939}
1940
1941/*
1942 * parse a dict: {'key': val} or #{key: val}
1943 * "*arg" points to the '{'.
1944 */
1945 static int
1946compile_dict(char_u **arg, cctx_T *cctx, int literal)
1947{
1948 garray_T *instr = &cctx->ctx_instr;
1949 int count = 0;
1950 dict_T *d = dict_alloc();
1951 dictitem_T *item;
1952
1953 if (d == NULL)
1954 return FAIL;
1955 *arg = skipwhite(*arg + 1);
1956 while (**arg != '}' && **arg != NUL)
1957 {
1958 char_u *key = NULL;
1959
1960 if (literal)
1961 {
1962 char_u *p = to_name_end(*arg);
1963
1964 if (p == *arg)
1965 {
1966 semsg(_("E1014: Invalid key: %s"), *arg);
1967 return FAIL;
1968 }
1969 key = vim_strnsave(*arg, p - *arg);
1970 if (generate_PUSHS(cctx, key) == FAIL)
1971 return FAIL;
1972 *arg = p;
1973 }
1974 else
1975 {
1976 isn_T *isn;
1977
1978 if (compile_expr1(arg, cctx) == FAIL)
1979 return FAIL;
1980 // TODO: check type is string
1981 isn = ((isn_T *)instr->ga_data) + instr->ga_len - 1;
1982 if (isn->isn_type == ISN_PUSHS)
1983 key = isn->isn_arg.string;
1984 }
1985
1986 // Check for duplicate keys, if using string keys.
1987 if (key != NULL)
1988 {
1989 item = dict_find(d, key, -1);
1990 if (item != NULL)
1991 {
1992 semsg(_(e_duplicate_key), key);
1993 goto failret;
1994 }
1995 item = dictitem_alloc(key);
1996 if (item != NULL)
1997 {
1998 item->di_tv.v_type = VAR_UNKNOWN;
1999 item->di_tv.v_lock = 0;
2000 if (dict_add(d, item) == FAIL)
2001 dictitem_free(item);
2002 }
2003 }
2004
2005 *arg = skipwhite(*arg);
2006 if (**arg != ':')
2007 {
2008 semsg(_(e_missing_dict_colon), *arg);
2009 return FAIL;
2010 }
2011
2012 *arg = skipwhite(*arg + 1);
2013 if (compile_expr1(arg, cctx) == FAIL)
2014 return FAIL;
2015 ++count;
2016
2017 if (**arg == '}')
2018 break;
2019 if (**arg != ',')
2020 {
2021 semsg(_(e_missing_dict_comma), *arg);
2022 goto failret;
2023 }
2024 *arg = skipwhite(*arg + 1);
2025 }
2026
2027 if (**arg != '}')
2028 {
2029 semsg(_(e_missing_dict_end), *arg);
2030 goto failret;
2031 }
2032 *arg = *arg + 1;
2033
2034 dict_unref(d);
2035 return generate_NEWDICT(cctx, count);
2036
2037failret:
2038 dict_unref(d);
2039 return FAIL;
2040}
2041
2042/*
2043 * Compile "&option".
2044 */
2045 static int
2046compile_get_option(char_u **arg, cctx_T *cctx)
2047{
2048 typval_T rettv;
2049 char_u *start = *arg;
2050 int ret;
2051
2052 // parse the option and get the current value to get the type.
2053 rettv.v_type = VAR_UNKNOWN;
2054 ret = get_option_tv(arg, &rettv, TRUE);
2055 if (ret == OK)
2056 {
2057 // include the '&' in the name, get_option_tv() expects it.
2058 char_u *name = vim_strnsave(start, *arg - start);
2059 type_T *type = rettv.v_type == VAR_NUMBER ? &t_number : &t_string;
2060
2061 ret = generate_LOAD(cctx, ISN_LOADOPT, 0, name, type);
2062 vim_free(name);
2063 }
2064 clear_tv(&rettv);
2065
2066 return ret;
2067}
2068
2069/*
2070 * Compile "$VAR".
2071 */
2072 static int
2073compile_get_env(char_u **arg, cctx_T *cctx)
2074{
2075 char_u *start = *arg;
2076 int len;
2077 int ret;
2078 char_u *name;
2079
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002080 ++*arg;
2081 len = get_env_len(arg);
2082 if (len == 0)
2083 {
2084 semsg(_(e_syntax_at), start - 1);
2085 return FAIL;
2086 }
2087
2088 // include the '$' in the name, get_env_tv() expects it.
2089 name = vim_strnsave(start, len + 1);
2090 ret = generate_LOAD(cctx, ISN_LOADENV, 0, name, &t_string);
2091 vim_free(name);
2092 return ret;
2093}
2094
2095/*
2096 * Compile "@r".
2097 */
2098 static int
2099compile_get_register(char_u **arg, cctx_T *cctx)
2100{
2101 int ret;
2102
2103 ++*arg;
2104 if (**arg == NUL)
2105 {
2106 semsg(_(e_syntax_at), *arg - 1);
2107 return FAIL;
2108 }
2109 if (!valid_yank_reg(**arg, TRUE))
2110 {
2111 emsg_invreg(**arg);
2112 return FAIL;
2113 }
2114 ret = generate_LOAD(cctx, ISN_LOADREG, **arg, NULL, &t_string);
2115 ++*arg;
2116 return ret;
2117}
2118
2119/*
2120 * Apply leading '!', '-' and '+' to constant "rettv".
2121 */
2122 static int
2123apply_leader(typval_T *rettv, char_u *start, char_u *end)
2124{
2125 char_u *p = end;
2126
2127 // this works from end to start
2128 while (p > start)
2129 {
2130 --p;
2131 if (*p == '-' || *p == '+')
2132 {
2133 // only '-' has an effect, for '+' we only check the type
2134#ifdef FEAT_FLOAT
2135 if (rettv->v_type == VAR_FLOAT)
2136 {
2137 if (*p == '-')
2138 rettv->vval.v_float = -rettv->vval.v_float;
2139 }
2140 else
2141#endif
2142 {
2143 varnumber_T val;
2144 int error = FALSE;
2145
2146 // tv_get_number_chk() accepts a string, but we don't want that
2147 // here
2148 if (check_not_string(rettv) == FAIL)
2149 return FAIL;
2150 val = tv_get_number_chk(rettv, &error);
2151 clear_tv(rettv);
2152 if (error)
2153 return FAIL;
2154 if (*p == '-')
2155 val = -val;
2156 rettv->v_type = VAR_NUMBER;
2157 rettv->vval.v_number = val;
2158 }
2159 }
2160 else
2161 {
2162 int v = tv2bool(rettv);
2163
2164 // '!' is permissive in the type.
2165 clear_tv(rettv);
2166 rettv->v_type = VAR_BOOL;
2167 rettv->vval.v_number = v ? VVAL_FALSE : VVAL_TRUE;
2168 }
2169 }
2170 return OK;
2171}
2172
2173/*
2174 * Recognize v: variables that are constants and set "rettv".
2175 */
2176 static void
2177get_vim_constant(char_u **arg, typval_T *rettv)
2178{
2179 if (STRNCMP(*arg, "v:true", 6) == 0)
2180 {
2181 rettv->v_type = VAR_BOOL;
2182 rettv->vval.v_number = VVAL_TRUE;
2183 *arg += 6;
2184 }
2185 else if (STRNCMP(*arg, "v:false", 7) == 0)
2186 {
2187 rettv->v_type = VAR_BOOL;
2188 rettv->vval.v_number = VVAL_FALSE;
2189 *arg += 7;
2190 }
2191 else if (STRNCMP(*arg, "v:null", 6) == 0)
2192 {
2193 rettv->v_type = VAR_SPECIAL;
2194 rettv->vval.v_number = VVAL_NULL;
2195 *arg += 6;
2196 }
2197 else if (STRNCMP(*arg, "v:none", 6) == 0)
2198 {
2199 rettv->v_type = VAR_SPECIAL;
2200 rettv->vval.v_number = VVAL_NONE;
2201 *arg += 6;
2202 }
2203}
2204
2205/*
2206 * Compile code to apply '-', '+' and '!'.
2207 */
2208 static int
2209compile_leader(cctx_T *cctx, char_u *start, char_u *end)
2210{
2211 char_u *p = end;
2212
2213 // this works from end to start
2214 while (p > start)
2215 {
2216 --p;
2217 if (*p == '-' || *p == '+')
2218 {
2219 int negate = *p == '-';
2220 isn_T *isn;
2221
2222 // TODO: check type
2223 while (p > start && (p[-1] == '-' || p[-1] == '+'))
2224 {
2225 --p;
2226 if (*p == '-')
2227 negate = !negate;
2228 }
2229 // only '-' has an effect, for '+' we only check the type
2230 if (negate)
2231 isn = generate_instr(cctx, ISN_NEGATENR);
2232 else
2233 isn = generate_instr(cctx, ISN_CHECKNR);
2234 if (isn == NULL)
2235 return FAIL;
2236 }
2237 else
2238 {
2239 int invert = TRUE;
2240
2241 while (p > start && p[-1] == '!')
2242 {
2243 --p;
2244 invert = !invert;
2245 }
2246 if (generate_2BOOL(cctx, invert) == FAIL)
2247 return FAIL;
2248 }
2249 }
2250 return OK;
2251}
2252
2253/*
2254 * Compile whatever comes after "name" or "name()".
2255 */
2256 static int
2257compile_subscript(
2258 char_u **arg,
2259 cctx_T *cctx,
2260 char_u **start_leader,
2261 char_u *end_leader)
2262{
2263 for (;;)
2264 {
2265 if (**arg == '(')
2266 {
2267 int argcount = 0;
2268
2269 // funcref(arg)
2270 *arg = skipwhite(*arg + 1);
2271 if (compile_arguments(arg, cctx, &argcount) == FAIL)
2272 return FAIL;
2273 if (generate_PCALL(cctx, argcount, TRUE) == FAIL)
2274 return FAIL;
2275 }
2276 else if (**arg == '-' && (*arg)[1] == '>')
2277 {
2278 char_u *p;
2279
2280 // something->method()
2281 // Apply the '!', '-' and '+' first:
2282 // -1.0->func() works like (-1.0)->func()
2283 if (compile_leader(cctx, *start_leader, end_leader) == FAIL)
2284 return FAIL;
2285 *start_leader = end_leader; // don't apply again later
2286
2287 *arg = skipwhite(*arg + 2);
2288 if (**arg == '{')
2289 {
2290 // lambda call: list->{lambda}
2291 if (compile_lambda_call(arg, cctx) == FAIL)
2292 return FAIL;
2293 }
2294 else
2295 {
2296 // method call: list->method()
2297 for (p = *arg; eval_isnamec1(*p); ++p)
2298 ;
2299 if (*p != '(')
2300 {
2301 semsg(_(e_missing_paren), arg);
2302 return FAIL;
2303 }
2304 // TODO: base value may not be the first argument
2305 if (compile_call(arg, p - *arg, cctx, 1) == FAIL)
2306 return FAIL;
2307 }
2308 }
2309 else if (**arg == '[')
2310 {
2311 // list index: list[123]
2312 // TODO: more arguments
2313 // TODO: dict member dict['name']
2314 *arg = skipwhite(*arg + 1);
2315 if (compile_expr1(arg, cctx) == FAIL)
2316 return FAIL;
2317
2318 if (**arg != ']')
2319 {
2320 emsg(_(e_missbrac));
2321 return FAIL;
2322 }
2323 *arg = skipwhite(*arg + 1);
2324
2325 if (generate_instr_drop(cctx, ISN_INDEX, 1) == FAIL)
2326 return FAIL;
2327 }
2328 else if (**arg == '.' && (*arg)[1] != '.')
2329 {
2330 char_u *p;
2331
2332 ++*arg;
2333 p = *arg;
2334 // dictionary member: dict.name
2335 if (eval_isnamec1(*p))
2336 while (eval_isnamec(*p))
2337 MB_PTR_ADV(p);
2338 if (p == *arg)
2339 {
2340 semsg(_(e_syntax_at), *arg);
2341 return FAIL;
2342 }
2343 // TODO: check type is dict
2344 if (generate_MEMBER(cctx, *arg, p - *arg) == FAIL)
2345 return FAIL;
2346 *arg = p;
2347 }
2348 else
2349 break;
2350 }
2351
2352 // TODO - see handle_subscript():
2353 // Turn "dict.Func" into a partial for "Func" bound to "dict".
2354 // Don't do this when "Func" is already a partial that was bound
2355 // explicitly (pt_auto is FALSE).
2356
2357 return OK;
2358}
2359
2360/*
2361 * Compile an expression at "*p" and add instructions to "instr".
2362 * "p" is advanced until after the expression, skipping white space.
2363 *
2364 * This is the equivalent of eval1(), eval2(), etc.
2365 */
2366
2367/*
2368 * number number constant
2369 * 0zFFFFFFFF Blob constant
2370 * "string" string constant
2371 * 'string' literal string constant
2372 * &option-name option value
2373 * @r register contents
2374 * identifier variable value
2375 * function() function call
2376 * $VAR environment variable
2377 * (expression) nested expression
2378 * [expr, expr] List
2379 * {key: val, key: val} Dictionary
2380 * #{key: val, key: val} Dictionary with literal keys
2381 *
2382 * Also handle:
2383 * ! in front logical NOT
2384 * - in front unary minus
2385 * + in front unary plus (ignored)
2386 * trailing (arg) funcref/partial call
2387 * trailing [] subscript in String or List
2388 * trailing .name entry in Dictionary
2389 * trailing ->name() method call
2390 */
2391 static int
2392compile_expr7(char_u **arg, cctx_T *cctx)
2393{
2394 typval_T rettv;
2395 char_u *start_leader, *end_leader;
2396 int ret = OK;
2397
2398 /*
2399 * Skip '!', '-' and '+' characters. They are handled later.
2400 */
2401 start_leader = *arg;
2402 while (**arg == '!' || **arg == '-' || **arg == '+')
2403 *arg = skipwhite(*arg + 1);
2404 end_leader = *arg;
2405
2406 rettv.v_type = VAR_UNKNOWN;
2407 switch (**arg)
2408 {
2409 /*
2410 * Number constant.
2411 */
2412 case '0': // also for blob starting with 0z
2413 case '1':
2414 case '2':
2415 case '3':
2416 case '4':
2417 case '5':
2418 case '6':
2419 case '7':
2420 case '8':
2421 case '9':
2422 case '.': if (get_number_tv(arg, &rettv, TRUE, FALSE) == FAIL)
2423 return FAIL;
2424 break;
2425
2426 /*
2427 * String constant: "string".
2428 */
2429 case '"': if (get_string_tv(arg, &rettv, TRUE) == FAIL)
2430 return FAIL;
2431 break;
2432
2433 /*
2434 * Literal string constant: 'str''ing'.
2435 */
2436 case '\'': if (get_lit_string_tv(arg, &rettv, TRUE) == FAIL)
2437 return FAIL;
2438 break;
2439
2440 /*
2441 * Constant Vim variable.
2442 */
2443 case 'v': get_vim_constant(arg, &rettv);
2444 ret = NOTDONE;
2445 break;
2446
2447 /*
2448 * List: [expr, expr]
2449 */
2450 case '[': ret = compile_list(arg, cctx);
2451 break;
2452
2453 /*
2454 * Dictionary: #{key: val, key: val}
2455 */
2456 case '#': if ((*arg)[1] == '{')
2457 {
2458 ++*arg;
2459 ret = compile_dict(arg, cctx, TRUE);
2460 }
2461 else
2462 ret = NOTDONE;
2463 break;
2464
2465 /*
2466 * Lambda: {arg, arg -> expr}
2467 * Dictionary: {'key': val, 'key': val}
2468 */
2469 case '{': {
2470 char_u *start = skipwhite(*arg + 1);
2471
2472 // Find out what comes after the arguments.
2473 ret = get_function_args(&start, '-', NULL,
2474 NULL, NULL, NULL, TRUE);
2475 if (ret != FAIL && *start == '>')
2476 ret = compile_lambda(arg, cctx);
2477 else
2478 ret = compile_dict(arg, cctx, FALSE);
2479 }
2480 break;
2481
2482 /*
2483 * Option value: &name
2484 */
2485 case '&': ret = compile_get_option(arg, cctx);
2486 break;
2487
2488 /*
2489 * Environment variable: $VAR.
2490 */
2491 case '$': ret = compile_get_env(arg, cctx);
2492 break;
2493
2494 /*
2495 * Register contents: @r.
2496 */
2497 case '@': ret = compile_get_register(arg, cctx);
2498 break;
2499 /*
2500 * nested expression: (expression).
2501 */
2502 case '(': *arg = skipwhite(*arg + 1);
2503 ret = compile_expr1(arg, cctx); // recursive!
2504 *arg = skipwhite(*arg);
2505 if (**arg == ')')
2506 ++*arg;
2507 else if (ret == OK)
2508 {
2509 emsg(_(e_missing_close));
2510 ret = FAIL;
2511 }
2512 break;
2513
2514 default: ret = NOTDONE;
2515 break;
2516 }
2517 if (ret == FAIL)
2518 return FAIL;
2519
2520 if (rettv.v_type != VAR_UNKNOWN)
2521 {
2522 // apply the '!', '-' and '+' before the constant
2523 if (apply_leader(&rettv, start_leader, end_leader) == FAIL)
2524 {
2525 clear_tv(&rettv);
2526 return FAIL;
2527 }
2528 start_leader = end_leader; // don't apply again below
2529
2530 // push constant
2531 switch (rettv.v_type)
2532 {
2533 case VAR_BOOL:
2534 generate_PUSHBOOL(cctx, rettv.vval.v_number);
2535 break;
2536 case VAR_SPECIAL:
2537 generate_PUSHSPEC(cctx, rettv.vval.v_number);
2538 break;
2539 case VAR_NUMBER:
2540 generate_PUSHNR(cctx, rettv.vval.v_number);
2541 break;
2542#ifdef FEAT_FLOAT
2543 case VAR_FLOAT:
2544 generate_PUSHF(cctx, rettv.vval.v_float);
2545 break;
2546#endif
2547 case VAR_BLOB:
2548 generate_PUSHBLOB(cctx, rettv.vval.v_blob);
2549 rettv.vval.v_blob = NULL;
2550 break;
2551 case VAR_STRING:
2552 generate_PUSHS(cctx, rettv.vval.v_string);
2553 rettv.vval.v_string = NULL;
2554 break;
2555 default:
2556 iemsg("constant type missing");
2557 return FAIL;
2558 }
2559 }
2560 else if (ret == NOTDONE)
2561 {
2562 char_u *p;
2563 int r;
2564
2565 if (!eval_isnamec1(**arg))
2566 {
2567 semsg(_("E1015: Name expected: %s"), *arg);
2568 return FAIL;
2569 }
2570
2571 // "name" or "name()"
2572 p = to_name_end(*arg);
2573 if (*p == '(')
2574 r = compile_call(arg, p - *arg, cctx, 0);
2575 else
2576 r = compile_load(arg, p, cctx, TRUE);
2577 if (r == FAIL)
2578 return FAIL;
2579 }
2580
2581 if (compile_subscript(arg, cctx, &start_leader, end_leader) == FAIL)
2582 return FAIL;
2583
2584 // Now deal with prefixed '-', '+' and '!', if not done already.
2585 return compile_leader(cctx, start_leader, end_leader);
2586}
2587
2588/*
2589 * * number multiplication
2590 * / number division
2591 * % number modulo
2592 */
2593 static int
2594compile_expr6(char_u **arg, cctx_T *cctx)
2595{
2596 char_u *op;
2597
2598 // get the first variable
2599 if (compile_expr7(arg, cctx) == FAIL)
2600 return FAIL;
2601
2602 /*
2603 * Repeat computing, until no "*", "/" or "%" is following.
2604 */
2605 for (;;)
2606 {
2607 op = skipwhite(*arg);
2608 if (*op != '*' && *op != '/' && *op != '%')
2609 break;
2610 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(op[1]))
2611 {
2612 char_u buf[3];
2613
2614 vim_strncpy(buf, op, 1);
2615 semsg(_(e_white_both), buf);
2616 }
2617 *arg = skipwhite(op + 1);
2618
2619 // get the second variable
2620 if (compile_expr7(arg, cctx) == FAIL)
2621 return FAIL;
2622
2623 generate_two_op(cctx, op);
2624 }
2625
2626 return OK;
2627}
2628
2629/*
2630 * + number addition
2631 * - number subtraction
2632 * .. string concatenation
2633 */
2634 static int
2635compile_expr5(char_u **arg, cctx_T *cctx)
2636{
2637 char_u *op;
2638 int oplen;
2639
2640 // get the first variable
2641 if (compile_expr6(arg, cctx) == FAIL)
2642 return FAIL;
2643
2644 /*
2645 * Repeat computing, until no "+", "-" or ".." is following.
2646 */
2647 for (;;)
2648 {
2649 op = skipwhite(*arg);
2650 if (*op != '+' && *op != '-' && !(*op == '.' && (*(*arg + 1) == '.')))
2651 break;
2652 oplen = (*op == '.' ? 2 : 1);
2653
2654 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(op[oplen]))
2655 {
2656 char_u buf[3];
2657
2658 vim_strncpy(buf, op, oplen);
2659 semsg(_(e_white_both), buf);
2660 }
2661
2662 *arg = skipwhite(op + oplen);
2663
2664 // get the second variable
2665 if (compile_expr6(arg, cctx) == FAIL)
2666 return FAIL;
2667
2668 if (*op == '.')
2669 {
2670 if (may_generate_2STRING(-2, cctx) == FAIL
2671 || may_generate_2STRING(-1, cctx) == FAIL)
2672 return FAIL;
2673 generate_instr_drop(cctx, ISN_CONCAT, 1);
2674 }
2675 else
2676 generate_two_op(cctx, op);
2677 }
2678
2679 return OK;
2680}
2681
2682/*
2683 * expr5a == expr5b
2684 * expr5a =~ expr5b
2685 * expr5a != expr5b
2686 * expr5a !~ expr5b
2687 * expr5a > expr5b
2688 * expr5a >= expr5b
2689 * expr5a < expr5b
2690 * expr5a <= expr5b
2691 * expr5a is expr5b
2692 * expr5a isnot expr5b
2693 *
2694 * Produces instructions:
2695 * EVAL expr5a Push result of "expr5a"
2696 * EVAL expr5b Push result of "expr5b"
2697 * COMPARE one of the compare instructions
2698 */
2699 static int
2700compile_expr4(char_u **arg, cctx_T *cctx)
2701{
2702 exptype_T type = EXPR_UNKNOWN;
2703 char_u *p;
2704 int len = 2;
2705 int i;
2706 int type_is = FALSE;
2707
2708 // get the first variable
2709 if (compile_expr5(arg, cctx) == FAIL)
2710 return FAIL;
2711
2712 p = skipwhite(*arg);
2713 switch (p[0])
2714 {
2715 case '=': if (p[1] == '=')
2716 type = EXPR_EQUAL;
2717 else if (p[1] == '~')
2718 type = EXPR_MATCH;
2719 break;
2720 case '!': if (p[1] == '=')
2721 type = EXPR_NEQUAL;
2722 else if (p[1] == '~')
2723 type = EXPR_NOMATCH;
2724 break;
2725 case '>': if (p[1] != '=')
2726 {
2727 type = EXPR_GREATER;
2728 len = 1;
2729 }
2730 else
2731 type = EXPR_GEQUAL;
2732 break;
2733 case '<': if (p[1] != '=')
2734 {
2735 type = EXPR_SMALLER;
2736 len = 1;
2737 }
2738 else
2739 type = EXPR_SEQUAL;
2740 break;
2741 case 'i': if (p[1] == 's')
2742 {
2743 // "is" and "isnot"; but not a prefix of a name
2744 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
2745 len = 5;
2746 i = p[len];
2747 if (!isalnum(i) && i != '_')
2748 {
2749 type = len == 2 ? EXPR_IS : EXPR_ISNOT;
2750 type_is = TRUE;
2751 }
2752 }
2753 break;
2754 }
2755
2756 /*
2757 * If there is a comparative operator, use it.
2758 */
2759 if (type != EXPR_UNKNOWN)
2760 {
2761 int ic = FALSE; // Default: do not ignore case
2762
2763 if (type_is && (p[len] == '?' || p[len] == '#'))
2764 {
2765 semsg(_(e_invexpr2), *arg);
2766 return FAIL;
2767 }
2768 // extra question mark appended: ignore case
2769 if (p[len] == '?')
2770 {
2771 ic = TRUE;
2772 ++len;
2773 }
2774 // extra '#' appended: match case (ignored)
2775 else if (p[len] == '#')
2776 ++len;
2777 // nothing appended: match case
2778
2779 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[len]))
2780 {
2781 char_u buf[7];
2782
2783 vim_strncpy(buf, p, len);
2784 semsg(_(e_white_both), buf);
2785 }
2786
2787 // get the second variable
2788 *arg = skipwhite(p + len);
2789 if (compile_expr5(arg, cctx) == FAIL)
2790 return FAIL;
2791
2792 generate_COMPARE(cctx, type, ic);
2793 }
2794
2795 return OK;
2796}
2797
2798/*
2799 * Compile || or &&.
2800 */
2801 static int
2802compile_and_or(char_u **arg, cctx_T *cctx, char *op)
2803{
2804 char_u *p = skipwhite(*arg);
2805 int opchar = *op;
2806
2807 if (p[0] == opchar && p[1] == opchar)
2808 {
2809 garray_T *instr = &cctx->ctx_instr;
2810 garray_T end_ga;
2811
2812 /*
2813 * Repeat until there is no following "||" or "&&"
2814 */
2815 ga_init2(&end_ga, sizeof(int), 10);
2816 while (p[0] == opchar && p[1] == opchar)
2817 {
2818 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[2]))
2819 semsg(_(e_white_both), op);
2820
2821 if (ga_grow(&end_ga, 1) == FAIL)
2822 {
2823 ga_clear(&end_ga);
2824 return FAIL;
2825 }
2826 *(((int *)end_ga.ga_data) + end_ga.ga_len) = instr->ga_len;
2827 ++end_ga.ga_len;
2828 generate_JUMP(cctx, opchar == '|'
2829 ? JUMP_AND_KEEP_IF_TRUE : JUMP_AND_KEEP_IF_FALSE, 0);
2830
2831 // eval the next expression
2832 *arg = skipwhite(p + 2);
2833 if ((opchar == '|' ? compile_expr3(arg, cctx)
2834 : compile_expr4(arg, cctx)) == FAIL)
2835 {
2836 ga_clear(&end_ga);
2837 return FAIL;
2838 }
2839 p = skipwhite(*arg);
2840 }
2841
2842 // Fill in the end label in all jumps.
2843 while (end_ga.ga_len > 0)
2844 {
2845 isn_T *isn;
2846
2847 --end_ga.ga_len;
2848 isn = ((isn_T *)instr->ga_data)
2849 + *(((int *)end_ga.ga_data) + end_ga.ga_len);
2850 isn->isn_arg.jump.jump_where = instr->ga_len;
2851 }
2852 ga_clear(&end_ga);
2853 }
2854
2855 return OK;
2856}
2857
2858/*
2859 * expr4a && expr4a && expr4a logical AND
2860 *
2861 * Produces instructions:
2862 * EVAL expr4a Push result of "expr4a"
2863 * JUMP_AND_KEEP_IF_FALSE end
2864 * EVAL expr4b Push result of "expr4b"
2865 * JUMP_AND_KEEP_IF_FALSE end
2866 * EVAL expr4c Push result of "expr4c"
2867 * end:
2868 */
2869 static int
2870compile_expr3(char_u **arg, cctx_T *cctx)
2871{
2872 // get the first variable
2873 if (compile_expr4(arg, cctx) == FAIL)
2874 return FAIL;
2875
2876 // || and && work almost the same
2877 return compile_and_or(arg, cctx, "&&");
2878}
2879
2880/*
2881 * expr3a || expr3b || expr3c logical OR
2882 *
2883 * Produces instructions:
2884 * EVAL expr3a Push result of "expr3a"
2885 * JUMP_AND_KEEP_IF_TRUE end
2886 * EVAL expr3b Push result of "expr3b"
2887 * JUMP_AND_KEEP_IF_TRUE end
2888 * EVAL expr3c Push result of "expr3c"
2889 * end:
2890 */
2891 static int
2892compile_expr2(char_u **arg, cctx_T *cctx)
2893{
2894 // eval the first expression
2895 if (compile_expr3(arg, cctx) == FAIL)
2896 return FAIL;
2897
2898 // || and && work almost the same
2899 return compile_and_or(arg, cctx, "||");
2900}
2901
2902/*
2903 * Toplevel expression: expr2 ? expr1a : expr1b
2904 *
2905 * Produces instructions:
2906 * EVAL expr2 Push result of "expr"
2907 * JUMP_IF_FALSE alt jump if false
2908 * EVAL expr1a
2909 * JUMP_ALWAYS end
2910 * alt: EVAL expr1b
2911 * end:
2912 */
2913 static int
2914compile_expr1(char_u **arg, cctx_T *cctx)
2915{
2916 char_u *p;
2917
2918 // evaluate the first expression
2919 if (compile_expr2(arg, cctx) == FAIL)
2920 return FAIL;
2921
2922 p = skipwhite(*arg);
2923 if (*p == '?')
2924 {
2925 garray_T *instr = &cctx->ctx_instr;
2926 garray_T *stack = &cctx->ctx_type_stack;
2927 int alt_idx = instr->ga_len;
2928 int end_idx;
2929 isn_T *isn;
2930 type_T *type1;
2931 type_T *type2;
2932
2933 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[1]))
2934 semsg(_(e_white_both), "?");
2935
2936 generate_JUMP(cctx, JUMP_IF_FALSE, 0);
2937
2938 // evaluate the second expression; any type is accepted
2939 *arg = skipwhite(p + 1);
Bram Moolenaara6d53682020-01-28 23:04:06 +01002940 if (compile_expr1(arg, cctx) == FAIL)
2941 return FAIL;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002942
2943 // remember the type and drop it
2944 --stack->ga_len;
2945 type1 = ((type_T **)stack->ga_data)[stack->ga_len];
2946
2947 end_idx = instr->ga_len;
2948 generate_JUMP(cctx, JUMP_ALWAYS, 0);
2949
2950 // jump here from JUMP_IF_FALSE
2951 isn = ((isn_T *)instr->ga_data) + alt_idx;
2952 isn->isn_arg.jump.jump_where = instr->ga_len;
2953
2954 // Check for the ":".
2955 p = skipwhite(*arg);
2956 if (*p != ':')
2957 {
2958 emsg(_(e_missing_colon));
2959 return FAIL;
2960 }
2961 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[1]))
2962 semsg(_(e_white_both), ":");
2963
2964 // evaluate the third expression
2965 *arg = skipwhite(p + 1);
Bram Moolenaara6d53682020-01-28 23:04:06 +01002966 if (compile_expr1(arg, cctx) == FAIL)
2967 return FAIL;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01002968
2969 // If the types differ, the result has a more generic type.
2970 type2 = ((type_T **)stack->ga_data)[stack->ga_len - 1];
2971 common_type(type1, type2, type2);
2972
2973 // jump here from JUMP_ALWAYS
2974 isn = ((isn_T *)instr->ga_data) + end_idx;
2975 isn->isn_arg.jump.jump_where = instr->ga_len;
2976 }
2977 return OK;
2978}
2979
2980/*
2981 * compile "return [expr]"
2982 */
2983 static char_u *
2984compile_return(char_u *arg, int set_return_type, cctx_T *cctx)
2985{
2986 char_u *p = arg;
2987 garray_T *stack = &cctx->ctx_type_stack;
2988 type_T *stack_type;
2989
2990 if (*p != NUL && *p != '|' && *p != '\n')
2991 {
2992 // compile return argument into instructions
2993 if (compile_expr1(&p, cctx) == FAIL)
2994 return NULL;
2995
2996 stack_type = ((type_T **)stack->ga_data)[stack->ga_len - 1];
2997 if (set_return_type)
2998 cctx->ctx_ufunc->uf_ret_type = stack_type;
2999 else if (need_type(stack_type, cctx->ctx_ufunc->uf_ret_type, -1, cctx)
3000 == FAIL)
3001 return NULL;
3002 }
3003 else
3004 {
3005 if (set_return_type)
3006 cctx->ctx_ufunc->uf_ret_type = &t_void;
3007 else if (cctx->ctx_ufunc->uf_ret_type->tt_type != VAR_VOID)
3008 {
3009 emsg(_("E1003: Missing return value"));
3010 return NULL;
3011 }
3012
3013 // No argument, return zero.
3014 generate_PUSHNR(cctx, 0);
3015 }
3016
3017 if (generate_instr(cctx, ISN_RETURN) == NULL)
3018 return NULL;
3019
3020 // "return val | endif" is possible
3021 return skipwhite(p);
3022}
3023
3024/*
3025 * Return the length of an assignment operator, or zero if there isn't one.
3026 */
3027 int
3028assignment_len(char_u *p, int *heredoc)
3029{
3030 if (*p == '=')
3031 {
3032 if (p[1] == '<' && p[2] == '<')
3033 {
3034 *heredoc = TRUE;
3035 return 3;
3036 }
3037 return 1;
3038 }
3039 if (vim_strchr((char_u *)"+-*/%", *p) != NULL && p[1] == '=')
3040 return 2;
3041 if (STRNCMP(p, "..=", 3) == 0)
3042 return 3;
3043 return 0;
3044}
3045
3046// words that cannot be used as a variable
3047static char *reserved[] = {
3048 "true",
3049 "false",
3050 NULL
3051};
3052
3053/*
3054 * Get a line for "=<<".
3055 * Return a pointer to the line in allocated memory.
3056 * Return NULL for end-of-file or some error.
3057 */
3058 static char_u *
3059heredoc_getline(
3060 int c UNUSED,
3061 void *cookie,
3062 int indent UNUSED,
3063 int do_concat UNUSED)
3064{
3065 cctx_T *cctx = (cctx_T *)cookie;
3066
3067 if (cctx->ctx_lnum == cctx->ctx_ufunc->uf_lines.ga_len)
3068 NULL;
3069 ++cctx->ctx_lnum;
3070 return vim_strsave(((char_u **)cctx->ctx_ufunc->uf_lines.ga_data)
3071 [cctx->ctx_lnum]);
3072}
3073
3074/*
3075 * compile "let var [= expr]", "const var = expr" and "var = expr"
3076 * "arg" points to "var".
3077 */
3078 static char_u *
3079compile_assignment(char_u *arg, exarg_T *eap, cmdidx_T cmdidx, cctx_T *cctx)
3080{
3081 char_u *p;
3082 char_u *ret = NULL;
3083 int var_count = 0;
3084 int semicolon = 0;
3085 size_t varlen;
3086 garray_T *instr = &cctx->ctx_instr;
3087 int idx = -1;
3088 char_u *op;
3089 int option = FALSE;
3090 int opt_type;
3091 int opt_flags = 0;
3092 int global = FALSE;
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003093 int env = FALSE;
3094 int reg = FALSE;
3095 int vimvaridx = -1;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003096 int script = FALSE;
3097 int oplen = 0;
3098 int heredoc = FALSE;
3099 type_T *type;
3100 lvar_T *lvar;
3101 char_u *name;
3102 char_u *sp;
3103 int has_type = FALSE;
3104 int is_decl = cmdidx == CMD_let || cmdidx == CMD_const;
3105 int instr_count = -1;
3106
3107 p = skip_var_list(arg, FALSE, &var_count, &semicolon);
3108 if (p == NULL)
3109 return NULL;
3110 if (var_count > 0)
3111 {
3112 // TODO: let [var, var] = list
3113 emsg("Cannot handle a list yet");
3114 return NULL;
3115 }
3116
3117 varlen = p - arg;
3118 name = vim_strnsave(arg, (int)varlen);
3119 if (name == NULL)
3120 return NULL;
3121
3122 if (*arg == '&')
3123 {
3124 int cc;
3125 long numval;
3126 char_u *stringval = NULL;
3127
3128 option = TRUE;
3129 if (cmdidx == CMD_const)
3130 {
3131 emsg(_(e_const_option));
3132 return NULL;
3133 }
3134 if (is_decl)
3135 {
3136 semsg(_("E1052: Cannot declare an option: %s"), arg);
3137 goto theend;
3138 }
3139 p = arg;
3140 p = find_option_end(&p, &opt_flags);
3141 if (p == NULL)
3142 {
3143 emsg(_(e_letunexp));
3144 return NULL;
3145 }
3146 cc = *p;
3147 *p = NUL;
3148 opt_type = get_option_value(arg + 1, &numval, &stringval, opt_flags);
3149 *p = cc;
3150 if (opt_type == -3)
3151 {
3152 semsg(_(e_unknown_option), *arg);
3153 return NULL;
3154 }
3155 if (opt_type == -2 || opt_type == 0)
3156 type = &t_string;
3157 else
3158 type = &t_number; // both number and boolean option
3159 }
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003160 else if (*arg == '$')
3161 {
3162 env = TRUE;
3163 if (is_decl)
3164 {
3165 semsg(_("E1065: Cannot declare an environment variable: %s"), name);
3166 goto theend;
3167 }
3168 }
3169 else if (*arg == '@')
3170 {
3171 if (!valid_yank_reg(arg[1], TRUE))
3172 {
3173 emsg_invreg(arg[1]);
3174 return FAIL;
3175 }
3176 reg = TRUE;
3177 if (is_decl)
3178 {
3179 semsg(_("E1066: Cannot declare a register: %s"), name);
3180 goto theend;
3181 }
3182 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003183 else if (STRNCMP(arg, "g:", 2) == 0)
3184 {
3185 global = TRUE;
3186 if (is_decl)
3187 {
3188 semsg(_("E1016: Cannot declare a global variable: %s"), name);
3189 goto theend;
3190 }
3191 }
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003192 else if (STRNCMP(arg, "v:", 2) == 0)
3193 {
3194 vimvaridx = find_vim_var(name + 2);
3195 if (vimvaridx < 0)
3196 {
3197 semsg(_(e_var_notfound), arg);
3198 goto theend;
3199 }
3200 if (is_decl)
3201 {
3202 semsg(_("E1064: Cannot declare a v: variable: %s"), name);
3203 goto theend;
3204 }
3205 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003206 else
3207 {
3208 for (idx = 0; reserved[idx] != NULL; ++idx)
3209 if (STRCMP(reserved[idx], name) == 0)
3210 {
3211 semsg(_("E1034: Cannot use reserved name %s"), name);
3212 goto theend;
3213 }
3214
3215 idx = lookup_local(arg, varlen, cctx);
3216 if (idx >= 0)
3217 {
3218 if (is_decl)
3219 {
3220 semsg(_("E1017: Variable already declared: %s"), name);
3221 goto theend;
3222 }
3223 else
3224 {
3225 lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
3226 if (lvar->lv_const)
3227 {
3228 semsg(_("E1018: Cannot assign to a constant: %s"), name);
3229 goto theend;
3230 }
3231 }
3232 }
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003233 else if ((STRNCMP(arg, "s:", 2) == 0
3234 ? lookup_script(arg + 2, varlen - 2)
3235 : lookup_script(arg, varlen)) == OK)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003236 {
3237 script = TRUE;
3238 if (is_decl)
3239 {
3240 semsg(_("E1054: Variable already declared in the script: %s"),
3241 name);
3242 goto theend;
3243 }
3244 }
3245 }
3246
3247 if (!option)
3248 {
3249 if (is_decl && *p == ':')
3250 {
3251 // parse optional type: "let var: type = expr"
3252 p = skipwhite(p + 1);
3253 type = parse_type(&p, cctx->ctx_type_list);
3254 if (type == NULL)
3255 goto theend;
3256 has_type = TRUE;
3257 }
3258 else if (idx < 0)
3259 {
3260 // global and new local default to "any" type
3261 type = &t_any;
3262 }
3263 else
3264 {
3265 lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
3266 type = lvar->lv_type;
3267 }
3268 }
3269
3270 sp = p;
3271 p = skipwhite(p);
3272 op = p;
3273 oplen = assignment_len(p, &heredoc);
3274 if (oplen > 0 && (!VIM_ISWHITE(*sp) || !VIM_ISWHITE(op[oplen])))
3275 {
3276 char_u buf[4];
3277
3278 vim_strncpy(buf, op, oplen);
3279 semsg(_(e_white_both), buf);
3280 }
3281
3282 if (oplen == 3 && !heredoc && !global && type->tt_type != VAR_STRING
3283 && type->tt_type != VAR_UNKNOWN)
3284 {
3285 emsg("E1019: Can only concatenate to string");
3286 goto theend;
3287 }
3288
3289 // +=, /=, etc. require an existing variable
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003290 if (idx < 0 && !global && !env && !reg && !option)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003291 {
3292 if (oplen > 1 && !heredoc)
3293 {
3294 semsg(_("E1020: cannot use an operator on a new variable: %s"),
3295 name);
3296 goto theend;
3297 }
3298
3299 // new local variable
3300 idx = reserve_local(cctx, arg, varlen, cmdidx == CMD_const, type);
3301 if (idx < 0)
3302 goto theend;
3303 }
3304
3305 if (heredoc)
3306 {
3307 list_T *l;
3308 listitem_T *li;
3309
3310 // [let] varname =<< [trim] {end}
3311 eap->getline = heredoc_getline;
3312 eap->cookie = cctx;
3313 l = heredoc_get(eap, op + 3);
3314
3315 // Push each line and the create the list.
3316 for (li = l->lv_first; li != NULL; li = li->li_next)
3317 {
3318 generate_PUSHS(cctx, li->li_tv.vval.v_string);
3319 li->li_tv.vval.v_string = NULL;
3320 }
3321 generate_NEWLIST(cctx, l->lv_len);
3322 type = &t_list_string;
3323 list_free(l);
3324 p += STRLEN(p);
3325 }
3326 else if (oplen > 0)
3327 {
3328 // for "+=", "*=", "..=" etc. first load the current value
3329 if (*op != '=')
3330 {
3331 if (option)
Bram Moolenaara6d53682020-01-28 23:04:06 +01003332 // TODO: check the option exists
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003333 generate_LOAD(cctx, ISN_LOADOPT, 0, name + 1, type);
3334 else if (global)
3335 generate_LOAD(cctx, ISN_LOADG, 0, name + 2, type);
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003336 else if (env)
3337 // Include $ in the name here
3338 generate_LOAD(cctx, ISN_LOADENV, 0, name, type);
3339 else if (reg)
3340 generate_LOAD(cctx, ISN_LOADREG, arg[1], NULL, &t_string);
3341 else if (vimvaridx >= 0)
3342 generate_LOADV(cctx, name + 2, TRUE);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003343 else
3344 generate_LOAD(cctx, ISN_LOAD, idx, NULL, type);
3345 }
3346
3347 // compile the expression
3348 instr_count = instr->ga_len;
3349 p = skipwhite(p + oplen);
3350 if (compile_expr1(&p, cctx) == FAIL)
3351 goto theend;
3352
3353 if (idx >= 0 && (is_decl || !has_type))
3354 {
3355 garray_T *stack = &cctx->ctx_type_stack;
3356 type_T *stacktype =
3357 ((type_T **)stack->ga_data)[stack->ga_len - 1];
3358
3359 lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + idx;
3360 if (!has_type)
3361 {
3362 if (stacktype->tt_type == VAR_VOID)
3363 {
3364 emsg(_("E1031: Cannot use void value"));
3365 goto theend;
3366 }
3367 else
3368 lvar->lv_type = stacktype;
3369 }
3370 else
3371 if (check_type(lvar->lv_type, stacktype, TRUE) == FAIL)
3372 goto theend;
3373 }
3374 }
3375 else if (cmdidx == CMD_const)
3376 {
3377 emsg(_("E1021: const requires a value"));
3378 goto theend;
3379 }
3380 else if (!has_type || option)
3381 {
3382 emsg(_("E1022: type or initialization required"));
3383 goto theend;
3384 }
3385 else
3386 {
3387 // variables are always initialized
3388 // TODO: support more types
3389 if (ga_grow(instr, 1) == FAIL)
3390 goto theend;
3391 if (type->tt_type == VAR_STRING)
3392 generate_PUSHS(cctx, vim_strsave((char_u *)""));
3393 else
3394 generate_PUSHNR(cctx, 0);
3395 }
3396
3397 if (oplen > 0 && *op != '=')
3398 {
3399 type_T *expected = &t_number;
3400 garray_T *stack = &cctx->ctx_type_stack;
3401 type_T *stacktype;
3402
3403 // TODO: if type is known use float or any operation
3404
3405 if (*op == '.')
3406 expected = &t_string;
3407 stacktype = ((type_T **)stack->ga_data)[stack->ga_len - 1];
3408 if (need_type(stacktype, expected, -1, cctx) == FAIL)
3409 goto theend;
3410
3411 if (*op == '.')
3412 generate_instr_drop(cctx, ISN_CONCAT, 1);
3413 else
3414 {
3415 isn_T *isn = generate_instr_drop(cctx, ISN_OPNR, 1);
3416
3417 if (isn == NULL)
3418 goto theend;
3419 switch (*op)
3420 {
3421 case '+': isn->isn_arg.op.op_type = EXPR_ADD; break;
3422 case '-': isn->isn_arg.op.op_type = EXPR_SUB; break;
3423 case '*': isn->isn_arg.op.op_type = EXPR_MULT; break;
3424 case '/': isn->isn_arg.op.op_type = EXPR_DIV; break;
3425 case '%': isn->isn_arg.op.op_type = EXPR_REM; break;
3426 }
3427 }
3428 }
3429
3430 if (option)
3431 generate_STOREOPT(cctx, name + 1, opt_flags);
3432 else if (global)
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003433 // include g: with the name, easier to execute that way
3434 generate_STORE(cctx, ISN_STOREG, 0, name);
3435 else if (env)
3436 generate_STORE(cctx, ISN_STOREENV, 0, name + 1);
3437 else if (reg)
3438 generate_STORE(cctx, ISN_STOREREG, name[1], NULL);
3439 else if (vimvaridx >= 0)
3440 generate_STORE(cctx, ISN_STOREV, vimvaridx, NULL);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003441 else if (script)
3442 {
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003443 char_u *rawname = name + (name[1] == ':' ? 2 : 0);
3444
3445 idx = get_script_item_idx(current_sctx.sc_sid, rawname, TRUE);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003446 // TODO: specific type
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01003447 if (idx < 0)
3448 generate_OLDSCRIPT(cctx, ISN_STORES, rawname,
3449 current_sctx.sc_sid, &t_any);
3450 else
3451 generate_VIM9SCRIPT(cctx, ISN_STORESCRIPT,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003452 current_sctx.sc_sid, idx, &t_any);
3453 }
3454 else
3455 {
3456 isn_T *isn = ((isn_T *)instr->ga_data) + instr->ga_len - 1;
3457
3458 // optimization: turn "var = 123" from ISN_PUSHNR + ISN_STORE into
3459 // ISN_STORENR
3460 if (instr->ga_len == instr_count + 1 && isn->isn_type == ISN_PUSHNR)
3461 {
3462 varnumber_T val = isn->isn_arg.number;
3463 garray_T *stack = &cctx->ctx_type_stack;
3464
3465 isn->isn_type = ISN_STORENR;
3466 isn->isn_arg.storenr.str_idx = idx;
3467 isn->isn_arg.storenr.str_val = val;
3468 if (stack->ga_len > 0)
3469 --stack->ga_len;
3470 }
3471 else
3472 generate_STORE(cctx, ISN_STORE, idx, NULL);
3473 }
3474 ret = p;
3475
3476theend:
3477 vim_free(name);
3478 return ret;
3479}
3480
3481/*
3482 * Compile an :import command.
3483 */
3484 static char_u *
3485compile_import(char_u *arg, cctx_T *cctx)
3486{
3487 return handle_import(arg, &cctx->ctx_imports, 0);
3488}
3489
3490/*
3491 * generate a jump to the ":endif"/":endfor"/":endwhile"/":finally"/":endtry".
3492 */
3493 static int
3494compile_jump_to_end(endlabel_T **el, jumpwhen_T when, cctx_T *cctx)
3495{
3496 garray_T *instr = &cctx->ctx_instr;
3497 endlabel_T *endlabel = ALLOC_CLEAR_ONE(endlabel_T);
3498
3499 if (endlabel == NULL)
3500 return FAIL;
3501 endlabel->el_next = *el;
3502 *el = endlabel;
3503 endlabel->el_end_label = instr->ga_len;
3504
3505 generate_JUMP(cctx, when, 0);
3506 return OK;
3507}
3508
3509 static void
3510compile_fill_jump_to_end(endlabel_T **el, cctx_T *cctx)
3511{
3512 garray_T *instr = &cctx->ctx_instr;
3513
3514 while (*el != NULL)
3515 {
3516 endlabel_T *cur = (*el);
3517 isn_T *isn;
3518
3519 isn = ((isn_T *)instr->ga_data) + cur->el_end_label;
3520 isn->isn_arg.jump.jump_where = instr->ga_len;
3521 *el = cur->el_next;
3522 vim_free(cur);
3523 }
3524}
3525
3526/*
3527 * Create a new scope and set up the generic items.
3528 */
3529 static scope_T *
3530new_scope(cctx_T *cctx, scopetype_T type)
3531{
3532 scope_T *scope = ALLOC_CLEAR_ONE(scope_T);
3533
3534 if (scope == NULL)
3535 return NULL;
3536 scope->se_outer = cctx->ctx_scope;
3537 cctx->ctx_scope = scope;
3538 scope->se_type = type;
3539 scope->se_local_count = cctx->ctx_locals.ga_len;
3540 return scope;
3541}
3542
3543/*
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003544 * Evaluate an expression that is a constant:
3545 * has(arg)
3546 *
3547 * Also handle:
3548 * ! in front logical NOT
3549 *
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003550 * Return FAIL if the expression is not a constant.
3551 */
3552 static int
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003553evaluate_const_expr7(char_u **arg, cctx_T *cctx UNUSED, typval_T *tv)
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003554{
3555 typval_T argvars[2];
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003556 char_u *start_leader, *end_leader;
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003557
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003558 /*
3559 * Skip '!' characters. They are handled later.
3560 */
3561 start_leader = *arg;
3562 while (**arg == '!')
3563 *arg = skipwhite(*arg + 1);
3564 end_leader = *arg;
3565
3566 /*
3567 * Recognize only has() for now.
3568 */
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003569 if (STRNCMP("has(", *arg, 4) != 0)
3570 return FAIL;
3571 *arg = skipwhite(*arg + 4);
3572
3573 if (**arg == '"')
3574 {
3575 if (get_string_tv(arg, tv, TRUE) == FAIL)
3576 return FAIL;
3577 }
3578 else if (**arg == '\'')
3579 {
3580 if (get_lit_string_tv(arg, tv, TRUE) == FAIL)
3581 return FAIL;
3582 }
3583 else
3584 return FAIL;
3585
3586 *arg = skipwhite(*arg);
3587 if (**arg != ')')
3588 return FAIL;
3589 *arg = skipwhite(*arg + 1);
3590
3591 argvars[0] = *tv;
3592 argvars[1].v_type = VAR_UNKNOWN;
3593 tv->v_type = VAR_NUMBER;
3594 tv->vval.v_number = 0;
3595 f_has(argvars, tv);
3596 clear_tv(&argvars[0]);
3597
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003598 while (start_leader < end_leader)
3599 {
3600 if (*start_leader == '!')
3601 tv->vval.v_number = !tv->vval.v_number;
3602 ++start_leader;
3603 }
3604
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003605 return OK;
3606}
3607
3608static int evaluate_const_expr3(char_u **arg, cctx_T *cctx, typval_T *tv);
3609
3610/*
3611 * Compile constant || or &&.
3612 */
3613 static int
3614evaluate_const_and_or(char_u **arg, cctx_T *cctx, char *op, typval_T *tv)
3615{
3616 char_u *p = skipwhite(*arg);
3617 int opchar = *op;
3618
3619 if (p[0] == opchar && p[1] == opchar)
3620 {
3621 int val = tv2bool(tv);
3622
3623 /*
3624 * Repeat until there is no following "||" or "&&"
3625 */
3626 while (p[0] == opchar && p[1] == opchar)
3627 {
3628 typval_T tv2;
3629
3630 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[2]))
3631 return FAIL;
3632
3633 // eval the next expression
3634 *arg = skipwhite(p + 2);
3635 tv2.v_type = VAR_UNKNOWN;
3636 if ((opchar == '|' ? evaluate_const_expr3(arg, cctx, &tv2)
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003637 : evaluate_const_expr7(arg, cctx, &tv2)) == FAIL)
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003638 {
3639 clear_tv(&tv2);
3640 return FAIL;
3641 }
3642 if ((opchar == '&') == val)
3643 {
3644 // false || tv2 or true && tv2: use tv2
3645 clear_tv(tv);
3646 *tv = tv2;
3647 val = tv2bool(tv);
3648 }
3649 else
3650 clear_tv(&tv2);
3651 p = skipwhite(*arg);
3652 }
3653 }
3654
3655 return OK;
3656}
3657
3658/*
3659 * Evaluate an expression that is a constant: expr4 && expr4 && expr4
3660 * Return FAIL if the expression is not a constant.
3661 */
3662 static int
3663evaluate_const_expr3(char_u **arg, cctx_T *cctx, typval_T *tv)
3664{
3665 // evaluate the first expression
Bram Moolenaar7f829ca2020-01-31 22:12:41 +01003666 if (evaluate_const_expr7(arg, cctx, tv) == FAIL)
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003667 return FAIL;
3668
3669 // || and && work almost the same
3670 return evaluate_const_and_or(arg, cctx, "&&", tv);
3671}
3672
3673/*
3674 * Evaluate an expression that is a constant: expr3 || expr3 || expr3
3675 * Return FAIL if the expression is not a constant.
3676 */
3677 static int
3678evaluate_const_expr2(char_u **arg, cctx_T *cctx, typval_T *tv)
3679{
3680 // evaluate the first expression
3681 if (evaluate_const_expr3(arg, cctx, tv) == FAIL)
3682 return FAIL;
3683
3684 // || and && work almost the same
3685 return evaluate_const_and_or(arg, cctx, "||", tv);
3686}
3687
3688/*
3689 * Evaluate an expression that is a constant: expr2 ? expr1 : expr1
3690 * E.g. for "has('feature')".
3691 * This does not produce error messages. "tv" should be cleared afterwards.
3692 * Return FAIL if the expression is not a constant.
3693 */
3694 static int
3695evaluate_const_expr1(char_u **arg, cctx_T *cctx, typval_T *tv)
3696{
3697 char_u *p;
3698
3699 // evaluate the first expression
3700 if (evaluate_const_expr2(arg, cctx, tv) == FAIL)
3701 return FAIL;
3702
3703 p = skipwhite(*arg);
3704 if (*p == '?')
3705 {
3706 int val = tv2bool(tv);
3707 typval_T tv2;
3708
3709 if (!VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[1]))
3710 return FAIL;
3711
3712 // evaluate the second expression; any type is accepted
3713 clear_tv(tv);
3714 *arg = skipwhite(p + 1);
3715 if (evaluate_const_expr1(arg, cctx, tv) == FAIL)
3716 return FAIL;
3717
3718 // Check for the ":".
3719 p = skipwhite(*arg);
3720 if (*p != ':' || !VIM_ISWHITE(**arg) || !VIM_ISWHITE(p[1]))
3721 return FAIL;
3722
3723 // evaluate the third expression
3724 *arg = skipwhite(p + 1);
3725 tv2.v_type = VAR_UNKNOWN;
3726 if (evaluate_const_expr1(arg, cctx, &tv2) == FAIL)
3727 {
3728 clear_tv(&tv2);
3729 return FAIL;
3730 }
3731 if (val)
3732 {
3733 // use the expr after "?"
3734 clear_tv(&tv2);
3735 }
3736 else
3737 {
3738 // use the expr after ":"
3739 clear_tv(tv);
3740 *tv = tv2;
3741 }
3742 }
3743 return OK;
3744}
3745
3746/*
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003747 * compile "if expr"
3748 *
3749 * "if expr" Produces instructions:
3750 * EVAL expr Push result of "expr"
3751 * JUMP_IF_FALSE end
3752 * ... body ...
3753 * end:
3754 *
3755 * "if expr | else" Produces instructions:
3756 * EVAL expr Push result of "expr"
3757 * JUMP_IF_FALSE else
3758 * ... body ...
3759 * JUMP_ALWAYS end
3760 * else:
3761 * ... body ...
3762 * end:
3763 *
3764 * "if expr1 | elseif expr2 | else" Produces instructions:
3765 * EVAL expr Push result of "expr"
3766 * JUMP_IF_FALSE elseif
3767 * ... body ...
3768 * JUMP_ALWAYS end
3769 * elseif:
3770 * EVAL expr Push result of "expr"
3771 * JUMP_IF_FALSE else
3772 * ... body ...
3773 * JUMP_ALWAYS end
3774 * else:
3775 * ... body ...
3776 * end:
3777 */
3778 static char_u *
3779compile_if(char_u *arg, cctx_T *cctx)
3780{
3781 char_u *p = arg;
3782 garray_T *instr = &cctx->ctx_instr;
3783 scope_T *scope;
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003784 typval_T tv;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003785
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003786 // compile "expr"; if we know it evaluates to FALSE skip the block
3787 tv.v_type = VAR_UNKNOWN;
3788 if (evaluate_const_expr1(&p, cctx, &tv) == OK)
3789 cctx->ctx_skip = tv2bool(&tv) ? FALSE : TRUE;
3790 else
3791 cctx->ctx_skip = MAYBE;
3792 clear_tv(&tv);
3793 if (cctx->ctx_skip == MAYBE)
3794 {
3795 p = arg;
3796 if (compile_expr1(&p, cctx) == FAIL)
3797 return NULL;
3798 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003799
3800 scope = new_scope(cctx, IF_SCOPE);
3801 if (scope == NULL)
3802 return NULL;
3803
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003804 if (cctx->ctx_skip == MAYBE)
3805 {
3806 // "where" is set when ":elseif", "else" or ":endif" is found
3807 scope->se_u.se_if.is_if_label = instr->ga_len;
3808 generate_JUMP(cctx, JUMP_IF_FALSE, 0);
3809 }
3810 else
3811 scope->se_u.se_if.is_if_label = -1;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003812
3813 return p;
3814}
3815
3816 static char_u *
3817compile_elseif(char_u *arg, cctx_T *cctx)
3818{
3819 char_u *p = arg;
3820 garray_T *instr = &cctx->ctx_instr;
3821 isn_T *isn;
3822 scope_T *scope = cctx->ctx_scope;
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003823 typval_T tv;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003824
3825 if (scope == NULL || scope->se_type != IF_SCOPE)
3826 {
3827 emsg(_(e_elseif_without_if));
3828 return NULL;
3829 }
3830 cctx->ctx_locals.ga_len = scope->se_local_count;
3831
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003832 if (cctx->ctx_skip != TRUE)
3833 {
3834 if (compile_jump_to_end(&scope->se_u.se_if.is_end_label,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003835 JUMP_ALWAYS, cctx) == FAIL)
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003836 return NULL;
3837 // previous "if" or "elseif" jumps here
3838 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
3839 isn->isn_arg.jump.jump_where = instr->ga_len;
3840 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003841
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003842 // compile "expr"; if we know it evaluates to FALSE skip the block
3843 tv.v_type = VAR_UNKNOWN;
3844 if (evaluate_const_expr1(&p, cctx, &tv) == OK)
3845 cctx->ctx_skip = tv2bool(&tv) ? FALSE : TRUE;
3846 else
3847 cctx->ctx_skip = MAYBE;
3848 clear_tv(&tv);
3849 if (cctx->ctx_skip == MAYBE)
3850 {
3851 p = arg;
3852 if (compile_expr1(&p, cctx) == FAIL)
3853 return NULL;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003854
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003855 // "where" is set when ":elseif", "else" or ":endif" is found
3856 scope->se_u.se_if.is_if_label = instr->ga_len;
3857 generate_JUMP(cctx, JUMP_IF_FALSE, 0);
3858 }
3859 else
3860 scope->se_u.se_if.is_if_label = -1;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003861
3862 return p;
3863}
3864
3865 static char_u *
3866compile_else(char_u *arg, cctx_T *cctx)
3867{
3868 char_u *p = arg;
3869 garray_T *instr = &cctx->ctx_instr;
3870 isn_T *isn;
3871 scope_T *scope = cctx->ctx_scope;
3872
3873 if (scope == NULL || scope->se_type != IF_SCOPE)
3874 {
3875 emsg(_(e_else_without_if));
3876 return NULL;
3877 }
3878 cctx->ctx_locals.ga_len = scope->se_local_count;
3879
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003880 // jump from previous block to the end, unless the else block is empty
3881 if (cctx->ctx_skip == MAYBE)
3882 {
3883 if (compile_jump_to_end(&scope->se_u.se_if.is_end_label,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003884 JUMP_ALWAYS, cctx) == FAIL)
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003885 return NULL;
3886 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003887
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003888 if (cctx->ctx_skip != TRUE)
3889 {
3890 if (scope->se_u.se_if.is_if_label >= 0)
3891 {
3892 // previous "if" or "elseif" jumps here
3893 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
3894 isn->isn_arg.jump.jump_where = instr->ga_len;
3895 }
3896 }
3897
3898 if (cctx->ctx_skip != MAYBE)
3899 cctx->ctx_skip = !cctx->ctx_skip;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003900
3901 return p;
3902}
3903
3904 static char_u *
3905compile_endif(char_u *arg, cctx_T *cctx)
3906{
3907 scope_T *scope = cctx->ctx_scope;
3908 ifscope_T *ifscope;
3909 garray_T *instr = &cctx->ctx_instr;
3910 isn_T *isn;
3911
3912 if (scope == NULL || scope->se_type != IF_SCOPE)
3913 {
3914 emsg(_(e_endif_without_if));
3915 return NULL;
3916 }
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01003917 ifscope = &scope->se_u.se_if;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003918 cctx->ctx_scope = scope->se_outer;
3919 cctx->ctx_locals.ga_len = scope->se_local_count;
3920
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003921 if (scope->se_u.se_if.is_if_label >= 0)
3922 {
3923 // previous "if" or "elseif" jumps here
3924 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_if.is_if_label;
3925 isn->isn_arg.jump.jump_where = instr->ga_len;
3926 }
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003927 // Fill in the "end" label in jumps at the end of the blocks.
3928 compile_fill_jump_to_end(&ifscope->is_end_label, cctx);
Bram Moolenaara259d8d2020-01-31 20:10:50 +01003929 cctx->ctx_skip = FALSE;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01003930
3931 vim_free(scope);
3932 return arg;
3933}
3934
3935/*
3936 * compile "for var in expr"
3937 *
3938 * Produces instructions:
3939 * PUSHNR -1
3940 * STORE loop-idx Set index to -1
3941 * EVAL expr Push result of "expr"
3942 * top: FOR loop-idx, end Increment index, use list on bottom of stack
3943 * - if beyond end, jump to "end"
3944 * - otherwise get item from list and push it
3945 * STORE var Store item in "var"
3946 * ... body ...
3947 * JUMP top Jump back to repeat
3948 * end: DROP Drop the result of "expr"
3949 *
3950 */
3951 static char_u *
3952compile_for(char_u *arg, cctx_T *cctx)
3953{
3954 char_u *p;
3955 size_t varlen;
3956 garray_T *instr = &cctx->ctx_instr;
3957 garray_T *stack = &cctx->ctx_type_stack;
3958 scope_T *scope;
3959 int loop_idx; // index of loop iteration variable
3960 int var_idx; // index of "var"
3961 type_T *vartype;
3962
3963 // TODO: list of variables: "for [key, value] in dict"
3964 // parse "var"
3965 for (p = arg; eval_isnamec1(*p); ++p)
3966 ;
3967 varlen = p - arg;
3968 var_idx = lookup_local(arg, varlen, cctx);
3969 if (var_idx >= 0)
3970 {
3971 semsg(_("E1023: variable already defined: %s"), arg);
3972 return NULL;
3973 }
3974
3975 // consume "in"
3976 p = skipwhite(p);
3977 if (STRNCMP(p, "in", 2) != 0 || !VIM_ISWHITE(p[2]))
3978 {
3979 emsg(_(e_missing_in));
3980 return NULL;
3981 }
3982 p = skipwhite(p + 2);
3983
3984
3985 scope = new_scope(cctx, FOR_SCOPE);
3986 if (scope == NULL)
3987 return NULL;
3988
3989 // Reserve a variable to store the loop iteration counter.
3990 loop_idx = reserve_local(cctx, (char_u *)"", 0, FALSE, &t_number);
3991 if (loop_idx < 0)
3992 return NULL;
3993
3994 // Reserve a variable to store "var"
3995 var_idx = reserve_local(cctx, arg, varlen, FALSE, &t_any);
3996 if (var_idx < 0)
3997 return NULL;
3998
3999 generate_STORENR(cctx, loop_idx, -1);
4000
4001 // compile "expr", it remains on the stack until "endfor"
4002 arg = p;
4003 if (compile_expr1(&arg, cctx) == FAIL)
4004 return NULL;
4005
4006 // now we know the type of "var"
4007 vartype = ((type_T **)stack->ga_data)[stack->ga_len - 1];
4008 if (vartype->tt_type != VAR_LIST)
4009 {
4010 emsg(_("E1024: need a List to iterate over"));
4011 return NULL;
4012 }
4013 if (vartype->tt_member->tt_type != VAR_UNKNOWN)
4014 {
4015 lvar_T *lvar = ((lvar_T *)cctx->ctx_locals.ga_data) + var_idx;
4016
4017 lvar->lv_type = vartype->tt_member;
4018 }
4019
4020 // "for_end" is set when ":endfor" is found
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004021 scope->se_u.se_for.fs_top_label = instr->ga_len;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004022
4023 generate_FOR(cctx, loop_idx);
4024 generate_STORE(cctx, ISN_STORE, var_idx, NULL);
4025
4026 return arg;
4027}
4028
4029/*
4030 * compile "endfor"
4031 */
4032 static char_u *
4033compile_endfor(char_u *arg, cctx_T *cctx)
4034{
4035 garray_T *instr = &cctx->ctx_instr;
4036 scope_T *scope = cctx->ctx_scope;
4037 forscope_T *forscope;
4038 isn_T *isn;
4039
4040 if (scope == NULL || scope->se_type != FOR_SCOPE)
4041 {
4042 emsg(_(e_for));
4043 return NULL;
4044 }
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004045 forscope = &scope->se_u.se_for;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004046 cctx->ctx_scope = scope->se_outer;
4047 cctx->ctx_locals.ga_len = scope->se_local_count;
4048
4049 // At end of ":for" scope jump back to the FOR instruction.
4050 generate_JUMP(cctx, JUMP_ALWAYS, forscope->fs_top_label);
4051
4052 // Fill in the "end" label in the FOR statement so it can jump here
4053 isn = ((isn_T *)instr->ga_data) + forscope->fs_top_label;
4054 isn->isn_arg.forloop.for_end = instr->ga_len;
4055
4056 // Fill in the "end" label any BREAK statements
4057 compile_fill_jump_to_end(&forscope->fs_end_label, cctx);
4058
4059 // Below the ":for" scope drop the "expr" list from the stack.
4060 if (generate_instr_drop(cctx, ISN_DROP, 1) == NULL)
4061 return NULL;
4062
4063 vim_free(scope);
4064
4065 return arg;
4066}
4067
4068/*
4069 * compile "while expr"
4070 *
4071 * Produces instructions:
4072 * top: EVAL expr Push result of "expr"
4073 * JUMP_IF_FALSE end jump if false
4074 * ... body ...
4075 * JUMP top Jump back to repeat
4076 * end:
4077 *
4078 */
4079 static char_u *
4080compile_while(char_u *arg, cctx_T *cctx)
4081{
4082 char_u *p = arg;
4083 garray_T *instr = &cctx->ctx_instr;
4084 scope_T *scope;
4085
4086 scope = new_scope(cctx, WHILE_SCOPE);
4087 if (scope == NULL)
4088 return NULL;
4089
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004090 scope->se_u.se_while.ws_top_label = instr->ga_len;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004091
4092 // compile "expr"
4093 if (compile_expr1(&p, cctx) == FAIL)
4094 return NULL;
4095
4096 // "while_end" is set when ":endwhile" is found
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004097 if (compile_jump_to_end(&scope->se_u.se_while.ws_end_label,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004098 JUMP_IF_FALSE, cctx) == FAIL)
4099 return FAIL;
4100
4101 return p;
4102}
4103
4104/*
4105 * compile "endwhile"
4106 */
4107 static char_u *
4108compile_endwhile(char_u *arg, cctx_T *cctx)
4109{
4110 scope_T *scope = cctx->ctx_scope;
4111
4112 if (scope == NULL || scope->se_type != WHILE_SCOPE)
4113 {
4114 emsg(_(e_while));
4115 return NULL;
4116 }
4117 cctx->ctx_scope = scope->se_outer;
4118 cctx->ctx_locals.ga_len = scope->se_local_count;
4119
4120 // At end of ":for" scope jump back to the FOR instruction.
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004121 generate_JUMP(cctx, JUMP_ALWAYS, scope->se_u.se_while.ws_top_label);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004122
4123 // Fill in the "end" label in the WHILE statement so it can jump here.
4124 // And in any jumps for ":break"
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004125 compile_fill_jump_to_end(&scope->se_u.se_while.ws_end_label, cctx);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004126
4127 vim_free(scope);
4128
4129 return arg;
4130}
4131
4132/*
4133 * compile "continue"
4134 */
4135 static char_u *
4136compile_continue(char_u *arg, cctx_T *cctx)
4137{
4138 scope_T *scope = cctx->ctx_scope;
4139
4140 for (;;)
4141 {
4142 if (scope == NULL)
4143 {
4144 emsg(_(e_continue));
4145 return NULL;
4146 }
4147 if (scope->se_type == FOR_SCOPE || scope->se_type == WHILE_SCOPE)
4148 break;
4149 scope = scope->se_outer;
4150 }
4151
4152 // Jump back to the FOR or WHILE instruction.
4153 generate_JUMP(cctx, JUMP_ALWAYS,
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004154 scope->se_type == FOR_SCOPE ? scope->se_u.se_for.fs_top_label
4155 : scope->se_u.se_while.ws_top_label);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004156 return arg;
4157}
4158
4159/*
4160 * compile "break"
4161 */
4162 static char_u *
4163compile_break(char_u *arg, cctx_T *cctx)
4164{
4165 scope_T *scope = cctx->ctx_scope;
4166 endlabel_T **el;
4167
4168 for (;;)
4169 {
4170 if (scope == NULL)
4171 {
4172 emsg(_(e_break));
4173 return NULL;
4174 }
4175 if (scope->se_type == FOR_SCOPE || scope->se_type == WHILE_SCOPE)
4176 break;
4177 scope = scope->se_outer;
4178 }
4179
4180 // Jump to the end of the FOR or WHILE loop.
4181 if (scope->se_type == FOR_SCOPE)
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004182 el = &scope->se_u.se_for.fs_end_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004183 else
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004184 el = &scope->se_u.se_while.ws_end_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004185 if (compile_jump_to_end(el, JUMP_ALWAYS, cctx) == FAIL)
4186 return FAIL;
4187
4188 return arg;
4189}
4190
4191/*
4192 * compile "{" start of block
4193 */
4194 static char_u *
4195compile_block(char_u *arg, cctx_T *cctx)
4196{
4197 if (new_scope(cctx, BLOCK_SCOPE) == NULL)
4198 return NULL;
4199 return skipwhite(arg + 1);
4200}
4201
4202/*
4203 * compile end of block: drop one scope
4204 */
4205 static void
4206compile_endblock(cctx_T *cctx)
4207{
4208 scope_T *scope = cctx->ctx_scope;
4209
4210 cctx->ctx_scope = scope->se_outer;
4211 cctx->ctx_locals.ga_len = scope->se_local_count;
4212 vim_free(scope);
4213}
4214
4215/*
4216 * compile "try"
4217 * Creates a new scope for the try-endtry, pointing to the first catch and
4218 * finally.
4219 * Creates another scope for the "try" block itself.
4220 * TRY instruction sets up exception handling at runtime.
4221 *
4222 * "try"
4223 * TRY -> catch1, -> finally push trystack entry
4224 * ... try block
4225 * "throw {exception}"
4226 * EVAL {exception}
4227 * THROW create exception
4228 * ... try block
4229 * " catch {expr}"
4230 * JUMP -> finally
4231 * catch1: PUSH exeception
4232 * EVAL {expr}
4233 * MATCH
4234 * JUMP nomatch -> catch2
4235 * CATCH remove exception
4236 * ... catch block
4237 * " catch"
4238 * JUMP -> finally
4239 * catch2: CATCH remove exception
4240 * ... catch block
4241 * " finally"
4242 * finally:
4243 * ... finally block
4244 * " endtry"
4245 * ENDTRY pop trystack entry, may rethrow
4246 */
4247 static char_u *
4248compile_try(char_u *arg, cctx_T *cctx)
4249{
4250 garray_T *instr = &cctx->ctx_instr;
4251 scope_T *try_scope;
4252 scope_T *scope;
4253
4254 // scope that holds the jumps that go to catch/finally/endtry
4255 try_scope = new_scope(cctx, TRY_SCOPE);
4256 if (try_scope == NULL)
4257 return NULL;
4258
4259 // "catch" is set when the first ":catch" is found.
4260 // "finally" is set when ":finally" or ":endtry" is found
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004261 try_scope->se_u.se_try.ts_try_label = instr->ga_len;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004262 if (generate_instr(cctx, ISN_TRY) == NULL)
4263 return NULL;
4264
4265 // scope for the try block itself
4266 scope = new_scope(cctx, BLOCK_SCOPE);
4267 if (scope == NULL)
4268 return NULL;
4269
4270 return arg;
4271}
4272
4273/*
4274 * compile "catch {expr}"
4275 */
4276 static char_u *
4277compile_catch(char_u *arg, cctx_T *cctx UNUSED)
4278{
4279 scope_T *scope = cctx->ctx_scope;
4280 garray_T *instr = &cctx->ctx_instr;
4281 char_u *p;
4282 isn_T *isn;
4283
4284 // end block scope from :try or :catch
4285 if (scope != NULL && scope->se_type == BLOCK_SCOPE)
4286 compile_endblock(cctx);
4287 scope = cctx->ctx_scope;
4288
4289 // Error if not in a :try scope
4290 if (scope == NULL || scope->se_type != TRY_SCOPE)
4291 {
4292 emsg(_(e_catch));
4293 return NULL;
4294 }
4295
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004296 if (scope->se_u.se_try.ts_caught_all)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004297 {
4298 emsg(_("E1033: catch unreachable after catch-all"));
4299 return NULL;
4300 }
4301
4302 // Jump from end of previous block to :finally or :endtry
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004303 if (compile_jump_to_end(&scope->se_u.se_try.ts_end_label,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004304 JUMP_ALWAYS, cctx) == FAIL)
4305 return NULL;
4306
4307 // End :try or :catch scope: set value in ISN_TRY instruction
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004308 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004309 if (isn->isn_arg.try.try_catch == 0)
4310 isn->isn_arg.try.try_catch = instr->ga_len;
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004311 if (scope->se_u.se_try.ts_catch_label != 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004312 {
4313 // Previous catch without match jumps here
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004314 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_catch_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004315 isn->isn_arg.jump.jump_where = instr->ga_len;
4316 }
4317
4318 p = skipwhite(arg);
4319 if (ends_excmd(*p))
4320 {
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004321 scope->se_u.se_try.ts_caught_all = TRUE;
4322 scope->se_u.se_try.ts_catch_label = 0;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004323 }
4324 else
4325 {
4326 // Push v:exception, push {expr} and MATCH
4327 generate_instr_type(cctx, ISN_PUSHEXC, &t_string);
4328
4329 if (compile_expr1(&p, cctx) == FAIL)
4330 return NULL;
4331
4332 // TODO: check for strings?
4333 if (generate_COMPARE(cctx, EXPR_MATCH, FALSE) == FAIL)
4334 return NULL;
4335
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004336 scope->se_u.se_try.ts_catch_label = instr->ga_len;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004337 if (generate_JUMP(cctx, JUMP_IF_FALSE, 0) == FAIL)
4338 return NULL;
4339 }
4340
4341 if (generate_instr(cctx, ISN_CATCH) == NULL)
4342 return NULL;
4343
4344 if (new_scope(cctx, BLOCK_SCOPE) == NULL)
4345 return NULL;
4346 return p;
4347}
4348
4349 static char_u *
4350compile_finally(char_u *arg, cctx_T *cctx)
4351{
4352 scope_T *scope = cctx->ctx_scope;
4353 garray_T *instr = &cctx->ctx_instr;
4354 isn_T *isn;
4355
4356 // end block scope from :try or :catch
4357 if (scope != NULL && scope->se_type == BLOCK_SCOPE)
4358 compile_endblock(cctx);
4359 scope = cctx->ctx_scope;
4360
4361 // Error if not in a :try scope
4362 if (scope == NULL || scope->se_type != TRY_SCOPE)
4363 {
4364 emsg(_(e_finally));
4365 return NULL;
4366 }
4367
4368 // End :catch or :finally scope: set value in ISN_TRY instruction
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004369 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004370 if (isn->isn_arg.try.try_finally != 0)
4371 {
4372 emsg(_(e_finally_dup));
4373 return NULL;
4374 }
4375
4376 // Fill in the "end" label in jumps at the end of the blocks.
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004377 compile_fill_jump_to_end(&scope->se_u.se_try.ts_end_label, cctx);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004378
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004379 if (scope->se_u.se_try.ts_catch_label != 0)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004380 {
4381 // Previous catch without match jumps here
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004382 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_catch_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004383 isn->isn_arg.jump.jump_where = instr->ga_len;
4384 }
4385
4386 isn->isn_arg.try.try_finally = instr->ga_len;
4387 // TODO: set index in ts_finally_label jumps
4388
4389 return arg;
4390}
4391
4392 static char_u *
4393compile_endtry(char_u *arg, cctx_T *cctx)
4394{
4395 scope_T *scope = cctx->ctx_scope;
4396 garray_T *instr = &cctx->ctx_instr;
4397 isn_T *isn;
4398
4399 // end block scope from :catch or :finally
4400 if (scope != NULL && scope->se_type == BLOCK_SCOPE)
4401 compile_endblock(cctx);
4402 scope = cctx->ctx_scope;
4403
4404 // Error if not in a :try scope
4405 if (scope == NULL || scope->se_type != TRY_SCOPE)
4406 {
4407 if (scope == NULL)
4408 emsg(_(e_no_endtry));
4409 else if (scope->se_type == WHILE_SCOPE)
4410 emsg(_(e_endwhile));
Bram Moolenaar5b18c242020-01-28 22:30:32 +01004411 else if (scope->se_type == FOR_SCOPE)
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004412 emsg(_(e_endfor));
4413 else
4414 emsg(_(e_endif));
4415 return NULL;
4416 }
4417
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004418 isn = ((isn_T *)instr->ga_data) + scope->se_u.se_try.ts_try_label;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004419 if (isn->isn_arg.try.try_catch == 0 && isn->isn_arg.try.try_finally == 0)
4420 {
4421 emsg(_("E1032: missing :catch or :finally"));
4422 return NULL;
4423 }
4424
4425 // Fill in the "end" label in jumps at the end of the blocks, if not done
4426 // by ":finally".
Bram Moolenaar0ff6aad2020-01-29 21:27:21 +01004427 compile_fill_jump_to_end(&scope->se_u.se_try.ts_end_label, cctx);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004428
4429 // End :catch or :finally scope: set value in ISN_TRY instruction
4430 if (isn->isn_arg.try.try_finally == 0)
4431 isn->isn_arg.try.try_finally = instr->ga_len;
4432 compile_endblock(cctx);
4433
4434 if (generate_instr(cctx, ISN_ENDTRY) == NULL)
4435 return NULL;
4436 return arg;
4437}
4438
4439/*
4440 * compile "throw {expr}"
4441 */
4442 static char_u *
4443compile_throw(char_u *arg, cctx_T *cctx UNUSED)
4444{
4445 char_u *p = skipwhite(arg);
4446
4447 if (ends_excmd(*p))
4448 {
4449 emsg(_(e_argreq));
4450 return NULL;
4451 }
4452 if (compile_expr1(&p, cctx) == FAIL)
4453 return NULL;
4454 if (may_generate_2STRING(-1, cctx) == FAIL)
4455 return NULL;
4456 if (generate_instr_drop(cctx, ISN_THROW, 1) == NULL)
4457 return NULL;
4458
4459 return p;
4460}
4461
4462/*
4463 * compile "echo expr"
4464 */
4465 static char_u *
4466compile_echo(char_u *arg, int with_white, cctx_T *cctx)
4467{
4468 char_u *p = arg;
4469 int count = 0;
4470
4471 // for ()
4472 {
4473 if (compile_expr1(&p, cctx) == FAIL)
4474 return NULL;
4475 ++count;
4476 }
4477
4478 generate_ECHO(cctx, with_white, count);
4479
4480 return p;
4481}
4482
4483/*
4484 * After ex_function() has collected all the function lines: parse and compile
4485 * the lines into instructions.
4486 * Adds the function to "def_functions".
4487 * When "set_return_type" is set then set ufunc->uf_ret_type to the type of the
4488 * return statement (used for lambda).
4489 */
4490 void
4491compile_def_function(ufunc_T *ufunc, int set_return_type)
4492{
4493 dfunc_T *dfunc;
4494 char_u *line = NULL;
4495 char_u *p;
4496 exarg_T ea;
4497 char *errormsg = NULL; // error message
4498 int had_return = FALSE;
4499 cctx_T cctx;
4500 garray_T *instr;
4501 int called_emsg_before = called_emsg;
4502 int ret = FAIL;
4503 sctx_T save_current_sctx = current_sctx;
4504
4505 if (ufunc->uf_dfunc_idx >= 0)
4506 {
4507 // redefining a function that was compiled before
4508 dfunc = ((dfunc_T *)def_functions.ga_data) + ufunc->uf_dfunc_idx;
4509 dfunc->df_deleted = FALSE;
4510 }
4511 else
4512 {
4513 // Add the function to "def_functions".
4514 if (ga_grow(&def_functions, 1) == FAIL)
4515 return;
4516 dfunc = ((dfunc_T *)def_functions.ga_data) + def_functions.ga_len;
4517 vim_memset(dfunc, 0, sizeof(dfunc_T));
4518 dfunc->df_idx = def_functions.ga_len;
4519 ufunc->uf_dfunc_idx = dfunc->df_idx;
4520 dfunc->df_ufunc = ufunc;
4521 ++def_functions.ga_len;
4522 }
4523
4524 vim_memset(&cctx, 0, sizeof(cctx));
4525 cctx.ctx_ufunc = ufunc;
4526 cctx.ctx_lnum = -1;
4527 ga_init2(&cctx.ctx_locals, sizeof(lvar_T), 10);
4528 ga_init2(&cctx.ctx_type_stack, sizeof(type_T *), 50);
4529 ga_init2(&cctx.ctx_imports, sizeof(imported_T), 10);
4530 cctx.ctx_type_list = &ufunc->uf_type_list;
4531 ga_init2(&cctx.ctx_instr, sizeof(isn_T), 50);
4532 instr = &cctx.ctx_instr;
4533
4534 // Most modern script version.
4535 current_sctx.sc_version = SCRIPT_VERSION_VIM9;
4536
4537 for (;;)
4538 {
4539 if (line != NULL && *line == '|')
4540 // the line continues after a '|'
4541 ++line;
4542 else if (line != NULL && *line != NUL)
4543 {
4544 semsg(_("E488: Trailing characters: %s"), line);
4545 goto erret;
4546 }
4547 else
4548 {
4549 do
4550 {
4551 ++cctx.ctx_lnum;
4552 if (cctx.ctx_lnum == ufunc->uf_lines.ga_len)
4553 break;
4554 line = ((char_u **)ufunc->uf_lines.ga_data)[cctx.ctx_lnum];
4555 } while (line == NULL);
4556 if (cctx.ctx_lnum == ufunc->uf_lines.ga_len)
4557 break;
4558 SOURCING_LNUM = ufunc->uf_script_ctx.sc_lnum + cctx.ctx_lnum + 1;
4559 }
4560
4561 had_return = FALSE;
4562 vim_memset(&ea, 0, sizeof(ea));
4563 ea.cmdlinep = &line;
4564 ea.cmd = skipwhite(line);
4565
4566 // "}" ends a block scope
4567 if (*ea.cmd == '}')
4568 {
4569 scopetype_T stype = cctx.ctx_scope == NULL
4570 ? NO_SCOPE : cctx.ctx_scope->se_type;
4571
4572 if (stype == BLOCK_SCOPE)
4573 {
4574 compile_endblock(&cctx);
4575 line = ea.cmd;
4576 }
4577 else
4578 {
4579 emsg("E1025: using } outside of a block scope");
4580 goto erret;
4581 }
4582 if (line != NULL)
4583 line = skipwhite(ea.cmd + 1);
4584 continue;
4585 }
4586
4587 // "{" starts a block scope
4588 if (*ea.cmd == '{')
4589 {
4590 line = compile_block(ea.cmd, &cctx);
4591 continue;
4592 }
4593
4594 /*
4595 * COMMAND MODIFIERS
4596 */
4597 if (parse_command_modifiers(&ea, &errormsg, FALSE) == FAIL)
4598 {
4599 if (errormsg != NULL)
4600 goto erret;
4601 // empty line or comment
4602 line = (char_u *)"";
4603 continue;
4604 }
4605
4606 // Skip ":call" to get to the function name.
4607 if (checkforcmd(&ea.cmd, "call", 3))
4608 ea.cmd = skipwhite(ea.cmd);
4609
4610 // Assuming the command starts with a variable or function name, find
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004611 // what follows. Also "&opt = val", "$ENV = val" and "@r = val".
4612 p = (*ea.cmd == '&' || *ea.cmd == '$' || *ea.cmd == '@')
4613 ? ea.cmd + 1 : ea.cmd;
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004614 p = to_name_end(p);
4615 if (p > ea.cmd && *p != NUL)
4616 {
4617 int oplen;
4618 int heredoc;
4619
4620 // "funcname(" is always a function call.
4621 // "varname[]" is an expression.
4622 // "g:varname" is an expression.
4623 // "varname->expr" is an expression.
4624 if (*p == '('
4625 || *p == '['
4626 || ((p - ea.cmd) > 2 && ea.cmd[1] == ':')
4627 || (*p == '-' && p[1] == '>'))
4628 {
4629 // TODO
4630 }
4631
4632 oplen = assignment_len(skipwhite(p), &heredoc);
4633 if (oplen > 0)
4634 {
4635 // Recognize an assignment if we recognize the variable name:
4636 // "g:var = expr"
4637 // "var = expr" where "var" is a local var name.
4638 // "&opt = expr"
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004639 // "$ENV = expr"
4640 // "@r = expr"
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004641 if (*ea.cmd == '&'
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004642 || *ea.cmd == '$'
4643 || *ea.cmd == '@'
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004644 || ((p - ea.cmd) > 2 && ea.cmd[1] == ':')
4645 || lookup_local(ea.cmd, p - ea.cmd, &cctx) >= 0
4646 || lookup_script(ea.cmd, p - ea.cmd) == OK)
4647 {
4648 line = compile_assignment(ea.cmd, &ea, CMD_SIZE, &cctx);
4649 if (line == NULL)
4650 goto erret;
4651 continue;
4652 }
4653 }
4654 }
4655
4656 /*
4657 * COMMAND after range
4658 */
4659 ea.cmd = skip_range(ea.cmd, NULL);
4660 p = find_ex_command(&ea, NULL, lookup_local, &cctx);
4661
4662 if (p == ea.cmd && ea.cmdidx != CMD_SIZE)
4663 {
Bram Moolenaara259d8d2020-01-31 20:10:50 +01004664 if (cctx.ctx_skip == TRUE)
4665 {
4666 line += STRLEN(line);
4667 continue;
4668 }
4669
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004670 // Expression or function call.
4671 if (ea.cmdidx == CMD_eval)
4672 {
4673 p = ea.cmd;
4674 if (compile_expr1(&p, &cctx) == FAIL)
4675 goto erret;
4676
4677 // drop the return value
4678 generate_instr_drop(&cctx, ISN_DROP, 1);
4679 line = p;
4680 continue;
4681 }
4682 if (ea.cmdidx == CMD_let)
4683 {
4684 line = compile_assignment(ea.cmd, &ea, CMD_SIZE, &cctx);
4685 if (line == NULL)
4686 goto erret;
4687 continue;
4688 }
4689 iemsg("Command from find_ex_command() not handled");
4690 goto erret;
4691 }
4692
4693 p = skipwhite(p);
4694
Bram Moolenaara259d8d2020-01-31 20:10:50 +01004695 if (cctx.ctx_skip == TRUE
4696 && ea.cmdidx != CMD_elseif
4697 && ea.cmdidx != CMD_else
4698 && ea.cmdidx != CMD_endif)
4699 {
4700 line += STRLEN(line);
4701 continue;
4702 }
4703
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004704 switch (ea.cmdidx)
4705 {
4706 case CMD_def:
4707 case CMD_function:
4708 // TODO: Nested function
4709 emsg("Nested function not implemented yet");
4710 goto erret;
4711
4712 case CMD_return:
4713 line = compile_return(p, set_return_type, &cctx);
4714 had_return = TRUE;
4715 break;
4716
4717 case CMD_let:
4718 case CMD_const:
4719 line = compile_assignment(p, &ea, ea.cmdidx, &cctx);
4720 break;
4721
4722 case CMD_import:
4723 line = compile_import(p, &cctx);
4724 break;
4725
4726 case CMD_if:
4727 line = compile_if(p, &cctx);
4728 break;
4729 case CMD_elseif:
4730 line = compile_elseif(p, &cctx);
4731 break;
4732 case CMD_else:
4733 line = compile_else(p, &cctx);
4734 break;
4735 case CMD_endif:
4736 line = compile_endif(p, &cctx);
4737 break;
4738
4739 case CMD_while:
4740 line = compile_while(p, &cctx);
4741 break;
4742 case CMD_endwhile:
4743 line = compile_endwhile(p, &cctx);
4744 break;
4745
4746 case CMD_for:
4747 line = compile_for(p, &cctx);
4748 break;
4749 case CMD_endfor:
4750 line = compile_endfor(p, &cctx);
4751 break;
4752 case CMD_continue:
4753 line = compile_continue(p, &cctx);
4754 break;
4755 case CMD_break:
4756 line = compile_break(p, &cctx);
4757 break;
4758
4759 case CMD_try:
4760 line = compile_try(p, &cctx);
4761 break;
4762 case CMD_catch:
4763 line = compile_catch(p, &cctx);
4764 break;
4765 case CMD_finally:
4766 line = compile_finally(p, &cctx);
4767 break;
4768 case CMD_endtry:
4769 line = compile_endtry(p, &cctx);
4770 break;
4771 case CMD_throw:
4772 line = compile_throw(p, &cctx);
4773 break;
4774
4775 case CMD_echo:
4776 line = compile_echo(p, TRUE, &cctx);
4777 break;
4778 case CMD_echon:
4779 line = compile_echo(p, FALSE, &cctx);
4780 break;
4781
4782 default:
4783 // Not recognized, execute with do_cmdline_cmd().
4784 generate_EXEC(&cctx, line);
4785 line = (char_u *)"";
4786 break;
4787 }
4788 if (line == NULL)
4789 goto erret;
4790
4791 if (cctx.ctx_type_stack.ga_len < 0)
4792 {
4793 iemsg("Type stack underflow");
4794 goto erret;
4795 }
4796 }
4797
4798 if (cctx.ctx_scope != NULL)
4799 {
4800 if (cctx.ctx_scope->se_type == IF_SCOPE)
4801 emsg(_(e_endif));
4802 else if (cctx.ctx_scope->se_type == WHILE_SCOPE)
4803 emsg(_(e_endwhile));
4804 else if (cctx.ctx_scope->se_type == FOR_SCOPE)
4805 emsg(_(e_endfor));
4806 else
4807 emsg(_("E1026: Missing }"));
4808 goto erret;
4809 }
4810
4811 if (!had_return)
4812 {
4813 if (ufunc->uf_ret_type->tt_type != VAR_VOID)
4814 {
4815 emsg(_("E1027: Missing return statement"));
4816 goto erret;
4817 }
4818
4819 // Return zero if there is no return at the end.
4820 generate_PUSHNR(&cctx, 0);
4821 generate_instr(&cctx, ISN_RETURN);
4822 }
4823
4824 dfunc->df_instr = instr->ga_data;
4825 dfunc->df_instr_count = instr->ga_len;
4826 dfunc->df_varcount = cctx.ctx_max_local;
4827
4828 ret = OK;
4829
4830erret:
4831 if (ret == FAIL)
4832 {
4833 ga_clear(instr);
4834 ufunc->uf_dfunc_idx = -1;
4835 --def_functions.ga_len;
4836 if (errormsg != NULL)
4837 emsg(errormsg);
4838 else if (called_emsg == called_emsg_before)
4839 emsg("E1028: compile_def_function failed");
4840
4841 // don't execute this function body
4842 ufunc->uf_lines.ga_len = 0;
4843 }
4844
4845 current_sctx = save_current_sctx;
4846 ga_clear(&cctx.ctx_type_stack);
4847 ga_clear(&cctx.ctx_locals);
4848}
4849
4850/*
4851 * Delete an instruction, free what it contains.
4852 */
4853 static void
4854delete_instr(isn_T *isn)
4855{
4856 switch (isn->isn_type)
4857 {
4858 case ISN_EXEC:
4859 case ISN_LOADENV:
4860 case ISN_LOADG:
4861 case ISN_LOADOPT:
4862 case ISN_MEMBER:
4863 case ISN_PUSHEXC:
4864 case ISN_PUSHS:
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004865 case ISN_STOREENV:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004866 case ISN_STOREG:
4867 vim_free(isn->isn_arg.string);
4868 break;
4869
4870 case ISN_LOADS:
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004871 case ISN_STORES:
4872 vim_free(isn->isn_arg.loadstore.ls_name);
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004873 break;
4874
4875 case ISN_STOREOPT:
4876 vim_free(isn->isn_arg.storeopt.so_name);
4877 break;
4878
4879 case ISN_PUSHBLOB: // push blob isn_arg.blob
4880 blob_unref(isn->isn_arg.blob);
4881 break;
4882
4883 case ISN_UCALL:
4884 vim_free(isn->isn_arg.ufunc.cuf_name);
4885 break;
4886
4887 case ISN_2BOOL:
4888 case ISN_2STRING:
4889 case ISN_ADDBLOB:
4890 case ISN_ADDLIST:
4891 case ISN_BCALL:
4892 case ISN_CATCH:
4893 case ISN_CHECKNR:
4894 case ISN_CHECKTYPE:
4895 case ISN_COMPAREANY:
4896 case ISN_COMPAREBLOB:
4897 case ISN_COMPAREBOOL:
4898 case ISN_COMPAREDICT:
4899 case ISN_COMPAREFLOAT:
4900 case ISN_COMPAREFUNC:
4901 case ISN_COMPARELIST:
4902 case ISN_COMPARENR:
4903 case ISN_COMPAREPARTIAL:
4904 case ISN_COMPARESPECIAL:
4905 case ISN_COMPARESTRING:
4906 case ISN_CONCAT:
4907 case ISN_DCALL:
4908 case ISN_DROP:
4909 case ISN_ECHO:
4910 case ISN_ENDTRY:
4911 case ISN_FOR:
4912 case ISN_FUNCREF:
4913 case ISN_INDEX:
4914 case ISN_JUMP:
4915 case ISN_LOAD:
4916 case ISN_LOADSCRIPT:
4917 case ISN_LOADREG:
4918 case ISN_LOADV:
4919 case ISN_NEGATENR:
4920 case ISN_NEWDICT:
4921 case ISN_NEWLIST:
4922 case ISN_OPNR:
4923 case ISN_OPFLOAT:
4924 case ISN_OPANY:
4925 case ISN_PCALL:
4926 case ISN_PUSHF:
4927 case ISN_PUSHNR:
4928 case ISN_PUSHBOOL:
4929 case ISN_PUSHSPEC:
4930 case ISN_RETURN:
4931 case ISN_STORE:
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004932 case ISN_STOREV:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004933 case ISN_STORENR:
Bram Moolenaarb283a8a2020-02-02 22:24:04 +01004934 case ISN_STOREREG:
Bram Moolenaar8a7d6542020-01-26 15:56:19 +01004935 case ISN_STORESCRIPT:
4936 case ISN_THROW:
4937 case ISN_TRY:
4938 // nothing allocated
4939 break;
4940 }
4941}
4942
4943/*
4944 * When a user function is deleted, delete any associated def function.
4945 */
4946 void
4947delete_def_function(ufunc_T *ufunc)
4948{
4949 int idx;
4950
4951 if (ufunc->uf_dfunc_idx >= 0)
4952 {
4953 dfunc_T *dfunc = ((dfunc_T *)def_functions.ga_data)
4954 + ufunc->uf_dfunc_idx;
4955 ga_clear(&dfunc->df_def_args_isn);
4956
4957 for (idx = 0; idx < dfunc->df_instr_count; ++idx)
4958 delete_instr(dfunc->df_instr + idx);
4959 VIM_CLEAR(dfunc->df_instr);
4960
4961 dfunc->df_deleted = TRUE;
4962 }
4963}
4964
4965#if defined(EXITFREE) || defined(PROTO)
4966 void
4967free_def_functions(void)
4968{
4969 vim_free(def_functions.ga_data);
4970}
4971#endif
4972
4973
4974#endif // FEAT_EVAL