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