]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
Implemented hashtable as-per Blubs request
[xonotic/gmqcc.git] / parser.c
1 #include <stdio.h>
2 #include <stdarg.h>
3
4 #include "gmqcc.h"
5 #include "lexer.h"
6
7 typedef struct {
8     char *name;
9     ast_expression *var;
10 } varentry_t;
11
12 typedef struct {
13     lex_file *lex;
14     int      tok;
15
16     varentry_t    *globals;
17     varentry_t    *fields;
18     ast_function **functions;
19     ast_value    **imm_float;
20     ast_value    **imm_string;
21     ast_value    **imm_vector;
22
23     /* must be deleted first, they reference immediates and values */
24     ast_value    **accessors;
25
26     ast_value *imm_float_zero;
27     ast_value *imm_vector_zero;
28
29     size_t crc_globals;
30     size_t crc_fields;
31
32     ast_function *function;
33     varentry_t *locals;
34     size_t blocklocal;
35
36     size_t errors;
37
38     /* we store the '=' operator info */
39     const oper_info *assign_op;
40
41     /* TYPE_FIELD -> parser_find_fields is used instead of find_var
42      * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
43      * anything else: type error
44      */
45     qcint  memberof;
46 } parser_t;
47
48
49 static bool GMQCC_WARN parser_pop_local(parser_t *parser);
50 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields);
51 static ast_block* parse_block(parser_t *parser, bool warnreturn);
52 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
53 static ast_expression* parse_statement_or_block(parser_t *parser);
54 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
55 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
56 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
57
58 static void parseerror(parser_t *parser, const char *fmt, ...)
59 {
60         va_list ap;
61
62         parser->errors++;
63
64         va_start(ap, fmt);
65     con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
66         va_end(ap);
67 }
68
69 /* returns true if it counts as an error */
70 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
71 {
72         va_list ap;
73         int lvl = LVL_WARNING;
74
75     if (!OPTS_WARN(warntype))
76         return false;
77
78     if (opts_werror) {
79             parser->errors++;
80             lvl = LVL_ERROR;
81         }
82
83         va_start(ap, fmt);
84     con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
85         va_end(ap);
86
87         return opts_werror;
88 }
89
90 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
91 {
92         va_list ap;
93         int lvl = LVL_WARNING;
94
95     if (!OPTS_WARN(warntype))
96         return false;
97
98     if (opts_werror)
99             lvl = LVL_ERROR;
100
101         va_start(ap, fmt);
102     con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
103         va_end(ap);
104
105         return opts_werror;
106 }
107
108 /**********************************************************************
109  * some maths used for constant folding
110  */
111
112 vector vec3_add(vector a, vector b)
113 {
114     vector out;
115     out.x = a.x + b.x;
116     out.y = a.y + b.y;
117     out.z = a.z + b.z;
118     return out;
119 }
120
121 vector vec3_sub(vector a, vector b)
122 {
123     vector out;
124     out.x = a.x - b.x;
125     out.y = a.y - b.y;
126     out.z = a.z - b.z;
127     return out;
128 }
129
130 qcfloat vec3_mulvv(vector a, vector b)
131 {
132     return (a.x * b.x + a.y * b.y + a.z * b.z);
133 }
134
135 vector vec3_mulvf(vector a, float b)
136 {
137     vector out;
138     out.x = a.x * b;
139     out.y = a.y * b;
140     out.z = a.z * b;
141     return out;
142 }
143
144 /**********************************************************************
145  * parsing
146  */
147
148 bool parser_next(parser_t *parser)
149 {
150     /* lex_do kills the previous token */
151     parser->tok = lex_do(parser->lex);
152     if (parser->tok == TOKEN_EOF)
153         return true;
154     if (parser->tok >= TOKEN_ERROR) {
155         parseerror(parser, "lex error");
156         return false;
157     }
158     return true;
159 }
160
161 #define parser_tokval(p) ((p)->lex->tok.value)
162 #define parser_token(p)  (&((p)->lex->tok))
163 #define parser_ctx(p)    ((p)->lex->tok.ctx)
164
165 static ast_value* parser_const_float(parser_t *parser, double d)
166 {
167     size_t i;
168     ast_value *out;
169     for (i = 0; i < vec_size(parser->imm_float); ++i) {
170         if ((double)(parser->imm_float[i]->constval.vfloat) == d)
171             return parser->imm_float[i];
172     }
173     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
174     out->isconst = true;
175     out->constval.vfloat = d;
176     vec_push(parser->imm_float, out);
177     return out;
178 }
179
180 static ast_value* parser_const_float_0(parser_t *parser)
181 {
182     if (!parser->imm_float_zero)
183         parser->imm_float_zero = parser_const_float(parser, 0);
184     return parser->imm_float_zero;
185 }
186
187 static char *parser_strdup(const char *str)
188 {
189     if (str && !*str) {
190         /* actually dup empty strings */
191         char *out = mem_a(1);
192         *out = 0;
193         return out;
194     }
195     return util_strdup(str);
196 }
197
198 static ast_value* parser_const_string(parser_t *parser, const char *str)
199 {
200     size_t i;
201     ast_value *out;
202     for (i = 0; i < vec_size(parser->imm_string); ++i) {
203         if (!strcmp(parser->imm_string[i]->constval.vstring, str))
204             return parser->imm_string[i];
205     }
206     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
207     out->isconst = true;
208     out->constval.vstring = parser_strdup(str);
209     vec_push(parser->imm_string, out);
210     return out;
211 }
212
213 static ast_value* parser_const_vector(parser_t *parser, vector v)
214 {
215     size_t i;
216     ast_value *out;
217     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
218         if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
219             return parser->imm_vector[i];
220     }
221     out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
222     out->isconst = true;
223     out->constval.vvec = v;
224     vec_push(parser->imm_vector, out);
225     return out;
226 }
227
228 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
229 {
230     vector v;
231     v.x = x;
232     v.y = y;
233     v.z = z;
234     return parser_const_vector(parser, v);
235 }
236
237 static ast_value* parser_const_vector_0(parser_t *parser)
238 {
239     if (!parser->imm_vector_zero)
240         parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
241     return parser->imm_vector_zero;
242 }
243
244 static ast_expression* parser_find_field(parser_t *parser, const char *name)
245 {
246     size_t i;
247     for (i = 0; i < vec_size(parser->fields); ++i) {
248         if (!strcmp(parser->fields[i].name, name))
249             return parser->fields[i].var;
250     }
251     return NULL;
252 }
253
254 static ast_expression* parser_find_global(parser_t *parser, const char *name)
255 {
256     size_t i;
257     for (i = 0; i < vec_size(parser->globals); ++i) {
258         if (!strcmp(parser->globals[i].name, name))
259             return parser->globals[i].var;
260     }
261     return NULL;
262 }
263
264 static ast_expression* parser_find_param(parser_t *parser, const char *name)
265 {
266     size_t i;
267     ast_value *fun;
268     if (!parser->function)
269         return NULL;
270     fun = parser->function->vtype;
271     for (i = 0; i < vec_size(fun->expression.params); ++i) {
272         if (!strcmp(fun->expression.params[i]->name, name))
273             return (ast_expression*)(fun->expression.params[i]);
274     }
275     return NULL;
276 }
277
278 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
279 {
280     size_t i;
281     *isparam = false;
282     for (i = vec_size(parser->locals); i > upto;) {
283         --i;
284         if (!strcmp(parser->locals[i].name, name))
285             return parser->locals[i].var;
286     }
287     *isparam = true;
288     return parser_find_param(parser, name);
289 }
290
291 static ast_expression* parser_find_var(parser_t *parser, const char *name)
292 {
293     bool dummy;
294     ast_expression *v;
295     v         = parser_find_local(parser, name, 0, &dummy);
296     if (!v) v = parser_find_global(parser, name);
297     return v;
298 }
299
300 typedef struct
301 {
302     size_t etype; /* 0 = expression, others are operators */
303     int             paren;
304     size_t          off;
305     ast_expression *out;
306     ast_block      *block; /* for commas and function calls */
307     lex_ctx ctx;
308 } sy_elem;
309 typedef struct
310 {
311     sy_elem *out;
312     sy_elem *ops;
313 } shunt;
314
315 #define SY_PAREN_EXPR '('
316 #define SY_PAREN_FUNC 'f'
317 #define SY_PAREN_INDEX '['
318
319 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
320     sy_elem e;
321     e.etype = 0;
322     e.off   = 0;
323     e.out   = v;
324     e.block = NULL;
325     e.ctx   = ctx;
326     e.paren = 0;
327     return e;
328 }
329
330 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
331     sy_elem e;
332     e.etype = 0;
333     e.off   = 0;
334     e.out   = (ast_expression*)v;
335     e.block = v;
336     e.ctx   = ctx;
337     e.paren = 0;
338     return e;
339 }
340
341 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
342     sy_elem e;
343     e.etype = 1 + (op - operators);
344     e.off   = 0;
345     e.out   = NULL;
346     e.block = NULL;
347     e.ctx   = ctx;
348     e.paren = 0;
349     return e;
350 }
351
352 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
353     sy_elem e;
354     e.etype = 0;
355     e.off   = off;
356     e.out   = NULL;
357     e.block = NULL;
358     e.ctx   = ctx;
359     e.paren = p;
360     return e;
361 }
362
363 #ifdef DEBUGSHUNT
364 # define DEBUGSHUNTDO(x) x
365 #else
366 # define DEBUGSHUNTDO(x)
367 #endif
368
369 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
370  * so we need to rotate it to become ent.(foo[n]).
371  */
372 static bool rotate_entfield_array_index_nodes(ast_expression **out)
373 {
374     ast_array_index *index;
375     ast_entfield    *entfield;
376
377     ast_value       *field;
378     ast_expression  *sub;
379     ast_expression  *entity;
380
381     lex_ctx ctx = ast_ctx(*out);
382
383     if (!ast_istype(*out, ast_array_index))
384         return false;
385     index = (ast_array_index*)*out;
386
387     if (!ast_istype(index->array, ast_entfield))
388         return false;
389     entfield = (ast_entfield*)index->array;
390
391     if (!ast_istype(entfield->field, ast_value))
392         return false;
393     field = (ast_value*)entfield->field;
394
395     sub    = index->index;
396     entity = entfield->entity;
397
398     ast_delete(index);
399
400     index = ast_array_index_new(ctx, (ast_expression*)field, sub);
401     entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
402     *out = (ast_expression*)entfield;
403
404     return true;
405 }
406
407 static bool parser_sy_pop(parser_t *parser, shunt *sy)
408 {
409     const oper_info *op;
410     lex_ctx ctx;
411     ast_expression *out = NULL;
412     ast_expression *exprs[3];
413     ast_block      *blocks[3];
414     ast_value      *asvalue[3];
415     size_t i, assignop;
416     qcint  generated_op = 0;
417
418     char ty1[1024];
419     char ty2[1024];
420
421     if (!vec_size(sy->ops)) {
422         parseerror(parser, "internal error: missing operator");
423         return false;
424     }
425
426     if (vec_last(sy->ops).paren) {
427         parseerror(parser, "unmatched parenthesis");
428         return false;
429     }
430
431     op = &operators[vec_last(sy->ops).etype - 1];
432     ctx = vec_last(sy->ops).ctx;
433
434     DEBUGSHUNTDO(con_out("apply %s\n", op->op));
435
436     if (vec_size(sy->out) < op->operands) {
437         parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
438                    op->op, (int)op->id);
439         return false;
440     }
441
442     vec_shrinkby(sy->ops, 1);
443
444     vec_shrinkby(sy->out, op->operands);
445     for (i = 0; i < op->operands; ++i) {
446         exprs[i]  = sy->out[vec_size(sy->out)+i].out;
447         blocks[i] = sy->out[vec_size(sy->out)+i].block;
448         asvalue[i] = (ast_value*)exprs[i];
449     }
450
451     if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
452         parseerror(parser, "internal error: operator cannot be applied on empty blocks");
453         return false;
454     }
455
456 #define NotSameType(T) \
457              (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
458               exprs[0]->expression.vtype != T)
459 #define CanConstFold1(A) \
460              (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
461 #define CanConstFold(A, B) \
462              (CanConstFold1(A) && CanConstFold1(B))
463 #define ConstV(i) (asvalue[(i)]->constval.vvec)
464 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
465 #define ConstS(i) (asvalue[(i)]->constval.vstring)
466     switch (op->id)
467     {
468         default:
469             parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
470             return false;
471
472         case opid1('.'):
473             if (exprs[0]->expression.vtype == TYPE_ENTITY) {
474                 if (exprs[1]->expression.vtype != TYPE_FIELD) {
475                     parseerror(parser, "type error: right hand of member-operand should be an entity-field");
476                     return false;
477                 }
478                 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
479             }
480             else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
481                 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
482                 return false;
483             }
484             else {
485                 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
486                 return false;
487             }
488             break;
489
490         case opid1('['):
491             if (exprs[0]->expression.vtype != TYPE_ARRAY &&
492                 !(exprs[0]->expression.vtype == TYPE_FIELD &&
493                   exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
494             {
495                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
496                 parseerror(parser, "cannot index value of type %s", ty1);
497                 return false;
498             }
499             if (exprs[1]->expression.vtype != TYPE_FLOAT) {
500                 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
501                 parseerror(parser, "index must be of type float, not %s", ty1);
502                 return false;
503             }
504             out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
505             if (rotate_entfield_array_index_nodes(&out))
506             {
507                 if (opts_standard != COMPILER_GMQCC) {
508                     /* this error doesn't need to make us bail out */
509                     (void)!parsewarning(parser, WARN_EXTENSIONS,
510                                         "accessing array-field members of an entity without parenthesis\n"
511                                         " -> this is an extension from -std=gmqcc");
512                 }
513             }
514             break;
515
516         case opid1(','):
517             if (blocks[0]) {
518                 vec_push(blocks[0]->exprs, exprs[1]);
519             } else {
520                 blocks[0] = ast_block_new(ctx);
521                 vec_push(blocks[0]->exprs, exprs[0]);
522                 vec_push(blocks[0]->exprs, exprs[1]);
523             }
524             if (!ast_block_set_type(blocks[0], exprs[1]))
525                 return false;
526
527             vec_push(sy->out, syblock(ctx, blocks[0]));
528             return true;
529
530         case opid2('-','P'):
531             switch (exprs[0]->expression.vtype) {
532                 case TYPE_FLOAT:
533                     if (CanConstFold1(exprs[0]))
534                         out = (ast_expression*)parser_const_float(parser, -ConstF(0));
535                     else
536                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
537                                                               (ast_expression*)parser_const_float_0(parser),
538                                                               exprs[0]);
539                     break;
540                 case TYPE_VECTOR:
541                     if (CanConstFold1(exprs[0]))
542                         out = (ast_expression*)parser_const_vector_f(parser,
543                             -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
544                     else
545                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
546                                                               (ast_expression*)parser_const_vector_0(parser),
547                                                               exprs[0]);
548                     break;
549                 default:
550                 parseerror(parser, "invalid types used in expression: cannot negate type %s",
551                            type_name[exprs[0]->expression.vtype]);
552                 return false;
553             }
554             break;
555
556         case opid2('!','P'):
557             switch (exprs[0]->expression.vtype) {
558                 case TYPE_FLOAT:
559                     if (CanConstFold1(exprs[0]))
560                         out = (ast_expression*)parser_const_float(parser, !ConstF(0));
561                     else
562                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
563                     break;
564                 case TYPE_VECTOR:
565                     if (CanConstFold1(exprs[0]))
566                         out = (ast_expression*)parser_const_float(parser,
567                             (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
568                     else
569                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
570                     break;
571                 case TYPE_STRING:
572                     if (CanConstFold1(exprs[0]))
573                         out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
574                     else
575                         out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
576                     break;
577                 /* we don't constant-fold NOT for these types */
578                 case TYPE_ENTITY:
579                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
580                     break;
581                 case TYPE_FUNCTION:
582                     out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
583                     break;
584                 default:
585                 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
586                            type_name[exprs[0]->expression.vtype]);
587                 return false;
588             }
589             break;
590
591         case opid1('+'):
592             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
593                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
594             {
595                 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
596                            type_name[exprs[0]->expression.vtype],
597                            type_name[exprs[1]->expression.vtype]);
598                 return false;
599             }
600             switch (exprs[0]->expression.vtype) {
601                 case TYPE_FLOAT:
602                     if (CanConstFold(exprs[0], exprs[1]))
603                     {
604                         out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
605                     }
606                     else
607                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
608                     break;
609                 case TYPE_VECTOR:
610                     if (CanConstFold(exprs[0], exprs[1]))
611                         out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
612                     else
613                         out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
614                     break;
615                 default:
616                     parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
617                                type_name[exprs[0]->expression.vtype],
618                                type_name[exprs[1]->expression.vtype]);
619                     return false;
620             };
621             break;
622         case opid1('-'):
623             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
624                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
625             {
626                 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
627                            type_name[exprs[1]->expression.vtype],
628                            type_name[exprs[0]->expression.vtype]);
629                 return false;
630             }
631             switch (exprs[0]->expression.vtype) {
632                 case TYPE_FLOAT:
633                     if (CanConstFold(exprs[0], exprs[1]))
634                         out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
635                     else
636                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
637                     break;
638                 case TYPE_VECTOR:
639                     if (CanConstFold(exprs[0], exprs[1]))
640                         out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
641                     else
642                         out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
643                     break;
644                 default:
645                     parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
646                                type_name[exprs[1]->expression.vtype],
647                                type_name[exprs[0]->expression.vtype]);
648                     return false;
649             };
650             break;
651         case opid1('*'):
652             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
653                 exprs[0]->expression.vtype != TYPE_VECTOR &&
654                 exprs[0]->expression.vtype != TYPE_FLOAT &&
655                 exprs[1]->expression.vtype != TYPE_VECTOR &&
656                 exprs[1]->expression.vtype != TYPE_FLOAT)
657             {
658                 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
659                            type_name[exprs[1]->expression.vtype],
660                            type_name[exprs[0]->expression.vtype]);
661                 return false;
662             }
663             switch (exprs[0]->expression.vtype) {
664                 case TYPE_FLOAT:
665                     if (exprs[1]->expression.vtype == TYPE_VECTOR)
666                     {
667                         if (CanConstFold(exprs[0], exprs[1]))
668                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
669                         else
670                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
671                     }
672                     else
673                     {
674                         if (CanConstFold(exprs[0], exprs[1]))
675                             out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
676                         else
677                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
678                     }
679                     break;
680                 case TYPE_VECTOR:
681                     if (exprs[1]->expression.vtype == TYPE_FLOAT)
682                     {
683                         if (CanConstFold(exprs[0], exprs[1]))
684                             out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
685                         else
686                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
687                     }
688                     else
689                     {
690                         if (CanConstFold(exprs[0], exprs[1]))
691                             out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
692                         else
693                             out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
694                     }
695                     break;
696                 default:
697                     parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
698                                type_name[exprs[1]->expression.vtype],
699                                type_name[exprs[0]->expression.vtype]);
700                     return false;
701             };
702             break;
703         case opid1('/'):
704             if (NotSameType(TYPE_FLOAT)) {
705                 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
706                            type_name[exprs[0]->expression.vtype],
707                            type_name[exprs[1]->expression.vtype]);
708                 return false;
709             }
710             if (CanConstFold(exprs[0], exprs[1]))
711                 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
712             else
713                 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
714             break;
715         case opid1('%'):
716         case opid2('%','='):
717             parseerror(parser, "qc does not have a modulo operator");
718             return false;
719         case opid1('|'):
720         case opid1('&'):
721             if (NotSameType(TYPE_FLOAT)) {
722                 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
723                            type_name[exprs[0]->expression.vtype],
724                            type_name[exprs[1]->expression.vtype]);
725                 return false;
726             }
727             if (CanConstFold(exprs[0], exprs[1]))
728                 out = (ast_expression*)parser_const_float(parser,
729                     (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
730                                             (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
731             else
732                 out = (ast_expression*)ast_binary_new(ctx,
733                     (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
734                     exprs[0], exprs[1]);
735             break;
736         case opid1('^'):
737             parseerror(parser, "TODO: bitxor");
738             return false;
739
740         case opid2('<','<'):
741         case opid2('>','>'):
742         case opid3('<','<','='):
743         case opid3('>','>','='):
744             parseerror(parser, "TODO: shifts");
745             return false;
746
747         case opid2('|','|'):
748             generated_op += 1; /* INSTR_OR */
749         case opid2('&','&'):
750             generated_op += INSTR_AND;
751             if (NotSameType(TYPE_FLOAT)) {
752                 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
753                            type_name[exprs[0]->expression.vtype],
754                            type_name[exprs[1]->expression.vtype]);
755                 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
756                 parseerror(parser, "TODO: optional early out");
757                 return false;
758             }
759             if (opts_standard == COMPILER_GMQCC)
760                 con_out("TODO: early out logic\n");
761             if (CanConstFold(exprs[0], exprs[1]))
762                 out = (ast_expression*)parser_const_float(parser,
763                     (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
764             else
765                 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
766             break;
767
768         case opid2('?',':'):
769             if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
770                 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
771                 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
772                 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
773                 return false;
774             }
775             if (CanConstFold1(exprs[0]))
776                 out = (ConstF(0) ? exprs[1] : exprs[2]);
777             else
778                 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
779             break;
780
781         case opid1('>'):
782             generated_op += 1; /* INSTR_GT */
783         case opid1('<'):
784             generated_op += 1; /* INSTR_LT */
785         case opid2('>', '='):
786             generated_op += 1; /* INSTR_GE */
787         case opid2('<', '='):
788             generated_op += INSTR_LE;
789             if (NotSameType(TYPE_FLOAT)) {
790                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
791                            type_name[exprs[0]->expression.vtype],
792                            type_name[exprs[1]->expression.vtype]);
793                 return false;
794             }
795             out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
796             break;
797         case opid2('!', '='):
798             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
799                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
800                            type_name[exprs[0]->expression.vtype],
801                            type_name[exprs[1]->expression.vtype]);
802                 return false;
803             }
804             out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
805             break;
806         case opid2('=', '='):
807             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
808                 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
809                            type_name[exprs[0]->expression.vtype],
810                            type_name[exprs[1]->expression.vtype]);
811                 return false;
812             }
813             out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
814             break;
815
816         case opid1('='):
817             if (ast_istype(exprs[0], ast_entfield)) {
818                 ast_expression *field = ((ast_entfield*)exprs[0])->field;
819                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
820                     exprs[0]->expression.vtype == TYPE_FIELD &&
821                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
822                 {
823                     assignop = type_storep_instr[TYPE_VECTOR];
824                 }
825                 else
826                     assignop = type_storep_instr[exprs[0]->expression.vtype];
827                 if (!ast_compare_type(field->expression.next, exprs[1])) {
828                     ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
829                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
830                     if (opts_standard == COMPILER_QCC &&
831                         field->expression.next->expression.vtype == TYPE_FUNCTION &&
832                         exprs[1]->expression.vtype == TYPE_FUNCTION)
833                     {
834                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
835                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
836                         {
837                             parser->errors++;
838                         }
839                     }
840                     else
841                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
842                 }
843             }
844             else
845             {
846                 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
847                     exprs[0]->expression.vtype == TYPE_FIELD &&
848                     exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
849                 {
850                     assignop = type_store_instr[TYPE_VECTOR];
851                 }
852                 else {
853                     assignop = type_store_instr[exprs[0]->expression.vtype];
854                 }
855
856                 if (assignop == AINSTR_END) {
857                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
858                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
859                     parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
860                 }
861                 else if (!ast_compare_type(exprs[0], exprs[1])) {
862                     ast_type_to_string(exprs[0], ty1, sizeof(ty1));
863                     ast_type_to_string(exprs[1], ty2, sizeof(ty2));
864                     if (opts_standard == COMPILER_QCC &&
865                         exprs[0]->expression.vtype == TYPE_FUNCTION &&
866                         exprs[1]->expression.vtype == TYPE_FUNCTION)
867                     {
868                         if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
869                                          "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
870                         {
871                             parser->errors++;
872                         }
873                     }
874                     else
875                         parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
876                 }
877             }
878             out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
879             break;
880         case opid2('+','='):
881         case opid2('-','='):
882             if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
883                 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
884             {
885                 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
886                            type_name[exprs[0]->expression.vtype],
887                            type_name[exprs[1]->expression.vtype]);
888                 return false;
889             }
890             if (ast_istype(exprs[0], ast_entfield))
891                 assignop = type_storep_instr[exprs[0]->expression.vtype];
892             else
893                 assignop = type_store_instr[exprs[0]->expression.vtype];
894             switch (exprs[0]->expression.vtype) {
895                 case TYPE_FLOAT:
896                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
897                                                             (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
898                                                             exprs[0], exprs[1]);
899                     break;
900                 case TYPE_VECTOR:
901                     out = (ast_expression*)ast_binstore_new(ctx, assignop,
902                                                             (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
903                                                             exprs[0], exprs[1]);
904                     break;
905                 default:
906                     parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
907                                type_name[exprs[0]->expression.vtype],
908                                type_name[exprs[1]->expression.vtype]);
909                     return false;
910             };
911             break;
912     }
913 #undef NotSameType
914
915     if (!out) {
916         parseerror(parser, "failed to apply operand %s", op->op);
917         return false;
918     }
919
920     DEBUGSHUNTDO(con_out("applied %s\n", op->op));
921     vec_push(sy->out, syexp(ctx, out));
922     return true;
923 }
924
925 static bool parser_close_call(parser_t *parser, shunt *sy)
926 {
927     /* was a function call */
928     ast_expression *fun;
929     ast_call       *call;
930
931     size_t          fid;
932     size_t          paramcount;
933
934     vec_shrinkby(sy->ops, 1);
935     fid = sy->ops[vec_size(sy->ops)].off;
936
937     /* out[fid] is the function
938      * everything above is parameters...
939      * 0 params = nothing
940      * 1 params = ast_expression
941      * more = ast_block
942      */
943
944     if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
945         parseerror(parser, "internal error: function call needs function and parameter list...");
946         return false;
947     }
948
949     fun = sy->out[fid].out;
950
951     call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
952     if (!call) {
953         parseerror(parser, "out of memory");
954         return false;
955     }
956
957     if (fid+1 == vec_size(sy->out)) {
958         /* no arguments */
959         paramcount = 0;
960     } else if (fid+2 == vec_size(sy->out)) {
961         ast_block *params;
962         vec_shrinkby(sy->out, 1);
963         params = sy->out[vec_size(sy->out)].block;
964         if (!params) {
965             /* 1 param */
966             paramcount = 1;
967             vec_push(call->params, sy->out[vec_size(sy->out)].out);
968         } else {
969             paramcount = vec_size(params->exprs);
970             call->params = params->exprs;
971             params->exprs = NULL;
972             ast_delete(params);
973         }
974         if (!ast_call_check_types(call))
975             parser->errors++;
976     } else {
977         parseerror(parser, "invalid function call");
978         return false;
979     }
980
981     /* overwrite fid, the function, with a call */
982     sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
983
984     if (fun->expression.vtype != TYPE_FUNCTION) {
985         parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
986         return false;
987     }
988
989     if (!fun->expression.next) {
990         parseerror(parser, "could not determine function return type");
991         return false;
992     } else {
993         if (vec_size(fun->expression.params) != paramcount &&
994             !(fun->expression.variadic &&
995               vec_size(fun->expression.params) < paramcount))
996         {
997             ast_value *fval;
998             const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
999
1000             fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1001             if (opts_standard == COMPILER_GMQCC)
1002             {
1003                 if (fval)
1004                     parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1005                                " -> `%s` has been declared here: %s:%i",
1006                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1007                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1008                 else
1009                     parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1010                                " -> `%s` has been declared here: %s:%i",
1011                                fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1012                                fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1013                 return false;
1014             }
1015             else
1016             {
1017                 if (fval)
1018                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1019                                          "too %s parameters for call to %s: expected %i, got %i\n"
1020                                          " -> `%s` has been declared here: %s:%i",
1021                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1022                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1023                 else
1024                     return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1025                                          "too %s parameters for function call: expected %i, got %i\n"
1026                                          " -> `%s` has been declared here: %s:%i",
1027                                          fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1028                                          fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1029             }
1030         }
1031     }
1032
1033     return true;
1034 }
1035
1036 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1037 {
1038     if (!vec_size(sy->ops)) {
1039         parseerror(parser, "unmatched closing paren");
1040         return false;
1041     }
1042     /* this would for bit a + (x) because there are no operators inside (x)
1043     if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1044         parseerror(parser, "empty parenthesis expression");
1045         return false;
1046     }
1047     */
1048     while (vec_size(sy->ops)) {
1049         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1050             if (!parser_close_call(parser, sy))
1051                 return false;
1052             break;
1053         }
1054         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1055             vec_shrinkby(sy->ops, 1);
1056             return !functions_only;
1057         }
1058         if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1059             if (functions_only)
1060                 return false;
1061             /* pop off the parenthesis */
1062             vec_shrinkby(sy->ops, 1);
1063             /* then apply the index operator */
1064             if (!parser_sy_pop(parser, sy))
1065                 return false;
1066             return true;
1067         }
1068         if (!parser_sy_pop(parser, sy))
1069             return false;
1070     }
1071     return true;
1072 }
1073
1074 static void parser_reclassify_token(parser_t *parser)
1075 {
1076     size_t i;
1077     for (i = 0; i < operator_count; ++i) {
1078         if (!strcmp(parser_tokval(parser), operators[i].op)) {
1079             parser->tok = TOKEN_OPERATOR;
1080             return;
1081         }
1082     }
1083 }
1084
1085 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1086 {
1087     ast_expression *expr = NULL;
1088     shunt sy;
1089     bool wantop = false;
1090     bool gotmemberof = false;
1091
1092     /* count the parens because an if starts with one, so the
1093      * end of a condition is an unmatched closing paren
1094      */
1095     int parens = 0;
1096     int ternaries = 0;
1097
1098     sy.out = NULL;
1099     sy.ops = NULL;
1100
1101     parser->lex->flags.noops = false;
1102
1103     parser_reclassify_token(parser);
1104
1105     while (true)
1106     {
1107         if (gotmemberof)
1108             gotmemberof = false;
1109         else
1110             parser->memberof = 0;
1111
1112         if (parser->tok == TOKEN_IDENT)
1113         {
1114             ast_expression *var;
1115             if (wantop) {
1116                 parseerror(parser, "expected operator or end of statement");
1117                 goto onerr;
1118             }
1119             wantop = true;
1120             /* variable */
1121             if (opts_standard == COMPILER_GMQCC)
1122             {
1123                 if (parser->memberof == TYPE_ENTITY) {
1124                     /* still get vars first since there could be a fieldpointer */
1125                     var = parser_find_var(parser, parser_tokval(parser));
1126                     if (!var)
1127                         var = parser_find_field(parser, parser_tokval(parser));
1128                 }
1129                 else if (parser->memberof == TYPE_VECTOR)
1130                 {
1131                     parseerror(parser, "TODO: implement effective vector member access");
1132                     goto onerr;
1133                 }
1134                 else if (parser->memberof) {
1135                     parseerror(parser, "namespace for member not found");
1136                     goto onerr;
1137                 }
1138                 else
1139                     var = parser_find_var(parser, parser_tokval(parser));
1140             } else {
1141                 var = parser_find_var(parser, parser_tokval(parser));
1142                 if (!var)
1143                     var = parser_find_field(parser, parser_tokval(parser));
1144             }
1145             if (!var) {
1146                 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1147                 goto onerr;
1148             }
1149             if (ast_istype(var, ast_value))
1150                 ((ast_value*)var)->uses++;
1151             vec_push(sy.out, syexp(parser_ctx(parser), var));
1152             DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1153         }
1154         else if (parser->tok == TOKEN_FLOATCONST) {
1155             ast_value *val;
1156             if (wantop) {
1157                 parseerror(parser, "expected operator or end of statement, got constant");
1158                 goto onerr;
1159             }
1160             wantop = true;
1161             val = parser_const_float(parser, (parser_token(parser)->constval.f));
1162             if (!val)
1163                 return false;
1164             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1165             DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1166         }
1167         else if (parser->tok == TOKEN_INTCONST) {
1168             ast_value *val;
1169             if (wantop) {
1170                 parseerror(parser, "expected operator or end of statement, got constant");
1171                 goto onerr;
1172             }
1173             wantop = true;
1174             val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1175             if (!val)
1176                 return false;
1177             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1178             DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1179         }
1180         else if (parser->tok == TOKEN_STRINGCONST) {
1181             ast_value *val;
1182             if (wantop) {
1183                 parseerror(parser, "expected operator or end of statement, got constant");
1184                 goto onerr;
1185             }
1186             wantop = true;
1187             val = parser_const_string(parser, parser_tokval(parser));
1188             if (!val)
1189                 return false;
1190             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1191             DEBUGSHUNTDO(con_out("push string\n"));
1192         }
1193         else if (parser->tok == TOKEN_VECTORCONST) {
1194             ast_value *val;
1195             if (wantop) {
1196                 parseerror(parser, "expected operator or end of statement, got constant");
1197                 goto onerr;
1198             }
1199             wantop = true;
1200             val = parser_const_vector(parser, parser_token(parser)->constval.v);
1201             if (!val)
1202                 return false;
1203             vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1204             DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1205                                 parser_token(parser)->constval.v.x,
1206                                 parser_token(parser)->constval.v.y,
1207                                 parser_token(parser)->constval.v.z));
1208         }
1209         else if (parser->tok == '(') {
1210             parseerror(parser, "internal error: '(' should be classified as operator");
1211             goto onerr;
1212         }
1213         else if (parser->tok == '[') {
1214             parseerror(parser, "internal error: '[' should be classified as operator");
1215             goto onerr;
1216         }
1217         else if (parser->tok == ')') {
1218             if (wantop) {
1219                 DEBUGSHUNTDO(con_out("do[op] )\n"));
1220                 --parens;
1221                 if (parens < 0)
1222                     break;
1223                 /* we do expect an operator next */
1224                 /* closing an opening paren */
1225                 if (!parser_close_paren(parser, &sy, false))
1226                     goto onerr;
1227             } else {
1228                 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1229                 --parens;
1230                 if (parens < 0)
1231                     break;
1232                 /* allowed for function calls */
1233                 if (!parser_close_paren(parser, &sy, true))
1234                     goto onerr;
1235             }
1236             wantop = true;
1237         }
1238         else if (parser->tok == ']') {
1239             if (!wantop)
1240                 parseerror(parser, "operand expected");
1241             --parens;
1242             if (parens < 0)
1243                 break;
1244             if (!parser_close_paren(parser, &sy, false))
1245                 goto onerr;
1246             wantop = true;
1247         }
1248         else if (parser->tok != TOKEN_OPERATOR) {
1249             if (wantop) {
1250                 parseerror(parser, "expected operator or end of statement");
1251                 goto onerr;
1252             }
1253             break;
1254         }
1255         else
1256         {
1257             /* classify the operator */
1258             /* TODO: suffix operators */
1259             const oper_info *op;
1260             const oper_info *olast = NULL;
1261             size_t o;
1262             for (o = 0; o < operator_count; ++o) {
1263                 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1264                     !(operators[o].flags & OP_SUFFIX) && /* remove this */
1265                     !strcmp(parser_tokval(parser), operators[o].op))
1266                 {
1267                     break;
1268                 }
1269             }
1270             if (o == operator_count) {
1271                 /* no operator found... must be the end of the statement */
1272                 break;
1273             }
1274             /* found an operator */
1275             op = &operators[o];
1276
1277             /* when declaring variables, a comma starts a new variable */
1278             if (op->id == opid1(',') && !parens && stopatcomma) {
1279                 /* fixup the token */
1280                 parser->tok = ',';
1281                 break;
1282             }
1283
1284             /* a colon without a pervious question mark cannot be a ternary */
1285             if (!ternaries && op->id == opid2(':','?')) {
1286                 parser->tok = ':';
1287                 break;
1288             }
1289
1290             if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1291                 olast = &operators[vec_last(sy.ops).etype-1];
1292
1293             while (olast && (
1294                     (op->prec < olast->prec) ||
1295                     (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1296             {
1297                 if (!parser_sy_pop(parser, &sy))
1298                     goto onerr;
1299                 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1300                     olast = &operators[vec_last(sy.ops).etype-1];
1301                 else
1302                     olast = NULL;
1303             }
1304
1305             if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1306                 /* for gmqcc standard: open up the namespace of the previous type */
1307                 ast_expression *prevex = vec_last(sy.out).out;
1308                 if (!prevex) {
1309                     parseerror(parser, "unexpected member operator");
1310                     goto onerr;
1311                 }
1312                 if (prevex->expression.vtype == TYPE_ENTITY)
1313                     parser->memberof = TYPE_ENTITY;
1314                 else if (prevex->expression.vtype == TYPE_VECTOR)
1315                     parser->memberof = TYPE_VECTOR;
1316                 else {
1317                     parseerror(parser, "type error: type has no members");
1318                     goto onerr;
1319                 }
1320                 gotmemberof = true;
1321             }
1322
1323             if (op->id == opid1('(')) {
1324                 if (wantop) {
1325                     size_t sycount = vec_size(sy.out);
1326                     DEBUGSHUNTDO(con_out("push [op] (\n"));
1327                     ++parens;
1328                     /* we expected an operator, this is the function-call operator */
1329                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1330                 } else {
1331                     ++parens;
1332                     vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1333                     DEBUGSHUNTDO(con_out("push [nop] (\n"));
1334                 }
1335                 wantop = false;
1336             } else if (op->id == opid1('[')) {
1337                 if (!wantop) {
1338                     parseerror(parser, "unexpected array subscript");
1339                     goto onerr;
1340                 }
1341                 ++parens;
1342                 /* push both the operator and the paren, this makes life easier */
1343                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1344                 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1345                 wantop = false;
1346             } else if (op->id == opid2('?',':')) {
1347                 wantop = false;
1348                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1349                 wantop = false;
1350                 --ternaries;
1351             } else if (op->id == opid2(':','?')) {
1352                 /* we don't push this operator */
1353                 wantop = false;
1354                 ++ternaries;
1355             } else {
1356                 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1357                 vec_push(sy.ops, syop(parser_ctx(parser), op));
1358                 wantop = false;
1359             }
1360         }
1361         if (!parser_next(parser)) {
1362             goto onerr;
1363         }
1364         if (parser->tok == ';' ||
1365             (!parens && parser->tok == ']'))
1366         {
1367             break;
1368         }
1369     }
1370
1371     while (vec_size(sy.ops)) {
1372         if (!parser_sy_pop(parser, &sy))
1373             goto onerr;
1374     }
1375
1376     parser->lex->flags.noops = true;
1377     if (!vec_size(sy.out)) {
1378         parseerror(parser, "empty expression");
1379         expr = NULL;
1380     } else
1381         expr = sy.out[0].out;
1382     vec_free(sy.out);
1383     vec_free(sy.ops);
1384     DEBUGSHUNTDO(con_out("shunt done\n"));
1385     return expr;
1386
1387 onerr:
1388     parser->lex->flags.noops = true;
1389     vec_free(sy.out);
1390     vec_free(sy.ops);
1391     return NULL;
1392 }
1393
1394 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1395 {
1396     ast_expression *e = parse_expression_leave(parser, stopatcomma);
1397     if (!e)
1398         return NULL;
1399     if (!parser_next(parser)) {
1400         ast_delete(e);
1401         return NULL;
1402     }
1403     return e;
1404 }
1405
1406 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1407 {
1408     ast_ifthen *ifthen;
1409     ast_expression *cond, *ontrue, *onfalse = NULL;
1410     bool ifnot = false;
1411
1412     lex_ctx ctx = parser_ctx(parser);
1413
1414     (void)block; /* not touching */
1415
1416     /* skip the 'if', parse an optional 'not' and check for an opening paren */
1417     if (!parser_next(parser)) {
1418         parseerror(parser, "expected condition or 'not'");
1419         return false;
1420     }
1421     if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1422         ifnot = true;
1423         if (!parser_next(parser)) {
1424             parseerror(parser, "expected condition in parenthesis");
1425             return false;
1426         }
1427     }
1428     if (parser->tok != '(') {
1429         parseerror(parser, "expected 'if' condition in parenthesis");
1430         return false;
1431     }
1432     /* parse into the expression */
1433     if (!parser_next(parser)) {
1434         parseerror(parser, "expected 'if' condition after opening paren");
1435         return false;
1436     }
1437     /* parse the condition */
1438     cond = parse_expression_leave(parser, false);
1439     if (!cond)
1440         return false;
1441     /* closing paren */
1442     if (parser->tok != ')') {
1443         parseerror(parser, "expected closing paren after 'if' condition");
1444         ast_delete(cond);
1445         return false;
1446     }
1447     /* parse into the 'then' branch */
1448     if (!parser_next(parser)) {
1449         parseerror(parser, "expected statement for on-true branch of 'if'");
1450         ast_delete(cond);
1451         return false;
1452     }
1453     ontrue = parse_statement_or_block(parser);
1454     if (!ontrue) {
1455         ast_delete(cond);
1456         return false;
1457     }
1458     /* check for an else */
1459     if (!strcmp(parser_tokval(parser), "else")) {
1460         /* parse into the 'else' branch */
1461         if (!parser_next(parser)) {
1462             parseerror(parser, "expected on-false branch after 'else'");
1463             ast_delete(ontrue);
1464             ast_delete(cond);
1465             return false;
1466         }
1467         onfalse = parse_statement_or_block(parser);
1468         if (!onfalse) {
1469             ast_delete(ontrue);
1470             ast_delete(cond);
1471             return false;
1472         }
1473     }
1474
1475     if (ifnot)
1476         ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1477     else
1478         ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1479     *out = (ast_expression*)ifthen;
1480     return true;
1481 }
1482
1483 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1484 {
1485     ast_loop *aloop;
1486     ast_expression *cond, *ontrue;
1487
1488     lex_ctx ctx = parser_ctx(parser);
1489
1490     (void)block; /* not touching */
1491
1492     /* skip the 'while' and check for opening paren */
1493     if (!parser_next(parser) || parser->tok != '(') {
1494         parseerror(parser, "expected 'while' condition in parenthesis");
1495         return false;
1496     }
1497     /* parse into the expression */
1498     if (!parser_next(parser)) {
1499         parseerror(parser, "expected 'while' condition after opening paren");
1500         return false;
1501     }
1502     /* parse the condition */
1503     cond = parse_expression_leave(parser, false);
1504     if (!cond)
1505         return false;
1506     /* closing paren */
1507     if (parser->tok != ')') {
1508         parseerror(parser, "expected closing paren after 'while' condition");
1509         ast_delete(cond);
1510         return false;
1511     }
1512     /* parse into the 'then' branch */
1513     if (!parser_next(parser)) {
1514         parseerror(parser, "expected while-loop body");
1515         ast_delete(cond);
1516         return false;
1517     }
1518     ontrue = parse_statement_or_block(parser);
1519     if (!ontrue) {
1520         ast_delete(cond);
1521         return false;
1522     }
1523
1524     aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1525     *out = (ast_expression*)aloop;
1526     return true;
1527 }
1528
1529 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1530 {
1531     ast_loop *aloop;
1532     ast_expression *cond, *ontrue;
1533
1534     lex_ctx ctx = parser_ctx(parser);
1535
1536     (void)block; /* not touching */
1537
1538     /* skip the 'do' and get the body */
1539     if (!parser_next(parser)) {
1540         parseerror(parser, "expected loop body");
1541         return false;
1542     }
1543     ontrue = parse_statement_or_block(parser);
1544     if (!ontrue)
1545         return false;
1546
1547     /* expect the "while" */
1548     if (parser->tok != TOKEN_KEYWORD ||
1549         strcmp(parser_tokval(parser), "while"))
1550     {
1551         parseerror(parser, "expected 'while' and condition");
1552         ast_delete(ontrue);
1553         return false;
1554     }
1555
1556     /* skip the 'while' and check for opening paren */
1557     if (!parser_next(parser) || parser->tok != '(') {
1558         parseerror(parser, "expected 'while' condition in parenthesis");
1559         ast_delete(ontrue);
1560         return false;
1561     }
1562     /* parse into the expression */
1563     if (!parser_next(parser)) {
1564         parseerror(parser, "expected 'while' condition after opening paren");
1565         ast_delete(ontrue);
1566         return false;
1567     }
1568     /* parse the condition */
1569     cond = parse_expression_leave(parser, false);
1570     if (!cond)
1571         return false;
1572     /* closing paren */
1573     if (parser->tok != ')') {
1574         parseerror(parser, "expected closing paren after 'while' condition");
1575         ast_delete(ontrue);
1576         ast_delete(cond);
1577         return false;
1578     }
1579     /* parse on */
1580     if (!parser_next(parser) || parser->tok != ';') {
1581         parseerror(parser, "expected semicolon after condition");
1582         ast_delete(ontrue);
1583         ast_delete(cond);
1584         return false;
1585     }
1586
1587     if (!parser_next(parser)) {
1588         parseerror(parser, "parse error");
1589         ast_delete(ontrue);
1590         ast_delete(cond);
1591         return false;
1592     }
1593
1594     aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1595     *out = (ast_expression*)aloop;
1596     return true;
1597 }
1598
1599 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1600 {
1601     ast_loop *aloop;
1602     ast_expression *initexpr, *cond, *increment, *ontrue;
1603     size_t oldblocklocal;
1604     bool   retval = true;
1605
1606     lex_ctx ctx = parser_ctx(parser);
1607
1608     oldblocklocal = parser->blocklocal;
1609     parser->blocklocal = vec_size(parser->locals);
1610
1611     initexpr  = NULL;
1612     cond      = NULL;
1613     increment = NULL;
1614     ontrue    = NULL;
1615
1616     /* skip the 'while' and check for opening paren */
1617     if (!parser_next(parser) || parser->tok != '(') {
1618         parseerror(parser, "expected 'for' expressions in parenthesis");
1619         goto onerr;
1620     }
1621     /* parse into the expression */
1622     if (!parser_next(parser)) {
1623         parseerror(parser, "expected 'for' initializer after opening paren");
1624         goto onerr;
1625     }
1626
1627     if (parser->tok == TOKEN_TYPENAME) {
1628         if (opts_standard != COMPILER_GMQCC) {
1629             if (parsewarning(parser, WARN_EXTENSIONS,
1630                              "current standard does not allow variable declarations in for-loop initializers"))
1631                 goto onerr;
1632         }
1633
1634         parseerror(parser, "TODO: assignment of new variables to be non-const");
1635         goto onerr;
1636         if (!parse_variable(parser, block, true))
1637             goto onerr;
1638     }
1639     else if (parser->tok != ';')
1640     {
1641         initexpr = parse_expression_leave(parser, false);
1642         if (!initexpr)
1643             goto onerr;
1644     }
1645
1646     /* move on to condition */
1647     if (parser->tok != ';') {
1648         parseerror(parser, "expected semicolon after for-loop initializer");
1649         goto onerr;
1650     }
1651     if (!parser_next(parser)) {
1652         parseerror(parser, "expected for-loop condition");
1653         goto onerr;
1654     }
1655
1656     /* parse the condition */
1657     if (parser->tok != ';') {
1658         cond = parse_expression_leave(parser, false);
1659         if (!cond)
1660             goto onerr;
1661     }
1662
1663     /* move on to incrementor */
1664     if (parser->tok != ';') {
1665         parseerror(parser, "expected semicolon after for-loop initializer");
1666         goto onerr;
1667     }
1668     if (!parser_next(parser)) {
1669         parseerror(parser, "expected for-loop condition");
1670         goto onerr;
1671     }
1672
1673     /* parse the incrementor */
1674     if (parser->tok != ')') {
1675         increment = parse_expression_leave(parser, false);
1676         if (!increment)
1677             goto onerr;
1678         if (!ast_istype(increment, ast_store) &&
1679             !ast_istype(increment, ast_call) &&
1680             !ast_istype(increment, ast_binstore))
1681         {
1682             if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1683                 goto onerr;
1684         }
1685     }
1686
1687     /* closing paren */
1688     if (parser->tok != ')') {
1689         parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1690         goto onerr;
1691     }
1692     /* parse into the 'then' branch */
1693     if (!parser_next(parser)) {
1694         parseerror(parser, "expected for-loop body");
1695         goto onerr;
1696     }
1697     ontrue = parse_statement_or_block(parser);
1698     if (!ontrue) {
1699         goto onerr;
1700     }
1701
1702     aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1703     *out = (ast_expression*)aloop;
1704
1705     while (vec_size(parser->locals) > parser->blocklocal)
1706         retval = retval && parser_pop_local(parser);
1707     parser->blocklocal = oldblocklocal;
1708     return retval;
1709 onerr:
1710     if (initexpr)  ast_delete(initexpr);
1711     if (cond)      ast_delete(cond);
1712     if (increment) ast_delete(increment);
1713     while (vec_size(parser->locals) > parser->blocklocal)
1714         (void)!parser_pop_local(parser);
1715     parser->blocklocal = oldblocklocal;
1716     return false;
1717 }
1718
1719 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1720 {
1721     ast_expression *exp = NULL;
1722     ast_return     *ret = NULL;
1723     ast_value      *expected = parser->function->vtype;
1724
1725     (void)block; /* not touching */
1726
1727     if (!parser_next(parser)) {
1728         parseerror(parser, "expected return expression");
1729         return false;
1730     }
1731
1732     if (parser->tok != ';') {
1733         exp = parse_expression(parser, false);
1734         if (!exp)
1735             return false;
1736
1737         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1738             parseerror(parser, "return with invalid expression");
1739         }
1740
1741         ret = ast_return_new(exp->expression.node.context, exp);
1742         if (!ret) {
1743             ast_delete(exp);
1744             return false;
1745         }
1746     } else {
1747         if (!parser_next(parser))
1748             parseerror(parser, "parse error");
1749         if (expected->expression.next->expression.vtype != TYPE_VOID) {
1750             if (opts_standard != COMPILER_GMQCC)
1751                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1752             else
1753                 parseerror(parser, "return without value");
1754         }
1755         ret = ast_return_new(parser_ctx(parser), NULL);
1756     }
1757     *out = (ast_expression*)ret;
1758     return true;
1759 }
1760
1761 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1762 {
1763     lex_ctx ctx = parser_ctx(parser);
1764
1765     (void)block; /* not touching */
1766
1767     if (!parser_next(parser) || parser->tok != ';') {
1768         parseerror(parser, "expected semicolon");
1769         return false;
1770     }
1771
1772     if (!parser_next(parser))
1773         parseerror(parser, "parse error");
1774
1775     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1776     return true;
1777 }
1778
1779 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
1780 {
1781     ast_expression *operand;
1782     ast_value      *opval;
1783     ast_switch     *switchnode;
1784     ast_switch_case swcase;
1785
1786     lex_ctx ctx = parser_ctx(parser);
1787
1788     (void)block; /* not touching */
1789
1790     /* parse over the opening paren */
1791     if (!parser_next(parser) || parser->tok != '(') {
1792         parseerror(parser, "expected switch operand in parenthesis");
1793         return false;
1794     }
1795
1796     /* parse into the expression */
1797     if (!parser_next(parser)) {
1798         parseerror(parser, "expected switch operand");
1799         return false;
1800     }
1801     /* parse the operand */
1802     operand = parse_expression_leave(parser, false);
1803     if (!operand)
1804         return false;
1805
1806     if (!OPTS_FLAG(RELAXED_SWITCH)) {
1807         opval = (ast_value*)operand;
1808         if (!ast_istype(operand, ast_value) || !opval->isconst) {
1809             parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
1810             ast_unref(operand);
1811             return false;
1812         }
1813     }
1814
1815     switchnode = ast_switch_new(ctx, operand);
1816
1817     /* closing paren */
1818     if (parser->tok != ')') {
1819         ast_delete(switchnode);
1820         parseerror(parser, "expected closing paren after 'switch' operand");
1821         return false;
1822     }
1823
1824     /* parse over the opening paren */
1825     if (!parser_next(parser) || parser->tok != '{') {
1826         ast_delete(switchnode);
1827         parseerror(parser, "expected list of cases");
1828         return false;
1829     }
1830
1831     if (!parser_next(parser)) {
1832         ast_delete(switchnode);
1833         parseerror(parser, "expected 'case' or 'default'");
1834         return false;
1835     }
1836
1837     /* case list! */
1838     while (parser->tok != '}') {
1839         ast_block *caseblock;
1840
1841         if (parser->tok != TOKEN_KEYWORD) {
1842             ast_delete(switchnode);
1843             parseerror(parser, "expected 'case' or 'default'");
1844             return false;
1845         }
1846         if (!strcmp(parser_tokval(parser), "case")) {
1847             if (!parser_next(parser)) {
1848                 ast_delete(switchnode);
1849                 parseerror(parser, "expected expression for case");
1850                 return false;
1851             }
1852             swcase.value = parse_expression_leave(parser, false);
1853             if (!swcase.value) {
1854                 ast_delete(switchnode);
1855                 parseerror(parser, "expected expression for case");
1856                 return false;
1857             }
1858         }
1859         else if (!strcmp(parser_tokval(parser), "default")) {
1860             swcase.value = NULL;
1861             if (!parser_next(parser)) {
1862                 ast_delete(switchnode);
1863                 parseerror(parser, "expected colon");
1864                 return false;
1865             }
1866         }
1867
1868         /* Now the colon and body */
1869         if (parser->tok != ':') {
1870             if (swcase.value) ast_unref(swcase.value);
1871             ast_delete(switchnode);
1872             parseerror(parser, "expected colon");
1873             return false;
1874         }
1875
1876         if (!parser_next(parser)) {
1877             if (swcase.value) ast_unref(swcase.value);
1878             ast_delete(switchnode);
1879             parseerror(parser, "expected statements or case");
1880             return false;
1881         }
1882         caseblock = ast_block_new(parser_ctx(parser));
1883         if (!caseblock) {
1884             if (swcase.value) ast_unref(swcase.value);
1885             ast_delete(switchnode);
1886             return false;
1887         }
1888         swcase.code = (ast_expression*)caseblock;
1889         vec_push(switchnode->cases, swcase);
1890         while (true) {
1891             ast_expression *expr;
1892             if (parser->tok == '}')
1893                 break;
1894             if (parser->tok == TOKEN_KEYWORD) {
1895                 if (!strcmp(parser_tokval(parser), "case") ||
1896                     !strcmp(parser_tokval(parser), "default"))
1897                 {
1898                     break;
1899                 }
1900             }
1901             if (!parse_statement(parser, caseblock, &expr, true)) {
1902                 ast_delete(switchnode);
1903                 return false;
1904             }
1905             if (!expr)
1906                 continue;
1907             vec_push(caseblock->exprs, expr);
1908         }
1909     }
1910
1911     /* closing paren */
1912     if (parser->tok != '}') {
1913         ast_delete(switchnode);
1914         parseerror(parser, "expected closing paren of case list");
1915         return false;
1916     }
1917     if (!parser_next(parser)) {
1918         ast_delete(switchnode);
1919         parseerror(parser, "parse error after switch");
1920         return false;
1921     }
1922     *out = (ast_expression*)switchnode;
1923     return true;
1924 }
1925
1926 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
1927 {
1928     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1929     {
1930         /* local variable */
1931         if (!block) {
1932             parseerror(parser, "cannot declare a variable from here");
1933             return false;
1934         }
1935         if (opts_standard == COMPILER_QCC) {
1936             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1937                 return false;
1938         }
1939         if (!parse_variable(parser, block, false))
1940             return false;
1941         *out = NULL;
1942         return true;
1943     }
1944     else if (parser->tok == TOKEN_KEYWORD)
1945     {
1946         if (!strcmp(parser_tokval(parser), "local"))
1947         {
1948             if (!block) {
1949                 parseerror(parser, "cannot declare a local variable here");
1950                 return false;
1951             }
1952             if (!parser_next(parser)) {
1953                 parseerror(parser, "expected variable declaration");
1954                 return false;
1955             }
1956             if (!parse_variable(parser, block, true))
1957                 return false;
1958             *out = NULL;
1959             return true;
1960         }
1961         else if (!strcmp(parser_tokval(parser), "return"))
1962         {
1963             return parse_return(parser, block, out);
1964         }
1965         else if (!strcmp(parser_tokval(parser), "if"))
1966         {
1967             return parse_if(parser, block, out);
1968         }
1969         else if (!strcmp(parser_tokval(parser), "while"))
1970         {
1971             return parse_while(parser, block, out);
1972         }
1973         else if (!strcmp(parser_tokval(parser), "do"))
1974         {
1975             return parse_dowhile(parser, block, out);
1976         }
1977         else if (!strcmp(parser_tokval(parser), "for"))
1978         {
1979             if (opts_standard == COMPILER_QCC) {
1980                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1981                     return false;
1982             }
1983             return parse_for(parser, block, out);
1984         }
1985         else if (!strcmp(parser_tokval(parser), "break"))
1986         {
1987             return parse_break_continue(parser, block, out, false);
1988         }
1989         else if (!strcmp(parser_tokval(parser), "continue"))
1990         {
1991             return parse_break_continue(parser, block, out, true);
1992         }
1993         else if (!strcmp(parser_tokval(parser), "switch"))
1994         {
1995             return parse_switch(parser, block, out);
1996         }
1997         else if (!strcmp(parser_tokval(parser), "case") ||
1998                  !strcmp(parser_tokval(parser), "default"))
1999         {
2000             if (!allow_cases) {
2001                 parseerror(parser, "unexpected 'case' label");
2002                 return false;
2003             }
2004             return true;
2005         }
2006         parseerror(parser, "Unexpected keyword");
2007         return false;
2008     }
2009     else if (parser->tok == '{')
2010     {
2011         ast_block *inner;
2012         inner = parse_block(parser, false);
2013         if (!inner)
2014             return false;
2015         *out = (ast_expression*)inner;
2016         return true;
2017     }
2018     else
2019     {
2020         ast_expression *exp = parse_expression(parser, false);
2021         if (!exp)
2022             return false;
2023         *out = exp;
2024         if (!ast_istype(exp, ast_store) &&
2025             !ast_istype(exp, ast_call) &&
2026             !ast_istype(exp, ast_binstore))
2027         {
2028             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2029                 return false;
2030         }
2031         return true;
2032     }
2033 }
2034
2035 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
2036 {
2037     bool rv = true;
2038     varentry_t *ve;
2039
2040     ve = &vec_last(parser->locals);
2041     if (!parser->errors) {
2042         if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
2043             if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
2044                 rv = false;
2045         }
2046     }
2047     mem_d(ve->name);
2048     vec_pop(parser->locals);
2049     return rv;
2050 }
2051
2052 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2053 {
2054     size_t oldblocklocal;
2055     bool   retval = true;
2056
2057     oldblocklocal = parser->blocklocal;
2058     parser->blocklocal = vec_size(parser->locals);
2059
2060     if (!parser_next(parser)) { /* skip the '{' */
2061         parseerror(parser, "expected function body");
2062         goto cleanup;
2063     }
2064
2065     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2066     {
2067         ast_expression *expr;
2068         if (parser->tok == '}')
2069             break;
2070
2071         if (!parse_statement(parser, block, &expr, false)) {
2072             /* parseerror(parser, "parse error"); */
2073             block = NULL;
2074             goto cleanup;
2075         }
2076         if (!expr)
2077             continue;
2078         vec_push(block->exprs, expr);
2079     }
2080
2081     if (parser->tok != '}') {
2082         block = NULL;
2083     } else {
2084         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2085         {
2086             if (!vec_size(block->exprs) ||
2087                 !ast_istype(vec_last(block->exprs), ast_return))
2088             {
2089                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2090                     block = NULL;
2091                     goto cleanup;
2092                 }
2093             }
2094         }
2095         (void)parser_next(parser);
2096     }
2097
2098 cleanup:
2099     while (vec_size(parser->locals) > parser->blocklocal)
2100         retval = retval && parser_pop_local(parser);
2101     parser->blocklocal = oldblocklocal;
2102     return !!block;
2103 }
2104
2105 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2106 {
2107     ast_block *block;
2108     block = ast_block_new(parser_ctx(parser));
2109     if (!block)
2110         return NULL;
2111     if (!parse_block_into(parser, block, warnreturn)) {
2112         ast_block_delete(block);
2113         return NULL;
2114     }
2115     return block;
2116 }
2117
2118 static ast_expression* parse_statement_or_block(parser_t *parser)
2119 {
2120     ast_expression *expr = NULL;
2121     if (parser->tok == '{')
2122         return (ast_expression*)parse_block(parser, false);
2123     if (!parse_statement(parser, NULL, &expr, false))
2124         return NULL;
2125     return expr;
2126 }
2127
2128 /* loop method */
2129 static bool create_vector_members(ast_value *var, varentry_t *ve)
2130 {
2131     size_t i;
2132     size_t len = strlen(var->name);
2133
2134     for (i = 0; i < 3; ++i) {
2135         ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
2136         if (!ve[i].var)
2137             break;
2138
2139         ve[i].name = (char*)mem_a(len+3);
2140         if (!ve[i].name) {
2141             ast_delete(ve[i].var);
2142             break;
2143         }
2144
2145         memcpy(ve[i].name, var->name, len);
2146         ve[i].name[len]   = '_';
2147         ve[i].name[len+1] = 'x'+i;
2148         ve[i].name[len+2] = 0;
2149     }
2150     if (i == 3)
2151         return true;
2152
2153     /* unroll */
2154     do {
2155         --i;
2156         mem_d(ve[i].name);
2157         ast_delete(ve[i].var);
2158         ve[i].name = NULL;
2159         ve[i].var  = NULL;
2160     } while (i);
2161     return false;
2162 }
2163
2164 static bool parse_function_body(parser_t *parser, ast_value *var)
2165 {
2166     ast_block      *block = NULL;
2167     ast_function   *func;
2168     ast_function   *old;
2169     size_t          parami;
2170
2171     ast_expression *framenum  = NULL;
2172     ast_expression *nextthink = NULL;
2173     /* None of the following have to be deleted */
2174     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2175     ast_expression *gbl_time = NULL, *gbl_self = NULL;
2176     bool            has_frame_think;
2177
2178     bool retval = true;
2179
2180     has_frame_think = false;
2181     old = parser->function;
2182
2183     if (var->expression.variadic) {
2184         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2185                          "variadic function with implementation will not be able to access additional parameters"))
2186         {
2187             return false;
2188         }
2189     }
2190
2191     if (parser->tok == '[') {
2192         /* got a frame definition: [ framenum, nextthink ]
2193          * this translates to:
2194          * self.frame = framenum;
2195          * self.nextthink = time + 0.1;
2196          * self.think = nextthink;
2197          */
2198         nextthink = NULL;
2199
2200         fld_think     = parser_find_field(parser, "think");
2201         fld_nextthink = parser_find_field(parser, "nextthink");
2202         fld_frame     = parser_find_field(parser, "frame");
2203         if (!fld_think || !fld_nextthink || !fld_frame) {
2204             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2205             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2206             return false;
2207         }
2208         gbl_time      = parser_find_global(parser, "time");
2209         gbl_self      = parser_find_global(parser, "self");
2210         if (!gbl_time || !gbl_self) {
2211             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2212             parseerror(parser, "please declare the following globals: `time`, `self`");
2213             return false;
2214         }
2215
2216         if (!parser_next(parser))
2217             return false;
2218
2219         framenum = parse_expression_leave(parser, true);
2220         if (!framenum) {
2221             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2222             return false;
2223         }
2224         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2225             ast_unref(framenum);
2226             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2227             return false;
2228         }
2229
2230         if (parser->tok != ',') {
2231             ast_unref(framenum);
2232             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2233             parseerror(parser, "Got a %i\n", parser->tok);
2234             return false;
2235         }
2236
2237         if (!parser_next(parser)) {
2238             ast_unref(framenum);
2239             return false;
2240         }
2241
2242         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2243         {
2244             /* qc allows the use of not-yet-declared functions here
2245              * - this automatically creates a prototype */
2246             varentry_t      varent;
2247             ast_value      *thinkfunc;
2248             ast_expression *functype = fld_think->expression.next;
2249
2250             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2251             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2252                 ast_unref(framenum);
2253                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2254                 return false;
2255             }
2256
2257             if (!parser_next(parser)) {
2258                 ast_unref(framenum);
2259                 ast_delete(thinkfunc);
2260                 return false;
2261             }
2262
2263             varent.var = (ast_expression*)thinkfunc;
2264             varent.name = util_strdup(thinkfunc->name);
2265             vec_push(parser->globals, varent);
2266             nextthink = (ast_expression*)thinkfunc;
2267
2268         } else {
2269             nextthink = parse_expression_leave(parser, true);
2270             if (!nextthink) {
2271                 ast_unref(framenum);
2272                 parseerror(parser, "expected a think-function in [frame,think] notation");
2273                 return false;
2274             }
2275         }
2276
2277         if (!ast_istype(nextthink, ast_value)) {
2278             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2279             retval = false;
2280         }
2281
2282         if (retval && parser->tok != ']') {
2283             parseerror(parser, "expected closing `]` for [frame,think] notation");
2284             retval = false;
2285         }
2286
2287         if (retval && !parser_next(parser)) {
2288             retval = false;
2289         }
2290
2291         if (retval && parser->tok != '{') {
2292             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2293             retval = false;
2294         }
2295
2296         if (!retval) {
2297             ast_unref(nextthink);
2298             ast_unref(framenum);
2299             return false;
2300         }
2301
2302         has_frame_think = true;
2303     }
2304
2305     block = ast_block_new(parser_ctx(parser));
2306     if (!block) {
2307         parseerror(parser, "failed to allocate block");
2308         if (has_frame_think) {
2309             ast_unref(nextthink);
2310             ast_unref(framenum);
2311         }
2312         return false;
2313     }
2314
2315     if (has_frame_think) {
2316         lex_ctx ctx;
2317         ast_expression *self_frame;
2318         ast_expression *self_nextthink;
2319         ast_expression *self_think;
2320         ast_expression *time_plus_1;
2321         ast_store *store_frame;
2322         ast_store *store_nextthink;
2323         ast_store *store_think;
2324
2325         ctx = parser_ctx(parser);
2326         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2327         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2328         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2329
2330         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2331                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2332
2333         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2334             if (self_frame)     ast_delete(self_frame);
2335             if (self_nextthink) ast_delete(self_nextthink);
2336             if (self_think)     ast_delete(self_think);
2337             if (time_plus_1)    ast_delete(time_plus_1);
2338             retval = false;
2339         }
2340
2341         if (retval)
2342         {
2343             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2344             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2345             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2346
2347             if (!store_frame) {
2348                 ast_delete(self_frame);
2349                 retval = false;
2350             }
2351             if (!store_nextthink) {
2352                 ast_delete(self_nextthink);
2353                 retval = false;
2354             }
2355             if (!store_think) {
2356                 ast_delete(self_think);
2357                 retval = false;
2358             }
2359             if (!retval) {
2360                 if (store_frame)     ast_delete(store_frame);
2361                 if (store_nextthink) ast_delete(store_nextthink);
2362                 if (store_think)     ast_delete(store_think);
2363                 retval = false;
2364             }
2365             vec_push(block->exprs, (ast_expression*)store_frame);
2366             vec_push(block->exprs, (ast_expression*)store_nextthink);
2367             vec_push(block->exprs, (ast_expression*)store_think);
2368         }
2369
2370         if (!retval) {
2371             parseerror(parser, "failed to generate code for [frame,think]");
2372             ast_unref(nextthink);
2373             ast_unref(framenum);
2374             ast_delete(block);
2375             return false;
2376         }
2377     }
2378
2379     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2380         size_t     e;
2381         varentry_t ve[3];
2382         ast_value *param = var->expression.params[parami];
2383
2384         if (param->expression.vtype != TYPE_VECTOR &&
2385             (param->expression.vtype != TYPE_FIELD ||
2386              param->expression.next->expression.vtype != TYPE_VECTOR))
2387         {
2388             continue;
2389         }
2390
2391         if (!create_vector_members(param, ve)) {
2392             ast_block_delete(block);
2393             return false;
2394         }
2395
2396         for (e = 0; e < 3; ++e) {
2397             vec_push(parser->locals, ve[e]);
2398             ast_block_collect(block, ve[e].var);
2399             ve[e].var = NULL; /* collected */
2400         }
2401     }
2402
2403     func = ast_function_new(ast_ctx(var), var->name, var);
2404     if (!func) {
2405         parseerror(parser, "failed to allocate function for `%s`", var->name);
2406         ast_block_delete(block);
2407         goto enderr;
2408     }
2409     vec_push(parser->functions, func);
2410
2411     parser->function = func;
2412     if (!parse_block_into(parser, block, true)) {
2413         ast_block_delete(block);
2414         goto enderrfn;
2415     }
2416
2417     vec_push(func->blocks, block);
2418
2419     parser->function = old;
2420     while (vec_size(parser->locals))
2421         retval = retval && parser_pop_local(parser);
2422
2423     if (parser->tok == ';')
2424         return parser_next(parser);
2425     else if (opts_standard == COMPILER_QCC)
2426         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2427     return retval;
2428
2429 enderrfn:
2430     vec_pop(parser->functions);
2431     ast_function_delete(func);
2432     var->constval.vfunc = NULL;
2433
2434 enderr:
2435     while (vec_size(parser->locals)) {
2436         mem_d(vec_last(parser->locals).name);
2437         vec_pop(parser->locals);
2438     }
2439     parser->function = old;
2440     return false;
2441 }
2442
2443 static ast_expression *array_accessor_split(
2444     parser_t  *parser,
2445     ast_value *array,
2446     ast_value *index,
2447     size_t     middle,
2448     ast_expression *left,
2449     ast_expression *right
2450     )
2451 {
2452     ast_ifthen *ifthen;
2453     ast_binary *cmp;
2454
2455     lex_ctx ctx = ast_ctx(array);
2456
2457     if (!left || !right) {
2458         if (left)  ast_delete(left);
2459         if (right) ast_delete(right);
2460         return NULL;
2461     }
2462
2463     cmp = ast_binary_new(ctx, INSTR_LT,
2464                          (ast_expression*)index,
2465                          (ast_expression*)parser_const_float(parser, middle));
2466     if (!cmp) {
2467         ast_delete(left);
2468         ast_delete(right);
2469         parseerror(parser, "internal error: failed to create comparison for array setter");
2470         return NULL;
2471     }
2472
2473     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2474     if (!ifthen) {
2475         ast_delete(cmp); /* will delete left and right */
2476         parseerror(parser, "internal error: failed to create conditional jump for array setter");
2477         return NULL;
2478     }
2479
2480     return (ast_expression*)ifthen;
2481 }
2482
2483 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2484 {
2485     lex_ctx ctx = ast_ctx(array);
2486
2487     if (from+1 == afterend) {
2488         /* set this value */
2489         ast_block       *block;
2490         ast_return      *ret;
2491         ast_array_index *subscript;
2492         ast_store       *st;
2493         int assignop = type_store_instr[value->expression.vtype];
2494
2495         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2496             assignop = INSTR_STORE_V;
2497
2498         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2499         if (!subscript)
2500             return NULL;
2501
2502         st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2503         if (!st) {
2504             ast_delete(subscript);
2505             return NULL;
2506         }
2507
2508         block = ast_block_new(ctx);
2509         if (!block) {
2510             ast_delete(st);
2511             return NULL;
2512         }
2513
2514         vec_push(block->exprs, (ast_expression*)st);
2515
2516         ret = ast_return_new(ctx, NULL);
2517         if (!ret) {
2518             ast_delete(block);
2519             return NULL;
2520         }
2521
2522         vec_push(block->exprs, (ast_expression*)ret);
2523
2524         return (ast_expression*)block;
2525     } else {
2526         ast_expression *left, *right;
2527         size_t diff = afterend - from;
2528         size_t middle = from + diff/2;
2529         left  = array_setter_node(parser, array, index, value, from, middle);
2530         right = array_setter_node(parser, array, index, value, middle, afterend);
2531         return array_accessor_split(parser, array, index, middle, left, right);
2532     }
2533 }
2534
2535 static ast_expression *array_field_setter_node(
2536     parser_t  *parser,
2537     ast_value *array,
2538     ast_value *entity,
2539     ast_value *index,
2540     ast_value *value,
2541     size_t     from,
2542     size_t     afterend)
2543 {
2544     lex_ctx ctx = ast_ctx(array);
2545
2546     if (from+1 == afterend) {
2547         /* set this value */
2548         ast_block       *block;
2549         ast_return      *ret;
2550         ast_entfield    *entfield;
2551         ast_array_index *subscript;
2552         ast_store       *st;
2553         int assignop = type_storep_instr[value->expression.vtype];
2554
2555         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2556             assignop = INSTR_STOREP_V;
2557
2558         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2559         if (!subscript)
2560             return NULL;
2561
2562         entfield = ast_entfield_new_force(ctx,
2563                                           (ast_expression*)entity,
2564                                           (ast_expression*)subscript,
2565                                           (ast_expression*)subscript);
2566         if (!entfield) {
2567             ast_delete(subscript);
2568             return NULL;
2569         }
2570
2571         st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2572         if (!st) {
2573             ast_delete(entfield);
2574             return NULL;
2575         }
2576
2577         block = ast_block_new(ctx);
2578         if (!block) {
2579             ast_delete(st);
2580             return NULL;
2581         }
2582
2583         vec_push(block->exprs, (ast_expression*)st);
2584
2585         ret = ast_return_new(ctx, NULL);
2586         if (!ret) {
2587             ast_delete(block);
2588             return NULL;
2589         }
2590
2591         vec_push(block->exprs, (ast_expression*)ret);
2592
2593         return (ast_expression*)block;
2594     } else {
2595         ast_expression *left, *right;
2596         size_t diff = afterend - from;
2597         size_t middle = from + diff/2;
2598         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
2599         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2600         return array_accessor_split(parser, array, index, middle, left, right);
2601     }
2602 }
2603
2604 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2605 {
2606     lex_ctx ctx = ast_ctx(array);
2607
2608     if (from+1 == afterend) {
2609         ast_return      *ret;
2610         ast_array_index *subscript;
2611
2612         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2613         if (!subscript)
2614             return NULL;
2615
2616         ret = ast_return_new(ctx, (ast_expression*)subscript);
2617         if (!ret) {
2618             ast_delete(subscript);
2619             return NULL;
2620         }
2621
2622         return (ast_expression*)ret;
2623     } else {
2624         ast_expression *left, *right;
2625         size_t diff = afterend - from;
2626         size_t middle = from + diff/2;
2627         left  = array_getter_node(parser, array, index, from, middle);
2628         right = array_getter_node(parser, array, index, middle, afterend);
2629         return array_accessor_split(parser, array, index, middle, left, right);
2630     }
2631 }
2632
2633 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2634 {
2635     ast_function   *func = NULL;
2636     ast_value      *fval = NULL;
2637     ast_block      *body = NULL;
2638
2639     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2640     if (!fval) {
2641         parseerror(parser, "failed to create accessor function value");
2642         return false;
2643     }
2644
2645     func = ast_function_new(ast_ctx(array), funcname, fval);
2646     if (!func) {
2647         ast_delete(fval);
2648         parseerror(parser, "failed to create accessor function node");
2649         return false;
2650     }
2651
2652     body = ast_block_new(ast_ctx(array));
2653     if (!body) {
2654         parseerror(parser, "failed to create block for array accessor");
2655         ast_delete(fval);
2656         ast_delete(func);
2657         return false;
2658     }
2659
2660     vec_push(func->blocks, body);
2661     *out = fval;
2662
2663     vec_push(parser->accessors, fval);
2664
2665     return true;
2666 }
2667
2668 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2669 {
2670     ast_expression *root = NULL;
2671     ast_value      *index = NULL;
2672     ast_value      *value = NULL;
2673     ast_function   *func;
2674     ast_value      *fval;
2675
2676     if (!ast_istype(array->expression.next, ast_value)) {
2677         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2678         return false;
2679     }
2680
2681     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2682         return false;
2683     func = fval->constval.vfunc;
2684     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2685
2686     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2687     value = ast_value_copy((ast_value*)array->expression.next);
2688
2689     if (!index || !value) {
2690         parseerror(parser, "failed to create locals for array accessor");
2691         goto cleanup;
2692     }
2693     (void)!ast_value_set_name(value, "value"); /* not important */
2694     vec_push(fval->expression.params, index);
2695     vec_push(fval->expression.params, value);
2696
2697     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2698     if (!root) {
2699         parseerror(parser, "failed to build accessor search tree");
2700         goto cleanup;
2701     }
2702
2703     vec_push(func->blocks[0]->exprs, root);
2704     array->setter = fval;
2705     return true;
2706 cleanup:
2707     if (index) ast_delete(index);
2708     if (value) ast_delete(value);
2709     if (root)  ast_delete(root);
2710     ast_delete(func);
2711     ast_delete(fval);
2712     return false;
2713 }
2714
2715 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2716 {
2717     ast_expression *root = NULL;
2718     ast_value      *entity = NULL;
2719     ast_value      *index = NULL;
2720     ast_value      *value = NULL;
2721     ast_function   *func;
2722     ast_value      *fval;
2723
2724     if (!ast_istype(array->expression.next, ast_value)) {
2725         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2726         return false;
2727     }
2728
2729     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2730         return false;
2731     func = fval->constval.vfunc;
2732     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2733
2734     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2735     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
2736     value  = ast_value_copy((ast_value*)array->expression.next);
2737     if (!entity || !index || !value) {
2738         parseerror(parser, "failed to create locals for array accessor");
2739         goto cleanup;
2740     }
2741     (void)!ast_value_set_name(value, "value"); /* not important */
2742     vec_push(fval->expression.params, entity);
2743     vec_push(fval->expression.params, index);
2744     vec_push(fval->expression.params, value);
2745
2746     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2747     if (!root) {
2748         parseerror(parser, "failed to build accessor search tree");
2749         goto cleanup;
2750     }
2751
2752     vec_push(func->blocks[0]->exprs, root);
2753     array->setter = fval;
2754     return true;
2755 cleanup:
2756     if (entity) ast_delete(entity);
2757     if (index)  ast_delete(index);
2758     if (value)  ast_delete(value);
2759     if (root)   ast_delete(root);
2760     ast_delete(func);
2761     ast_delete(fval);
2762     return false;
2763 }
2764
2765 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2766 {
2767     ast_expression *root = NULL;
2768     ast_value      *index = NULL;
2769     ast_value      *fval;
2770     ast_function   *func;
2771
2772     /* NOTE: checking array->expression.next rather than elemtype since
2773      * for fields elemtype is a temporary fieldtype.
2774      */
2775     if (!ast_istype(array->expression.next, ast_value)) {
2776         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2777         return false;
2778     }
2779
2780     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2781         return false;
2782     func = fval->constval.vfunc;
2783     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2784
2785     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2786
2787     if (!index) {
2788         parseerror(parser, "failed to create locals for array accessor");
2789         goto cleanup;
2790     }
2791     vec_push(fval->expression.params, index);
2792
2793     root = array_getter_node(parser, array, index, 0, array->expression.count);
2794     if (!root) {
2795         parseerror(parser, "failed to build accessor search tree");
2796         goto cleanup;
2797     }
2798
2799     vec_push(func->blocks[0]->exprs, root);
2800     array->getter = fval;
2801     return true;
2802 cleanup:
2803     if (index) ast_delete(index);
2804     if (root)  ast_delete(root);
2805     ast_delete(func);
2806     ast_delete(fval);
2807     return false;
2808 }
2809
2810 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2811 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2812 {
2813     lex_ctx     ctx;
2814     size_t      i;
2815     ast_value **params;
2816     ast_value  *param;
2817     ast_value  *fval;
2818     bool        first = true;
2819     bool        variadic = false;
2820
2821     ctx = parser_ctx(parser);
2822
2823     /* for the sake of less code we parse-in in this function */
2824     if (!parser_next(parser)) {
2825         parseerror(parser, "expected parameter list");
2826         return NULL;
2827     }
2828
2829     params = NULL;
2830
2831     /* parse variables until we hit a closing paren */
2832     while (parser->tok != ')') {
2833         if (!first) {
2834             /* there must be commas between them */
2835             if (parser->tok != ',') {
2836                 parseerror(parser, "expected comma or end of parameter list");
2837                 goto on_error;
2838             }
2839             if (!parser_next(parser)) {
2840                 parseerror(parser, "expected parameter");
2841                 goto on_error;
2842             }
2843         }
2844         first = false;
2845
2846         if (parser->tok == TOKEN_DOTS) {
2847             /* '...' indicates a varargs function */
2848             variadic = true;
2849             if (!parser_next(parser)) {
2850                 parseerror(parser, "expected parameter");
2851                 return NULL;
2852             }
2853             if (parser->tok != ')') {
2854                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2855                 goto on_error;
2856             }
2857         }
2858         else
2859         {
2860             /* for anything else just parse a typename */
2861             param = parse_typename(parser, NULL);
2862             if (!param)
2863                 goto on_error;
2864             vec_push(params, param);
2865             if (param->expression.vtype >= TYPE_VARIANT) {
2866                 char typename[1024];
2867                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2868                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2869                 goto on_error;
2870             }
2871         }
2872     }
2873
2874     /* sanity check */
2875     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
2876         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
2877
2878     /* parse-out */
2879     if (!parser_next(parser)) {
2880         parseerror(parser, "parse error after typename");
2881         goto on_error;
2882     }
2883
2884     /* now turn 'var' into a function type */
2885     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2886     fval->expression.next     = (ast_expression*)var;
2887     fval->expression.variadic = variadic;
2888     var = fval;
2889
2890     var->expression.params = params;
2891     params = NULL;
2892
2893     return var;
2894
2895 on_error:
2896     ast_delete(var);
2897     for (i = 0; i < vec_size(params); ++i)
2898         ast_delete(params[i]);
2899     vec_free(params);
2900     return NULL;
2901 }
2902
2903 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2904 {
2905     ast_expression *cexp;
2906     ast_value      *cval, *tmp;
2907     lex_ctx ctx;
2908
2909     ctx = parser_ctx(parser);
2910
2911     if (!parser_next(parser)) {
2912         ast_delete(var);
2913         parseerror(parser, "expected array-size");
2914         return NULL;
2915     }
2916
2917     cexp = parse_expression_leave(parser, true);
2918
2919     if (!cexp || !ast_istype(cexp, ast_value)) {
2920         if (cexp)
2921             ast_unref(cexp);
2922         ast_delete(var);
2923         parseerror(parser, "expected array-size as constant positive integer");
2924         return NULL;
2925     }
2926     cval = (ast_value*)cexp;
2927
2928     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2929     tmp->expression.next = (ast_expression*)var;
2930     var = tmp;
2931
2932     if (cval->expression.vtype == TYPE_INTEGER)
2933         tmp->expression.count = cval->constval.vint;
2934     else if (cval->expression.vtype == TYPE_FLOAT)
2935         tmp->expression.count = cval->constval.vfloat;
2936     else {
2937         ast_unref(cexp);
2938         ast_delete(var);
2939         parseerror(parser, "array-size must be a positive integer constant");
2940         return NULL;
2941     }
2942     ast_unref(cexp);
2943
2944     if (parser->tok != ']') {
2945         ast_delete(var);
2946         parseerror(parser, "expected ']' after array-size");
2947         return NULL;
2948     }
2949     if (!parser_next(parser)) {
2950         ast_delete(var);
2951         parseerror(parser, "error after parsing array size");
2952         return NULL;
2953     }
2954     return var;
2955 }
2956
2957 /* Parse a complete typename.
2958  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2959  * but when parsing variables separated by comma
2960  * 'storebase' should point to where the base-type should be kept.
2961  * The base type makes up every bit of type information which comes *before* the
2962  * variable name.
2963  *
2964  * The following will be parsed in its entirety:
2965  *     void() foo()
2966  * The 'basetype' in this case is 'void()'
2967  * and if there's a comma after it, say:
2968  *     void() foo(), bar
2969  * then the type-information 'void()' can be stored in 'storebase'
2970  */
2971 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2972 {
2973     ast_value *var, *tmp;
2974     lex_ctx    ctx;
2975
2976     const char *name = NULL;
2977     bool        isfield  = false;
2978     bool        wasarray = false;
2979
2980     ctx = parser_ctx(parser);
2981
2982     /* types may start with a dot */
2983     if (parser->tok == '.') {
2984         isfield = true;
2985         /* if we parsed a dot we need a typename now */
2986         if (!parser_next(parser)) {
2987             parseerror(parser, "expected typename for field definition");
2988             return NULL;
2989         }
2990         if (parser->tok != TOKEN_TYPENAME) {
2991             parseerror(parser, "expected typename");
2992             return NULL;
2993         }
2994     }
2995
2996     /* generate the basic type value */
2997     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2998     /* do not yet turn into a field - remember:
2999      * .void() foo; is a field too
3000      * .void()() foo; is a function
3001      */
3002
3003     /* parse on */
3004     if (!parser_next(parser)) {
3005         ast_delete(var);
3006         parseerror(parser, "parse error after typename");
3007         return NULL;
3008     }
3009
3010     /* an opening paren now starts the parameter-list of a function
3011      * this is where original-QC has parameter lists.
3012      * We allow a single parameter list here.
3013      * Much like fteqcc we don't allow `float()() x`
3014      */
3015     if (parser->tok == '(') {
3016         var = parse_parameter_list(parser, var);
3017         if (!var)
3018             return NULL;
3019     }
3020
3021     /* store the base if requested */
3022     if (storebase) {
3023         *storebase = ast_value_copy(var);
3024         if (isfield) {
3025             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3026             tmp->expression.next = (ast_expression*)*storebase;
3027             *storebase = tmp;
3028         }
3029     }
3030
3031     /* there may be a name now */
3032     if (parser->tok == TOKEN_IDENT) {
3033         name = util_strdup(parser_tokval(parser));
3034         /* parse on */
3035         if (!parser_next(parser)) {
3036             ast_delete(var);
3037             parseerror(parser, "error after variable or field declaration");
3038             return NULL;
3039         }
3040     }
3041
3042     /* now this may be an array */
3043     if (parser->tok == '[') {
3044         wasarray = true;
3045         var = parse_arraysize(parser, var);
3046         if (!var)
3047             return NULL;
3048     }
3049
3050     /* This is the point where we can turn it into a field */
3051     if (isfield) {
3052         /* turn it into a field if desired */
3053         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3054         tmp->expression.next = (ast_expression*)var;
3055         var = tmp;
3056     }
3057
3058     /* now there may be function parens again */
3059     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3060         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3061     if (parser->tok == '(' && wasarray)
3062         parseerror(parser, "arrays as part of a return type is not supported");
3063     while (parser->tok == '(') {
3064         var = parse_parameter_list(parser, var);
3065         if (!var) {
3066             if (name)
3067                 mem_d((void*)name);
3068             ast_delete(var);
3069             return NULL;
3070         }
3071     }
3072
3073     /* finally name it */
3074     if (name) {
3075         if (!ast_value_set_name(var, name)) {
3076             ast_delete(var);
3077             parseerror(parser, "internal error: failed to set name");
3078             return NULL;
3079         }
3080         /* free the name, ast_value_set_name duplicates */
3081         mem_d((void*)name);
3082     }
3083
3084     return var;
3085 }
3086
3087 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
3088 {
3089     ast_value *var;
3090     ast_value *proto;
3091     ast_expression *old;
3092     bool       was_end;
3093     size_t     i;
3094
3095     ast_value *basetype = NULL;
3096     bool      retval    = true;
3097     bool      isparam   = false;
3098     bool      isvector  = false;
3099     bool      cleanvar  = true;
3100     bool      wasarray  = false;
3101
3102     varentry_t varent, ve[3];
3103
3104     /* get the first complete variable */
3105     var = parse_typename(parser, &basetype);
3106     if (!var) {
3107         if (basetype)
3108             ast_delete(basetype);
3109         return false;
3110     }
3111
3112     memset(&varent, 0, sizeof(varent));
3113     memset(&ve, 0, sizeof(ve));
3114
3115     while (true) {
3116         proto = NULL;
3117         wasarray = false;
3118
3119         /* Part 0: finish the type */
3120         if (parser->tok == '(') {
3121             if (opts_standard == COMPILER_QCC)
3122                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3123             var = parse_parameter_list(parser, var);
3124             if (!var) {
3125                 retval = false;
3126                 goto cleanup;
3127             }
3128         }
3129         /* we only allow 1-dimensional arrays */
3130         if (parser->tok == '[') {
3131             wasarray = true;
3132             var = parse_arraysize(parser, var);
3133             if (!var) {
3134                 retval = false;
3135                 goto cleanup;
3136             }
3137         }
3138         if (parser->tok == '(' && wasarray) {
3139             parseerror(parser, "arrays as part of a return type is not supported");
3140             /* we'll still parse the type completely for now */
3141         }
3142         /* for functions returning functions */
3143         while (parser->tok == '(') {
3144             if (opts_standard == COMPILER_QCC)
3145                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3146             var = parse_parameter_list(parser, var);
3147             if (!var) {
3148                 retval = false;
3149                 goto cleanup;
3150             }
3151         }
3152
3153         /* Part 1:
3154          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3155          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3156          * is then filled with the previous definition and the parameter-names replaced.
3157          */
3158         if (!localblock) {
3159             /* Deal with end_sys_ vars */
3160             was_end = false;
3161             if (!strcmp(var->name, "end_sys_globals")) {
3162                 parser->crc_globals = vec_size(parser->globals);
3163                 was_end = true;
3164             }
3165             else if (!strcmp(var->name, "end_sys_fields")) {
3166                 parser->crc_fields = vec_size(parser->fields);
3167                 was_end = true;
3168             }
3169             if (was_end && var->expression.vtype == TYPE_FIELD) {
3170                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3171                                  "global '%s' hint should not be a field",
3172                                  parser_tokval(parser)))
3173                 {
3174                     retval = false;
3175                     goto cleanup;
3176                 }
3177             }
3178
3179             if (!nofields && var->expression.vtype == TYPE_FIELD)
3180             {
3181                 /* deal with field declarations */
3182                 old = parser_find_field(parser, var->name);
3183                 if (old) {
3184                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3185                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3186                     {
3187                         retval = false;
3188                         goto cleanup;
3189                     }
3190                     ast_delete(var);
3191                     var = NULL;
3192                     goto skipvar;
3193                     /*
3194                     parseerror(parser, "field `%s` already declared here: %s:%i",
3195                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3196                     retval = false;
3197                     goto cleanup;
3198                     */
3199                 }
3200                 if (opts_standard == COMPILER_QCC &&
3201                     (old = parser_find_global(parser, var->name)))
3202                 {
3203                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3204                     parseerror(parser, "field `%s` already declared here: %s:%i",
3205                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3206                     retval = false;
3207                     goto cleanup;
3208                 }
3209             }
3210             else
3211             {
3212                 /* deal with other globals */
3213                 old = parser_find_global(parser, var->name);
3214                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3215                 {
3216                     /* This is a function which had a prototype */
3217                     if (!ast_istype(old, ast_value)) {
3218                         parseerror(parser, "internal error: prototype is not an ast_value");
3219                         retval = false;
3220                         goto cleanup;
3221                     }
3222                     proto = (ast_value*)old;
3223                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3224                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3225                                    proto->name,
3226                                    ast_ctx(proto).file, ast_ctx(proto).line);
3227                         retval = false;
3228                         goto cleanup;
3229                     }
3230                     /* we need the new parameter-names */
3231                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3232                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3233                     ast_delete(var);
3234                     var = proto;
3235                 }
3236                 else
3237                 {
3238                     /* other globals */
3239                     if (old) {
3240                         parseerror(parser, "global `%s` already declared here: %s:%i",
3241                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3242                         retval = false;
3243                         goto cleanup;
3244                     }
3245                     if (opts_standard == COMPILER_QCC &&
3246                         (old = parser_find_field(parser, var->name)))
3247                     {
3248                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3249                         parseerror(parser, "global `%s` already declared here: %s:%i",
3250                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3251                         retval = false;
3252                         goto cleanup;
3253                     }
3254                 }
3255             }
3256         }
3257         else /* it's not a global */
3258         {
3259             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
3260             if (old && !isparam) {
3261                 parseerror(parser, "local `%s` already declared here: %s:%i",
3262                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3263                 retval = false;
3264                 goto cleanup;
3265             }
3266             old = parser_find_local(parser, var->name, 0, &isparam);
3267             if (old && isparam) {
3268                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3269                                  "local `%s` is shadowing a parameter", var->name))
3270                 {
3271                     parseerror(parser, "local `%s` already declared here: %s:%i",
3272                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3273                     retval = false;
3274                     goto cleanup;
3275                 }
3276                 if (opts_standard != COMPILER_GMQCC) {
3277                     ast_delete(var);
3278                     var = NULL;
3279                     goto skipvar;
3280                 }
3281             }
3282         }
3283
3284         /* Part 2:
3285          * Create the global/local, and deal with vector types.
3286          */
3287         if (!proto) {
3288             if (var->expression.vtype == TYPE_VECTOR)
3289                 isvector = true;
3290             else if (var->expression.vtype == TYPE_FIELD &&
3291                      var->expression.next->expression.vtype == TYPE_VECTOR)
3292                 isvector = true;
3293
3294             if (isvector) {
3295                 if (!create_vector_members(var, ve)) {
3296                     retval = false;
3297                     goto cleanup;
3298                 }
3299             }
3300
3301             varent.name = util_strdup(var->name);
3302             varent.var  = (ast_expression*)var;
3303
3304             if (!localblock) {
3305                 /* deal with global variables, fields, functions */
3306                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3307                     vec_push(parser->fields, varent);
3308                     if (isvector) {
3309                         for (i = 0; i < 3; ++i)
3310                             vec_push(parser->fields, ve[i]);
3311                     }
3312                 }
3313                 else {
3314                     vec_push(parser->globals, varent);
3315                     if (isvector) {
3316                         for (i = 0; i < 3; ++i)
3317                             vec_push(parser->globals, ve[i]);
3318                     }
3319                 }
3320             } else {
3321                 vec_push(parser->locals, varent);
3322                 vec_push(localblock->locals, var);
3323                 if (isvector) {
3324                     for (i = 0; i < 3; ++i) {
3325                         vec_push(parser->locals, ve[i]);
3326                         ast_block_collect(localblock, ve[i].var);
3327                         ve[i].var = NULL; /* from here it's being collected in the block */
3328                     }
3329                 }
3330             }
3331
3332             varent.name = NULL;
3333             ve[0].name = ve[1].name = ve[2].name = NULL;
3334             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
3335             cleanvar = false;
3336         }
3337         /* Part 2.2
3338          * deal with arrays
3339          */
3340         if (var->expression.vtype == TYPE_ARRAY) {
3341             char name[1024];
3342             snprintf(name, sizeof(name), "%s##SET", var->name);
3343             if (!parser_create_array_setter(parser, var, name))
3344                 goto cleanup;
3345             snprintf(name, sizeof(name), "%s##GET", var->name);
3346             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3347                 goto cleanup;
3348         }
3349         else if (!localblock && !nofields &&
3350                  var->expression.vtype == TYPE_FIELD &&
3351                  var->expression.next->expression.vtype == TYPE_ARRAY)
3352         {
3353             char name[1024];
3354             ast_expression *telem;
3355             ast_value      *tfield;
3356             ast_value      *array = (ast_value*)var->expression.next;
3357
3358             if (!ast_istype(var->expression.next, ast_value)) {
3359                 parseerror(parser, "internal error: field element type must be an ast_value");
3360                 goto cleanup;
3361             }
3362
3363             snprintf(name, sizeof(name), "%s##SETF", var->name);
3364             if (!parser_create_array_field_setter(parser, array, name))
3365                 goto cleanup;
3366
3367             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3368             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3369             tfield->expression.next = telem;
3370             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3371             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3372                 ast_delete(tfield);
3373                 goto cleanup;
3374             }
3375             ast_delete(tfield);
3376         }
3377
3378 skipvar:
3379         if (parser->tok == ';') {
3380             ast_delete(basetype);
3381             if (!parser_next(parser)) {
3382                 parseerror(parser, "error after variable declaration");
3383                 return false;
3384             }
3385             return true;
3386         }
3387
3388         if (parser->tok == ',')
3389             goto another;
3390
3391         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3392             parseerror(parser, "missing comma or semicolon while parsing variables");
3393             break;
3394         }
3395
3396         if (localblock && opts_standard == COMPILER_QCC) {
3397             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3398                              "initializing expression turns variable `%s` into a constant in this standard",
3399                              var->name) )
3400             {
3401                 break;
3402             }
3403         }
3404
3405         if (parser->tok != '{') {
3406             if (parser->tok != '=') {
3407                 parseerror(parser, "missing semicolon or initializer");
3408                 break;
3409             }
3410
3411             if (!parser_next(parser)) {
3412                 parseerror(parser, "error parsing initializer");
3413                 break;
3414             }
3415         }
3416         else if (opts_standard == COMPILER_QCC) {
3417             parseerror(parser, "expected '=' before function body in this standard");
3418         }
3419
3420         if (parser->tok == '#') {
3421             ast_function *func;
3422
3423             if (localblock) {
3424                 parseerror(parser, "cannot declare builtins within functions");
3425                 break;
3426             }
3427             if (var->expression.vtype != TYPE_FUNCTION) {
3428                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3429                 break;
3430             }
3431             if (!parser_next(parser)) {
3432                 parseerror(parser, "expected builtin number");
3433                 break;
3434             }
3435             if (parser->tok != TOKEN_INTCONST) {
3436                 parseerror(parser, "builtin number must be an integer constant");
3437                 break;
3438             }
3439             if (parser_token(parser)->constval.i <= 0) {
3440                 parseerror(parser, "builtin number must be an integer greater than zero");
3441                 break;
3442             }
3443
3444             func = ast_function_new(ast_ctx(var), var->name, var);
3445             if (!func) {
3446                 parseerror(parser, "failed to allocate function for `%s`", var->name);
3447                 break;
3448             }
3449             vec_push(parser->functions, func);
3450
3451             func->builtin = -parser_token(parser)->constval.i;
3452
3453             if (!parser_next(parser)) {
3454                 parseerror(parser, "expected comma or semicolon");
3455                 ast_function_delete(func);
3456                 var->constval.vfunc = NULL;
3457                 break;
3458             }
3459         }
3460         else if (parser->tok == '{' || parser->tok == '[')
3461         {
3462             if (localblock) {
3463                 parseerror(parser, "cannot declare functions within functions");
3464                 break;
3465             }
3466
3467             if (!parse_function_body(parser, var))
3468                 break;
3469             ast_delete(basetype);
3470             return true;
3471         } else {
3472             ast_expression *cexp;
3473             ast_value      *cval;
3474
3475             cexp = parse_expression_leave(parser, true);
3476             if (!cexp)
3477                 break;
3478
3479             if (!localblock) {
3480                 cval = (ast_value*)cexp;
3481                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3482                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3483                 else
3484                 {
3485                     var->isconst = true;
3486                     if (cval->expression.vtype == TYPE_STRING)
3487                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3488                     else
3489                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3490                     ast_unref(cval);
3491                 }
3492             } else {
3493                 shunt sy = { NULL, NULL };
3494                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3495                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3496                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3497                 if (!parser_sy_pop(parser, &sy))
3498                     ast_unref(cexp);
3499                 else {
3500                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3501                         parseerror(parser, "internal error: leaked operands");
3502                     vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3503                 }
3504                 vec_free(sy.out);
3505                 vec_free(sy.ops);
3506             }
3507         }
3508
3509 another:
3510         if (parser->tok == ',') {
3511             if (!parser_next(parser)) {
3512                 parseerror(parser, "expected another variable");
3513                 break;
3514             }
3515
3516             if (parser->tok != TOKEN_IDENT) {
3517                 parseerror(parser, "expected another variable");
3518                 break;
3519             }
3520             var = ast_value_copy(basetype);
3521             cleanvar = true;
3522             ast_value_set_name(var, parser_tokval(parser));
3523             if (!parser_next(parser)) {
3524                 parseerror(parser, "error parsing variable declaration");
3525                 break;
3526             }
3527             continue;
3528         }
3529
3530         if (parser->tok != ';') {
3531             parseerror(parser, "missing semicolon after variables");
3532             break;
3533         }
3534
3535         if (!parser_next(parser)) {
3536             parseerror(parser, "parse error after variable declaration");
3537             break;
3538         }
3539
3540         ast_delete(basetype);
3541         return true;
3542     }
3543
3544     if (cleanvar && var)
3545         ast_delete(var);
3546     ast_delete(basetype);
3547     return false;
3548
3549 cleanup:
3550     ast_delete(basetype);
3551     if (cleanvar && var)
3552         ast_delete(var);
3553     if (varent.name) mem_d(varent.name);
3554     if (ve[0].name)  mem_d(ve[0].name);
3555     if (ve[1].name)  mem_d(ve[1].name);
3556     if (ve[2].name)  mem_d(ve[2].name);
3557     if (ve[0].var)   mem_d(ve[0].var);
3558     if (ve[1].var)   mem_d(ve[1].var);
3559     if (ve[2].var)   mem_d(ve[2].var);
3560     return retval;
3561 }
3562
3563 static bool parser_global_statement(parser_t *parser)
3564 {
3565     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3566     {
3567         return parse_variable(parser, NULL, false);
3568     }
3569     else if (parser->tok == TOKEN_KEYWORD)
3570     {
3571         /* handle 'var' and 'const' */
3572         if (!strcmp(parser_tokval(parser), "var")) {
3573             if (!parser_next(parser)) {
3574                 parseerror(parser, "expected variable declaration after 'var'");
3575                 return false;
3576             }
3577             return parse_variable(parser, NULL, true);
3578         }
3579         return false;
3580     }
3581     else if (parser->tok == '$')
3582     {
3583         if (!parser_next(parser)) {
3584             parseerror(parser, "parse error");
3585             return false;
3586         }
3587     }
3588     else
3589     {
3590         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3591         return false;
3592     }
3593     return true;
3594 }
3595
3596 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3597 {
3598     return util_crc16(old, str, strlen(str));
3599 }
3600
3601 static void progdefs_crc_file(const char *str)
3602 {
3603     /* write to progdefs.h here */
3604     (void)str;
3605 }
3606
3607 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3608 {
3609     old = progdefs_crc_sum(old, str);
3610     progdefs_crc_file(str);
3611     return old;
3612 }
3613
3614 static void generate_checksum(parser_t *parser)
3615 {
3616     uint16_t crc = 0xFFFF;
3617     size_t i;
3618
3619         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3620         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3621         /*
3622         progdefs_crc_file("\tint\tpad;\n");
3623         progdefs_crc_file("\tint\tofs_return[3];\n");
3624         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3625         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3626         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3627         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3628         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3629         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3630         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3631         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3632         */
3633         for (i = 0; i < parser->crc_globals; ++i) {
3634             if (!ast_istype(parser->globals[i].var, ast_value))
3635                 continue;
3636             switch (parser->globals[i].var->expression.vtype) {
3637                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3638                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3639                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3640                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3641                 default:
3642                     crc = progdefs_crc_both(crc, "\tint\t");
3643                     break;
3644             }
3645             crc = progdefs_crc_both(crc, parser->globals[i].name);
3646             crc = progdefs_crc_both(crc, ";\n");
3647         }
3648         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3649         for (i = 0; i < parser->crc_fields; ++i) {
3650             if (!ast_istype(parser->fields[i].var, ast_value))
3651                 continue;
3652             switch (parser->fields[i].var->expression.next->expression.vtype) {
3653                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3654                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3655                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3656                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3657                 default:
3658                     crc = progdefs_crc_both(crc, "\tint\t");
3659                     break;
3660             }
3661             crc = progdefs_crc_both(crc, parser->fields[i].name);
3662             crc = progdefs_crc_both(crc, ";\n");
3663         }
3664         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3665
3666         code_crc = crc;
3667 }
3668
3669 static parser_t *parser;
3670
3671 bool parser_init()
3672 {
3673     size_t i;
3674     parser = (parser_t*)mem_a(sizeof(parser_t));
3675     if (!parser)
3676         return false;
3677
3678     memset(parser, 0, sizeof(*parser));
3679
3680     for (i = 0; i < operator_count; ++i) {
3681         if (operators[i].id == opid1('=')) {
3682             parser->assign_op = operators+i;
3683             break;
3684         }
3685     }
3686     if (!parser->assign_op) {
3687         printf("internal error: initializing parser: failed to find assign operator\n");
3688         mem_d(parser);
3689         return false;
3690     }
3691     return true;
3692 }
3693
3694 bool parser_compile()
3695 {
3696     /* initial lexer/parser state */
3697     parser->lex->flags.noops = true;
3698
3699     if (parser_next(parser))
3700     {
3701         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3702         {
3703             if (!parser_global_statement(parser)) {
3704                 if (parser->tok == TOKEN_EOF)
3705                     parseerror(parser, "unexpected eof");
3706                 else if (!parser->errors)
3707                     parseerror(parser, "there have been errors, bailing out");
3708                 lex_close(parser->lex);
3709                 parser->lex = NULL;
3710                 return false;
3711             }
3712         }
3713     } else {
3714         parseerror(parser, "parse error");
3715         lex_close(parser->lex);
3716         parser->lex = NULL;
3717         return false;
3718     }
3719
3720     lex_close(parser->lex);
3721     parser->lex = NULL;
3722
3723     return !parser->errors;
3724 }
3725
3726 bool parser_compile_file(const char *filename)
3727 {
3728     parser->lex = lex_open(filename);
3729     if (!parser->lex) {
3730         con_err("failed to open file \"%s\"\n", filename);
3731         return false;
3732     }
3733     return parser_compile();
3734 }
3735
3736 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3737 {
3738     parser->lex = lex_open_string(str, len, name);
3739     if (!parser->lex) {
3740         con_err("failed to create lexer for string \"%s\"\n", name);
3741         return false;
3742     }
3743     return parser_compile();
3744 }
3745
3746 bool parser_compile_string(const char *name, const char *str)
3747 {
3748     parser->lex = lex_open_string(str, strlen(str), name);
3749     if (!parser->lex) {
3750         con_err("failed to create lexer for string \"%s\"\n", name);
3751         return false;
3752     }
3753     return parser_compile();
3754 }
3755
3756 void parser_cleanup()
3757 {
3758     size_t i;
3759     for (i = 0; i < vec_size(parser->accessors); ++i) {
3760         ast_delete(parser->accessors[i]->constval.vfunc);
3761         parser->accessors[i]->constval.vfunc = NULL;
3762         ast_delete(parser->accessors[i]);
3763     }
3764     for (i = 0; i < vec_size(parser->functions); ++i) {
3765         ast_delete(parser->functions[i]);
3766     }
3767     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3768         ast_delete(parser->imm_vector[i]);
3769     }
3770     for (i = 0; i < vec_size(parser->imm_string); ++i) {
3771         ast_delete(parser->imm_string[i]);
3772     }
3773     for (i = 0; i < vec_size(parser->imm_float); ++i) {
3774         ast_delete(parser->imm_float[i]);
3775     }
3776     for (i = 0; i < vec_size(parser->fields); ++i) {
3777         ast_delete(parser->fields[i].var);
3778         mem_d(parser->fields[i].name);
3779     }
3780     for (i = 0; i < vec_size(parser->globals); ++i) {
3781         ast_delete(parser->globals[i].var);
3782         mem_d(parser->globals[i].name);
3783     }
3784     vec_free(parser->accessors);
3785     vec_free(parser->functions);
3786     vec_free(parser->imm_vector);
3787     vec_free(parser->imm_string);
3788     vec_free(parser->imm_float);
3789     vec_free(parser->globals);
3790     vec_free(parser->fields);
3791     vec_free(parser->locals);
3792
3793     mem_d(parser);
3794 }
3795
3796 bool parser_finish(const char *output)
3797 {
3798     size_t i;
3799     ir_builder *ir;
3800     bool retval = true;
3801
3802     if (!parser->errors)
3803     {
3804         ir = ir_builder_new("gmqcc_out");
3805         if (!ir) {
3806             con_out("failed to allocate builder\n");
3807             return false;
3808         }
3809
3810         for (i = 0; i < vec_size(parser->fields); ++i) {
3811             ast_value *field;
3812             bool isconst;
3813             if (!ast_istype(parser->fields[i].var, ast_value))
3814                 continue;
3815             field = (ast_value*)parser->fields[i].var;
3816             isconst = field->isconst;
3817             field->isconst = false;
3818             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3819                 con_out("failed to generate field %s\n", field->name);
3820                 ir_builder_delete(ir);
3821                 return false;
3822             }
3823             if (isconst) {
3824                 ir_value *ifld;
3825                 ast_expression *subtype;
3826                 field->isconst = true;
3827                 subtype = field->expression.next;
3828                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3829                 if (subtype->expression.vtype == TYPE_FIELD)
3830                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3831                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3832                     ifld->outtype = subtype->expression.next->expression.vtype;
3833                 (void)!ir_value_set_field(field->ir_v, ifld);
3834             }
3835         }
3836         for (i = 0; i < vec_size(parser->globals); ++i) {
3837             ast_value *asvalue;
3838             if (!ast_istype(parser->globals[i].var, ast_value))
3839                 continue;
3840             asvalue = (ast_value*)(parser->globals[i].var);
3841             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3842                 if (strcmp(asvalue->name, "end_sys_globals") &&
3843                     strcmp(asvalue->name, "end_sys_fields"))
3844                 {
3845                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3846                                                    "unused global: `%s`", asvalue->name);
3847                 }
3848             }
3849             if (!ast_global_codegen(asvalue, ir, false)) {
3850                 con_out("failed to generate global %s\n", parser->globals[i].name);
3851                 ir_builder_delete(ir);
3852                 return false;
3853             }
3854         }
3855         for (i = 0; i < vec_size(parser->imm_float); ++i) {
3856             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3857                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
3858                 ir_builder_delete(ir);
3859                 return false;
3860             }
3861         }
3862         for (i = 0; i < vec_size(parser->imm_string); ++i) {
3863             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3864                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
3865                 ir_builder_delete(ir);
3866                 return false;
3867             }
3868         }
3869         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3870             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3871                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
3872                 ir_builder_delete(ir);
3873                 return false;
3874             }
3875         }
3876         for (i = 0; i < vec_size(parser->globals); ++i) {
3877             ast_value *asvalue;
3878             if (!ast_istype(parser->globals[i].var, ast_value))
3879                 continue;
3880             asvalue = (ast_value*)(parser->globals[i].var);
3881             if (asvalue->setter) {
3882                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3883                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3884                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3885                 {
3886                     printf("failed to generate setter for %s\n", parser->globals[i].name);
3887                     ir_builder_delete(ir);
3888                     return false;
3889                 }
3890             }
3891             if (asvalue->getter) {
3892                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3893                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3894                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3895                 {
3896                     printf("failed to generate getter for %s\n", parser->globals[i].name);
3897                     ir_builder_delete(ir);
3898                     return false;
3899                 }
3900             }
3901         }
3902         for (i = 0; i < vec_size(parser->fields); ++i) {
3903             ast_value *asvalue;
3904             asvalue = (ast_value*)(parser->fields[i].var->expression.next);
3905
3906             if (!ast_istype((ast_expression*)asvalue, ast_value))
3907                 continue;
3908             if (asvalue->expression.vtype != TYPE_ARRAY)
3909                 continue;
3910             if (asvalue->setter) {
3911                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3912                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3913                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3914                 {
3915                     printf("failed to generate setter for %s\n", parser->fields[i].name);
3916                     ir_builder_delete(ir);
3917                     return false;
3918                 }
3919             }
3920             if (asvalue->getter) {
3921                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3922                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3923                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3924                 {
3925                     printf("failed to generate getter for %s\n", parser->fields[i].name);
3926                     ir_builder_delete(ir);
3927                     return false;
3928                 }
3929             }
3930         }
3931         for (i = 0; i < vec_size(parser->functions); ++i) {
3932             if (!ast_function_codegen(parser->functions[i], ir)) {
3933                 con_out("failed to generate function %s\n", parser->functions[i]->name);
3934                 ir_builder_delete(ir);
3935                 return false;
3936             }
3937         }
3938         if (opts_dump)
3939             ir_builder_dump(ir, con_out);
3940         for (i = 0; i < vec_size(parser->functions); ++i) {
3941             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3942                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
3943                 ir_builder_delete(ir);
3944                 return false;
3945             }
3946         }
3947
3948         if (retval) {
3949             if (opts_dumpfin)
3950                 ir_builder_dump(ir, con_out);
3951
3952             generate_checksum(parser);
3953
3954             if (!ir_builder_generate(ir, output)) {
3955                 con_out("*** failed to generate output file\n");
3956                 ir_builder_delete(ir);
3957                 return false;
3958             }
3959         }
3960
3961         ir_builder_delete(ir);
3962         return retval;
3963     }
3964
3965     con_out("*** there were compile errors\n");
3966     return false;
3967 }