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