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