fix the INCLUDE_DEF flag getting applied regardless of dotranslate...
[xonotic/gmqcc.git] / parser.c
1 /*
2  * Copyright (C) 2012, 2013
3  *     Wolfgang Bumiller
4  *     Dale Weiler
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include <stdio.h>
25 #include <stdarg.h>
26 #include <math.h>
27
28 #include "gmqcc.h"
29 #include "lexer.h"
30 #include "ast.h"
31
32 /* beginning of locals */
33 #define PARSER_HT_LOCALS  2
34
35 #define PARSER_HT_SIZE    128
36 #define TYPEDEF_HT_SIZE   16
37
38 typedef struct parser_s {
39     lex_file *lex;
40     int      tok;
41
42     ast_expression **globals;
43     ast_expression **fields;
44     ast_function **functions;
45     ast_value    **imm_float;
46     ast_value    **imm_string;
47     ast_value    **imm_vector;
48     size_t         translated;
49
50     ht ht_imm_string;
51
52     /* must be deleted first, they reference immediates and values */
53     ast_value    **accessors;
54
55     ast_value *imm_float_zero;
56     ast_value *imm_float_one;
57     ast_value *imm_float_neg_one;
58
59     ast_value *imm_vector_zero;
60
61     ast_value *nil;
62     ast_value *reserved_version;
63
64     size_t crc_globals;
65     size_t crc_fields;
66
67     ast_function *function;
68     ht            aliases;
69
70     /* All the labels the function defined...
71      * Should they be in ast_function instead?
72      */
73     ast_label  **labels;
74     ast_goto   **gotos;
75     const char **breaks;
76     const char **continues;
77
78     /* A list of hashtables for each scope */
79     ht *variables;
80     ht htfields;
81     ht htglobals;
82     ht *typedefs;
83
84     /* same as above but for the spelling corrector */
85     correct_trie_t  **correct_variables;
86     size_t         ***correct_variables_score;  /* vector of vector of size_t* */
87
88     /* not to be used directly, we use the hash table */
89     ast_expression **_locals;
90     size_t          *_blocklocals;
91     ast_value      **_typedefs;
92     size_t          *_blocktypedefs;
93     lex_ctx         *_block_ctx;
94
95     /* we store the '=' operator info */
96     const oper_info *assign_op;
97
98     /* magic values */
99     ast_value *const_vec[3];
100
101     /* pragma flags */
102     bool noref;
103
104     /* collected information */
105     size_t     max_param_count;
106
107     /* code generator */
108     code_t     *code;
109 } parser_t;
110
111 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
112
113 static void parser_enterblock(parser_t *parser);
114 static bool parser_leaveblock(parser_t *parser);
115 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
116 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
117 static bool parse_typedef(parser_t *parser);
118 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
119 static ast_block* parse_block(parser_t *parser);
120 static bool parse_block_into(parser_t *parser, ast_block *block);
121 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
122 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
123 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
124 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
125 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
126 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
127 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
128
129 static void parseerror(parser_t *parser, const char *fmt, ...)
130 {
131     va_list ap;
132     va_start(ap, fmt);
133     vcompile_error(parser->lex->tok.ctx, fmt, ap);
134     va_end(ap);
135 }
136
137 /* returns true if it counts as an error */
138 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
139 {
140     bool    r;
141     va_list ap;
142     va_start(ap, fmt);
143     r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
144     va_end(ap);
145     return r;
146 }
147
148 /**********************************************************************
149  * some maths used for constant folding
150  */
151
152 vector vec3_add(vector a, vector b)
153 {
154     vector out;
155     out.x = a.x + b.x;
156     out.y = a.y + b.y;
157     out.z = a.z + b.z;
158     return out;
159 }
160
161 vector vec3_sub(vector a, vector b)
162 {
163     vector out;
164     out.x = a.x - b.x;
165     out.y = a.y - b.y;
166     out.z = a.z - b.z;
167     return out;
168 }
169
170 qcfloat vec3_mulvv(vector a, vector b)
171 {
172     return (a.x * b.x + a.y * b.y + a.z * b.z);
173 }
174
175 vector vec3_mulvf(vector a, float b)
176 {
177     vector out;
178     out.x = a.x * b;
179     out.y = a.y * b;
180     out.z = a.z * b;
181     return out;
182 }
183
184 /**********************************************************************
185  * parsing
186  */
187
188 bool parser_next(parser_t *parser)
189 {
190     /* lex_do kills the previous token */
191     parser->tok = lex_do(parser->lex);
192     if (parser->tok == TOKEN_EOF)
193         return true;
194     if (parser->tok >= TOKEN_ERROR) {
195         parseerror(parser, "lex error");
196         return false;
197     }
198     return true;
199 }
200
201 #define parser_tokval(p) ((p)->lex->tok.value)
202 #define parser_token(p)  (&((p)->lex->tok))
203 #define parser_ctx(p)    ((p)->lex->tok.ctx)
204
205 static ast_value* parser_const_float(parser_t *parser, double d)
206 {
207     size_t i;
208     ast_value *out;
209     lex_ctx ctx;
210     for (i = 0; i < vec_size(parser->imm_float); ++i) {
211         const double compare = parser->imm_float[i]->constval.vfloat;
212         if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
213             return parser->imm_float[i];
214     }
215     if (parser->lex)
216         ctx = parser_ctx(parser);
217     else {
218         memset(&ctx, 0, sizeof(ctx));
219     }
220     out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
221     out->cvq      = CV_CONST;
222     out->hasvalue = true;
223     out->isimm    = true;
224     out->constval.vfloat = d;
225     vec_push(parser->imm_float, out);
226     return out;
227 }
228
229 static ast_value* parser_const_float_0(parser_t *parser)
230 {
231     if (!parser->imm_float_zero)
232         parser->imm_float_zero = parser_const_float(parser, 0);
233     return parser->imm_float_zero;
234 }
235
236 static ast_value* parser_const_float_neg1(parser_t *parser) {
237     if (!parser->imm_float_neg_one)
238         parser->imm_float_neg_one = parser_const_float(parser, -1);
239     return parser->imm_float_neg_one;
240 }
241
242 static ast_value* parser_const_float_1(parser_t *parser)
243 {
244     if (!parser->imm_float_one)
245         parser->imm_float_one = parser_const_float(parser, 1);
246     return parser->imm_float_one;
247 }
248
249 static char *parser_strdup(const char *str)
250 {
251     if (str && !*str) {
252         /* actually dup empty strings */
253         char *out = (char*)mem_a(1);
254         *out = 0;
255         return out;
256     }
257     return util_strdup(str);
258 }
259
260 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
261 {
262     size_t hash = util_hthash(parser->ht_imm_string, str);
263     ast_value *out;
264     if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
265         if (dotranslate && out->name[0] == '#') {
266             char name[32];
267             util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
268             ast_value_set_name(out, name);
269             out->expression.flags |= AST_FLAG_INCLUDE_DEF;
270         }
271         return out;
272     }
273     /*
274     for (i = 0; i < vec_size(parser->imm_string); ++i) {
275         if (!strcmp(parser->imm_string[i]->constval.vstring, str))
276             return parser->imm_string[i];
277     }
278     */
279     if (dotranslate) {
280         char name[32];
281         util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
282         out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
283         out->expression.flags |= AST_FLAG_INCLUDE_DEF;
284     } else
285         out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
286     out->cvq      = CV_CONST;
287     out->hasvalue = true;
288     out->isimm    = true;
289     out->constval.vstring = parser_strdup(str);
290     vec_push(parser->imm_string, out);
291     util_htseth(parser->ht_imm_string, str, hash, out);
292     return out;
293 }
294
295 static ast_value* parser_const_vector(parser_t *parser, vector v)
296 {
297     size_t i;
298     ast_value *out;
299     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
300         if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
301             return parser->imm_vector[i];
302     }
303     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
304     out->cvq      = CV_CONST;
305     out->hasvalue = true;
306     out->isimm    = true;
307     out->constval.vvec = v;
308     vec_push(parser->imm_vector, out);
309     return out;
310 }
311
312 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
313 {
314     vector v;
315     v.x = x;
316     v.y = y;
317     v.z = z;
318     return parser_const_vector(parser, v);
319 }
320
321 static ast_value* parser_const_vector_0(parser_t *parser)
322 {
323     if (!parser->imm_vector_zero)
324         parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
325     return parser->imm_vector_zero;
326 }
327
328 static ast_expression* parser_find_field(parser_t *parser, const char *name)
329 {
330     return ( ast_expression*)util_htget(parser->htfields, name);
331 }
332
333 static ast_expression* parser_find_label(parser_t *parser, const char *name)
334 {
335     size_t i;
336     for(i = 0; i < vec_size(parser->labels); i++)
337         if (!strcmp(parser->labels[i]->name, name))
338             return (ast_expression*)parser->labels[i];
339     return NULL;
340 }
341
342 static ast_expression* parser_find_global(parser_t *parser, const char *name)
343 {
344     ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
345     if (var)
346         return var;
347     return (ast_expression*)util_htget(parser->htglobals, name);
348 }
349
350 static ast_expression* parser_find_param(parser_t *parser, const char *name)
351 {
352     size_t i;
353     ast_value *fun;
354     if (!parser->function)
355         return NULL;
356     fun = parser->function->vtype;
357     for (i = 0; i < vec_size(fun->expression.params); ++i) {
358         if (!strcmp(fun->expression.params[i]->name, name))
359             return (ast_expression*)(fun->expression.params[i]);
360     }
361     return NULL;
362 }
363
364 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
365 {
366     size_t          i, hash;
367     ast_expression *e;
368
369     hash = util_hthash(parser->htglobals, name);
370
371     *isparam = false;
372     for (i = vec_size(parser->variables); i > upto;) {
373         --i;
374         if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
375             return e;
376     }
377     *isparam = true;
378     return parser_find_param(parser, name);
379 }
380
381 static ast_expression* parser_find_var(parser_t *parser, const char *name)
382 {
383     bool dummy;
384     ast_expression *v;
385     v         = parser_find_local(parser, name, 0, &dummy);
386     if (!v) v = parser_find_global(parser, name);
387     return v;
388 }
389
390 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
391 {
392     size_t     i, hash;
393     ast_value *e;
394     hash = util_hthash(parser->typedefs[0], name);
395
396     for (i = vec_size(parser->typedefs); i > upto;) {
397         --i;
398         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
399             return e;
400     }
401     return NULL;
402 }
403
404 /* include intrinsics */
405 #include "intrin.h"
406
407 typedef struct
408 {
409     size_t etype; /* 0 = expression, others are operators */
410     bool            isparen;
411     size_t          off;
412     ast_expression *out;
413     ast_block      *block; /* for commas and function calls */
414     lex_ctx ctx;
415 } sy_elem;
416
417 enum {
418     PAREN_EXPR,
419     PAREN_FUNC,
420     PAREN_INDEX,
421     PAREN_TERNARY1,
422     PAREN_TERNARY2
423 };
424 typedef struct
425 {
426     sy_elem        *out;
427     sy_elem        *ops;
428     size_t         *argc;
429     unsigned int   *paren;
430 } shunt;
431
432 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
433     sy_elem e;
434     e.etype = 0;
435     e.off   = 0;
436     e.out   = v;
437     e.block = NULL;
438     e.ctx   = ctx;
439     e.isparen = false;
440     return e;
441 }
442
443 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
444     sy_elem e;
445     e.etype = 0;
446     e.off   = 0;
447     e.out   = (ast_expression*)v;
448     e.block = v;
449     e.ctx   = ctx;
450     e.isparen = false;
451     return e;
452 }
453
454 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
455     sy_elem e;
456     e.etype = 1 + (op - operators);
457     e.off   = 0;
458     e.out   = NULL;
459     e.block = NULL;
460     e.ctx   = ctx;
461     e.isparen = false;
462     return e;
463 }
464
465 static sy_elem syparen(lex_ctx ctx, size_t off) {
466     sy_elem e;
467     e.etype = 0;
468     e.off   = off;
469     e.out   = NULL;
470     e.block = NULL;
471     e.ctx   = ctx;
472     e.isparen = true;
473     return e;
474 }
475
476 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
477  * so we need to rotate it to become ent.(foo[n]).
478  */
479 static bool rotate_entfield_array_index_nodes(ast_expression **out)
480 {
481     ast_array_index *index, *oldindex;
482     ast_entfield    *entfield;
483
484     ast_value       *field;
485     ast_expression  *sub;
486     ast_expression  *entity;
487
488     lex_ctx ctx = ast_ctx(*out);
489
490     if (!ast_istype(*out, ast_array_index))
491         return false;
492     index = (ast_array_index*)*out;
493
494     if (!ast_istype(index->array, ast_entfield))
495         return false;
496     entfield = (ast_entfield*)index->array;
497
498     if (!ast_istype(entfield->field, ast_value))
499         return false;
500     field = (ast_value*)entfield->field;
501
502     sub    = index->index;
503     entity = entfield->entity;
504
505     oldindex = index;
506
507     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
508     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
509     *out = (ast_expression*)entfield;
510
511     oldindex->array = NULL;
512     oldindex->index = NULL;
513     ast_delete(oldindex);
514
515     return true;
516 }
517
518 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
519 {
520     switch (v->expression.vtype) {
521         case TYPE_FLOAT:
522             return !!v->constval.vfloat;
523         case TYPE_INTEGER:
524             return !!v->constval.vint;
525         case TYPE_VECTOR:
526             if (OPTS_FLAG(CORRECT_LOGIC))
527                 return v->constval.vvec.x &&
528                        v->constval.vvec.y &&
529                        v->constval.vvec.z;
530             else
531                 return !!(v->constval.vvec.x);
532         case TYPE_STRING:
533             if (!v->constval.vstring)
534                 return false;
535             if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
536                 return true;
537             return !!v->constval.vstring[0];
538         default:
539             compile_error(ctx, "internal error: immediate_is_true on invalid type");
540             return !!v->constval.vfunc;
541     }
542 }
543
544 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
545 {
546     const oper_info *op;
547     lex_ctx ctx;
548     ast_expression *out = NULL;
549     ast_expression *exprs[3];
550     ast_block      *blocks[3];
551     ast_value      *asvalue[3];
552     ast_binstore   *asbinstore;
553     size_t i, assignop, addop, subop;
554     qcint  generated_op = 0;
555
556     char ty1[1024];
557     char ty2[1024];
558
559     if (!vec_size(sy->ops)) {
560         parseerror(parser, "internal error: missing operator");
561         return false;
562     }
563
564     if (vec_last(sy->ops).isparen) {
565         parseerror(parser, "unmatched parenthesis");
566         return false;
567     }
568
569     op = &operators[vec_last(sy->ops).etype - 1];
570     ctx = vec_last(sy->ops).ctx;
571
572     if (vec_size(sy->out) < op->operands) {
573         compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
574                       op->op, (int)op->id);
575         return false;
576     }
577
578     vec_shrinkby(sy->ops, 1);
579
580     /* op(:?) has no input and no output */
581     if (!op->operands)
582         return true;
583
584     vec_shrinkby(sy->out, op->operands);
585     for (i = 0; i < op->operands; ++i) {
586         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
587         blocks[i] = sy->out[vec_size(sy->out)+i].block;
588         asvalue[i] = (ast_value*)exprs[i];
589
590         if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
591             !(i != 0 && op->id == opid2('?',':')) &&
592             !(i == 1 && op->id == opid1('.')))
593         {
594             if (ast_istype(exprs[i], ast_label))
595                 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
596             else
597                 compile_error(ast_ctx(exprs[i]), "not an expression");
598             (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
599         }
600     }
601
602     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
603         compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
604         return false;
605     }
606
607 #define NotSameType(T) \
608              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
609               exprs[0]->expression.vtype != T)
610 #define CanConstFold1(A) \
611              (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
612               (A)->expression.vtype != TYPE_FUNCTION)
613 #define CanConstFold(A, B) \
614              (CanConstFold1(A) && CanConstFold1(B))
615 #define ConstV(i) (asvalue[(i)]->constval.vvec)
616 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
617 #define ConstS(i) (asvalue[(i)]->constval.vstring)
618     switch (op->id)
619     {
620         default:
621             compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
622             return false;
623
624         case opid1('.'):
625             if (exprs[0]->expression.vtype == TYPE_VECTOR &&
626                 exprs[1]->expression.vtype == TYPE_NOEXPR)
627             {
628                 if      (exprs[1] == (ast_expression*)parser->const_vec[0])
629                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
630                 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
631                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
632                 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
633                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
634                 else {
635                     compile_error(ctx, "access to invalid vector component");
636                     return false;
637                 }
638             }
639             else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
640                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
641                     compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
642                     return false;
643                 }
644                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
645             }
646             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
647                 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
648                 return false;
649             }
650             else {
651                 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
652                 return false;
653             }
654             break;
655
656         case opid1('['):
657             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
658                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
659                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
660             {
661                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
662                 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
663                 return false;
664             }
665             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
666                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
667                 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
668                 return false;
669             }
670             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
671             if (rotate_entfield_array_index_nodes(&out))
672             {
673 #if 0
674                 /* This is not broken in fteqcc anymore */
675                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
676                     /* this error doesn't need to make us bail out */
677                     (void)!parsewarning(parser, WARN_EXTENSIONS,
678                                         "accessing array-field members of an entity without parenthesis\n"
679                                         " -> this is an extension from -std=gmqcc");
680                 }
681 #endif
682             }
683             break;
684
685         case opid1(','):
686             if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
687                 vec_push(sy->out, syexp(ctx, exprs[0]));
688                 vec_push(sy->out, syexp(ctx, exprs[1]));
689                 vec_last(sy->argc)++;
690                 return true;
691             }
692             if (blocks[0]) {
693                 if (!ast_block_add_expr(blocks[0], exprs[1]))
694                     return false;
695             } else {
696                 blocks[0] = ast_block_new(ctx);
697                 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
698                     !ast_block_add_expr(blocks[0], exprs[1]))
699                 {
700                     return false;
701                 }
702             }
703             ast_block_set_type(blocks[0], exprs[1]);
704
705             vec_push(sy->out, syblock(ctx, blocks[0]));
706             return true;
707
708         case opid2('+','P'):
709             out = exprs[0];
710             break;
711         case opid2('-','P'):
712             switch (exprs[0]->expression.vtype) {
713                 case TYPE_FLOAT:
714                     if (CanConstFold1(exprs[0]))
715                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
716                     else
717                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
718                                                               (ast_expression*)parser_const_float_0(parser),
719                                                               exprs[0]);
720                     break;
721                 case TYPE_VECTOR:
722                     if (CanConstFold1(exprs[0]))
723                         out = (ast_expression*)parser_const_vector_f(parser,
724                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
725                     else
726                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
727                                                               (ast_expression*)parser_const_vector_0(parser),
728                                                               exprs[0]);
729                     break;
730                 default:
731                 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
732                               type_name[exprs[0]->expression.vtype]);
733                 return false;
734             }
735             break;
736
737         case opid2('!','P'):
738             switch (exprs[0]->expression.vtype) {
739                 case TYPE_FLOAT:
740                     if (CanConstFold1(exprs[0]))
741                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
742                     else
743                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
744                     break;
745                 case TYPE_VECTOR:
746                     if (CanConstFold1(exprs[0]))
747                         out = (ast_expression*)parser_const_float(parser,
748                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
749                     else
750                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
751                     break;
752                 case TYPE_STRING:
753                     if (CanConstFold1(exprs[0])) {
754                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
755                             out = (ast_expression*)parser_const_float(parser, !ConstS(0));
756                         else
757                             out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
758                     } else {
759                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
760                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
761                         else
762                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
763                     }
764                     break;
765                 /* we don't constant-fold NOT for these types */
766                 case TYPE_ENTITY:
767                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
768                     break;
769                 case TYPE_FUNCTION:
770                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
771                     break;
772                 default:
773                 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
774                               type_name[exprs[0]->expression.vtype]);
775                 return false;
776             }
777             break;
778
779         case opid1('+'):
780             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
781                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
782             {
783                 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
784                               type_name[exprs[0]->expression.vtype],
785                               type_name[exprs[1]->expression.vtype]);
786                 return false;
787             }
788             switch (exprs[0]->expression.vtype) {
789                 case TYPE_FLOAT:
790                     if (CanConstFold(exprs[0], exprs[1]))
791                     {
792                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
793                     }
794                     else
795                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
796                     break;
797                 case TYPE_VECTOR:
798                     if (CanConstFold(exprs[0], exprs[1]))
799                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
800                     else
801                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
802                     break;
803                 default:
804                     compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
805                                   type_name[exprs[0]->expression.vtype],
806                                   type_name[exprs[1]->expression.vtype]);
807                     return false;
808             };
809             break;
810         case opid1('-'):
811             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
812                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
813             {
814                 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
815                               type_name[exprs[1]->expression.vtype],
816                               type_name[exprs[0]->expression.vtype]);
817                 return false;
818             }
819             switch (exprs[0]->expression.vtype) {
820                 case TYPE_FLOAT:
821                     if (CanConstFold(exprs[0], exprs[1]))
822                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
823                     else
824                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
825                     break;
826                 case TYPE_VECTOR:
827                     if (CanConstFold(exprs[0], exprs[1]))
828                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
829                     else
830                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
831                     break;
832                 default:
833                     compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
834                                   type_name[exprs[1]->expression.vtype],
835                                   type_name[exprs[0]->expression.vtype]);
836                     return false;
837             };
838             break;
839         case opid1('*'):
840             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
841                 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
842                   exprs[1]->expression.vtype == TYPE_FLOAT) &&
843                 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
844                   exprs[0]->expression.vtype == TYPE_FLOAT)
845                 )
846             {
847                 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
848                               type_name[exprs[1]->expression.vtype],
849                               type_name[exprs[0]->expression.vtype]);
850                 return false;
851             }
852             switch (exprs[0]->expression.vtype) {
853                 case TYPE_FLOAT:
854                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
855                     {
856                         if (CanConstFold(exprs[0], exprs[1]))
857                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
858                         else
859                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
860                     }
861                     else
862                     {
863                         if (CanConstFold(exprs[0], exprs[1]))
864                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
865                         else
866                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
867                     }
868                     break;
869                 case TYPE_VECTOR:
870                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
871                     {
872                         if (CanConstFold(exprs[0], exprs[1]))
873                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
874                         else
875                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
876                     }
877                     else
878                     {
879                         if (CanConstFold(exprs[0], exprs[1]))
880                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
881                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
882                             vector vec = ConstV(0);
883                             if (!vec.y && !vec.z) { /* 'n 0 0' * v */
884                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
885                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
886                                 out->expression.node.keep = false;
887                                 ((ast_member*)out)->rvalue = true;
888                                 if (vec.x != 1)
889                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
890                             }
891                             else if (!vec.x && !vec.z) { /* '0 n 0' * v */
892                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
893                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
894                                 out->expression.node.keep = false;
895                                 ((ast_member*)out)->rvalue = true;
896                                 if (vec.y != 1)
897                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
898                             }
899                             else if (!vec.x && !vec.y) { /* '0 n 0' * v */
900                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
901                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
902                                 out->expression.node.keep = false;
903                                 ((ast_member*)out)->rvalue = true;
904                                 if (vec.z != 1)
905                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
906                             }
907                             else
908                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
909                         }
910                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
911                             vector vec = ConstV(1);
912                             if (!vec.y && !vec.z) { /* v * 'n 0 0' */
913                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
914                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
915                                 out->expression.node.keep = false;
916                                 ((ast_member*)out)->rvalue = true;
917                                 if (vec.x != 1)
918                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
919                             }
920                             else if (!vec.x && !vec.z) { /* v * '0 n 0' */
921                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
922                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
923                                 out->expression.node.keep = false;
924                                 ((ast_member*)out)->rvalue = true;
925                                 if (vec.y != 1)
926                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
927                             }
928                             else if (!vec.x && !vec.y) { /* v * '0 n 0' */
929                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
930                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
931                                 out->expression.node.keep = false;
932                                 ((ast_member*)out)->rvalue = true;
933                                 if (vec.z != 1)
934                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
935                             }
936                             else
937                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
938                         }
939                         else
940                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
941                     }
942                     break;
943                 default:
944                     compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
945                                   type_name[exprs[1]->expression.vtype],
946                                   type_name[exprs[0]->expression.vtype]);
947                     return false;
948             };
949             break;
950         case opid1('/'):
951             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
952                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
955                 return false;
956             }
957             if (exprs[0]->expression.vtype == TYPE_FLOAT) {
958                 if (CanConstFold(exprs[0], exprs[1]))
959                     out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
960                 else
961                     out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
962             }
963             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
964                 if (CanConstFold(exprs[0], exprs[1]))
965                     out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
966                 else {
967                     if (CanConstFold1(exprs[1])) {
968                         out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
969                     } else {
970                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
971                                                               (ast_expression*)parser_const_float_1(parser),
972                                                               exprs[1]);
973                     }
974                     if (!out) {
975                         compile_error(ctx, "internal error: failed to generate division");
976                         return false;
977                     }
978                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
979                 }
980             }
981             else
982             {
983                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
984                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
985                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
986                 return false;
987             }
988             break;
989
990         case opid1('%'):
991             if (NotSameType(TYPE_FLOAT)) {
992                 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
993                     type_name[exprs[0]->expression.vtype],
994                     type_name[exprs[1]->expression.vtype]);
995                 return false;
996             }
997             if (CanConstFold(exprs[0], exprs[1])) {
998                 out = (ast_expression*)parser_const_float(parser,
999                             (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
1000             } else {
1001                 /* generate a call to __builtin_mod */
1002                 ast_expression *mod  = intrin_func(parser, "mod");
1003                 ast_call       *call = NULL;
1004                 if (!mod) return false; /* can return null for missing floor */
1005
1006                 call = ast_call_new(parser_ctx(parser), mod);
1007                 vec_push(call->params, exprs[0]);
1008                 vec_push(call->params, exprs[1]);
1009
1010                 out = (ast_expression*)call;
1011             }
1012             break;
1013
1014         case opid2('%','='):
1015             compile_error(ctx, "%= is unimplemented");
1016             return false;
1017
1018         case opid1('|'):
1019         case opid1('&'):
1020             if (NotSameType(TYPE_FLOAT)) {
1021                 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1022                               type_name[exprs[0]->expression.vtype],
1023                               type_name[exprs[1]->expression.vtype]);
1024                 return false;
1025             }
1026             if (CanConstFold(exprs[0], exprs[1]))
1027                 out = (ast_expression*)parser_const_float(parser,
1028                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1029                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1030             else
1031                 out = (ast_expression*)ast_binary_new(ctx,
1032                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1033                     exprs[0], exprs[1]);
1034             break;
1035         case opid1('^'):
1036             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1037             return false;
1038
1039         case opid2('<','<'):
1040         case opid2('>','>'):
1041             if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1042                 if (op->id == opid2('<','<'))
1043                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1044                 else
1045                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1046                 break;
1047             }
1048         case opid3('<','<','='):
1049         case opid3('>','>','='):
1050             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1051             return false;
1052
1053         case opid2('|','|'):
1054             generated_op += 1; /* INSTR_OR */
1055         case opid2('&','&'):
1056             generated_op += INSTR_AND;
1057             if (CanConstFold(exprs[0], exprs[1]))
1058             {
1059                 if (OPTS_FLAG(PERL_LOGIC)) {
1060                     if (immediate_is_true(ctx, asvalue[0]))
1061                         out = exprs[1];
1062                 }
1063                 else
1064                     out = (ast_expression*)parser_const_float(parser,
1065                           ( (generated_op == INSTR_OR)
1066                             ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1067                             : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1068                           ? 1 : 0);
1069             }
1070             else
1071             {
1072                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1073                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1075                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1076                     return false;
1077                 }
1078                 for (i = 0; i < 2; ++i) {
1079                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1080                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1081                         if (!out) break;
1082                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1083                         if (!out) break;
1084                         exprs[i] = out; out = NULL;
1085                         if (OPTS_FLAG(PERL_LOGIC)) {
1086                             /* here we want to keep the right expressions' type */
1087                             break;
1088                         }
1089                     }
1090                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1091                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1092                         if (!out) break;
1093                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1094                         if (!out) break;
1095                         exprs[i] = out; out = NULL;
1096                         if (OPTS_FLAG(PERL_LOGIC)) {
1097                             /* here we want to keep the right expressions' type */
1098                             break;
1099                         }
1100                     }
1101                 }
1102                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1103             }
1104             break;
1105
1106         case opid2('?',':'):
1107             if (vec_last(sy->paren) != PAREN_TERNARY2) {
1108                 compile_error(ctx, "mismatched parenthesis/ternary");
1109                 return false;
1110             }
1111             vec_pop(sy->paren);
1112             if (!ast_compare_type(exprs[1], exprs[2])) {
1113                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1114                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1115                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1116                 return false;
1117             }
1118             if (CanConstFold1(exprs[0]))
1119                 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1120             else
1121                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1122             break;
1123
1124         case opid2('*', '*'):
1125             if (NotSameType(TYPE_FLOAT)) {
1126                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128                 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1129                     ty1, ty2);
1130
1131                 return false;
1132             }
1133
1134             if (CanConstFold(exprs[0], exprs[1])) {
1135                 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1136             } else {
1137                 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1138                 vec_push(gencall->params, exprs[0]);
1139                 vec_push(gencall->params, exprs[1]);
1140                 out = (ast_expression*)gencall;
1141             }
1142             break;
1143
1144         case opid3('<','=','>'): /* -1, 0, or 1 */
1145             if (NotSameType(TYPE_FLOAT)) {
1146                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1147                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1148                 compile_error(ctx, "invalid types used in comparision: %s and %s",
1149                     ty1, ty2);
1150
1151                 return false;
1152             }
1153
1154             if (CanConstFold(exprs[0], exprs[1])) {
1155                 if (ConstF(0) < ConstF(1))
1156                     out = (ast_expression*)parser_const_float_neg1(parser);
1157                 else if (ConstF(0) == ConstF(1))
1158                     out = (ast_expression*)parser_const_float_0(parser);
1159                 else if (ConstF(0) > ConstF(1))
1160                     out = (ast_expression*)parser_const_float_1(parser);
1161             } else {
1162                 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1163
1164                 eq->refs = (ast_binary_ref)false; /* references nothing */
1165
1166                     /* if (lt) { */
1167                 out = (ast_expression*)ast_ternary_new(ctx,
1168                         (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1169                         /* out = -1 */
1170                         (ast_expression*)parser_const_float_neg1(parser),
1171                     /* } else { */
1172                         /* if (eq) { */
1173                         (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1174                             /* out = 0 */
1175                             (ast_expression*)parser_const_float_0(parser),
1176                         /* } else { */
1177                             /* out = 1 */
1178                             (ast_expression*)parser_const_float_1(parser)
1179                         /* } */
1180                         )
1181                     /* } */
1182                     );
1183
1184             }
1185             break;
1186
1187         case opid1('>'):
1188             generated_op += 1; /* INSTR_GT */
1189         case opid1('<'):
1190             generated_op += 1; /* INSTR_LT */
1191         case opid2('>', '='):
1192             generated_op += 1; /* INSTR_GE */
1193         case opid2('<', '='):
1194             generated_op += INSTR_LE;
1195             if (NotSameType(TYPE_FLOAT)) {
1196                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1197                               type_name[exprs[0]->expression.vtype],
1198                               type_name[exprs[1]->expression.vtype]);
1199                 return false;
1200             }
1201             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1202             break;
1203         case opid2('!', '='):
1204             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1205                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1206                               type_name[exprs[0]->expression.vtype],
1207                               type_name[exprs[1]->expression.vtype]);
1208                 return false;
1209             }
1210             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1211             break;
1212         case opid2('=', '='):
1213             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1214                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1215                               type_name[exprs[0]->expression.vtype],
1216                               type_name[exprs[1]->expression.vtype]);
1217                 return false;
1218             }
1219             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1220             break;
1221
1222         case opid1('='):
1223             if (ast_istype(exprs[0], ast_entfield)) {
1224                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1225                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1226                     exprs[0]->expression.vtype == TYPE_FIELD &&
1227                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1228                 {
1229                     assignop = type_storep_instr[TYPE_VECTOR];
1230                 }
1231                 else
1232                     assignop = type_storep_instr[exprs[0]->expression.vtype];
1233                 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1234                 {
1235                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1236                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1237                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1238                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
1239                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1240                     {
1241                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1242                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1243                     }
1244                     else
1245                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1246                 }
1247             }
1248             else
1249             {
1250                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1251                     exprs[0]->expression.vtype == TYPE_FIELD &&
1252                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1253                 {
1254                     assignop = type_store_instr[TYPE_VECTOR];
1255                 }
1256                 else {
1257                     assignop = type_store_instr[exprs[0]->expression.vtype];
1258                 }
1259
1260                 if (assignop == VINSTR_END) {
1261                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1262                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1263                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1264                 }
1265                 else if (!ast_compare_type(exprs[0], exprs[1]))
1266                 {
1267                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1268                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1269                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1270                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
1271                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1272                     {
1273                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1274                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1275                     }
1276                     else
1277                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1278                 }
1279             }
1280             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1281                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1282             }
1283             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1284             break;
1285         case opid3('+','+','P'):
1286         case opid3('-','-','P'):
1287             /* prefix ++ */
1288             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1289                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1290                 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1291                 return false;
1292             }
1293             if (op->id == opid3('+','+','P'))
1294                 addop = INSTR_ADD_F;
1295             else
1296                 addop = INSTR_SUB_F;
1297             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1298                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1299             }
1300             if (ast_istype(exprs[0], ast_entfield)) {
1301                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1302                                                         exprs[0],
1303                                                         (ast_expression*)parser_const_float_1(parser));
1304             } else {
1305                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1306                                                         exprs[0],
1307                                                         (ast_expression*)parser_const_float_1(parser));
1308             }
1309             break;
1310         case opid3('S','+','+'):
1311         case opid3('S','-','-'):
1312             /* prefix ++ */
1313             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1314                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1315                 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1316                 return false;
1317             }
1318             if (op->id == opid3('S','+','+')) {
1319                 addop = INSTR_ADD_F;
1320                 subop = INSTR_SUB_F;
1321             } else {
1322                 addop = INSTR_SUB_F;
1323                 subop = INSTR_ADD_F;
1324             }
1325             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1326                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1327             }
1328             if (ast_istype(exprs[0], ast_entfield)) {
1329                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1330                                                         exprs[0],
1331                                                         (ast_expression*)parser_const_float_1(parser));
1332             } else {
1333                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1334                                                         exprs[0],
1335                                                         (ast_expression*)parser_const_float_1(parser));
1336             }
1337             if (!out)
1338                 return false;
1339             out = (ast_expression*)ast_binary_new(ctx, subop,
1340                                                   out,
1341                                                   (ast_expression*)parser_const_float_1(parser));
1342             break;
1343         case opid2('+','='):
1344         case opid2('-','='):
1345             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1346                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1347             {
1348                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1349                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1350                 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1351                               ty1, ty2);
1352                 return false;
1353             }
1354             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1355                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1356             }
1357             if (ast_istype(exprs[0], ast_entfield))
1358                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1359             else
1360                 assignop = type_store_instr[exprs[0]->expression.vtype];
1361             switch (exprs[0]->expression.vtype) {
1362                 case TYPE_FLOAT:
1363                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1364                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1365                                                             exprs[0], exprs[1]);
1366                     break;
1367                 case TYPE_VECTOR:
1368                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1369                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1370                                                             exprs[0], exprs[1]);
1371                     break;
1372                 default:
1373                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1374                                   type_name[exprs[0]->expression.vtype],
1375                                   type_name[exprs[1]->expression.vtype]);
1376                     return false;
1377             };
1378             break;
1379         case opid2('*','='):
1380         case opid2('/','='):
1381             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1382                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1383                   exprs[0]->expression.vtype == TYPE_VECTOR))
1384             {
1385                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1386                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1387                 compile_error(ctx, "invalid types used in expression: %s and %s",
1388                               ty1, ty2);
1389                 return false;
1390             }
1391             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1392                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1393             }
1394             if (ast_istype(exprs[0], ast_entfield))
1395                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1396             else
1397                 assignop = type_store_instr[exprs[0]->expression.vtype];
1398             switch (exprs[0]->expression.vtype) {
1399                 case TYPE_FLOAT:
1400                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1401                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1402                                                             exprs[0], exprs[1]);
1403                     break;
1404                 case TYPE_VECTOR:
1405                     if (op->id == opid2('*','=')) {
1406                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1407                                                                 exprs[0], exprs[1]);
1408                     } else {
1409                         /* there's no DIV_VF */
1410                         if (CanConstFold1(exprs[1])) {
1411                             out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1412                         } else {
1413                             out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1414                                                                   (ast_expression*)parser_const_float_1(parser),
1415                                                                   exprs[1]);
1416                         }
1417                         if (!out) {
1418                             compile_error(ctx, "internal error: failed to generate division");
1419                             return false;
1420                         }
1421                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1422                                                                 exprs[0], out);
1423                     }
1424                     break;
1425                 default:
1426                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1427                                   type_name[exprs[0]->expression.vtype],
1428                                   type_name[exprs[1]->expression.vtype]);
1429                     return false;
1430             };
1431             break;
1432         case opid2('&','='):
1433         case opid2('|','='):
1434             if (NotSameType(TYPE_FLOAT)) {
1435                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1436                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1437                 compile_error(ctx, "invalid types used in expression: %s and %s",
1438                               ty1, ty2);
1439                 return false;
1440             }
1441             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1442                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1443             }
1444             if (ast_istype(exprs[0], ast_entfield))
1445                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1446             else
1447                 assignop = type_store_instr[exprs[0]->expression.vtype];
1448             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1449                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1450                                                     exprs[0], exprs[1]);
1451             break;
1452         case opid3('&','~','='):
1453             /* This is like: a &= ~(b);
1454              * But QC has no bitwise-not, so we implement it as
1455              * a -= a & (b);
1456              */
1457             if (NotSameType(TYPE_FLOAT)) {
1458                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1459                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1460                 compile_error(ctx, "invalid types used in expression: %s and %s",
1461                               ty1, ty2);
1462                 return false;
1463             }
1464             if (ast_istype(exprs[0], ast_entfield))
1465                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1466             else
1467                 assignop = type_store_instr[exprs[0]->expression.vtype];
1468             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1469             if (!out)
1470                 return false;
1471             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1472                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1473             }
1474             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1475             asbinstore->keep_dest = true;
1476             out = (ast_expression*)asbinstore;
1477             break;
1478
1479         case opid2('~', 'P'):
1480             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1481                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1482                 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1483                 return false;
1484             }
1485
1486             if(CanConstFold1(exprs[0]))
1487                 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1488             else
1489                 out = (ast_expression*)
1490                     ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1491             break;
1492     }
1493 #undef NotSameType
1494
1495     if (!out) {
1496         compile_error(ctx, "failed to apply operator %s", op->op);
1497         return false;
1498     }
1499
1500     vec_push(sy->out, syexp(ctx, out));
1501     return true;
1502 }
1503
1504 static bool parser_close_call(parser_t *parser, shunt *sy)
1505 {
1506     /* was a function call */
1507     ast_expression *fun;
1508     ast_value      *funval = NULL;
1509     ast_call       *call;
1510
1511     size_t          fid;
1512     size_t          paramcount, i;
1513
1514     fid = vec_last(sy->ops).off;
1515     vec_shrinkby(sy->ops, 1);
1516
1517     /* out[fid] is the function
1518      * everything above is parameters...
1519      */
1520     if (!vec_size(sy->argc)) {
1521         parseerror(parser, "internal error: no argument counter available");
1522         return false;
1523     }
1524
1525     paramcount = vec_last(sy->argc);
1526     vec_pop(sy->argc);
1527
1528     if (vec_size(sy->out) < fid) {
1529         parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1530                    (unsigned long)vec_size(sy->out),
1531                    (unsigned long)fid,
1532                    (unsigned long)paramcount);
1533         return false;
1534     }
1535
1536     fun = sy->out[fid].out;
1537
1538     if (fun == intrinsic_debug_typestring) {
1539         char ty[1024];
1540         if (fid+2 != vec_size(sy->out) ||
1541             vec_last(sy->out).block)
1542         {
1543             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1544             return false;
1545         }
1546         ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1547         ast_unref(vec_last(sy->out).out);
1548         sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1549                              (ast_expression*)parser_const_string(parser, ty, false));
1550         vec_shrinkby(sy->out, 1);
1551         return true;
1552     }
1553
1554     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1555     if (!call)
1556         return false;
1557
1558     if (fid+1 < vec_size(sy->out))
1559         ++paramcount;
1560
1561     if (fid+1 + paramcount != vec_size(sy->out)) {
1562         parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1563                    (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1564         return false;
1565     }
1566
1567     for (i = 0; i < paramcount; ++i)
1568         vec_push(call->params, sy->out[fid+1 + i].out);
1569     vec_shrinkby(sy->out, paramcount);
1570     (void)!ast_call_check_types(call);
1571     if (parser->max_param_count < paramcount)
1572         parser->max_param_count = paramcount;
1573
1574     if (ast_istype(fun, ast_value)) {
1575         funval = (ast_value*)fun;
1576         if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1577             !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1578         {
1579             call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1580         }
1581     }
1582
1583     /* overwrite fid, the function, with a call */
1584     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1585
1586     if (fun->expression.vtype != TYPE_FUNCTION) {
1587         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1588         return false;
1589     }
1590
1591     if (!fun->expression.next) {
1592         parseerror(parser, "could not determine function return type");
1593         return false;
1594     } else {
1595         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1596
1597         if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1598             if (!fval) {
1599                 return !parsewarning(parser, WARN_DEPRECATED,
1600                         "call to function (which is marked deprecated)\n",
1601                         "-> it has been declared here: %s:%i",
1602                         ast_ctx(fun).file, ast_ctx(fun).line);
1603             }
1604             if (!fval->desc) {
1605                 return !parsewarning(parser, WARN_DEPRECATED,
1606                         "call to `%s` (which is marked deprecated)\n"
1607                         "-> `%s` declared here: %s:%i",
1608                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1609             }
1610             return !parsewarning(parser, WARN_DEPRECATED,
1611                     "call to `%s` (deprecated: %s)\n"
1612                     "-> `%s` declared here: %s:%i",
1613                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1614                     ast_ctx(fun).line);
1615         }
1616
1617         if (vec_size(fun->expression.params) != paramcount &&
1618             !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1619               vec_size(fun->expression.params) < paramcount))
1620         {
1621             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1622             if (fval)
1623                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1624                                      "too %s parameters for call to %s: expected %i, got %i\n"
1625                                      " -> `%s` has been declared here: %s:%i",
1626                                      fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1627                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1628             else
1629                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1630                                      "too %s parameters for function call: expected %i, got %i\n"
1631                                      " -> it has been declared here: %s:%i",
1632                                      fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1633                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1634         }
1635     }
1636
1637     return true;
1638 }
1639
1640 static bool parser_close_paren(parser_t *parser, shunt *sy)
1641 {
1642     if (!vec_size(sy->ops)) {
1643         parseerror(parser, "unmatched closing paren");
1644         return false;
1645     }
1646
1647     while (vec_size(sy->ops)) {
1648         if (vec_last(sy->ops).isparen) {
1649             if (vec_last(sy->paren) == PAREN_FUNC) {
1650                 vec_pop(sy->paren);
1651                 if (!parser_close_call(parser, sy))
1652                     return false;
1653                 break;
1654             }
1655             if (vec_last(sy->paren) == PAREN_EXPR) {
1656                 vec_pop(sy->paren);
1657                 if (!vec_size(sy->out)) {
1658                     compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1659                     vec_shrinkby(sy->ops, 1);
1660                     return false;
1661                 }
1662                 vec_shrinkby(sy->ops, 1);
1663                 break;
1664             }
1665             if (vec_last(sy->paren) == PAREN_INDEX) {
1666                 vec_pop(sy->paren);
1667                 /* pop off the parenthesis */
1668                 vec_shrinkby(sy->ops, 1);
1669                 /* then apply the index operator */
1670                 if (!parser_sy_apply_operator(parser, sy))
1671                     return false;
1672                 break;
1673             }
1674             if (vec_last(sy->paren) == PAREN_TERNARY1) {
1675                 vec_last(sy->paren) = PAREN_TERNARY2;
1676                 /* pop off the parenthesis */
1677                 vec_shrinkby(sy->ops, 1);
1678                 break;
1679             }
1680             compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1681             return false;
1682         }
1683         if (!parser_sy_apply_operator(parser, sy))
1684             return false;
1685     }
1686     return true;
1687 }
1688
1689 static void parser_reclassify_token(parser_t *parser)
1690 {
1691     size_t i;
1692     for (i = 0; i < operator_count; ++i) {
1693         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1694             parser->tok = TOKEN_OPERATOR;
1695             return;
1696         }
1697     }
1698 }
1699
1700 static ast_expression* parse_vararg_do(parser_t *parser)
1701 {
1702     ast_expression *idx, *out;
1703     ast_value      *typevar;
1704     ast_value      *funtype = parser->function->vtype;
1705
1706     lex_ctx ctx = parser_ctx(parser);
1707
1708     if (!parser_next(parser) || parser->tok != '(') {
1709         parseerror(parser, "expected parameter index and type in parenthesis");
1710         return NULL;
1711     }
1712     if (!parser_next(parser)) {
1713         parseerror(parser, "error parsing parameter index");
1714         return NULL;
1715     }
1716
1717     idx = parse_expression_leave(parser, true, false, false);
1718     if (!idx)
1719         return NULL;
1720
1721     if (parser->tok != ',') {
1722         ast_unref(idx);
1723         parseerror(parser, "expected comma after parameter index");
1724         return NULL;
1725     }
1726
1727     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1728         ast_unref(idx);
1729         parseerror(parser, "expected typename for vararg");
1730         return NULL;
1731     }
1732
1733     typevar = parse_typename(parser, NULL, NULL);
1734     if (!typevar) {
1735         ast_unref(idx);
1736         return NULL;
1737     }
1738
1739     if (parser->tok != ')') {
1740         ast_unref(idx);
1741         ast_delete(typevar);
1742         parseerror(parser, "expected closing paren");
1743         return NULL;
1744     }
1745
1746 #if 0
1747     if (!parser_next(parser)) {
1748         ast_unref(idx);
1749         ast_delete(typevar);
1750         parseerror(parser, "parse error after vararg");
1751         return NULL;
1752     }
1753 #endif
1754
1755     if (!parser->function->varargs) {
1756         ast_unref(idx);
1757         ast_delete(typevar);
1758         parseerror(parser, "function has no variable argument list");
1759         return NULL;
1760     }
1761
1762     if (funtype->expression.varparam &&
1763         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1764     {
1765         char ty1[1024];
1766         char ty2[1024];
1767         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1768         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1769         compile_error(ast_ctx(typevar),
1770                       "function was declared to take varargs of type `%s`, requested type is: %s",
1771                       ty2, ty1);
1772     }
1773
1774     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1775     ast_type_adopt(out, typevar);
1776     ast_delete(typevar);
1777     return out;
1778 }
1779
1780 static ast_expression* parse_vararg(parser_t *parser)
1781 {
1782     bool           old_noops = parser->lex->flags.noops;
1783
1784     ast_expression *out;
1785
1786     parser->lex->flags.noops = true;
1787     out = parse_vararg_do(parser);
1788
1789     parser->lex->flags.noops = old_noops;
1790     return out;
1791 }
1792
1793 /* not to be exposed */
1794 extern bool ftepp_predef_exists(const char *name);
1795
1796 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1797 {
1798     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1799         parser->tok == TOKEN_IDENT &&
1800         !strcmp(parser_tokval(parser), "_"))
1801     {
1802         /* a translatable string */
1803         ast_value *val;
1804
1805         parser->lex->flags.noops = true;
1806         if (!parser_next(parser) || parser->tok != '(') {
1807             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1808             return false;
1809         }
1810         parser->lex->flags.noops = false;
1811         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1812             parseerror(parser, "expected a constant string in translatable-string extension");
1813             return false;
1814         }
1815         val = parser_const_string(parser, parser_tokval(parser), true);
1816         if (!val)
1817             return false;
1818         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1819
1820         if (!parser_next(parser) || parser->tok != ')') {
1821             parseerror(parser, "expected closing paren after translatable string");
1822             return false;
1823         }
1824         return true;
1825     }
1826     else if (parser->tok == TOKEN_DOTS)
1827     {
1828         ast_expression *va;
1829         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1830             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1831             return false;
1832         }
1833         va = parse_vararg(parser);
1834         if (!va)
1835             return false;
1836         vec_push(sy->out, syexp(parser_ctx(parser), va));
1837         return true;
1838     }
1839     else if (parser->tok == TOKEN_FLOATCONST) {
1840         ast_value *val;
1841         val = parser_const_float(parser, (parser_token(parser)->constval.f));
1842         if (!val)
1843             return false;
1844         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1845         return true;
1846     }
1847     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1848         ast_value *val;
1849         val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1850         if (!val)
1851             return false;
1852         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1853         return true;
1854     }
1855     else if (parser->tok == TOKEN_STRINGCONST) {
1856         ast_value *val;
1857         val = parser_const_string(parser, parser_tokval(parser), false);
1858         if (!val)
1859             return false;
1860         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1861         return true;
1862     }
1863     else if (parser->tok == TOKEN_VECTORCONST) {
1864         ast_value *val;
1865         val = parser_const_vector(parser, parser_token(parser)->constval.v);
1866         if (!val)
1867             return false;
1868         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1869         return true;
1870     }
1871     else if (parser->tok == TOKEN_IDENT)
1872     {
1873         const char     *ctoken = parser_tokval(parser);
1874         ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1875         ast_expression *var;
1876         /* a_vector.{x,y,z} */
1877         if (!vec_size(sy->ops) ||
1878             !vec_last(sy->ops).etype ||
1879             operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1880             (prev >= intrinsic_debug_typestring &&
1881              prev <= intrinsic_debug_typestring))
1882         {
1883             /* When adding more intrinsics, fix the above condition */
1884             prev = NULL;
1885         }
1886         if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1887         {
1888             var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1889         } else {
1890             var = parser_find_var(parser, parser_tokval(parser));
1891             if (!var)
1892                 var = parser_find_field(parser, parser_tokval(parser));
1893         }
1894         if (!var && with_labels) {
1895             var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1896             if (!with_labels) {
1897                 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1898                 var = (ast_expression*)lbl;
1899                 vec_push(parser->labels, lbl);
1900             }
1901         }
1902         if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1903             var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1904         if (!var) {
1905             /* intrinsics */
1906             if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1907                 var = (ast_expression*)intrinsic_debug_typestring;
1908             }
1909             /* now we try for the real intrinsic hashtable. If the string
1910              * begins with __builtin, we simply skip past it, otherwise we
1911              * use the identifier as is.
1912              */
1913             else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1914                 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1915             }
1916
1917             if (!var) {
1918                 char *correct = NULL;
1919                 size_t i;
1920
1921                 /*
1922                  * sometimes people use preprocessing predefs without enabling them
1923                  * i've done this thousands of times already myself.  Lets check for
1924                  * it in the predef table.  And diagnose it better :)
1925                  */
1926                 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1927                     parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1928                     return false;
1929                 }
1930
1931                 /*
1932                  * TODO: determine the best score for the identifier: be it
1933                  * a variable, a field.
1934                  *
1935                  * We should also consider adding correction tables for
1936                  * other things as well.
1937                  */
1938                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1939                     correction_t corr;
1940                     correct_init(&corr);
1941
1942                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1943                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1944                         if (strcmp(correct, parser_tokval(parser))) {
1945                             break;
1946                         } else if (correct) {
1947                             mem_d(correct);
1948                             correct = NULL;
1949                         }
1950                     }
1951                     correct_free(&corr);
1952
1953                     if (correct) {
1954                         parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1955                         mem_d(correct);
1956                         return false;
1957                     }
1958                 }
1959                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1960                 return false;
1961             }
1962         }
1963         else
1964         {
1965             if (ast_istype(var, ast_value)) {
1966                 ((ast_value*)var)->uses++;
1967             }
1968             else if (ast_istype(var, ast_member)) {
1969                 ast_member *mem = (ast_member*)var;
1970                 if (ast_istype(mem->owner, ast_value))
1971                     ((ast_value*)(mem->owner))->uses++;
1972             }
1973         }
1974         vec_push(sy->out, syexp(parser_ctx(parser), var));
1975         return true;
1976     }
1977     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1978     return false;
1979 }
1980
1981 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1982 {
1983     ast_expression *expr = NULL;
1984     shunt sy;
1985     size_t i;
1986     bool wantop = false;
1987     /* only warn once about an assignment in a truth value because the current code
1988      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1989      */
1990     bool warn_truthvalue = true;
1991
1992     /* count the parens because an if starts with one, so the
1993      * end of a condition is an unmatched closing paren
1994      */
1995     int ternaries = 0;
1996
1997     memset(&sy, 0, sizeof(sy));
1998
1999     parser->lex->flags.noops = false;
2000
2001     parser_reclassify_token(parser);
2002
2003     while (true)
2004     {
2005         if (parser->tok == TOKEN_TYPENAME) {
2006             parseerror(parser, "unexpected typename");
2007             goto onerr;
2008         }
2009
2010         if (parser->tok == TOKEN_OPERATOR)
2011         {
2012             /* classify the operator */
2013             const oper_info *op;
2014             const oper_info *olast = NULL;
2015             size_t o;
2016             for (o = 0; o < operator_count; ++o) {
2017                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2018                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2019                     !strcmp(parser_tokval(parser), operators[o].op))
2020                 {
2021                     break;
2022                 }
2023             }
2024             if (o == operator_count) {
2025                 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2026                 goto onerr;
2027             }
2028             /* found an operator */
2029             op = &operators[o];
2030
2031             /* when declaring variables, a comma starts a new variable */
2032             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2033                 /* fixup the token */
2034                 parser->tok = ',';
2035                 break;
2036             }
2037
2038             /* a colon without a pervious question mark cannot be a ternary */
2039             if (!ternaries && op->id == opid2(':','?')) {
2040                 parser->tok = ':';
2041                 break;
2042             }
2043
2044             if (op->id == opid1(',')) {
2045                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2046                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2047                 }
2048             }
2049
2050             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2051                 olast = &operators[vec_last(sy.ops).etype-1];
2052
2053 #define IsAssignOp(x) (\
2054                 (x) == opid1('=') || \
2055                 (x) == opid2('+','=') || \
2056                 (x) == opid2('-','=') || \
2057                 (x) == opid2('*','=') || \
2058                 (x) == opid2('/','=') || \
2059                 (x) == opid2('%','=') || \
2060                 (x) == opid2('&','=') || \
2061                 (x) == opid2('|','=') || \
2062                 (x) == opid3('&','~','=') \
2063                 )
2064             if (warn_truthvalue) {
2065                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2066                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2067                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2068                    )
2069                 {
2070                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2071                     warn_truthvalue = false;
2072                 }
2073             }
2074
2075             while (olast && (
2076                     (op->prec < olast->prec) ||
2077                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2078             {
2079                 if (!parser_sy_apply_operator(parser, &sy))
2080                     goto onerr;
2081                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2082                     olast = &operators[vec_last(sy.ops).etype-1];
2083                 else
2084                     olast = NULL;
2085             }
2086
2087             if (op->id == opid1('(')) {
2088                 if (wantop) {
2089                     size_t sycount = vec_size(sy.out);
2090                     /* we expected an operator, this is the function-call operator */
2091                     vec_push(sy.paren, PAREN_FUNC);
2092                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2093                     vec_push(sy.argc, 0);
2094                 } else {
2095                     vec_push(sy.paren, PAREN_EXPR);
2096                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2097                 }
2098                 wantop = false;
2099             } else if (op->id == opid1('[')) {
2100                 if (!wantop) {
2101                     parseerror(parser, "unexpected array subscript");
2102                     goto onerr;
2103                 }
2104                 vec_push(sy.paren, PAREN_INDEX);
2105                 /* push both the operator and the paren, this makes life easier */
2106                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2107                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2108                 wantop = false;
2109             } else if (op->id == opid2('?',':')) {
2110                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2111                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2112                 wantop = false;
2113                 ++ternaries;
2114                 vec_push(sy.paren, PAREN_TERNARY1);
2115             } else if (op->id == opid2(':','?')) {
2116                 if (!vec_size(sy.paren)) {
2117                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2118                     goto onerr;
2119                 }
2120                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2121                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2122                     goto onerr;
2123                 }
2124                 if (!parser_close_paren(parser, &sy))
2125                     goto onerr;
2126                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2127                 wantop = false;
2128                 --ternaries;
2129             } else {
2130                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2131                 wantop = !!(op->flags & OP_SUFFIX);
2132             }
2133         }
2134         else if (parser->tok == ')') {
2135             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2136                 if (!parser_sy_apply_operator(parser, &sy))
2137                     goto onerr;
2138             }
2139             if (!vec_size(sy.paren))
2140                 break;
2141             if (wantop) {
2142                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2143                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2144                     goto onerr;
2145                 }
2146                 if (!parser_close_paren(parser, &sy))
2147                     goto onerr;
2148             } else {
2149                 /* must be a function call without parameters */
2150                 if (vec_last(sy.paren) != PAREN_FUNC) {
2151                     parseerror(parser, "closing paren in invalid position");
2152                     goto onerr;
2153                 }
2154                 if (!parser_close_paren(parser, &sy))
2155                     goto onerr;
2156             }
2157             wantop = true;
2158         }
2159         else if (parser->tok == '(') {
2160             parseerror(parser, "internal error: '(' should be classified as operator");
2161             goto onerr;
2162         }
2163         else if (parser->tok == '[') {
2164             parseerror(parser, "internal error: '[' should be classified as operator");
2165             goto onerr;
2166         }
2167         else if (parser->tok == ']') {
2168             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2169                 if (!parser_sy_apply_operator(parser, &sy))
2170                     goto onerr;
2171             }
2172             if (!vec_size(sy.paren))
2173                 break;
2174             if (vec_last(sy.paren) != PAREN_INDEX) {
2175                 parseerror(parser, "mismatched parentheses, unexpected ']'");
2176                 goto onerr;
2177             }
2178             if (!parser_close_paren(parser, &sy))
2179                 goto onerr;
2180             wantop = true;
2181         }
2182         else if (!wantop) {
2183             if (!parse_sya_operand(parser, &sy, with_labels))
2184                 goto onerr;
2185 #if 0
2186             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2187                 vec_last(sy.argc)++;
2188 #endif
2189             wantop = true;
2190         }
2191         else {
2192             /* in this case we might want to allow constant string concatenation */
2193             bool concatenated = false;
2194             if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2195                 ast_expression *lexpr = vec_last(sy.out).out;
2196                 if (ast_istype(lexpr, ast_value)) {
2197                     ast_value *last = (ast_value*)lexpr;
2198                     if (last->isimm == true && last->cvq == CV_CONST &&
2199                         last->hasvalue && last->expression.vtype == TYPE_STRING)
2200                     {
2201                         char *newstr = NULL;
2202                         util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2203                         vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2204                         mem_d(newstr);
2205                         concatenated = true;
2206                     }
2207                 }
2208             }
2209             if (!concatenated) {
2210                 parseerror(parser, "expected operator or end of statement");
2211                 goto onerr;
2212             }
2213         }
2214
2215         if (!parser_next(parser)) {
2216             goto onerr;
2217         }
2218         if (parser->tok == ';' ||
2219             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2220             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2221         {
2222             break;
2223         }
2224     }
2225
2226     while (vec_size(sy.ops)) {
2227         if (!parser_sy_apply_operator(parser, &sy))
2228             goto onerr;
2229     }
2230
2231     parser->lex->flags.noops = true;
2232     if (!vec_size(sy.out)) {
2233         parseerror(parser, "empty expression");
2234         expr = NULL;
2235     } else
2236         expr = sy.out[0].out;
2237     vec_free(sy.out);
2238     vec_free(sy.ops);
2239     if (vec_size(sy.paren)) {
2240         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2241         return NULL;
2242     }
2243     vec_free(sy.paren);
2244     vec_free(sy.argc);
2245     return expr;
2246
2247 onerr:
2248     parser->lex->flags.noops = true;
2249     for (i = 0; i < vec_size(sy.out); ++i) {
2250         if (sy.out[i].out)
2251             ast_unref(sy.out[i].out);
2252     }
2253     vec_free(sy.out);
2254     vec_free(sy.ops);
2255     vec_free(sy.paren);
2256     vec_free(sy.argc);
2257     return NULL;
2258 }
2259
2260 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2261 {
2262     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2263     if (!e)
2264         return NULL;
2265     if (parser->tok != ';') {
2266         parseerror(parser, "semicolon expected after expression");
2267         ast_unref(e);
2268         return NULL;
2269     }
2270     if (!parser_next(parser)) {
2271         ast_unref(e);
2272         return NULL;
2273     }
2274     return e;
2275 }
2276
2277 static void parser_enterblock(parser_t *parser)
2278 {
2279     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2280     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2281     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2282     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2283     vec_push(parser->_block_ctx, parser_ctx(parser));
2284
2285     /* corrector */
2286     vec_push(parser->correct_variables, correct_trie_new());
2287     vec_push(parser->correct_variables_score, NULL);
2288 }
2289
2290 static bool parser_leaveblock(parser_t *parser)
2291 {
2292     bool   rv = true;
2293     size_t locals, typedefs;
2294
2295     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2296         parseerror(parser, "internal error: parser_leaveblock with no block");
2297         return false;
2298     }
2299
2300     util_htdel(vec_last(parser->variables));
2301     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2302
2303     vec_pop(parser->variables);
2304     vec_pop(parser->correct_variables);
2305     vec_pop(parser->correct_variables_score);
2306     if (!vec_size(parser->_blocklocals)) {
2307         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2308         return false;
2309     }
2310
2311     locals = vec_last(parser->_blocklocals);
2312     vec_pop(parser->_blocklocals);
2313     while (vec_size(parser->_locals) != locals) {
2314         ast_expression *e = vec_last(parser->_locals);
2315         ast_value      *v = (ast_value*)e;
2316         vec_pop(parser->_locals);
2317         if (ast_istype(e, ast_value) && !v->uses) {
2318             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2319                 rv = false;
2320         }
2321     }
2322
2323     typedefs = vec_last(parser->_blocktypedefs);
2324     while (vec_size(parser->_typedefs) != typedefs) {
2325         ast_delete(vec_last(parser->_typedefs));
2326         vec_pop(parser->_typedefs);
2327     }
2328     util_htdel(vec_last(parser->typedefs));
2329     vec_pop(parser->typedefs);
2330
2331     vec_pop(parser->_block_ctx);
2332
2333     return rv;
2334 }
2335
2336 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2337 {
2338     vec_push(parser->_locals, e);
2339     util_htset(vec_last(parser->variables), name, (void*)e);
2340
2341     /* corrector */
2342     correct_add (
2343          vec_last(parser->correct_variables),
2344         &vec_last(parser->correct_variables_score),
2345         name
2346     );
2347 }
2348
2349 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2350 {
2351     vec_push(parser->globals, e);
2352     util_htset(parser->htglobals, name, e);
2353
2354     /* corrector */
2355     correct_add (
2356          parser->correct_variables[0],
2357         &parser->correct_variables_score[0],
2358         name
2359     );
2360 }
2361
2362 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2363 {
2364     bool       ifnot = false;
2365     ast_unary *unary;
2366     ast_expression *prev;
2367
2368     if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2369         char ty[1024];
2370         ast_type_to_string(cond, ty, sizeof(ty));
2371         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2372     }
2373
2374     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2375     {
2376         prev = cond;
2377         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2378         if (!cond) {
2379             ast_unref(prev);
2380             parseerror(parser, "internal error: failed to process condition");
2381             return NULL;
2382         }
2383         ifnot = !ifnot;
2384     }
2385     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2386     {
2387         /* vector types need to be cast to true booleans */
2388         ast_binary *bin = (ast_binary*)cond;
2389         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2390         {
2391             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2392             prev = cond;
2393             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2394             if (!cond) {
2395                 ast_unref(prev);
2396                 parseerror(parser, "internal error: failed to process condition");
2397                 return NULL;
2398             }
2399             ifnot = !ifnot;
2400         }
2401     }
2402
2403     unary = (ast_unary*)cond;
2404     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2405     {
2406         cond = unary->operand;
2407         unary->operand = NULL;
2408         ast_delete(unary);
2409         ifnot = !ifnot;
2410         unary = (ast_unary*)cond;
2411     }
2412
2413     if (!cond)
2414         parseerror(parser, "internal error: failed to process condition");
2415
2416     if (ifnot) *_ifnot = !*_ifnot;
2417     return cond;
2418 }
2419
2420 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2421 {
2422     ast_ifthen *ifthen;
2423     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2424     bool ifnot = false;
2425
2426     lex_ctx ctx = parser_ctx(parser);
2427
2428     (void)block; /* not touching */
2429
2430     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2431     if (!parser_next(parser)) {
2432         parseerror(parser, "expected condition or 'not'");
2433         return false;
2434     }
2435     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2436         ifnot = true;
2437         if (!parser_next(parser)) {
2438             parseerror(parser, "expected condition in parenthesis");
2439             return false;
2440         }
2441     }
2442     if (parser->tok != '(') {
2443         parseerror(parser, "expected 'if' condition in parenthesis");
2444         return false;
2445     }
2446     /* parse into the expression */
2447     if (!parser_next(parser)) {
2448         parseerror(parser, "expected 'if' condition after opening paren");
2449         return false;
2450     }
2451     /* parse the condition */
2452     cond = parse_expression_leave(parser, false, true, false);
2453     if (!cond)
2454         return false;
2455     /* closing paren */
2456     if (parser->tok != ')') {
2457         parseerror(parser, "expected closing paren after 'if' condition");
2458         ast_delete(cond);
2459         return false;
2460     }
2461     /* parse into the 'then' branch */
2462     if (!parser_next(parser)) {
2463         parseerror(parser, "expected statement for on-true branch of 'if'");
2464         ast_delete(cond);
2465         return false;
2466     }
2467     if (!parse_statement_or_block(parser, &ontrue)) {
2468         ast_delete(cond);
2469         return false;
2470     }
2471     if (!ontrue)
2472         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2473     /* check for an else */
2474     if (!strcmp(parser_tokval(parser), "else")) {
2475         /* parse into the 'else' branch */
2476         if (!parser_next(parser)) {
2477             parseerror(parser, "expected on-false branch after 'else'");
2478             ast_delete(ontrue);
2479             ast_delete(cond);
2480             return false;
2481         }
2482         if (!parse_statement_or_block(parser, &onfalse)) {
2483             ast_delete(ontrue);
2484             ast_delete(cond);
2485             return false;
2486         }
2487     }
2488
2489     cond = process_condition(parser, cond, &ifnot);
2490     if (!cond) {
2491         if (ontrue)  ast_delete(ontrue);
2492         if (onfalse) ast_delete(onfalse);
2493         return false;
2494     }
2495
2496     if (ifnot)
2497         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2498     else
2499         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2500     *out = (ast_expression*)ifthen;
2501     return true;
2502 }
2503
2504 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2505 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2506 {
2507     bool rv;
2508     char *label = NULL;
2509
2510     /* skip the 'while' and get the body */
2511     if (!parser_next(parser)) {
2512         if (OPTS_FLAG(LOOP_LABELS))
2513             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2514         else
2515             parseerror(parser, "expected 'while' condition in parenthesis");
2516         return false;
2517     }
2518
2519     if (parser->tok == ':') {
2520         if (!OPTS_FLAG(LOOP_LABELS))
2521             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2522         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2523             parseerror(parser, "expected loop label");
2524             return false;
2525         }
2526         label = util_strdup(parser_tokval(parser));
2527         if (!parser_next(parser)) {
2528             mem_d(label);
2529             parseerror(parser, "expected 'while' condition in parenthesis");
2530             return false;
2531         }
2532     }
2533
2534     if (parser->tok != '(') {
2535         parseerror(parser, "expected 'while' condition in parenthesis");
2536         return false;
2537     }
2538
2539     vec_push(parser->breaks, label);
2540     vec_push(parser->continues, label);
2541
2542     rv = parse_while_go(parser, block, out);
2543     if (label)
2544         mem_d(label);
2545     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2546         parseerror(parser, "internal error: label stack corrupted");
2547         rv = false;
2548         ast_delete(*out);
2549         *out = NULL;
2550     }
2551     else {
2552         vec_pop(parser->breaks);
2553         vec_pop(parser->continues);
2554     }
2555     return rv;
2556 }
2557
2558 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2559 {
2560     ast_loop *aloop;
2561     ast_expression *cond, *ontrue;
2562
2563     bool ifnot = false;
2564
2565     lex_ctx ctx = parser_ctx(parser);
2566
2567     (void)block; /* not touching */
2568
2569     /* parse into the expression */
2570     if (!parser_next(parser)) {
2571         parseerror(parser, "expected 'while' condition after opening paren");
2572         return false;
2573     }
2574     /* parse the condition */
2575     cond = parse_expression_leave(parser, false, true, false);
2576     if (!cond)
2577         return false;
2578     /* closing paren */
2579     if (parser->tok != ')') {
2580         parseerror(parser, "expected closing paren after 'while' condition");
2581         ast_delete(cond);
2582         return false;
2583     }
2584     /* parse into the 'then' branch */
2585     if (!parser_next(parser)) {
2586         parseerror(parser, "expected while-loop body");
2587         ast_delete(cond);
2588         return false;
2589     }
2590     if (!parse_statement_or_block(parser, &ontrue)) {
2591         ast_delete(cond);
2592         return false;
2593     }
2594
2595     cond = process_condition(parser, cond, &ifnot);
2596     if (!cond) {
2597         ast_delete(ontrue);
2598         return false;
2599     }
2600     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2601     *out = (ast_expression*)aloop;
2602     return true;
2603 }
2604
2605 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2606 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2607 {
2608     bool rv;
2609     char *label = NULL;
2610
2611     /* skip the 'do' and get the body */
2612     if (!parser_next(parser)) {
2613         if (OPTS_FLAG(LOOP_LABELS))
2614             parseerror(parser, "expected loop label or body");
2615         else
2616             parseerror(parser, "expected loop body");
2617         return false;
2618     }
2619
2620     if (parser->tok == ':') {
2621         if (!OPTS_FLAG(LOOP_LABELS))
2622             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2623         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2624             parseerror(parser, "expected loop label");
2625             return false;
2626         }
2627         label = util_strdup(parser_tokval(parser));
2628         if (!parser_next(parser)) {
2629             mem_d(label);
2630             parseerror(parser, "expected loop body");
2631             return false;
2632         }
2633     }
2634
2635     vec_push(parser->breaks, label);
2636     vec_push(parser->continues, label);
2637
2638     rv = parse_dowhile_go(parser, block, out);
2639     if (label)
2640         mem_d(label);
2641     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2642         parseerror(parser, "internal error: label stack corrupted");
2643         rv = false;
2644         ast_delete(*out);
2645         *out = NULL;
2646     }
2647     else {
2648         vec_pop(parser->breaks);
2649         vec_pop(parser->continues);
2650     }
2651     return rv;
2652 }
2653
2654 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2655 {
2656     ast_loop *aloop;
2657     ast_expression *cond, *ontrue;
2658
2659     bool ifnot = false;
2660
2661     lex_ctx ctx = parser_ctx(parser);
2662
2663     (void)block; /* not touching */
2664
2665     if (!parse_statement_or_block(parser, &ontrue))
2666         return false;
2667
2668     /* expect the "while" */
2669     if (parser->tok != TOKEN_KEYWORD ||
2670         strcmp(parser_tokval(parser), "while"))
2671     {
2672         parseerror(parser, "expected 'while' and condition");
2673         ast_delete(ontrue);
2674         return false;
2675     }
2676
2677     /* skip the 'while' and check for opening paren */
2678     if (!parser_next(parser) || parser->tok != '(') {
2679         parseerror(parser, "expected 'while' condition in parenthesis");
2680         ast_delete(ontrue);
2681         return false;
2682     }
2683     /* parse into the expression */
2684     if (!parser_next(parser)) {
2685         parseerror(parser, "expected 'while' condition after opening paren");
2686         ast_delete(ontrue);
2687         return false;
2688     }
2689     /* parse the condition */
2690     cond = parse_expression_leave(parser, false, true, false);
2691     if (!cond)
2692         return false;
2693     /* closing paren */
2694     if (parser->tok != ')') {
2695         parseerror(parser, "expected closing paren after 'while' condition");
2696         ast_delete(ontrue);
2697         ast_delete(cond);
2698         return false;
2699     }
2700     /* parse on */
2701     if (!parser_next(parser) || parser->tok != ';') {
2702         parseerror(parser, "expected semicolon after condition");
2703         ast_delete(ontrue);
2704         ast_delete(cond);
2705         return false;
2706     }
2707
2708     if (!parser_next(parser)) {
2709         parseerror(parser, "parse error");
2710         ast_delete(ontrue);
2711         ast_delete(cond);
2712         return false;
2713     }
2714
2715     cond = process_condition(parser, cond, &ifnot);
2716     if (!cond) {
2717         ast_delete(ontrue);
2718         return false;
2719     }
2720     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2721     *out = (ast_expression*)aloop;
2722     return true;
2723 }
2724
2725 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2726 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2727 {
2728     bool rv;
2729     char *label = NULL;
2730
2731     /* skip the 'for' and check for opening paren */
2732     if (!parser_next(parser)) {
2733         if (OPTS_FLAG(LOOP_LABELS))
2734             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2735         else
2736             parseerror(parser, "expected 'for' expressions in parenthesis");
2737         return false;
2738     }
2739
2740     if (parser->tok == ':') {
2741         if (!OPTS_FLAG(LOOP_LABELS))
2742             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2743         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2744             parseerror(parser, "expected loop label");
2745             return false;
2746         }
2747         label = util_strdup(parser_tokval(parser));
2748         if (!parser_next(parser)) {
2749             mem_d(label);
2750             parseerror(parser, "expected 'for' expressions in parenthesis");
2751             return false;
2752         }
2753     }
2754
2755     if (parser->tok != '(') {
2756         parseerror(parser, "expected 'for' expressions in parenthesis");
2757         return false;
2758     }
2759
2760     vec_push(parser->breaks, label);
2761     vec_push(parser->continues, label);
2762
2763     rv = parse_for_go(parser, block, out);
2764     if (label)
2765         mem_d(label);
2766     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2767         parseerror(parser, "internal error: label stack corrupted");
2768         rv = false;
2769         ast_delete(*out);
2770         *out = NULL;
2771     }
2772     else {
2773         vec_pop(parser->breaks);
2774         vec_pop(parser->continues);
2775     }
2776     return rv;
2777 }
2778 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2779 {
2780     ast_loop       *aloop;
2781     ast_expression *initexpr, *cond, *increment, *ontrue;
2782     ast_value      *typevar;
2783
2784     bool retval = true;
2785     bool ifnot  = false;
2786
2787     lex_ctx ctx = parser_ctx(parser);
2788
2789     parser_enterblock(parser);
2790
2791     initexpr  = NULL;
2792     cond      = NULL;
2793     increment = NULL;
2794     ontrue    = NULL;
2795
2796     /* parse into the expression */
2797     if (!parser_next(parser)) {
2798         parseerror(parser, "expected 'for' initializer after opening paren");
2799         goto onerr;
2800     }
2801
2802     typevar = NULL;
2803     if (parser->tok == TOKEN_IDENT)
2804         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2805
2806     if (typevar || parser->tok == TOKEN_TYPENAME) {
2807 #if 0
2808         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2809             if (parsewarning(parser, WARN_EXTENSIONS,
2810                              "current standard does not allow variable declarations in for-loop initializers"))
2811                 goto onerr;
2812         }
2813 #endif
2814         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2815             goto onerr;
2816     }
2817     else if (parser->tok != ';')
2818     {
2819         initexpr = parse_expression_leave(parser, false, false, false);
2820         if (!initexpr)
2821             goto onerr;
2822     }
2823
2824     /* move on to condition */
2825     if (parser->tok != ';') {
2826         parseerror(parser, "expected semicolon after for-loop initializer");
2827         goto onerr;
2828     }
2829     if (!parser_next(parser)) {
2830         parseerror(parser, "expected for-loop condition");
2831         goto onerr;
2832     }
2833
2834     /* parse the condition */
2835     if (parser->tok != ';') {
2836         cond = parse_expression_leave(parser, false, true, false);
2837         if (!cond)
2838             goto onerr;
2839     }
2840
2841     /* move on to incrementor */
2842     if (parser->tok != ';') {
2843         parseerror(parser, "expected semicolon after for-loop initializer");
2844         goto onerr;
2845     }
2846     if (!parser_next(parser)) {
2847         parseerror(parser, "expected for-loop condition");
2848         goto onerr;
2849     }
2850
2851     /* parse the incrementor */
2852     if (parser->tok != ')') {
2853         lex_ctx condctx = parser_ctx(parser);
2854         increment = parse_expression_leave(parser, false, false, false);
2855         if (!increment)
2856             goto onerr;
2857         if (!ast_side_effects(increment)) {
2858             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2859                 goto onerr;
2860         }
2861     }
2862
2863     /* closing paren */
2864     if (parser->tok != ')') {
2865         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2866         goto onerr;
2867     }
2868     /* parse into the 'then' branch */
2869     if (!parser_next(parser)) {
2870         parseerror(parser, "expected for-loop body");
2871         goto onerr;
2872     }
2873     if (!parse_statement_or_block(parser, &ontrue))
2874         goto onerr;
2875
2876     if (cond) {
2877         cond = process_condition(parser, cond, &ifnot);
2878         if (!cond)
2879             goto onerr;
2880     }
2881     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2882     *out = (ast_expression*)aloop;
2883
2884     if (!parser_leaveblock(parser))
2885         retval = false;
2886     return retval;
2887 onerr:
2888     if (initexpr)  ast_delete(initexpr);
2889     if (cond)      ast_delete(cond);
2890     if (increment) ast_delete(increment);
2891     (void)!parser_leaveblock(parser);
2892     return false;
2893 }
2894
2895 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2896 {
2897     ast_expression *exp = NULL;
2898     ast_return     *ret = NULL;
2899     ast_value      *expected = parser->function->vtype;
2900
2901     lex_ctx ctx = parser_ctx(parser);
2902
2903     (void)block; /* not touching */
2904
2905     if (!parser_next(parser)) {
2906         parseerror(parser, "expected return expression");
2907         return false;
2908     }
2909
2910     if (parser->tok != ';') {
2911         exp = parse_expression(parser, false, false);
2912         if (!exp)
2913             return false;
2914
2915         if (exp->expression.vtype != TYPE_NIL &&
2916             exp->expression.vtype != expected->expression.next->expression.vtype)
2917         {
2918             parseerror(parser, "return with invalid expression");
2919         }
2920
2921         ret = ast_return_new(ctx, exp);
2922         if (!ret) {
2923             ast_delete(exp);
2924             return false;
2925         }
2926     } else {
2927         if (!parser_next(parser))
2928             parseerror(parser, "parse error");
2929         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2930             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2931         }
2932         ret = ast_return_new(ctx, NULL);
2933     }
2934     *out = (ast_expression*)ret;
2935     return true;
2936 }
2937
2938 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2939 {
2940     size_t       i;
2941     unsigned int levels = 0;
2942     lex_ctx      ctx = parser_ctx(parser);
2943     const char **loops = (is_continue ? parser->continues : parser->breaks);
2944
2945     (void)block; /* not touching */
2946     if (!parser_next(parser)) {
2947         parseerror(parser, "expected semicolon or loop label");
2948         return false;
2949     }
2950
2951     if (!vec_size(loops)) {
2952         if (is_continue)
2953             parseerror(parser, "`continue` can only be used inside loops");
2954         else
2955             parseerror(parser, "`break` can only be used inside loops or switches");
2956     }
2957
2958     if (parser->tok == TOKEN_IDENT) {
2959         if (!OPTS_FLAG(LOOP_LABELS))
2960             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2961         i = vec_size(loops);
2962         while (i--) {
2963             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2964                 break;
2965             if (!i) {
2966                 parseerror(parser, "no such loop to %s: `%s`",
2967                            (is_continue ? "continue" : "break out of"),
2968                            parser_tokval(parser));
2969                 return false;
2970             }
2971             ++levels;
2972         }
2973         if (!parser_next(parser)) {
2974             parseerror(parser, "expected semicolon");
2975             return false;
2976         }
2977     }
2978
2979     if (parser->tok != ';') {
2980         parseerror(parser, "expected semicolon");
2981         return false;
2982     }
2983
2984     if (!parser_next(parser))
2985         parseerror(parser, "parse error");
2986
2987     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2988     return true;
2989 }
2990
2991 /* returns true when it was a variable qualifier, false otherwise!
2992  * on error, cvq is set to CV_WRONG
2993  */
2994 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2995 {
2996     bool had_const    = false;
2997     bool had_var      = false;
2998     bool had_noref    = false;
2999     bool had_attrib   = false;
3000     bool had_static   = false;
3001     uint32_t flags    = 0;
3002
3003     *cvq = CV_NONE;
3004     for (;;) {
3005         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3006             had_attrib = true;
3007             /* parse an attribute */
3008             if (!parser_next(parser)) {
3009                 parseerror(parser, "expected attribute after `[[`");
3010                 *cvq = CV_WRONG;
3011                 return false;
3012             }
3013             if (!strcmp(parser_tokval(parser), "noreturn")) {
3014                 flags |= AST_FLAG_NORETURN;
3015                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3016                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3017                     *cvq = CV_WRONG;
3018                     return false;
3019                 }
3020             }
3021             else if (!strcmp(parser_tokval(parser), "noref")) {
3022                 had_noref = true;
3023                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3024                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3025                     *cvq = CV_WRONG;
3026                     return false;
3027                 }
3028             }
3029             else if (!strcmp(parser_tokval(parser), "inline")) {
3030                 flags |= AST_FLAG_INLINE;
3031                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3032                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3033                     *cvq = CV_WRONG;
3034                     return false;
3035                 }
3036             }
3037             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3038                 flags   |= AST_FLAG_ALIAS;
3039                 *message = NULL;
3040
3041                 if (!parser_next(parser)) {
3042                     parseerror(parser, "parse error in attribute");
3043                     goto argerr;
3044                 }
3045
3046                 if (parser->tok == '(') {
3047                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3048                         parseerror(parser, "`alias` attribute missing parameter");
3049                         goto argerr;
3050                     }
3051
3052                     *message = util_strdup(parser_tokval(parser));
3053
3054                     if (!parser_next(parser)) {
3055                         parseerror(parser, "parse error in attribute");
3056                         goto argerr;
3057                     }
3058
3059                     if (parser->tok != ')') {
3060                         parseerror(parser, "`alias` attribute expected `)` after parameter");
3061                         goto argerr;
3062                     }
3063
3064                     if (!parser_next(parser)) {
3065                         parseerror(parser, "parse error in attribute");
3066                         goto argerr;
3067                     }
3068                 }
3069
3070                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3071                     parseerror(parser, "`alias` attribute expected `]]`");
3072                     goto argerr;
3073                 }
3074             }
3075             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3076                 flags   |= AST_FLAG_DEPRECATED;
3077                 *message = NULL;
3078
3079                 if (!parser_next(parser)) {
3080                     parseerror(parser, "parse error in attribute");
3081                     goto argerr;
3082                 }
3083
3084                 if (parser->tok == '(') {
3085                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3086                         parseerror(parser, "`deprecated` attribute missing parameter");
3087                         goto argerr;
3088                     }
3089
3090                     *message = util_strdup(parser_tokval(parser));
3091
3092                     if (!parser_next(parser)) {
3093                         parseerror(parser, "parse error in attribute");
3094                         goto argerr;
3095                     }
3096
3097                     if(parser->tok != ')') {
3098                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3099                         goto argerr;
3100                     }
3101
3102                     if (!parser_next(parser)) {
3103                         parseerror(parser, "parse error in attribute");
3104                         goto argerr;
3105                     }
3106                 }
3107                 /* no message */
3108                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3109                     parseerror(parser, "`deprecated` attribute expected `]]`");
3110
3111                     argerr: /* ugly */
3112                     if (*message) mem_d(*message);
3113                     *message = NULL;
3114                     *cvq     = CV_WRONG;
3115                     return false;
3116                 }
3117             }
3118             else
3119             {
3120                 /* Skip tokens until we hit a ]] */
3121                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3122                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3123                     if (!parser_next(parser)) {
3124                         parseerror(parser, "error inside attribute");
3125                         *cvq = CV_WRONG;
3126                         return false;
3127                     }
3128                 }
3129             }
3130         }
3131         else if (with_local && !strcmp(parser_tokval(parser), "static"))
3132             had_static = true;
3133         else if (!strcmp(parser_tokval(parser), "const"))
3134             had_const = true;
3135         else if (!strcmp(parser_tokval(parser), "var"))
3136             had_var = true;
3137         else if (with_local && !strcmp(parser_tokval(parser), "local"))
3138             had_var = true;
3139         else if (!strcmp(parser_tokval(parser), "noref"))
3140             had_noref = true;
3141         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3142             return false;
3143         }
3144         else
3145             break;
3146         if (!parser_next(parser))
3147             goto onerr;
3148     }
3149     if (had_const)
3150         *cvq = CV_CONST;
3151     else if (had_var)
3152         *cvq = CV_VAR;
3153     else
3154         *cvq = CV_NONE;
3155     *noref     = had_noref;
3156     *is_static = had_static;
3157     *_flags    = flags;
3158     return true;
3159 onerr:
3160     parseerror(parser, "parse error after variable qualifier");
3161     *cvq = CV_WRONG;
3162     return true;
3163 }
3164
3165 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3166 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3167 {
3168     bool rv;
3169     char *label = NULL;
3170
3171     /* skip the 'while' and get the body */
3172     if (!parser_next(parser)) {
3173         if (OPTS_FLAG(LOOP_LABELS))
3174             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3175         else
3176             parseerror(parser, "expected 'switch' operand in parenthesis");
3177         return false;
3178     }
3179
3180     if (parser->tok == ':') {
3181         if (!OPTS_FLAG(LOOP_LABELS))
3182             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3183         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3184             parseerror(parser, "expected loop label");
3185             return false;
3186         }
3187         label = util_strdup(parser_tokval(parser));
3188         if (!parser_next(parser)) {
3189             mem_d(label);
3190             parseerror(parser, "expected 'switch' operand in parenthesis");
3191             return false;
3192         }
3193     }
3194
3195     if (parser->tok != '(') {
3196         parseerror(parser, "expected 'switch' operand in parenthesis");
3197         return false;
3198     }
3199
3200     vec_push(parser->breaks, label);
3201
3202     rv = parse_switch_go(parser, block, out);
3203     if (label)
3204         mem_d(label);
3205     if (vec_last(parser->breaks) != label) {
3206         parseerror(parser, "internal error: label stack corrupted");
3207         rv = false;
3208         ast_delete(*out);
3209         *out = NULL;
3210     }
3211     else {
3212         vec_pop(parser->breaks);
3213     }
3214     return rv;
3215 }
3216
3217 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3218 {
3219     ast_expression *operand;
3220     ast_value      *opval;
3221     ast_value      *typevar;
3222     ast_switch     *switchnode;
3223     ast_switch_case swcase;
3224
3225     int  cvq;
3226     bool noref, is_static;
3227     uint32_t qflags = 0;
3228
3229     lex_ctx ctx = parser_ctx(parser);
3230
3231     (void)block; /* not touching */
3232     (void)opval;
3233
3234     /* parse into the expression */
3235     if (!parser_next(parser)) {
3236         parseerror(parser, "expected switch operand");
3237         return false;
3238     }
3239     /* parse the operand */
3240     operand = parse_expression_leave(parser, false, false, false);
3241     if (!operand)
3242         return false;
3243
3244     switchnode = ast_switch_new(ctx, operand);
3245
3246     /* closing paren */
3247     if (parser->tok != ')') {
3248         ast_delete(switchnode);
3249         parseerror(parser, "expected closing paren after 'switch' operand");
3250         return false;
3251     }
3252
3253     /* parse over the opening paren */
3254     if (!parser_next(parser) || parser->tok != '{') {
3255         ast_delete(switchnode);
3256         parseerror(parser, "expected list of cases");
3257         return false;
3258     }
3259
3260     if (!parser_next(parser)) {
3261         ast_delete(switchnode);
3262         parseerror(parser, "expected 'case' or 'default'");
3263         return false;
3264     }
3265
3266     /* new block; allow some variables to be declared here */
3267     parser_enterblock(parser);
3268     while (true) {
3269         typevar = NULL;
3270         if (parser->tok == TOKEN_IDENT)
3271             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3272         if (typevar || parser->tok == TOKEN_TYPENAME) {
3273             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3274                 ast_delete(switchnode);
3275                 return false;
3276             }
3277             continue;
3278         }
3279         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3280         {
3281             if (cvq == CV_WRONG) {
3282                 ast_delete(switchnode);
3283                 return false;
3284             }
3285             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3286                 ast_delete(switchnode);
3287                 return false;
3288             }
3289             continue;
3290         }
3291         break;
3292     }
3293
3294     /* case list! */
3295     while (parser->tok != '}') {
3296         ast_block *caseblock;
3297
3298         if (!strcmp(parser_tokval(parser), "case")) {
3299             if (!parser_next(parser)) {
3300                 ast_delete(switchnode);
3301                 parseerror(parser, "expected expression for case");
3302                 return false;
3303             }
3304             swcase.value = parse_expression_leave(parser, false, false, false);
3305             if (!swcase.value) {
3306                 ast_delete(switchnode);
3307                 parseerror(parser, "expected expression for case");
3308                 return false;
3309             }
3310             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3311                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3312                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3313                     ast_unref(operand);
3314                     return false;
3315                 }
3316             }
3317         }
3318         else if (!strcmp(parser_tokval(parser), "default")) {
3319             swcase.value = NULL;
3320             if (!parser_next(parser)) {
3321                 ast_delete(switchnode);
3322                 parseerror(parser, "expected colon");
3323                 return false;
3324             }
3325         }
3326         else {
3327             ast_delete(switchnode);
3328             parseerror(parser, "expected 'case' or 'default'");
3329             return false;
3330         }
3331
3332         /* Now the colon and body */
3333         if (parser->tok != ':') {
3334             if (swcase.value) ast_unref(swcase.value);
3335             ast_delete(switchnode);
3336             parseerror(parser, "expected colon");
3337             return false;
3338         }
3339
3340         if (!parser_next(parser)) {
3341             if (swcase.value) ast_unref(swcase.value);
3342             ast_delete(switchnode);
3343             parseerror(parser, "expected statements or case");
3344             return false;
3345         }
3346         caseblock = ast_block_new(parser_ctx(parser));
3347         if (!caseblock) {
3348             if (swcase.value) ast_unref(swcase.value);
3349             ast_delete(switchnode);
3350             return false;
3351         }
3352         swcase.code = (ast_expression*)caseblock;
3353         vec_push(switchnode->cases, swcase);
3354         while (true) {
3355             ast_expression *expr;
3356             if (parser->tok == '}')
3357                 break;
3358             if (parser->tok == TOKEN_KEYWORD) {
3359                 if (!strcmp(parser_tokval(parser), "case") ||
3360                     !strcmp(parser_tokval(parser), "default"))
3361                 {
3362                     break;
3363                 }
3364             }
3365             if (!parse_statement(parser, caseblock, &expr, true)) {
3366                 ast_delete(switchnode);
3367                 return false;
3368             }
3369             if (!expr)
3370                 continue;
3371             if (!ast_block_add_expr(caseblock, expr)) {
3372                 ast_delete(switchnode);
3373                 return false;
3374             }
3375         }
3376     }
3377
3378     parser_leaveblock(parser);
3379
3380     /* closing paren */
3381     if (parser->tok != '}') {
3382         ast_delete(switchnode);
3383         parseerror(parser, "expected closing paren of case list");
3384         return false;
3385     }
3386     if (!parser_next(parser)) {
3387         ast_delete(switchnode);
3388         parseerror(parser, "parse error after switch");
3389         return false;
3390     }
3391     *out = (ast_expression*)switchnode;
3392     return true;
3393 }
3394
3395 /* parse computed goto sides */
3396 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3397     ast_expression *on_true;
3398     ast_expression *on_false;
3399     ast_expression *cond;
3400
3401     if (!*side)
3402         return NULL;
3403
3404     if (ast_istype(*side, ast_ternary)) {
3405         ast_ternary *tern = (ast_ternary*)*side;
3406         on_true  = parse_goto_computed(parser, &tern->on_true);
3407         on_false = parse_goto_computed(parser, &tern->on_false);
3408
3409         if (!on_true || !on_false) {
3410             parseerror(parser, "expected label or expression in ternary");
3411             if (on_true) ast_unref(on_true);
3412             if (on_false) ast_unref(on_false);
3413             return NULL;
3414         }
3415
3416         cond = tern->cond;
3417         tern->cond = NULL;
3418         ast_delete(tern);
3419         *side = NULL;
3420         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3421     } else if (ast_istype(*side, ast_label)) {
3422         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3423         ast_goto_set_label(gt, ((ast_label*)*side));
3424         *side = NULL;
3425         return (ast_expression*)gt;
3426     }
3427     return NULL;
3428 }
3429
3430 static bool parse_goto(parser_t *parser, ast_expression **out)
3431 {
3432     ast_goto       *gt = NULL;
3433     ast_expression *lbl;
3434
3435     if (!parser_next(parser))
3436         return false;
3437
3438     if (parser->tok != TOKEN_IDENT) {
3439         ast_expression *expression;
3440
3441         /* could be an expression i.e computed goto :-) */
3442         if (parser->tok != '(') {
3443             parseerror(parser, "expected label name after `goto`");
3444             return false;
3445         }
3446
3447         /* failed to parse expression for goto */
3448         if (!(expression = parse_expression(parser, false, true)) ||
3449             !(*out = parse_goto_computed(parser, &expression))) {
3450             parseerror(parser, "invalid goto expression");
3451             ast_unref(expression);
3452             return false;
3453         }
3454
3455         return true;
3456     }
3457
3458     /* not computed goto */
3459     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3460     lbl = parser_find_label(parser, gt->name);
3461     if (lbl) {
3462         if (!ast_istype(lbl, ast_label)) {
3463             parseerror(parser, "internal error: label is not an ast_label");
3464             ast_delete(gt);
3465             return false;
3466         }
3467         ast_goto_set_label(gt, (ast_label*)lbl);
3468     }