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
85 static void parser_enterblock(parser_t *parser);
86 static bool parser_leaveblock(parser_t *parser);
87 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
88 static bool parse_typedef(parser_t *parser);
89 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef);
90 static ast_block* parse_block(parser_t *parser, bool warnreturn);
91 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
92 static ast_expression* parse_statement_or_block(parser_t *parser);
93 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
94 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
95 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
97 static void parseerror(parser_t *parser, const char *fmt, ...)
104 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
108 /* returns true if it counts as an error */
109 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
112 int lvl = LVL_WARNING;
114 if (!OPTS_WARN(warntype))
123 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
129 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
132 int lvl = LVL_WARNING;
134 if (!OPTS_WARN(warntype))
141 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
147 /**********************************************************************
148 * some maths used for constant folding
151 vector vec3_add(vector a, vector b)
160 vector vec3_sub(vector a, vector b)
169 qcfloat vec3_mulvv(vector a, vector b)
171 return (a.x * b.x + a.y * b.y + a.z * b.z);
174 vector vec3_mulvf(vector a, float b)
183 /**********************************************************************
187 bool parser_next(parser_t *parser)
189 /* lex_do kills the previous token */
190 parser->tok = lex_do(parser->lex);
191 if (parser->tok == TOKEN_EOF)
193 if (parser->tok >= TOKEN_ERROR) {
194 parseerror(parser, "lex error");
200 #define parser_tokval(p) ((p)->lex->tok.value)
201 #define parser_token(p) (&((p)->lex->tok))
202 #define parser_ctx(p) ((p)->lex->tok.ctx)
204 static ast_value* parser_const_float(parser_t *parser, double d)
208 for (i = 0; i < vec_size(parser->imm_float); ++i) {
209 const double compare = parser->imm_float[i]->constval.vfloat;
210 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
211 return parser->imm_float[i];
213 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
215 out->constval.vfloat = d;
216 vec_push(parser->imm_float, out);
220 static ast_value* parser_const_float_0(parser_t *parser)
222 if (!parser->imm_float_zero)
223 parser->imm_float_zero = parser_const_float(parser, 0);
224 return parser->imm_float_zero;
227 static ast_value* parser_const_float_1(parser_t *parser)
229 if (!parser->imm_float_one)
230 parser->imm_float_one = parser_const_float(parser, 1);
231 return parser->imm_float_one;
234 static char *parser_strdup(const char *str)
237 /* actually dup empty strings */
238 char *out = mem_a(1);
242 return util_strdup(str);
245 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
249 for (i = 0; i < vec_size(parser->imm_string); ++i) {
250 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
251 return parser->imm_string[i];
255 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
256 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
258 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
260 out->constval.vstring = parser_strdup(str);
261 vec_push(parser->imm_string, out);
265 static ast_value* parser_const_vector(parser_t *parser, vector v)
269 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
270 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
271 return parser->imm_vector[i];
273 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
275 out->constval.vvec = v;
276 vec_push(parser->imm_vector, out);
280 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
286 return parser_const_vector(parser, v);
289 static ast_value* parser_const_vector_0(parser_t *parser)
291 if (!parser->imm_vector_zero)
292 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
293 return parser->imm_vector_zero;
296 static ast_expression* parser_find_field(parser_t *parser, const char *name)
298 return util_htget(parser->htfields, name);
301 static ast_expression* parser_find_global(parser_t *parser, const char *name)
303 return util_htget(parser->htglobals, name);
306 static ast_expression* parser_find_param(parser_t *parser, const char *name)
310 if (!parser->function)
312 fun = parser->function->vtype;
313 for (i = 0; i < vec_size(fun->expression.params); ++i) {
314 if (!strcmp(fun->expression.params[i]->name, name))
315 return (ast_expression*)(fun->expression.params[i]);
320 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
325 hash = util_hthash(parser->htglobals, name);
328 for (i = vec_size(parser->variables); i > upto;) {
330 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
334 return parser_find_param(parser, name);
337 static ast_expression* parser_find_var(parser_t *parser, const char *name)
341 v = parser_find_local(parser, name, 0, &dummy);
342 if (!v) v = parser_find_global(parser, name);
346 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
350 hash = util_hthash(parser->typedefs[0], name);
352 for (i = vec_size(parser->typedefs); i > upto;) {
354 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
362 size_t etype; /* 0 = expression, others are operators */
366 ast_block *block; /* for commas and function calls */
375 #define SY_PAREN_EXPR '('
376 #define SY_PAREN_FUNC 'f'
377 #define SY_PAREN_INDEX '['
379 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
390 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
394 e.out = (ast_expression*)v;
401 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
403 e.etype = 1 + (op - operators);
412 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
424 # define DEBUGSHUNTDO(x) x
426 # define DEBUGSHUNTDO(x)
429 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
430 * so we need to rotate it to become ent.(foo[n]).
432 static bool rotate_entfield_array_index_nodes(ast_expression **out)
434 ast_array_index *index;
435 ast_entfield *entfield;
439 ast_expression *entity;
441 lex_ctx ctx = ast_ctx(*out);
443 if (!ast_istype(*out, ast_array_index))
445 index = (ast_array_index*)*out;
447 if (!ast_istype(index->array, ast_entfield))
449 entfield = (ast_entfield*)index->array;
451 if (!ast_istype(entfield->field, ast_value))
453 field = (ast_value*)entfield->field;
456 entity = entfield->entity;
460 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
461 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
462 *out = (ast_expression*)entfield;
467 static bool parser_sy_pop(parser_t *parser, shunt *sy)
471 ast_expression *out = NULL;
472 ast_expression *exprs[3];
473 ast_block *blocks[3];
474 ast_value *asvalue[3];
475 size_t i, assignop, addop, subop;
476 qcint generated_op = 0;
481 if (!vec_size(sy->ops)) {
482 parseerror(parser, "internal error: missing operator");
486 if (vec_last(sy->ops).paren) {
487 parseerror(parser, "unmatched parenthesis");
491 op = &operators[vec_last(sy->ops).etype - 1];
492 ctx = vec_last(sy->ops).ctx;
494 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
496 if (vec_size(sy->out) < op->operands) {
497 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
498 op->op, (int)op->id);
502 vec_shrinkby(sy->ops, 1);
504 vec_shrinkby(sy->out, op->operands);
505 for (i = 0; i < op->operands; ++i) {
506 exprs[i] = sy->out[vec_size(sy->out)+i].out;
507 blocks[i] = sy->out[vec_size(sy->out)+i].block;
508 asvalue[i] = (ast_value*)exprs[i];
511 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
512 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
516 #define NotSameType(T) \
517 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
518 exprs[0]->expression.vtype != T)
519 #define CanConstFold1(A) \
520 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
521 #define CanConstFold(A, B) \
522 (CanConstFold1(A) && CanConstFold1(B))
523 #define ConstV(i) (asvalue[(i)]->constval.vvec)
524 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
525 #define ConstS(i) (asvalue[(i)]->constval.vstring)
529 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
533 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
534 if (exprs[1]->expression.vtype != TYPE_FIELD) {
535 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
538 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
540 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
541 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
545 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
551 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
552 !(exprs[0]->expression.vtype == TYPE_FIELD &&
553 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
555 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
556 parseerror(parser, "cannot index value of type %s", ty1);
559 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
560 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
561 parseerror(parser, "index must be of type float, not %s", ty1);
564 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
565 if (rotate_entfield_array_index_nodes(&out))
567 if (opts_standard != COMPILER_GMQCC) {
568 /* this error doesn't need to make us bail out */
569 (void)!parsewarning(parser, WARN_EXTENSIONS,
570 "accessing array-field members of an entity without parenthesis\n"
571 " -> this is an extension from -std=gmqcc");
578 vec_push(blocks[0]->exprs, exprs[1]);
580 blocks[0] = ast_block_new(ctx);
581 vec_push(blocks[0]->exprs, exprs[0]);
582 vec_push(blocks[0]->exprs, exprs[1]);
584 if (!ast_block_set_type(blocks[0], exprs[1]))
587 vec_push(sy->out, syblock(ctx, blocks[0]));
591 switch (exprs[0]->expression.vtype) {
593 if (CanConstFold1(exprs[0]))
594 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
596 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
597 (ast_expression*)parser_const_float_0(parser),
601 if (CanConstFold1(exprs[0]))
602 out = (ast_expression*)parser_const_vector_f(parser,
603 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
605 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
606 (ast_expression*)parser_const_vector_0(parser),
610 parseerror(parser, "invalid types used in expression: cannot negate type %s",
611 type_name[exprs[0]->expression.vtype]);
617 switch (exprs[0]->expression.vtype) {
619 if (CanConstFold1(exprs[0]))
620 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
622 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
625 if (CanConstFold1(exprs[0]))
626 out = (ast_expression*)parser_const_float(parser,
627 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
629 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
632 if (CanConstFold1(exprs[0]))
633 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
635 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
637 /* we don't constant-fold NOT for these types */
639 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
642 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
645 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
646 type_name[exprs[0]->expression.vtype]);
652 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
653 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
655 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
656 type_name[exprs[0]->expression.vtype],
657 type_name[exprs[1]->expression.vtype]);
660 switch (exprs[0]->expression.vtype) {
662 if (CanConstFold(exprs[0], exprs[1]))
664 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
667 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
670 if (CanConstFold(exprs[0], exprs[1]))
671 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
673 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
676 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
677 type_name[exprs[0]->expression.vtype],
678 type_name[exprs[1]->expression.vtype]);
683 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
684 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
686 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
687 type_name[exprs[1]->expression.vtype],
688 type_name[exprs[0]->expression.vtype]);
691 switch (exprs[0]->expression.vtype) {
693 if (CanConstFold(exprs[0], exprs[1]))
694 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
696 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
699 if (CanConstFold(exprs[0], exprs[1]))
700 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
702 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
705 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
706 type_name[exprs[1]->expression.vtype],
707 type_name[exprs[0]->expression.vtype]);
712 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
713 exprs[0]->expression.vtype != TYPE_VECTOR &&
714 exprs[0]->expression.vtype != TYPE_FLOAT &&
715 exprs[1]->expression.vtype != TYPE_VECTOR &&
716 exprs[1]->expression.vtype != TYPE_FLOAT)
718 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
719 type_name[exprs[1]->expression.vtype],
720 type_name[exprs[0]->expression.vtype]);
723 switch (exprs[0]->expression.vtype) {
725 if (exprs[1]->expression.vtype == TYPE_VECTOR)
727 if (CanConstFold(exprs[0], exprs[1]))
728 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
730 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
734 if (CanConstFold(exprs[0], exprs[1]))
735 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
737 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
741 if (exprs[1]->expression.vtype == TYPE_FLOAT)
743 if (CanConstFold(exprs[0], exprs[1]))
744 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
746 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
750 if (CanConstFold(exprs[0], exprs[1]))
751 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
753 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
757 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
758 type_name[exprs[1]->expression.vtype],
759 type_name[exprs[0]->expression.vtype]);
764 if (NotSameType(TYPE_FLOAT)) {
765 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
766 type_name[exprs[0]->expression.vtype],
767 type_name[exprs[1]->expression.vtype]);
770 if (CanConstFold(exprs[0], exprs[1]))
771 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
773 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
777 parseerror(parser, "qc does not have a modulo operator");
781 if (NotSameType(TYPE_FLOAT)) {
782 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
783 type_name[exprs[0]->expression.vtype],
784 type_name[exprs[1]->expression.vtype]);
787 if (CanConstFold(exprs[0], exprs[1]))
788 out = (ast_expression*)parser_const_float(parser,
789 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
790 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
792 out = (ast_expression*)ast_binary_new(ctx,
793 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
797 parseerror(parser, "TODO: bitxor");
802 case opid3('<','<','='):
803 case opid3('>','>','='):
804 parseerror(parser, "TODO: shifts");
808 generated_op += 1; /* INSTR_OR */
810 generated_op += INSTR_AND;
811 if (NotSameType(TYPE_FLOAT)) {
812 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
813 type_name[exprs[0]->expression.vtype],
814 type_name[exprs[1]->expression.vtype]);
815 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
816 parseerror(parser, "TODO: optional early out");
819 if (opts_standard == COMPILER_GMQCC)
820 con_out("TODO: early out logic\n");
821 if (CanConstFold(exprs[0], exprs[1]))
822 out = (ast_expression*)parser_const_float(parser,
823 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
825 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
829 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
830 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
831 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
832 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
835 if (CanConstFold1(exprs[0]))
836 out = (ConstF(0) ? exprs[1] : exprs[2]);
838 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
842 generated_op += 1; /* INSTR_GT */
844 generated_op += 1; /* INSTR_LT */
845 case opid2('>', '='):
846 generated_op += 1; /* INSTR_GE */
847 case opid2('<', '='):
848 generated_op += INSTR_LE;
849 if (NotSameType(TYPE_FLOAT)) {
850 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
851 type_name[exprs[0]->expression.vtype],
852 type_name[exprs[1]->expression.vtype]);
855 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
857 case opid2('!', '='):
858 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
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, type_ne_instr[exprs[0]->expression.vtype], 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_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
877 if (ast_istype(exprs[0], ast_entfield)) {
878 ast_expression *field = ((ast_entfield*)exprs[0])->field;
879 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
880 exprs[0]->expression.vtype == TYPE_FIELD &&
881 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
883 assignop = type_storep_instr[TYPE_VECTOR];
886 assignop = type_storep_instr[exprs[0]->expression.vtype];
887 if (!ast_compare_type(field->expression.next, exprs[1])) {
888 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
889 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
890 if (opts_standard == COMPILER_QCC &&
891 field->expression.next->expression.vtype == TYPE_FUNCTION &&
892 exprs[1]->expression.vtype == TYPE_FUNCTION)
894 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
895 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
901 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
906 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
907 exprs[0]->expression.vtype == TYPE_FIELD &&
908 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
910 assignop = type_store_instr[TYPE_VECTOR];
913 assignop = type_store_instr[exprs[0]->expression.vtype];
916 if (assignop == AINSTR_END) {
917 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
918 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
919 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
921 else if (!ast_compare_type(exprs[0], exprs[1])) {
922 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
923 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
924 if (opts_standard == COMPILER_QCC &&
925 exprs[0]->expression.vtype == TYPE_FUNCTION &&
926 exprs[1]->expression.vtype == TYPE_FUNCTION)
928 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
929 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
935 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
938 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
940 case opid3('+','+','P'):
941 case opid3('-','-','P'):
943 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
944 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
945 parseerror(parser, "invalid type for prefix increment: %s", ty1);
948 if (op->id == opid3('+','+','P'))
952 if (ast_istype(exprs[0], ast_entfield)) {
953 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
955 (ast_expression*)parser_const_float_1(parser));
957 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
959 (ast_expression*)parser_const_float_1(parser));
962 case opid3('S','+','+'):
963 case opid3('S','-','-'):
965 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
966 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
967 parseerror(parser, "invalid type for suffix increment: %s", ty1);
970 if (op->id == opid3('S','+','+')) {
977 if (ast_istype(exprs[0], ast_entfield)) {
978 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
980 (ast_expression*)parser_const_float_1(parser));
982 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
984 (ast_expression*)parser_const_float_1(parser));
988 out = (ast_expression*)ast_binary_new(ctx, subop,
990 (ast_expression*)parser_const_float_1(parser));
994 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
995 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
997 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
998 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
999 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1003 if (ast_istype(exprs[0], ast_entfield))
1004 assignop = type_storep_instr[exprs[0]->expression.vtype];
1006 assignop = type_store_instr[exprs[0]->expression.vtype];
1007 switch (exprs[0]->expression.vtype) {
1009 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1010 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1011 exprs[0], exprs[1]);
1014 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1015 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1016 exprs[0], exprs[1]);
1019 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1020 type_name[exprs[0]->expression.vtype],
1021 type_name[exprs[1]->expression.vtype]);
1025 case opid2('*','='):
1026 case opid2('/','='):
1027 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1028 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1029 exprs[0]->expression.vtype == TYPE_VECTOR))
1031 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1032 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1033 parseerror(parser, "invalid types used in expression: %s and %s",
1037 if (ast_istype(exprs[0], ast_entfield))
1038 assignop = type_storep_instr[exprs[0]->expression.vtype];
1040 assignop = type_store_instr[exprs[0]->expression.vtype];
1041 switch (exprs[0]->expression.vtype) {
1043 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1044 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1045 exprs[0], exprs[1]);
1048 if (op->id == opid2('*','=')) {
1049 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1050 exprs[0], exprs[1]);
1052 /* there's no DIV_VF */
1053 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1054 (ast_expression*)parser_const_float_1(parser),
1058 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1063 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1064 type_name[exprs[0]->expression.vtype],
1065 type_name[exprs[1]->expression.vtype]);
1069 case opid2('&','='):
1070 case opid2('|','='):
1071 if (NotSameType(TYPE_FLOAT)) {
1072 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1073 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1074 parseerror(parser, "invalid types used in expression: %s and %s",
1078 if (ast_istype(exprs[0], ast_entfield))
1079 assignop = type_storep_instr[exprs[0]->expression.vtype];
1081 assignop = type_store_instr[exprs[0]->expression.vtype];
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1083 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1084 exprs[0], exprs[1]);
1086 case opid3('&','~','='):
1087 /* This is like: a &= ~(b);
1088 * But QC has no bitwise-not, so we implement it as
1091 if (NotSameType(TYPE_FLOAT)) {
1092 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1094 parseerror(parser, "invalid types used in expression: %s and %s",
1098 if (ast_istype(exprs[0], ast_entfield))
1099 assignop = type_storep_instr[exprs[0]->expression.vtype];
1101 assignop = type_store_instr[exprs[0]->expression.vtype];
1102 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1105 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1111 parseerror(parser, "failed to apply operand %s", op->op);
1115 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1116 vec_push(sy->out, syexp(ctx, out));
1120 static bool parser_close_call(parser_t *parser, shunt *sy)
1122 /* was a function call */
1123 ast_expression *fun;
1129 vec_shrinkby(sy->ops, 1);
1130 fid = sy->ops[vec_size(sy->ops)].off;
1132 /* out[fid] is the function
1133 * everything above is parameters...
1134 * 0 params = nothing
1135 * 1 params = ast_expression
1139 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1140 parseerror(parser, "internal error: function call needs function and parameter list...");
1144 fun = sy->out[fid].out;
1146 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1148 parseerror(parser, "out of memory");
1152 if (fid+1 == vec_size(sy->out)) {
1155 } else if (fid+2 == vec_size(sy->out)) {
1157 vec_shrinkby(sy->out, 1);
1158 params = sy->out[vec_size(sy->out)].block;
1162 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1164 paramcount = vec_size(params->exprs);
1165 call->params = params->exprs;
1166 params->exprs = NULL;
1169 if (!ast_call_check_types(call))
1172 parseerror(parser, "invalid function call");
1176 /* overwrite fid, the function, with a call */
1177 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1179 if (fun->expression.vtype != TYPE_FUNCTION) {
1180 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1184 if (!fun->expression.next) {
1185 parseerror(parser, "could not determine function return type");
1188 if (vec_size(fun->expression.params) != paramcount &&
1189 !(fun->expression.variadic &&
1190 vec_size(fun->expression.params) < paramcount))
1193 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1195 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1196 if (opts_standard == COMPILER_GMQCC)
1199 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1200 " -> `%s` has been declared here: %s:%i",
1201 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1202 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1204 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1205 " -> `%s` has been declared here: %s:%i",
1206 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1207 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1213 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1214 "too %s parameters for call to %s: expected %i, got %i\n"
1215 " -> `%s` has been declared here: %s:%i",
1216 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1217 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1219 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1220 "too %s parameters for function call: expected %i, got %i\n"
1221 " -> `%s` has been declared here: %s:%i",
1222 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1223 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1231 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1233 if (!vec_size(sy->ops)) {
1234 parseerror(parser, "unmatched closing paren");
1237 /* this would for bit a + (x) because there are no operators inside (x)
1238 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1239 parseerror(parser, "empty parenthesis expression");
1243 while (vec_size(sy->ops)) {
1244 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1245 if (!parser_close_call(parser, sy))
1249 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1250 vec_shrinkby(sy->ops, 1);
1251 return !functions_only;
1253 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1256 /* pop off the parenthesis */
1257 vec_shrinkby(sy->ops, 1);
1258 /* then apply the index operator */
1259 if (!parser_sy_pop(parser, sy))
1263 if (!parser_sy_pop(parser, sy))
1269 static void parser_reclassify_token(parser_t *parser)
1272 for (i = 0; i < operator_count; ++i) {
1273 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1274 parser->tok = TOKEN_OPERATOR;
1280 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1282 ast_expression *expr = NULL;
1284 bool wantop = false;
1285 bool gotmemberof = false;
1287 /* count the parens because an if starts with one, so the
1288 * end of a condition is an unmatched closing paren
1296 parser->lex->flags.noops = false;
1298 parser_reclassify_token(parser);
1303 gotmemberof = false;
1305 parser->memberof = 0;
1307 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_")) {
1308 /* a translatable string */
1312 parseerror(parser, "expected operator or end of statement, got constant");
1316 if (!parser_next(parser) || parser->tok != '(') {
1317 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1320 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1321 parseerror(parser, "expected a constant string in translatable-string extension");
1324 val = parser_const_string(parser, parser_tokval(parser), true);
1328 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1329 DEBUGSHUNTDO(con_out("push string\n"));
1331 if (!parser_next(parser) || parser->tok != ')') {
1332 parseerror(parser, "expected closing paren after translatable string");
1336 else if (parser->tok == TOKEN_IDENT)
1338 ast_expression *var;
1340 parseerror(parser, "expected operator or end of statement");
1345 if (opts_standard == COMPILER_GMQCC)
1347 if (parser->memberof == TYPE_ENTITY) {
1348 /* still get vars first since there could be a fieldpointer */
1349 var = parser_find_var(parser, parser_tokval(parser));
1351 var = parser_find_field(parser, parser_tokval(parser));
1353 else if (parser->memberof == TYPE_VECTOR)
1355 parseerror(parser, "TODO: implement effective vector member access");
1358 else if (parser->memberof) {
1359 parseerror(parser, "namespace for member not found");
1363 var = parser_find_var(parser, parser_tokval(parser));
1365 var = parser_find_var(parser, parser_tokval(parser));
1367 var = parser_find_field(parser, parser_tokval(parser));
1370 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1373 if (ast_istype(var, ast_value))
1374 ((ast_value*)var)->uses++;
1375 vec_push(sy.out, syexp(parser_ctx(parser), var));
1376 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1378 else if (parser->tok == TOKEN_FLOATCONST) {
1381 parseerror(parser, "expected operator or end of statement, got constant");
1385 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1388 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1389 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1391 else if (parser->tok == TOKEN_INTCONST) {
1394 parseerror(parser, "expected operator or end of statement, got constant");
1398 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1401 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1402 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1404 else if (parser->tok == TOKEN_STRINGCONST) {
1407 parseerror(parser, "expected operator or end of statement, got constant");
1411 val = parser_const_string(parser, parser_tokval(parser), false);
1414 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1415 DEBUGSHUNTDO(con_out("push string\n"));
1417 else if (parser->tok == TOKEN_VECTORCONST) {
1420 parseerror(parser, "expected operator or end of statement, got constant");
1424 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1427 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1428 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1429 parser_token(parser)->constval.v.x,
1430 parser_token(parser)->constval.v.y,
1431 parser_token(parser)->constval.v.z));
1433 else if (parser->tok == '(') {
1434 parseerror(parser, "internal error: '(' should be classified as operator");
1437 else if (parser->tok == '[') {
1438 parseerror(parser, "internal error: '[' should be classified as operator");
1441 else if (parser->tok == ')') {
1443 DEBUGSHUNTDO(con_out("do[op] )\n"));
1447 /* we do expect an operator next */
1448 /* closing an opening paren */
1449 if (!parser_close_paren(parser, &sy, false))
1452 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1456 /* allowed for function calls */
1457 if (!parser_close_paren(parser, &sy, true))
1462 else if (parser->tok == ']') {
1464 parseerror(parser, "operand expected");
1468 if (!parser_close_paren(parser, &sy, false))
1472 else if (parser->tok != TOKEN_OPERATOR) {
1474 parseerror(parser, "expected operator or end of statement");
1481 /* classify the operator */
1482 const oper_info *op;
1483 const oper_info *olast = NULL;
1485 for (o = 0; o < operator_count; ++o) {
1486 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1487 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1488 !strcmp(parser_tokval(parser), operators[o].op))
1493 if (o == operator_count) {
1494 /* no operator found... must be the end of the statement */
1497 /* found an operator */
1500 /* when declaring variables, a comma starts a new variable */
1501 if (op->id == opid1(',') && !parens && stopatcomma) {
1502 /* fixup the token */
1507 /* a colon without a pervious question mark cannot be a ternary */
1508 if (!ternaries && op->id == opid2(':','?')) {
1513 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1514 olast = &operators[vec_last(sy.ops).etype-1];
1517 (op->prec < olast->prec) ||
1518 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1520 if (!parser_sy_pop(parser, &sy))
1522 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1523 olast = &operators[vec_last(sy.ops).etype-1];
1528 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1529 /* for gmqcc standard: open up the namespace of the previous type */
1530 ast_expression *prevex = vec_last(sy.out).out;
1532 parseerror(parser, "unexpected member operator");
1535 if (prevex->expression.vtype == TYPE_ENTITY)
1536 parser->memberof = TYPE_ENTITY;
1537 else if (prevex->expression.vtype == TYPE_VECTOR)
1538 parser->memberof = TYPE_VECTOR;
1540 parseerror(parser, "type error: type has no members");
1546 if (op->id == opid1('(')) {
1548 size_t sycount = vec_size(sy.out);
1549 DEBUGSHUNTDO(con_out("push [op] (\n"));
1551 /* we expected an operator, this is the function-call operator */
1552 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1555 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1556 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1559 } else if (op->id == opid1('[')) {
1561 parseerror(parser, "unexpected array subscript");
1565 /* push both the operator and the paren, this makes life easier */
1566 vec_push(sy.ops, syop(parser_ctx(parser), op));
1567 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1569 } else if (op->id == opid2('?',':')) {
1571 vec_push(sy.ops, syop(parser_ctx(parser), op));
1574 } else if (op->id == opid2(':','?')) {
1575 /* we don't push this operator */
1579 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1580 vec_push(sy.ops, syop(parser_ctx(parser), op));
1581 wantop = !!(op->flags & OP_SUFFIX);
1584 if (!parser_next(parser)) {
1587 if (parser->tok == ';' ||
1588 (!parens && parser->tok == ']'))
1594 while (vec_size(sy.ops)) {
1595 if (!parser_sy_pop(parser, &sy))
1599 parser->lex->flags.noops = true;
1600 if (!vec_size(sy.out)) {
1601 parseerror(parser, "empty expression");
1604 expr = sy.out[0].out;
1607 DEBUGSHUNTDO(con_out("shunt done\n"));
1611 parser->lex->flags.noops = true;
1617 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1619 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1622 if (!parser_next(parser)) {
1629 static void parser_enterblock(parser_t *parser)
1631 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1632 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1633 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1634 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1637 static bool parser_leaveblock(parser_t *parser)
1640 size_t locals, typedefs;
1642 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1643 parseerror(parser, "internal error: parser_leaveblock with no block");
1647 util_htdel(vec_last(parser->variables));
1648 vec_pop(parser->variables);
1649 if (!vec_size(parser->_blocklocals)) {
1650 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1654 locals = vec_last(parser->_blocklocals);
1655 vec_pop(parser->_blocklocals);
1656 while (vec_size(parser->_locals) != locals) {
1657 ast_expression *e = vec_last(parser->_locals);
1658 ast_value *v = (ast_value*)e;
1659 vec_pop(parser->_locals);
1660 if (ast_istype(e, ast_value) && !v->uses) {
1661 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1666 typedefs = vec_last(parser->_blocktypedefs);
1667 while (vec_size(parser->_typedefs) != typedefs) {
1668 ast_delete(vec_last(parser->_typedefs));
1669 vec_pop(parser->_typedefs);
1671 util_htdel(vec_last(parser->typedefs));
1672 vec_pop(parser->typedefs);
1677 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1679 vec_push(parser->_locals, e);
1680 util_htset(vec_last(parser->variables), name, (void*)e);
1683 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1686 ast_expression *cond, *ontrue, *onfalse = NULL;
1689 lex_ctx ctx = parser_ctx(parser);
1691 (void)block; /* not touching */
1693 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1694 if (!parser_next(parser)) {
1695 parseerror(parser, "expected condition or 'not'");
1698 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1700 if (!parser_next(parser)) {
1701 parseerror(parser, "expected condition in parenthesis");
1705 if (parser->tok != '(') {
1706 parseerror(parser, "expected 'if' condition in parenthesis");
1709 /* parse into the expression */
1710 if (!parser_next(parser)) {
1711 parseerror(parser, "expected 'if' condition after opening paren");
1714 /* parse the condition */
1715 cond = parse_expression_leave(parser, false);
1719 if (parser->tok != ')') {
1720 parseerror(parser, "expected closing paren after 'if' condition");
1724 /* parse into the 'then' branch */
1725 if (!parser_next(parser)) {
1726 parseerror(parser, "expected statement for on-true branch of 'if'");
1730 ontrue = parse_statement_or_block(parser);
1735 /* check for an else */
1736 if (!strcmp(parser_tokval(parser), "else")) {
1737 /* parse into the 'else' branch */
1738 if (!parser_next(parser)) {
1739 parseerror(parser, "expected on-false branch after 'else'");
1744 onfalse = parse_statement_or_block(parser);
1753 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1755 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1756 *out = (ast_expression*)ifthen;
1760 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1763 ast_expression *cond, *ontrue;
1765 lex_ctx ctx = parser_ctx(parser);
1767 (void)block; /* not touching */
1769 /* skip the 'while' and check for opening paren */
1770 if (!parser_next(parser) || parser->tok != '(') {
1771 parseerror(parser, "expected 'while' condition in parenthesis");
1774 /* parse into the expression */
1775 if (!parser_next(parser)) {
1776 parseerror(parser, "expected 'while' condition after opening paren");
1779 /* parse the condition */
1780 cond = parse_expression_leave(parser, false);
1784 if (parser->tok != ')') {
1785 parseerror(parser, "expected closing paren after 'while' condition");
1789 /* parse into the 'then' branch */
1790 if (!parser_next(parser)) {
1791 parseerror(parser, "expected while-loop body");
1795 ontrue = parse_statement_or_block(parser);
1801 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1802 *out = (ast_expression*)aloop;
1806 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1809 ast_expression *cond, *ontrue;
1811 lex_ctx ctx = parser_ctx(parser);
1813 (void)block; /* not touching */
1815 /* skip the 'do' and get the body */
1816 if (!parser_next(parser)) {
1817 parseerror(parser, "expected loop body");
1820 ontrue = parse_statement_or_block(parser);
1824 /* expect the "while" */
1825 if (parser->tok != TOKEN_KEYWORD ||
1826 strcmp(parser_tokval(parser), "while"))
1828 parseerror(parser, "expected 'while' and condition");
1833 /* skip the 'while' and check for opening paren */
1834 if (!parser_next(parser) || parser->tok != '(') {
1835 parseerror(parser, "expected 'while' condition in parenthesis");
1839 /* parse into the expression */
1840 if (!parser_next(parser)) {
1841 parseerror(parser, "expected 'while' condition after opening paren");
1845 /* parse the condition */
1846 cond = parse_expression_leave(parser, false);
1850 if (parser->tok != ')') {
1851 parseerror(parser, "expected closing paren after 'while' condition");
1857 if (!parser_next(parser) || parser->tok != ';') {
1858 parseerror(parser, "expected semicolon after condition");
1864 if (!parser_next(parser)) {
1865 parseerror(parser, "parse error");
1871 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1872 *out = (ast_expression*)aloop;
1876 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1879 ast_expression *initexpr, *cond, *increment, *ontrue;
1883 lex_ctx ctx = parser_ctx(parser);
1885 parser_enterblock(parser);
1892 /* skip the 'while' and check for opening paren */
1893 if (!parser_next(parser) || parser->tok != '(') {
1894 parseerror(parser, "expected 'for' expressions in parenthesis");
1897 /* parse into the expression */
1898 if (!parser_next(parser)) {
1899 parseerror(parser, "expected 'for' initializer after opening paren");
1904 if (parser->tok == TOKEN_IDENT)
1905 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
1907 if (typevar || parser->tok == TOKEN_TYPENAME) {
1908 if (opts_standard != COMPILER_GMQCC) {
1909 if (parsewarning(parser, WARN_EXTENSIONS,
1910 "current standard does not allow variable declarations in for-loop initializers"))
1914 parseerror(parser, "TODO: assignment of new variables to be non-const");
1916 if (!parse_variable(parser, block, true, false, typevar))
1919 else if (parser->tok != ';')
1921 initexpr = parse_expression_leave(parser, false);
1926 /* move on to condition */
1927 if (parser->tok != ';') {
1928 parseerror(parser, "expected semicolon after for-loop initializer");
1931 if (!parser_next(parser)) {
1932 parseerror(parser, "expected for-loop condition");
1936 /* parse the condition */
1937 if (parser->tok != ';') {
1938 cond = parse_expression_leave(parser, false);
1943 /* move on to incrementor */
1944 if (parser->tok != ';') {
1945 parseerror(parser, "expected semicolon after for-loop initializer");
1948 if (!parser_next(parser)) {
1949 parseerror(parser, "expected for-loop condition");
1953 /* parse the incrementor */
1954 if (parser->tok != ')') {
1955 increment = parse_expression_leave(parser, false);
1958 if (!ast_istype(increment, ast_store) &&
1959 !ast_istype(increment, ast_call) &&
1960 !ast_istype(increment, ast_binstore))
1962 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1968 if (parser->tok != ')') {
1969 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1972 /* parse into the 'then' branch */
1973 if (!parser_next(parser)) {
1974 parseerror(parser, "expected for-loop body");
1977 ontrue = parse_statement_or_block(parser);
1982 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1983 *out = (ast_expression*)aloop;
1985 if (!parser_leaveblock(parser))
1989 if (initexpr) ast_delete(initexpr);
1990 if (cond) ast_delete(cond);
1991 if (increment) ast_delete(increment);
1992 (void)!parser_leaveblock(parser);
1996 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1998 ast_expression *exp = NULL;
1999 ast_return *ret = NULL;
2000 ast_value *expected = parser->function->vtype;
2002 (void)block; /* not touching */
2004 if (!parser_next(parser)) {
2005 parseerror(parser, "expected return expression");
2009 if (parser->tok != ';') {
2010 exp = parse_expression(parser, false);
2014 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2015 parseerror(parser, "return with invalid expression");
2018 ret = ast_return_new(exp->expression.node.context, exp);
2024 if (!parser_next(parser))
2025 parseerror(parser, "parse error");
2026 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2027 if (opts_standard != COMPILER_GMQCC)
2028 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2030 parseerror(parser, "return without value");
2032 ret = ast_return_new(parser_ctx(parser), NULL);
2034 *out = (ast_expression*)ret;
2038 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2040 lex_ctx ctx = parser_ctx(parser);
2042 (void)block; /* not touching */
2044 if (!parser_next(parser) || parser->tok != ';') {
2045 parseerror(parser, "expected semicolon");
2049 if (!parser_next(parser))
2050 parseerror(parser, "parse error");
2052 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2056 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2058 ast_expression *operand;
2060 ast_switch *switchnode;
2061 ast_switch_case swcase;
2063 lex_ctx ctx = parser_ctx(parser);
2065 (void)block; /* not touching */
2067 /* parse over the opening paren */
2068 if (!parser_next(parser) || parser->tok != '(') {
2069 parseerror(parser, "expected switch operand in parenthesis");
2073 /* parse into the expression */
2074 if (!parser_next(parser)) {
2075 parseerror(parser, "expected switch operand");
2078 /* parse the operand */
2079 operand = parse_expression_leave(parser, false);
2083 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2084 opval = (ast_value*)operand;
2085 if (!ast_istype(operand, ast_value) || !opval->isconst) {
2086 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2092 switchnode = ast_switch_new(ctx, operand);
2095 if (parser->tok != ')') {
2096 ast_delete(switchnode);
2097 parseerror(parser, "expected closing paren after 'switch' operand");
2101 /* parse over the opening paren */
2102 if (!parser_next(parser) || parser->tok != '{') {
2103 ast_delete(switchnode);
2104 parseerror(parser, "expected list of cases");
2108 if (!parser_next(parser)) {
2109 ast_delete(switchnode);
2110 parseerror(parser, "expected 'case' or 'default'");
2115 while (parser->tok != '}') {
2116 ast_block *caseblock;
2118 if (parser->tok != TOKEN_KEYWORD) {
2119 ast_delete(switchnode);
2120 parseerror(parser, "expected 'case' or 'default'");
2123 if (!strcmp(parser_tokval(parser), "case")) {
2124 if (!parser_next(parser)) {
2125 ast_delete(switchnode);
2126 parseerror(parser, "expected expression for case");
2129 swcase.value = parse_expression_leave(parser, false);
2130 if (!swcase.value) {
2131 ast_delete(switchnode);
2132 parseerror(parser, "expected expression for case");
2136 else if (!strcmp(parser_tokval(parser), "default")) {
2137 swcase.value = NULL;
2138 if (!parser_next(parser)) {
2139 ast_delete(switchnode);
2140 parseerror(parser, "expected colon");
2145 /* Now the colon and body */
2146 if (parser->tok != ':') {
2147 if (swcase.value) ast_unref(swcase.value);
2148 ast_delete(switchnode);
2149 parseerror(parser, "expected colon");
2153 if (!parser_next(parser)) {
2154 if (swcase.value) ast_unref(swcase.value);
2155 ast_delete(switchnode);
2156 parseerror(parser, "expected statements or case");
2159 caseblock = ast_block_new(parser_ctx(parser));
2161 if (swcase.value) ast_unref(swcase.value);
2162 ast_delete(switchnode);
2165 swcase.code = (ast_expression*)caseblock;
2166 vec_push(switchnode->cases, swcase);
2168 ast_expression *expr;
2169 if (parser->tok == '}')
2171 if (parser->tok == TOKEN_KEYWORD) {
2172 if (!strcmp(parser_tokval(parser), "case") ||
2173 !strcmp(parser_tokval(parser), "default"))
2178 if (!parse_statement(parser, caseblock, &expr, true)) {
2179 ast_delete(switchnode);
2184 vec_push(caseblock->exprs, expr);
2189 if (parser->tok != '}') {
2190 ast_delete(switchnode);
2191 parseerror(parser, "expected closing paren of case list");
2194 if (!parser_next(parser)) {
2195 ast_delete(switchnode);
2196 parseerror(parser, "parse error after switch");
2199 *out = (ast_expression*)switchnode;
2203 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2205 ast_value *typevar = NULL;
2206 if (parser->tok == TOKEN_IDENT)
2207 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2209 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2211 /* local variable */
2213 parseerror(parser, "cannot declare a variable from here");
2216 if (opts_standard == COMPILER_QCC) {
2217 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2220 if (!parse_variable(parser, block, false, false, typevar))
2225 else if (parser->tok == TOKEN_KEYWORD)
2227 if (!strcmp(parser_tokval(parser), "local"))
2230 parseerror(parser, "cannot declare a local variable here");
2233 if (!parser_next(parser)) {
2234 parseerror(parser, "expected variable declaration");
2237 if (!parse_variable(parser, block, true, false, NULL))
2242 else if (!strcmp(parser_tokval(parser), "return"))
2244 return parse_return(parser, block, out);
2246 else if (!strcmp(parser_tokval(parser), "if"))
2248 return parse_if(parser, block, out);
2250 else if (!strcmp(parser_tokval(parser), "while"))
2252 return parse_while(parser, block, out);
2254 else if (!strcmp(parser_tokval(parser), "do"))
2256 return parse_dowhile(parser, block, out);
2258 else if (!strcmp(parser_tokval(parser), "for"))
2260 if (opts_standard == COMPILER_QCC) {
2261 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2264 return parse_for(parser, block, out);
2266 else if (!strcmp(parser_tokval(parser), "break"))
2268 return parse_break_continue(parser, block, out, false);
2270 else if (!strcmp(parser_tokval(parser), "continue"))
2272 return parse_break_continue(parser, block, out, true);
2274 else if (!strcmp(parser_tokval(parser), "switch"))
2276 return parse_switch(parser, block, out);
2278 else if (!strcmp(parser_tokval(parser), "case") ||
2279 !strcmp(parser_tokval(parser), "default"))
2282 parseerror(parser, "unexpected 'case' label");
2287 else if (!strcmp(parser_tokval(parser), "typedef"))
2289 if (!parser_next(parser)) {
2290 parseerror(parser, "expected type definition after 'typedef'");
2293 return parse_typedef(parser);
2295 parseerror(parser, "Unexpected keyword");
2298 else if (parser->tok == '{')
2301 inner = parse_block(parser, false);
2304 *out = (ast_expression*)inner;
2309 ast_expression *exp = parse_expression(parser, false);
2313 if (!ast_istype(exp, ast_store) &&
2314 !ast_istype(exp, ast_call) &&
2315 !ast_istype(exp, ast_binstore))
2317 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2324 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2328 parser_enterblock(parser);
2330 if (!parser_next(parser)) { /* skip the '{' */
2331 parseerror(parser, "expected function body");
2335 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2337 ast_expression *expr = NULL;
2338 if (parser->tok == '}')
2341 if (!parse_statement(parser, block, &expr, false)) {
2342 /* parseerror(parser, "parse error"); */
2348 vec_push(block->exprs, expr);
2351 if (parser->tok != '}') {
2354 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2356 if (!vec_size(block->exprs) ||
2357 !ast_istype(vec_last(block->exprs), ast_return))
2359 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2365 (void)parser_next(parser);
2369 if (!parser_leaveblock(parser))
2371 return retval && !!block;
2374 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2377 block = ast_block_new(parser_ctx(parser));
2380 if (!parse_block_into(parser, block, warnreturn)) {
2381 ast_block_delete(block);
2387 static ast_expression* parse_statement_or_block(parser_t *parser)
2389 ast_expression *expr = NULL;
2390 if (parser->tok == '{')
2391 return (ast_expression*)parse_block(parser, false);
2392 if (!parse_statement(parser, NULL, &expr, false))
2397 static bool create_vector_members(ast_value *var, ast_member **me)
2400 size_t len = strlen(var->name);
2402 for (i = 0; i < 3; ++i) {
2403 char *name = mem_a(len+3);
2404 memcpy(name, var->name, len);
2406 name[len+1] = 'x'+i;
2408 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2417 do { ast_member_delete(me[--i]); } while(i);
2421 static bool parse_function_body(parser_t *parser, ast_value *var)
2423 ast_block *block = NULL;
2428 ast_expression *framenum = NULL;
2429 ast_expression *nextthink = NULL;
2430 /* None of the following have to be deleted */
2431 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2432 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2433 bool has_frame_think;
2437 has_frame_think = false;
2438 old = parser->function;
2440 if (var->expression.variadic) {
2441 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2442 "variadic function with implementation will not be able to access additional parameters"))
2448 if (parser->tok == '[') {
2449 /* got a frame definition: [ framenum, nextthink ]
2450 * this translates to:
2451 * self.frame = framenum;
2452 * self.nextthink = time + 0.1;
2453 * self.think = nextthink;
2457 fld_think = parser_find_field(parser, "think");
2458 fld_nextthink = parser_find_field(parser, "nextthink");
2459 fld_frame = parser_find_field(parser, "frame");
2460 if (!fld_think || !fld_nextthink || !fld_frame) {
2461 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2462 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2465 gbl_time = parser_find_global(parser, "time");
2466 gbl_self = parser_find_global(parser, "self");
2467 if (!gbl_time || !gbl_self) {
2468 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2469 parseerror(parser, "please declare the following globals: `time`, `self`");
2473 if (!parser_next(parser))
2476 framenum = parse_expression_leave(parser, true);
2478 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2481 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2482 ast_unref(framenum);
2483 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2487 if (parser->tok != ',') {
2488 ast_unref(framenum);
2489 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2490 parseerror(parser, "Got a %i\n", parser->tok);
2494 if (!parser_next(parser)) {
2495 ast_unref(framenum);
2499 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2501 /* qc allows the use of not-yet-declared functions here
2502 * - this automatically creates a prototype */
2503 ast_value *thinkfunc;
2504 ast_expression *functype = fld_think->expression.next;
2506 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2507 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2508 ast_unref(framenum);
2509 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2513 if (!parser_next(parser)) {
2514 ast_unref(framenum);
2515 ast_delete(thinkfunc);
2519 vec_push(parser->globals, (ast_expression*)thinkfunc);
2520 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2521 nextthink = (ast_expression*)thinkfunc;
2524 nextthink = parse_expression_leave(parser, true);
2526 ast_unref(framenum);
2527 parseerror(parser, "expected a think-function in [frame,think] notation");
2532 if (!ast_istype(nextthink, ast_value)) {
2533 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2537 if (retval && parser->tok != ']') {
2538 parseerror(parser, "expected closing `]` for [frame,think] notation");
2542 if (retval && !parser_next(parser)) {
2546 if (retval && parser->tok != '{') {
2547 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2552 ast_unref(nextthink);
2553 ast_unref(framenum);
2557 has_frame_think = true;
2560 block = ast_block_new(parser_ctx(parser));
2562 parseerror(parser, "failed to allocate block");
2563 if (has_frame_think) {
2564 ast_unref(nextthink);
2565 ast_unref(framenum);
2570 if (has_frame_think) {
2572 ast_expression *self_frame;
2573 ast_expression *self_nextthink;
2574 ast_expression *self_think;
2575 ast_expression *time_plus_1;
2576 ast_store *store_frame;
2577 ast_store *store_nextthink;
2578 ast_store *store_think;
2580 ctx = parser_ctx(parser);
2581 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2582 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2583 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2585 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2586 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2588 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2589 if (self_frame) ast_delete(self_frame);
2590 if (self_nextthink) ast_delete(self_nextthink);
2591 if (self_think) ast_delete(self_think);
2592 if (time_plus_1) ast_delete(time_plus_1);
2598 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2599 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2600 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2603 ast_delete(self_frame);
2606 if (!store_nextthink) {
2607 ast_delete(self_nextthink);
2611 ast_delete(self_think);
2615 if (store_frame) ast_delete(store_frame);
2616 if (store_nextthink) ast_delete(store_nextthink);
2617 if (store_think) ast_delete(store_think);
2620 vec_push(block->exprs, (ast_expression*)store_frame);
2621 vec_push(block->exprs, (ast_expression*)store_nextthink);
2622 vec_push(block->exprs, (ast_expression*)store_think);
2626 parseerror(parser, "failed to generate code for [frame,think]");
2627 ast_unref(nextthink);
2628 ast_unref(framenum);
2634 parser_enterblock(parser);
2636 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2638 ast_value *param = var->expression.params[parami];
2641 if (param->expression.vtype != TYPE_VECTOR &&
2642 (param->expression.vtype != TYPE_FIELD ||
2643 param->expression.next->expression.vtype != TYPE_VECTOR))
2648 if (!create_vector_members(param, me)) {
2649 ast_block_delete(block);
2653 for (e = 0; e < 3; ++e) {
2654 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2655 ast_block_collect(block, (ast_expression*)me[e]);
2659 func = ast_function_new(ast_ctx(var), var->name, var);
2661 parseerror(parser, "failed to allocate function for `%s`", var->name);
2662 ast_block_delete(block);
2665 vec_push(parser->functions, func);
2667 parser->function = func;
2668 if (!parse_block_into(parser, block, true)) {
2669 ast_block_delete(block);
2673 vec_push(func->blocks, block);
2675 parser->function = old;
2676 if (!parser_leaveblock(parser))
2678 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2679 parseerror(parser, "internal error: local scopes left");
2683 if (parser->tok == ';')
2684 return parser_next(parser);
2685 else if (opts_standard == COMPILER_QCC)
2686 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2690 vec_pop(parser->functions);
2691 ast_function_delete(func);
2692 var->constval.vfunc = NULL;
2695 (void)!parser_leaveblock(parser);
2696 parser->function = old;
2700 static ast_expression *array_accessor_split(
2705 ast_expression *left,
2706 ast_expression *right
2712 lex_ctx ctx = ast_ctx(array);
2714 if (!left || !right) {
2715 if (left) ast_delete(left);
2716 if (right) ast_delete(right);
2720 cmp = ast_binary_new(ctx, INSTR_LT,
2721 (ast_expression*)index,
2722 (ast_expression*)parser_const_float(parser, middle));
2726 parseerror(parser, "internal error: failed to create comparison for array setter");
2730 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2732 ast_delete(cmp); /* will delete left and right */
2733 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2737 return (ast_expression*)ifthen;
2740 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2742 lex_ctx ctx = ast_ctx(array);
2744 if (from+1 == afterend) {
2745 /* set this value */
2748 ast_array_index *subscript;
2750 int assignop = type_store_instr[value->expression.vtype];
2752 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2753 assignop = INSTR_STORE_V;
2755 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2759 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2761 ast_delete(subscript);
2765 block = ast_block_new(ctx);
2771 vec_push(block->exprs, (ast_expression*)st);
2773 ret = ast_return_new(ctx, NULL);
2779 vec_push(block->exprs, (ast_expression*)ret);
2781 return (ast_expression*)block;
2783 ast_expression *left, *right;
2784 size_t diff = afterend - from;
2785 size_t middle = from + diff/2;
2786 left = array_setter_node(parser, array, index, value, from, middle);
2787 right = array_setter_node(parser, array, index, value, middle, afterend);
2788 return array_accessor_split(parser, array, index, middle, left, right);
2792 static ast_expression *array_field_setter_node(
2801 lex_ctx ctx = ast_ctx(array);
2803 if (from+1 == afterend) {
2804 /* set this value */
2807 ast_entfield *entfield;
2808 ast_array_index *subscript;
2810 int assignop = type_storep_instr[value->expression.vtype];
2812 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2813 assignop = INSTR_STOREP_V;
2815 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2819 entfield = ast_entfield_new_force(ctx,
2820 (ast_expression*)entity,
2821 (ast_expression*)subscript,
2822 (ast_expression*)subscript);
2824 ast_delete(subscript);
2828 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2830 ast_delete(entfield);
2834 block = ast_block_new(ctx);
2840 vec_push(block->exprs, (ast_expression*)st);
2842 ret = ast_return_new(ctx, NULL);
2848 vec_push(block->exprs, (ast_expression*)ret);
2850 return (ast_expression*)block;
2852 ast_expression *left, *right;
2853 size_t diff = afterend - from;
2854 size_t middle = from + diff/2;
2855 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2856 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2857 return array_accessor_split(parser, array, index, middle, left, right);
2861 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2863 lex_ctx ctx = ast_ctx(array);
2865 if (from+1 == afterend) {
2867 ast_array_index *subscript;
2869 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2873 ret = ast_return_new(ctx, (ast_expression*)subscript);
2875 ast_delete(subscript);
2879 return (ast_expression*)ret;
2881 ast_expression *left, *right;
2882 size_t diff = afterend - from;
2883 size_t middle = from + diff/2;
2884 left = array_getter_node(parser, array, index, from, middle);
2885 right = array_getter_node(parser, array, index, middle, afterend);
2886 return array_accessor_split(parser, array, index, middle, left, right);
2890 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2892 ast_function *func = NULL;
2893 ast_value *fval = NULL;
2894 ast_block *body = NULL;
2896 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2898 parseerror(parser, "failed to create accessor function value");
2902 func = ast_function_new(ast_ctx(array), funcname, fval);
2905 parseerror(parser, "failed to create accessor function node");
2909 body = ast_block_new(ast_ctx(array));
2911 parseerror(parser, "failed to create block for array accessor");
2917 vec_push(func->blocks, body);
2920 vec_push(parser->accessors, fval);
2925 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2927 ast_expression *root = NULL;
2928 ast_value *index = NULL;
2929 ast_value *value = NULL;
2933 if (!ast_istype(array->expression.next, ast_value)) {
2934 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2938 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2940 func = fval->constval.vfunc;
2941 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2943 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2944 value = ast_value_copy((ast_value*)array->expression.next);
2946 if (!index || !value) {
2947 parseerror(parser, "failed to create locals for array accessor");
2950 (void)!ast_value_set_name(value, "value"); /* not important */
2951 vec_push(fval->expression.params, index);
2952 vec_push(fval->expression.params, value);
2954 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2956 parseerror(parser, "failed to build accessor search tree");
2960 vec_push(func->blocks[0]->exprs, root);
2961 array->setter = fval;
2964 if (index) ast_delete(index);
2965 if (value) ast_delete(value);
2966 if (root) ast_delete(root);
2972 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2974 ast_expression *root = NULL;
2975 ast_value *entity = NULL;
2976 ast_value *index = NULL;
2977 ast_value *value = NULL;
2981 if (!ast_istype(array->expression.next, ast_value)) {
2982 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2986 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2988 func = fval->constval.vfunc;
2989 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2991 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2992 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2993 value = ast_value_copy((ast_value*)array->expression.next);
2994 if (!entity || !index || !value) {
2995 parseerror(parser, "failed to create locals for array accessor");
2998 (void)!ast_value_set_name(value, "value"); /* not important */
2999 vec_push(fval->expression.params, entity);
3000 vec_push(fval->expression.params, index);
3001 vec_push(fval->expression.params, value);
3003 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3005 parseerror(parser, "failed to build accessor search tree");
3009 vec_push(func->blocks[0]->exprs, root);
3010 array->setter = fval;
3013 if (entity) ast_delete(entity);
3014 if (index) ast_delete(index);
3015 if (value) ast_delete(value);
3016 if (root) ast_delete(root);
3022 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3024 ast_expression *root = NULL;
3025 ast_value *index = NULL;
3029 /* NOTE: checking array->expression.next rather than elemtype since
3030 * for fields elemtype is a temporary fieldtype.
3032 if (!ast_istype(array->expression.next, ast_value)) {
3033 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3037 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3039 func = fval->constval.vfunc;
3040 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3042 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3045 parseerror(parser, "failed to create locals for array accessor");
3048 vec_push(fval->expression.params, index);
3050 root = array_getter_node(parser, array, index, 0, array->expression.count);
3052 parseerror(parser, "failed to build accessor search tree");
3056 vec_push(func->blocks[0]->exprs, root);
3057 array->getter = fval;
3060 if (index) ast_delete(index);
3061 if (root) ast_delete(root);
3067 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3068 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3076 bool variadic = false;
3078 ctx = parser_ctx(parser);
3080 /* for the sake of less code we parse-in in this function */
3081 if (!parser_next(parser)) {
3082 parseerror(parser, "expected parameter list");
3088 /* parse variables until we hit a closing paren */
3089 while (parser->tok != ')') {
3091 /* there must be commas between them */
3092 if (parser->tok != ',') {
3093 parseerror(parser, "expected comma or end of parameter list");
3096 if (!parser_next(parser)) {
3097 parseerror(parser, "expected parameter");
3103 if (parser->tok == TOKEN_DOTS) {
3104 /* '...' indicates a varargs function */
3106 if (!parser_next(parser)) {
3107 parseerror(parser, "expected parameter");
3110 if (parser->tok != ')') {
3111 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3117 /* for anything else just parse a typename */
3118 param = parse_typename(parser, NULL, NULL);
3121 vec_push(params, param);
3122 if (param->expression.vtype >= TYPE_VARIANT) {
3123 char typename[1024];
3124 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3125 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3132 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3133 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3136 if (!parser_next(parser)) {
3137 parseerror(parser, "parse error after typename");
3141 /* now turn 'var' into a function type */
3142 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3143 fval->expression.next = (ast_expression*)var;
3144 fval->expression.variadic = variadic;
3147 var->expression.params = params;
3154 for (i = 0; i < vec_size(params); ++i)
3155 ast_delete(params[i]);
3160 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3162 ast_expression *cexp;
3163 ast_value *cval, *tmp;
3166 ctx = parser_ctx(parser);
3168 if (!parser_next(parser)) {
3170 parseerror(parser, "expected array-size");
3174 cexp = parse_expression_leave(parser, true);
3176 if (!cexp || !ast_istype(cexp, ast_value)) {
3180 parseerror(parser, "expected array-size as constant positive integer");
3183 cval = (ast_value*)cexp;
3185 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3186 tmp->expression.next = (ast_expression*)var;
3189 if (cval->expression.vtype == TYPE_INTEGER)
3190 tmp->expression.count = cval->constval.vint;
3191 else if (cval->expression.vtype == TYPE_FLOAT)
3192 tmp->expression.count = cval->constval.vfloat;
3196 parseerror(parser, "array-size must be a positive integer constant");
3201 if (parser->tok != ']') {
3203 parseerror(parser, "expected ']' after array-size");
3206 if (!parser_next(parser)) {
3208 parseerror(parser, "error after parsing array size");
3214 /* Parse a complete typename.
3215 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3216 * but when parsing variables separated by comma
3217 * 'storebase' should point to where the base-type should be kept.
3218 * The base type makes up every bit of type information which comes *before* the
3221 * The following will be parsed in its entirety:
3223 * The 'basetype' in this case is 'void()'
3224 * and if there's a comma after it, say:
3226 * then the type-information 'void()' can be stored in 'storebase'
3228 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3230 ast_value *var, *tmp;
3233 const char *name = NULL;
3234 bool isfield = false;
3235 bool wasarray = false;
3236 size_t morefields = 0;
3238 ctx = parser_ctx(parser);
3240 /* types may start with a dot */
3241 if (parser->tok == '.') {
3243 /* if we parsed a dot we need a typename now */
3244 if (!parser_next(parser)) {
3245 parseerror(parser, "expected typename for field definition");
3249 /* Further dots are handled seperately because they won't be part of the
3252 while (parser->tok == '.') {
3254 if (!parser_next(parser)) {
3255 parseerror(parser, "expected typename for field definition");
3260 if (parser->tok == TOKEN_IDENT)
3261 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3262 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3263 parseerror(parser, "expected typename");
3268 /* generate the basic type value */
3269 if (cached_typedef) {
3270 var = ast_value_copy(cached_typedef);
3271 ast_value_set_name(var, "<type(from_def)>");
3273 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3275 for (; morefields; --morefields) {
3276 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3277 tmp->expression.next = (ast_expression*)var;
3281 /* do not yet turn into a field - remember:
3282 * .void() foo; is a field too
3283 * .void()() foo; is a function
3287 if (!parser_next(parser)) {
3289 parseerror(parser, "parse error after typename");
3293 /* an opening paren now starts the parameter-list of a function
3294 * this is where original-QC has parameter lists.
3295 * We allow a single parameter list here.
3296 * Much like fteqcc we don't allow `float()() x`
3298 if (parser->tok == '(') {
3299 var = parse_parameter_list(parser, var);
3304 /* store the base if requested */
3306 *storebase = ast_value_copy(var);
3308 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3309 tmp->expression.next = (ast_expression*)*storebase;
3314 /* there may be a name now */
3315 if (parser->tok == TOKEN_IDENT) {
3316 name = util_strdup(parser_tokval(parser));
3318 if (!parser_next(parser)) {
3320 parseerror(parser, "error after variable or field declaration");
3325 /* now this may be an array */
3326 if (parser->tok == '[') {
3328 var = parse_arraysize(parser, var);
3333 /* This is the point where we can turn it into a field */
3335 /* turn it into a field if desired */
3336 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3337 tmp->expression.next = (ast_expression*)var;
3341 /* now there may be function parens again */
3342 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3343 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3344 if (parser->tok == '(' && wasarray)
3345 parseerror(parser, "arrays as part of a return type is not supported");
3346 while (parser->tok == '(') {
3347 var = parse_parameter_list(parser, var);
3356 /* finally name it */
3358 if (!ast_value_set_name(var, name)) {
3360 parseerror(parser, "internal error: failed to set name");
3363 /* free the name, ast_value_set_name duplicates */
3370 static bool parse_typedef(parser_t *parser)
3372 ast_value *typevar, *oldtype;
3373 ast_expression *old;
3375 typevar = parse_typename(parser, NULL, NULL);
3380 if ( (old = parser_find_var(parser, typevar->name)) ) {
3381 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3382 " -> `%s` has been declared here: %s:%i",
3383 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3384 ast_delete(typevar);
3388 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3389 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3390 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3391 ast_delete(typevar);
3395 vec_push(parser->_typedefs, typevar);
3396 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3398 if (parser->tok != ';') {
3399 parseerror(parser, "expected semicolon after typedef");
3402 if (!parser_next(parser)) {
3403 parseerror(parser, "parse error after typedef");
3410 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef)
3414 ast_expression *old;
3418 ast_value *basetype = NULL;
3420 bool isparam = false;
3421 bool isvector = false;
3422 bool cleanvar = true;
3423 bool wasarray = false;
3427 /* get the first complete variable */
3428 var = parse_typename(parser, &basetype, cached_typedef);
3431 ast_delete(basetype);
3439 /* Part 0: finish the type */
3440 if (parser->tok == '(') {
3441 if (opts_standard == COMPILER_QCC)
3442 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3443 var = parse_parameter_list(parser, var);
3449 /* we only allow 1-dimensional arrays */
3450 if (parser->tok == '[') {
3452 var = parse_arraysize(parser, var);
3458 if (parser->tok == '(' && wasarray) {
3459 parseerror(parser, "arrays as part of a return type is not supported");
3460 /* we'll still parse the type completely for now */
3462 /* for functions returning functions */
3463 while (parser->tok == '(') {
3464 if (opts_standard == COMPILER_QCC)
3465 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3466 var = parse_parameter_list(parser, var);
3474 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3475 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3476 * is then filled with the previous definition and the parameter-names replaced.
3479 /* Deal with end_sys_ vars */
3481 if (!strcmp(var->name, "end_sys_globals")) {
3482 parser->crc_globals = vec_size(parser->globals);
3485 else if (!strcmp(var->name, "end_sys_fields")) {
3486 parser->crc_fields = vec_size(parser->fields);
3489 if (was_end && var->expression.vtype == TYPE_FIELD) {
3490 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3491 "global '%s' hint should not be a field",
3492 parser_tokval(parser)))
3499 if (!nofields && var->expression.vtype == TYPE_FIELD)
3501 /* deal with field declarations */
3502 old = parser_find_field(parser, var->name);
3504 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3505 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3514 parseerror(parser, "field `%s` already declared here: %s:%i",
3515 var->name, ast_ctx(old).file, ast_ctx(old).line);
3520 if (opts_standard == COMPILER_QCC &&
3521 (old = parser_find_global(parser, var->name)))
3523 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3524 parseerror(parser, "field `%s` already declared here: %s:%i",
3525 var->name, ast_ctx(old).file, ast_ctx(old).line);
3532 /* deal with other globals */
3533 old = parser_find_global(parser, var->name);
3534 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3536 /* This is a function which had a prototype */
3537 if (!ast_istype(old, ast_value)) {
3538 parseerror(parser, "internal error: prototype is not an ast_value");
3542 proto = (ast_value*)old;
3543 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3544 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3546 ast_ctx(proto).file, ast_ctx(proto).line);
3550 /* we need the new parameter-names */
3551 for (i = 0; i < vec_size(proto->expression.params); ++i)
3552 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3560 if (opts_standard == COMPILER_GMQCC) {
3561 parseerror(parser, "global `%s` already declared here: %s:%i",
3562 var->name, ast_ctx(old).file, ast_ctx(old).line);
3566 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3567 "global `%s` already declared here: %s:%i",
3568 var->name, ast_ctx(old).file, ast_ctx(old).line))
3575 if (opts_standard == COMPILER_QCC &&
3576 (old = parser_find_field(parser, var->name)))
3578 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3579 parseerror(parser, "global `%s` already declared here: %s:%i",
3580 var->name, ast_ctx(old).file, ast_ctx(old).line);
3587 else /* it's not a global */
3589 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3590 if (old && !isparam) {
3591 parseerror(parser, "local `%s` already declared here: %s:%i",
3592 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3596 old = parser_find_local(parser, var->name, 0, &isparam);
3597 if (old && isparam) {
3598 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3599 "local `%s` is shadowing a parameter", var->name))
3601 parseerror(parser, "local `%s` already declared here: %s:%i",
3602 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3606 if (opts_standard != COMPILER_GMQCC) {
3615 var->isconst = true;
3618 * Create the global/local, and deal with vector types.
3621 if (var->expression.vtype == TYPE_VECTOR)
3623 else if (var->expression.vtype == TYPE_FIELD &&
3624 var->expression.next->expression.vtype == TYPE_VECTOR)
3628 if (!create_vector_members(var, me)) {
3635 /* deal with global variables, fields, functions */
3636 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3637 vec_push(parser->fields, (ast_expression*)var);
3638 util_htset(parser->htfields, var->name, var);
3640 for (i = 0; i < 3; ++i) {
3641 vec_push(parser->fields, (ast_expression*)me[i]);
3642 util_htset(parser->htfields, me[i]->name, me[i]);
3647 vec_push(parser->globals, (ast_expression*)var);
3648 util_htset(parser->htglobals, var->name, var);
3650 for (i = 0; i < 3; ++i) {
3651 vec_push(parser->globals, (ast_expression*)me[i]);
3652 util_htset(parser->htglobals, me[i]->name, me[i]);
3657 vec_push(localblock->locals, var);
3658 parser_addlocal(parser, var->name, (ast_expression*)var);
3660 for (i = 0; i < 3; ++i) {
3661 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3662 ast_block_collect(localblock, (ast_expression*)me[i]);
3668 me[0] = me[1] = me[2] = NULL;
3673 if (var->expression.vtype == TYPE_ARRAY) {
3675 snprintf(name, sizeof(name), "%s##SET", var->name);
3676 if (!parser_create_array_setter(parser, var, name))
3678 snprintf(name, sizeof(name), "%s##GET", var->name);
3679 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3682 else if (!localblock && !nofields &&
3683 var->expression.vtype == TYPE_FIELD &&
3684 var->expression.next->expression.vtype == TYPE_ARRAY)
3687 ast_expression *telem;
3689 ast_value *array = (ast_value*)var->expression.next;
3691 if (!ast_istype(var->expression.next, ast_value)) {
3692 parseerror(parser, "internal error: field element type must be an ast_value");
3696 snprintf(name, sizeof(name), "%s##SETF", var->name);
3697 if (!parser_create_array_field_setter(parser, array, name))
3700 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3701 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3702 tfield->expression.next = telem;
3703 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3704 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3712 if (parser->tok == ';') {
3713 ast_delete(basetype);
3714 if (!parser_next(parser)) {
3715 parseerror(parser, "error after variable declaration");
3721 if (parser->tok == ',')
3724 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3725 parseerror(parser, "missing comma or semicolon while parsing variables");
3729 if (localblock && opts_standard == COMPILER_QCC) {
3730 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3731 "initializing expression turns variable `%s` into a constant in this standard",
3738 if (parser->tok != '{') {
3739 if (parser->tok != '=') {
3740 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
3744 if (!parser_next(parser)) {
3745 parseerror(parser, "error parsing initializer");
3749 else if (opts_standard == COMPILER_QCC) {
3750 parseerror(parser, "expected '=' before function body in this standard");
3753 if (parser->tok == '#') {
3754 ast_function *func = NULL;
3757 parseerror(parser, "cannot declare builtins within functions");
3760 if (var->expression.vtype != TYPE_FUNCTION) {
3761 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3764 if (!parser_next(parser)) {
3765 parseerror(parser, "expected builtin number");
3768 if (parser->tok != TOKEN_INTCONST) {
3769 parseerror(parser, "builtin number must be an integer constant");
3772 if (parser_token(parser)->constval.i <= 0) {
3773 parseerror(parser, "builtin number must be an integer greater than zero");
3778 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3779 "builtin `%s` has already been defined\n"
3780 " -> previous declaration here: %s:%i",
3781 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3785 func = ast_function_new(ast_ctx(var), var->name, var);
3787 parseerror(parser, "failed to allocate function for `%s`", var->name);
3790 vec_push(parser->functions, func);
3792 func->builtin = -parser_token(parser)->constval.i;
3795 if (!parser_next(parser)) {
3796 parseerror(parser, "expected comma or semicolon");
3798 ast_function_delete(func);
3799 var->constval.vfunc = NULL;
3803 else if (parser->tok == '{' || parser->tok == '[')
3806 parseerror(parser, "cannot declare functions within functions");
3810 if (!parse_function_body(parser, var))
3812 ast_delete(basetype);
3815 ast_expression *cexp;
3818 cexp = parse_expression_leave(parser, true);
3823 cval = (ast_value*)cexp;
3824 if (!ast_istype(cval, ast_value) || !cval->isconst)
3825 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3828 var->isconst = true;
3829 if (cval->expression.vtype == TYPE_STRING)
3830 var->constval.vstring = parser_strdup(cval->constval.vstring);
3832 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3836 shunt sy = { NULL, NULL };
3837 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3838 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3839 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3840 if (!parser_sy_pop(parser, &sy))
3843 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3844 parseerror(parser, "internal error: leaked operands");
3845 vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3853 if (parser->tok == ',') {
3854 if (!parser_next(parser)) {
3855 parseerror(parser, "expected another variable");
3859 if (parser->tok != TOKEN_IDENT) {
3860 parseerror(parser, "expected another variable");
3863 var = ast_value_copy(basetype);
3865 ast_value_set_name(var, parser_tokval(parser));
3866 if (!parser_next(parser)) {
3867 parseerror(parser, "error parsing variable declaration");
3873 if (parser->tok != ';') {
3874 parseerror(parser, "missing semicolon after variables");
3878 if (!parser_next(parser)) {
3879 parseerror(parser, "parse error after variable declaration");
3883 ast_delete(basetype);
3887 if (cleanvar && var)
3889 ast_delete(basetype);
3893 ast_delete(basetype);
3894 if (cleanvar && var)
3896 if (me[0]) ast_member_delete(me[0]);
3897 if (me[1]) ast_member_delete(me[1]);
3898 if (me[2]) ast_member_delete(me[2]);
3902 static bool parser_global_statement(parser_t *parser)
3904 ast_value *istype = NULL;
3905 if (parser->tok == TOKEN_IDENT)
3906 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
3908 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3910 return parse_variable(parser, NULL, false, false, istype);
3912 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3914 if (!strcmp(parser_tokval(parser), "var")) {
3915 if (!parser_next(parser)) {
3916 parseerror(parser, "expected variable declaration after 'var'");
3919 return parse_variable(parser, NULL, true, false, NULL);
3922 else if (parser->tok == TOKEN_KEYWORD)
3924 if (!strcmp(parser_tokval(parser), "const")) {
3925 if (!parser_next(parser)) {
3926 parseerror(parser, "expected variable declaration after 'const'");
3929 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
3930 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
3931 if (!parser_next(parser)) {
3932 parseerror(parser, "expected variable declaration after 'const var'");
3936 return parse_variable(parser, NULL, true, true, NULL);
3938 else if (!strcmp(parser_tokval(parser), "typedef")) {
3939 if (!parser_next(parser)) {
3940 parseerror(parser, "expected type definition after 'typedef'");
3943 return parse_typedef(parser);
3945 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3948 else if (parser->tok == '$')
3950 if (!parser_next(parser)) {
3951 parseerror(parser, "parse error");
3957 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3963 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3965 return util_crc16(old, str, strlen(str));
3968 static void progdefs_crc_file(const char *str)
3970 /* write to progdefs.h here */
3974 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3976 old = progdefs_crc_sum(old, str);
3977 progdefs_crc_file(str);
3981 static void generate_checksum(parser_t *parser)
3983 uint16_t crc = 0xFFFF;
3987 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3988 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3990 progdefs_crc_file("\tint\tpad;\n");
3991 progdefs_crc_file("\tint\tofs_return[3];\n");
3992 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3993 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3994 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3995 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3996 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3997 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3998 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3999 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4001 for (i = 0; i < parser->crc_globals; ++i) {
4002 if (!ast_istype(parser->globals[i], ast_value))
4004 value = (ast_value*)(parser->globals[i]);
4005 switch (value->expression.vtype) {
4006 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4007 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4008 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4009 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4011 crc = progdefs_crc_both(crc, "\tint\t");
4014 crc = progdefs_crc_both(crc, value->name);
4015 crc = progdefs_crc_both(crc, ";\n");
4017 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4018 for (i = 0; i < parser->crc_fields; ++i) {
4019 if (!ast_istype(parser->fields[i], ast_value))
4021 value = (ast_value*)(parser->fields[i]);
4022 switch (value->expression.next->expression.vtype) {
4023 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4024 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4025 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4026 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4028 crc = progdefs_crc_both(crc, "\tint\t");
4031 crc = progdefs_crc_both(crc, value->name);
4032 crc = progdefs_crc_both(crc, ";\n");
4034 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4039 static parser_t *parser;
4045 parser = (parser_t*)mem_a(sizeof(parser_t));
4049 memset(parser, 0, sizeof(*parser));
4051 for (i = 0; i < operator_count; ++i) {
4052 if (operators[i].id == opid1('=')) {
4053 parser->assign_op = operators+i;
4057 if (!parser->assign_op) {
4058 printf("internal error: initializing parser: failed to find assign operator\n");
4063 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4064 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4065 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4066 vec_push(parser->_blocktypedefs, 0);
4070 bool parser_compile()
4072 /* initial lexer/parser state */
4073 parser->lex->flags.noops = true;
4075 if (parser_next(parser))
4077 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4079 if (!parser_global_statement(parser)) {
4080 if (parser->tok == TOKEN_EOF)
4081 parseerror(parser, "unexpected eof");
4082 else if (!parser->errors)
4083 parseerror(parser, "there have been errors, bailing out");
4084 lex_close(parser->lex);
4090 parseerror(parser, "parse error");
4091 lex_close(parser->lex);
4096 lex_close(parser->lex);
4099 return !parser->errors;
4102 bool parser_compile_file(const char *filename)
4104 parser->lex = lex_open(filename);
4106 con_err("failed to open file \"%s\"\n", filename);
4109 return parser_compile();
4112 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4114 parser->lex = lex_open_string(str, len, name);
4116 con_err("failed to create lexer for string \"%s\"\n", name);
4119 return parser_compile();
4122 bool parser_compile_string(const char *name, const char *str)
4124 parser->lex = lex_open_string(str, strlen(str), name);
4126 con_err("failed to create lexer for string \"%s\"\n", name);
4129 return parser_compile();
4132 void parser_cleanup()
4135 for (i = 0; i < vec_size(parser->accessors); ++i) {
4136 ast_delete(parser->accessors[i]->constval.vfunc);
4137 parser->accessors[i]->constval.vfunc = NULL;
4138 ast_delete(parser->accessors[i]);
4140 for (i = 0; i < vec_size(parser->functions); ++i) {
4141 ast_delete(parser->functions[i]);
4143 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4144 ast_delete(parser->imm_vector[i]);
4146 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4147 ast_delete(parser->imm_string[i]);
4149 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4150 ast_delete(parser->imm_float[i]);
4152 for (i = 0; i < vec_size(parser->fields); ++i) {
4153 ast_delete(parser->fields[i]);
4155 for (i = 0; i < vec_size(parser->globals); ++i) {
4156 ast_delete(parser->globals[i]);
4158 vec_free(parser->accessors);
4159 vec_free(parser->functions);
4160 vec_free(parser->imm_vector);
4161 vec_free(parser->imm_string);
4162 vec_free(parser->imm_float);
4163 vec_free(parser->globals);
4164 vec_free(parser->fields);
4166 for (i = 0; i < vec_size(parser->variables); ++i)
4167 util_htdel(parser->variables[i]);
4168 vec_free(parser->variables);
4169 vec_free(parser->_blocklocals);
4170 vec_free(parser->_locals);
4172 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4173 ast_delete(parser->_typedefs[i]);
4174 vec_free(parser->_typedefs);
4175 for (i = 0; i < vec_size(parser->typedefs); ++i)
4176 util_htdel(parser->typedefs[i]);
4177 vec_free(parser->typedefs);
4178 vec_free(parser->_blocktypedefs);
4183 bool parser_finish(const char *output)
4189 if (!parser->errors)
4191 ir = ir_builder_new("gmqcc_out");
4193 con_out("failed to allocate builder\n");
4197 for (i = 0; i < vec_size(parser->fields); ++i) {
4200 if (!ast_istype(parser->fields[i], ast_value))
4202 field = (ast_value*)parser->fields[i];
4203 isconst = field->isconst;
4204 field->isconst = false;
4205 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4206 con_out("failed to generate field %s\n", field->name);
4207 ir_builder_delete(ir);
4212 ast_expression *subtype;
4213 field->isconst = true;
4214 subtype = field->expression.next;
4215 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4216 if (subtype->expression.vtype == TYPE_FIELD)
4217 ifld->fieldtype = subtype->expression.next->expression.vtype;
4218 else if (subtype->expression.vtype == TYPE_FUNCTION)
4219 ifld->outtype = subtype->expression.next->expression.vtype;
4220 (void)!ir_value_set_field(field->ir_v, ifld);
4223 for (i = 0; i < vec_size(parser->globals); ++i) {
4225 if (!ast_istype(parser->globals[i], ast_value))
4227 asvalue = (ast_value*)(parser->globals[i]);
4228 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
4229 if (strcmp(asvalue->name, "end_sys_globals") &&
4230 strcmp(asvalue->name, "end_sys_fields"))
4232 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4233 "unused global: `%s`", asvalue->name);
4236 if (!ast_global_codegen(asvalue, ir, false)) {
4237 con_out("failed to generate global %s\n", asvalue->name);
4238 ir_builder_delete(ir);
4242 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4243 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4244 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4245 ir_builder_delete(ir);
4249 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4250 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4251 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4252 ir_builder_delete(ir);
4256 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4257 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4258 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4259 ir_builder_delete(ir);
4263 for (i = 0; i < vec_size(parser->globals); ++i) {
4265 if (!ast_istype(parser->globals[i], ast_value))
4267 asvalue = (ast_value*)(parser->globals[i]);
4268 if (asvalue->setter) {
4269 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4270 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4271 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4273 printf("failed to generate setter for %s\n", asvalue->name);
4274 ir_builder_delete(ir);
4278 if (asvalue->getter) {
4279 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4280 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4281 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4283 printf("failed to generate getter for %s\n", asvalue->name);
4284 ir_builder_delete(ir);
4289 for (i = 0; i < vec_size(parser->fields); ++i) {
4291 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4293 if (!ast_istype((ast_expression*)asvalue, ast_value))
4295 if (asvalue->expression.vtype != TYPE_ARRAY)
4297 if (asvalue->setter) {
4298 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4299 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4300 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4302 printf("failed to generate setter for %s\n", asvalue->name);
4303 ir_builder_delete(ir);
4307 if (asvalue->getter) {
4308 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4309 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4310 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4312 printf("failed to generate getter for %s\n", asvalue->name);
4313 ir_builder_delete(ir);
4318 for (i = 0; i < vec_size(parser->functions); ++i) {
4319 if (!ast_function_codegen(parser->functions[i], ir)) {
4320 con_out("failed to generate function %s\n", parser->functions[i]->name);
4321 ir_builder_delete(ir);
4326 ir_builder_dump(ir, con_out);
4327 for (i = 0; i < vec_size(parser->functions); ++i) {
4328 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4329 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4330 ir_builder_delete(ir);
4337 ir_builder_dump(ir, con_out);
4339 generate_checksum(parser);
4341 if (!ir_builder_generate(ir, output)) {
4342 con_out("*** failed to generate output file\n");
4343 ir_builder_delete(ir);
4348 ir_builder_delete(ir);
4352 con_out("*** there were compile errors\n");