5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define PARSER_HT_FIELDS 0
30 #define PARSER_HT_GLOBALS 1
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
59 ast_function *function;
61 /* A list of hashtables for each scope */
67 /* not to be used directly, we use the hash table */
68 ast_expression **_locals;
70 ast_value **_typedefs;
71 size_t *_blocktypedefs;
75 /* we store the '=' operator info */
76 const oper_info *assign_op;
78 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
79 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
80 * anything else: type error
89 static void parser_enterblock(parser_t *parser);
90 static bool parser_leaveblock(parser_t *parser);
91 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
92 static bool parse_typedef(parser_t *parser);
93 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int is_const_var, ast_value *cached_typedef);
94 static ast_block* parse_block(parser_t *parser, bool warnreturn);
95 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
96 static ast_expression* parse_statement_or_block(parser_t *parser);
97 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
98 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
99 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
101 static void parseerror(parser_t *parser, const char *fmt, ...)
108 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
112 /* returns true if it counts as an error */
113 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
116 int lvl = LVL_WARNING;
118 if (!OPTS_WARN(warntype))
127 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
133 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
136 int lvl = LVL_WARNING;
138 if (!OPTS_WARN(warntype))
145 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
151 /**********************************************************************
152 * some maths used for constant folding
155 vector vec3_add(vector a, vector b)
164 vector vec3_sub(vector a, vector b)
173 qcfloat vec3_mulvv(vector a, vector b)
175 return (a.x * b.x + a.y * b.y + a.z * b.z);
178 vector vec3_mulvf(vector a, float b)
187 /**********************************************************************
191 bool parser_next(parser_t *parser)
193 /* lex_do kills the previous token */
194 parser->tok = lex_do(parser->lex);
195 if (parser->tok == TOKEN_EOF)
197 if (parser->tok >= TOKEN_ERROR) {
198 parseerror(parser, "lex error");
204 #define parser_tokval(p) ((p)->lex->tok.value)
205 #define parser_token(p) (&((p)->lex->tok))
206 #define parser_ctx(p) ((p)->lex->tok.ctx)
208 static ast_value* parser_const_float(parser_t *parser, double d)
212 for (i = 0; i < vec_size(parser->imm_float); ++i) {
213 const double compare = parser->imm_float[i]->constval.vfloat;
214 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
215 return parser->imm_float[i];
217 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
218 out->constant = true;
219 out->hasvalue = true;
220 out->constval.vfloat = d;
221 vec_push(parser->imm_float, out);
225 static ast_value* parser_const_float_0(parser_t *parser)
227 if (!parser->imm_float_zero)
228 parser->imm_float_zero = parser_const_float(parser, 0);
229 return parser->imm_float_zero;
232 static ast_value* parser_const_float_1(parser_t *parser)
234 if (!parser->imm_float_one)
235 parser->imm_float_one = parser_const_float(parser, 1);
236 return parser->imm_float_one;
239 static char *parser_strdup(const char *str)
242 /* actually dup empty strings */
243 char *out = mem_a(1);
247 return util_strdup(str);
250 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
254 for (i = 0; i < vec_size(parser->imm_string); ++i) {
255 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
256 return parser->imm_string[i];
260 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
261 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
263 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
264 out->constant = true;
265 out->hasvalue = true;
266 out->constval.vstring = parser_strdup(str);
267 vec_push(parser->imm_string, out);
271 static ast_value* parser_const_vector(parser_t *parser, vector v)
275 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
276 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
277 return parser->imm_vector[i];
279 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
280 out->constant = true;
281 out->hasvalue = true;
282 out->constval.vvec = v;
283 vec_push(parser->imm_vector, out);
287 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
293 return parser_const_vector(parser, v);
296 static ast_value* parser_const_vector_0(parser_t *parser)
298 if (!parser->imm_vector_zero)
299 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
300 return parser->imm_vector_zero;
303 static ast_expression* parser_find_field(parser_t *parser, const char *name)
305 return util_htget(parser->htfields, name);
308 static ast_expression* parser_find_global(parser_t *parser, const char *name)
310 return util_htget(parser->htglobals, name);
313 static ast_expression* parser_find_param(parser_t *parser, const char *name)
317 if (!parser->function)
319 fun = parser->function->vtype;
320 for (i = 0; i < vec_size(fun->expression.params); ++i) {
321 if (!strcmp(fun->expression.params[i]->name, name))
322 return (ast_expression*)(fun->expression.params[i]);
327 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
332 hash = util_hthash(parser->htglobals, name);
335 for (i = vec_size(parser->variables); i > upto;) {
337 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
341 return parser_find_param(parser, name);
344 static ast_expression* parser_find_var(parser_t *parser, const char *name)
348 v = parser_find_local(parser, name, 0, &dummy);
349 if (!v) v = parser_find_global(parser, name);
353 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
357 hash = util_hthash(parser->typedefs[0], name);
359 for (i = vec_size(parser->typedefs); i > upto;) {
361 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
369 size_t etype; /* 0 = expression, others are operators */
373 ast_block *block; /* for commas and function calls */
382 #define SY_PAREN_EXPR '('
383 #define SY_PAREN_FUNC 'f'
384 #define SY_PAREN_INDEX '['
386 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
397 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
401 e.out = (ast_expression*)v;
408 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
410 e.etype = 1 + (op - operators);
419 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
431 # define DEBUGSHUNTDO(x) x
433 # define DEBUGSHUNTDO(x)
436 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
437 * so we need to rotate it to become ent.(foo[n]).
439 static bool rotate_entfield_array_index_nodes(ast_expression **out)
441 ast_array_index *index;
442 ast_entfield *entfield;
446 ast_expression *entity;
448 lex_ctx ctx = ast_ctx(*out);
450 if (!ast_istype(*out, ast_array_index))
452 index = (ast_array_index*)*out;
454 if (!ast_istype(index->array, ast_entfield))
456 entfield = (ast_entfield*)index->array;
458 if (!ast_istype(entfield->field, ast_value))
460 field = (ast_value*)entfield->field;
463 entity = entfield->entity;
467 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
468 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
469 *out = (ast_expression*)entfield;
474 static bool parser_sy_pop(parser_t *parser, shunt *sy)
478 ast_expression *out = NULL;
479 ast_expression *exprs[3];
480 ast_block *blocks[3];
481 ast_value *asvalue[3];
482 size_t i, assignop, addop, subop;
483 qcint generated_op = 0;
488 if (!vec_size(sy->ops)) {
489 parseerror(parser, "internal error: missing operator");
493 if (vec_last(sy->ops).paren) {
494 parseerror(parser, "unmatched parenthesis");
498 op = &operators[vec_last(sy->ops).etype - 1];
499 ctx = vec_last(sy->ops).ctx;
501 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
503 if (vec_size(sy->out) < op->operands) {
504 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
505 op->op, (int)op->id);
509 vec_shrinkby(sy->ops, 1);
511 vec_shrinkby(sy->out, op->operands);
512 for (i = 0; i < op->operands; ++i) {
513 exprs[i] = sy->out[vec_size(sy->out)+i].out;
514 blocks[i] = sy->out[vec_size(sy->out)+i].block;
515 asvalue[i] = (ast_value*)exprs[i];
518 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
519 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
523 #define NotSameType(T) \
524 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
525 exprs[0]->expression.vtype != T)
526 #define CanConstFold1(A) \
527 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && ((ast_value*)(A))->constant)
528 #define CanConstFold(A, B) \
529 (CanConstFold1(A) && CanConstFold1(B))
530 #define ConstV(i) (asvalue[(i)]->constval.vvec)
531 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
532 #define ConstS(i) (asvalue[(i)]->constval.vstring)
536 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
540 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
541 if (exprs[1]->expression.vtype != TYPE_FIELD) {
542 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
545 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
547 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
548 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
552 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
558 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
559 !(exprs[0]->expression.vtype == TYPE_FIELD &&
560 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
562 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
563 parseerror(parser, "cannot index value of type %s", ty1);
566 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
567 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
568 parseerror(parser, "index must be of type float, not %s", ty1);
571 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
572 if (rotate_entfield_array_index_nodes(&out))
574 if (opts_standard != COMPILER_GMQCC) {
575 /* this error doesn't need to make us bail out */
576 (void)!parsewarning(parser, WARN_EXTENSIONS,
577 "accessing array-field members of an entity without parenthesis\n"
578 " -> this is an extension from -std=gmqcc");
585 ast_block_add_expr(blocks[0], exprs[1]);
587 blocks[0] = ast_block_new(ctx);
588 ast_block_add_expr(blocks[0], exprs[0]);
589 ast_block_add_expr(blocks[0], exprs[1]);
591 if (!ast_block_set_type(blocks[0], exprs[1]))
594 vec_push(sy->out, syblock(ctx, blocks[0]));
598 switch (exprs[0]->expression.vtype) {
600 if (CanConstFold1(exprs[0]))
601 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
603 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
604 (ast_expression*)parser_const_float_0(parser),
608 if (CanConstFold1(exprs[0]))
609 out = (ast_expression*)parser_const_vector_f(parser,
610 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
612 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
613 (ast_expression*)parser_const_vector_0(parser),
617 parseerror(parser, "invalid types used in expression: cannot negate type %s",
618 type_name[exprs[0]->expression.vtype]);
624 switch (exprs[0]->expression.vtype) {
626 if (CanConstFold1(exprs[0]))
627 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
629 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
632 if (CanConstFold1(exprs[0]))
633 out = (ast_expression*)parser_const_float(parser,
634 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
636 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
639 if (CanConstFold1(exprs[0]))
640 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
642 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
644 /* we don't constant-fold NOT for these types */
646 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
649 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
652 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
653 type_name[exprs[0]->expression.vtype]);
659 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
660 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
662 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
663 type_name[exprs[0]->expression.vtype],
664 type_name[exprs[1]->expression.vtype]);
667 switch (exprs[0]->expression.vtype) {
669 if (CanConstFold(exprs[0], exprs[1]))
671 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
674 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
677 if (CanConstFold(exprs[0], exprs[1]))
678 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
680 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
683 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
684 type_name[exprs[0]->expression.vtype],
685 type_name[exprs[1]->expression.vtype]);
690 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
691 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
693 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
694 type_name[exprs[1]->expression.vtype],
695 type_name[exprs[0]->expression.vtype]);
698 switch (exprs[0]->expression.vtype) {
700 if (CanConstFold(exprs[0], exprs[1]))
701 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
703 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
706 if (CanConstFold(exprs[0], exprs[1]))
707 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
709 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
712 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
713 type_name[exprs[1]->expression.vtype],
714 type_name[exprs[0]->expression.vtype]);
719 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
720 exprs[0]->expression.vtype != TYPE_VECTOR &&
721 exprs[0]->expression.vtype != TYPE_FLOAT &&
722 exprs[1]->expression.vtype != TYPE_VECTOR &&
723 exprs[1]->expression.vtype != TYPE_FLOAT)
725 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
726 type_name[exprs[1]->expression.vtype],
727 type_name[exprs[0]->expression.vtype]);
730 switch (exprs[0]->expression.vtype) {
732 if (exprs[1]->expression.vtype == TYPE_VECTOR)
734 if (CanConstFold(exprs[0], exprs[1]))
735 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
737 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
741 if (CanConstFold(exprs[0], exprs[1]))
742 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
744 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
748 if (exprs[1]->expression.vtype == TYPE_FLOAT)
750 if (CanConstFold(exprs[0], exprs[1]))
751 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
753 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
757 if (CanConstFold(exprs[0], exprs[1]))
758 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
760 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
764 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
765 type_name[exprs[1]->expression.vtype],
766 type_name[exprs[0]->expression.vtype]);
771 if (NotSameType(TYPE_FLOAT)) {
772 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
773 type_name[exprs[0]->expression.vtype],
774 type_name[exprs[1]->expression.vtype]);
777 if (CanConstFold(exprs[0], exprs[1]))
778 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
780 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
784 parseerror(parser, "qc does not have a modulo operator");
788 if (NotSameType(TYPE_FLOAT)) {
789 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
790 type_name[exprs[0]->expression.vtype],
791 type_name[exprs[1]->expression.vtype]);
794 if (CanConstFold(exprs[0], exprs[1]))
795 out = (ast_expression*)parser_const_float(parser,
796 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
797 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
799 out = (ast_expression*)ast_binary_new(ctx,
800 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
804 parseerror(parser, "TODO: bitxor");
809 case opid3('<','<','='):
810 case opid3('>','>','='):
811 parseerror(parser, "TODO: shifts");
815 generated_op += 1; /* INSTR_OR */
817 generated_op += INSTR_AND;
819 if (NotSameType(TYPE_FLOAT)) {
820 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
821 type_name[exprs[0]->expression.vtype],
822 type_name[exprs[1]->expression.vtype]);
823 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
824 parseerror(parser, "TODO: optional early out");
828 if (opts_standard == COMPILER_GMQCC)
829 con_out("TODO: early out logic\n");
830 if (CanConstFold(exprs[0], exprs[1]))
831 out = (ast_expression*)parser_const_float(parser,
832 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
834 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
838 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
839 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
840 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
841 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
844 if (CanConstFold1(exprs[0]))
845 out = (ConstF(0) ? exprs[1] : exprs[2]);
847 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
851 generated_op += 1; /* INSTR_GT */
853 generated_op += 1; /* INSTR_LT */
854 case opid2('>', '='):
855 generated_op += 1; /* INSTR_GE */
856 case opid2('<', '='):
857 generated_op += INSTR_LE;
858 if (NotSameType(TYPE_FLOAT)) {
859 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
860 type_name[exprs[0]->expression.vtype],
861 type_name[exprs[1]->expression.vtype]);
864 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
866 case opid2('!', '='):
867 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
868 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
869 type_name[exprs[0]->expression.vtype],
870 type_name[exprs[1]->expression.vtype]);
873 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
875 case opid2('=', '='):
876 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
877 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
878 type_name[exprs[0]->expression.vtype],
879 type_name[exprs[1]->expression.vtype]);
882 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
886 if (ast_istype(exprs[0], ast_entfield)) {
887 ast_expression *field = ((ast_entfield*)exprs[0])->field;
888 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
889 exprs[0]->expression.vtype == TYPE_FIELD &&
890 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
892 assignop = type_storep_instr[TYPE_VECTOR];
895 assignop = type_storep_instr[exprs[0]->expression.vtype];
896 if (!ast_compare_type(field->expression.next, exprs[1])) {
897 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
898 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
899 if (opts_standard == COMPILER_QCC &&
900 field->expression.next->expression.vtype == TYPE_FUNCTION &&
901 exprs[1]->expression.vtype == TYPE_FUNCTION)
903 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
904 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
910 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
915 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
916 exprs[0]->expression.vtype == TYPE_FIELD &&
917 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
919 assignop = type_store_instr[TYPE_VECTOR];
922 assignop = type_store_instr[exprs[0]->expression.vtype];
925 if (assignop == AINSTR_END) {
926 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
927 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
928 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
930 else if (!ast_compare_type(exprs[0], exprs[1])) {
931 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
932 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
933 if (opts_standard == COMPILER_QCC &&
934 exprs[0]->expression.vtype == TYPE_FUNCTION &&
935 exprs[1]->expression.vtype == TYPE_FUNCTION)
937 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
938 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
944 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
947 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
948 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
950 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
952 case opid3('+','+','P'):
953 case opid3('-','-','P'):
955 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
956 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
957 parseerror(parser, "invalid type for prefix increment: %s", ty1);
960 if (op->id == opid3('+','+','P'))
964 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
965 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
967 if (ast_istype(exprs[0], ast_entfield)) {
968 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
970 (ast_expression*)parser_const_float_1(parser));
972 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
974 (ast_expression*)parser_const_float_1(parser));
977 case opid3('S','+','+'):
978 case opid3('S','-','-'):
980 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
981 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
982 parseerror(parser, "invalid type for suffix increment: %s", ty1);
985 if (op->id == opid3('S','+','+')) {
992 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
993 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
995 if (ast_istype(exprs[0], ast_entfield)) {
996 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
998 (ast_expression*)parser_const_float_1(parser));
1000 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1002 (ast_expression*)parser_const_float_1(parser));
1006 out = (ast_expression*)ast_binary_new(ctx, subop,
1008 (ast_expression*)parser_const_float_1(parser));
1010 case opid2('+','='):
1011 case opid2('-','='):
1012 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1013 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1015 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1016 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1017 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1021 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
1022 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1024 if (ast_istype(exprs[0], ast_entfield))
1025 assignop = type_storep_instr[exprs[0]->expression.vtype];
1027 assignop = type_store_instr[exprs[0]->expression.vtype];
1028 switch (exprs[0]->expression.vtype) {
1030 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1031 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1032 exprs[0], exprs[1]);
1035 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1036 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1037 exprs[0], exprs[1]);
1040 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1041 type_name[exprs[0]->expression.vtype],
1042 type_name[exprs[1]->expression.vtype]);
1046 case opid2('*','='):
1047 case opid2('/','='):
1048 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1049 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1050 exprs[0]->expression.vtype == TYPE_VECTOR))
1052 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1053 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1054 parseerror(parser, "invalid types used in expression: %s and %s",
1058 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
1059 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1061 if (ast_istype(exprs[0], ast_entfield))
1062 assignop = type_storep_instr[exprs[0]->expression.vtype];
1064 assignop = type_store_instr[exprs[0]->expression.vtype];
1065 switch (exprs[0]->expression.vtype) {
1067 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1068 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1069 exprs[0], exprs[1]);
1072 if (op->id == opid2('*','=')) {
1073 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1074 exprs[0], exprs[1]);
1076 /* there's no DIV_VF */
1077 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1078 (ast_expression*)parser_const_float_1(parser),
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1087 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1088 type_name[exprs[0]->expression.vtype],
1089 type_name[exprs[1]->expression.vtype]);
1093 case opid2('&','='):
1094 case opid2('|','='):
1095 if (NotSameType(TYPE_FLOAT)) {
1096 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1097 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1098 parseerror(parser, "invalid types used in expression: %s and %s",
1102 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
1103 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1105 if (ast_istype(exprs[0], ast_entfield))
1106 assignop = type_storep_instr[exprs[0]->expression.vtype];
1108 assignop = type_store_instr[exprs[0]->expression.vtype];
1109 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1110 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1111 exprs[0], exprs[1]);
1113 case opid3('&','~','='):
1114 /* This is like: a &= ~(b);
1115 * But QC has no bitwise-not, so we implement it as
1118 if (NotSameType(TYPE_FLOAT)) {
1119 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1120 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1121 parseerror(parser, "invalid types used in expression: %s and %s",
1125 if (ast_istype(exprs[0], ast_entfield))
1126 assignop = type_storep_instr[exprs[0]->expression.vtype];
1128 assignop = type_store_instr[exprs[0]->expression.vtype];
1129 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1132 if (ast_istype(exprs[0], ast_value) && asvalue[0]->constant) {
1133 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1135 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1141 parseerror(parser, "failed to apply operand %s", op->op);
1145 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1146 vec_push(sy->out, syexp(ctx, out));
1150 static bool parser_close_call(parser_t *parser, shunt *sy)
1152 /* was a function call */
1153 ast_expression *fun;
1159 vec_shrinkby(sy->ops, 1);
1160 fid = sy->ops[vec_size(sy->ops)].off;
1162 /* out[fid] is the function
1163 * everything above is parameters...
1164 * 0 params = nothing
1165 * 1 params = ast_expression
1169 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1170 parseerror(parser, "internal error: function call needs function and parameter list...");
1174 fun = sy->out[fid].out;
1176 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1178 parseerror(parser, "out of memory");
1182 if (fid+1 == vec_size(sy->out)) {
1185 } else if (fid+2 == vec_size(sy->out)) {
1187 vec_shrinkby(sy->out, 1);
1188 params = sy->out[vec_size(sy->out)].block;
1192 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1194 paramcount = vec_size(params->exprs);
1195 call->params = params->exprs;
1196 params->exprs = NULL;
1199 if (!ast_call_check_types(call))
1202 parseerror(parser, "invalid function call");
1206 /* overwrite fid, the function, with a call */
1207 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1209 if (fun->expression.vtype != TYPE_FUNCTION) {
1210 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1214 if (!fun->expression.next) {
1215 parseerror(parser, "could not determine function return type");
1218 if (vec_size(fun->expression.params) != paramcount &&
1219 !(fun->expression.variadic &&
1220 vec_size(fun->expression.params) < paramcount))
1223 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1225 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1226 if (opts_standard == COMPILER_GMQCC)
1229 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1230 " -> `%s` has been declared here: %s:%i",
1231 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1232 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1234 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1235 " -> `%s` has been declared here: %s:%i",
1236 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1237 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1243 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1244 "too %s parameters for call to %s: expected %i, got %i\n"
1245 " -> `%s` has been declared here: %s:%i",
1246 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1247 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1249 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1250 "too %s parameters for function call: expected %i, got %i\n"
1251 " -> `%s` has been declared here: %s:%i",
1252 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1253 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1261 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1263 if (!vec_size(sy->ops)) {
1264 parseerror(parser, "unmatched closing paren");
1267 /* this would for bit a + (x) because there are no operators inside (x)
1268 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1269 parseerror(parser, "empty parenthesis expression");
1273 while (vec_size(sy->ops)) {
1274 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1275 if (!parser_close_call(parser, sy))
1279 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1280 vec_shrinkby(sy->ops, 1);
1281 return !functions_only;
1283 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1286 /* pop off the parenthesis */
1287 vec_shrinkby(sy->ops, 1);
1288 /* then apply the index operator */
1289 if (!parser_sy_pop(parser, sy))
1293 if (!parser_sy_pop(parser, sy))
1299 static void parser_reclassify_token(parser_t *parser)
1302 for (i = 0; i < operator_count; ++i) {
1303 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1304 parser->tok = TOKEN_OPERATOR;
1310 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1312 ast_expression *expr = NULL;
1314 bool wantop = false;
1315 bool gotmemberof = false;
1317 /* count the parens because an if starts with one, so the
1318 * end of a condition is an unmatched closing paren
1326 parser->lex->flags.noops = false;
1328 parser_reclassify_token(parser);
1333 gotmemberof = false;
1335 parser->memberof = 0;
1337 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1338 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1340 /* a translatable string */
1344 parseerror(parser, "expected operator or end of statement, got constant");
1348 parser->lex->flags.noops = true;
1349 if (!parser_next(parser) || parser->tok != '(') {
1350 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1353 parser->lex->flags.noops = false;
1354 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1355 parseerror(parser, "expected a constant string in translatable-string extension");
1358 val = parser_const_string(parser, parser_tokval(parser), true);
1362 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1363 DEBUGSHUNTDO(con_out("push string\n"));
1365 if (!parser_next(parser) || parser->tok != ')') {
1366 parseerror(parser, "expected closing paren after translatable string");
1370 else if (parser->tok == TOKEN_IDENT)
1372 ast_expression *var;
1374 parseerror(parser, "expected operator or end of statement");
1379 if (opts_standard == COMPILER_GMQCC)
1381 if (parser->memberof == TYPE_ENTITY) {
1382 /* still get vars first since there could be a fieldpointer */
1383 var = parser_find_var(parser, parser_tokval(parser));
1385 var = parser_find_field(parser, parser_tokval(parser));
1387 else if (parser->memberof == TYPE_VECTOR)
1389 parseerror(parser, "TODO: implement effective vector member access");
1392 else if (parser->memberof) {
1393 parseerror(parser, "namespace for member not found");
1397 var = parser_find_var(parser, parser_tokval(parser));
1399 var = parser_find_var(parser, parser_tokval(parser));
1401 var = parser_find_field(parser, parser_tokval(parser));
1404 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1407 if (ast_istype(var, ast_value))
1408 ((ast_value*)var)->uses++;
1409 vec_push(sy.out, syexp(parser_ctx(parser), var));
1410 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1412 else if (parser->tok == TOKEN_FLOATCONST) {
1415 parseerror(parser, "expected operator or end of statement, got constant");
1419 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1422 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1423 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1425 else if (parser->tok == TOKEN_INTCONST) {
1428 parseerror(parser, "expected operator or end of statement, got constant");
1432 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1435 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1436 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1438 else if (parser->tok == TOKEN_STRINGCONST) {
1441 parseerror(parser, "expected operator or end of statement, got constant");
1445 val = parser_const_string(parser, parser_tokval(parser), false);
1448 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1449 DEBUGSHUNTDO(con_out("push string\n"));
1451 else if (parser->tok == TOKEN_VECTORCONST) {
1454 parseerror(parser, "expected operator or end of statement, got constant");
1458 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1461 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1462 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1463 parser_token(parser)->constval.v.x,
1464 parser_token(parser)->constval.v.y,
1465 parser_token(parser)->constval.v.z));
1467 else if (parser->tok == '(') {
1468 parseerror(parser, "internal error: '(' should be classified as operator");
1471 else if (parser->tok == '[') {
1472 parseerror(parser, "internal error: '[' should be classified as operator");
1475 else if (parser->tok == ')') {
1477 DEBUGSHUNTDO(con_out("do[op] )\n"));
1481 /* we do expect an operator next */
1482 /* closing an opening paren */
1483 if (!parser_close_paren(parser, &sy, false))
1486 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1490 /* allowed for function calls */
1491 if (!parser_close_paren(parser, &sy, true))
1496 else if (parser->tok == ']') {
1498 parseerror(parser, "operand expected");
1502 if (!parser_close_paren(parser, &sy, false))
1506 else if (parser->tok != TOKEN_OPERATOR) {
1508 parseerror(parser, "expected operator or end of statement");
1515 /* classify the operator */
1516 const oper_info *op;
1517 const oper_info *olast = NULL;
1519 for (o = 0; o < operator_count; ++o) {
1520 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1521 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1522 !strcmp(parser_tokval(parser), operators[o].op))
1527 if (o == operator_count) {
1528 /* no operator found... must be the end of the statement */
1531 /* found an operator */
1534 /* when declaring variables, a comma starts a new variable */
1535 if (op->id == opid1(',') && !parens && stopatcomma) {
1536 /* fixup the token */
1541 /* a colon without a pervious question mark cannot be a ternary */
1542 if (!ternaries && op->id == opid2(':','?')) {
1547 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1548 olast = &operators[vec_last(sy.ops).etype-1];
1551 (op->prec < olast->prec) ||
1552 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1554 if (!parser_sy_pop(parser, &sy))
1556 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1557 olast = &operators[vec_last(sy.ops).etype-1];
1562 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1563 /* for gmqcc standard: open up the namespace of the previous type */
1564 ast_expression *prevex = vec_last(sy.out).out;
1566 parseerror(parser, "unexpected member operator");
1569 if (prevex->expression.vtype == TYPE_ENTITY)
1570 parser->memberof = TYPE_ENTITY;
1571 else if (prevex->expression.vtype == TYPE_VECTOR)
1572 parser->memberof = TYPE_VECTOR;
1574 parseerror(parser, "type error: type has no members");
1580 if (op->id == opid1('(')) {
1582 size_t sycount = vec_size(sy.out);
1583 DEBUGSHUNTDO(con_out("push [op] (\n"));
1585 /* we expected an operator, this is the function-call operator */
1586 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1589 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1590 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1593 } else if (op->id == opid1('[')) {
1595 parseerror(parser, "unexpected array subscript");
1599 /* push both the operator and the paren, this makes life easier */
1600 vec_push(sy.ops, syop(parser_ctx(parser), op));
1601 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1603 } else if (op->id == opid2('?',':')) {
1605 vec_push(sy.ops, syop(parser_ctx(parser), op));
1608 } else if (op->id == opid2(':','?')) {
1609 /* we don't push this operator */
1613 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1614 vec_push(sy.ops, syop(parser_ctx(parser), op));
1615 wantop = !!(op->flags & OP_SUFFIX);
1618 if (!parser_next(parser)) {
1621 if (parser->tok == ';' ||
1622 (!parens && parser->tok == ']'))
1628 while (vec_size(sy.ops)) {
1629 if (!parser_sy_pop(parser, &sy))
1633 parser->lex->flags.noops = true;
1634 if (!vec_size(sy.out)) {
1635 parseerror(parser, "empty expression");
1638 expr = sy.out[0].out;
1641 DEBUGSHUNTDO(con_out("shunt done\n"));
1645 parser->lex->flags.noops = true;
1651 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1653 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1656 if (!parser_next(parser)) {
1663 static void parser_enterblock(parser_t *parser)
1665 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1666 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1667 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1668 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1671 static bool parser_leaveblock(parser_t *parser)
1674 size_t locals, typedefs;
1676 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1677 parseerror(parser, "internal error: parser_leaveblock with no block");
1681 util_htdel(vec_last(parser->variables));
1682 vec_pop(parser->variables);
1683 if (!vec_size(parser->_blocklocals)) {
1684 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1688 locals = vec_last(parser->_blocklocals);
1689 vec_pop(parser->_blocklocals);
1690 while (vec_size(parser->_locals) != locals) {
1691 ast_expression *e = vec_last(parser->_locals);
1692 ast_value *v = (ast_value*)e;
1693 vec_pop(parser->_locals);
1694 if (ast_istype(e, ast_value) && !v->uses) {
1695 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1700 typedefs = vec_last(parser->_blocktypedefs);
1701 while (vec_size(parser->_typedefs) != typedefs) {
1702 ast_delete(vec_last(parser->_typedefs));
1703 vec_pop(parser->_typedefs);
1705 util_htdel(vec_last(parser->typedefs));
1706 vec_pop(parser->typedefs);
1711 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1713 vec_push(parser->_locals, e);
1714 util_htset(vec_last(parser->variables), name, (void*)e);
1717 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1720 ast_expression *cond, *ontrue, *onfalse = NULL;
1723 lex_ctx ctx = parser_ctx(parser);
1725 (void)block; /* not touching */
1727 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1728 if (!parser_next(parser)) {
1729 parseerror(parser, "expected condition or 'not'");
1732 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1734 if (!parser_next(parser)) {
1735 parseerror(parser, "expected condition in parenthesis");
1739 if (parser->tok != '(') {
1740 parseerror(parser, "expected 'if' condition in parenthesis");
1743 /* parse into the expression */
1744 if (!parser_next(parser)) {
1745 parseerror(parser, "expected 'if' condition after opening paren");
1748 /* parse the condition */
1749 cond = parse_expression_leave(parser, false);
1753 if (parser->tok != ')') {
1754 parseerror(parser, "expected closing paren after 'if' condition");
1758 /* parse into the 'then' branch */
1759 if (!parser_next(parser)) {
1760 parseerror(parser, "expected statement for on-true branch of 'if'");
1764 ontrue = parse_statement_or_block(parser);
1769 /* check for an else */
1770 if (!strcmp(parser_tokval(parser), "else")) {
1771 /* parse into the 'else' branch */
1772 if (!parser_next(parser)) {
1773 parseerror(parser, "expected on-false branch after 'else'");
1778 onfalse = parse_statement_or_block(parser);
1787 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1789 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1790 *out = (ast_expression*)ifthen;
1794 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1797 ast_expression *cond, *ontrue;
1799 lex_ctx ctx = parser_ctx(parser);
1801 (void)block; /* not touching */
1803 /* skip the 'while' and check for opening paren */
1804 if (!parser_next(parser) || parser->tok != '(') {
1805 parseerror(parser, "expected 'while' condition in parenthesis");
1808 /* parse into the expression */
1809 if (!parser_next(parser)) {
1810 parseerror(parser, "expected 'while' condition after opening paren");
1813 /* parse the condition */
1814 cond = parse_expression_leave(parser, false);
1818 if (parser->tok != ')') {
1819 parseerror(parser, "expected closing paren after 'while' condition");
1823 /* parse into the 'then' branch */
1824 if (!parser_next(parser)) {
1825 parseerror(parser, "expected while-loop body");
1829 ontrue = parse_statement_or_block(parser);
1835 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1836 *out = (ast_expression*)aloop;
1840 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1843 ast_expression *cond, *ontrue;
1845 lex_ctx ctx = parser_ctx(parser);
1847 (void)block; /* not touching */
1849 /* skip the 'do' and get the body */
1850 if (!parser_next(parser)) {
1851 parseerror(parser, "expected loop body");
1854 ontrue = parse_statement_or_block(parser);
1858 /* expect the "while" */
1859 if (parser->tok != TOKEN_KEYWORD ||
1860 strcmp(parser_tokval(parser), "while"))
1862 parseerror(parser, "expected 'while' and condition");
1867 /* skip the 'while' and check for opening paren */
1868 if (!parser_next(parser) || parser->tok != '(') {
1869 parseerror(parser, "expected 'while' condition in parenthesis");
1873 /* parse into the expression */
1874 if (!parser_next(parser)) {
1875 parseerror(parser, "expected 'while' condition after opening paren");
1879 /* parse the condition */
1880 cond = parse_expression_leave(parser, false);
1884 if (parser->tok != ')') {
1885 parseerror(parser, "expected closing paren after 'while' condition");
1891 if (!parser_next(parser) || parser->tok != ';') {
1892 parseerror(parser, "expected semicolon after condition");
1898 if (!parser_next(parser)) {
1899 parseerror(parser, "parse error");
1905 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1906 *out = (ast_expression*)aloop;
1910 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1913 ast_expression *initexpr, *cond, *increment, *ontrue;
1917 lex_ctx ctx = parser_ctx(parser);
1919 parser_enterblock(parser);
1926 /* skip the 'while' and check for opening paren */
1927 if (!parser_next(parser) || parser->tok != '(') {
1928 parseerror(parser, "expected 'for' expressions in parenthesis");
1931 /* parse into the expression */
1932 if (!parser_next(parser)) {
1933 parseerror(parser, "expected 'for' initializer after opening paren");
1938 if (parser->tok == TOKEN_IDENT)
1939 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
1941 if (typevar || parser->tok == TOKEN_TYPENAME) {
1942 if (opts_standard != COMPILER_GMQCC) {
1943 if (parsewarning(parser, WARN_EXTENSIONS,
1944 "current standard does not allow variable declarations in for-loop initializers"))
1947 if (!parse_variable(parser, block, true, CV_VAR, typevar))
1950 else if (parser->tok != ';')
1952 initexpr = parse_expression_leave(parser, false);
1957 /* move on to condition */
1958 if (parser->tok != ';') {
1959 parseerror(parser, "expected semicolon after for-loop initializer");
1962 if (!parser_next(parser)) {
1963 parseerror(parser, "expected for-loop condition");
1967 /* parse the condition */
1968 if (parser->tok != ';') {
1969 cond = parse_expression_leave(parser, false);
1974 /* move on to incrementor */
1975 if (parser->tok != ';') {
1976 parseerror(parser, "expected semicolon after for-loop initializer");
1979 if (!parser_next(parser)) {
1980 parseerror(parser, "expected for-loop condition");
1984 /* parse the incrementor */
1985 if (parser->tok != ')') {
1986 increment = parse_expression_leave(parser, false);
1989 if (!ast_side_effects(increment)) {
1990 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1996 if (parser->tok != ')') {
1997 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2000 /* parse into the 'then' branch */
2001 if (!parser_next(parser)) {
2002 parseerror(parser, "expected for-loop body");
2005 ontrue = parse_statement_or_block(parser);
2010 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2011 *out = (ast_expression*)aloop;
2013 if (!parser_leaveblock(parser))
2017 if (initexpr) ast_delete(initexpr);
2018 if (cond) ast_delete(cond);
2019 if (increment) ast_delete(increment);
2020 (void)!parser_leaveblock(parser);
2024 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2026 ast_expression *exp = NULL;
2027 ast_return *ret = NULL;
2028 ast_value *expected = parser->function->vtype;
2030 (void)block; /* not touching */
2032 if (!parser_next(parser)) {
2033 parseerror(parser, "expected return expression");
2037 if (parser->tok != ';') {
2038 exp = parse_expression(parser, false);
2042 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2043 parseerror(parser, "return with invalid expression");
2046 ret = ast_return_new(exp->expression.node.context, exp);
2052 if (!parser_next(parser))
2053 parseerror(parser, "parse error");
2054 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2055 if (opts_standard != COMPILER_GMQCC)
2056 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2058 parseerror(parser, "return without value");
2060 ret = ast_return_new(parser_ctx(parser), NULL);
2062 *out = (ast_expression*)ret;
2066 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2068 lex_ctx ctx = parser_ctx(parser);
2070 (void)block; /* not touching */
2072 if (!parser_next(parser) || parser->tok != ';') {
2073 parseerror(parser, "expected semicolon");
2077 if (!parser_next(parser))
2078 parseerror(parser, "parse error");
2080 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2084 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2086 ast_expression *operand;
2088 ast_switch *switchnode;
2089 ast_switch_case swcase;
2091 lex_ctx ctx = parser_ctx(parser);
2093 (void)block; /* not touching */
2095 /* parse over the opening paren */
2096 if (!parser_next(parser) || parser->tok != '(') {
2097 parseerror(parser, "expected switch operand in parenthesis");
2101 /* parse into the expression */
2102 if (!parser_next(parser)) {
2103 parseerror(parser, "expected switch operand");
2106 /* parse the operand */
2107 operand = parse_expression_leave(parser, false);
2111 switchnode = ast_switch_new(ctx, operand);
2114 if (parser->tok != ')') {
2115 ast_delete(switchnode);
2116 parseerror(parser, "expected closing paren after 'switch' operand");
2120 /* parse over the opening paren */
2121 if (!parser_next(parser) || parser->tok != '{') {
2122 ast_delete(switchnode);
2123 parseerror(parser, "expected list of cases");
2127 if (!parser_next(parser)) {
2128 ast_delete(switchnode);
2129 parseerror(parser, "expected 'case' or 'default'");
2134 while (parser->tok != '}') {
2135 ast_block *caseblock;
2137 if (parser->tok != TOKEN_KEYWORD) {
2138 ast_delete(switchnode);
2139 parseerror(parser, "expected 'case' or 'default'");
2142 if (!strcmp(parser_tokval(parser), "case")) {
2143 if (!parser_next(parser)) {
2144 ast_delete(switchnode);
2145 parseerror(parser, "expected expression for case");
2148 swcase.value = parse_expression_leave(parser, false);
2149 if (!swcase.value) {
2150 ast_delete(switchnode);
2151 parseerror(parser, "expected expression for case");
2154 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2155 opval = (ast_value*)swcase.value;
2156 if (!ast_istype(swcase.value, ast_value) || !opval->constant) {
2157 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2163 else if (!strcmp(parser_tokval(parser), "default")) {
2164 swcase.value = NULL;
2165 if (!parser_next(parser)) {
2166 ast_delete(switchnode);
2167 parseerror(parser, "expected colon");
2172 /* Now the colon and body */
2173 if (parser->tok != ':') {
2174 if (swcase.value) ast_unref(swcase.value);
2175 ast_delete(switchnode);
2176 parseerror(parser, "expected colon");
2180 if (!parser_next(parser)) {
2181 if (swcase.value) ast_unref(swcase.value);
2182 ast_delete(switchnode);
2183 parseerror(parser, "expected statements or case");
2186 caseblock = ast_block_new(parser_ctx(parser));
2188 if (swcase.value) ast_unref(swcase.value);
2189 ast_delete(switchnode);
2192 swcase.code = (ast_expression*)caseblock;
2193 vec_push(switchnode->cases, swcase);
2195 ast_expression *expr;
2196 if (parser->tok == '}')
2198 if (parser->tok == TOKEN_KEYWORD) {
2199 if (!strcmp(parser_tokval(parser), "case") ||
2200 !strcmp(parser_tokval(parser), "default"))
2205 if (!parse_statement(parser, caseblock, &expr, true)) {
2206 ast_delete(switchnode);
2211 ast_block_add_expr(caseblock, expr);
2216 if (parser->tok != '}') {
2217 ast_delete(switchnode);
2218 parseerror(parser, "expected closing paren of case list");
2221 if (!parser_next(parser)) {
2222 ast_delete(switchnode);
2223 parseerror(parser, "parse error after switch");
2226 *out = (ast_expression*)switchnode;
2230 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2232 ast_value *typevar = NULL;
2235 if (parser->tok == TOKEN_IDENT)
2236 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2238 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2240 /* local variable */
2242 parseerror(parser, "cannot declare a variable from here");
2245 if (opts_standard == COMPILER_QCC) {
2246 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2249 if (!parse_variable(parser, block, false, CV_NONE, typevar))
2254 else if (parser->tok == TOKEN_KEYWORD)
2256 if (!strcmp(parser_tokval(parser), "local") ||
2257 !strcmp(parser_tokval(parser), "const"))
2259 int cvq = parser_tokval(parser)[0] == 'c' ? CV_CONST : CV_VAR;
2262 parseerror(parser, "cannot declare a local variable here");
2265 if (!parser_next(parser)) {
2266 parseerror(parser, "expected variable declaration");
2269 if (!parse_variable(parser, block, true, cvq, NULL))
2274 else if (!strcmp(parser_tokval(parser), "return"))
2276 return parse_return(parser, block, out);
2278 else if (!strcmp(parser_tokval(parser), "if"))
2280 return parse_if(parser, block, out);
2282 else if (!strcmp(parser_tokval(parser), "while"))
2284 return parse_while(parser, block, out);
2286 else if (!strcmp(parser_tokval(parser), "do"))
2288 return parse_dowhile(parser, block, out);
2290 else if (!strcmp(parser_tokval(parser), "for"))
2292 if (opts_standard == COMPILER_QCC) {
2293 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2296 return parse_for(parser, block, out);
2298 else if (!strcmp(parser_tokval(parser), "break"))
2300 return parse_break_continue(parser, block, out, false);
2302 else if (!strcmp(parser_tokval(parser), "continue"))
2304 return parse_break_continue(parser, block, out, true);
2306 else if (!strcmp(parser_tokval(parser), "switch"))
2308 return parse_switch(parser, block, out);
2310 else if (!strcmp(parser_tokval(parser), "case") ||
2311 !strcmp(parser_tokval(parser), "default"))
2314 parseerror(parser, "unexpected 'case' label");
2319 else if (!strcmp(parser_tokval(parser), "typedef"))
2321 if (!parser_next(parser)) {
2322 parseerror(parser, "expected type definition after 'typedef'");
2325 return parse_typedef(parser);
2327 parseerror(parser, "Unexpected keyword");
2330 else if (parser->tok == '{')
2333 inner = parse_block(parser, false);
2336 *out = (ast_expression*)inner;
2339 else if (parser->tok == ':')
2342 if (!parser_next(parser)) {
2343 parseerror(parser, "expected label name");
2346 if (parser->tok != TOKEN_IDENT) {
2347 parseerror(parser, "label must be an identifier");
2350 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2353 *out = (ast_expression*)label;
2354 if (!parser_next(parser)) {
2355 parseerror(parser, "parse error after label");
2360 else if (parser->tok == ';')
2362 if (!parser_next(parser)) {
2363 parseerror(parser, "parse error after empty statement");
2370 ast_expression *exp = parse_expression(parser, false);
2374 if (!ast_side_effects(exp)) {
2375 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2382 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2386 parser_enterblock(parser);
2388 if (!parser_next(parser)) { /* skip the '{' */
2389 parseerror(parser, "expected function body");
2393 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2395 ast_expression *expr = NULL;
2396 if (parser->tok == '}')
2399 if (!parse_statement(parser, block, &expr, false)) {
2400 /* parseerror(parser, "parse error"); */
2406 ast_block_add_expr(block, expr);
2409 if (parser->tok != '}') {
2412 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2414 if (!vec_size(block->exprs) ||
2415 !ast_istype(vec_last(block->exprs), ast_return))
2417 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2423 (void)parser_next(parser);
2427 if (!parser_leaveblock(parser))
2429 return retval && !!block;
2432 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2435 block = ast_block_new(parser_ctx(parser));
2438 if (!parse_block_into(parser, block, warnreturn)) {
2439 ast_block_delete(block);
2445 static ast_expression* parse_statement_or_block(parser_t *parser)
2447 ast_expression *expr = NULL;
2448 if (parser->tok == '{')
2449 return (ast_expression*)parse_block(parser, false);
2450 if (!parse_statement(parser, NULL, &expr, false))
2455 static bool create_vector_members(ast_value *var, ast_member **me)
2458 size_t len = strlen(var->name);
2460 for (i = 0; i < 3; ++i) {
2461 char *name = mem_a(len+3);
2462 memcpy(name, var->name, len);
2464 name[len+1] = 'x'+i;
2466 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2475 do { ast_member_delete(me[--i]); } while(i);
2479 static bool parse_function_body(parser_t *parser, ast_value *var)
2481 ast_block *block = NULL;
2486 ast_expression *framenum = NULL;
2487 ast_expression *nextthink = NULL;
2488 /* None of the following have to be deleted */
2489 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2490 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2491 bool has_frame_think;
2495 has_frame_think = false;
2496 old = parser->function;
2498 if (var->expression.variadic) {
2499 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2500 "variadic function with implementation will not be able to access additional parameters"))
2506 if (parser->tok == '[') {
2507 /* got a frame definition: [ framenum, nextthink ]
2508 * this translates to:
2509 * self.frame = framenum;
2510 * self.nextthink = time + 0.1;
2511 * self.think = nextthink;
2515 fld_think = parser_find_field(parser, "think");
2516 fld_nextthink = parser_find_field(parser, "nextthink");
2517 fld_frame = parser_find_field(parser, "frame");
2518 if (!fld_think || !fld_nextthink || !fld_frame) {
2519 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2520 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2523 gbl_time = parser_find_global(parser, "time");
2524 gbl_self = parser_find_global(parser, "self");
2525 if (!gbl_time || !gbl_self) {
2526 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2527 parseerror(parser, "please declare the following globals: `time`, `self`");
2531 if (!parser_next(parser))
2534 framenum = parse_expression_leave(parser, true);
2536 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2539 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2540 ast_unref(framenum);
2541 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2545 if (parser->tok != ',') {
2546 ast_unref(framenum);
2547 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2548 parseerror(parser, "Got a %i\n", parser->tok);
2552 if (!parser_next(parser)) {
2553 ast_unref(framenum);
2557 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2559 /* qc allows the use of not-yet-declared functions here
2560 * - this automatically creates a prototype */
2561 ast_value *thinkfunc;
2562 ast_expression *functype = fld_think->expression.next;
2564 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2565 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2566 ast_unref(framenum);
2567 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2571 if (!parser_next(parser)) {
2572 ast_unref(framenum);
2573 ast_delete(thinkfunc);
2577 vec_push(parser->globals, (ast_expression*)thinkfunc);
2578 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2579 nextthink = (ast_expression*)thinkfunc;
2582 nextthink = parse_expression_leave(parser, true);
2584 ast_unref(framenum);
2585 parseerror(parser, "expected a think-function in [frame,think] notation");
2590 if (!ast_istype(nextthink, ast_value)) {
2591 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2595 if (retval && parser->tok != ']') {
2596 parseerror(parser, "expected closing `]` for [frame,think] notation");
2600 if (retval && !parser_next(parser)) {
2604 if (retval && parser->tok != '{') {
2605 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2610 ast_unref(nextthink);
2611 ast_unref(framenum);
2615 has_frame_think = true;
2618 block = ast_block_new(parser_ctx(parser));
2620 parseerror(parser, "failed to allocate block");
2621 if (has_frame_think) {
2622 ast_unref(nextthink);
2623 ast_unref(framenum);
2628 if (has_frame_think) {
2630 ast_expression *self_frame;
2631 ast_expression *self_nextthink;
2632 ast_expression *self_think;
2633 ast_expression *time_plus_1;
2634 ast_store *store_frame;
2635 ast_store *store_nextthink;
2636 ast_store *store_think;
2638 ctx = parser_ctx(parser);
2639 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2640 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2641 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2643 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2644 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2646 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2647 if (self_frame) ast_delete(self_frame);
2648 if (self_nextthink) ast_delete(self_nextthink);
2649 if (self_think) ast_delete(self_think);
2650 if (time_plus_1) ast_delete(time_plus_1);
2656 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2657 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2658 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2661 ast_delete(self_frame);
2664 if (!store_nextthink) {
2665 ast_delete(self_nextthink);
2669 ast_delete(self_think);
2673 if (store_frame) ast_delete(store_frame);
2674 if (store_nextthink) ast_delete(store_nextthink);
2675 if (store_think) ast_delete(store_think);
2678 ast_block_add_expr(block, (ast_expression*)store_frame);
2679 ast_block_add_expr(block, (ast_expression*)store_nextthink);
2680 ast_block_add_expr(block, (ast_expression*)store_think);
2684 parseerror(parser, "failed to generate code for [frame,think]");
2685 ast_unref(nextthink);
2686 ast_unref(framenum);
2692 parser_enterblock(parser);
2694 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2696 ast_value *param = var->expression.params[parami];
2699 if (param->expression.vtype != TYPE_VECTOR &&
2700 (param->expression.vtype != TYPE_FIELD ||
2701 param->expression.next->expression.vtype != TYPE_VECTOR))
2706 if (!create_vector_members(param, me)) {
2707 ast_block_delete(block);
2711 for (e = 0; e < 3; ++e) {
2712 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2713 ast_block_collect(block, (ast_expression*)me[e]);
2717 func = ast_function_new(ast_ctx(var), var->name, var);
2719 parseerror(parser, "failed to allocate function for `%s`", var->name);
2720 ast_block_delete(block);
2723 vec_push(parser->functions, func);
2725 parser->function = func;
2726 if (!parse_block_into(parser, block, true)) {
2727 ast_block_delete(block);
2731 vec_push(func->blocks, block);
2733 parser->function = old;
2734 if (!parser_leaveblock(parser))
2736 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2737 parseerror(parser, "internal error: local scopes left");
2741 if (parser->tok == ';')
2742 return parser_next(parser);
2743 else if (opts_standard == COMPILER_QCC)
2744 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2748 vec_pop(parser->functions);
2749 ast_function_delete(func);
2750 var->constval.vfunc = NULL;
2753 (void)!parser_leaveblock(parser);
2754 parser->function = old;
2758 static ast_expression *array_accessor_split(
2763 ast_expression *left,
2764 ast_expression *right
2770 lex_ctx ctx = ast_ctx(array);
2772 if (!left || !right) {
2773 if (left) ast_delete(left);
2774 if (right) ast_delete(right);
2778 cmp = ast_binary_new(ctx, INSTR_LT,
2779 (ast_expression*)index,
2780 (ast_expression*)parser_const_float(parser, middle));
2784 parseerror(parser, "internal error: failed to create comparison for array setter");
2788 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2790 ast_delete(cmp); /* will delete left and right */
2791 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2795 return (ast_expression*)ifthen;
2798 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2800 lex_ctx ctx = ast_ctx(array);
2802 if (from+1 == afterend) {
2803 /* set this value */
2806 ast_array_index *subscript;
2808 int assignop = type_store_instr[value->expression.vtype];
2810 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2811 assignop = INSTR_STORE_V;
2813 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2817 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2819 ast_delete(subscript);
2823 block = ast_block_new(ctx);
2829 ast_block_add_expr(block, (ast_expression*)st);
2831 ret = ast_return_new(ctx, NULL);
2837 ast_block_add_expr(block, (ast_expression*)ret);
2839 return (ast_expression*)block;
2841 ast_expression *left, *right;
2842 size_t diff = afterend - from;
2843 size_t middle = from + diff/2;
2844 left = array_setter_node(parser, array, index, value, from, middle);
2845 right = array_setter_node(parser, array, index, value, middle, afterend);
2846 return array_accessor_split(parser, array, index, middle, left, right);
2850 static ast_expression *array_field_setter_node(
2859 lex_ctx ctx = ast_ctx(array);
2861 if (from+1 == afterend) {
2862 /* set this value */
2865 ast_entfield *entfield;
2866 ast_array_index *subscript;
2868 int assignop = type_storep_instr[value->expression.vtype];
2870 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2871 assignop = INSTR_STOREP_V;
2873 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2877 entfield = ast_entfield_new_force(ctx,
2878 (ast_expression*)entity,
2879 (ast_expression*)subscript,
2880 (ast_expression*)subscript);
2882 ast_delete(subscript);
2886 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2888 ast_delete(entfield);
2892 block = ast_block_new(ctx);
2898 ast_block_add_expr(block, (ast_expression*)st);
2900 ret = ast_return_new(ctx, NULL);
2906 ast_block_add_expr(block, (ast_expression*)ret);
2908 return (ast_expression*)block;
2910 ast_expression *left, *right;
2911 size_t diff = afterend - from;
2912 size_t middle = from + diff/2;
2913 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2914 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2915 return array_accessor_split(parser, array, index, middle, left, right);
2919 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2921 lex_ctx ctx = ast_ctx(array);
2923 if (from+1 == afterend) {
2925 ast_array_index *subscript;
2927 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2931 ret = ast_return_new(ctx, (ast_expression*)subscript);
2933 ast_delete(subscript);
2937 return (ast_expression*)ret;
2939 ast_expression *left, *right;
2940 size_t diff = afterend - from;
2941 size_t middle = from + diff/2;
2942 left = array_getter_node(parser, array, index, from, middle);
2943 right = array_getter_node(parser, array, index, middle, afterend);
2944 return array_accessor_split(parser, array, index, middle, left, right);
2948 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2950 ast_function *func = NULL;
2951 ast_value *fval = NULL;
2952 ast_block *body = NULL;
2954 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2956 parseerror(parser, "failed to create accessor function value");
2960 func = ast_function_new(ast_ctx(array), funcname, fval);
2963 parseerror(parser, "failed to create accessor function node");
2967 body = ast_block_new(ast_ctx(array));
2969 parseerror(parser, "failed to create block for array accessor");
2975 vec_push(func->blocks, body);
2978 vec_push(parser->accessors, fval);
2983 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2985 ast_expression *root = NULL;
2986 ast_value *index = NULL;
2987 ast_value *value = NULL;
2991 if (!ast_istype(array->expression.next, ast_value)) {
2992 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2996 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2998 func = fval->constval.vfunc;
2999 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3001 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3002 value = ast_value_copy((ast_value*)array->expression.next);
3004 if (!index || !value) {
3005 parseerror(parser, "failed to create locals for array accessor");
3008 (void)!ast_value_set_name(value, "value"); /* not important */
3009 vec_push(fval->expression.params, index);
3010 vec_push(fval->expression.params, value);
3012 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3014 parseerror(parser, "failed to build accessor search tree");
3018 ast_block_add_expr(func->blocks[0], root);
3019 array->setter = fval;
3022 if (index) ast_delete(index);
3023 if (value) ast_delete(value);
3024 if (root) ast_delete(root);
3030 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3032 ast_expression *root = NULL;
3033 ast_value *entity = NULL;
3034 ast_value *index = NULL;
3035 ast_value *value = NULL;
3039 if (!ast_istype(array->expression.next, ast_value)) {
3040 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3044 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3046 func = fval->constval.vfunc;
3047 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3049 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3050 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3051 value = ast_value_copy((ast_value*)array->expression.next);
3052 if (!entity || !index || !value) {
3053 parseerror(parser, "failed to create locals for array accessor");
3056 (void)!ast_value_set_name(value, "value"); /* not important */
3057 vec_push(fval->expression.params, entity);
3058 vec_push(fval->expression.params, index);
3059 vec_push(fval->expression.params, value);
3061 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3063 parseerror(parser, "failed to build accessor search tree");
3067 ast_block_add_expr(func->blocks[0], root);
3068 array->setter = fval;
3071 if (entity) ast_delete(entity);
3072 if (index) ast_delete(index);
3073 if (value) ast_delete(value);
3074 if (root) ast_delete(root);
3080 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3082 ast_expression *root = NULL;
3083 ast_value *index = NULL;
3087 /* NOTE: checking array->expression.next rather than elemtype since
3088 * for fields elemtype is a temporary fieldtype.
3090 if (!ast_istype(array->expression.next, ast_value)) {
3091 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3095 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3097 func = fval->constval.vfunc;
3098 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3100 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3103 parseerror(parser, "failed to create locals for array accessor");
3106 vec_push(fval->expression.params, index);
3108 root = array_getter_node(parser, array, index, 0, array->expression.count);
3110 parseerror(parser, "failed to build accessor search tree");
3114 ast_block_add_expr(func->blocks[0], root);
3115 array->getter = fval;
3118 if (index) ast_delete(index);
3119 if (root) ast_delete(root);
3125 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3126 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3134 bool variadic = false;
3136 ctx = parser_ctx(parser);
3138 /* for the sake of less code we parse-in in this function */
3139 if (!parser_next(parser)) {
3140 parseerror(parser, "expected parameter list");
3146 /* parse variables until we hit a closing paren */
3147 while (parser->tok != ')') {
3149 /* there must be commas between them */
3150 if (parser->tok != ',') {
3151 parseerror(parser, "expected comma or end of parameter list");
3154 if (!parser_next(parser)) {
3155 parseerror(parser, "expected parameter");
3161 if (parser->tok == TOKEN_DOTS) {
3162 /* '...' indicates a varargs function */
3164 if (!parser_next(parser)) {
3165 parseerror(parser, "expected parameter");
3168 if (parser->tok != ')') {
3169 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3175 /* for anything else just parse a typename */
3176 param = parse_typename(parser, NULL, NULL);
3179 vec_push(params, param);
3180 if (param->expression.vtype >= TYPE_VARIANT) {
3181 char typename[1024];
3182 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3183 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3189 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3193 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3194 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3197 if (!parser_next(parser)) {
3198 parseerror(parser, "parse error after typename");
3202 /* now turn 'var' into a function type */
3203 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3204 fval->expression.next = (ast_expression*)var;
3205 fval->expression.variadic = variadic;
3208 var->expression.params = params;
3215 for (i = 0; i < vec_size(params); ++i)
3216 ast_delete(params[i]);
3221 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3223 ast_expression *cexp;
3224 ast_value *cval, *tmp;
3227 ctx = parser_ctx(parser);
3229 if (!parser_next(parser)) {
3231 parseerror(parser, "expected array-size");
3235 cexp = parse_expression_leave(parser, true);
3237 if (!cexp || !ast_istype(cexp, ast_value)) {
3241 parseerror(parser, "expected array-size as constant positive integer");
3244 cval = (ast_value*)cexp;
3246 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3247 tmp->expression.next = (ast_expression*)var;
3250 if (cval->expression.vtype == TYPE_INTEGER)
3251 tmp->expression.count = cval->constval.vint;
3252 else if (cval->expression.vtype == TYPE_FLOAT)
3253 tmp->expression.count = cval->constval.vfloat;
3257 parseerror(parser, "array-size must be a positive integer constant");
3262 if (parser->tok != ']') {
3264 parseerror(parser, "expected ']' after array-size");
3267 if (!parser_next(parser)) {
3269 parseerror(parser, "error after parsing array size");
3275 /* Parse a complete typename.
3276 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3277 * but when parsing variables separated by comma
3278 * 'storebase' should point to where the base-type should be kept.
3279 * The base type makes up every bit of type information which comes *before* the
3282 * The following will be parsed in its entirety:
3284 * The 'basetype' in this case is 'void()'
3285 * and if there's a comma after it, say:
3287 * then the type-information 'void()' can be stored in 'storebase'
3289 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3291 ast_value *var, *tmp;
3294 const char *name = NULL;
3295 bool isfield = false;
3296 bool wasarray = false;
3297 size_t morefields = 0;
3299 ctx = parser_ctx(parser);
3301 /* types may start with a dot */
3302 if (parser->tok == '.') {
3304 /* if we parsed a dot we need a typename now */
3305 if (!parser_next(parser)) {
3306 parseerror(parser, "expected typename for field definition");
3310 /* Further dots are handled seperately because they won't be part of the
3313 while (parser->tok == '.') {
3315 if (!parser_next(parser)) {
3316 parseerror(parser, "expected typename for field definition");
3321 if (parser->tok == TOKEN_IDENT)
3322 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3323 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3324 parseerror(parser, "expected typename");
3329 /* generate the basic type value */
3330 if (cached_typedef) {
3331 var = ast_value_copy(cached_typedef);
3332 ast_value_set_name(var, "<type(from_def)>");
3334 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3336 for (; morefields; --morefields) {
3337 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3338 tmp->expression.next = (ast_expression*)var;
3342 /* do not yet turn into a field - remember:
3343 * .void() foo; is a field too
3344 * .void()() foo; is a function
3348 if (!parser_next(parser)) {
3350 parseerror(parser, "parse error after typename");
3354 /* an opening paren now starts the parameter-list of a function
3355 * this is where original-QC has parameter lists.
3356 * We allow a single parameter list here.
3357 * Much like fteqcc we don't allow `float()() x`
3359 if (parser->tok == '(') {
3360 var = parse_parameter_list(parser, var);
3365 /* store the base if requested */
3367 *storebase = ast_value_copy(var);
3369 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3370 tmp->expression.next = (ast_expression*)*storebase;
3375 /* there may be a name now */
3376 if (parser->tok == TOKEN_IDENT) {
3377 name = util_strdup(parser_tokval(parser));
3379 if (!parser_next(parser)) {
3381 parseerror(parser, "error after variable or field declaration");
3386 /* now this may be an array */
3387 if (parser->tok == '[') {
3389 var = parse_arraysize(parser, var);
3394 /* This is the point where we can turn it into a field */
3396 /* turn it into a field if desired */
3397 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3398 tmp->expression.next = (ast_expression*)var;
3402 /* now there may be function parens again */
3403 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3404 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3405 if (parser->tok == '(' && wasarray)
3406 parseerror(parser, "arrays as part of a return type is not supported");
3407 while (parser->tok == '(') {
3408 var = parse_parameter_list(parser, var);
3417 /* finally name it */
3419 if (!ast_value_set_name(var, name)) {
3421 parseerror(parser, "internal error: failed to set name");
3424 /* free the name, ast_value_set_name duplicates */
3431 static bool parse_typedef(parser_t *parser)
3433 ast_value *typevar, *oldtype;
3434 ast_expression *old;
3436 typevar = parse_typename(parser, NULL, NULL);
3441 if ( (old = parser_find_var(parser, typevar->name)) ) {
3442 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3443 " -> `%s` has been declared here: %s:%i",
3444 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3445 ast_delete(typevar);
3449 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3450 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3451 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3452 ast_delete(typevar);
3456 vec_push(parser->_typedefs, typevar);
3457 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3459 if (parser->tok != ';') {
3460 parseerror(parser, "expected semicolon after typedef");
3463 if (!parser_next(parser)) {
3464 parseerror(parser, "parse error after typedef");
3471 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int is_const_var, ast_value *cached_typedef)
3475 ast_expression *old;
3479 ast_value *basetype = NULL;
3481 bool isparam = false;
3482 bool isvector = false;
3483 bool cleanvar = true;
3484 bool wasarray = false;
3488 /* get the first complete variable */
3489 var = parse_typename(parser, &basetype, cached_typedef);
3492 ast_delete(basetype);
3500 /* Part 0: finish the type */
3501 if (parser->tok == '(') {
3502 if (opts_standard == COMPILER_QCC)
3503 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3504 var = parse_parameter_list(parser, var);
3510 /* we only allow 1-dimensional arrays */
3511 if (parser->tok == '[') {
3513 var = parse_arraysize(parser, var);
3519 if (parser->tok == '(' && wasarray) {
3520 parseerror(parser, "arrays as part of a return type is not supported");
3521 /* we'll still parse the type completely for now */
3523 /* for functions returning functions */
3524 while (parser->tok == '(') {
3525 if (opts_standard == COMPILER_QCC)
3526 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3527 var = parse_parameter_list(parser, var);
3534 if (is_const_var == CV_CONST)
3535 var->constant = true;
3538 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3539 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3540 * is then filled with the previous definition and the parameter-names replaced.
3543 /* Deal with end_sys_ vars */
3545 if (!strcmp(var->name, "end_sys_globals")) {
3546 parser->crc_globals = vec_size(parser->globals);
3549 else if (!strcmp(var->name, "end_sys_fields")) {
3550 parser->crc_fields = vec_size(parser->fields);
3553 if (was_end && var->expression.vtype == TYPE_FIELD) {
3554 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3555 "global '%s' hint should not be a field",
3556 parser_tokval(parser)))
3563 if (!nofields && var->expression.vtype == TYPE_FIELD)
3565 /* deal with field declarations */
3566 old = parser_find_field(parser, var->name);
3568 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3569 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3578 parseerror(parser, "field `%s` already declared here: %s:%i",
3579 var->name, ast_ctx(old).file, ast_ctx(old).line);
3584 if (opts_standard == COMPILER_QCC &&
3585 (old = parser_find_global(parser, var->name)))
3587 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3588 parseerror(parser, "field `%s` already declared here: %s:%i",
3589 var->name, ast_ctx(old).file, ast_ctx(old).line);
3596 /* deal with other globals */
3597 old = parser_find_global(parser, var->name);
3598 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3600 /* This is a function which had a prototype */
3601 if (!ast_istype(old, ast_value)) {
3602 parseerror(parser, "internal error: prototype is not an ast_value");
3606 proto = (ast_value*)old;
3607 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3608 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3610 ast_ctx(proto).file, ast_ctx(proto).line);
3614 /* we need the new parameter-names */
3615 for (i = 0; i < vec_size(proto->expression.params); ++i)
3616 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3624 if (opts_standard == COMPILER_GMQCC) {
3625 parseerror(parser, "global `%s` already declared here: %s:%i",
3626 var->name, ast_ctx(old).file, ast_ctx(old).line);
3630 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3631 "global `%s` already declared here: %s:%i",
3632 var->name, ast_ctx(old).file, ast_ctx(old).line))
3639 if (opts_standard == COMPILER_QCC &&
3640 (old = parser_find_field(parser, var->name)))
3642 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3643 parseerror(parser, "global `%s` already declared here: %s:%i",
3644 var->name, ast_ctx(old).file, ast_ctx(old).line);
3651 else /* it's not a global */
3653 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3654 if (old && !isparam) {
3655 parseerror(parser, "local `%s` already declared here: %s:%i",
3656 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3660 old = parser_find_local(parser, var->name, 0, &isparam);
3661 if (old && isparam) {
3662 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3663 "local `%s` is shadowing a parameter", var->name))
3665 parseerror(parser, "local `%s` already declared here: %s:%i",
3666 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3670 if (opts_standard != COMPILER_GMQCC) {
3679 * Create the global/local, and deal with vector types.
3682 if (var->expression.vtype == TYPE_VECTOR)
3684 else if (var->expression.vtype == TYPE_FIELD &&
3685 var->expression.next->expression.vtype == TYPE_VECTOR)
3689 if (!create_vector_members(var, me)) {
3696 /* deal with global variables, fields, functions */
3697 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3698 vec_push(parser->fields, (ast_expression*)var);
3699 util_htset(parser->htfields, var->name, var);
3701 for (i = 0; i < 3; ++i) {
3702 vec_push(parser->fields, (ast_expression*)me[i]);
3703 util_htset(parser->htfields, me[i]->name, me[i]);
3708 vec_push(parser->globals, (ast_expression*)var);
3709 util_htset(parser->htglobals, var->name, var);
3711 for (i = 0; i < 3; ++i) {
3712 vec_push(parser->globals, (ast_expression*)me[i]);
3713 util_htset(parser->htglobals, me[i]->name, me[i]);
3718 vec_push(localblock->locals, var);
3719 parser_addlocal(parser, var->name, (ast_expression*)var);
3721 for (i = 0; i < 3; ++i) {
3722 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3723 ast_block_collect(localblock, (ast_expression*)me[i]);
3729 me[0] = me[1] = me[2] = NULL;
3734 if (var->expression.vtype == TYPE_ARRAY) {
3736 snprintf(name, sizeof(name), "%s##SET", var->name);
3737 if (!parser_create_array_setter(parser, var, name))
3739 snprintf(name, sizeof(name), "%s##GET", var->name);
3740 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3743 else if (!localblock && !nofields &&
3744 var->expression.vtype == TYPE_FIELD &&
3745 var->expression.next->expression.vtype == TYPE_ARRAY)
3748 ast_expression *telem;
3750 ast_value *array = (ast_value*)var->expression.next;
3752 if (!ast_istype(var->expression.next, ast_value)) {
3753 parseerror(parser, "internal error: field element type must be an ast_value");
3757 snprintf(name, sizeof(name), "%s##SETF", var->name);
3758 if (!parser_create_array_field_setter(parser, array, name))
3761 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3762 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3763 tfield->expression.next = telem;
3764 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3765 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3773 if (parser->tok == ';') {
3774 ast_delete(basetype);
3775 if (!parser_next(parser)) {
3776 parseerror(parser, "error after variable declaration");
3782 if (parser->tok == ',')
3785 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3786 parseerror(parser, "missing comma or semicolon while parsing variables");
3790 if (localblock && opts_standard == COMPILER_QCC) {
3791 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3792 "initializing expression turns variable `%s` into a constant in this standard",
3799 if (parser->tok != '{') {
3800 if (parser->tok != '=') {
3801 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
3805 if (!parser_next(parser)) {
3806 parseerror(parser, "error parsing initializer");
3810 else if (opts_standard == COMPILER_QCC) {
3811 parseerror(parser, "expected '=' before function body in this standard");
3814 if (parser->tok == '#') {
3815 ast_function *func = NULL;
3818 parseerror(parser, "cannot declare builtins within functions");
3821 if (var->expression.vtype != TYPE_FUNCTION) {
3822 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3825 if (!parser_next(parser)) {
3826 parseerror(parser, "expected builtin number");
3829 if (parser->tok != TOKEN_INTCONST) {
3830 parseerror(parser, "builtin number must be an integer constant");
3833 if (parser_token(parser)->constval.i <= 0) {
3834 parseerror(parser, "builtin number must be an integer greater than zero");
3838 if (var->hasvalue) {
3839 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3840 "builtin `%s` has already been defined\n"
3841 " -> previous declaration here: %s:%i",
3842 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3846 func = ast_function_new(ast_ctx(var), var->name, var);
3848 parseerror(parser, "failed to allocate function for `%s`", var->name);
3851 vec_push(parser->functions, func);
3853 func->builtin = -parser_token(parser)->constval.i;
3856 if (!parser_next(parser)) {
3857 parseerror(parser, "expected comma or semicolon");
3859 ast_function_delete(func);
3860 var->constval.vfunc = NULL;
3864 else if (parser->tok == '{' || parser->tok == '[')
3867 parseerror(parser, "cannot declare functions within functions");
3871 if (!parse_function_body(parser, var))
3873 ast_delete(basetype);
3876 ast_expression *cexp;
3879 cexp = parse_expression_leave(parser, true);
3884 cval = (ast_value*)cexp;
3885 if (!ast_istype(cval, ast_value) || !cval->hasvalue || !cval->constant)
3886 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3889 if (opts_standard != COMPILER_GMQCC &&
3890 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
3891 is_const_var != CV_VAR)
3893 var->constant = true;
3895 var->hasvalue = true;
3896 if (cval->expression.vtype == TYPE_STRING)
3897 var->constval.vstring = parser_strdup(cval->constval.vstring);
3899 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3904 shunt sy = { NULL, NULL };
3905 cvq = var->constant;
3906 var->constant = false;
3907 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3908 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3909 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3910 if (!parser_sy_pop(parser, &sy))
3913 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3914 parseerror(parser, "internal error: leaked operands");
3915 ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out);
3919 var->constant = cvq;
3924 if (parser->tok == ',') {
3925 if (!parser_next(parser)) {
3926 parseerror(parser, "expected another variable");
3930 if (parser->tok != TOKEN_IDENT) {
3931 parseerror(parser, "expected another variable");
3934 var = ast_value_copy(basetype);
3936 ast_value_set_name(var, parser_tokval(parser));
3937 if (!parser_next(parser)) {
3938 parseerror(parser, "error parsing variable declaration");
3944 if (parser->tok != ';') {
3945 parseerror(parser, "missing semicolon after variables");
3949 if (!parser_next(parser)) {
3950 parseerror(parser, "parse error after variable declaration");
3954 ast_delete(basetype);
3958 if (cleanvar && var)
3960 ast_delete(basetype);
3964 ast_delete(basetype);
3965 if (cleanvar && var)
3967 if (me[0]) ast_member_delete(me[0]);
3968 if (me[1]) ast_member_delete(me[1]);
3969 if (me[2]) ast_member_delete(me[2]);
3973 static bool parser_global_statement(parser_t *parser)
3975 ast_value *istype = NULL;
3976 if (parser->tok == TOKEN_IDENT)
3977 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
3979 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3981 return parse_variable(parser, NULL, false, CV_NONE, istype);
3983 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3985 if (!strcmp(parser_tokval(parser), "var")) {
3986 if (!parser_next(parser)) {
3987 parseerror(parser, "expected variable declaration after 'var'");
3990 return parse_variable(parser, NULL, true, CV_VAR, NULL);
3993 else if (parser->tok == TOKEN_KEYWORD)
3995 if (!strcmp(parser_tokval(parser), "const")) {
3996 if (!parser_next(parser)) {
3997 parseerror(parser, "expected variable declaration after 'const'");
4000 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
4001 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
4002 if (!parser_next(parser)) {
4003 parseerror(parser, "expected variable declaration after 'const var'");
4007 return parse_variable(parser, NULL, true, CV_CONST, NULL);
4009 else if (!strcmp(parser_tokval(parser), "typedef")) {
4010 if (!parser_next(parser)) {
4011 parseerror(parser, "expected type definition after 'typedef'");
4014 return parse_typedef(parser);
4016 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4019 else if (parser->tok == '$')
4021 if (!parser_next(parser)) {
4022 parseerror(parser, "parse error");
4028 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4034 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4036 return util_crc16(old, str, strlen(str));
4039 static void progdefs_crc_file(const char *str)
4041 /* write to progdefs.h here */
4045 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4047 old = progdefs_crc_sum(old, str);
4048 progdefs_crc_file(str);
4052 static void generate_checksum(parser_t *parser)
4054 uint16_t crc = 0xFFFF;
4058 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4059 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4061 progdefs_crc_file("\tint\tpad;\n");
4062 progdefs_crc_file("\tint\tofs_return[3];\n");
4063 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4064 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4065 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4066 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4067 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4068 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4069 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4070 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4072 for (i = 0; i < parser->crc_globals; ++i) {
4073 if (!ast_istype(parser->globals[i], ast_value))
4075 value = (ast_value*)(parser->globals[i]);
4076 switch (value->expression.vtype) {
4077 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4078 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4079 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4080 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4082 crc = progdefs_crc_both(crc, "\tint\t");
4085 crc = progdefs_crc_both(crc, value->name);
4086 crc = progdefs_crc_both(crc, ";\n");
4088 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4089 for (i = 0; i < parser->crc_fields; ++i) {
4090 if (!ast_istype(parser->fields[i], ast_value))
4092 value = (ast_value*)(parser->fields[i]);
4093 switch (value->expression.next->expression.vtype) {
4094 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4095 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4096 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4097 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4099 crc = progdefs_crc_both(crc, "\tint\t");
4102 crc = progdefs_crc_both(crc, value->name);
4103 crc = progdefs_crc_both(crc, ";\n");
4105 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4110 static parser_t *parser;
4116 parser = (parser_t*)mem_a(sizeof(parser_t));
4120 memset(parser, 0, sizeof(*parser));
4122 for (i = 0; i < operator_count; ++i) {
4123 if (operators[i].id == opid1('=')) {
4124 parser->assign_op = operators+i;
4128 if (!parser->assign_op) {
4129 printf("internal error: initializing parser: failed to find assign operator\n");
4134 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4135 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4136 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4137 vec_push(parser->_blocktypedefs, 0);
4141 bool parser_compile()
4143 /* initial lexer/parser state */
4144 parser->lex->flags.noops = true;
4146 if (parser_next(parser))
4148 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4150 if (!parser_global_statement(parser)) {
4151 if (parser->tok == TOKEN_EOF)
4152 parseerror(parser, "unexpected eof");
4153 else if (!parser->errors)
4154 parseerror(parser, "there have been errors, bailing out");
4155 lex_close(parser->lex);
4161 parseerror(parser, "parse error");
4162 lex_close(parser->lex);
4167 lex_close(parser->lex);
4170 return !parser->errors;
4173 bool parser_compile_file(const char *filename)
4175 parser->lex = lex_open(filename);
4177 con_err("failed to open file \"%s\"\n", filename);
4180 return parser_compile();
4183 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4185 parser->lex = lex_open_string(str, len, name);
4187 con_err("failed to create lexer for string \"%s\"\n", name);
4190 return parser_compile();
4193 bool parser_compile_string(const char *name, const char *str)
4195 parser->lex = lex_open_string(str, strlen(str), name);
4197 con_err("failed to create lexer for string \"%s\"\n", name);
4200 return parser_compile();
4203 void parser_cleanup()
4206 for (i = 0; i < vec_size(parser->accessors); ++i) {
4207 ast_delete(parser->accessors[i]->constval.vfunc);
4208 parser->accessors[i]->constval.vfunc = NULL;
4209 ast_delete(parser->accessors[i]);
4211 for (i = 0; i < vec_size(parser->functions); ++i) {
4212 ast_delete(parser->functions[i]);
4214 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4215 ast_delete(parser->imm_vector[i]);
4217 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4218 ast_delete(parser->imm_string[i]);
4220 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4221 ast_delete(parser->imm_float[i]);
4223 for (i = 0; i < vec_size(parser->fields); ++i) {
4224 ast_delete(parser->fields[i]);
4226 for (i = 0; i < vec_size(parser->globals); ++i) {
4227 ast_delete(parser->globals[i]);
4229 vec_free(parser->accessors);
4230 vec_free(parser->functions);
4231 vec_free(parser->imm_vector);
4232 vec_free(parser->imm_string);
4233 vec_free(parser->imm_float);
4234 vec_free(parser->globals);
4235 vec_free(parser->fields);
4237 for (i = 0; i < vec_size(parser->variables); ++i)
4238 util_htdel(parser->variables[i]);
4239 vec_free(parser->variables);
4240 vec_free(parser->_blocklocals);
4241 vec_free(parser->_locals);
4243 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4244 ast_delete(parser->_typedefs[i]);
4245 vec_free(parser->_typedefs);
4246 for (i = 0; i < vec_size(parser->typedefs); ++i)
4247 util_htdel(parser->typedefs[i]);
4248 vec_free(parser->typedefs);
4249 vec_free(parser->_blocktypedefs);
4254 bool parser_finish(const char *output)
4260 if (!parser->errors)
4262 ir = ir_builder_new("gmqcc_out");
4264 con_out("failed to allocate builder\n");
4268 for (i = 0; i < vec_size(parser->fields); ++i) {
4271 if (!ast_istype(parser->fields[i], ast_value))
4273 field = (ast_value*)parser->fields[i];
4274 hasvalue = field->hasvalue;
4275 field->hasvalue = false;
4276 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4277 con_out("failed to generate field %s\n", field->name);
4278 ir_builder_delete(ir);
4283 ast_expression *subtype;
4284 field->hasvalue = true;
4285 subtype = field->expression.next;
4286 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4287 if (subtype->expression.vtype == TYPE_FIELD)
4288 ifld->fieldtype = subtype->expression.next->expression.vtype;
4289 else if (subtype->expression.vtype == TYPE_FUNCTION)
4290 ifld->outtype = subtype->expression.next->expression.vtype;
4291 (void)!ir_value_set_field(field->ir_v, ifld);
4294 for (i = 0; i < vec_size(parser->globals); ++i) {
4296 if (!ast_istype(parser->globals[i], ast_value))
4298 asvalue = (ast_value*)(parser->globals[i]);
4299 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4300 if (strcmp(asvalue->name, "end_sys_globals") &&
4301 strcmp(asvalue->name, "end_sys_fields"))
4303 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4304 "unused global: `%s`", asvalue->name);
4307 if (!ast_global_codegen(asvalue, ir, false)) {
4308 con_out("failed to generate global %s\n", asvalue->name);
4309 ir_builder_delete(ir);
4313 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4314 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4315 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4316 ir_builder_delete(ir);
4320 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4321 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4322 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4323 ir_builder_delete(ir);
4327 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4328 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4329 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4330 ir_builder_delete(ir);
4334 for (i = 0; i < vec_size(parser->globals); ++i) {
4336 if (!ast_istype(parser->globals[i], ast_value))
4338 asvalue = (ast_value*)(parser->globals[i]);
4339 if (asvalue->setter) {
4340 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4341 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4342 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4344 printf("failed to generate setter for %s\n", asvalue->name);
4345 ir_builder_delete(ir);
4349 if (asvalue->getter) {
4350 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4351 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4352 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4354 printf("failed to generate getter for %s\n", asvalue->name);
4355 ir_builder_delete(ir);
4360 for (i = 0; i < vec_size(parser->fields); ++i) {
4362 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4364 if (!ast_istype((ast_expression*)asvalue, ast_value))
4366 if (asvalue->expression.vtype != TYPE_ARRAY)
4368 if (asvalue->setter) {
4369 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4370 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4371 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4373 printf("failed to generate setter for %s\n", asvalue->name);
4374 ir_builder_delete(ir);
4378 if (asvalue->getter) {
4379 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4380 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4381 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4383 printf("failed to generate getter for %s\n", asvalue->name);
4384 ir_builder_delete(ir);
4389 for (i = 0; i < vec_size(parser->functions); ++i) {
4390 if (!ast_function_codegen(parser->functions[i], ir)) {
4391 con_out("failed to generate function %s\n", parser->functions[i]->name);
4392 ir_builder_delete(ir);
4397 ir_builder_dump(ir, con_out);
4398 for (i = 0; i < vec_size(parser->functions); ++i) {
4399 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4400 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4401 ir_builder_delete(ir);
4408 ir_builder_dump(ir, con_out);
4410 generate_checksum(parser);
4412 if (!ir_builder_generate(ir, output)) {
4413 con_out("*** failed to generate output file\n");
4414 ir_builder_delete(ir);
4419 ir_builder_delete(ir);
4423 con_out("*** there were compile errors\n");