]> git.xonotic.org Git - xonotic/gmqcc.git/blob - parser.c
fix a warning and remove unused variables
[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_return(parser_t *parser, ast_block *block, ast_expression **out)
1682 {
1683     ast_expression *exp = NULL;
1684     ast_return     *ret = NULL;
1685     ast_value      *expected = parser->function->vtype;
1686
1687     if (!parser_next(parser)) {
1688         parseerror(parser, "expected return expression");
1689         return false;
1690     }
1691
1692     if (parser->tok != ';') {
1693         exp = parse_expression(parser, false);
1694         if (!exp)
1695             return false;
1696
1697         if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1698             parseerror(parser, "return with invalid expression");
1699         }
1700
1701         ret = ast_return_new(exp->expression.node.context, exp);
1702         if (!ret) {
1703             ast_delete(exp);
1704             return false;
1705         }
1706     } else {
1707         if (!parser_next(parser))
1708             parseerror(parser, "parse error");
1709         if (expected->expression.next->expression.vtype != TYPE_VOID) {
1710             if (opts_standard != COMPILER_GMQCC)
1711                 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1712             else
1713                 parseerror(parser, "return without value");
1714         }
1715         ret = ast_return_new(parser_ctx(parser), NULL);
1716     }
1717     *out = (ast_expression*)ret;
1718     return true;
1719 }
1720
1721 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1722 {
1723     lex_ctx ctx = parser_ctx(parser);
1724
1725     if (!parser_next(parser) || parser->tok != ';') {
1726         parseerror(parser, "expected semicolon");
1727         return false;
1728     }
1729
1730     if (!parser_next(parser))
1731         parseerror(parser, "parse error");
1732
1733     *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1734     return true;
1735 }
1736
1737 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1738 {
1739     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1740     {
1741         /* local variable */
1742         if (!block) {
1743             parseerror(parser, "cannot declare a variable from here");
1744             return false;
1745         }
1746         if (opts_standard == COMPILER_QCC) {
1747             if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1748                 return false;
1749         }
1750         if (!parse_variable(parser, block, false))
1751             return false;
1752         *out = NULL;
1753         return true;
1754     }
1755     else if (parser->tok == TOKEN_KEYWORD)
1756     {
1757         if (!strcmp(parser_tokval(parser), "local"))
1758         {
1759             if (!block) {
1760                 parseerror(parser, "cannot declare a local variable here");
1761                 return false;
1762             }
1763             if (!parser_next(parser)) {
1764                 parseerror(parser, "expected variable declaration");
1765                 return false;
1766             }
1767             if (!parse_variable(parser, block, true))
1768                 return false;
1769             *out = NULL;
1770             return true;
1771         }
1772         else if (!strcmp(parser_tokval(parser), "return"))
1773         {
1774             return parse_return(parser, block, out);
1775         }
1776         else if (!strcmp(parser_tokval(parser), "if"))
1777         {
1778             return parse_if(parser, block, out);
1779         }
1780         else if (!strcmp(parser_tokval(parser), "while"))
1781         {
1782             return parse_while(parser, block, out);
1783         }
1784         else if (!strcmp(parser_tokval(parser), "do"))
1785         {
1786             return parse_dowhile(parser, block, out);
1787         }
1788         else if (!strcmp(parser_tokval(parser), "for"))
1789         {
1790             if (opts_standard == COMPILER_QCC) {
1791                 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1792                     return false;
1793             }
1794             return parse_for(parser, block, out);
1795         }
1796         else if (!strcmp(parser_tokval(parser), "break"))
1797         {
1798             return parse_break_continue(parser, block, out, false);
1799         }
1800         else if (!strcmp(parser_tokval(parser), "continue"))
1801         {
1802             return parse_break_continue(parser, block, out, true);
1803         }
1804         parseerror(parser, "Unexpected keyword");
1805         return false;
1806     }
1807     else if (parser->tok == '{')
1808     {
1809         ast_block *inner;
1810         inner = parse_block(parser, false);
1811         if (!inner)
1812             return false;
1813         *out = (ast_expression*)inner;
1814         return true;
1815     }
1816     else
1817     {
1818         ast_expression *exp = parse_expression(parser, false);
1819         if (!exp)
1820             return false;
1821         *out = exp;
1822         if (!ast_istype(exp, ast_store) &&
1823             !ast_istype(exp, ast_call) &&
1824             !ast_istype(exp, ast_binstore))
1825         {
1826             if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1827                 return false;
1828         }
1829         return true;
1830     }
1831 }
1832
1833 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1834 {
1835     bool rv = true;
1836     varentry_t *ve;
1837
1838     ve = &vec_last(parser->locals);
1839     if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1840         if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1841             rv = false;
1842     }
1843     mem_d(ve->name);
1844     vec_pop(parser->locals);
1845     return rv;
1846 }
1847
1848 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1849 {
1850     size_t oldblocklocal;
1851     bool   retval = true;
1852
1853     oldblocklocal = parser->blocklocal;
1854     parser->blocklocal = vec_size(parser->locals);
1855
1856     if (!parser_next(parser)) { /* skip the '{' */
1857         parseerror(parser, "expected function body");
1858         goto cleanup;
1859     }
1860
1861     while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1862     {
1863         ast_expression *expr;
1864         if (parser->tok == '}')
1865             break;
1866
1867         if (!parse_statement(parser, block, &expr)) {
1868             /* parseerror(parser, "parse error"); */
1869             block = NULL;
1870             goto cleanup;
1871         }
1872         if (!expr)
1873             continue;
1874         vec_push(block->exprs, expr);
1875     }
1876
1877     if (parser->tok != '}') {
1878         block = NULL;
1879     } else {
1880         if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1881         {
1882             if (!vec_size(block->exprs) ||
1883                 !ast_istype(vec_last(block->exprs), ast_return))
1884             {
1885                 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1886                     block = NULL;
1887                     goto cleanup;
1888                 }
1889             }
1890         }
1891         (void)parser_next(parser);
1892     }
1893
1894 cleanup:
1895     while (vec_size(parser->locals) > parser->blocklocal)
1896         retval = retval && parser_pop_local(parser);
1897     parser->blocklocal = oldblocklocal;
1898     return !!block;
1899 }
1900
1901 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1902 {
1903     ast_block *block;
1904     block = ast_block_new(parser_ctx(parser));
1905     if (!block)
1906         return NULL;
1907     if (!parse_block_into(parser, block, warnreturn)) {
1908         ast_block_delete(block);
1909         return NULL;
1910     }
1911     return block;
1912 }
1913
1914 static ast_expression* parse_statement_or_block(parser_t *parser)
1915 {
1916     ast_expression *expr = NULL;
1917     if (parser->tok == '{')
1918         return (ast_expression*)parse_block(parser, false);
1919     if (!parse_statement(parser, NULL, &expr))
1920         return NULL;
1921     return expr;
1922 }
1923
1924 /* loop method */
1925 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1926 {
1927     size_t i;
1928     size_t len = strlen(var->name);
1929
1930     for (i = 0; i < 3; ++i) {
1931         ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1932         if (!ve[i].var)
1933             break;
1934
1935         ve[i].name = (char*)mem_a(len+3);
1936         if (!ve[i].name) {
1937             ast_delete(ve[i].var);
1938             break;
1939         }
1940
1941         memcpy(ve[i].name, var->name, len);
1942         ve[i].name[len]   = '_';
1943         ve[i].name[len+1] = 'x'+i;
1944         ve[i].name[len+2] = 0;
1945     }
1946     if (i == 3)
1947         return true;
1948
1949     /* unroll */
1950     do {
1951         --i;
1952         mem_d(ve[i].name);
1953         ast_delete(ve[i].var);
1954         ve[i].name = NULL;
1955         ve[i].var  = NULL;
1956     } while (i);
1957     return false;
1958 }
1959
1960 static bool parse_function_body(parser_t *parser, ast_value *var)
1961 {
1962     ast_block      *block = NULL;
1963     ast_function   *func;
1964     ast_function   *old;
1965     size_t          parami;
1966
1967     ast_expression *framenum  = NULL;
1968     ast_expression *nextthink = NULL;
1969     /* None of the following have to be deleted */
1970     ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1971     ast_expression *gbl_time = NULL, *gbl_self = NULL;
1972     bool            has_frame_think;
1973
1974     bool retval = true;
1975
1976     has_frame_think = false;
1977     old = parser->function;
1978
1979     if (var->expression.variadic) {
1980         if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1981                          "variadic function with implementation will not be able to access additional parameters"))
1982         {
1983             return false;
1984         }
1985     }
1986
1987     if (parser->tok == '[') {
1988         /* got a frame definition: [ framenum, nextthink ]
1989          * this translates to:
1990          * self.frame = framenum;
1991          * self.nextthink = time + 0.1;
1992          * self.think = nextthink;
1993          */
1994         nextthink = NULL;
1995
1996         fld_think     = parser_find_field(parser, "think");
1997         fld_nextthink = parser_find_field(parser, "nextthink");
1998         fld_frame     = parser_find_field(parser, "frame");
1999         if (!fld_think || !fld_nextthink || !fld_frame) {
2000             parseerror(parser, "cannot use [frame,think] notation without the required fields");
2001             parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2002             return false;
2003         }
2004         gbl_time      = parser_find_global(parser, "time");
2005         gbl_self      = parser_find_global(parser, "self");
2006         if (!gbl_time || !gbl_self) {
2007             parseerror(parser, "cannot use [frame,think] notation without the required globals");
2008             parseerror(parser, "please declare the following globals: `time`, `self`");
2009             return false;
2010         }
2011
2012         if (!parser_next(parser))
2013             return false;
2014
2015         framenum = parse_expression_leave(parser, true);
2016         if (!framenum) {
2017             parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2018             return false;
2019         }
2020         if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2021             ast_unref(framenum);
2022             parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2023             return false;
2024         }
2025
2026         if (parser->tok != ',') {
2027             ast_unref(framenum);
2028             parseerror(parser, "expected comma after frame number in [frame,think] notation");
2029             parseerror(parser, "Got a %i\n", parser->tok);
2030             return false;
2031         }
2032
2033         if (!parser_next(parser)) {
2034             ast_unref(framenum);
2035             return false;
2036         }
2037
2038         if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2039         {
2040             /* qc allows the use of not-yet-declared functions here
2041              * - this automatically creates a prototype */
2042             varentry_t      varent;
2043             ast_value      *thinkfunc;
2044             ast_expression *functype = fld_think->expression.next;
2045
2046             thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2047             if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2048                 ast_unref(framenum);
2049                 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2050                 return false;
2051             }
2052
2053             if (!parser_next(parser)) {
2054                 ast_unref(framenum);
2055                 ast_delete(thinkfunc);
2056                 return false;
2057             }
2058
2059             varent.var = (ast_expression*)thinkfunc;
2060             varent.name = util_strdup(thinkfunc->name);
2061             vec_push(parser->globals, varent);
2062             nextthink = (ast_expression*)thinkfunc;
2063
2064         } else {
2065             nextthink = parse_expression_leave(parser, true);
2066             if (!nextthink) {
2067                 ast_unref(framenum);
2068                 parseerror(parser, "expected a think-function in [frame,think] notation");
2069                 return false;
2070             }
2071         }
2072
2073         if (!ast_istype(nextthink, ast_value)) {
2074             parseerror(parser, "think-function in [frame,think] notation must be a constant");
2075             retval = false;
2076         }
2077
2078         if (retval && parser->tok != ']') {
2079             parseerror(parser, "expected closing `]` for [frame,think] notation");
2080             retval = false;
2081         }
2082
2083         if (retval && !parser_next(parser)) {
2084             retval = false;
2085         }
2086
2087         if (retval && parser->tok != '{') {
2088             parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2089             retval = false;
2090         }
2091
2092         if (!retval) {
2093             ast_unref(nextthink);
2094             ast_unref(framenum);
2095             return false;
2096         }
2097
2098         has_frame_think = true;
2099     }
2100
2101     block = ast_block_new(parser_ctx(parser));
2102     if (!block) {
2103         parseerror(parser, "failed to allocate block");
2104         if (has_frame_think) {
2105             ast_unref(nextthink);
2106             ast_unref(framenum);
2107         }
2108         return false;
2109     }
2110
2111     if (has_frame_think) {
2112         lex_ctx ctx;
2113         ast_expression *self_frame;
2114         ast_expression *self_nextthink;
2115         ast_expression *self_think;
2116         ast_expression *time_plus_1;
2117         ast_store *store_frame;
2118         ast_store *store_nextthink;
2119         ast_store *store_think;
2120
2121         ctx = parser_ctx(parser);
2122         self_frame     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2123         self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2124         self_think     = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2125
2126         time_plus_1    = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2127                          gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2128
2129         if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2130             if (self_frame)     ast_delete(self_frame);
2131             if (self_nextthink) ast_delete(self_nextthink);
2132             if (self_think)     ast_delete(self_think);
2133             if (time_plus_1)    ast_delete(time_plus_1);
2134             retval = false;
2135         }
2136
2137         if (retval)
2138         {
2139             store_frame     = ast_store_new(ctx, INSTR_STOREP_F,   self_frame,     framenum);
2140             store_nextthink = ast_store_new(ctx, INSTR_STOREP_F,   self_nextthink, time_plus_1);
2141             store_think     = ast_store_new(ctx, INSTR_STOREP_FNC, self_think,     nextthink);
2142
2143             if (!store_frame) {
2144                 ast_delete(self_frame);
2145                 retval = false;
2146             }
2147             if (!store_nextthink) {
2148                 ast_delete(self_nextthink);
2149                 retval = false;
2150             }
2151             if (!store_think) {
2152                 ast_delete(self_think);
2153                 retval = false;
2154             }
2155             if (!retval) {
2156                 if (store_frame)     ast_delete(store_frame);
2157                 if (store_nextthink) ast_delete(store_nextthink);
2158                 if (store_think)     ast_delete(store_think);
2159                 retval = false;
2160             }
2161             vec_push(block->exprs, (ast_expression*)store_frame);
2162             vec_push(block->exprs, (ast_expression*)store_nextthink);
2163             vec_push(block->exprs, (ast_expression*)store_think);
2164         }
2165
2166         if (!retval) {
2167             parseerror(parser, "failed to generate code for [frame,think]");
2168             ast_unref(nextthink);
2169             ast_unref(framenum);
2170             ast_delete(block);
2171             return false;
2172         }
2173     }
2174
2175     for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2176         size_t     e;
2177         varentry_t ve[3];
2178         ast_value *param = var->expression.params[parami];
2179
2180         if (param->expression.vtype != TYPE_VECTOR &&
2181             (param->expression.vtype != TYPE_FIELD ||
2182              param->expression.next->expression.vtype != TYPE_VECTOR))
2183         {
2184             continue;
2185         }
2186
2187         if (!create_vector_members(parser, param, ve)) {
2188             ast_block_delete(block);
2189             return false;
2190         }
2191
2192         for (e = 0; e < 3; ++e) {
2193             vec_push(parser->locals, ve[e]);
2194             ast_block_collect(block, ve[e].var);
2195             ve[e].var = NULL; /* collected */
2196         }
2197     }
2198
2199     func = ast_function_new(ast_ctx(var), var->name, var);
2200     if (!func) {
2201         parseerror(parser, "failed to allocate function for `%s`", var->name);
2202         ast_block_delete(block);
2203         goto enderr;
2204     }
2205     vec_push(parser->functions, func);
2206
2207     parser->function = func;
2208     if (!parse_block_into(parser, block, true)) {
2209         ast_block_delete(block);
2210         goto enderrfn;
2211     }
2212
2213     vec_push(func->blocks, block);
2214
2215     parser->function = old;
2216     while (vec_size(parser->locals))
2217         retval = retval && parser_pop_local(parser);
2218
2219     if (parser->tok == ';')
2220         return parser_next(parser);
2221     else if (opts_standard == COMPILER_QCC)
2222         parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2223     return retval;
2224
2225 enderrfn:
2226     vec_pop(parser->functions);
2227     ast_function_delete(func);
2228     var->constval.vfunc = NULL;
2229
2230 enderr:
2231     while (vec_size(parser->locals)) {
2232         mem_d(vec_last(parser->locals).name);
2233         vec_pop(parser->locals);
2234     }
2235     parser->function = old;
2236     return false;
2237 }
2238
2239 static ast_expression *array_accessor_split(
2240     parser_t  *parser,
2241     ast_value *array,
2242     ast_value *index,
2243     size_t     middle,
2244     ast_expression *left,
2245     ast_expression *right
2246     )
2247 {
2248     ast_ifthen *ifthen;
2249     ast_binary *cmp;
2250
2251     lex_ctx ctx = ast_ctx(array);
2252
2253     if (!left || !right) {
2254         if (left)  ast_delete(left);
2255         if (right) ast_delete(right);
2256         return NULL;
2257     }
2258
2259     cmp = ast_binary_new(ctx, INSTR_LT,
2260                          (ast_expression*)index,
2261                          (ast_expression*)parser_const_float(parser, middle));
2262     if (!cmp) {
2263         ast_delete(left);
2264         ast_delete(right);
2265         parseerror(parser, "internal error: failed to create comparison for array setter");
2266         return NULL;
2267     }
2268
2269     ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2270     if (!ifthen) {
2271         ast_delete(cmp); /* will delete left and right */
2272         parseerror(parser, "internal error: failed to create conditional jump for array setter");
2273         return NULL;
2274     }
2275
2276     return (ast_expression*)ifthen;
2277 }
2278
2279 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2280 {
2281     lex_ctx ctx = ast_ctx(array);
2282
2283     if (from+1 == afterend) {
2284         // set this value
2285         ast_block       *block;
2286         ast_return      *ret;
2287         ast_array_index *subscript;
2288         int assignop = type_store_instr[value->expression.vtype];
2289
2290         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2291             assignop = INSTR_STORE_V;
2292
2293         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2294         if (!subscript)
2295             return NULL;
2296
2297         ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2298         if (!st) {
2299             ast_delete(subscript);
2300             return NULL;
2301         }
2302
2303         block = ast_block_new(ctx);
2304         if (!block) {
2305             ast_delete(st);
2306             return NULL;
2307         }
2308
2309         vec_push(block->exprs, (ast_expression*)st);
2310
2311         ret = ast_return_new(ctx, NULL);
2312         if (!ret) {
2313             ast_delete(block);
2314             return NULL;
2315         }
2316
2317         vec_push(block->exprs, (ast_expression*)ret);
2318
2319         return (ast_expression*)block;
2320     } else {
2321         ast_expression *left, *right;
2322         size_t diff = afterend - from;
2323         size_t middle = from + diff/2;
2324         left  = array_setter_node(parser, array, index, value, from, middle);
2325         right = array_setter_node(parser, array, index, value, middle, afterend);
2326         return array_accessor_split(parser, array, index, middle, left, right);
2327     }
2328 }
2329
2330 static ast_expression *array_field_setter_node(
2331     parser_t  *parser,
2332     ast_value *array,
2333     ast_value *entity,
2334     ast_value *index,
2335     ast_value *value,
2336     size_t     from,
2337     size_t     afterend)
2338 {
2339     lex_ctx ctx = ast_ctx(array);
2340
2341     if (from+1 == afterend) {
2342         // set this value
2343         ast_block       *block;
2344         ast_return      *ret;
2345         ast_entfield    *entfield;
2346         ast_array_index *subscript;
2347         int assignop = type_storep_instr[value->expression.vtype];
2348
2349         if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2350             assignop = INSTR_STOREP_V;
2351
2352         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2353         if (!subscript)
2354             return NULL;
2355
2356         entfield = ast_entfield_new_force(ctx,
2357                                           (ast_expression*)entity,
2358                                           (ast_expression*)subscript,
2359                                           (ast_expression*)subscript);
2360         if (!entfield) {
2361             ast_delete(subscript);
2362             return NULL;
2363         }
2364
2365         ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2366         if (!st) {
2367             ast_delete(entfield);
2368             return NULL;
2369         }
2370
2371         block = ast_block_new(ctx);
2372         if (!block) {
2373             ast_delete(st);
2374             return NULL;
2375         }
2376
2377         vec_push(block->exprs, (ast_expression*)st);
2378
2379         ret = ast_return_new(ctx, NULL);
2380         if (!ret) {
2381             ast_delete(block);
2382             return NULL;
2383         }
2384
2385         vec_push(block->exprs, (ast_expression*)ret);
2386
2387         return (ast_expression*)block;
2388     } else {
2389         ast_expression *left, *right;
2390         size_t diff = afterend - from;
2391         size_t middle = from + diff/2;
2392         left  = array_field_setter_node(parser, array, entity, index, value, from, middle);
2393         right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2394         return array_accessor_split(parser, array, index, middle, left, right);
2395     }
2396 }
2397
2398 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2399 {
2400     lex_ctx ctx = ast_ctx(array);
2401
2402     if (from+1 == afterend) {
2403         ast_return      *ret;
2404         ast_array_index *subscript;
2405
2406         subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2407         if (!subscript)
2408             return NULL;
2409
2410         ret = ast_return_new(ctx, (ast_expression*)subscript);
2411         if (!ret) {
2412             ast_delete(subscript);
2413             return NULL;
2414         }
2415
2416         return (ast_expression*)ret;
2417     } else {
2418         ast_expression *left, *right;
2419         size_t diff = afterend - from;
2420         size_t middle = from + diff/2;
2421         left  = array_getter_node(parser, array, index, from, middle);
2422         right = array_getter_node(parser, array, index, middle, afterend);
2423         return array_accessor_split(parser, array, index, middle, left, right);
2424     }
2425 }
2426
2427 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2428 {
2429     ast_function   *func = NULL;
2430     ast_value      *fval = NULL;
2431     ast_block      *body = NULL;
2432
2433     fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2434     if (!fval) {
2435         parseerror(parser, "failed to create accessor function value");
2436         return false;
2437     }
2438
2439     func = ast_function_new(ast_ctx(array), funcname, fval);
2440     if (!func) {
2441         ast_delete(fval);
2442         parseerror(parser, "failed to create accessor function node");
2443         return false;
2444     }
2445
2446     body = ast_block_new(ast_ctx(array));
2447     if (!body) {
2448         parseerror(parser, "failed to create block for array accessor");
2449         ast_delete(fval);
2450         ast_delete(func);
2451         return false;
2452     }
2453
2454     vec_push(func->blocks, body);
2455     *out = fval;
2456
2457     vec_push(parser->accessors, fval);
2458
2459     return true;
2460 }
2461
2462 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2463 {
2464     ast_expression *root = NULL;
2465     ast_value      *index = NULL;
2466     ast_value      *value = NULL;
2467     ast_function   *func;
2468     ast_value      *fval;
2469
2470     if (!ast_istype(array->expression.next, ast_value)) {
2471         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2472         return false;
2473     }
2474
2475     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2476         return false;
2477     func = fval->constval.vfunc;
2478     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2479
2480     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2481     value = ast_value_copy((ast_value*)array->expression.next);
2482
2483     if (!index || !value) {
2484         parseerror(parser, "failed to create locals for array accessor");
2485         goto cleanup;
2486     }
2487     (void)!ast_value_set_name(value, "value"); /* not important */
2488     vec_push(fval->expression.params, index);
2489     vec_push(fval->expression.params, value);
2490
2491     root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2492     if (!root) {
2493         parseerror(parser, "failed to build accessor search tree");
2494         goto cleanup;
2495     }
2496
2497     vec_push(func->blocks[0]->exprs, root);
2498     array->setter = fval;
2499     return true;
2500 cleanup:
2501     if (index) ast_delete(index);
2502     if (value) ast_delete(value);
2503     if (root)  ast_delete(root);
2504     ast_delete(func);
2505     ast_delete(fval);
2506     return false;
2507 }
2508
2509 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2510 {
2511     ast_expression *root = NULL;
2512     ast_value      *entity = NULL;
2513     ast_value      *index = NULL;
2514     ast_value      *value = NULL;
2515     ast_function   *func;
2516     ast_value      *fval;
2517
2518     if (!ast_istype(array->expression.next, ast_value)) {
2519         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2520         return false;
2521     }
2522
2523     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2524         return false;
2525     func = fval->constval.vfunc;
2526     fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2527
2528     entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2529     index  = ast_value_new(ast_ctx(array), "index",  TYPE_FLOAT);
2530     value  = ast_value_copy((ast_value*)array->expression.next);
2531     if (!entity || !index || !value) {
2532         parseerror(parser, "failed to create locals for array accessor");
2533         goto cleanup;
2534     }
2535     (void)!ast_value_set_name(value, "value"); /* not important */
2536     vec_push(fval->expression.params, entity);
2537     vec_push(fval->expression.params, index);
2538     vec_push(fval->expression.params, value);
2539
2540     root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2541     if (!root) {
2542         parseerror(parser, "failed to build accessor search tree");
2543         goto cleanup;
2544     }
2545
2546     vec_push(func->blocks[0]->exprs, root);
2547     array->setter = fval;
2548     return true;
2549 cleanup:
2550     if (entity) ast_delete(entity);
2551     if (index)  ast_delete(index);
2552     if (value)  ast_delete(value);
2553     if (root)   ast_delete(root);
2554     ast_delete(func);
2555     ast_delete(fval);
2556     return false;
2557 }
2558
2559 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2560 {
2561     ast_expression *root = NULL;
2562     ast_value      *index = NULL;
2563     ast_value      *fval;
2564     ast_function   *func;
2565
2566     /* NOTE: checking array->expression.next rather than elemtype since
2567      * for fields elemtype is a temporary fieldtype.
2568      */
2569     if (!ast_istype(array->expression.next, ast_value)) {
2570         parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2571         return false;
2572     }
2573
2574     if (!parser_create_array_accessor(parser, array, funcname, &fval))
2575         return false;
2576     func = fval->constval.vfunc;
2577     fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2578
2579     index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2580
2581     if (!index) {
2582         parseerror(parser, "failed to create locals for array accessor");
2583         goto cleanup;
2584     }
2585     vec_push(fval->expression.params, index);
2586
2587     root = array_getter_node(parser, array, index, 0, array->expression.count);
2588     if (!root) {
2589         parseerror(parser, "failed to build accessor search tree");
2590         goto cleanup;
2591     }
2592
2593     vec_push(func->blocks[0]->exprs, root);
2594     array->getter = fval;
2595     return true;
2596 cleanup:
2597     if (index) ast_delete(index);
2598     if (root)  ast_delete(root);
2599     ast_delete(func);
2600     ast_delete(fval);
2601     return false;
2602 }
2603
2604 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2605 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2606 {
2607     lex_ctx     ctx;
2608     size_t      i;
2609     ast_value **params;
2610     ast_value  *param;
2611     ast_value  *fval;
2612     bool        first = true;
2613     bool        variadic = false;
2614
2615     ctx = parser_ctx(parser);
2616
2617     /* for the sake of less code we parse-in in this function */
2618     if (!parser_next(parser)) {
2619         parseerror(parser, "expected parameter list");
2620         return NULL;
2621     }
2622
2623     params = NULL;
2624
2625     /* parse variables until we hit a closing paren */
2626     while (parser->tok != ')') {
2627         if (!first) {
2628             /* there must be commas between them */
2629             if (parser->tok != ',') {
2630                 parseerror(parser, "expected comma or end of parameter list");
2631                 goto on_error;
2632             }
2633             if (!parser_next(parser)) {
2634                 parseerror(parser, "expected parameter");
2635                 goto on_error;
2636             }
2637         }
2638         first = false;
2639
2640         if (parser->tok == TOKEN_DOTS) {
2641             /* '...' indicates a varargs function */
2642             variadic = true;
2643             if (!parser_next(parser)) {
2644                 parseerror(parser, "expected parameter");
2645                 return NULL;
2646             }
2647             if (parser->tok != ')') {
2648                 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2649                 goto on_error;
2650             }
2651         }
2652         else
2653         {
2654             /* for anything else just parse a typename */
2655             param = parse_typename(parser, NULL);
2656             if (!param)
2657                 goto on_error;
2658             vec_push(params, param);
2659             if (param->expression.vtype >= TYPE_VARIANT) {
2660                 char typename[1024];
2661                 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2662                 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2663                 goto on_error;
2664             }
2665         }
2666     }
2667
2668     /* sanity check */
2669     if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
2670         (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
2671
2672     /* parse-out */
2673     if (!parser_next(parser)) {
2674         parseerror(parser, "parse error after typename");
2675         goto on_error;
2676     }
2677
2678     /* now turn 'var' into a function type */
2679     fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2680     fval->expression.next     = (ast_expression*)var;
2681     fval->expression.variadic = variadic;
2682     var = fval;
2683
2684     var->expression.params = params;
2685     params = NULL;
2686
2687     return var;
2688
2689 on_error:
2690     ast_delete(var);
2691     for (i = 0; i < vec_size(params); ++i)
2692         ast_delete(params[i]);
2693     vec_free(params);
2694     return NULL;
2695 }
2696
2697 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2698 {
2699     ast_expression *cexp;
2700     ast_value      *cval, *tmp;
2701     lex_ctx ctx;
2702
2703     ctx = parser_ctx(parser);
2704
2705     if (!parser_next(parser)) {
2706         ast_delete(var);
2707         parseerror(parser, "expected array-size");
2708         return NULL;
2709     }
2710
2711     cexp = parse_expression_leave(parser, true);
2712
2713     if (!cexp || !ast_istype(cexp, ast_value)) {
2714         if (cexp)
2715             ast_unref(cexp);
2716         ast_delete(var);
2717         parseerror(parser, "expected array-size as constant positive integer");
2718         return NULL;
2719     }
2720     cval = (ast_value*)cexp;
2721
2722     tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2723     tmp->expression.next = (ast_expression*)var;
2724     var = tmp;
2725
2726     if (cval->expression.vtype == TYPE_INTEGER)
2727         tmp->expression.count = cval->constval.vint;
2728     else if (cval->expression.vtype == TYPE_FLOAT)
2729         tmp->expression.count = cval->constval.vfloat;
2730     else {
2731         ast_unref(cexp);
2732         ast_delete(var);
2733         parseerror(parser, "array-size must be a positive integer constant");
2734         return NULL;
2735     }
2736     ast_unref(cexp);
2737
2738     if (parser->tok != ']') {
2739         ast_delete(var);
2740         parseerror(parser, "expected ']' after array-size");
2741         return NULL;
2742     }
2743     if (!parser_next(parser)) {
2744         ast_delete(var);
2745         parseerror(parser, "error after parsing array size");
2746         return NULL;
2747     }
2748     return var;
2749 }
2750
2751 /* Parse a complete typename.
2752  * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2753  * but when parsing variables separated by comma
2754  * 'storebase' should point to where the base-type should be kept.
2755  * The base type makes up every bit of type information which comes *before* the
2756  * variable name.
2757  *
2758  * The following will be parsed in its entirety:
2759  *     void() foo()
2760  * The 'basetype' in this case is 'void()'
2761  * and if there's a comma after it, say:
2762  *     void() foo(), bar
2763  * then the type-information 'void()' can be stored in 'storebase'
2764  */
2765 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2766 {
2767     ast_value *var, *tmp;
2768     lex_ctx    ctx;
2769
2770     const char *name = NULL;
2771     bool        isfield  = false;
2772     bool        wasarray = false;
2773
2774     ctx = parser_ctx(parser);
2775
2776     /* types may start with a dot */
2777     if (parser->tok == '.') {
2778         isfield = true;
2779         /* if we parsed a dot we need a typename now */
2780         if (!parser_next(parser)) {
2781             parseerror(parser, "expected typename for field definition");
2782             return NULL;
2783         }
2784         if (parser->tok != TOKEN_TYPENAME) {
2785             parseerror(parser, "expected typename");
2786             return NULL;
2787         }
2788     }
2789
2790     /* generate the basic type value */
2791     var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2792     /* do not yet turn into a field - remember:
2793      * .void() foo; is a field too
2794      * .void()() foo; is a function
2795      */
2796
2797     /* parse on */
2798     if (!parser_next(parser)) {
2799         ast_delete(var);
2800         parseerror(parser, "parse error after typename");
2801         return NULL;
2802     }
2803
2804     /* an opening paren now starts the parameter-list of a function
2805      * this is where original-QC has parameter lists.
2806      * We allow a single parameter list here.
2807      * Much like fteqcc we don't allow `float()() x`
2808      */
2809     if (parser->tok == '(') {
2810         var = parse_parameter_list(parser, var);
2811         if (!var)
2812             return NULL;
2813     }
2814
2815     /* store the base if requested */
2816     if (storebase) {
2817         *storebase = ast_value_copy(var);
2818         if (isfield) {
2819             tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2820             tmp->expression.next = (ast_expression*)*storebase;
2821             *storebase = tmp;
2822         }
2823     }
2824
2825     /* there may be a name now */
2826     if (parser->tok == TOKEN_IDENT) {
2827         name = util_strdup(parser_tokval(parser));
2828         /* parse on */
2829         if (!parser_next(parser)) {
2830             ast_delete(var);
2831             parseerror(parser, "error after variable or field declaration");
2832             return NULL;
2833         }
2834     }
2835
2836     /* now this may be an array */
2837     if (parser->tok == '[') {
2838         wasarray = true;
2839         var = parse_arraysize(parser, var);
2840         if (!var)
2841             return NULL;
2842     }
2843
2844     /* This is the point where we can turn it into a field */
2845     if (isfield) {
2846         /* turn it into a field if desired */
2847         tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2848         tmp->expression.next = (ast_expression*)var;
2849         var = tmp;
2850     }
2851
2852     /* now there may be function parens again */
2853     if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2854         parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2855     if (parser->tok == '(' && wasarray)
2856         parseerror(parser, "arrays as part of a return type is not supported");
2857     while (parser->tok == '(') {
2858         var = parse_parameter_list(parser, var);
2859         if (!var) {
2860             if (name)
2861                 mem_d((void*)name);
2862             ast_delete(var);
2863             return NULL;
2864         }
2865     }
2866
2867     /* finally name it */
2868     if (name) {
2869         if (!ast_value_set_name(var, name)) {
2870             ast_delete(var);
2871             parseerror(parser, "internal error: failed to set name");
2872             return NULL;
2873         }
2874         /* free the name, ast_value_set_name duplicates */
2875         mem_d((void*)name);
2876     }
2877
2878     return var;
2879 }
2880
2881 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2882 {
2883     ast_value *var;
2884     ast_value *proto;
2885     ast_expression *old;
2886     bool       was_end;
2887     size_t     i;
2888
2889     ast_value *basetype = NULL;
2890     bool      retval    = true;
2891     bool      isparam   = false;
2892     bool      isvector  = false;
2893     bool      cleanvar  = true;
2894     bool      wasarray  = false;
2895
2896     varentry_t varent, ve[3];
2897
2898     /* get the first complete variable */
2899     var = parse_typename(parser, &basetype);
2900     if (!var) {
2901         if (basetype)
2902             ast_delete(basetype);
2903         return false;
2904     }
2905
2906     memset(&varent, 0, sizeof(varent));
2907     memset(&ve, 0, sizeof(ve));
2908
2909     while (true) {
2910         proto = NULL;
2911         wasarray = false;
2912
2913         /* Part 0: finish the type */
2914         if (parser->tok == '(') {
2915             if (opts_standard == COMPILER_QCC)
2916                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2917             var = parse_parameter_list(parser, var);
2918             if (!var) {
2919                 retval = false;
2920                 goto cleanup;
2921             }
2922         }
2923         /* we only allow 1-dimensional arrays */
2924         if (parser->tok == '[') {
2925             wasarray = true;
2926             var = parse_arraysize(parser, var);
2927             if (!var) {
2928                 retval = false;
2929                 goto cleanup;
2930             }
2931         }
2932         if (parser->tok == '(' && wasarray) {
2933             parseerror(parser, "arrays as part of a return type is not supported");
2934             /* we'll still parse the type completely for now */
2935         }
2936         /* for functions returning functions */
2937         while (parser->tok == '(') {
2938             if (opts_standard == COMPILER_QCC)
2939                 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2940             var = parse_parameter_list(parser, var);
2941             if (!var) {
2942                 retval = false;
2943                 goto cleanup;
2944             }
2945         }
2946
2947         /* Part 1:
2948          * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2949          * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2950          * is then filled with the previous definition and the parameter-names replaced.
2951          */
2952         if (!localblock) {
2953             /* Deal with end_sys_ vars */
2954             was_end = false;
2955             if (!strcmp(var->name, "end_sys_globals")) {
2956                 parser->crc_globals = vec_size(parser->globals);
2957                 was_end = true;
2958             }
2959             else if (!strcmp(var->name, "end_sys_fields")) {
2960                 parser->crc_fields = vec_size(parser->fields);
2961                 was_end = true;
2962             }
2963             if (was_end && var->expression.vtype == TYPE_FIELD) {
2964                 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2965                                  "global '%s' hint should not be a field",
2966                                  parser_tokval(parser)))
2967                 {
2968                     retval = false;
2969                     goto cleanup;
2970                 }
2971             }
2972
2973             if (!nofields && var->expression.vtype == TYPE_FIELD)
2974             {
2975                 /* deal with field declarations */
2976                 old = parser_find_field(parser, var->name);
2977                 if (old) {
2978                     if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2979                                      var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2980                     {
2981                         retval = false;
2982                         goto cleanup;
2983                     }
2984                     ast_delete(var);
2985                     var = NULL;
2986                     goto skipvar;
2987                     /*
2988                     parseerror(parser, "field `%s` already declared here: %s:%i",
2989                                var->name, ast_ctx(old).file, ast_ctx(old).line);
2990                     retval = false;
2991                     goto cleanup;
2992                     */
2993                 }
2994                 if (opts_standard == COMPILER_QCC &&
2995                     (old = parser_find_global(parser, var->name)))
2996                 {
2997                     parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2998                     parseerror(parser, "field `%s` already declared here: %s:%i",
2999                                var->name, ast_ctx(old).file, ast_ctx(old).line);
3000                     retval = false;
3001                     goto cleanup;
3002                 }
3003             }
3004             else
3005             {
3006                 /* deal with other globals */
3007                 old = parser_find_global(parser, var->name);
3008                 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3009                 {
3010                     /* This is a function which had a prototype */
3011                     if (!ast_istype(old, ast_value)) {
3012                         parseerror(parser, "internal error: prototype is not an ast_value");
3013                         retval = false;
3014                         goto cleanup;
3015                     }
3016                     proto = (ast_value*)old;
3017                     if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3018                         parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3019                                    proto->name,
3020                                    ast_ctx(proto).file, ast_ctx(proto).line);
3021                         retval = false;
3022                         goto cleanup;
3023                     }
3024                     /* we need the new parameter-names */
3025                     for (i = 0; i < vec_size(proto->expression.params); ++i)
3026                         ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3027                     ast_delete(var);
3028                     var = proto;
3029                 }
3030                 else
3031                 {
3032                     /* other globals */
3033                     if (old) {
3034                         parseerror(parser, "global `%s` already declared here: %s:%i",
3035                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3036                         retval = false;
3037                         goto cleanup;
3038                     }
3039                     if (opts_standard == COMPILER_QCC &&
3040                         (old = parser_find_field(parser, var->name)))
3041                     {
3042                         parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3043                         parseerror(parser, "global `%s` already declared here: %s:%i",
3044                                    var->name, ast_ctx(old).file, ast_ctx(old).line);
3045                         retval = false;
3046                         goto cleanup;
3047                     }
3048                 }
3049             }
3050         }
3051         else /* it's not a global */
3052         {
3053             old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
3054             if (old && !isparam) {
3055                 parseerror(parser, "local `%s` already declared here: %s:%i",
3056                            var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3057                 retval = false;
3058                 goto cleanup;
3059             }
3060             old = parser_find_local(parser, var->name, 0, &isparam);
3061             if (old && isparam) {
3062                 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3063                                  "local `%s` is shadowing a parameter", var->name))
3064                 {
3065                     parseerror(parser, "local `%s` already declared here: %s:%i",
3066                                var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3067                     retval = false;
3068                     goto cleanup;
3069                 }
3070                 if (opts_standard != COMPILER_GMQCC) {
3071                     ast_delete(var);
3072                     var = NULL;
3073                     goto skipvar;
3074                 }
3075             }
3076         }
3077
3078         /* Part 2:
3079          * Create the global/local, and deal with vector types.
3080          */
3081         if (!proto) {
3082             if (var->expression.vtype == TYPE_VECTOR)
3083                 isvector = true;
3084             else if (var->expression.vtype == TYPE_FIELD &&
3085                      var->expression.next->expression.vtype == TYPE_VECTOR)
3086                 isvector = true;
3087
3088             if (isvector) {
3089                 if (!create_vector_members(parser, var, ve)) {
3090                     retval = false;
3091                     goto cleanup;
3092                 }
3093             }
3094
3095             varent.name = util_strdup(var->name);
3096             varent.var  = (ast_expression*)var;
3097
3098             if (!localblock) {
3099                 /* deal with global variables, fields, functions */
3100                 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3101                     vec_push(parser->fields, varent);
3102                     if (isvector) {
3103                         for (i = 0; i < 3; ++i)
3104                             vec_push(parser->fields, ve[i]);
3105                     }
3106                 }
3107                 else {
3108                     vec_push(parser->globals, varent);
3109                     if (isvector) {
3110                         for (i = 0; i < 3; ++i)
3111                             vec_push(parser->globals, ve[i]);
3112                     }
3113                 }
3114             } else {
3115                 vec_push(parser->locals, varent);
3116                 vec_push(localblock->locals, var);
3117                 if (isvector) {
3118                     for (i = 0; i < 3; ++i) {
3119                         vec_push(parser->locals, ve[i]);
3120                         ast_block_collect(localblock, ve[i].var);
3121                         ve[i].var = NULL; /* from here it's being collected in the block */
3122                     }
3123                 }
3124             }
3125
3126             varent.name = NULL;
3127             ve[0].name = ve[1].name = ve[2].name = NULL;
3128             ve[0].var  = ve[1].var  = ve[2].var  = NULL;
3129             cleanvar = false;
3130         }
3131         /* Part 2.2
3132          * deal with arrays
3133          */
3134         if (var->expression.vtype == TYPE_ARRAY) {
3135             char name[1024];
3136             snprintf(name, sizeof(name), "%s##SET", var->name);
3137             if (!parser_create_array_setter(parser, var, name))
3138                 goto cleanup;
3139             snprintf(name, sizeof(name), "%s##GET", var->name);
3140             if (!parser_create_array_getter(parser, var, var->expression.next, name))
3141                 goto cleanup;
3142         }
3143         else if (!localblock && !nofields &&
3144                  var->expression.vtype == TYPE_FIELD &&
3145                  var->expression.next->expression.vtype == TYPE_ARRAY)
3146         {
3147             char name[1024];
3148             ast_expression *telem;
3149             ast_value      *tfield;
3150             ast_value      *array = (ast_value*)var->expression.next;
3151
3152             if (!ast_istype(var->expression.next, ast_value)) {
3153                 parseerror(parser, "internal error: field element type must be an ast_value");
3154                 goto cleanup;
3155             }
3156
3157             snprintf(name, sizeof(name), "%s##SETF", var->name);
3158             if (!parser_create_array_field_setter(parser, array, name))
3159                 goto cleanup;
3160
3161             telem = ast_type_copy(ast_ctx(var), array->expression.next);
3162             tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3163             tfield->expression.next = telem;
3164             snprintf(name, sizeof(name), "%s##GETFP", var->name);
3165             if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3166                 ast_delete(tfield);
3167                 goto cleanup;
3168             }
3169             ast_delete(tfield);
3170         }
3171
3172 skipvar:
3173         if (parser->tok == ';') {
3174             ast_delete(basetype);
3175             if (!parser_next(parser)) {
3176                 parseerror(parser, "error after variable declaration");
3177                 return false;
3178             }
3179             return true;
3180         }
3181
3182         if (parser->tok == ',')
3183             goto another;
3184
3185         if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3186             parseerror(parser, "missing comma or semicolon while parsing variables");
3187             break;
3188         }
3189
3190         if (localblock && opts_standard == COMPILER_QCC) {
3191             if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3192                              "initializing expression turns variable `%s` into a constant in this standard",
3193                              var->name) )
3194             {
3195                 break;
3196             }
3197         }
3198
3199         if (parser->tok != '{') {
3200             if (parser->tok != '=') {
3201                 parseerror(parser, "missing semicolon or initializer");
3202                 break;
3203             }
3204
3205             if (!parser_next(parser)) {
3206                 parseerror(parser, "error parsing initializer");
3207                 break;
3208             }
3209         }
3210         else if (opts_standard == COMPILER_QCC) {
3211             parseerror(parser, "expected '=' before function body in this standard");
3212         }
3213
3214         if (parser->tok == '#') {
3215             ast_function *func;
3216
3217             if (localblock) {
3218                 parseerror(parser, "cannot declare builtins within functions");
3219                 break;
3220             }
3221             if (var->expression.vtype != TYPE_FUNCTION) {
3222                 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3223                 break;
3224             }
3225             if (!parser_next(parser)) {
3226                 parseerror(parser, "expected builtin number");
3227                 break;
3228             }
3229             if (parser->tok != TOKEN_INTCONST) {
3230                 parseerror(parser, "builtin number must be an integer constant");
3231                 break;
3232             }
3233             if (parser_token(parser)->constval.i <= 0) {
3234                 parseerror(parser, "builtin number must be an integer greater than zero");
3235                 break;
3236             }
3237
3238             func = ast_function_new(ast_ctx(var), var->name, var);
3239             if (!func) {
3240                 parseerror(parser, "failed to allocate function for `%s`", var->name);
3241                 break;
3242             }
3243             vec_push(parser->functions, func);
3244
3245             func->builtin = -parser_token(parser)->constval.i;
3246
3247             if (!parser_next(parser)) {
3248                 parseerror(parser, "expected comma or semicolon");
3249                 ast_function_delete(func);
3250                 var->constval.vfunc = NULL;
3251                 break;
3252             }
3253         }
3254         else if (parser->tok == '{' || parser->tok == '[')
3255         {
3256             if (localblock) {
3257                 parseerror(parser, "cannot declare functions within functions");
3258                 break;
3259             }
3260
3261             if (!parse_function_body(parser, var))
3262                 break;
3263             ast_delete(basetype);
3264             return true;
3265         } else {
3266             ast_expression *cexp;
3267             ast_value      *cval;
3268
3269             cexp = parse_expression_leave(parser, true);
3270             if (!cexp)
3271                 break;
3272
3273             if (!localblock) {
3274                 cval = (ast_value*)cexp;
3275                 if (!ast_istype(cval, ast_value) || !cval->isconst)
3276                     parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3277                 else
3278                 {
3279                     var->isconst = true;
3280                     if (cval->expression.vtype == TYPE_STRING)
3281                         var->constval.vstring = parser_strdup(cval->constval.vstring);
3282                     else
3283                         memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3284                     ast_unref(cval);
3285                 }
3286             } else {
3287                 shunt sy = { NULL, NULL };
3288                 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3289                 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3290                 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3291                 if (!parser_sy_pop(parser, &sy))
3292                     ast_unref(cexp);
3293                 else {
3294                     if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3295                         parseerror(parser, "internal error: leaked operands");
3296                     vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3297                 }
3298                 vec_free(sy.out);
3299                 vec_free(sy.ops);
3300             }
3301         }
3302
3303 another:
3304         if (parser->tok == ',') {
3305             if (!parser_next(parser)) {
3306                 parseerror(parser, "expected another variable");
3307                 break;
3308             }
3309
3310             if (parser->tok != TOKEN_IDENT) {
3311                 parseerror(parser, "expected another variable");
3312                 break;
3313             }
3314             var = ast_value_copy(basetype);
3315             cleanvar = true;
3316             ast_value_set_name(var, parser_tokval(parser));
3317             if (!parser_next(parser)) {
3318                 parseerror(parser, "error parsing variable declaration");
3319                 break;
3320             }
3321             continue;
3322         }
3323
3324         if (parser->tok != ';') {
3325             parseerror(parser, "missing semicolon after variables");
3326             break;
3327         }
3328
3329         if (!parser_next(parser)) {
3330             parseerror(parser, "parse error after variable declaration");
3331             break;
3332         }
3333
3334         ast_delete(basetype);
3335         return true;
3336     }
3337
3338     if (cleanvar && var)
3339         ast_delete(var);
3340     ast_delete(basetype);
3341     return false;
3342
3343 cleanup:
3344     ast_delete(basetype);
3345     if (cleanvar && var)
3346         ast_delete(var);
3347     if (varent.name) mem_d(varent.name);
3348     if (ve[0].name)  mem_d(ve[0].name);
3349     if (ve[1].name)  mem_d(ve[1].name);
3350     if (ve[2].name)  mem_d(ve[2].name);
3351     if (ve[0].var)   mem_d(ve[0].var);
3352     if (ve[1].var)   mem_d(ve[1].var);
3353     if (ve[2].var)   mem_d(ve[2].var);
3354     return retval;
3355 }
3356
3357 static bool parser_global_statement(parser_t *parser)
3358 {
3359     if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3360     {
3361         return parse_variable(parser, NULL, false);
3362     }
3363     else if (parser->tok == TOKEN_KEYWORD)
3364     {
3365         /* handle 'var' and 'const' */
3366         if (!strcmp(parser_tokval(parser), "var")) {
3367             if (!parser_next(parser)) {
3368                 parseerror(parser, "expected variable declaration after 'var'");
3369                 return false;
3370             }
3371             return parse_variable(parser, NULL, true);
3372         }
3373         return false;
3374     }
3375     else if (parser->tok == '$')
3376     {
3377         if (!parser_next(parser)) {
3378             parseerror(parser, "parse error");
3379             return false;
3380         }
3381     }
3382     else
3383     {
3384         parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3385         return false;
3386     }
3387     return true;
3388 }
3389
3390 static parser_t *parser;
3391
3392 bool parser_init()
3393 {
3394     size_t i;
3395     parser = (parser_t*)mem_a(sizeof(parser_t));
3396     if (!parser)
3397         return false;
3398
3399     memset(parser, 0, sizeof(*parser));
3400
3401     for (i = 0; i < operator_count; ++i) {
3402         if (operators[i].id == opid1('=')) {
3403             parser->assign_op = operators+i;
3404             break;
3405         }
3406     }
3407     if (!parser->assign_op) {
3408         printf("internal error: initializing parser: failed to find assign operator\n");
3409         mem_d(parser);
3410         return false;
3411     }
3412     return true;
3413 }
3414
3415 bool parser_compile()
3416 {
3417     /* initial lexer/parser state */
3418     parser->lex->flags.noops = true;
3419
3420     if (parser_next(parser))
3421     {
3422         while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3423         {
3424             if (!parser_global_statement(parser)) {
3425                 if (parser->tok == TOKEN_EOF)
3426                     parseerror(parser, "unexpected eof");
3427                 else if (!parser->errors)
3428                     parseerror(parser, "there have been errors, bailing out");
3429                 lex_close(parser->lex);
3430                 parser->lex = NULL;
3431                 return false;
3432             }
3433         }
3434     } else {
3435         parseerror(parser, "parse error");
3436         lex_close(parser->lex);
3437         parser->lex = NULL;
3438         return false;
3439     }
3440
3441     lex_close(parser->lex);
3442     parser->lex = NULL;
3443
3444     return !parser->errors;
3445 }
3446
3447 bool parser_compile_file(const char *filename)
3448 {
3449     parser->lex = lex_open(filename);
3450     if (!parser->lex) {
3451         con_err("failed to open file \"%s\"\n", filename);
3452         return false;
3453     }
3454     return parser_compile();
3455 }
3456
3457 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3458 {
3459     parser->lex = lex_open_string(str, len, name);
3460     if (!parser->lex) {
3461         con_err("failed to create lexer for string \"%s\"\n", name);
3462         return false;
3463     }
3464     return parser_compile();
3465 }
3466
3467 bool parser_compile_string(const char *name, const char *str)
3468 {
3469     parser->lex = lex_open_string(str, strlen(str), name);
3470     if (!parser->lex) {
3471         con_err("failed to create lexer for string \"%s\"\n", name);
3472         return false;
3473     }
3474     return parser_compile();
3475 }
3476
3477 void parser_cleanup()
3478 {
3479     size_t i;
3480     for (i = 0; i < vec_size(parser->accessors); ++i) {
3481         ast_delete(parser->accessors[i]->constval.vfunc);
3482         parser->accessors[i]->constval.vfunc = NULL;
3483         ast_delete(parser->accessors[i]);
3484     }
3485     for (i = 0; i < vec_size(parser->functions); ++i) {
3486         ast_delete(parser->functions[i]);
3487     }
3488     for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3489         ast_delete(parser->imm_vector[i]);
3490     }
3491     for (i = 0; i < vec_size(parser->imm_string); ++i) {
3492         ast_delete(parser->imm_string[i]);
3493     }
3494     for (i = 0; i < vec_size(parser->imm_float); ++i) {
3495         ast_delete(parser->imm_float[i]);
3496     }
3497     for (i = 0; i < vec_size(parser->fields); ++i) {
3498         ast_delete(parser->fields[i].var);
3499         mem_d(parser->fields[i].name);
3500     }
3501     for (i = 0; i < vec_size(parser->globals); ++i) {
3502         ast_delete(parser->globals[i].var);
3503         mem_d(parser->globals[i].name);
3504     }
3505     vec_free(parser->accessors);
3506     vec_free(parser->functions);
3507     vec_free(parser->imm_vector);
3508     vec_free(parser->imm_string);
3509     vec_free(parser->imm_float);
3510     vec_free(parser->globals);
3511     vec_free(parser->fields);
3512     vec_free(parser->locals);
3513
3514     mem_d(parser);
3515 }
3516
3517 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3518 {
3519     return util_crc16(old, str, strlen(str));
3520 }
3521
3522 static void progdefs_crc_file(const char *str)
3523 {
3524     /* write to progdefs.h here */
3525 }
3526
3527 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3528 {
3529     old = progdefs_crc_sum(old, str);
3530     progdefs_crc_file(str);
3531     return old;
3532 }
3533
3534 static void generate_checksum(parser_t *parser)
3535 {
3536     uint16_t crc = 0xFFFF;
3537     size_t i;
3538
3539         crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3540         crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3541         /*
3542         progdefs_crc_file("\tint\tpad;\n");
3543         progdefs_crc_file("\tint\tofs_return[3];\n");
3544         progdefs_crc_file("\tint\tofs_parm0[3];\n");
3545         progdefs_crc_file("\tint\tofs_parm1[3];\n");
3546         progdefs_crc_file("\tint\tofs_parm2[3];\n");
3547         progdefs_crc_file("\tint\tofs_parm3[3];\n");
3548         progdefs_crc_file("\tint\tofs_parm4[3];\n");
3549         progdefs_crc_file("\tint\tofs_parm5[3];\n");
3550         progdefs_crc_file("\tint\tofs_parm6[3];\n");
3551         progdefs_crc_file("\tint\tofs_parm7[3];\n");
3552         */
3553         for (i = 0; i < parser->crc_globals; ++i) {
3554             if (!ast_istype(parser->globals[i].var, ast_value))
3555                 continue;
3556             switch (parser->globals[i].var->expression.vtype) {
3557                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3558                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3559                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3560                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3561                 default:
3562                     crc = progdefs_crc_both(crc, "\tint\t");
3563                     break;
3564             }
3565             crc = progdefs_crc_both(crc, parser->globals[i].name);
3566             crc = progdefs_crc_both(crc, ";\n");
3567         }
3568         crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3569         for (i = 0; i < parser->crc_fields; ++i) {
3570             if (!ast_istype(parser->fields[i].var, ast_value))
3571                 continue;
3572             switch (parser->fields[i].var->expression.next->expression.vtype) {
3573                 case TYPE_FLOAT:    crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3574                 case TYPE_VECTOR:   crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3575                 case TYPE_STRING:   crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3576                 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3577                 default:
3578                     crc = progdefs_crc_both(crc, "\tint\t");
3579                     break;
3580             }
3581             crc = progdefs_crc_both(crc, parser->fields[i].name);
3582             crc = progdefs_crc_both(crc, ";\n");
3583         }
3584         crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3585
3586         code_crc = crc;
3587 }
3588
3589 bool parser_finish(const char *output)
3590 {
3591     size_t i;
3592     ir_builder *ir;
3593     bool retval = true;
3594
3595     if (!parser->errors)
3596     {
3597         ir = ir_builder_new("gmqcc_out");
3598         if (!ir) {
3599             con_out("failed to allocate builder\n");
3600             return false;
3601         }
3602
3603         for (i = 0; i < vec_size(parser->fields); ++i) {
3604             ast_value *field;
3605             bool isconst;
3606             if (!ast_istype(parser->fields[i].var, ast_value))
3607                 continue;
3608             field = (ast_value*)parser->fields[i].var;
3609             isconst = field->isconst;
3610             field->isconst = false;
3611             if (!ast_global_codegen((ast_value*)field, ir, true)) {
3612                 con_out("failed to generate field %s\n", field->name);
3613                 ir_builder_delete(ir);
3614                 return false;
3615             }
3616             if (isconst) {
3617                 ir_value *ifld;
3618                 ast_expression *subtype;
3619                 field->isconst = true;
3620                 subtype = field->expression.next;
3621                 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3622                 if (subtype->expression.vtype == TYPE_FIELD)
3623                     ifld->fieldtype = subtype->expression.next->expression.vtype;
3624                 else if (subtype->expression.vtype == TYPE_FUNCTION)
3625                     ifld->outtype = subtype->expression.next->expression.vtype;
3626                 (void)!ir_value_set_field(field->ir_v, ifld);
3627             }
3628         }
3629         for (i = 0; i < vec_size(parser->globals); ++i) {
3630             ast_value *asvalue;
3631             if (!ast_istype(parser->globals[i].var, ast_value))
3632                 continue;
3633             asvalue = (ast_value*)(parser->globals[i].var);
3634             if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3635                 if (strcmp(asvalue->name, "end_sys_globals") &&
3636                     strcmp(asvalue->name, "end_sys_fields"))
3637                 {
3638                     retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3639                                                    "unused global: `%s`", asvalue->name);
3640                 }
3641             }
3642             if (!ast_global_codegen(asvalue, ir, false)) {
3643                 con_out("failed to generate global %s\n", parser->globals[i].name);
3644                 ir_builder_delete(ir);
3645                 return false;
3646             }
3647         }
3648         for (i = 0; i < vec_size(parser->imm_float); ++i) {
3649             if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3650                 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
3651                 ir_builder_delete(ir);
3652                 return false;
3653             }
3654         }
3655         for (i = 0; i < vec_size(parser->imm_string); ++i) {
3656             if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3657                 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
3658                 ir_builder_delete(ir);
3659                 return false;
3660             }
3661         }
3662         for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3663             if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3664                 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
3665                 ir_builder_delete(ir);
3666                 return false;
3667             }
3668         }
3669         for (i = 0; i < vec_size(parser->globals); ++i) {
3670             ast_value *asvalue;
3671             if (!ast_istype(parser->globals[i].var, ast_value))
3672                 continue;
3673             asvalue = (ast_value*)(parser->globals[i].var);
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->globals[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->globals[i].name);
3690                     ir_builder_delete(ir);
3691                     return false;
3692                 }
3693             }
3694         }
3695         for (i = 0; i < vec_size(parser->fields); ++i) {
3696             ast_value *asvalue;
3697             asvalue = (ast_value*)(parser->fields[i].var->expression.next);
3698
3699             if (!ast_istype((ast_expression*)asvalue, ast_value))
3700                 continue;
3701             if (asvalue->expression.vtype != TYPE_ARRAY)
3702                 continue;
3703             if (asvalue->setter) {
3704                 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3705                     !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3706                     !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3707                 {
3708                     printf("failed to generate setter for %s\n", parser->fields[i].name);
3709                     ir_builder_delete(ir);
3710                     return false;
3711                 }
3712             }
3713             if (asvalue->getter) {
3714                 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3715                     !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3716                     !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3717                 {
3718                     printf("failed to generate getter for %s\n", parser->fields[i].name);
3719                     ir_builder_delete(ir);
3720                     return false;
3721                 }
3722             }
3723         }
3724         for (i = 0; i < vec_size(parser->functions); ++i) {
3725             if (!ast_function_codegen(parser->functions[i], ir)) {
3726                 con_out("failed to generate function %s\n", parser->functions[i]->name);
3727                 ir_builder_delete(ir);
3728                 return false;
3729             }
3730             if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3731                 con_out("failed to finalize function %s\n", parser->functions[i]->name);
3732                 ir_builder_delete(ir);
3733                 return false;
3734             }
3735         }
3736
3737         if (retval) {
3738             if (opts_dump)
3739                 ir_builder_dump(ir, con_out);
3740
3741             generate_checksum(parser);
3742
3743             if (!ir_builder_generate(ir, output)) {
3744                 con_out("*** failed to generate output file\n");
3745                 ir_builder_delete(ir);
3746                 return false;
3747             }
3748         }
3749
3750         ir_builder_delete(ir);
3751         return retval;
3752     }
3753
3754     con_out("*** there were compile errors\n");
3755     return false;
3756 }