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