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