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