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