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