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