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