]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Actually generate an ast_call for __builtin_pow for the ** operator, otherwise the...
[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 {
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     /* must be deleted first, they reference immediates and values */
51     ast_value    **accessors;
52
53     ast_value *imm_float_zero;
54     ast_value *imm_float_one;
55     ast_value *imm_float_neg_one;
56
57     ast_value *imm_vector_zero;
58
59     ast_value *nil;
60     ast_value *reserved_version;
61
62     size_t crc_globals;
63     size_t crc_fields;
64
65     ast_function *function;
66     ht            aliases;
67
68     /* All the labels the function defined...
69      * Should they be in ast_function instead?
70      */
71     ast_label  **labels;
72     ast_goto   **gotos;
73     const char **breaks;
74     const char **continues;
75
76     /* A list of hashtables for each scope */
77     ht *variables;
78     ht htfields;
79     ht htglobals;
80     ht *typedefs;
81
82     /* same as above but for the spelling corrector */
83     correct_trie_t  **correct_variables;
84     size_t         ***correct_variables_score;  /* vector of vector of size_t* */
85
86     /* not to be used directly, we use the hash table */
87     ast_expression **_locals;
88     size_t          *_blocklocals;
89     ast_value      **_typedefs;
90     size_t          *_blocktypedefs;
91     lex_ctx         *_block_ctx;
92
93     /* we store the '=' operator info */
94     const oper_info *assign_op;
95
96     /* magic values */
97     ast_value *const_vec[3];
98
99     /* pragma flags */
100     bool noref;
101
102     /* collected information */
103     size_t     max_param_count;
104 } parser_t;
105
106 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
107
108 static void parser_enterblock(parser_t *parser);
109 static bool parser_leaveblock(parser_t *parser);
110 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
111 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
112 static bool parse_typedef(parser_t *parser);
113 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);
114 static ast_block* parse_block(parser_t *parser);
115 static bool parse_block_into(parser_t *parser, ast_block *block);
116 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
117 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
118 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
119 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
120 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
121 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
122 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
123 static ast_expression *parser_builtin_pow(parser_t *);
124
125 static void parseerror(parser_t *parser, const char *fmt, ...)
126 {
127     va_list ap;
128     va_start(ap, fmt);
129     vcompile_error(parser->lex->tok.ctx, fmt, ap);
130     va_end(ap);
131 }
132
133 /* returns true if it counts as an error */
134 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
135 {
136     bool    r;
137     va_list ap;
138     va_start(ap, fmt);
139     r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
140     va_end(ap);
141     return r;
142 }
143
144 /**********************************************************************
145  * some maths used for constant folding
146  */
147
148 vector vec3_add(vector a, vector b)
149 {
150     vector out;
151     out.x = a.x + b.x;
152     out.y = a.y + b.y;
153     out.z = a.z + b.z;
154     return out;
155 }
156
157 vector vec3_sub(vector a, vector b)
158 {
159     vector out;
160     out.x = a.x - b.x;
161     out.y = a.y - b.y;
162     out.z = a.z - b.z;
163     return out;
164 }
165
166 qcfloat vec3_mulvv(vector a, vector b)
167 {
168     return (a.x * b.x + a.y * b.y + a.z * b.z);
169 }
170
171 vector vec3_mulvf(vector a, float b)
172 {
173     vector out;
174     out.x = a.x * b;
175     out.y = a.y * b;
176     out.z = a.z * b;
177     return out;
178 }
179
180 /**********************************************************************
181  * parsing
182  */
183
184 bool parser_next(parser_t *parser)
185 {
186     /* lex_do kills the previous token */
187     parser->tok = lex_do(parser->lex);
188     if (parser->tok == TOKEN_EOF)
189         return true;
190     if (parser->tok >= TOKEN_ERROR) {
191         parseerror(parser, "lex error");
192         return false;
193     }
194     return true;
195 }
196
197 #define parser_tokval(p) ((p)->lex->tok.value)
198 #define parser_token(p)  (&((p)->lex->tok))
199 #define parser_ctx(p)    ((p)->lex->tok.ctx)
200
201 static ast_value* parser_const_float(parser_t *parser, double d)
202 {
203     size_t i;
204     ast_value *out;
205     lex_ctx ctx;
206     for (i = 0; i < vec_size(parser->imm_float); ++i) {
207         const double compare = parser->imm_float[i]->constval.vfloat;
208         if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
209             return parser->imm_float[i];
210     }
211     if (parser->lex)
212         ctx = parser_ctx(parser);
213     else {
214         memset(&ctx, 0, sizeof(ctx));
215     }
216     out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
217     out->cvq      = CV_CONST;
218     out->hasvalue = true;
219     out->constval.vfloat = d;
220     vec_push(parser->imm_float, out);
221     return out;
222 }
223
224 static ast_value* parser_const_float_0(parser_t *parser)
225 {
226     if (!parser->imm_float_zero)
227         parser->imm_float_zero = parser_const_float(parser, 0);
228     return parser->imm_float_zero;
229 }
230
231 static ast_value* parser_const_float_neg1(parser_t *parser) {
232     if (!parser->imm_float_neg_one)
233         parser->imm_float_neg_one = parser_const_float(parser, -1);
234     return parser->imm_float_neg_one;
235 }
236
237 static ast_value* parser_const_float_1(parser_t *parser)
238 {
239     if (!parser->imm_float_one)
240         parser->imm_float_one = parser_const_float(parser, 1);
241     return parser->imm_float_one;
242 }
243
244 static char *parser_strdup(const char *str)
245 {
246     if (str && !*str) {
247         /* actually dup empty strings */
248         char *out = (char*)mem_a(1);
249         *out = 0;
250         return out;
251     }
252     return util_strdup(str);
253 }
254
255 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
256 {
257     size_t i;
258     ast_value *out;
259     for (i = 0; i < vec_size(parser->imm_string); ++i) {
260         if (!strcmp(parser->imm_string[i]->constval.vstring, str))
261             return parser->imm_string[i];
262     }
263     if (dotranslate) {
264         char name[32];
265         snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
266         out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
267     } else
268         out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
269     out->cvq      = CV_CONST;
270     out->hasvalue = true;
271     out->constval.vstring = parser_strdup(str);
272     vec_push(parser->imm_string, out);
273     return out;
274 }
275
276 static ast_value* parser_const_vector(parser_t *parser, vector v)
277 {
278     size_t i;
279     ast_value *out;
280     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
281         if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
282             return parser->imm_vector[i];
283     }
284     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
285     out->cvq      = CV_CONST;
286     out->hasvalue = true;
287     out->constval.vvec = v;
288     vec_push(parser->imm_vector, out);
289     return out;
290 }
291
292 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
293 {
294     vector v;
295     v.x = x;
296     v.y = y;
297     v.z = z;
298     return parser_const_vector(parser, v);
299 }
300
301 static ast_value* parser_const_vector_0(parser_t *parser)
302 {
303     if (!parser->imm_vector_zero)
304         parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
305     return parser->imm_vector_zero;
306 }
307
308 static ast_expression* parser_find_field(parser_t *parser, const char *name)
309 {
310     return ( ast_expression*)util_htget(parser->htfields, name);
311 }
312
313 static ast_expression* parser_find_label(parser_t *parser, const char *name)
314 {
315     size_t i;
316     for(i = 0; i < vec_size(parser->labels); i++)
317         if (!strcmp(parser->labels[i]->name, name))
318             return (ast_expression*)parser->labels[i];
319     return NULL;
320 }
321
322 static ast_expression* parser_find_global(parser_t *parser, const char *name)
323 {
324     ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
325     if (var)
326         return var;
327     return (ast_expression*)util_htget(parser->htglobals, name);
328 }
329
330 static ast_expression* parser_find_param(parser_t *parser, const char *name)
331 {
332     size_t i;
333     ast_value *fun;
334     if (!parser->function)
335         return NULL;
336     fun = parser->function->vtype;
337     for (i = 0; i < vec_size(fun->expression.params); ++i) {
338         if (!strcmp(fun->expression.params[i]->name, name))
339             return (ast_expression*)(fun->expression.params[i]);
340     }
341     return NULL;
342 }
343
344 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
345 {
346     size_t          i, hash;
347     ast_expression *e;
348
349     hash = util_hthash(parser->htglobals, name);
350
351     *isparam = false;
352     for (i = vec_size(parser->variables); i > upto;) {
353         --i;
354         if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
355             return e;
356     }
357     *isparam = true;
358     return parser_find_param(parser, name);
359 }
360
361 static ast_expression* parser_find_var(parser_t *parser, const char *name)
362 {
363     bool dummy;
364     ast_expression *v;
365     v         = parser_find_local(parser, name, 0, &dummy);
366     if (!v) v = parser_find_global(parser, name);
367     return v;
368 }
369
370 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
371 {
372     size_t     i, hash;
373     ast_value *e;
374     hash = util_hthash(parser->typedefs[0], name);
375
376     for (i = vec_size(parser->typedefs); i > upto;) {
377         --i;
378         if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
379             return e;
380     }
381     return NULL;
382 }
383
384 typedef struct
385 {
386     size_t etype; /* 0 = expression, others are operators */
387     bool            isparen;
388     size_t          off;
389     ast_expression *out;
390     ast_block      *block; /* for commas and function calls */
391     lex_ctx ctx;
392 } sy_elem;
393
394 enum {
395     PAREN_EXPR,
396     PAREN_FUNC,
397     PAREN_INDEX,
398     PAREN_TERNARY1,
399     PAREN_TERNARY2
400 };
401 typedef struct
402 {
403     sy_elem        *out;
404     sy_elem        *ops;
405     size_t         *argc;
406     unsigned int   *paren;
407 } shunt;
408
409 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
410     sy_elem e;
411     e.etype = 0;
412     e.off   = 0;
413     e.out   = v;
414     e.block = NULL;
415     e.ctx   = ctx;
416     e.isparen = false;
417     return e;
418 }
419
420 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
421     sy_elem e;
422     e.etype = 0;
423     e.off   = 0;
424     e.out   = (ast_expression*)v;
425     e.block = v;
426     e.ctx   = ctx;
427     e.isparen = false;
428     return e;
429 }
430
431 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
432     sy_elem e;
433     e.etype = 1 + (op - operators);
434     e.off   = 0;
435     e.out   = NULL;
436     e.block = NULL;
437     e.ctx   = ctx;
438     e.isparen = false;
439     return e;
440 }
441
442 static sy_elem syparen(lex_ctx ctx, size_t off) {
443     sy_elem e;
444     e.etype = 0;
445     e.off   = off;
446     e.out   = NULL;
447     e.block = NULL;
448     e.ctx   = ctx;
449     e.isparen = true;
450     return e;
451 }
452
453 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
454  * so we need to rotate it to become ent.(foo[n]).
455  */
456 static bool rotate_entfield_array_index_nodes(ast_expression **out)
457 {
458     ast_array_index *index, *oldindex;
459     ast_entfield    *entfield;
460
461     ast_value       *field;
462     ast_expression  *sub;
463     ast_expression  *entity;
464
465     lex_ctx ctx = ast_ctx(*out);
466
467     if (!ast_istype(*out, ast_array_index))
468         return false;
469     index = (ast_array_index*)*out;
470
471     if (!ast_istype(index->array, ast_entfield))
472         return false;
473     entfield = (ast_entfield*)index->array;
474
475     if (!ast_istype(entfield->field, ast_value))
476         return false;
477     field = (ast_value*)entfield->field;
478
479     sub    = index->index;
480     entity = entfield->entity;
481
482     oldindex = index;
483
484     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
485     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
486     *out = (ast_expression*)entfield;
487
488     oldindex->array = NULL;
489     oldindex->index = NULL;
490     ast_delete(oldindex);
491
492     return true;
493 }
494
495 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
496 {
497     switch (v->expression.vtype) {
498         case TYPE_FLOAT:
499             return !!v->constval.vfloat;
500         case TYPE_INTEGER:
501             return !!v->constval.vint;
502         case TYPE_VECTOR:
503             if (OPTS_FLAG(CORRECT_LOGIC))
504                 return v->constval.vvec.x &&
505                        v->constval.vvec.y &&
506                        v->constval.vvec.z;
507             else
508                 return !!(v->constval.vvec.x);
509         case TYPE_STRING:
510             if (!v->constval.vstring)
511                 return false;
512             if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
513                 return true;
514             return !!v->constval.vstring[0];
515         default:
516             compile_error(ctx, "internal error: immediate_is_true on invalid type");
517             return !!v->constval.vfunc;
518     }
519 }
520
521 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
522 {
523     const oper_info *op;
524     lex_ctx ctx;
525     ast_expression *out = NULL;
526     ast_expression *exprs[3];
527     ast_block      *blocks[3];
528     ast_value      *asvalue[3];
529     ast_binstore   *asbinstore;
530     size_t i, assignop, addop, subop;
531     qcint  generated_op = 0;
532
533     char ty1[1024];
534     char ty2[1024];
535
536     if (!vec_size(sy->ops)) {
537         parseerror(parser, "internal error: missing operator");
538         return false;
539     }
540
541     if (vec_last(sy->ops).isparen) {
542         parseerror(parser, "unmatched parenthesis");
543         return false;
544     }
545
546     op = &operators[vec_last(sy->ops).etype - 1];
547     ctx = vec_last(sy->ops).ctx;
548
549     if (vec_size(sy->out) < op->operands) {
550         compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
551                       op->op, (int)op->id);
552         return false;
553     }
554
555     vec_shrinkby(sy->ops, 1);
556
557     /* op(:?) has no input and no output */
558     if (!op->operands)
559         return true;
560
561     vec_shrinkby(sy->out, op->operands);
562     for (i = 0; i < op->operands; ++i) {
563         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
564         blocks[i] = sy->out[vec_size(sy->out)+i].block;
565         asvalue[i] = (ast_value*)exprs[i];
566
567         if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
568             !(i != 0 && op->id == opid2('?',':')) &&
569             !(i == 1 && op->id == opid1('.')))
570         {
571             if (ast_istype(exprs[i], ast_label))
572                 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
573             else
574                 compile_error(ast_ctx(exprs[i]), "not an expression");
575             (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
576         }
577     }
578
579     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
580         compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
581         return false;
582     }
583
584 #define NotSameType(T) \
585              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
586               exprs[0]->expression.vtype != T)
587 #define CanConstFold1(A) \
588              (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
589               (A)->expression.vtype != TYPE_FUNCTION)
590 #define CanConstFold(A, B) \
591              (CanConstFold1(A) && CanConstFold1(B))
592 #define ConstV(i) (asvalue[(i)]->constval.vvec)
593 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
594 #define ConstS(i) (asvalue[(i)]->constval.vstring)
595     switch (op->id)
596     {
597         default:
598             compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
599             return false;
600
601         case opid1('.'):
602             if (exprs[0]->expression.vtype == TYPE_VECTOR &&
603                 exprs[1]->expression.vtype == TYPE_NOEXPR)
604             {
605                 if      (exprs[1] == (ast_expression*)parser->const_vec[0])
606                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
607                 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
608                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
609                 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
610                     out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
611                 else {
612                     compile_error(ctx, "access to invalid vector component");
613                     return false;
614                 }
615             }
616             else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
617                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
618                     compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
619                     return false;
620                 }
621                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
622             }
623             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
624                 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
625                 return false;
626             }
627             else {
628                 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
629                 return false;
630             }
631             break;
632
633         case opid1('['):
634             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
635                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
636                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
637             {
638                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
639                 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
640                 return false;
641             }
642             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
643                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
644                 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
645                 return false;
646             }
647             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
648             if (rotate_entfield_array_index_nodes(&out))
649             {
650 #if 0
651                 /* This is not broken in fteqcc anymore */
652                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
653                     /* this error doesn't need to make us bail out */
654                     (void)!parsewarning(parser, WARN_EXTENSIONS,
655                                         "accessing array-field members of an entity without parenthesis\n"
656                                         " -> this is an extension from -std=gmqcc");
657                 }
658 #endif
659             }
660             break;
661
662         case opid1(','):
663             if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
664                 vec_push(sy->out, syexp(ctx, exprs[0]));
665                 vec_push(sy->out, syexp(ctx, exprs[1]));
666                 vec_last(sy->argc)++;
667                 return true;
668             }
669             if (blocks[0]) {
670                 if (!ast_block_add_expr(blocks[0], exprs[1]))
671                     return false;
672             } else {
673                 blocks[0] = ast_block_new(ctx);
674                 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
675                     !ast_block_add_expr(blocks[0], exprs[1]))
676                 {
677                     return false;
678                 }
679             }
680             ast_block_set_type(blocks[0], exprs[1]);
681
682             vec_push(sy->out, syblock(ctx, blocks[0]));
683             return true;
684
685         case opid2('+','P'):
686             out = exprs[0];
687             break;
688         case opid2('-','P'):
689             switch (exprs[0]->expression.vtype) {
690                 case TYPE_FLOAT:
691                     if (CanConstFold1(exprs[0]))
692                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
693                     else
694                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
695                                                               (ast_expression*)parser_const_float_0(parser),
696                                                               exprs[0]);
697                     break;
698                 case TYPE_VECTOR:
699                     if (CanConstFold1(exprs[0]))
700                         out = (ast_expression*)parser_const_vector_f(parser,
701                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
702                     else
703                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
704                                                               (ast_expression*)parser_const_vector_0(parser),
705                                                               exprs[0]);
706                     break;
707                 default:
708                 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
709                               type_name[exprs[0]->expression.vtype]);
710                 return false;
711             }
712             break;
713
714         case opid2('!','P'):
715             switch (exprs[0]->expression.vtype) {
716                 case TYPE_FLOAT:
717                     if (CanConstFold1(exprs[0]))
718                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
719                     else
720                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
721                     break;
722                 case TYPE_VECTOR:
723                     if (CanConstFold1(exprs[0]))
724                         out = (ast_expression*)parser_const_float(parser,
725                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
726                     else
727                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
728                     break;
729                 case TYPE_STRING:
730                     if (CanConstFold1(exprs[0])) {
731                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
732                             out = (ast_expression*)parser_const_float(parser, !ConstS(0));
733                         else
734                             out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
735                     } else {
736                         if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
737                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
738                         else
739                             out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
740                     }
741                     break;
742                 /* we don't constant-fold NOT for these types */
743                 case TYPE_ENTITY:
744                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
745                     break;
746                 case TYPE_FUNCTION:
747                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
748                     break;
749                 default:
750                 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
751                               type_name[exprs[0]->expression.vtype]);
752                 return false;
753             }
754             break;
755
756         case opid1('+'):
757             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
758                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
759             {
760                 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
761                               type_name[exprs[0]->expression.vtype],
762                               type_name[exprs[1]->expression.vtype]);
763                 return false;
764             }
765             switch (exprs[0]->expression.vtype) {
766                 case TYPE_FLOAT:
767                     if (CanConstFold(exprs[0], exprs[1]))
768                     {
769                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
770                     }
771                     else
772                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
773                     break;
774                 case TYPE_VECTOR:
775                     if (CanConstFold(exprs[0], exprs[1]))
776                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
777                     else
778                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
779                     break;
780                 default:
781                     compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
782                                   type_name[exprs[0]->expression.vtype],
783                                   type_name[exprs[1]->expression.vtype]);
784                     return false;
785             };
786             break;
787         case opid1('-'):
788             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
789                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
790             {
791                 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
792                               type_name[exprs[1]->expression.vtype],
793                               type_name[exprs[0]->expression.vtype]);
794                 return false;
795             }
796             switch (exprs[0]->expression.vtype) {
797                 case TYPE_FLOAT:
798                     if (CanConstFold(exprs[0], exprs[1]))
799                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
800                     else
801                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
802                     break;
803                 case TYPE_VECTOR:
804                     if (CanConstFold(exprs[0], exprs[1]))
805                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
806                     else
807                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
808                     break;
809                 default:
810                     compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
811                                   type_name[exprs[1]->expression.vtype],
812                                   type_name[exprs[0]->expression.vtype]);
813                     return false;
814             };
815             break;
816         case opid1('*'):
817             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
818                 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
819                   exprs[1]->expression.vtype == TYPE_FLOAT) &&
820                 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
821                   exprs[0]->expression.vtype == TYPE_FLOAT)
822                 )
823             {
824                 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
825                               type_name[exprs[1]->expression.vtype],
826                               type_name[exprs[0]->expression.vtype]);
827                 return false;
828             }
829             switch (exprs[0]->expression.vtype) {
830                 case TYPE_FLOAT:
831                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
832                     {
833                         if (CanConstFold(exprs[0], exprs[1]))
834                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
835                         else
836                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
837                     }
838                     else
839                     {
840                         if (CanConstFold(exprs[0], exprs[1]))
841                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
842                         else
843                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
844                     }
845                     break;
846                 case TYPE_VECTOR:
847                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
848                     {
849                         if (CanConstFold(exprs[0], exprs[1]))
850                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
851                         else
852                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
853                     }
854                     else
855                     {
856                         if (CanConstFold(exprs[0], exprs[1]))
857                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
858                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
859                             vector vec = ConstV(0);
860                             if (!vec.y && !vec.z) { /* 'n 0 0' * v */
861                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
862                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
863                                 out->expression.node.keep = false;
864                                 ((ast_member*)out)->rvalue = true;
865                                 if (vec.x != 1)
866                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
867                             }
868                             else if (!vec.x && !vec.z) { /* '0 n 0' * v */
869                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
870                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
871                                 out->expression.node.keep = false;
872                                 ((ast_member*)out)->rvalue = true;
873                                 if (vec.y != 1)
874                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
875                             }
876                             else if (!vec.x && !vec.y) { /* '0 n 0' * v */
877                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
878                                 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
879                                 out->expression.node.keep = false;
880                                 ((ast_member*)out)->rvalue = true;
881                                 if (vec.z != 1)
882                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
883                             }
884                             else
885                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
886                         }
887                         else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
888                             vector vec = ConstV(1);
889                             if (!vec.y && !vec.z) { /* v * 'n 0 0' */
890                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
891                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
892                                 out->expression.node.keep = false;
893                                 ((ast_member*)out)->rvalue = true;
894                                 if (vec.x != 1)
895                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
896                             }
897                             else if (!vec.x && !vec.z) { /* v * '0 n 0' */
898                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
899                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
900                                 out->expression.node.keep = false;
901                                 ((ast_member*)out)->rvalue = true;
902                                 if (vec.y != 1)
903                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
904                             }
905                             else if (!vec.x && !vec.y) { /* v * '0 n 0' */
906                                 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
907                                 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
908                                 out->expression.node.keep = false;
909                                 ((ast_member*)out)->rvalue = true;
910                                 if (vec.z != 1)
911                                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
912                             }
913                             else
914                                 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
915                         }
916                         else
917                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
918                     }
919                     break;
920                 default:
921                     compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
922                                   type_name[exprs[1]->expression.vtype],
923                                   type_name[exprs[0]->expression.vtype]);
924                     return false;
925             };
926             break;
927         case opid1('/'):
928             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
929                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
930                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
931                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
932                 return false;
933             }
934             if (exprs[0]->expression.vtype == TYPE_FLOAT) {
935                 if (CanConstFold(exprs[0], exprs[1]))
936                     out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
937                 else
938                     out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
939             }
940             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
941                 if (CanConstFold(exprs[0], exprs[1]))
942                     out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
943                 else {
944                     if (CanConstFold1(exprs[1])) {
945                         out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
946                     } else {
947                         out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
948                                                               (ast_expression*)parser_const_float_1(parser),
949                                                               exprs[1]);
950                     }
951                     if (!out) {
952                         compile_error(ctx, "internal error: failed to generate division");
953                         return false;
954                     }
955                     out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
956                 }
957             }
958             else
959             {
960                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
961                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
962                 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
963                 return false;
964             }
965             break;
966         case opid1('%'):
967         case opid2('%','='):
968             compile_error(ctx, "qc does not have a modulo operator");
969             return false;
970         case opid1('|'):
971         case opid1('&'):
972             if (NotSameType(TYPE_FLOAT)) {
973                 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
974                               type_name[exprs[0]->expression.vtype],
975                               type_name[exprs[1]->expression.vtype]);
976                 return false;
977             }
978             if (CanConstFold(exprs[0], exprs[1]))
979                 out = (ast_expression*)parser_const_float(parser,
980                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
981                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
982             else
983                 out = (ast_expression*)ast_binary_new(ctx,
984                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
985                     exprs[0], exprs[1]);
986             break;
987         case opid1('^'):
988             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
989             return false;
990
991         case opid2('<','<'):
992         case opid2('>','>'):
993             if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
994                 if (op->id == opid2('<','<'))
995                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
996                 else
997                     out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
998                 break;
999             }
1000         case opid3('<','<','='):
1001         case opid3('>','>','='):
1002             compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1003             return false;
1004
1005         case opid2('|','|'):
1006             generated_op += 1; /* INSTR_OR */
1007         case opid2('&','&'):
1008             generated_op += INSTR_AND;
1009             if (CanConstFold(exprs[0], exprs[1]))
1010             {
1011                 if (OPTS_FLAG(PERL_LOGIC)) {
1012                     if (immediate_is_true(ctx, asvalue[0]))
1013                         out = exprs[1];
1014                 }
1015                 else
1016                     out = (ast_expression*)parser_const_float(parser,
1017                           ( (generated_op == INSTR_OR)
1018                             ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1019                             : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1020                           ? 1 : 0);
1021             }
1022             else
1023             {
1024                 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1025                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1026                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1027                     compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1028                     return false;
1029                 }
1030                 for (i = 0; i < 2; ++i) {
1031                     if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1032                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1033                         if (!out) break;
1034                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1035                         if (!out) break;
1036                         exprs[i] = out; out = NULL;
1037                         if (OPTS_FLAG(PERL_LOGIC)) {
1038                             /* here we want to keep the right expressions' type */
1039                             break;
1040                         }
1041                     }
1042                     else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1043                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1044                         if (!out) break;
1045                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1046                         if (!out) break;
1047                         exprs[i] = out; out = NULL;
1048                         if (OPTS_FLAG(PERL_LOGIC)) {
1049                             /* here we want to keep the right expressions' type */
1050                             break;
1051                         }
1052                     }
1053                 }
1054                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1055             }
1056             break;
1057
1058         case opid2('?',':'):
1059             if (vec_last(sy->paren) != PAREN_TERNARY2) {
1060                 compile_error(ctx, "mismatched parenthesis/ternary");
1061                 return false;
1062             }
1063             vec_pop(sy->paren);
1064             if (!ast_compare_type(exprs[1], exprs[2])) {
1065                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1066                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1067                 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1068                 return false;
1069             }
1070             if (CanConstFold1(exprs[0]))
1071                 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1072             else
1073                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1074             break;
1075
1076         case opid2('*', '*'):
1077             if (NotSameType(TYPE_FLOAT)) {
1078                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1079                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080                 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1081                     ty1, ty2);
1082
1083                 return false;
1084             }
1085
1086             if (CanConstFold(exprs[0], exprs[1])) {
1087                 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1088             } else {
1089                 ast_call *gencall = ast_call_new(parser_ctx(parser), parser_builtin_pow(parser));
1090                 vec_push(gencall->params, exprs[0]);
1091                 vec_push(gencall->params, exprs[1]);
1092                 out = (ast_expression*)gencall;
1093             }
1094             break;
1095
1096         case opid3('<','=','>'): /* -1, 0, or 1 */
1097             if (NotSameType(TYPE_FLOAT)) {
1098                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1099                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1100                 compile_error(ctx, "invalid types used in comparision: %s and %s",
1101                     ty1, ty2);
1102
1103                 return false;
1104             }
1105
1106             if (CanConstFold(exprs[0], exprs[1])) {
1107                 if (ConstF(0) < ConstF(1))
1108                     out = (ast_expression*)parser_const_float_neg1(parser);
1109                 else if (ConstF(0) == ConstF(1))
1110                     out = (ast_expression*)parser_const_float_0(parser);
1111                 else if (ConstF(0) > ConstF(1))
1112                     out = (ast_expression*)parser_const_float_1(parser);
1113             } else {
1114                 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1115
1116                 eq->refs = (ast_binary_ref)false; /* references nothing */
1117
1118                     /* if (lt) { */
1119                 out = (ast_expression*)ast_ternary_new(ctx,
1120                         (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1121                         /* out = -1 */
1122                         (ast_expression*)parser_const_float_neg1(parser),
1123                     /* } else { */
1124                         /* if (eq) { */
1125                         (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1126                             /* out = 0 */
1127                             (ast_expression*)parser_const_float_0(parser),
1128                         /* } else { */
1129                             /* out = 1 */
1130                             (ast_expression*)parser_const_float_1(parser)
1131                         /* } */
1132                         )
1133                     /* } */
1134                     );
1135
1136             }
1137             break;
1138
1139         case opid1('>'):
1140             generated_op += 1; /* INSTR_GT */
1141         case opid1('<'):
1142             generated_op += 1; /* INSTR_LT */
1143         case opid2('>', '='):
1144             generated_op += 1; /* INSTR_GE */
1145         case opid2('<', '='):
1146             generated_op += INSTR_LE;
1147             if (NotSameType(TYPE_FLOAT)) {
1148                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1149                               type_name[exprs[0]->expression.vtype],
1150                               type_name[exprs[1]->expression.vtype]);
1151                 return false;
1152             }
1153             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1154             break;
1155         case opid2('!', '='):
1156             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1157                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1158                               type_name[exprs[0]->expression.vtype],
1159                               type_name[exprs[1]->expression.vtype]);
1160                 return false;
1161             }
1162             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1163             break;
1164         case opid2('=', '='):
1165             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1166                 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1167                               type_name[exprs[0]->expression.vtype],
1168                               type_name[exprs[1]->expression.vtype]);
1169                 return false;
1170             }
1171             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1172             break;
1173
1174         case opid1('='):
1175             if (ast_istype(exprs[0], ast_entfield)) {
1176                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1177                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1178                     exprs[0]->expression.vtype == TYPE_FIELD &&
1179                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1180                 {
1181                     assignop = type_storep_instr[TYPE_VECTOR];
1182                 }
1183                 else
1184                     assignop = type_storep_instr[exprs[0]->expression.vtype];
1185                 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1186                 {
1187                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1188                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1189                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1190                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
1191                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1192                     {
1193                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1194                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1195                     }
1196                     else
1197                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1198                 }
1199             }
1200             else
1201             {
1202                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1203                     exprs[0]->expression.vtype == TYPE_FIELD &&
1204                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1205                 {
1206                     assignop = type_store_instr[TYPE_VECTOR];
1207                 }
1208                 else {
1209                     assignop = type_store_instr[exprs[0]->expression.vtype];
1210                 }
1211
1212                 if (assignop == VINSTR_END) {
1213                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1214                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1215                     compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1216                 }
1217                 else if (!ast_compare_type(exprs[0], exprs[1]))
1218                 {
1219                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1220                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1221                     if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1222                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
1223                         exprs[1]->expression.vtype == TYPE_FUNCTION)
1224                     {
1225                         (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1226                                                "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1227                     }
1228                     else
1229                         compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1230                 }
1231             }
1232             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1233                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1234             }
1235             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1236             break;
1237         case opid3('+','+','P'):
1238         case opid3('-','-','P'):
1239             /* prefix ++ */
1240             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1241                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1242                 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1243                 return false;
1244             }
1245             if (op->id == opid3('+','+','P'))
1246                 addop = INSTR_ADD_F;
1247             else
1248                 addop = INSTR_SUB_F;
1249             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1250                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1251             }
1252             if (ast_istype(exprs[0], ast_entfield)) {
1253                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1254                                                         exprs[0],
1255                                                         (ast_expression*)parser_const_float_1(parser));
1256             } else {
1257                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1258                                                         exprs[0],
1259                                                         (ast_expression*)parser_const_float_1(parser));
1260             }
1261             break;
1262         case opid3('S','+','+'):
1263         case opid3('S','-','-'):
1264             /* prefix ++ */
1265             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1266                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1267                 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1268                 return false;
1269             }
1270             if (op->id == opid3('S','+','+')) {
1271                 addop = INSTR_ADD_F;
1272                 subop = INSTR_SUB_F;
1273             } else {
1274                 addop = INSTR_SUB_F;
1275                 subop = INSTR_ADD_F;
1276             }
1277             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1278                 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1279             }
1280             if (ast_istype(exprs[0], ast_entfield)) {
1281                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1282                                                         exprs[0],
1283                                                         (ast_expression*)parser_const_float_1(parser));
1284             } else {
1285                 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1286                                                         exprs[0],
1287                                                         (ast_expression*)parser_const_float_1(parser));
1288             }
1289             if (!out)
1290                 return false;
1291             out = (ast_expression*)ast_binary_new(ctx, subop,
1292                                                   out,
1293                                                   (ast_expression*)parser_const_float_1(parser));
1294             break;
1295         case opid2('+','='):
1296         case opid2('-','='):
1297             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1298                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1299             {
1300                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1301                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1302                 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1303                               ty1, ty2);
1304                 return false;
1305             }
1306             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1307                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1308             }
1309             if (ast_istype(exprs[0], ast_entfield))
1310                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1311             else
1312                 assignop = type_store_instr[exprs[0]->expression.vtype];
1313             switch (exprs[0]->expression.vtype) {
1314                 case TYPE_FLOAT:
1315                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1316                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1317                                                             exprs[0], exprs[1]);
1318                     break;
1319                 case TYPE_VECTOR:
1320                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1321                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1322                                                             exprs[0], exprs[1]);
1323                     break;
1324                 default:
1325                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1326                                   type_name[exprs[0]->expression.vtype],
1327                                   type_name[exprs[1]->expression.vtype]);
1328                     return false;
1329             };
1330             break;
1331         case opid2('*','='):
1332         case opid2('/','='):
1333             if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1334                 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1335                   exprs[0]->expression.vtype == TYPE_VECTOR))
1336             {
1337                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1338                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1339                 compile_error(ctx, "invalid types used in expression: %s and %s",
1340                               ty1, ty2);
1341                 return false;
1342             }
1343             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1344                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1345             }
1346             if (ast_istype(exprs[0], ast_entfield))
1347                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1348             else
1349                 assignop = type_store_instr[exprs[0]->expression.vtype];
1350             switch (exprs[0]->expression.vtype) {
1351                 case TYPE_FLOAT:
1352                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
1353                                                             (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1354                                                             exprs[0], exprs[1]);
1355                     break;
1356                 case TYPE_VECTOR:
1357                     if (op->id == opid2('*','=')) {
1358                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1359                                                                 exprs[0], exprs[1]);
1360                     } else {
1361                         /* there's no DIV_VF */
1362                         if (CanConstFold1(exprs[1])) {
1363                             out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1364                         } else {
1365                             out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1366                                                                   (ast_expression*)parser_const_float_1(parser),
1367                                                                   exprs[1]);
1368                         }
1369                         if (!out) {
1370                             compile_error(ctx, "internal error: failed to generate division");
1371                             return false;
1372                         }
1373                         out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1374                                                                 exprs[0], out);
1375                     }
1376                     break;
1377                 default:
1378                     compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1379                                   type_name[exprs[0]->expression.vtype],
1380                                   type_name[exprs[1]->expression.vtype]);
1381                     return false;
1382             };
1383             break;
1384         case opid2('&','='):
1385         case opid2('|','='):
1386             if (NotSameType(TYPE_FLOAT)) {
1387                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1388                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1389                 compile_error(ctx, "invalid types used in expression: %s and %s",
1390                               ty1, ty2);
1391                 return false;
1392             }
1393             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1394                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1395             }
1396             if (ast_istype(exprs[0], ast_entfield))
1397                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1398             else
1399                 assignop = type_store_instr[exprs[0]->expression.vtype];
1400             out = (ast_expression*)ast_binstore_new(ctx, assignop,
1401                                                     (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1402                                                     exprs[0], exprs[1]);
1403             break;
1404         case opid3('&','~','='):
1405             /* This is like: a &= ~(b);
1406              * But QC has no bitwise-not, so we implement it as
1407              * a -= a & (b);
1408              */
1409             if (NotSameType(TYPE_FLOAT)) {
1410                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1411                 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1412                 compile_error(ctx, "invalid types used in expression: %s and %s",
1413                               ty1, ty2);
1414                 return false;
1415             }
1416             if (ast_istype(exprs[0], ast_entfield))
1417                 assignop = type_storep_instr[exprs[0]->expression.vtype];
1418             else
1419                 assignop = type_store_instr[exprs[0]->expression.vtype];
1420             out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1421             if (!out)
1422                 return false;
1423             if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1424                 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1425             }
1426             asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1427             asbinstore->keep_dest = true;
1428             out = (ast_expression*)asbinstore;
1429             break;
1430
1431         case opid2('~', 'P'):
1432             if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1433                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1434                 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1435                 return false;
1436             }
1437
1438             if(CanConstFold1(exprs[0]))
1439                 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1440             else
1441                 out = (ast_expression*)
1442                     ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1443             break;
1444     }
1445 #undef NotSameType
1446
1447     if (!out) {
1448         compile_error(ctx, "failed to apply operator %s", op->op);
1449         return false;
1450     }
1451
1452     vec_push(sy->out, syexp(ctx, out));
1453     return true;
1454 }
1455
1456 static bool parser_close_call(parser_t *parser, shunt *sy)
1457 {
1458     /* was a function call */
1459     ast_expression *fun;
1460     ast_value      *funval = NULL;
1461     ast_call       *call;
1462
1463     size_t          fid;
1464     size_t          paramcount, i;
1465
1466     fid = vec_last(sy->ops).off;
1467     vec_shrinkby(sy->ops, 1);
1468
1469     /* out[fid] is the function
1470      * everything above is parameters...
1471      */
1472     if (!vec_size(sy->argc)) {
1473         parseerror(parser, "internal error: no argument counter available");
1474         return false;
1475     }
1476
1477     paramcount = vec_last(sy->argc);
1478     vec_pop(sy->argc);
1479
1480     if (vec_size(sy->out) < fid) {
1481         parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1482                    (unsigned long)vec_size(sy->out),
1483                    (unsigned long)fid,
1484                    (unsigned long)paramcount);
1485         return false;
1486     }
1487
1488     fun = sy->out[fid].out;
1489
1490     if (fun == intrinsic_debug_typestring) {
1491         char ty[1024];
1492         if (fid+2 != vec_size(sy->out) ||
1493             vec_last(sy->out).block)
1494         {
1495             parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1496             return false;
1497         }
1498         ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1499         ast_unref(vec_last(sy->out).out);
1500         sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1501                              (ast_expression*)parser_const_string(parser, ty, false));
1502         vec_shrinkby(sy->out, 1);
1503         return true;
1504     }
1505
1506     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1507     if (!call)
1508         return false;
1509
1510     if (fid+1 < vec_size(sy->out))
1511         ++paramcount;
1512
1513     if (fid+1 + paramcount != vec_size(sy->out)) {
1514         parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1515                    (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1516         return false;
1517     }
1518
1519     for (i = 0; i < paramcount; ++i)
1520         vec_push(call->params, sy->out[fid+1 + i].out);
1521     vec_shrinkby(sy->out, paramcount);
1522     (void)!ast_call_check_types(call);
1523     if (parser->max_param_count < paramcount)
1524         parser->max_param_count = paramcount;
1525
1526     if (ast_istype(fun, ast_value)) {
1527         funval = (ast_value*)fun;
1528         if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1529             !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1530         {
1531             call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1532         }
1533     }
1534
1535     /* overwrite fid, the function, with a call */
1536     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1537
1538     if (fun->expression.vtype != TYPE_FUNCTION) {
1539         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1540         return false;
1541     }
1542
1543     if (!fun->expression.next) {
1544         parseerror(parser, "could not determine function return type");
1545         return false;
1546     } else {
1547         ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1548
1549         if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1550             if (!fval) {
1551                 return !parsewarning(parser, WARN_DEPRECATED,
1552                         "call to function (which is marked deprecated)\n",
1553                         "-> it has been declared here: %s:%i",
1554                         ast_ctx(fun).file, ast_ctx(fun).line);
1555             }
1556             if (!fval->desc) {
1557                 return !parsewarning(parser, WARN_DEPRECATED,
1558                         "call to `%s` (which is marked deprecated)\n"
1559                         "-> `%s` declared here: %s:%i",
1560                         fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1561             }
1562             return !parsewarning(parser, WARN_DEPRECATED,
1563                     "call to `%s` (deprecated: %s)\n"
1564                     "-> `%s` declared here: %s:%i",
1565                     fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1566                     ast_ctx(fun).line);
1567         }
1568
1569         if (vec_size(fun->expression.params) != paramcount &&
1570             !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1571               vec_size(fun->expression.params) < paramcount))
1572         {
1573             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1574             if (fval)
1575                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1576                                      "too %s parameters for call to %s: expected %i, got %i\n"
1577                                      " -> `%s` has been declared here: %s:%i",
1578                                      fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1579                                      fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1580             else
1581                 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1582                                      "too %s parameters for function call: expected %i, got %i\n"
1583                                      " -> it has been declared here: %s:%i",
1584                                      fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1585                                      ast_ctx(fun).file, (int)ast_ctx(fun).line);
1586         }
1587     }
1588
1589     return true;
1590 }
1591
1592 static bool parser_close_paren(parser_t *parser, shunt *sy)
1593 {
1594     if (!vec_size(sy->ops)) {
1595         parseerror(parser, "unmatched closing paren");
1596         return false;
1597     }
1598
1599     while (vec_size(sy->ops)) {
1600         if (vec_last(sy->ops).isparen) {
1601             if (vec_last(sy->paren) == PAREN_FUNC) {
1602                 vec_pop(sy->paren);
1603                 if (!parser_close_call(parser, sy))
1604                     return false;
1605                 break;
1606             }
1607             if (vec_last(sy->paren) == PAREN_EXPR) {
1608                 vec_pop(sy->paren);
1609                 if (!vec_size(sy->out)) {
1610                     compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1611                     vec_shrinkby(sy->ops, 1);
1612                     return false;
1613                 }
1614                 vec_shrinkby(sy->ops, 1);
1615                 break;
1616             }
1617             if (vec_last(sy->paren) == PAREN_INDEX) {
1618                 vec_pop(sy->paren);
1619                 /* pop off the parenthesis */
1620                 vec_shrinkby(sy->ops, 1);
1621                 /* then apply the index operator */
1622                 if (!parser_sy_apply_operator(parser, sy))
1623                     return false;
1624                 break;
1625             }
1626             if (vec_last(sy->paren) == PAREN_TERNARY1) {
1627                 vec_last(sy->paren) = PAREN_TERNARY2;
1628                 /* pop off the parenthesis */
1629                 vec_shrinkby(sy->ops, 1);
1630                 break;
1631             }
1632             compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1633             return false;
1634         }
1635         if (!parser_sy_apply_operator(parser, sy))
1636             return false;
1637     }
1638     return true;
1639 }
1640
1641 static void parser_reclassify_token(parser_t *parser)
1642 {
1643     size_t i;
1644     for (i = 0; i < operator_count; ++i) {
1645         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1646             parser->tok = TOKEN_OPERATOR;
1647             return;
1648         }
1649     }
1650 }
1651
1652 static ast_expression* parse_vararg_do(parser_t *parser)
1653 {
1654     ast_expression *idx, *out;
1655     ast_value      *typevar;
1656     ast_value      *funtype = parser->function->vtype;
1657
1658     lex_ctx ctx = parser_ctx(parser);
1659
1660     if (!parser_next(parser) || parser->tok != '(') {
1661         parseerror(parser, "expected parameter index and type in parenthesis");
1662         return NULL;
1663     }
1664     if (!parser_next(parser)) {
1665         parseerror(parser, "error parsing parameter index");
1666         return NULL;
1667     }
1668
1669     idx = parse_expression_leave(parser, true, false, false);
1670     if (!idx)
1671         return NULL;
1672
1673     if (parser->tok != ',') {
1674         ast_unref(idx);
1675         parseerror(parser, "expected comma after parameter index");
1676         return NULL;
1677     }
1678
1679     if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1680         ast_unref(idx);
1681         parseerror(parser, "expected typename for vararg");
1682         return NULL;
1683     }
1684
1685     typevar = parse_typename(parser, NULL, NULL);
1686     if (!typevar) {
1687         ast_unref(idx);
1688         return NULL;
1689     }
1690
1691     if (parser->tok != ')') {
1692         ast_unref(idx);
1693         ast_delete(typevar);
1694         parseerror(parser, "expected closing paren");
1695         return NULL;
1696     }
1697
1698 #if 0
1699     if (!parser_next(parser)) {
1700         ast_unref(idx);
1701         ast_delete(typevar);
1702         parseerror(parser, "parse error after vararg");
1703         return NULL;
1704     }
1705 #endif
1706
1707     if (!parser->function->varargs) {
1708         ast_unref(idx);
1709         ast_delete(typevar);
1710         parseerror(parser, "function has no variable argument list");
1711         return NULL;
1712     }
1713
1714     if (funtype->expression.varparam &&
1715         !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1716     {
1717         char ty1[1024];
1718         char ty2[1024];
1719         ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1720         ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1721         compile_error(ast_ctx(typevar),
1722                       "function was declared to take varargs of type `%s`, requested type is: %s",
1723                       ty2, ty1);
1724     }
1725
1726     out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1727     ast_type_adopt(out, typevar);
1728     ast_delete(typevar);
1729     return out;
1730 }
1731
1732 static ast_expression* parse_vararg(parser_t *parser)
1733 {
1734     bool           old_noops = parser->lex->flags.noops;
1735
1736     ast_expression *out;
1737
1738     parser->lex->flags.noops = true;
1739     out = parse_vararg_do(parser);
1740
1741     parser->lex->flags.noops = old_noops;
1742     return out;
1743 }
1744
1745 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1746 {
1747     if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1748         parser->tok == TOKEN_IDENT &&
1749         !strcmp(parser_tokval(parser), "_"))
1750     {
1751         /* a translatable string */
1752         ast_value *val;
1753
1754         parser->lex->flags.noops = true;
1755         if (!parser_next(parser) || parser->tok != '(') {
1756             parseerror(parser, "use _(\"string\") to create a translatable string constant");
1757             return false;
1758         }
1759         parser->lex->flags.noops = false;
1760         if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1761             parseerror(parser, "expected a constant string in translatable-string extension");
1762             return false;
1763         }
1764         val = parser_const_string(parser, parser_tokval(parser), true);
1765         if (!val)
1766             return false;
1767         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1768
1769         if (!parser_next(parser) || parser->tok != ')') {
1770             parseerror(parser, "expected closing paren after translatable string");
1771             return false;
1772         }
1773         return true;
1774     }
1775     else if (parser->tok == TOKEN_DOTS)
1776     {
1777         ast_expression *va;
1778         if (!OPTS_FLAG(VARIADIC_ARGS)) {
1779             parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1780             return false;
1781         }
1782         va = parse_vararg(parser);
1783         if (!va)
1784             return false;
1785         vec_push(sy->out, syexp(parser_ctx(parser), va));
1786         return true;
1787     }
1788     else if (parser->tok == TOKEN_FLOATCONST) {
1789         ast_value *val;
1790         val = parser_const_float(parser, (parser_token(parser)->constval.f));
1791         if (!val)
1792             return false;
1793         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1794         return true;
1795     }
1796     else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1797         ast_value *val;
1798         val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1799         if (!val)
1800             return false;
1801         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1802         return true;
1803     }
1804     else if (parser->tok == TOKEN_STRINGCONST) {
1805         ast_value *val;
1806         val = parser_const_string(parser, parser_tokval(parser), false);
1807         if (!val)
1808             return false;
1809         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1810         return true;
1811     }
1812     else if (parser->tok == TOKEN_VECTORCONST) {
1813         ast_value *val;
1814         val = parser_const_vector(parser, parser_token(parser)->constval.v);
1815         if (!val)
1816             return false;
1817         vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1818         return true;
1819     }
1820     else if (parser->tok == TOKEN_IDENT)
1821     {
1822         const char     *ctoken = parser_tokval(parser);
1823         ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1824         ast_expression *var;
1825         /* a_vector.{x,y,z} */
1826         if (!vec_size(sy->ops) ||
1827             !vec_last(sy->ops).etype ||
1828             operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1829             (prev >= intrinsic_debug_typestring &&
1830              prev <= intrinsic_debug_typestring))
1831         {
1832             /* When adding more intrinsics, fix the above condition */
1833             prev = NULL;
1834         }
1835         if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1836         {
1837             var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1838         } else {
1839             var = parser_find_var(parser, parser_tokval(parser));
1840             if (!var)
1841                 var = parser_find_field(parser, parser_tokval(parser));
1842         }
1843         if (!var && with_labels) {
1844             var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1845             if (!with_labels) {
1846                 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1847                 var = (ast_expression*)lbl;
1848                 vec_push(parser->labels, lbl);
1849             }
1850         }
1851         if (!var) {
1852             /* intrinsics */
1853             if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1854                 var = (ast_expression*)intrinsic_debug_typestring;
1855             }
1856             if (!strcmp(parser_tokval(parser), "__builtin_pow"))
1857                 var = parser_builtin_pow(parser);
1858                 
1859             if (!var) {
1860                 char *correct = NULL;
1861                 size_t i;
1862
1863                 /*
1864                  * sometimes people use preprocessing predefs without enabling them
1865                  * i've done this thousands of times already myself.  Lets check for
1866                  * it in the predef table.  And diagnose it better :)
1867                  */
1868                 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1869                     for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1870                         if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1871                             parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1872                             return false;
1873                         }
1874                     }
1875                 }
1876
1877                 /*
1878                  * TODO: determine the best score for the identifier: be it
1879                  * a variable, a field.
1880                  *
1881                  * We should also consider adding correction tables for
1882                  * other things as well.
1883                  */
1884                 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1885                     correction_t corr;
1886                     correct_init(&corr);
1887
1888                     for (i = 0; i < vec_size(parser->correct_variables); i++) {
1889                         correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1890                         if (strcmp(correct, parser_tokval(parser))) {
1891                             break;
1892                         } else if (correct) {
1893                             mem_d(correct);
1894                             correct = NULL;
1895                         }
1896                     }
1897                     correct_free(&corr);
1898
1899                     if (correct) {
1900                         parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1901                         mem_d(correct);
1902                         return false;
1903                     }
1904                 }
1905                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1906                 return false;
1907             }
1908         }
1909         else
1910         {
1911             if (ast_istype(var, ast_value)) {
1912                 ((ast_value*)var)->uses++;
1913             }
1914             else if (ast_istype(var, ast_member)) {
1915                 ast_member *mem = (ast_member*)var;
1916                 if (ast_istype(mem->owner, ast_value))
1917                     ((ast_value*)(mem->owner))->uses++;
1918             }
1919         }
1920         vec_push(sy->out, syexp(parser_ctx(parser), var));
1921         return true;
1922     }
1923     parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1924     return false;
1925 }
1926
1927 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1928 {
1929     ast_expression *expr = NULL;
1930     shunt sy;
1931     size_t i;
1932     bool wantop = false;
1933     /* only warn once about an assignment in a truth value because the current code
1934      * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1935      */
1936     bool warn_truthvalue = true;
1937
1938     /* count the parens because an if starts with one, so the
1939      * end of a condition is an unmatched closing paren
1940      */
1941     int ternaries = 0;
1942
1943     memset(&sy, 0, sizeof(sy));
1944
1945     parser->lex->flags.noops = false;
1946
1947     parser_reclassify_token(parser);
1948
1949     while (true)
1950     {
1951         if (parser->tok == TOKEN_TYPENAME) {
1952             parseerror(parser, "unexpected typename");
1953             goto onerr;
1954         }
1955
1956         if (parser->tok == TOKEN_OPERATOR)
1957         {
1958             /* classify the operator */
1959             const oper_info *op;
1960             const oper_info *olast = NULL;
1961             size_t o;
1962             for (o = 0; o < operator_count; ++o) {
1963                 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1964                     /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1965                     !strcmp(parser_tokval(parser), operators[o].op))
1966                 {
1967                     break;
1968                 }
1969             }
1970             if (o == operator_count) {
1971                 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1972                 goto onerr;
1973             }
1974             /* found an operator */
1975             op = &operators[o];
1976
1977             /* when declaring variables, a comma starts a new variable */
1978             if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1979                 /* fixup the token */
1980                 parser->tok = ',';
1981                 break;
1982             }
1983
1984             /* a colon without a pervious question mark cannot be a ternary */
1985             if (!ternaries && op->id == opid2(':','?')) {
1986                 parser->tok = ':';
1987                 break;
1988             }
1989
1990             if (op->id == opid1(',')) {
1991                 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1992                     (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1993                 }
1994             }
1995
1996             if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1997                 olast = &operators[vec_last(sy.ops).etype-1];
1998
1999 #define IsAssignOp(x) (\
2000                 (x) == opid1('=') || \
2001                 (x) == opid2('+','=') || \
2002                 (x) == opid2('-','=') || \
2003                 (x) == opid2('*','=') || \
2004                 (x) == opid2('/','=') || \
2005                 (x) == opid2('%','=') || \
2006                 (x) == opid2('&','=') || \
2007                 (x) == opid2('|','=') || \
2008                 (x) == opid3('&','~','=') \
2009                 )
2010             if (warn_truthvalue) {
2011                 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2012                      (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2013                      (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2014                    )
2015                 {
2016                     (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2017                     warn_truthvalue = false;
2018                 }
2019             }
2020
2021             while (olast && (
2022                     (op->prec < olast->prec) ||
2023                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2024             {
2025                 if (!parser_sy_apply_operator(parser, &sy))
2026                     goto onerr;
2027                 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2028                     olast = &operators[vec_last(sy.ops).etype-1];
2029                 else
2030                     olast = NULL;
2031             }
2032
2033             if (op->id == opid1('(')) {
2034                 if (wantop) {
2035                     size_t sycount = vec_size(sy.out);
2036                     /* we expected an operator, this is the function-call operator */
2037                     vec_push(sy.paren, PAREN_FUNC);
2038                     vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2039                     vec_push(sy.argc, 0);
2040                 } else {
2041                     vec_push(sy.paren, PAREN_EXPR);
2042                     vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2043                 }
2044                 wantop = false;
2045             } else if (op->id == opid1('[')) {
2046                 if (!wantop) {
2047                     parseerror(parser, "unexpected array subscript");
2048                     goto onerr;
2049                 }
2050                 vec_push(sy.paren, PAREN_INDEX);
2051                 /* push both the operator and the paren, this makes life easier */
2052                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2053                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2054                 wantop = false;
2055             } else if (op->id == opid2('?',':')) {
2056                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2057                 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2058                 wantop = false;
2059                 ++ternaries;
2060                 vec_push(sy.paren, PAREN_TERNARY1);
2061             } else if (op->id == opid2(':','?')) {
2062                 if (!vec_size(sy.paren)) {
2063                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2064                     goto onerr;
2065                 }
2066                 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2067                     parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2068                     goto onerr;
2069                 }
2070                 if (!parser_close_paren(parser, &sy))
2071                     goto onerr;
2072                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2073                 wantop = false;
2074                 --ternaries;
2075             } else {
2076                 vec_push(sy.ops, syop(parser_ctx(parser), op));
2077                 wantop = !!(op->flags & OP_SUFFIX);
2078             }
2079         }
2080         else if (parser->tok == ')') {
2081             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2082                 if (!parser_sy_apply_operator(parser, &sy))
2083                     goto onerr;
2084             }
2085             if (!vec_size(sy.paren))
2086                 break;
2087             if (wantop) {
2088                 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2089                     parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2090                     goto onerr;
2091                 }
2092                 if (!parser_close_paren(parser, &sy))
2093                     goto onerr;
2094             } else {
2095                 /* must be a function call without parameters */
2096                 if (vec_last(sy.paren) != PAREN_FUNC) {
2097                     parseerror(parser, "closing paren in invalid position");
2098                     goto onerr;
2099                 }
2100                 if (!parser_close_paren(parser, &sy))
2101                     goto onerr;
2102             }
2103             wantop = true;
2104         }
2105         else if (parser->tok == '(') {
2106             parseerror(parser, "internal error: '(' should be classified as operator");
2107             goto onerr;
2108         }
2109         else if (parser->tok == '[') {
2110             parseerror(parser, "internal error: '[' should be classified as operator");
2111             goto onerr;
2112         }
2113         else if (parser->tok == ']') {
2114             while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2115                 if (!parser_sy_apply_operator(parser, &sy))
2116                     goto onerr;
2117             }
2118             if (!vec_size(sy.paren))
2119                 break;
2120             if (vec_last(sy.paren) != PAREN_INDEX) {
2121                 parseerror(parser, "mismatched parentheses, unexpected ']'");
2122                 goto onerr;
2123             }
2124             if (!parser_close_paren(parser, &sy))
2125                 goto onerr;
2126             wantop = true;
2127         }
2128         else if (!wantop) {
2129             if (!parse_sya_operand(parser, &sy, with_labels))
2130                 goto onerr;
2131 #if 0
2132             if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2133                 vec_last(sy.argc)++;
2134 #endif
2135             wantop = true;
2136         }
2137         else {
2138             parseerror(parser, "expected operator or end of statement");
2139             goto onerr;
2140         }
2141
2142         if (!parser_next(parser)) {
2143             goto onerr;
2144         }
2145         if (parser->tok == ';' ||
2146             ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2147             (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2148         {
2149             break;
2150         }
2151     }
2152
2153     while (vec_size(sy.ops)) {
2154         if (!parser_sy_apply_operator(parser, &sy))
2155             goto onerr;
2156     }
2157
2158     parser->lex->flags.noops = true;
2159     if (!vec_size(sy.out)) {
2160         parseerror(parser, "empty expression");
2161         expr = NULL;
2162     } else
2163         expr = sy.out[0].out;
2164     vec_free(sy.out);
2165     vec_free(sy.ops);
2166     if (vec_size(sy.paren)) {
2167         parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2168         return NULL;
2169     }
2170     vec_free(sy.paren);
2171     vec_free(sy.argc);
2172     return expr;
2173
2174 onerr:
2175     parser->lex->flags.noops = true;
2176     for (i = 0; i < vec_size(sy.out); ++i) {
2177         if (sy.out[i].out)
2178             ast_unref(sy.out[i].out);
2179     }
2180     vec_free(sy.out);
2181     vec_free(sy.ops);
2182     vec_free(sy.paren);
2183     vec_free(sy.argc);
2184     return NULL;
2185 }
2186
2187 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2188 {
2189     ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2190     if (!e)
2191         return NULL;
2192     if (parser->tok != ';') {
2193         parseerror(parser, "semicolon expected after expression");
2194         ast_unref(e);
2195         return NULL;
2196     }
2197     if (!parser_next(parser)) {
2198         ast_unref(e);
2199         return NULL;
2200     }
2201     return e;
2202 }
2203
2204 static void parser_enterblock(parser_t *parser)
2205 {
2206     vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2207     vec_push(parser->_blocklocals, vec_size(parser->_locals));
2208     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2209     vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2210     vec_push(parser->_block_ctx, parser_ctx(parser));
2211
2212     /* corrector */
2213     vec_push(parser->correct_variables, correct_trie_new());
2214     vec_push(parser->correct_variables_score, NULL);
2215 }
2216
2217 static bool parser_leaveblock(parser_t *parser)
2218 {
2219     bool   rv = true;
2220     size_t locals, typedefs;
2221
2222     if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2223         parseerror(parser, "internal error: parser_leaveblock with no block");
2224         return false;
2225     }
2226
2227     util_htdel(vec_last(parser->variables));
2228     correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2229
2230     vec_pop(parser->variables);
2231     vec_pop(parser->correct_variables);
2232     vec_pop(parser->correct_variables_score);
2233     if (!vec_size(parser->_blocklocals)) {
2234         parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2235         return false;
2236     }
2237
2238     locals = vec_last(parser->_blocklocals);
2239     vec_pop(parser->_blocklocals);
2240     while (vec_size(parser->_locals) != locals) {
2241         ast_expression *e = vec_last(parser->_locals);
2242         ast_value      *v = (ast_value*)e;
2243         vec_pop(parser->_locals);
2244         if (ast_istype(e, ast_value) && !v->uses) {
2245             if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2246                 rv = false;
2247         }
2248     }
2249
2250     typedefs = vec_last(parser->_blocktypedefs);
2251     while (vec_size(parser->_typedefs) != typedefs) {
2252         ast_delete(vec_last(parser->_typedefs));
2253         vec_pop(parser->_typedefs);
2254     }
2255     util_htdel(vec_last(parser->typedefs));
2256     vec_pop(parser->typedefs);
2257
2258     vec_pop(parser->_block_ctx);
2259
2260     return rv;
2261 }
2262
2263 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2264 {
2265     vec_push(parser->_locals, e);
2266     util_htset(vec_last(parser->variables), name, (void*)e);
2267
2268     /* corrector */
2269     correct_add (
2270          vec_last(parser->correct_variables),
2271         &vec_last(parser->correct_variables_score),
2272         name
2273     );
2274 }
2275
2276 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2277 {
2278     vec_push(parser->globals, e);
2279     util_htset(parser->htglobals, name, e);
2280
2281     /* corrector */
2282     correct_add (
2283          parser->correct_variables[0],
2284         &parser->correct_variables_score[0],
2285         name
2286     );
2287 }
2288
2289 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2290 {
2291     bool       ifnot = false;
2292     ast_unary *unary;
2293     ast_expression *prev;
2294
2295     if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2296         char ty[1024];
2297         ast_type_to_string(cond, ty, sizeof(ty));
2298         compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2299     }
2300
2301     if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2302     {
2303         prev = cond;
2304         cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2305         if (!cond) {
2306             ast_unref(prev);
2307             parseerror(parser, "internal error: failed to process condition");
2308             return NULL;
2309         }
2310         ifnot = !ifnot;
2311     }
2312     else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2313     {
2314         /* vector types need to be cast to true booleans */
2315         ast_binary *bin = (ast_binary*)cond;
2316         if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2317         {
2318             /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2319             prev = cond;
2320             cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2321             if (!cond) {
2322                 ast_unref(prev);
2323                 parseerror(parser, "internal error: failed to process condition");
2324                 return NULL;
2325             }
2326             ifnot = !ifnot;
2327         }
2328     }
2329
2330     unary = (ast_unary*)cond;
2331     while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2332     {
2333         cond = unary->operand;
2334         unary->operand = NULL;
2335         ast_delete(unary);
2336         ifnot = !ifnot;
2337         unary = (ast_unary*)cond;
2338     }
2339
2340     if (!cond)
2341         parseerror(parser, "internal error: failed to process condition");
2342
2343     if (ifnot) *_ifnot = !*_ifnot;
2344     return cond;
2345 }
2346
2347 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2348 {
2349     ast_ifthen *ifthen;
2350     ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2351     bool ifnot = false;
2352
2353     lex_ctx ctx = parser_ctx(parser);
2354
2355     (void)block; /* not touching */
2356
2357     /* skip the 'if', parse an optional 'not' and check for an opening paren */
2358     if (!parser_next(parser)) {
2359         parseerror(parser, "expected condition or 'not'");
2360         return false;
2361     }
2362     if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2363         ifnot = true;
2364         if (!parser_next(parser)) {
2365             parseerror(parser, "expected condition in parenthesis");
2366             return false;
2367         }
2368     }
2369     if (parser->tok != '(') {
2370         parseerror(parser, "expected 'if' condition in parenthesis");
2371         return false;
2372     }
2373     /* parse into the expression */
2374     if (!parser_next(parser)) {
2375         parseerror(parser, "expected 'if' condition after opening paren");
2376         return false;
2377     }
2378     /* parse the condition */
2379     cond = parse_expression_leave(parser, false, true, false);
2380     if (!cond)
2381         return false;
2382     /* closing paren */
2383     if (parser->tok != ')') {
2384         parseerror(parser, "expected closing paren after 'if' condition");
2385         ast_delete(cond);
2386         return false;
2387     }
2388     /* parse into the 'then' branch */
2389     if (!parser_next(parser)) {
2390         parseerror(parser, "expected statement for on-true branch of 'if'");
2391         ast_delete(cond);
2392         return false;
2393     }
2394     if (!parse_statement_or_block(parser, &ontrue)) {
2395         ast_delete(cond);
2396         return false;
2397     }
2398     if (!ontrue)
2399         ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2400     /* check for an else */
2401     if (!strcmp(parser_tokval(parser), "else")) {
2402         /* parse into the 'else' branch */
2403         if (!parser_next(parser)) {
2404             parseerror(parser, "expected on-false branch after 'else'");
2405             ast_delete(ontrue);
2406             ast_delete(cond);
2407             return false;
2408         }
2409         if (!parse_statement_or_block(parser, &onfalse)) {
2410             ast_delete(ontrue);
2411             ast_delete(cond);
2412             return false;
2413         }
2414     }
2415
2416     cond = process_condition(parser, cond, &ifnot);
2417     if (!cond) {
2418         if (ontrue)  ast_delete(ontrue);
2419         if (onfalse) ast_delete(onfalse);
2420         return false;
2421     }
2422
2423     if (ifnot)
2424         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2425     else
2426         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2427     *out = (ast_expression*)ifthen;
2428     return true;
2429 }
2430
2431 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2432 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2433 {
2434     bool rv;
2435     char *label = NULL;
2436
2437     /* skip the 'while' and get the body */
2438     if (!parser_next(parser)) {
2439         if (OPTS_FLAG(LOOP_LABELS))
2440             parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2441         else
2442             parseerror(parser, "expected 'while' condition in parenthesis");
2443         return false;
2444     }
2445
2446     if (parser->tok == ':') {
2447         if (!OPTS_FLAG(LOOP_LABELS))
2448             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2449         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2450             parseerror(parser, "expected loop label");
2451             return false;
2452         }
2453         label = util_strdup(parser_tokval(parser));
2454         if (!parser_next(parser)) {
2455             mem_d(label);
2456             parseerror(parser, "expected 'while' condition in parenthesis");
2457             return false;
2458         }
2459     }
2460
2461     if (parser->tok != '(') {
2462         parseerror(parser, "expected 'while' condition in parenthesis");
2463         return false;
2464     }
2465
2466     vec_push(parser->breaks, label);
2467     vec_push(parser->continues, label);
2468
2469     rv = parse_while_go(parser, block, out);
2470     if (label)
2471         mem_d(label);
2472     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2473         parseerror(parser, "internal error: label stack corrupted");
2474         rv = false;
2475         ast_delete(*out);
2476         *out = NULL;
2477     }
2478     else {
2479         vec_pop(parser->breaks);
2480         vec_pop(parser->continues);
2481     }
2482     return rv;
2483 }
2484
2485 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2486 {
2487     ast_loop *aloop;
2488     ast_expression *cond, *ontrue;
2489
2490     bool ifnot = false;
2491
2492     lex_ctx ctx = parser_ctx(parser);
2493
2494     (void)block; /* not touching */
2495
2496     /* parse into the expression */
2497     if (!parser_next(parser)) {
2498         parseerror(parser, "expected 'while' condition after opening paren");
2499         return false;
2500     }
2501     /* parse the condition */
2502     cond = parse_expression_leave(parser, false, true, false);
2503     if (!cond)
2504         return false;
2505     /* closing paren */
2506     if (parser->tok != ')') {
2507         parseerror(parser, "expected closing paren after 'while' condition");
2508         ast_delete(cond);
2509         return false;
2510     }
2511     /* parse into the 'then' branch */
2512     if (!parser_next(parser)) {
2513         parseerror(parser, "expected while-loop body");
2514         ast_delete(cond);
2515         return false;
2516     }
2517     if (!parse_statement_or_block(parser, &ontrue)) {
2518         ast_delete(cond);
2519         return false;
2520     }
2521
2522     cond = process_condition(parser, cond, &ifnot);
2523     if (!cond) {
2524         ast_delete(ontrue);
2525         return false;
2526     }
2527     aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2528     *out = (ast_expression*)aloop;
2529     return true;
2530 }
2531
2532 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2533 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2534 {
2535     bool rv;
2536     char *label = NULL;
2537
2538     /* skip the 'do' and get the body */
2539     if (!parser_next(parser)) {
2540         if (OPTS_FLAG(LOOP_LABELS))
2541             parseerror(parser, "expected loop label or body");
2542         else
2543             parseerror(parser, "expected loop body");
2544         return false;
2545     }
2546
2547     if (parser->tok == ':') {
2548         if (!OPTS_FLAG(LOOP_LABELS))
2549             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2550         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2551             parseerror(parser, "expected loop label");
2552             return false;
2553         }
2554         label = util_strdup(parser_tokval(parser));
2555         if (!parser_next(parser)) {
2556             mem_d(label);
2557             parseerror(parser, "expected loop body");
2558             return false;
2559         }
2560     }
2561
2562     vec_push(parser->breaks, label);
2563     vec_push(parser->continues, label);
2564
2565     rv = parse_dowhile_go(parser, block, out);
2566     if (label)
2567         mem_d(label);
2568     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2569         parseerror(parser, "internal error: label stack corrupted");
2570         rv = false;
2571         ast_delete(*out);
2572         *out = NULL;
2573     }
2574     else {
2575         vec_pop(parser->breaks);
2576         vec_pop(parser->continues);
2577     }
2578     return rv;
2579 }
2580
2581 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2582 {
2583     ast_loop *aloop;
2584     ast_expression *cond, *ontrue;
2585
2586     bool ifnot = false;
2587
2588     lex_ctx ctx = parser_ctx(parser);
2589
2590     (void)block; /* not touching */
2591
2592     if (!parse_statement_or_block(parser, &ontrue))
2593         return false;
2594
2595     /* expect the "while" */
2596     if (parser->tok != TOKEN_KEYWORD ||
2597         strcmp(parser_tokval(parser), "while"))
2598     {
2599         parseerror(parser, "expected 'while' and condition");
2600         ast_delete(ontrue);
2601         return false;
2602     }
2603
2604     /* skip the 'while' and check for opening paren */
2605     if (!parser_next(parser) || parser->tok != '(') {
2606         parseerror(parser, "expected 'while' condition in parenthesis");
2607         ast_delete(ontrue);
2608         return false;
2609     }
2610     /* parse into the expression */
2611     if (!parser_next(parser)) {
2612         parseerror(parser, "expected 'while' condition after opening paren");
2613         ast_delete(ontrue);
2614         return false;
2615     }
2616     /* parse the condition */
2617     cond = parse_expression_leave(parser, false, true, false);
2618     if (!cond)
2619         return false;
2620     /* closing paren */
2621     if (parser->tok != ')') {
2622         parseerror(parser, "expected closing paren after 'while' condition");
2623         ast_delete(ontrue);
2624         ast_delete(cond);
2625         return false;
2626     }
2627     /* parse on */
2628     if (!parser_next(parser) || parser->tok != ';') {
2629         parseerror(parser, "expected semicolon after condition");
2630         ast_delete(ontrue);
2631         ast_delete(cond);
2632         return false;
2633     }
2634
2635     if (!parser_next(parser)) {
2636         parseerror(parser, "parse error");
2637         ast_delete(ontrue);
2638         ast_delete(cond);
2639         return false;
2640     }
2641
2642     cond = process_condition(parser, cond, &ifnot);
2643     if (!cond) {
2644         ast_delete(ontrue);
2645         return false;
2646     }
2647     aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2648     *out = (ast_expression*)aloop;
2649     return true;
2650 }
2651
2652 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2653 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2654 {
2655     bool rv;
2656     char *label = NULL;
2657
2658     /* skip the 'for' and check for opening paren */
2659     if (!parser_next(parser)) {
2660         if (OPTS_FLAG(LOOP_LABELS))
2661             parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2662         else
2663             parseerror(parser, "expected 'for' expressions in parenthesis");
2664         return false;
2665     }
2666
2667     if (parser->tok == ':') {
2668         if (!OPTS_FLAG(LOOP_LABELS))
2669             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2670         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2671             parseerror(parser, "expected loop label");
2672             return false;
2673         }
2674         label = util_strdup(parser_tokval(parser));
2675         if (!parser_next(parser)) {
2676             mem_d(label);
2677             parseerror(parser, "expected 'for' expressions in parenthesis");
2678             return false;
2679         }
2680     }
2681
2682     if (parser->tok != '(') {
2683         parseerror(parser, "expected 'for' expressions in parenthesis");
2684         return false;
2685     }
2686
2687     vec_push(parser->breaks, label);
2688     vec_push(parser->continues, label);
2689
2690     rv = parse_for_go(parser, block, out);
2691     if (label)
2692         mem_d(label);
2693     if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2694         parseerror(parser, "internal error: label stack corrupted");
2695         rv = false;
2696         ast_delete(*out);
2697         *out = NULL;
2698     }
2699     else {
2700         vec_pop(parser->breaks);
2701         vec_pop(parser->continues);
2702     }
2703     return rv;
2704 }
2705 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2706 {
2707     ast_loop       *aloop;
2708     ast_expression *initexpr, *cond, *increment, *ontrue;
2709     ast_value      *typevar;
2710
2711     bool retval = true;
2712     bool ifnot  = false;
2713
2714     lex_ctx ctx = parser_ctx(parser);
2715
2716     parser_enterblock(parser);
2717
2718     initexpr  = NULL;
2719     cond      = NULL;
2720     increment = NULL;
2721     ontrue    = NULL;
2722
2723     /* parse into the expression */
2724     if (!parser_next(parser)) {
2725         parseerror(parser, "expected 'for' initializer after opening paren");
2726         goto onerr;
2727     }
2728
2729     typevar = NULL;
2730     if (parser->tok == TOKEN_IDENT)
2731         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2732
2733     if (typevar || parser->tok == TOKEN_TYPENAME) {
2734 #if 0
2735         if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2736             if (parsewarning(parser, WARN_EXTENSIONS,
2737                              "current standard does not allow variable declarations in for-loop initializers"))
2738                 goto onerr;
2739         }
2740 #endif
2741         if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2742             goto onerr;
2743     }
2744     else if (parser->tok != ';')
2745     {
2746         initexpr = parse_expression_leave(parser, false, false, false);
2747         if (!initexpr)
2748             goto onerr;
2749     }
2750
2751     /* move on to condition */
2752     if (parser->tok != ';') {
2753         parseerror(parser, "expected semicolon after for-loop initializer");
2754         goto onerr;
2755     }
2756     if (!parser_next(parser)) {
2757         parseerror(parser, "expected for-loop condition");
2758         goto onerr;
2759     }
2760
2761     /* parse the condition */
2762     if (parser->tok != ';') {
2763         cond = parse_expression_leave(parser, false, true, false);
2764         if (!cond)
2765             goto onerr;
2766     }
2767
2768     /* move on to incrementor */
2769     if (parser->tok != ';') {
2770         parseerror(parser, "expected semicolon after for-loop initializer");
2771         goto onerr;
2772     }
2773     if (!parser_next(parser)) {
2774         parseerror(parser, "expected for-loop condition");
2775         goto onerr;
2776     }
2777
2778     /* parse the incrementor */
2779     if (parser->tok != ')') {
2780         lex_ctx condctx = parser_ctx(parser);
2781         increment = parse_expression_leave(parser, false, false, false);
2782         if (!increment)
2783             goto onerr;
2784         if (!ast_side_effects(increment)) {
2785             if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2786                 goto onerr;
2787         }
2788     }
2789
2790     /* closing paren */
2791     if (parser->tok != ')') {
2792         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2793         goto onerr;
2794     }
2795     /* parse into the 'then' branch */
2796     if (!parser_next(parser)) {
2797         parseerror(parser, "expected for-loop body");
2798         goto onerr;
2799     }
2800     if (!parse_statement_or_block(parser, &ontrue))
2801         goto onerr;
2802
2803     if (cond) {
2804         cond = process_condition(parser, cond, &ifnot);
2805         if (!cond)
2806             goto onerr;
2807     }
2808     aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2809     *out = (ast_expression*)aloop;
2810
2811     if (!parser_leaveblock(parser))
2812         retval = false;
2813     return retval;
2814 onerr:
2815     if (initexpr)  ast_delete(initexpr);
2816     if (cond)      ast_delete(cond);
2817     if (increment) ast_delete(increment);
2818     (void)!parser_leaveblock(parser);
2819     return false;
2820 }
2821
2822 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2823 {
2824     ast_expression *exp = NULL;
2825     ast_return     *ret = NULL;
2826     ast_value      *expected = parser->function->vtype;
2827
2828     lex_ctx ctx = parser_ctx(parser);
2829
2830     (void)block; /* not touching */
2831
2832     if (!parser_next(parser)) {
2833         parseerror(parser, "expected return expression");
2834         return false;
2835     }
2836
2837     if (parser->tok != ';') {
2838         exp = parse_expression(parser, false, false);
2839         if (!exp)
2840             return false;
2841
2842         if (exp->expression.vtype != TYPE_NIL &&
2843             exp->expression.vtype != expected->expression.next->expression.vtype)
2844         {
2845             parseerror(parser, "return with invalid expression");
2846         }
2847
2848         ret = ast_return_new(ctx, exp);
2849         if (!ret) {
2850             ast_delete(exp);
2851             return false;
2852         }
2853     } else {
2854         if (!parser_next(parser))
2855             parseerror(parser, "parse error");
2856         if (expected->expression.next->expression.vtype != TYPE_VOID) {
2857             (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2858         }
2859         ret = ast_return_new(ctx, NULL);
2860     }
2861     *out = (ast_expression*)ret;
2862     return true;
2863 }
2864
2865 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2866 {
2867     size_t       i;
2868     unsigned int levels = 0;
2869     lex_ctx      ctx = parser_ctx(parser);
2870     const char **loops = (is_continue ? parser->continues : parser->breaks);
2871
2872     (void)block; /* not touching */
2873     if (!parser_next(parser)) {
2874         parseerror(parser, "expected semicolon or loop label");
2875         return false;
2876     }
2877
2878     if (!vec_size(loops)) {
2879         if (is_continue)
2880             parseerror(parser, "`continue` can only be used inside loops");
2881         else
2882             parseerror(parser, "`break` can only be used inside loops or switches");
2883     }
2884
2885     if (parser->tok == TOKEN_IDENT) {
2886         if (!OPTS_FLAG(LOOP_LABELS))
2887             parseerror(parser, "labeled loops not activated, try using -floop-labels");
2888         i = vec_size(loops);
2889         while (i--) {
2890             if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2891                 break;
2892             if (!i) {
2893                 parseerror(parser, "no such loop to %s: `%s`",
2894                            (is_continue ? "continue" : "break out of"),
2895                            parser_tokval(parser));
2896                 return false;
2897             }
2898             ++levels;
2899         }
2900         if (!parser_next(parser)) {
2901             parseerror(parser, "expected semicolon");
2902             return false;
2903         }
2904     }
2905
2906     if (parser->tok != ';') {
2907         parseerror(parser, "expected semicolon");
2908         return false;
2909     }
2910
2911     if (!parser_next(parser))
2912         parseerror(parser, "parse error");
2913
2914     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2915     return true;
2916 }
2917
2918 /* returns true when it was a variable qualifier, false otherwise!
2919  * on error, cvq is set to CV_WRONG
2920  */
2921 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2922 {
2923     bool had_const    = false;
2924     bool had_var      = false;
2925     bool had_noref    = false;
2926     bool had_attrib   = false;
2927     bool had_static   = false;
2928     uint32_t flags    = 0;
2929
2930     *cvq = CV_NONE;
2931     for (;;) {
2932         if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2933             had_attrib = true;
2934             /* parse an attribute */
2935             if (!parser_next(parser)) {
2936                 parseerror(parser, "expected attribute after `[[`");
2937                 *cvq = CV_WRONG;
2938                 return false;
2939             }
2940             if (!strcmp(parser_tokval(parser), "noreturn")) {
2941                 flags |= AST_FLAG_NORETURN;
2942                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2943                     parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2944                     *cvq = CV_WRONG;
2945                     return false;
2946                 }
2947             }
2948             else if (!strcmp(parser_tokval(parser), "noref")) {
2949                 had_noref = true;
2950                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2951                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2952                     *cvq = CV_WRONG;
2953                     return false;
2954                 }
2955             }
2956             else if (!strcmp(parser_tokval(parser), "inline")) {
2957                 flags |= AST_FLAG_INLINE;
2958                 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2959                     parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2960                     *cvq = CV_WRONG;
2961                     return false;
2962                 }
2963             }
2964             else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2965                 flags   |= AST_FLAG_ALIAS;
2966                 *message = NULL;
2967
2968                 if (!parser_next(parser)) {
2969                     parseerror(parser, "parse error in attribute");
2970                     goto argerr;
2971                 }
2972
2973                 if (parser->tok == '(') {
2974                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2975                         parseerror(parser, "`alias` attribute missing parameter");
2976                         goto argerr;
2977                     }
2978
2979                     *message = util_strdup(parser_tokval(parser));
2980
2981                     if (!parser_next(parser)) {
2982                         parseerror(parser, "parse error in attribute");
2983                         goto argerr;
2984                     }
2985
2986                     if (parser->tok != ')') {
2987                         parseerror(parser, "`alias` attribute expected `)` after parameter");
2988                         goto argerr;
2989                     }
2990
2991                     if (!parser_next(parser)) {
2992                         parseerror(parser, "parse error in attribute");
2993                         goto argerr;
2994                     }
2995                 }
2996
2997                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2998                     parseerror(parser, "`alias` attribute expected `]]`");
2999                     goto argerr;
3000                 }
3001             }
3002             else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3003                 flags   |= AST_FLAG_DEPRECATED;
3004                 *message = NULL;
3005
3006                 if (!parser_next(parser)) {
3007                     parseerror(parser, "parse error in attribute");
3008                     goto argerr;
3009                 }
3010
3011                 if (parser->tok == '(') {
3012                     if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3013                         parseerror(parser, "`deprecated` attribute missing parameter");
3014                         goto argerr;
3015                     }
3016
3017                     *message = util_strdup(parser_tokval(parser));
3018
3019                     if (!parser_next(parser)) {
3020                         parseerror(parser, "parse error in attribute");
3021                         goto argerr;
3022                     }
3023
3024                     if(parser->tok != ')') {
3025                         parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3026                         goto argerr;
3027                     }
3028
3029                     if (!parser_next(parser)) {
3030                         parseerror(parser, "parse error in attribute");
3031                         goto argerr;
3032                     }
3033                 }
3034                 /* no message */
3035                 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3036                     parseerror(parser, "`deprecated` attribute expected `]]`");
3037
3038                     argerr: /* ugly */
3039                     if (*message) mem_d(*message);
3040                     *message = NULL;
3041                     *cvq     = CV_WRONG;
3042                     return false;
3043                 }
3044             }
3045             else
3046             {
3047                 /* Skip tokens until we hit a ]] */
3048                 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3049                 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3050                     if (!parser_next(parser)) {
3051                         parseerror(parser, "error inside attribute");
3052                         *cvq = CV_WRONG;
3053                         return false;
3054                     }
3055                 }
3056             }
3057         }
3058         else if (with_local && !strcmp(parser_tokval(parser), "static"))
3059             had_static = true;
3060         else if (!strcmp(parser_tokval(parser), "const"))
3061             had_const = true;
3062         else if (!strcmp(parser_tokval(parser), "var"))
3063             had_var = true;
3064         else if (with_local && !strcmp(parser_tokval(parser), "local"))
3065             had_var = true;
3066         else if (!strcmp(parser_tokval(parser), "noref"))
3067             had_noref = true;
3068         else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3069             return false;
3070         }
3071         else
3072             break;
3073         if (!parser_next(parser))
3074             goto onerr;
3075     }
3076     if (had_const)
3077         *cvq = CV_CONST;
3078     else if (had_var)
3079         *cvq = CV_VAR;
3080     else
3081         *cvq = CV_NONE;
3082     *noref     = had_noref;
3083     *is_static = had_static;
3084     *_flags    = flags;
3085     return true;
3086 onerr:
3087     parseerror(parser, "parse error after variable qualifier");
3088     *cvq = CV_WRONG;
3089     return true;
3090 }
3091
3092 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3093 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3094 {
3095     bool rv;
3096     char *label = NULL;
3097
3098     /* skip the 'while' and get the body */
3099     if (!parser_next(parser)) {
3100         if (OPTS_FLAG(LOOP_LABELS))
3101             parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3102         else
3103             parseerror(parser, "expected 'switch' operand in parenthesis");
3104         return false;
3105     }
3106
3107     if (parser->tok == ':') {
3108         if (!OPTS_FLAG(LOOP_LABELS))
3109             parseerror(parser, "labeled loops not activated, try using -floop-labels");
3110         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3111             parseerror(parser, "expected loop label");
3112             return false;
3113         }
3114         label = util_strdup(parser_tokval(parser));
3115         if (!parser_next(parser)) {
3116             mem_d(label);
3117             parseerror(parser, "expected 'switch' operand in parenthesis");
3118             return false;
3119         }
3120     }
3121
3122     if (parser->tok != '(') {
3123         parseerror(parser, "expected 'switch' operand in parenthesis");
3124         return false;
3125     }
3126
3127     vec_push(parser->breaks, label);
3128
3129     rv = parse_switch_go(parser, block, out);
3130     if (label)
3131         mem_d(label);
3132     if (vec_last(parser->breaks) != label) {
3133         parseerror(parser, "internal error: label stack corrupted");
3134         rv = false;
3135         ast_delete(*out);
3136         *out = NULL;
3137     }
3138     else {
3139         vec_pop(parser->breaks);
3140     }
3141     return rv;
3142 }
3143
3144 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3145 {
3146     ast_expression *operand;
3147     ast_value      *opval;
3148     ast_value      *typevar;
3149     ast_switch     *switchnode;
3150     ast_switch_case swcase;
3151
3152     int  cvq;
3153     bool noref, is_static;
3154     uint32_t qflags = 0;
3155
3156     lex_ctx ctx = parser_ctx(parser);
3157
3158     (void)block; /* not touching */
3159     (void)opval;
3160
3161     /* parse into the expression */
3162     if (!parser_next(parser)) {
3163         parseerror(parser, "expected switch operand");
3164         return false;
3165     }
3166     /* parse the operand */
3167     operand = parse_expression_leave(parser, false, false, false);
3168     if (!operand)
3169         return false;
3170
3171     switchnode = ast_switch_new(ctx, operand);
3172
3173     /* closing paren */
3174     if (parser->tok != ')') {
3175         ast_delete(switchnode);
3176         parseerror(parser, "expected closing paren after 'switch' operand");
3177         return false;
3178     }
3179
3180     /* parse over the opening paren */
3181     if (!parser_next(parser) || parser->tok != '{') {
3182         ast_delete(switchnode);
3183         parseerror(parser, "expected list of cases");
3184         return false;
3185     }
3186
3187     if (!parser_next(parser)) {
3188         ast_delete(switchnode);
3189         parseerror(parser, "expected 'case' or 'default'");
3190         return false;
3191     }
3192
3193     /* new block; allow some variables to be declared here */
3194     parser_enterblock(parser);
3195     while (true) {
3196         typevar = NULL;
3197         if (parser->tok == TOKEN_IDENT)
3198             typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3199         if (typevar || parser->tok == TOKEN_TYPENAME) {
3200             if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3201                 ast_delete(switchnode);
3202                 return false;
3203             }
3204             continue;
3205         }
3206         if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3207         {
3208             if (cvq == CV_WRONG) {
3209                 ast_delete(switchnode);
3210                 return false;
3211             }
3212             if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3213                 ast_delete(switchnode);
3214                 return false;
3215             }
3216             continue;
3217         }
3218         break;
3219     }
3220
3221     /* case list! */
3222     while (parser->tok != '}') {
3223         ast_block *caseblock;
3224
3225         if (!strcmp(parser_tokval(parser), "case")) {
3226             if (!parser_next(parser)) {
3227                 ast_delete(switchnode);
3228                 parseerror(parser, "expected expression for case");
3229                 return false;
3230             }
3231             swcase.value = parse_expression_leave(parser, false, false, false);
3232             if (!swcase.value) {
3233                 ast_delete(switchnode);
3234                 parseerror(parser, "expected expression for case");
3235                 return false;
3236             }
3237             if (!OPTS_FLAG(RELAXED_SWITCH)) {
3238                 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3239                     parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3240                     ast_unref(operand);
3241                     return false;
3242                 }
3243             }
3244         }
3245         else if (!strcmp(parser_tokval(parser), "default")) {
3246             swcase.value = NULL;
3247             if (!parser_next(parser)) {
3248                 ast_delete(switchnode);
3249                 parseerror(parser, "expected colon");
3250                 return false;
3251             }
3252         }
3253         else {
3254             ast_delete(switchnode);
3255             parseerror(parser, "expected 'case' or 'default'");
3256             return false;
3257         }
3258
3259         /* Now the colon and body */
3260         if (parser->tok != ':') {
3261             if (swcase.value) ast_unref(swcase.value);
3262             ast_delete(switchnode);
3263             parseerror(parser, "expected colon");
3264             return false;
3265         }
3266
3267         if (!parser_next(parser)) {
3268             if (swcase.value) ast_unref(swcase.value);
3269             ast_delete(switchnode);
3270             parseerror(parser, "expected statements or case");
3271             return false;
3272         }
3273         caseblock = ast_block_new(parser_ctx(parser));
3274         if (!caseblock) {
3275             if (swcase.value) ast_unref(swcase.value);
3276             ast_delete(switchnode);
3277             return false;
3278         }
3279         swcase.code = (ast_expression*)caseblock;
3280         vec_push(switchnode->cases, swcase);
3281         while (true) {
3282             ast_expression *expr;
3283             if (parser->tok == '}')
3284                 break;
3285             if (parser->tok == TOKEN_KEYWORD) {
3286                 if (!strcmp(parser_tokval(parser), "case") ||
3287                     !strcmp(parser_tokval(parser), "default"))
3288                 {
3289                     break;
3290                 }
3291             }
3292             if (!parse_statement(parser, caseblock, &expr, true)) {
3293                 ast_delete(switchnode);
3294                 return false;
3295             }
3296             if (!expr)
3297                 continue;
3298             if (!ast_block_add_expr(caseblock, expr)) {
3299                 ast_delete(switchnode);
3300                 return false;
3301             }
3302         }
3303     }
3304
3305     parser_leaveblock(parser);
3306
3307     /* closing paren */
3308     if (parser->tok != '}') {
3309         ast_delete(switchnode);
3310         parseerror(parser, "expected closing paren of case list");
3311         return false;
3312     }
3313     if (!parser_next(parser)) {
3314         ast_delete(switchnode);
3315         parseerror(parser, "parse error after switch");
3316         return false;
3317     }
3318     *out = (ast_expression*)switchnode;
3319     return true;
3320 }
3321
3322 ast_expression *parser_builtin_pow(parser_t *parser) {
3323     /*
3324      * float __builtin_pow(float x, float y) { 
3325      *   float value = 1.0f;
3326      *   while (y > 0) {
3327      *     while (!(y&1)) {
3328      *       y *= 2;
3329      *       x *= x;
3330      *     }
3331      *     y = y - 1;
3332      *     value = x * value;
3333      *   }
3334      *   return value;
3335      * }      
3336      */
3337     static ast_function  *pow_func       = NULL;
3338     static ast_value     *pow_func_val   = NULL; 
3339     if (!pow_func) {
3340         ast_value    *pow_arguments[2];
3341         ast_value    *pow_value          = ast_value_new   (parser_ctx(parser), "value",         TYPE_FLOAT);
3342         ast_block    *pow_body           = ast_block_new   (parser_ctx(parser));
3343         ast_block    *pow_loop_body      = ast_block_new   (parser_ctx(parser));
3344         ast_block    *pow_loop_nest_body = ast_block_new   (parser_ctx(parser));
3345         ast_loop     *pow_loop           = NULL;
3346         ast_loop     *pow_loop_nest      = NULL;
3347
3348         pow_arguments[0]                 = ast_value_new   (parser_ctx(parser), "x", TYPE_FLOAT);
3349         pow_arguments[1]                 = ast_value_new   (parser_ctx(parser), "x", TYPE_FLOAT);
3350         pow_func_val                     = ast_value_new   (parser_ctx(parser), "__builtin_pow", TYPE_FUNCTION);
3351         pow_func_val->expression.next    = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
3352
3353         vec_push(pow_func_val->expression.params, pow_arguments[0]);
3354         vec_push(pow_func_val->expression.params, pow_arguments[1]);
3355
3356         pow_func = ast_function_new(parser_ctx(parser), "__builtin_pow", pow_func_val);
3357
3358         /* float value; */
3359         vec_push(pow_body->locals, pow_value);
3360         /* value = 1.0f; */
3361         vec_push(pow_body->exprs,
3362             (ast_expression*)ast_store_new(
3363                 parser_ctx(parser),
3364                 INSTR_STORE_F,
3365                 (ast_expression*)pow_value,
3366                 (ast_expression*)parser_const_float_1(parser)
3367             )
3368         );
3369
3370         /* y >>= 2 */
3371         vec_push(pow_loop_nest_body->exprs,
3372             (ast_expression*)ast_binstore_new(
3373                 parser_ctx(parser),
3374                 INSTR_STORE_F,
3375                 INSTR_MUL_F,
3376                 (ast_expression*)pow_arguments[1],
3377                 (ast_expression*)parser_const_float(parser, 0.25f)
3378             )
3379         );
3380         vec_push(pow_loop_nest_body->exprs,
3381             (ast_expression*)ast_binstore_new(
3382                 parser_ctx(parser),
3383                 INSTR_STORE_F,
3384                 INSTR_MUL_F,
3385                 (ast_expression*)pow_arguments[0],
3386                 (ast_expression*)pow_arguments[0]
3387             )
3388         );
3389
3390         /* while (!(y&1)) */
3391         pow_loop_nest = ast_loop_new (
3392             parser_ctx(parser),
3393             NULL,
3394             (ast_expression*)ast_binary_new(
3395                 parser_ctx(parser),
3396                 INSTR_AND,
3397                 (ast_expression*)pow_arguments[1],
3398                 (ast_expression*)parser_const_float_1(parser)
3399             ),
3400             true,
3401             NULL,
3402             false,
3403             NULL,
3404             (ast_expression*)pow_loop_nest_body
3405         );
3406         
3407         vec_push(pow_loop_body->exprs, (ast_expression*)pow_loop_nest);
3408         vec_push(pow_loop_body->exprs,
3409             (ast_expression*)ast_binstore_new(
3410                 parser_ctx(parser),
3411                 INSTR_STORE_F,
3412                 INSTR_SUB_F,
3413                 (ast_expression*)pow_arguments[1],
3414                 (ast_expression*)parser_const_float_1(parser)
3415             )
3416         );
3417         vec_push(pow_loop_body->exprs,
3418             (ast_expression*)ast_binstore_new(
3419                 parser_ctx(parser),
3420                 INSTR_STORE_F,
3421                 INSTR_MUL_F,
3422                 (ast_expression*)pow_value,
3423                 (ast_expression*)pow_arguments[0]
3424             )
3425         );
3426
3427         /* while (y > 0) { */
3428         pow_loop = ast_loop_new(
3429             parser_ctx(parser),
3430             NULL,
3431             (ast_expression*)ast_binary_new(
3432                 parser_ctx(parser),
3433                 INSTR_GT,
3434                 (ast_expression*)pow_arguments[1],
3435                 (ast_expression*)parser_const_float_0(parser)
3436             ),
3437             false,
3438             NULL,
3439             false,
3440             NULL,
3441             (ast_expression*)pow_loop_body
3442         );
3443         /* } */
3444         vec_push(pow_body->exprs, (ast_expression*)pow_loop);
3445         /* return value; */
3446         vec_push(pow_body->exprs,
3447             (ast_expression*)ast_return_new(
3448                 parser_ctx(parser),
3449                 (ast_expression*)pow_value
3450             )
3451         );
3452
3453         vec_push(pow_func->blocks, pow_body);
3454         vec_push(parser->globals, (ast_expression*)pow_func_val);
3455         vec_push(parser->functions, pow_func);
3456     }
3457
3458     return (ast_expression*)pow_func_val;
3459 }
3460
3461 /* parse computed goto sides */
3462 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3463     ast_expression *on_true;
3464     ast_expression *on_false;
3465     ast_expression *cond;
3466
3467     if (!*side)
3468         return NULL;
3469
3470     if (ast_istype(*side, ast_ternary)) {
3471         ast_ternary *tern = (ast_ternary*)*side;
3472         on_true  = parse_goto_computed(parser, &tern->on_true);
3473         on_false = parse_goto_computed(parser, &tern->on_false);
3474
3475         if (!on_true || !on_false) {
3476             parseerror(parser, "expected label or expression in ternary");
3477             if (on_true) ast_unref(on_true);
3478             if (on_false) ast_unref(on_false);
3479             return NULL;
3480         }
3481
3482         cond = tern->cond;
3483         tern->cond = NULL;
3484         ast_delete(tern);
3485         *side = NULL;
3486         return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3487     } else if (ast_istype(*side, ast_label)) {
3488         ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3489         ast_goto_set_label(gt, ((ast_label*)*side));
3490         *side = NULL;
3491         return (ast_expression*)gt;
3492     }
3493     return NULL;
3494 }
3495
3496 static bool parse_goto(parser_t *parser, ast_expression **out)
3497 {
3498     ast_goto       *gt = NULL;
3499     ast_expression *lbl;
3500
3501     if (!parser_next(parser))
3502         return false;
3503
3504     if (parser->tok != TOKEN_IDENT) {
3505         ast_expression *expression;
3506
3507         /* could be an expression i.e computed goto :-) */
3508         if (parser->tok != '(') {
3509             parseerror(parser, "expected label name after `goto`");
3510             return false;
3511         }
3512
3513         /* failed to parse expression for goto */
3514         if (!(expression = parse_expression(parser, false, true)) ||
3515             !(*out = parse_goto_computed(parser, &expression))) {
3516             parseerror(parser, "invalid goto expression");
3517             ast_unref(expression);
3518             return false;
3519         }
3520
3521         return true;
3522     }
3523
3524     /* not computed goto */
3525     gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3526     lbl = parser_find_label(parser, gt->name);
3527     if (lbl) {
3528         if (!ast_istype(lbl, ast_label)) {
3529             parseerror(parser, "internal error: label is not an ast_label");
3530             ast_delete(gt);
3531             return false;
3532         }
3533         ast_goto_set_label(gt, (ast_label*)lbl);
3534     }
3535     else
3536         vec_push(parser->gotos, gt);
3537
3538     if (!parser_next(parser) || parser->tok != ';') {
3539         parseerror(parser, "semicolon expected after goto label");
3540         return false;
3541     }
3542     if (!parser_next(parser)) {
3543         parseerror(parser, "parse error after goto");
3544         return false;
3545     }
3546
3547     *out = (ast_expression*)gt;
3548     return true;
3549 }
3550
3551 static bool parse_skipwhite(parser_t *parser)
3552 {
3553     do {
3554         if (!parser_next(parser))
3555             return false;
3556     } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3557     return parser->tok < TOKEN_ERROR;
3558 }
3559
3560 static bool parse_eol(parser_t *parser)
3561 {
3562     if (!parse_skipwhite(parser))
3563         return false;
3564     return parser->tok == TOKEN_EOL;
3565 }
3566
3567 static bool parse_pragma_do(parser_t *parser)
3568 {
3569     if (!parser_next(parser) ||
3570         parser->tok != TOKEN_IDENT ||
3571         strcmp(parser_tokval(parser), "pragma"))
3572     {
3573         parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3574         return false;
3575     }
3576     if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3577         parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3578         return false;
3579     }
3580
3581     if (!strcmp(parser_tokval(parser), "noref")) {
3582         if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3583             parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3584             return false;
3585         }
3586         parser->noref = !!parser_token(parser)->constval.i;
3587         if (!parse_eol(parser)) {
3588             parseerror(parser, "parse error after `noref` pragma");
3589             return false;
3590         }
3591     }
3592     else
3593     {
3594         (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3595         return false;
3596     }
3597
3598     return true;
3599 }
3600
3601 static bool parse_pragma(parser_t *parser)
3602 {
3603     bool rv;
3604     parser->lex->flags.preprocessing = true;
3605     parser->lex->flags.mergelines = true;
3606     rv = parse_pragma_do(parser);
3607     if (parser->tok != TOKEN_EOL) {
3608         parseerror(parser, "junk after pragma");
3609         rv = false;
3610     }
3611     parser->lex->flags.preprocessing = false;
3612     parser->lex->flags.mergelines = false;
3613     if (!parser_next(parser)) {
3614         parseerror(parser, "parse error after pragma");
3615         rv = false;
3616     }
3617     return rv;
3618 }
3619
3620 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3621 {
3622     bool       noref, is_static;
3623     int        cvq     = CV_NONE;
3624     uint32_t   qflags  = 0;
3625     ast_value *typevar = NULL;
3626     char      *vstring = NULL;
3627
3628     *out = NULL;
3629
3630     if (parser->tok == TOKEN_IDENT)
3631         typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3632
3633     if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3634     {
3635         /* local variable */
3636         if (!block) {
3637             parseerror(parser, "cannot declare a variable from here");
3638             return false;
3639         }
3640         if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3641             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3642                 return false;
3643         }
3644         if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3645             return false;
3646         return true;
3647     }
3648     else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3649     {
3650         if (cvq == CV_WRONG)
3651             return false;
3652         return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3653     }
3654     else if (parser->tok == TOKEN_KEYWORD)
3655     {
3656         if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3657         {
3658             char ty[1024];
3659             ast_value *tdef;
3660
3661             if (!parser_next(parser)) {
3662                 parseerror(parser, "parse error after __builtin_debug_printtype");
3663                 return false;
3664             }
3665
3666             if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3667             {
3668                 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3669                 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3670                 if (!parser_next(parser)) {
3671                     parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3672                     return false;
3673                 }
3674             }
3675             else
3676             {
3677                 if (!parse_statement(parser, block, out, allow_cases))
3678                     return false;
3679                 if (!*out)
3680                     con_out("__builtin_debug_printtype: got no output node\n");
3681                 else
3682                 {
3683                     ast_type_to_string(*out, ty, sizeof(ty));
3684                     con_out("__builtin_debug_printtype: `%s`\n", ty);
3685                 }
3686             }
3687             return true;
3688         }
3689         else if (!strcmp(parser_tokval(parser), "return"))
3690         {
3691             return parse_return(parser, block, out);
3692         }
3693         else if (!strcmp(parser_tokval(parser), "if"))
3694         {
3695             return parse_if(parser, block, out);
3696         }
3697         else if (!strcmp(parser_tokval(parser), "while"))
3698         {
3699             return parse_while(parser, block, out);
3700         }
3701         else if (!strcmp(parser_tokval(parser), "do"))
3702         {
3703             return parse_dowhile(parser, block, out);
3704         }
3705         else if (!strcmp(parser_tokval(parser), "for"))
3706         {
3707             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3708                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3709                     return false;
3710             }
3711             return parse_for(parser, block, out);
3712         }
3713         else if (!strcmp(parser_tokval(parser), "break"))
3714         {
3715             return parse_break_continue(parser, block, out, false);
3716         }
3717         else if (!strcmp(parser_tokval(parser), "continue"))
3718         {
3719             return parse_break_continue(parser, block, out, true);
3720         }
3721         else if (!strcmp(parser_tokval(parser), "switch"))
3722         {
3723             return parse_switch(parser, block, out);
3724         }
3725         else if (!strcmp(parser_tokval(parser), "case") ||
3726                  !strcmp(parser_tokval(parser), "default"))
3727         {
3728             if (!allow_cases) {
3729                 parseerror(parser, "unexpected 'case' label");
3730                 return false;
3731             }
3732             return true;
3733         }
3734         else if (!strcmp(parser_tokval(parser), "goto"))
3735         {
3736             return parse_goto(parser, out);
3737         }
3738         else if (!strcmp(parser_tokval(parser), "typedef"))
3739         {
3740             if (!parser_next(parser)) {
3741                 parseerror(parser, "expected type definition after 'typedef'");
3742                 return false;
3743             }
3744             return parse_typedef(parser);
3745         }
3746         parseerror(parser, "Unexpected keyword");
3747         return false;
3748     }
3749     else if (parser->tok == '{')
3750     {
3751         ast_block *inner;
3752         inner = parse_block(parser);
3753         if (!inner)
3754             return false;
3755         *out = (ast_expression*)inner;
3756         return true;
3757     }
3758     else if (parser->tok == ':')
3759     {
3760         size_t i;
3761         ast_label *label;
3762         if (!parser_next(parser)) {
3763             parseerror(parser, "expected label name");
3764             return false;
3765         }
3766         if (parser->tok != TOKEN_IDENT) {
3767             parseerror(parser, "label must be an identifier");
3768             return false;
3769         }
3770         label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3771         if (label) {
3772             if (!label->undefined) {
3773                 parseerror(parser, "label `%s` already defined", label->name);
3774                 return false;
3775             }
3776             label->undefined = false;
3777         }
3778         else {
3779             label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3780             vec_push(parser->labels, label);
3781         }
3782         *out = (ast_expression*)label;
3783         if (!parser_next(parser)) {
3784             parseerror(parser, "parse error after label");
3785             return false;
3786         }
3787         for (i = 0; i < vec_size(parser->gotos); ++i) {
3788             if (!strcmp(parser->gotos[i]->name, label->name)) {
3789                 ast_goto_set_label(parser->gotos[i], label);
3790                 vec_remove(parser->gotos, i, 1);
3791                 --i;
3792             }
3793         }
3794         return true;
3795     }
3796     else if (parser->tok == ';')
3797     {
3798         if (!parser_next(parser)) {
3799             parseerror(parser, "parse error after empty statement");
3800             return false;
3801         }
3802         return true;
3803     }
3804     else
3805     {
3806         lex_ctx ctx = parser_ctx(parser);
3807         ast_expression *exp = parse_expression(parser, false, false);
3808         if (!exp)
3809             return false;
3810         *out = exp;
3811         if (!ast_side_effects(exp)) {
3812             if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3813                 return false;
3814         }
3815         return true;
3816     }
3817 }
3818
3819 static bool parse_enum(parser_t *parser)
3820 {
3821     qcfloat     num = 0;
3822     ast_value **values = NULL;
3823     ast_value  *var = NULL;
3824     ast_value  *asvalue;
3825
3826     ast_expression *old;
3827
3828     if (!parser_next(parser) || parser->tok != '{') {
3829         parseerror(parser, "expected `{` after `enum` keyword");
3830         return false;
3831     }
3832
3833     while (true) {
3834         if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3835             if (parser->tok == '}') {
3836                 /* allow an empty enum */
3837                 break;
3838             }
3839             parseerror(parser, "expected identifier or `}`");
3840             goto onerror;
3841         }
3842
3843         old = parser_find_field(parser, parser_tokval(parser));
3844         if (!old)
3845             old = parser_find_global(parser, parser_tokval(parser));
3846         if (old) {
3847             parseerror(parser, "value `%s` has already been declared here: %s:%i",
3848                        parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3849             goto onerror;
3850         }
3851
3852         var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3853         vec_push(values, var);
3854         var->cvq             = CV_CONST;
3855         var->hasvalue        = true;
3856         var->constval.vfloat = num++;
3857
3858         parser_addglobal(parser, var->name, (ast_expression*)var);
3859
3860         if (!parser_next(parser)) {
3861             parseerror(parser, "expected `=`, `}` or comma after identifier");
3862             goto onerror;
3863         }
3864
3865         if (parser->tok == ',')
3866             continue;
3867         if (parser->tok == '}')
3868             break;
3869         if (parser->tok != '=') {
3870             parseerror(parser, "expected `=`, `}` or comma after identifier");
3871             goto onerror;
3872         }
3873
3874         if (!parser_next(parser)) {
3875             parseerror(parser, "expected expression after `=`");
3876             goto onerror;
3877         }
3878
3879         /* We got a value! */
3880         old = parse_expression_leave(parser, true, false, false);
3881         asvalue = (ast_value*)old;
3882         if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3883             compile_error(ast_ctx(var), "constant value or expression expected");
3884             goto onerror;
3885         }
3886         num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3887
3888         if (parser->tok == '}')
3889             break;
3890         if (parser->tok != ',') {
3891             parseerror(parser, "expected `}` or comma after expression");
3892             goto onerror;
3893         }
3894     }
3895
3896     if (parser->tok != '}') {
3897         parseerror(parser, "internal error: breaking without `}`");
3898         goto onerror;
3899     }
3900
3901     if (!parser_next(parser) || parser->tok != ';') {
3902         parseerror(parser, "expected semicolon after enumeration");
3903         goto onerror;
3904     }
3905
3906     if (!parser_next(parser)) {
3907         parseerror(parser, "parse error after enumeration");
3908         goto onerror;
3909     }
3910
3911     vec_free(values);
3912     return true;
3913
3914 onerror:
3915     vec_free(values);
3916     return false;
3917 }
3918
3919 static bool parse_block_into(parser_t *parser, ast_block *block)
3920 {
3921     bool   retval = true;
3922
3923     parser_enterblock(parser);
3924
3925     if (!parser_next(parser)) { /* skip the '{' */
3926         parseerror(parser, "expected function body");
3927         goto cleanup;
3928     }
3929
3930     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3931     {
3932         ast_expression *expr = NULL;
3933         if (parser->tok == '}')
3934             break;
3935
3936         if (!parse_statement(parser, block, &expr, false)) {
3937             /* parseerror(parser, "parse error"); */
3938             block = NULL;
3939             goto cleanup;
3940         }
3941         if (!expr)
3942             continue;
3943         if (!ast_block_add_expr(block, expr)) {
3944             ast_delete(block);
3945             block = NULL;
3946             goto cleanup;
3947         }
3948     }
3949
3950     if (parser->tok != '}') {
3951         block = NULL;
3952     } else {
3953         (void)parser_next(parser);
3954     }
3955
3956 cleanup:
3957     if (!parser_leaveblock(parser))
3958         retval = false;
3959     return retval && !!block;
3960 }
3961
3962 static ast_block* parse_block(parser_t *parser)
3963 {
3964     ast_block *block;
3965     block = ast_block_new(parser_ctx(parser));
3966     if (!block)
3967         return NULL;
3968     if (!parse_block_into(parser, block)) {
3969         ast_block_delete(block);
3970         return NULL;
3971     }
3972     return block;
3973 }
3974
3975 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3976 {
3977     if (parser->tok == '{') {
3978         *out = (ast_expression*)parse_block(parser);
3979         return !!*out;
3980     }
3981     return parse_statement(parser, NULL, out, false);
3982 }
3983
3984 static bool create_vector_members(ast_value *var, ast_member **me)
3985 {
3986     size_t i;
3987     size_t len = strlen(var->name);
3988
3989     for (i = 0; i < 3; ++i) {
3990         char *name = (char*)mem_a(len+3);
3991         memcpy(name, var->name, len);
3992         name[len+0] = '_';
3993         name[len+1] = 'x'+i;
3994         name[len+2] = 0;
3995         me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3996         mem_d(name);
3997         if (!me[i])
3998             break;
3999     }
4000     if (i == 3)
4001         return true;
4002
4003     /* unroll */
4004     do { ast_member_delete(me[--i]); } while(i);
4005     return false;
4006 }
4007
4008 static bool parse_function_body(parser_t *parser, ast_value *var)
4009 {
4010     ast_block      *block = NULL;
4011     ast_function   *func;
4012     ast_function   *old;
4013     size_t          parami;
4014
4015     ast_expression *framenum  = NULL;
4016     ast_expression *nextthink = NULL;
4017     /* None of the following have to be deleted */
4018     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4019     ast_expression *gbl_time = NULL, *gbl_self = NULL;
4020     bool            has_frame_think;
4021
4022     bool retval = true;
4023
4024     has_frame_think = false;
4025     old = parser->function;
4026
4027     if (var->expression.flags & AST_FLAG_ALIAS) {
4028         parseerror(parser, "function aliases cannot have bodies");
4029         return false;
4030     }
4031
4032     if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4033         parseerror(parser, "gotos/labels leaking");
4034         return false;
4035     }
4036
4037     if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4038         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4039                          "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4040         {
4041             return false;
4042         }
4043     }
4044
4045     if (parser->tok == '[') {
4046         /* got a frame definition: [ framenum, nextthink ]
4047          * this translates to:
4048          * self.frame = framenum;
4049          * self.nextthink = time + 0.1;
4050          * self.think = nextthink;
4051          */
4052         nextthink = NULL;
4053
4054         fld_think     = parser_find_field(parser, "think");
4055         fld_nextthink = parser_find_field(parser, "nextthink");
4056         fld_frame     = parser_find_field(parser, "frame");
4057         if (!fld_think || !fld_nextthink || !fld_frame) {
4058             parseerror(parser, "cannot use [frame,think] notation without the required fields");
4059             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4060             return false;
4061         }
4062         gbl_time      = parser_find_global(parser, "time");
4063         gbl_self      = parser_find_global(parser, "self");
4064         if (!gbl_time || !gbl_self) {
4065             parseerror(parser, "cannot use [frame,think] notation without the required globals");
4066             parseerror(parser, "please declare the following globals: `time`, `self`");
4067             return false;
4068         }
4069
4070         if (!parser_next(parser))
4071             return false;
4072
4073         framenum = parse_expression_leave(parser, true, false, false);
4074         if (!framenum) {
4075             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4076             return false;
4077         }
4078         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4079             ast_unref(framenum);
4080             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4081             return false;
4082         }
4083
4084         if (parser->tok != ',') {
4085             ast_unref(framenum);
4086             parseerror(parser, "expected comma after frame number in [frame,think] notation");
4087             parseerror(parser, "Got a %i\n", parser->tok);
4088             return false;
4089         }
4090
4091         if (!parser_next(parser)) {
4092             ast_unref(framenum);
4093             return false;
4094         }
4095
4096         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4097         {
4098             /* qc allows the use of not-yet-declared functions here
4099              * - this automatically creates a prototype */
4100             ast_value      *thinkfunc;
4101             ast_expression *functype = fld_think->expression.next;
4102
4103             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4104             if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4105                 ast_unref(framenum);
4106                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4107                 return false;
4108             }
4109             ast_type_adopt(thinkfunc, functype);
4110
4111             if (!parser_next(parser)) {
4112                 ast_unref(framenum);
4113                 ast_delete(thinkfunc);
4114                 return false;
4115             }
4116
4117             parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4118
4119             nextthink = (ast_expression*)thinkfunc;
4120
4121         } else {
4122             nextthink = parse_expression_leave(parser, true, false, false);
4123             if (!nextthink) {
4124                 ast_unref(framenum);
4125                 parseerror(parser, "expected a think-function in [frame,think] notation");
4126                 return false;
4127             }
4128         }
4129
4130         if (!ast_istype(nextthink, ast_value)) {
4131             parseerror(parser, "think-function in [frame,think] notation must be a constant");
4132             retval = false;
4133         }
4134
4135         if (retval && parser->tok != ']') {
4136             parseerror(parser, "expected closing `]` for [frame,think] notation");
4137             retval = false;
4138         }
4139
4140         if (retval && !parser_next(parser)) {
4141             retval = false;
4142         }
4143
4144         if (retval && parser->tok != '{') {
4145             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4146             retval = false;
4147         }
4148
4149         if (!retval) {
4150             ast_unref(nextthink);
4151             ast_unref(framenum);
4152             return false;
4153         }
4154
4155         has_frame_think = true;
4156     }
4157
4158     block = ast_block_new(parser_ctx(parser));
4159     if (!block) {
4160         parseerror(parser, "failed to allocate block");
4161         if (has_frame_think) {
4162             ast_unref(nextthink);
4163             ast_unref(framenum);
4164         }
4165         return false;
4166     }
4167
4168     if (has_frame_think) {
4169         lex_ctx ctx;
4170         ast_expression *self_frame;
4171         ast_expression *self_nextthink;
4172         ast_expression *self_think;
4173         ast_expression *time_plus_1;
4174         ast_store *store_frame;
4175         ast_store *store_nextthink;
4176         ast_store *store_think;
4177
4178         ctx = parser_ctx(parser);
4179         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4180         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4181         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4182
4183         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4184                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4185
4186         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4187             if (self_frame)     ast_delete(self_frame);
4188             if (self_nextthink) ast_delete(self_nextthink);
4189             if (self_think)     ast_delete(self_think);
4190             if (time_plus_1)    ast_delete(time_plus_1);
4191             retval = false;
4192         }
4193
4194         if (retval)
4195         {
4196             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
4197             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
4198             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
4199
4200             if (!store_frame) {
4201                 ast_delete(self_frame);
4202                 retval = false;
4203             }
4204             if (!store_nextthink) {
4205                 ast_delete(self_nextthink);
4206                 retval = false;
4207             }
4208             if (!store_think) {
4209                 ast_delete(self_think);
4210                 retval = false;
4211             }
4212             if (!retval) {
4213                 if (store_frame)     ast_delete(store_frame);
4214                 if (store_nextthink) ast_delete(store_nextthink);
4215                 if (store_think)     ast_delete(store_think);
4216                 retval = false;
4217             }
4218             if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4219                 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4220                 !ast_block_add_expr(block, (ast_expression*)store_think))
4221             {
4222                 retval = false;
4223             }
4224         }
4225
4226         if (!retval) {
4227             parseerror(parser, "failed to generate code for [frame,think]");
4228             ast_unref(nextthink);
4229             ast_unref(framenum);
4230             ast_delete(block);
4231             return false;
4232         }
4233     }
4234
4235     if (var->hasvalue) {
4236         parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4237         ast_block_delete(block);
4238         goto enderr;
4239     }
4240
4241     func = ast_function_new(ast_ctx(var), var->name, var);
4242     if (!func) {
4243         parseerror(parser, "failed to allocate function for `%s`", var->name);
4244         ast_block_delete(block);
4245         goto enderr;
4246     }
4247     vec_push(parser->functions, func);
4248
4249     parser_enterblock(parser);
4250
4251     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4252         size_t     e;
4253         ast_value *param = var->expression.params[parami];
4254         ast_member *me[3];
4255
4256         if (param->expression.vtype != TYPE_VECTOR &&
4257             (param->expression.vtype != TYPE_FIELD ||
4258              param->expression.next->expression.vtype != TYPE_VECTOR))
4259         {
4260             continue;
4261         }
4262
4263         if (!create_vector_members(param, me)) {
4264             ast_block_delete(block);
4265             goto enderrfn;
4266         }
4267
4268         for (e = 0; e < 3; ++e) {
4269             parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4270             ast_block_collect(block, (ast_expression*)me[e]);
4271         }
4272     }
4273
4274     if (var->argcounter) {
4275         ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4276         parser_addlocal(parser, argc->name, (ast_expression*)argc);
4277         func->argc = argc;
4278     }
4279
4280     if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4281         char name[1024];
4282         ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4283         varargs->expression.flags |= AST_FLAG_IS_VARARG;
4284         varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4285         varargs->expression.count = 0;
4286         snprintf(name, sizeof(name), "%s##va##SET", var->name);
4287         if (!parser_create_array_setter_proto(parser, varargs, name)) {
4288             ast_delete(varargs);
4289             ast_block_delete(block);
4290             goto enderrfn;
4291         }
4292         snprintf(name, sizeof(name), "%s##va##GET", var->name);
4293         if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4294             ast_delete(varargs);
4295             ast_block_delete(block);
4296             goto enderrfn;
4297         }
4298         func->varargs = varargs;
4299
4300         func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4301     }
4302
4303     parser->function = func;
4304     if (!parse_block_into(parser, block)) {
4305         ast_block_delete(block);
4306         goto enderrfn;
4307     }
4308
4309     vec_push(func->blocks, block);
4310
4311     parser->function = old;
4312     if (!parser_leaveblock(parser))
4313         retval = false;
4314     if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4315         parseerror(parser, "internal error: local scopes left");
4316         retval = false;
4317     }
4318
4319     if (parser->tok == ';')
4320         return parser_next(parser);
4321     else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4322         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4323     return retval;
4324
4325 enderrfn:
4326     (void)!parser_leaveblock(parser);
4327     vec_pop(parser->functions);
4328     ast_function_delete(func);
4329     var->constval.vfunc = NULL;
4330
4331 enderr:
4332     parser->function = old;
4333     return false;
4334 }
4335
4336 static ast_expression *array_accessor_split(
4337     parser_t  *parser,
4338     ast_value *array,
4339     ast_value *index,
4340     size_t     middle,
4341     ast_expression *left,
4342     ast_expression *right
4343     )
4344 {
4345     ast_ifthen *ifthen;
4346     ast_binary *cmp;
4347
4348     lex_ctx ctx = ast_ctx(array);
4349
4350     if (!left || !right) {
4351         if (left)  ast_delete(left);
4352         if (right) ast_delete(right);
4353         return NULL;
4354     }
4355
4356     cmp = ast_binary_new(ctx, INSTR_LT,
4357                          (ast_expression*)index,
4358                          (ast_expression*)parser_const_float(parser, middle));
4359     if (!cmp) {
4360         ast_delete(left);
4361         ast_delete(right);
4362         parseerror(parser, "internal error: failed to create comparison for array setter");
4363         return NULL;
4364     }
4365
4366     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4367     if (!ifthen) {
4368         ast_delete(cmp); /* will delete left and right */
4369         parseerror(parser, "internal error: failed to create conditional jump for array setter");
4370         return NULL;
4371     }
4372
4373     return (ast_expression*)ifthen;
4374 }
4375
4376 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4377 {
4378     lex_ctx ctx = ast_ctx(array);
4379
4380     if (from+1 == afterend) {
4381         /* set this value */
4382         ast_block       *block;
4383         ast_return      *ret;
4384         ast_array_index *subscript;
4385         ast_store       *st;
4386         int assignop = type_store_instr[value->expression.vtype];
4387
4388         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4389             assignop = INSTR_STORE_V;
4390
4391         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4392         if (!subscript)
4393             return NULL;
4394
4395         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4396         if (!st) {
4397             ast_delete(subscript);
4398             return NULL;
4399         }
4400
4401         block = ast_block_new(ctx);
4402         if (!block) {
4403             ast_delete(st);
4404             return NULL;
4405         }
4406
4407         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4408             ast_delete(block);
4409             return NULL;
4410         }
4411
4412         ret = ast_return_new(ctx, NULL);
4413         if (!ret) {
4414             ast_delete(block);
4415             return NULL;
4416         }
4417
4418         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4419             ast_delete(block);
4420             return NULL;
4421         }
4422
4423         return (ast_expression*)block;
4424     } else {
4425         ast_expression *left, *right;
4426         size_t diff = afterend - from;
4427         size_t middle = from + diff/2;
4428         left  = array_setter_node(parser, array, index, value, from, middle);
4429         right = array_setter_node(parser, array, index, value, middle, afterend);
4430         return array_accessor_split(parser, array, index, middle, left, right);
4431     }
4432 }
4433
4434 static ast_expression *array_field_setter_node(
4435     parser_t  *parser,
4436     ast_value *array,
4437     ast_value *entity,
4438     ast_value *index,
4439     ast_value *value,
4440     size_t     from,
4441     size_t     afterend)
4442 {
4443     lex_ctx ctx = ast_ctx(array);
4444
4445     if (from+1 == afterend) {
4446         /* set this value */
4447         ast_block       *block;
4448         ast_return      *ret;
4449         ast_entfield    *entfield;
4450         ast_array_index *subscript;
4451         ast_store       *st;
4452         int assignop = type_storep_instr[value->expression.vtype];
4453
4454         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4455             assignop = INSTR_STOREP_V;
4456
4457         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4458         if (!subscript)
4459             return NULL;
4460
4461         subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4462         subscript->expression.vtype = TYPE_FIELD;
4463
4464         entfield = ast_entfield_new_force(ctx,
4465                                           (ast_expression*)entity,
4466                                           (ast_expression*)subscript,
4467                                           (ast_expression*)subscript);
4468         if (!entfield) {
4469             ast_delete(subscript);
4470             return NULL;
4471         }
4472
4473         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4474         if (!st) {
4475             ast_delete(entfield);
4476             return NULL;
4477         }
4478
4479         block = ast_block_new(ctx);
4480         if (!block) {
4481             ast_delete(st);
4482             return NULL;
4483         }
4484
4485         if (!ast_block_add_expr(block, (ast_expression*)st)) {
4486             ast_delete(block);
4487             return NULL;
4488         }
4489
4490         ret = ast_return_new(ctx, NULL);
4491         if (!ret) {
4492             ast_delete(block);
4493             return NULL;
4494         }
4495
4496         if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4497             ast_delete(block);
4498             return NULL;
4499         }
4500
4501         return (ast_expression*)block;
4502     } else {
4503         ast_expression *left, *right;
4504         size_t diff = afterend - from;
4505         size_t middle = from + diff/2;
4506         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
4507         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4508         return array_accessor_split(parser, array, index, middle, left, right);
4509     }
4510 }
4511
4512 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4513 {
4514     lex_ctx ctx = ast_ctx(array);
4515
4516     if (from+1 == afterend) {
4517         ast_return      *ret;
4518         ast_array_index *subscript;
4519
4520         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4521         if (!subscript)
4522             return NULL;
4523
4524         ret = ast_return_new(ctx, (ast_expression*)subscript);
4525         if (!ret) {
4526             ast_delete(subscript);
4527             return NULL;
4528         }
4529
4530         return (ast_expression*)ret;
4531     } else {
4532         ast_expression *left, *right;
4533         size_t diff = afterend - from;
4534         size_t middle = from + diff/2;
4535         left  = array_getter_node(parser, array, index, from, middle);
4536         right = array_getter_node(parser, array, index, middle, afterend);
4537         return array_accessor_split(parser, array, index, middle, left, right);
4538     }
4539 }
4540
4541 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4542 {
4543     ast_function   *func = NULL;
4544     ast_value      *fval = NULL;
4545     ast_block      *body = NULL;
4546
4547     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4548     if (!fval) {
4549         parseerror(parser, "failed to create accessor function value");
4550         return false;
4551     }
4552
4553     func = ast_function_new(ast_ctx(array), funcname, fval);
4554     if (!func) {
4555         ast_delete(fval);
4556         parseerror(parser, "failed to create accessor function node");
4557         return false;
4558     }
4559
4560     body = ast_block_new(ast_ctx(array));
4561     if (!body) {
4562         parseerror(parser, "failed to create block for array accessor");
4563         ast_delete(fval);
4564         ast_delete(func);
4565         return false;
4566     }
4567
4568     vec_push(func->blocks, body);
4569     *out = fval;
4570
4571     vec_push(parser->accessors, fval);
4572
4573     return true;
4574 }
4575
4576 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4577 {
4578     ast_value      *index = NULL;
4579     ast_value      *value = NULL;
4580     ast_function   *func;
4581     ast_value      *fval;
4582
4583     if (!ast_istype(array->expression.next, ast_value)) {
4584         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4585         return NULL;
4586     }
4587
4588     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4589         return NULL;
4590     func = fval->constval.vfunc;
4591     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4592
4593     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4594     value = ast_value_copy((ast_value*)array->expression.next);
4595
4596     if (!index || !value) {
4597         parseerror(parser, "failed to create locals for array accessor");
4598         goto cleanup;
4599     }
4600     (void)!ast_value_set_name(value, "value"); /* not important */
4601     vec_push(fval->expression.params, index);
4602     vec_push(fval->expression.params, value);
4603
4604     array->setter = fval;
4605     return fval;
4606 cleanup:
4607     if (index) ast_delete(index);
4608     if (value) ast_delete(value);
4609     ast_delete(func);
4610     ast_delete(fval);
4611     return NULL;
4612 }
4613
4614 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4615 {
4616     ast_expression *root = NULL;
4617     root = array_setter_node(parser, array,
4618                              array->setter->expression.params[0],
4619                              array->setter->expression.params[1],
4620                              0, array->expression.count);
4621     if (!root) {
4622         parseerror(parser, "failed to build accessor search tree");
4623         return false;
4624     }
4625     if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4626         ast_delete(root);
4627         return false;
4628     }
4629     return true;
4630 }
4631
4632 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4633 {
4634     if (!parser_create_array_setter_proto(parser, array, funcname))
4635         return false;
4636     return parser_create_array_setter_impl(parser, array);
4637 }
4638
4639 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4640 {
4641     ast_expression *root = NULL;
4642     ast_value      *entity = NULL;
4643     ast_value      *index = NULL;
4644     ast_value      *value = NULL;
4645     ast_function   *func;
4646     ast_value      *fval;
4647
4648     if (!ast_istype(array->expression.next, ast_value)) {
4649         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4650         return false;
4651     }
4652
4653     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4654         return false;
4655     func = fval->constval.vfunc;
4656     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4657
4658     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4659     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
4660     value  = ast_value_copy((ast_value*)array->expression.next);
4661     if (!entity || !index || !value) {
4662         parseerror(parser, "failed to create locals for array accessor");
4663         goto cleanup;
4664     }
4665     (void)!ast_value_set_name(value, "value"); /* not important */
4666     vec_push(fval->expression.params, entity);
4667     vec_push(fval->expression.params, index);
4668     vec_push(fval->expression.params, value);
4669
4670     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4671     if (!root) {
4672         parseerror(parser, "failed to build accessor search tree");
4673         goto cleanup;
4674     }
4675
4676     array->setter = fval;
4677     return ast_block_add_expr(func->blocks[0], root);
4678 cleanup:
4679     if (entity) ast_delete(entity);
4680     if (index)  ast_delete(index);
4681     if (value)  ast_delete(value);
4682     if (root)   ast_delete(root);
4683     ast_delete(func);
4684     ast_delete(fval);
4685     return false;
4686 }
4687
4688 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4689 {
4690     ast_value      *index = NULL;
4691     ast_value      *fval;
4692     ast_function   *func;
4693
4694     /* NOTE: checking array->expression.next rather than elemtype since
4695      * for fields elemtype is a temporary fieldtype.
4696      */
4697     if (!ast_istype(array->expression.next, ast_value)) {
4698         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4699         return NULL;
4700     }
4701
4702     if (!parser_create_array_accessor(parser, array, funcname, &fval))
4703         return NULL;
4704     func = fval->constval.vfunc;
4705     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4706
4707     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4708
4709     if (!index) {
4710         parseerror(parser, "failed to create locals for array accessor");
4711         goto cleanup;
4712     }
4713     vec_push(fval->expression.params, index);
4714
4715     array->getter = fval;
4716     return fval;
4717 cleanup:
4718     if (index) ast_delete(index);
4719     ast_delete(func);
4720     ast_delete(fval);
4721     return NULL;
4722 }
4723
4724 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4725 {
4726     ast_expression *root = NULL;
4727
4728     root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4729     if (!root) {
4730         parseerror(parser, "failed to build accessor search tree");
4731         return false;
4732     }
4733     if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4734         ast_delete(root);
4735         return false;
4736     }
4737     return true;
4738 }
4739
4740 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4741 {
4742     if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4743         return false;
4744     return parser_create_array_getter_impl(parser, array);
4745 }
4746
4747 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4748 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4749 {
4750     lex_ctx     ctx;
4751     size_t      i;
4752     ast_value **params;
4753     ast_value  *param;
4754     ast_value  *fval;
4755     bool        first = true;
4756     bool        variadic = false;
4757     ast_value  *varparam = NULL;
4758     char       *argcounter = NULL;
4759
4760     ctx = parser_ctx(parser);
4761
4762     /* for the sake of less code we parse-in in this function */
4763     if (!parser_next(parser)) {
4764         parseerror(parser, "expected parameter list");
4765         return NULL;
4766     }
4767
4768     params = NULL;
4769
4770     /* parse variables until we hit a closing paren */
4771     while (parser->tok != ')') {
4772         if (!first) {
4773             /* there must be commas between them */
4774             if (parser->tok != ',') {
4775                 parseerror(parser, "expected comma or end of parameter list");
4776                 goto on_error;
4777             }
4778             if (!parser_next(parser)) {
4779                 parseerror(parser, "expected parameter");
4780                 goto on_error;
4781             }
4782         }
4783         first = false;
4784
4785         if (parser->tok == TOKEN_DOTS) {
4786             /* '...' indicates a varargs function */
4787             variadic = true;
4788             if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4789                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4790                 goto on_error;
4791             }
4792             if (parser->tok == TOKEN_IDENT) {
4793                 argcounter = util_strdup(parser_tokval(parser));
4794                 if (!parser_next(parser) || parser->tok != ')') {
4795                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4796                     goto on_error;
4797                 }
4798             }
4799         }
4800         else
4801         {
4802             /* for anything else just parse a typename */
4803             param = parse_typename(parser, NULL, NULL);
4804             if (!param)
4805                 goto on_error;
4806             vec_push(params, param);
4807             if (param->expression.vtype >= TYPE_VARIANT) {
4808                 char tname[1024]; /* typename is reserved in C++ */
4809                 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4810                 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4811                 goto on_error;
4812             }
4813             /* type-restricted varargs */
4814             if (parser->tok == TOKEN_DOTS) {
4815                 variadic = true;
4816                 varparam = vec_last(params);
4817                 vec_pop(params);
4818                 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4819                     parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4820                     goto on_error;
4821                 }
4822                 if (parser->tok == TOKEN_IDENT) {
4823                     argcounter = util_strdup(parser_tokval(parser));
4824                     if (!parser_next(parser) || parser->tok != ')') {
4825                         parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4826                         goto on_error;
4827                     }
4828                 }
4829             }
4830         }
4831     }
4832
4833     if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4834         vec_free(params);
4835
4836     /* sanity check */
4837     if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4838         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4839
4840     /* parse-out */
4841     if (!parser_next(parser)) {
4842         parseerror(parser, "parse error after typename");
4843         goto on_error;
4844     }
4845
4846     /* now turn 'var' into a function type */
4847     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4848     fval->expression.next     = (ast_expression*)var;
4849     if (variadic)
4850         fval->expression.flags |= AST_FLAG_VARIADIC;
4851     var = fval;
4852
4853     var->expression.params   = params;
4854     var->expression.varparam = (ast_expression*)varparam;
4855     var->argcounter          = argcounter;
4856     params = NULL;
4857
4858     return var;
4859
4860 on_error:
4861     if (argcounter)
4862         mem_d(argcounter);
4863     ast_delete(var);
4864     for (i = 0; i < vec_size(params); ++i)
4865         ast_delete(params[i]);
4866     vec_free(params);
4867     return NULL;
4868 }
4869
4870 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4871 {
4872     ast_expression *cexp;
4873     ast_value      *cval, *tmp;
4874     lex_ctx ctx;
4875
4876     ctx = parser_ctx(parser);
4877
4878     if (!parser_next(parser)) {
4879         ast_delete(var);
4880         parseerror(parser, "expected array-size");
4881         return NULL;
4882     }
4883
4884     cexp = parse_expression_leave(parser, true, false, false);
4885
4886     if (!cexp || !ast_istype(cexp, ast_value)) {
4887         if (cexp)
4888             ast_unref(cexp);
4889         ast_delete(var);
4890         parseerror(parser, "expected array-size as constant positive integer");
4891         return NULL;
4892     }
4893     cval = (ast_value*)cexp;
4894
4895     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4896     tmp->expression.next = (ast_expression*)var;
4897     var = tmp;
4898
4899     if (cval->expression.vtype == TYPE_INTEGER)
4900         tmp->expression.count = cval->constval.vint;
4901     else if (cval->expression.vtype == TYPE_FLOAT)
4902         tmp->expression.count = cval->constval.vfloat;
4903     else {
4904         ast_unref(cexp);
4905         ast_delete(var);
4906         parseerror(parser, "array-size must be a positive integer constant");
4907         return NULL;
4908     }
4909     ast_unref(cexp);
4910
4911     if (parser->tok != ']') {
4912         ast_delete(var);
4913         parseerror(parser, "expected ']' after array-size");
4914         return NULL;
4915     }
4916     if (!parser_next(parser)) {
4917         ast_delete(var);
4918         parseerror(parser, "error after parsing array size");
4919         return NULL;
4920     }
4921     return var;
4922 }
4923
4924 /* Parse a complete typename.
4925  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4926  * but when parsing variables separated by comma
4927  * 'storebase' should point to where the base-type should be kept.
4928  * The base type makes up every bit of type information which comes *before* the
4929  * variable name.
4930  *
4931  * The following will be parsed in its entirety:
4932  *     void() foo()
4933  * The 'basetype' in this case is 'void()'
4934  * and if there's a comma after it, say:
4935  *     void() foo(), bar
4936  * then the type-information 'void()' can be stored in 'storebase'
4937  */
4938 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4939 {
4940     ast_value *var, *tmp;
4941     lex_ctx    ctx;
4942
4943     const char *name = NULL;
4944     bool        isfield  = false;
4945     bool        wasarray = false;
4946     size_t      morefields = 0;
4947
4948     ctx = parser_ctx(parser);
4949
4950     /* types may start with a dot */
4951     if (parser->tok == '.') {
4952         isfield = true;
4953         /* if we parsed a dot we need a typename now */
4954         if (!parser_next(parser)) {
4955             parseerror(parser, "expected typename for field definition");
4956             return NULL;
4957         }
4958
4959         /* Further dots are handled seperately because they won't be part of the
4960          * basetype
4961          */
4962         while (parser->tok == '.') {
4963             ++morefields;
4964             if (!parser_next(parser)) {
4965                 parseerror(parser, "expected typename for field definition");
4966                 return NULL;
4967             }
4968         }
4969     }
4970     if (parser->tok == TOKEN_IDENT)
4971         cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4972     if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4973         parseerror(parser, "expected typename");
4974         return NULL;
4975     }
4976
4977     /* generate the basic type value */
4978     if (cached_typedef) {
4979         var = ast_value_copy(cached_typedef);
4980         ast_value_set_name(var, "<type(from_def)>");
4981     } else
4982         var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4983
4984     for (; morefields; --morefields) {
4985         tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4986         tmp->expression.next = (ast_expression*)var;
4987         var = tmp;
4988     }
4989
4990     /* do not yet turn into a field - remember:
4991      * .void() foo; is a field too
4992      * .void()() foo; is a function
4993      */
4994
4995     /* parse on */
4996     if (!parser_next(parser)) {
4997         ast_delete(var);
4998         parseerror(parser, "parse error after typename");
4999         return NULL;
5000     }
5001
5002     /* an opening paren now starts the parameter-list of a function
5003      * this is where original-QC has parameter lists.
5004      * We allow a single parameter list here.
5005      * Much like fteqcc we don't allow `float()() x`
5006      */
5007     if (parser->tok == '(') {
5008         var = parse_parameter_list(parser, var);
5009         if (!var)
5010             return NULL;
5011     }
5012
5013     /* store the base if requested */
5014     if (storebase) {
5015         *storebase = ast_value_copy(var);
5016         if (isfield) {
5017             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5018             tmp->expression.next = (ast_expression*)*storebase;
5019             *storebase = tmp;
5020         }
5021     }
5022
5023     /* there may be a name now */
5024     if (parser->tok == TOKEN_IDENT) {
5025         name = util_strdup(parser_tokval(parser));
5026         /* parse on */
5027         if (!parser_next(parser)) {
5028             ast_delete(var);
5029             parseerror(parser, "error after variable or field declaration");
5030             return NULL;
5031         }
5032     }
5033
5034     /* now this may be an array */
5035     if (parser->tok == '[') {
5036         wasarray = true;
5037         var = parse_arraysize(parser, var);
5038         if (!var)
5039             return NULL;
5040     }
5041
5042     /* This is the point where we can turn it into a field */
5043     if (isfield) {
5044         /* turn it into a field if desired */
5045         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5046         tmp->expression.next = (ast_expression*)var;
5047         var = tmp;
5048     }
5049
5050     /* now there may be function parens again */
5051     if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5052         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5053     if (parser->tok == '(' && wasarray)
5054         parseerror(parser, "arrays as part of a return type is not supported");
5055     while (parser->tok == '(') {
5056         var = parse_parameter_list(parser, var);
5057         if (!var) {
5058             if (name)
5059                 mem_d((void*)name);
5060             return NULL;
5061         }
5062     }
5063
5064     /* finally name it */
5065     if (name) {
5066         if (!ast_value_set_name(var, name)) {
5067             ast_delete(var);
5068             parseerror(parser, "internal error: failed to set name");
5069             return NULL;
5070         }
5071         /* free the name, ast_value_set_name duplicates */
5072         mem_d((void*)name);
5073     }
5074
5075     return var;
5076 }
5077
5078 static bool parse_typedef(parser_t *parser)
5079 {
5080     ast_value      *typevar, *oldtype;
5081     ast_expression *old;
5082
5083     typevar = parse_typename(parser, NULL, NULL);
5084
5085     if (!typevar)
5086         return false;
5087
5088     if ( (old = parser_find_var(parser, typevar->name)) ) {
5089         parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5090                    " -> `%s` has been declared here: %s:%i",
5091                    typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5092         ast_delete(typevar);
5093         return false;
5094     }
5095
5096     if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5097         parseerror(parser, "type `%s` has already been declared here: %s:%i",
5098                    typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5099         ast_delete(typevar);
5100         return false;
5101     }
5102
5103     vec_push(parser->_typedefs, typevar);
5104     util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5105
5106     if (parser->tok != ';') {
5107         parseerror(parser, "expected semicolon after typedef");
5108         return false;
5109     }
5110     if (!parser_next(parser)) {
5111         parseerror(parser, "parse error after typedef");
5112         return false;
5113     }
5114
5115     return true;
5116 }
5117
5118 static const char *cvq_to_str(int cvq) {
5119     switch (cvq) {
5120         case CV_NONE:  return "none";
5121         case CV_VAR:   return "`var`";
5122         case CV_CONST: return "`const`";
5123         default:       return "<INVALID>";
5124     }
5125 }
5126
5127 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5128 {
5129     bool av, ao;
5130     if (proto->cvq != var->cvq) {
5131         if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5132               !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5133               parser->tok == '='))
5134         {
5135             return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5136                                  "`%s` declared with different qualifiers: %s\n"
5137                                  " -> previous declaration here: %s:%i uses %s",
5138                                  var->name, cvq_to_str(var->cvq),
5139                                  ast_ctx(proto).file, ast_ctx(proto).line,
5140                                  cvq_to_str(proto->cvq));
5141         }
5142     }
5143     av = (var  ->expression.flags & AST_FLAG_NORETURN);
5144     ao = (proto->expression.flags & AST_FLAG_NORETURN);
5145     if (!av != !ao) {
5146         return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5147                              "`%s` declared with different attributes%s\n"
5148                              " -> previous declaration here: %s:%i",
5149                              var->name, (av ? ": noreturn" : ""),
5150                              ast_ctx(proto).file, ast_ctx(proto).line,
5151                              (ao ? ": noreturn" : ""));
5152     }
5153     return true;
5154 }
5155
5156 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)
5157 {
5158     ast_value *var;
5159     ast_value *proto;
5160     ast_expression *old;
5161     bool       was_end;
5162     size_t     i;
5163
5164     ast_value *basetype = NULL;
5165     bool      retval    = true;
5166     bool      isparam   = false;
5167     bool      isvector  = false;
5168     bool      cleanvar  = true;
5169     bool      wasarray  = false;
5170
5171     ast_member *me[3];
5172
5173     if (!localblock && is_static)
5174         parseerror(parser, "`static` qualifier is not supported in global scope");
5175
5176     /* get the first complete variable */
5177     var = parse_typename(parser, &basetype, cached_typedef);
5178     if (!var) {
5179         if (basetype)
5180             ast_delete(basetype);
5181         return false;
5182     }
5183
5184     while (true) {
5185         proto = NULL;
5186         wasarray = false;
5187
5188         /* Part 0: finish the type */
5189         if (parser->tok == '(') {
5190             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5191                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5192             var = parse_parameter_list(parser, var);
5193             if (!var) {
5194                 retval = false;
5195                 goto cleanup;
5196             }
5197         }
5198         /* we only allow 1-dimensional arrays */
5199         if (parser->tok == '[') {
5200             wasarray = true;
5201             var = parse_arraysize(parser, var);
5202             if (!var) {
5203                 retval = false;
5204                 goto cleanup;
5205             }
5206         }
5207         if (parser->tok == '(' && wasarray) {
5208             parseerror(parser, "arrays as part of a return type is not supported");
5209             /* we'll still parse the type completely for now */
5210         }
5211         /* for functions returning functions */
5212         while (parser->tok == '(') {
5213             if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5214                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5215             var = parse_parameter_list(parser, var);
5216             if (!var) {
5217                 retval = false;
5218                 goto cleanup;
5219             }
5220         }
5221
5222         var->cvq = qualifier;
5223         var->expression.flags |= qflags;
5224
5225         /*
5226          * store the vstring back to var for alias and
5227          * deprecation messages.
5228          */   
5229         if (var->expression.flags & AST_FLAG_DEPRECATED ||
5230             var->expression.flags & AST_FLAG_ALIAS)
5231             var->desc = vstring;
5232
5233         /* Part 1:
5234          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5235          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5236          * is then filled with the previous definition and the parameter-names replaced.
5237          */
5238         if (!strcmp(var->name, "nil")) {
5239             if (OPTS_FLAG(UNTYPED_NIL)) {
5240                 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5241                     parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5242             } else
5243                 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5244         }
5245         if (!localblock) {
5246             /* Deal with end_sys_ vars */
5247             was_end = false;
5248             if (!strcmp(var->name, "end_sys_globals")) {
5249                 var->uses++;
5250                 parser->crc_globals = vec_size(parser->globals);
5251                 was_end = true;
5252             }
5253             else if (!strcmp(var->name, "end_sys_fields")) {
5254                 var->uses++;
5255                 parser->crc_fields = vec_size(parser->fields);
5256                 was_end = true;
5257             }
5258             if (was_end && var->expression.vtype == TYPE_FIELD) {
5259                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5260                                  "global '%s' hint should not be a field",
5261                                  parser_tokval(parser)))
5262                 {
5263                     retval = false;
5264                     goto cleanup;
5265                 }
5266             }
5267
5268             if (!nofields && var->expression.vtype == TYPE_FIELD)
5269             {
5270                 /* deal with field declarations */
5271                 old = parser_find_field(parser, var->name);
5272                 if (old) {
5273                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5274                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5275                     {
5276                         retval = false;
5277                         goto cleanup;
5278                     }
5279                     ast_delete(var);
5280                     var = NULL;
5281                     goto skipvar;
5282                     /*
5283                     parseerror(parser, "field `%s` already declared here: %s:%i",
5284                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5285                     retval = false;
5286                     goto cleanup;
5287                     */
5288                 }
5289                 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5290                     (old = parser_find_global(parser, var->name)))
5291                 {
5292                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5293                     parseerror(parser, "field `%s` already declared here: %s:%i",
5294                                var->name, ast_ctx(old).file, ast_ctx(old).line);
5295                     retval = false;
5296                     goto cleanup;
5297                 }
5298             }
5299             else
5300             {
5301                 /* deal with other globals */
5302                 old = parser_find_global(parser, var->name);
5303                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5304                 {
5305                     /* This is a function which had a prototype */
5306                     if (!ast_istype(old, ast_value)) {
5307                         parseerror(parser, "internal error: prototype is not an ast_value");
5308                         retval = false;
5309                         goto cleanup;
5310                     }
5311                     proto = (ast_value*)old;
5312                     proto->desc = var->desc;
5313                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5314                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5315                                    proto->name,
5316                                    ast_ctx(proto).file, ast_ctx(proto).line);
5317                         retval = false;
5318                         goto cleanup;
5319                     }
5320                     /* we need the new parameter-names */
5321                     for (i = 0; i < vec_size(proto->expression.params); ++i)
5322                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5323                     if (!parser_check_qualifiers(parser, var, proto)) {
5324                         retval = false;
5325                         if (proto->desc) 
5326                             mem_d(proto->desc);
5327                         proto = NULL;
5328                         goto cleanup;
5329                     }
5330                     proto->expression.flags |= var->expression.flags;
5331                     ast_delete(var);
5332                     var = proto;
5333                 }
5334                 else
5335                 {
5336                     /* other globals */
5337                     if (old) {
5338                         if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5339                                          "global `%s` already declared here: %s:%i",
5340                                          var->name, ast_ctx(old).file, ast_ctx(old).line))
5341                         {
5342                             retval = false;
5343                             goto cleanup;
5344                         }
5345                         proto = (ast_value*)old;
5346                         if (!ast_istype(old, ast_value)) {
5347                             parseerror(parser, "internal error: not an ast_value");
5348                             retval = false;
5349                             proto = NULL;
5350                             goto cleanup;
5351                         }
5352                         if (!parser_check_qualifiers(parser, var, proto)) {
5353                             retval = false;
5354                             proto = NULL;
5355                             goto cleanup;
5356                         }
5357                         proto->expression.flags |= var->expression.flags;
5358                         ast_delete(var);
5359                         var = proto;
5360                     }
5361                     if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5362                         (old = parser_find_field(parser, var->name)))
5363                     {
5364                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5365                         parseerror(parser, "global `%s` already declared here: %s:%i",
5366                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
5367                         retval = false;
5368                         goto cleanup;
5369                     }
5370                 }
5371             }
5372         }
5373         else /* it's not a global */
5374         {
5375             old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5376             if (old && !isparam) {
5377                 parseerror(parser, "local `%s` already declared here: %s:%i",
5378                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5379                 retval = false;
5380                 goto cleanup;
5381             }
5382             old = parser_find_local(parser, var->name, 0, &isparam);
5383             if (old && isparam) {
5384                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5385                                  "local `%s` is shadowing a parameter", var->name))
5386                 {
5387                     parseerror(parser, "local `%s` already declared here: %s:%i",
5388                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5389                     retval = false;
5390                     goto cleanup;
5391                 }
5392                 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5393                     ast_delete(var);
5394                     var = NULL;
5395                     goto skipvar;
5396                 }
5397             }
5398         }
5399
5400         /* in a noref section we simply bump the usecount */
5401         if (noref || parser->noref)
5402             var->uses++;
5403
5404         /* Part 2:
5405          * Create the global/local, and deal with vector types.
5406          */
5407         if (!proto) {
5408             if (var->expression.vtype == TYPE_VECTOR)
5409                 isvector = true;
5410             else if (var->expression.vtype == TYPE_FIELD &&
5411                      var->expression.next->expression.vtype == TYPE_VECTOR)
5412                 isvector = true;
5413
5414             if (isvector) {
5415                 if (!create_vector_members(var, me)) {
5416                     retval = false;
5417                     goto cleanup;
5418                 }
5419             }
5420
5421             if (!localblock) {
5422                 /* deal with global variables, fields, functions */
5423                 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5424                     var->isfield = true;
5425                     vec_push(parser->fields, (ast_expression*)var);
5426                     util_htset(parser->htfields, var->name, var);
5427                     if (isvector) {
5428                         for (i = 0; i < 3; ++i) {
5429                             vec_push(parser->fields, (ast_expression*)me[i]);
5430                             util_htset(parser->htfields, me[i]->name, me[i]);
5431                         }
5432                     }
5433                 }
5434                 else {
5435                     if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5436                         parser_addglobal(parser, var->name, (ast_expression*)var);
5437                         if (isvector) {
5438                             for (i = 0; i < 3; ++i) {
5439                                 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5440                             }
5441                         }
5442                     } else {
5443                         ast_expression *find  = parser_find_global(parser, var->desc);
5444
5445                         if (!find) {
5446                             compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5447                             return false;
5448                         }
5449
5450                         if (var->expression.vtype != find->expression.vtype) {
5451                             char ty1[1024];
5452                             char ty2[1024];
5453
5454                             ast_type_to_string(find,                  ty1, sizeof(ty1));
5455                             ast_type_to_string((ast_expression*)var,  ty2, sizeof(ty2));
5456
5457                             compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5458                                 ty1, ty2, var->name
5459                             );
5460                             return false;
5461                         }
5462
5463                         /*
5464                          * add alias to aliases table and to corrector
5465                          * so corrections can apply for aliases as well.
5466                          */  
5467                         util_htset(parser->aliases, var->name, find);
5468
5469                         /*
5470                          * add to corrector so corrections can work
5471                          * even for aliases too.
5472                          */ 
5473                         correct_add (
5474                              vec_last(parser->correct_variables),
5475                             &vec_last(parser->correct_variables_score),
5476                             var->name
5477                         );
5478
5479                         /* generate aliases for vector components */
5480                         if (isvector) {
5481                             char *buffer[3];
5482
5483                             util_asprintf(&buffer[0], "%s_x", var->desc);
5484                             util_asprintf(&buffer[1], "%s_y", var->desc);
5485                             util_asprintf(&buffer[2], "%s_z", var->desc);
5486
5487                             util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5488                             util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5489                             util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5490
5491                             mem_d(buffer[0]);
5492                             mem_d(buffer[1]);
5493                             mem_d(buffer[2]);
5494
5495                             /*
5496                              * add to corrector so corrections can work
5497                              * even for aliases too.
5498                              */  
5499                             correct_add (
5500                                  vec_last(parser->correct_variables),
5501                                 &vec_last(parser->correct_variables_score),
5502                                 me[0]->name
5503                             );
5504                             correct_add (
5505                                  vec_last(parser->correct_variables),
5506                                 &vec_last(parser->correct_variables_score),
5507                                 me[1]->name
5508                             );
5509                             correct_add (
5510                                  vec_last(parser->correct_variables),
5511                                 &vec_last(parser->correct_variables_score),
5512                                 me[2]->name
5513                             );
5514                         }
5515                     }
5516                 }
5517             } else {
5518                 if (is_static) {
5519                     /* a static adds itself to be generated like any other global
5520                      * but is added to the local namespace instead
5521                      */
5522                     char   *defname = NULL;
5523                     size_t  prefix_len, ln;
5524
5525                     ln = strlen(parser->function->name);
5526                     vec_append(defname, ln, parser->function->name);
5527
5528                     vec_append(defname, 2, "::");
5529                     /* remember the length up to here */
5530                     prefix_len = vec_size(defname);
5531
5532                     /* Add it to the local scope */
5533                     util_htset(vec_last(parser->variables), var->name, (void*)var);
5534
5535                     /* corrector */
5536                     correct_add (
5537                          vec_last(parser->correct_variables),
5538                         &vec_last(parser->correct_variables_score),
5539                         var->name
5540                     );
5541
5542                     /* now rename the global */
5543                     ln = strlen(var->name);
5544                     vec_append(defname, ln, var->name);
5545                     ast_value_set_name(var, defname);
5546
5547                     /* push it to the to-be-generated globals */
5548                     vec_push(parser->globals, (ast_expression*)var);
5549
5550                     /* same game for the vector members */
5551                     if (isvector) {
5552                         for (i = 0; i < 3; ++i) {
5553                             util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5554
5555                             /* corrector */
5556                             correct_add(
5557                                  vec_last(parser->correct_variables),
5558                                 &vec_last(parser->correct_variables_score),
5559                                 me[i]->name
5560                             );
5561
5562                             vec_shrinkto(defname, prefix_len);
5563                             ln = strlen(me[i]->name);
5564                             vec_append(defname, ln, me[i]->name);
5565                             ast_member_set_name(me[i], defname);
5566
5567                             vec_push(parser->globals, (ast_expression*)me[i]);
5568                         }
5569                     }
5570                     vec_free(defname);
5571                 } else {
5572                     vec_push(localblock->locals, var);
5573                     parser_addlocal(parser, var->name, (ast_expression*)var);
5574                     if (isvector) {
5575                         for (i = 0; i < 3; ++i) {
5576                             parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5577                             ast_block_collect(localblock, (ast_expression*)me[i]);
5578                         }
5579                     }
5580                 }
5581             }
5582         }
5583         me[0] = me[1] = me[2] = NULL;
5584         cleanvar = false;
5585         /* Part 2.2
5586          * deal with arrays
5587          */
5588         if (var->expression.vtype == TYPE_ARRAY) {
5589             char name[1024];
5590             snprintf(name, sizeof(name), "%s##SET", var->name);
5591             if (!parser_create_array_setter(parser, var, name))
5592                 goto cleanup;
5593             snprintf(name, sizeof(name), "%s##GET", var->name);
5594             if (!parser_create_array_getter(parser, var, var->expression.next, name))
5595                 goto cleanup;
5596         }
5597         else if (!localblock && !nofields &&
5598                  var->expression.vtype == TYPE_FIELD &&
5599                  var->expression.next->expression.vtype == TYPE_ARRAY)
5600         {
5601             char name[1024];
5602             ast_expression *telem;
5603             ast_value      *tfield;
5604             ast_value      *array = (ast_value*)var->expression.next;
5605
5606             if (!ast_istype(var->expression.next, ast_value)) {
5607                 parseerror(parser, "internal error: field element type must be an ast_value");
5608                 goto cleanup;
5609             }
5610
5611             snprintf(name, sizeof(name), "%s##SETF", var->name);
5612             if (!parser_create_array_field_setter(parser, array, name))
5613                 goto cleanup;
5614
5615             telem = ast_type_copy(ast_ctx(var), array->expression.next);
5616             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5617             tfield->expression.next = telem;
5618             snprintf(name, sizeof(name), "%s##GETFP", var->name);
5619             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5620                 ast_delete(tfield);
5621                 goto cleanup;
5622             }
5623             ast_delete(tfield);
5624         }
5625
5626 skipvar:
5627         if (parser->tok == ';') {
5628             ast_delete(basetype);
5629             if (!parser_next(parser)) {
5630                 parseerror(parser, "error after variable declaration");
5631                 return false;
5632             }
5633             return true;
5634         }
5635
5636         if (parser->tok == ',')
5637             goto another;
5638
5639         /*
5640         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5641         */
5642         if (!var) {
5643             parseerror(parser, "missing comma or semicolon while parsing variables");
5644             break;
5645         }
5646
5647         if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5648             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5649                              "initializing expression turns variable `%s` into a constant in this standard",
5650                              var->name) )
5651             {
5652                 break;
5653             }
5654         }
5655
5656         if (parser->tok != '{') {
5657             if (parser->tok != '=') {
5658                 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5659                 break;
5660             }
5661
5662             if (!parser_next(parser)) {
5663                 parseerror(parser, "error parsing initializer");
5664                 break;
5665             }
5666         }
5667         else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5668             parseerror(parser, "expected '=' before function body in this standard");
5669         }
5670
5671         if (parser->tok == '#') {
5672             ast_function *func = NULL;
5673
5674             if (localblock) {
5675                 parseerror(parser, "cannot declare builtins within functions");
5676                 break;
5677             }
5678             if (var->expression.vtype != TYPE_FUNCTION) {
5679                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5680                 break;
5681             }
5682             if (!parser_next(parser)) {
5683                 parseerror(parser, "expected builtin number");
5684                 break;
5685             }
5686             if (parser->tok != TOKEN_INTCONST) {
5687                 parseerror(parser, "builtin number must be an integer constant");
5688                 break;
5689             }
5690             if (parser_token(parser)->constval.i < 0) {
5691                 parseerror(parser, "builtin number must be an integer greater than zero");
5692                 break;
5693             }
5694
5695             if (var->hasvalue) {
5696                 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5697                                     "builtin `%s` has already been defined\n"
5698                                     " -> previous declaration here: %s:%i",
5699                                     var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5700             }
5701             else
5702             {
5703                 func = ast_function_new(ast_ctx(var), var->name, var);
5704                 if (!func) {
5705                     parseerror(parser, "failed to allocate function for `%s`", var->name);
5706                     break;
5707                 }
5708                 vec_push(parser->functions, func);
5709
5710                 func->builtin = -parser_token(parser)->constval.i-1;
5711             }
5712
5713             if (!parser_next(parser)) {
5714                 parseerror(parser, "expected comma or semicolon");
5715                 if (func)
5716                     ast_function_delete(func);
5717                 var->constval.vfunc = NULL;
5718                 break;
5719             }
5720         }
5721         else if (parser->tok == '{' || parser->tok == '[')
5722         {
5723             if (localblock) {
5724                 parseerror(parser, "cannot declare functions within functions");
5725                 break;
5726             }
5727
5728             if (proto)
5729                 ast_ctx(proto) = parser_ctx(parser);
5730
5731             if (!parse_function_body(parser, var))
5732                 break;
5733             ast_delete(basetype);
5734             for (i = 0; i < vec_size(parser->gotos); ++i)
5735                 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5736             vec_free(parser->gotos);
5737             vec_free(parser->labels);
5738             return true;
5739         } else {
5740             ast_expression *cexp;
5741             ast_value      *cval;
5742
5743             cexp = parse_expression_leave(parser, true, false, false);
5744             if (!cexp)
5745                 break;
5746
5747             if (!localblock) {
5748                 cval = (ast_value*)cexp;
5749                 if (cval != parser->nil &&
5750                     (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5751                    )
5752                 {
5753                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5754                 }
5755                 else
5756                 {
5757                     if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5758                         qualifier != CV_VAR)
5759                     {
5760                         var->cvq = CV_CONST;
5761                     }
5762                     if (cval == parser->nil)
5763                         var->expression.flags |= AST_FLAG_INITIALIZED;
5764                     else
5765                     {
5766                         var->hasvalue = true;
5767                         if (cval->expression.vtype == TYPE_STRING)
5768                             var->constval.vstring = parser_strdup(cval->constval.vstring);
5769                         else if (cval->expression.vtype == TYPE_FIELD)
5770                             var->constval.vfield = cval;
5771                         else
5772                             memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5773                         ast_unref(cval);
5774                     }
5775                 }
5776             } else {
5777                 int cvq;
5778                 shunt sy = { NULL, NULL, NULL, NULL };
5779                 cvq = var->cvq;
5780                 var->cvq = CV_NONE;
5781                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5782                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5783                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5784                 if (!parser_sy_apply_operator(parser, &sy))
5785                     ast_unref(cexp);
5786                 else {
5787                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5788                         parseerror(parser, "internal error: leaked operands");
5789                     if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5790                         break;
5791                 }
5792                 vec_free(sy.out);
5793                 vec_free(sy.ops);
5794                 var->cvq = cvq;
5795             }
5796         }
5797
5798 another:
5799         if (parser->tok == ',') {
5800             if (!parser_next(parser)) {
5801                 parseerror(parser, "expected another variable");
5802                 break;
5803             }
5804
5805             if (parser->tok != TOKEN_IDENT) {
5806                 parseerror(parser, "expected another variable");
5807                 break;
5808             }
5809             var = ast_value_copy(basetype);
5810             cleanvar = true;
5811             ast_value_set_name(var, parser_tokval(parser));
5812             if (!parser_next(parser)) {
5813                 parseerror(parser, "error parsing variable declaration");
5814                 break;
5815             }
5816             continue;
5817         }
5818
5819         if (parser->tok != ';') {
5820             parseerror(parser, "missing semicolon after variables");
5821             break;
5822         }
5823
5824         if (!parser_next(parser)) {
5825             parseerror(parser, "parse error after variable declaration");
5826             break;
5827         }
5828
5829         ast_delete(basetype);
5830         return true;
5831     }
5832
5833     if (cleanvar && var)
5834         ast_delete(var);
5835     ast_delete(basetype);
5836     return false;
5837
5838 cleanup:
5839     ast_delete(basetype);
5840     if (cleanvar && var)
5841         ast_delete(var);
5842     if (me[0]) ast_member_delete(me[0]);
5843     if (me[1]) ast_member_delete(me[1]);
5844     if (me[2]) ast_member_delete(me[2]);
5845     return retval;
5846 }
5847
5848 static bool parser_global_statement(parser_t *parser)
5849 {
5850     int        cvq       = CV_WRONG;
5851     bool       noref     = false;
5852     bool       is_static = false;
5853     uint32_t   qflags    = 0;
5854     ast_value *istype    = NULL;
5855     char      *vstring   = NULL;
5856
5857     if (parser->tok == TOKEN_IDENT)
5858         istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5859
5860     if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5861     {
5862         return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5863     }
5864     else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5865     {
5866         if (cvq == CV_WRONG)
5867             return false;
5868         return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5869     }
5870     else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5871     {
5872         return parse_enum(parser);
5873     }
5874     else if (parser->tok == TOKEN_KEYWORD)
5875     {
5876         if (!strcmp(parser_tokval(parser), "typedef")) {
5877             if (!parser_next(parser)) {
5878                 parseerror(parser, "expected type definition after 'typedef'");
5879                 return false;
5880             }
5881             return parse_typedef(parser);
5882         }
5883         parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5884         return false;
5885     }
5886     else if (parser->tok == '#')
5887     {
5888         return parse_pragma(parser);
5889     }
5890     else if (parser->tok == '$')
5891     {
5892         if (!parser_next(parser)) {
5893             parseerror(parser, "parse error");
5894             return false;
5895         }
5896     }
5897     else
5898     {
5899         parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5900         return false;
5901     }
5902     return true;
5903 }
5904
5905 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5906 {
5907     return util_crc16(old, str, strlen(str));
5908 }
5909
5910 static void progdefs_crc_file(const char *str)
5911 {
5912     /* write to progdefs.h here */
5913     (void)str;
5914 }
5915
5916 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5917 {
5918     old = progdefs_crc_sum(old, str);
5919     progdefs_crc_file(str);
5920     return old;
5921 }
5922
5923 static void generate_checksum(parser_t *parser)
5924 {
5925     uint16_t   crc = 0xFFFF;
5926     size_t     i;
5927     ast_value *value;
5928
5929     crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5930     crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5931     /*
5932     progdefs_crc_file("\tint\tpad;\n");
5933     progdefs_crc_file("\tint\tofs_return[3];\n");
5934     progdefs_crc_file("\tint\tofs_parm0[3];\n");
5935     progdefs_crc_file("\tint\tofs_parm1[3];\n");
5936     progdefs_crc_file("\tint\tofs_parm2[3];\n");
5937     progdefs_crc_file("\tint\tofs_parm3[3];\n");
5938     progdefs_crc_file("\tint\tofs_parm4[3];\n");
5939     progdefs_crc_file("\tint\tofs_parm5[3];\n");
5940     progdefs_crc_file("\tint\tofs_parm6[3];\n");
5941     progdefs_crc_file("\tint\tofs_parm7[3];\n");
5942     */
5943     for (i = 0; i < parser->crc_globals; ++i) {
5944         if (!ast_istype(parser->globals[i], ast_value))
5945             continue;
5946         value = (ast_value*)(parser->globals[i]);
5947         switch (value->expression.vtype) {
5948             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5949             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5950             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5951             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5952             default:
5953                 crc = progdefs_crc_both(crc, "\tint\t");
5954                 break;
5955         }
5956         crc = progdefs_crc_both(crc, value->name);
5957         crc = progdefs_crc_both(crc, ";\n");
5958     }
5959     crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5960     for (i = 0; i < parser->crc_fields; ++i) {
5961         if (!ast_istype(parser->fields[i], ast_value))
5962             continue;
5963         value = (ast_value*)(parser->fields[i]);
5964         switch (value->expression.next->expression.vtype) {
5965             case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5966             case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5967             case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5968             case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5969             default:
5970                 crc = progdefs_crc_both(crc, "\tint\t");
5971                 break;
5972         }
5973         crc = progdefs_crc_both(crc, value->name);
5974         crc = progdefs_crc_both(crc, ";\n");
5975     }
5976     crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5977
5978     code_crc = crc;
5979 }
5980
5981 static parser_t *parser;
5982
5983 bool parser_init()
5984 {
5985     lex_ctx empty_ctx;
5986     size_t i;
5987
5988     parser = (parser_t*)mem_a(sizeof(parser_t));
5989     if (!parser)
5990         return false;
5991
5992     memset(parser, 0, sizeof(*parser));
5993
5994     for (i = 0; i < operator_count; ++i) {
5995         if (operators[i].id == opid1('=')) {
5996             parser->assign_op = operators+i;
5997             break;
5998         }
5999     }
6000     if (!parser->assign_op) {
6001         printf("internal error: initializing parser: failed to find assign operator\n");
6002         mem_d(parser);
6003         return false;
6004     }
6005
6006     vec_push(parser->variables, parser->htfields  = util_htnew(PARSER_HT_SIZE));
6007     vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6008     vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6009     vec_push(parser->_blocktypedefs, 0);
6010
6011     parser->aliases = util_htnew(PARSER_HT_SIZE);
6012
6013     /* corrector */
6014     vec_push(parser->correct_variables, correct_trie_new());
6015     vec_push(parser->correct_variables_score, NULL);
6016
6017     empty_ctx.file = "<internal>";
6018     empty_ctx.line = 0;
6019     parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6020     parser->nil->cvq = CV_CONST;
6021     if (OPTS_FLAG(UNTYPED_NIL))
6022         util_htset(parser->htglobals, "nil", (void*)parser->nil);
6023
6024     parser->max_param_count = 1;
6025
6026     parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6027     parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6028     parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6029
6030     if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6031         parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6032         parser->reserved_version->cvq = CV_CONST;
6033         parser->reserved_version->hasvalue = true;
6034         parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6035         parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6036     } else {
6037         parser->reserved_version = NULL;
6038     }
6039     return true;
6040 }
6041
6042 bool parser_compile()
6043 {
6044     /* initial lexer/parser state */
6045     parser->lex->flags.noops = true;
6046
6047     if (parser_next(parser))
6048     {
6049         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6050         {
6051             if (!parser_global_statement(parser)) {
6052                 if (parser->tok == TOKEN_EOF)
6053                     parseerror(parser, "unexpected eof");
6054                 else if (compile_errors)
6055                     parseerror(parser, "there have been errors, bailing out");
6056                 lex_close(parser->lex);
6057                 parser->lex = NULL;
6058                 return false;
6059             }
6060         }
6061     } else {
6062         parseerror(parser, "parse error");
6063         lex_close(parser->lex);
6064         parser->lex = NULL;
6065         return false;
6066     }
6067
6068     lex_close(parser->lex);
6069     parser->lex = NULL;
6070
6071     return !compile_errors;
6072 }
6073
6074 bool parser_compile_file(const char *filename)
6075 {
6076     parser->lex = lex_open(filename);
6077     if (!parser->lex) {
6078         con_err("failed to open file \"%s\"\n", filename);
6079         return false;
6080     }
6081     return parser_compile();
6082 }
6083
6084 bool parser_compile_string(const char *name, const char *str, size_t len)
6085 {
6086     parser->lex = lex_open_string(str, len, name);
6087     if (!parser->lex) {
6088         con_err("failed to create lexer for string \"%s\"\n", name);
6089         return false;
6090     }
6091     return parser_compile();
6092 }
6093
6094 void parser_cleanup()
6095 {
6096     size_t i;
6097     for (i = 0; i < vec_size(parser->accessors); ++i) {
6098         ast_delete(parser->accessors[i]->constval.vfunc);
6099         parser->accessors[i]->constval.vfunc = NULL;
6100         ast_delete(parser->accessors[i]);
6101     }
6102     for (i = 0; i < vec_size(parser->functions); ++i) {
6103         ast_delete(parser->functions[i]);
6104     }
6105     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6106         ast_delete(parser->imm_vector[i]);
6107     }
6108     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6109         ast_delete(parser->imm_string[i]);
6110     }
6111     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6112         ast_delete(parser->imm_float[i]);
6113     }
6114     for (i = 0; i < vec_size(parser->fields); ++i) {
6115         ast_delete(parser->fields[i]);
6116     }
6117     for (i = 0; i < vec_size(parser->globals); ++i) {
6118         ast_delete(parser->globals[i]);
6119     }
6120     vec_free(parser->accessors);
6121     vec_free(parser->functions);
6122     vec_free(parser->imm_vector);
6123     vec_free(parser->imm_string);
6124     vec_free(parser->imm_float);
6125     vec_free(parser->globals);
6126     vec_free(parser->fields);
6127
6128     for (i = 0; i < vec_size(parser->variables); ++i)
6129         util_htdel(parser->variables[i]);
6130     vec_free(parser->variables);
6131     vec_free(parser->_blocklocals);
6132     vec_free(parser->_locals);
6133
6134     /* corrector */
6135     for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6136         correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6137     }
6138     vec_free(parser->correct_variables);
6139     vec_free(parser->correct_variables_score);
6140
6141
6142     for (i = 0; i < vec_size(parser->_typedefs); ++i)
6143         ast_delete(parser->_typedefs[i]);
6144     vec_free(parser->_typedefs);
6145     for (i = 0; i < vec_size(parser->typedefs); ++i)
6146         util_htdel(parser->typedefs[i]);
6147     vec_free(parser->typedefs);
6148     vec_free(parser->_blocktypedefs);
6149
6150     vec_free(parser->_block_ctx);
6151
6152     vec_free(parser->labels);
6153     vec_free(parser->gotos);
6154     vec_free(parser->breaks);
6155     vec_free(parser->continues);
6156
6157     ast_value_delete(parser->nil);
6158
6159     ast_value_delete(parser->const_vec[0]);
6160     ast_value_delete(parser->const_vec[1]);
6161     ast_value_delete(parser->const_vec[2]);
6162
6163     util_htdel(parser->aliases);
6164
6165     mem_d(parser);
6166 }
6167
6168 bool parser_finish(const char *output)
6169 {
6170     size_t i;
6171     ir_builder *ir;
6172     bool retval = true;
6173
6174     if (compile_errors) {
6175         con_out("*** there were compile errors\n");
6176         return false;
6177     }
6178
6179     ir = ir_builder_new("gmqcc_out");
6180     if (!ir) {
6181         con_out("failed to allocate builder\n");
6182         return false;
6183     }
6184
6185     for (i = 0; i < vec_size(parser->fields); ++i) {
6186         ast_value *field;
6187         bool hasvalue;
6188         if (!ast_istype(parser->fields[i], ast_value))
6189             continue;
6190         field = (ast_value*)parser->fields[i];
6191         hasvalue = field->hasvalue;
6192         field->hasvalue = false;
6193         if (!ast_global_codegen((ast_value*)field, ir, true)) {
6194             con_out("failed to generate field %s\n", field->name);
6195             ir_builder_delete(ir);
6196             return false;
6197         }
6198         if (hasvalue) {
6199             ir_value *ifld;
6200             ast_expression *subtype;
6201             field->hasvalue = true;
6202             subtype = field->expression.next;
6203             ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6204             if (subtype->expression.vtype == TYPE_FIELD)
6205                 ifld->fieldtype = subtype->expression.next->expression.vtype;
6206             else if (subtype->expression.vtype == TYPE_FUNCTION)
6207                 ifld->outtype = subtype->expression.next->expression.vtype;
6208             (void)!ir_value_set_field(field->ir_v, ifld);
6209         }
6210     }
6211     for (i = 0; i < vec_size(parser->globals); ++i) {
6212         ast_value *asvalue;
6213         if (!ast_istype(parser->globals[i], ast_value))
6214             continue;
6215         asvalue = (ast_value*)(parser->globals[i]);
6216         if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6217             retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6218                                                 "unused global: `%s`", asvalue->name);
6219         }
6220         if (!ast_global_codegen(asvalue, ir, false)) {
6221             con_out("failed to generate global %s\n", asvalue->name);
6222             ir_builder_delete(ir);
6223             return false;
6224         }
6225     }
6226     /* Build function vararg accessor ast tree now before generating
6227      * immediates, because the accessors may add new immediates
6228      */
6229     for (i = 0; i < vec_size(parser->functions); ++i) {
6230         ast_function *f = parser->functions[i];
6231         if (f->varargs) {
6232             if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6233                 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6234                 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6235                     con_out("failed to generate vararg setter for %s\n", f->name);
6236                     ir_builder_delete(ir);
6237                     return false;
6238                 }
6239                 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6240                     con_out("failed to generate vararg getter for %s\n", f->name);
6241                     ir_builder_delete(ir);
6242                     return false;
6243                 }
6244             } else {
6245                 ast_delete(f->varargs);
6246                 f->varargs = NULL;
6247             }
6248         }
6249     }
6250     /* Now we can generate immediates */
6251     for (i = 0; i < vec_size(parser->imm_float); ++i) {
6252         if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6253             con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6254             ir_builder_delete(ir);
6255             return false;
6256         }
6257     }
6258     for (i = 0; i < vec_size(parser->imm_string); ++i) {
6259         if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6260             con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6261             ir_builder_delete(ir);
6262             return false;
6263         }
6264     }
6265     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6266         if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6267             con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6268             ir_builder_delete(ir);
6269             return false;
6270         }
6271     }
6272     for (i = 0; i < vec_size(parser->globals); ++i) {
6273         ast_value *asvalue;
6274         if (!ast_istype(parser->globals[i], ast_value))
6275             continue;
6276         asvalue = (ast_value*)(parser->globals[i]);
6277         if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6278         {
6279             if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6280                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6281                                        "uninitialized constant: `%s`",
6282                                        asvalue->name);
6283             else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6284                 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6285                                        "uninitialized global: `%s`",
6286                                        asvalue->name);
6287         }
6288         if (!ast_generate_accessors(asvalue, ir)) {
6289             ir_builder_delete(ir);
6290             return false;
6291         }
6292     }
6293     for (i = 0; i < vec_size(parser->fields); ++i) {
6294         ast_value *asvalue;
6295         asvalue = (ast_value*)(parser->fields[i]->expression.next);
6296
6297         if (!ast_istype((ast_expression*)asvalue, ast_value))
6298             continue;
6299         if (asvalue->expression.vtype != TYPE_ARRAY)
6300             continue;
6301         if (!ast_generate_accessors(asvalue, ir)) {
6302             ir_builder_delete(ir);
6303             return false;
6304         }
6305     }
6306     if (parser->reserved_version &&
6307         !ast_global_codegen(parser->reserved_version, ir, false))
6308     {
6309         con_out("failed to generate reserved::version");
6310         ir_builder_delete(ir);
6311         return false;
6312     }
6313     for (i = 0; i < vec_size(parser->functions); ++i) {
6314         ast_function *f = parser->functions[i];
6315         if (!ast_function_codegen(f, ir)) {
6316             con_out("failed to generate function %s\n", f->name);
6317             ir_builder_delete(ir);
6318             return false;
6319         }
6320     }
6321     if (OPTS_OPTION_BOOL(OPTION_DUMP))
6322         ir_builder_dump(ir, con_out);
6323     for (i = 0; i < vec_size(parser->functions); ++i) {
6324         if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6325             con_out("failed to finalize function %s\n", parser->functions[i]->name);
6326             ir_builder_delete(ir);
6327             return false;
6328         }
6329     }
6330
6331     if (compile_Werrors) {
6332         con_out("*** there were warnings treated as errors\n");
6333         compile_show_werrors();
6334         retval = false;
6335     }
6336
6337     if (retval) {
6338         if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6339             ir_builder_dump(ir, con_out);
6340
6341         generate_checksum(parser);
6342
6343         if (!ir_builder_generate(ir, output)) {
6344             con_out("*** failed to generate output file\n");
6345             ir_builder_delete(ir);
6346             return false;
6347         }
6348     }
6349
6350     ir_builder_delete(ir);
6351     return retval;
6352 }