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;
48 /* must be deleted first, they reference immediates and values */
49 ast_value **accessors;
51 ast_value *imm_float_zero;
52 ast_value *imm_float_one;
53 ast_value *imm_vector_zero;
58 ast_function *function;
60 /* A list of hashtables for each scope */
66 /* not to be used directly, we use the hash table */
67 ast_expression **_locals;
69 ast_value **_typedefs;
70 size_t *_blocktypedefs;
74 /* we store the '=' operator info */
75 const oper_info *assign_op;
77 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
78 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
79 * anything else: type error
84 static void parser_enterblock(parser_t *parser);
85 static bool parser_leaveblock(parser_t *parser);
86 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
87 static bool parse_typedef(parser_t *parser);
88 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef);
89 static ast_block* parse_block(parser_t *parser, bool warnreturn);
90 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
91 static ast_expression* parse_statement_or_block(parser_t *parser);
92 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
93 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
94 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
96 static void parseerror(parser_t *parser, const char *fmt, ...)
103 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
107 /* returns true if it counts as an error */
108 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
111 int lvl = LVL_WARNING;
113 if (!OPTS_WARN(warntype))
122 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
128 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
131 int lvl = LVL_WARNING;
133 if (!OPTS_WARN(warntype))
140 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
146 /**********************************************************************
147 * some maths used for constant folding
150 vector vec3_add(vector a, vector b)
159 vector vec3_sub(vector a, vector b)
168 qcfloat vec3_mulvv(vector a, vector b)
170 return (a.x * b.x + a.y * b.y + a.z * b.z);
173 vector vec3_mulvf(vector a, float b)
182 /**********************************************************************
186 bool parser_next(parser_t *parser)
188 /* lex_do kills the previous token */
189 parser->tok = lex_do(parser->lex);
190 if (parser->tok == TOKEN_EOF)
192 if (parser->tok >= TOKEN_ERROR) {
193 parseerror(parser, "lex error");
199 #define parser_tokval(p) ((p)->lex->tok.value)
200 #define parser_token(p) (&((p)->lex->tok))
201 #define parser_ctx(p) ((p)->lex->tok.ctx)
203 static ast_value* parser_const_float(parser_t *parser, double d)
207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
208 const double compare = parser->imm_float[i]->constval.vfloat;
209 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
210 return parser->imm_float[i];
212 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
214 out->constval.vfloat = d;
215 vec_push(parser->imm_float, out);
219 static ast_value* parser_const_float_0(parser_t *parser)
221 if (!parser->imm_float_zero)
222 parser->imm_float_zero = parser_const_float(parser, 0);
223 return parser->imm_float_zero;
226 static ast_value* parser_const_float_1(parser_t *parser)
228 if (!parser->imm_float_one)
229 parser->imm_float_one = parser_const_float(parser, 1);
230 return parser->imm_float_one;
233 static char *parser_strdup(const char *str)
236 /* actually dup empty strings */
237 char *out = mem_a(1);
241 return util_strdup(str);
244 static ast_value* parser_const_string(parser_t *parser, const char *str)
248 for (i = 0; i < vec_size(parser->imm_string); ++i) {
249 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
250 return parser->imm_string[i];
252 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
254 out->constval.vstring = parser_strdup(str);
255 vec_push(parser->imm_string, out);
259 static ast_value* parser_const_vector(parser_t *parser, vector v)
263 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
264 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
265 return parser->imm_vector[i];
267 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
269 out->constval.vvec = v;
270 vec_push(parser->imm_vector, out);
274 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
280 return parser_const_vector(parser, v);
283 static ast_value* parser_const_vector_0(parser_t *parser)
285 if (!parser->imm_vector_zero)
286 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
287 return parser->imm_vector_zero;
290 static ast_expression* parser_find_field(parser_t *parser, const char *name)
292 return util_htget(parser->htfields, name);
295 static ast_expression* parser_find_global(parser_t *parser, const char *name)
297 return util_htget(parser->htglobals, name);
300 static ast_expression* parser_find_param(parser_t *parser, const char *name)
304 if (!parser->function)
306 fun = parser->function->vtype;
307 for (i = 0; i < vec_size(fun->expression.params); ++i) {
308 if (!strcmp(fun->expression.params[i]->name, name))
309 return (ast_expression*)(fun->expression.params[i]);
314 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
319 hash = util_hthash(parser->htglobals, name);
322 for (i = vec_size(parser->variables); i > upto;) {
324 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
328 return parser_find_param(parser, name);
331 static ast_expression* parser_find_var(parser_t *parser, const char *name)
335 v = parser_find_local(parser, name, 0, &dummy);
336 if (!v) v = parser_find_global(parser, name);
340 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
344 hash = util_hthash(parser->typedefs[0], name);
346 for (i = vec_size(parser->typedefs); i > upto;) {
348 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
356 size_t etype; /* 0 = expression, others are operators */
360 ast_block *block; /* for commas and function calls */
369 #define SY_PAREN_EXPR '('
370 #define SY_PAREN_FUNC 'f'
371 #define SY_PAREN_INDEX '['
373 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
384 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
388 e.out = (ast_expression*)v;
395 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
397 e.etype = 1 + (op - operators);
406 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
418 # define DEBUGSHUNTDO(x) x
420 # define DEBUGSHUNTDO(x)
423 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
424 * so we need to rotate it to become ent.(foo[n]).
426 static bool rotate_entfield_array_index_nodes(ast_expression **out)
428 ast_array_index *index;
429 ast_entfield *entfield;
433 ast_expression *entity;
435 lex_ctx ctx = ast_ctx(*out);
437 if (!ast_istype(*out, ast_array_index))
439 index = (ast_array_index*)*out;
441 if (!ast_istype(index->array, ast_entfield))
443 entfield = (ast_entfield*)index->array;
445 if (!ast_istype(entfield->field, ast_value))
447 field = (ast_value*)entfield->field;
450 entity = entfield->entity;
454 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
455 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
456 *out = (ast_expression*)entfield;
461 static bool parser_sy_pop(parser_t *parser, shunt *sy)
465 ast_expression *out = NULL;
466 ast_expression *exprs[3];
467 ast_block *blocks[3];
468 ast_value *asvalue[3];
469 size_t i, assignop, addop, subop;
470 qcint generated_op = 0;
475 if (!vec_size(sy->ops)) {
476 parseerror(parser, "internal error: missing operator");
480 if (vec_last(sy->ops).paren) {
481 parseerror(parser, "unmatched parenthesis");
485 op = &operators[vec_last(sy->ops).etype - 1];
486 ctx = vec_last(sy->ops).ctx;
488 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
490 if (vec_size(sy->out) < op->operands) {
491 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
492 op->op, (int)op->id);
496 vec_shrinkby(sy->ops, 1);
498 vec_shrinkby(sy->out, op->operands);
499 for (i = 0; i < op->operands; ++i) {
500 exprs[i] = sy->out[vec_size(sy->out)+i].out;
501 blocks[i] = sy->out[vec_size(sy->out)+i].block;
502 asvalue[i] = (ast_value*)exprs[i];
505 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
506 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
510 #define NotSameType(T) \
511 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
512 exprs[0]->expression.vtype != T)
513 #define CanConstFold1(A) \
514 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
515 #define CanConstFold(A, B) \
516 (CanConstFold1(A) && CanConstFold1(B))
517 #define ConstV(i) (asvalue[(i)]->constval.vvec)
518 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
519 #define ConstS(i) (asvalue[(i)]->constval.vstring)
523 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
527 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
528 if (exprs[1]->expression.vtype != TYPE_FIELD) {
529 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
532 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
534 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
535 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
539 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
545 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
546 !(exprs[0]->expression.vtype == TYPE_FIELD &&
547 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
549 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
550 parseerror(parser, "cannot index value of type %s", ty1);
553 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
554 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
555 parseerror(parser, "index must be of type float, not %s", ty1);
558 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
559 if (rotate_entfield_array_index_nodes(&out))
561 if (opts_standard != COMPILER_GMQCC) {
562 /* this error doesn't need to make us bail out */
563 (void)!parsewarning(parser, WARN_EXTENSIONS,
564 "accessing array-field members of an entity without parenthesis\n"
565 " -> this is an extension from -std=gmqcc");
572 vec_push(blocks[0]->exprs, exprs[1]);
574 blocks[0] = ast_block_new(ctx);
575 vec_push(blocks[0]->exprs, exprs[0]);
576 vec_push(blocks[0]->exprs, exprs[1]);
578 if (!ast_block_set_type(blocks[0], exprs[1]))
581 vec_push(sy->out, syblock(ctx, blocks[0]));
585 switch (exprs[0]->expression.vtype) {
587 if (CanConstFold1(exprs[0]))
588 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
590 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
591 (ast_expression*)parser_const_float_0(parser),
595 if (CanConstFold1(exprs[0]))
596 out = (ast_expression*)parser_const_vector_f(parser,
597 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
599 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
600 (ast_expression*)parser_const_vector_0(parser),
604 parseerror(parser, "invalid types used in expression: cannot negate type %s",
605 type_name[exprs[0]->expression.vtype]);
611 switch (exprs[0]->expression.vtype) {
613 if (CanConstFold1(exprs[0]))
614 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
616 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
619 if (CanConstFold1(exprs[0]))
620 out = (ast_expression*)parser_const_float(parser,
621 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
623 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
626 if (CanConstFold1(exprs[0]))
627 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
629 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
631 /* we don't constant-fold NOT for these types */
633 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
636 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
639 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
640 type_name[exprs[0]->expression.vtype]);
646 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
647 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
649 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
650 type_name[exprs[0]->expression.vtype],
651 type_name[exprs[1]->expression.vtype]);
654 switch (exprs[0]->expression.vtype) {
656 if (CanConstFold(exprs[0], exprs[1]))
658 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
661 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
664 if (CanConstFold(exprs[0], exprs[1]))
665 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
667 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
670 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
671 type_name[exprs[0]->expression.vtype],
672 type_name[exprs[1]->expression.vtype]);
677 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
678 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
680 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
681 type_name[exprs[1]->expression.vtype],
682 type_name[exprs[0]->expression.vtype]);
685 switch (exprs[0]->expression.vtype) {
687 if (CanConstFold(exprs[0], exprs[1]))
688 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
690 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
693 if (CanConstFold(exprs[0], exprs[1]))
694 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
696 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
699 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
700 type_name[exprs[1]->expression.vtype],
701 type_name[exprs[0]->expression.vtype]);
706 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
707 exprs[0]->expression.vtype != TYPE_VECTOR &&
708 exprs[0]->expression.vtype != TYPE_FLOAT &&
709 exprs[1]->expression.vtype != TYPE_VECTOR &&
710 exprs[1]->expression.vtype != TYPE_FLOAT)
712 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
713 type_name[exprs[1]->expression.vtype],
714 type_name[exprs[0]->expression.vtype]);
717 switch (exprs[0]->expression.vtype) {
719 if (exprs[1]->expression.vtype == TYPE_VECTOR)
721 if (CanConstFold(exprs[0], exprs[1]))
722 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
728 if (CanConstFold(exprs[0], exprs[1]))
729 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
731 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
735 if (exprs[1]->expression.vtype == TYPE_FLOAT)
737 if (CanConstFold(exprs[0], exprs[1]))
738 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
740 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
744 if (CanConstFold(exprs[0], exprs[1]))
745 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
747 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
751 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
752 type_name[exprs[1]->expression.vtype],
753 type_name[exprs[0]->expression.vtype]);
758 if (NotSameType(TYPE_FLOAT)) {
759 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
760 type_name[exprs[0]->expression.vtype],
761 type_name[exprs[1]->expression.vtype]);
764 if (CanConstFold(exprs[0], exprs[1]))
765 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
767 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
771 parseerror(parser, "qc does not have a modulo operator");
775 if (NotSameType(TYPE_FLOAT)) {
776 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
777 type_name[exprs[0]->expression.vtype],
778 type_name[exprs[1]->expression.vtype]);
781 if (CanConstFold(exprs[0], exprs[1]))
782 out = (ast_expression*)parser_const_float(parser,
783 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
784 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
786 out = (ast_expression*)ast_binary_new(ctx,
787 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
791 parseerror(parser, "TODO: bitxor");
796 case opid3('<','<','='):
797 case opid3('>','>','='):
798 parseerror(parser, "TODO: shifts");
802 generated_op += 1; /* INSTR_OR */
804 generated_op += INSTR_AND;
805 if (NotSameType(TYPE_FLOAT)) {
806 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
807 type_name[exprs[0]->expression.vtype],
808 type_name[exprs[1]->expression.vtype]);
809 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
810 parseerror(parser, "TODO: optional early out");
813 if (opts_standard == COMPILER_GMQCC)
814 con_out("TODO: early out logic\n");
815 if (CanConstFold(exprs[0], exprs[1]))
816 out = (ast_expression*)parser_const_float(parser,
817 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
819 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
823 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
824 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
825 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
826 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
829 if (CanConstFold1(exprs[0]))
830 out = (ConstF(0) ? exprs[1] : exprs[2]);
832 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
836 generated_op += 1; /* INSTR_GT */
838 generated_op += 1; /* INSTR_LT */
839 case opid2('>', '='):
840 generated_op += 1; /* INSTR_GE */
841 case opid2('<', '='):
842 generated_op += INSTR_LE;
843 if (NotSameType(TYPE_FLOAT)) {
844 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
845 type_name[exprs[0]->expression.vtype],
846 type_name[exprs[1]->expression.vtype]);
849 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
851 case opid2('!', '='):
852 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
853 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
854 type_name[exprs[0]->expression.vtype],
855 type_name[exprs[1]->expression.vtype]);
858 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
860 case opid2('=', '='):
861 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
862 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
863 type_name[exprs[0]->expression.vtype],
864 type_name[exprs[1]->expression.vtype]);
867 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
871 if (ast_istype(exprs[0], ast_entfield)) {
872 ast_expression *field = ((ast_entfield*)exprs[0])->field;
873 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
874 exprs[0]->expression.vtype == TYPE_FIELD &&
875 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
877 assignop = type_storep_instr[TYPE_VECTOR];
880 assignop = type_storep_instr[exprs[0]->expression.vtype];
881 if (!ast_compare_type(field->expression.next, exprs[1])) {
882 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
883 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
884 if (opts_standard == COMPILER_QCC &&
885 field->expression.next->expression.vtype == TYPE_FUNCTION &&
886 exprs[1]->expression.vtype == TYPE_FUNCTION)
888 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
889 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
895 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
900 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
901 exprs[0]->expression.vtype == TYPE_FIELD &&
902 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
904 assignop = type_store_instr[TYPE_VECTOR];
907 assignop = type_store_instr[exprs[0]->expression.vtype];
910 if (assignop == AINSTR_END) {
911 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
912 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
913 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
915 else if (!ast_compare_type(exprs[0], exprs[1])) {
916 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
917 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
918 if (opts_standard == COMPILER_QCC &&
919 exprs[0]->expression.vtype == TYPE_FUNCTION &&
920 exprs[1]->expression.vtype == TYPE_FUNCTION)
922 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
923 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
929 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
932 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
934 case opid3('+','+','P'):
935 case opid3('-','-','P'):
937 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
938 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
939 parseerror(parser, "invalid type for prefix increment: %s", ty1);
942 if (op->id == opid3('+','+','P'))
946 if (ast_istype(exprs[0], ast_entfield)) {
947 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
949 (ast_expression*)parser_const_float_1(parser));
951 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
953 (ast_expression*)parser_const_float_1(parser));
956 case opid3('S','+','+'):
957 case opid3('S','-','-'):
959 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
960 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
961 parseerror(parser, "invalid type for suffix increment: %s", ty1);
964 if (op->id == opid3('S','+','+')) {
971 if (ast_istype(exprs[0], ast_entfield)) {
972 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
974 (ast_expression*)parser_const_float_1(parser));
976 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
978 (ast_expression*)parser_const_float_1(parser));
982 out = (ast_expression*)ast_binary_new(ctx, subop,
984 (ast_expression*)parser_const_float_1(parser));
988 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
989 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
991 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
992 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
993 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
997 if (ast_istype(exprs[0], ast_entfield))
998 assignop = type_storep_instr[exprs[0]->expression.vtype];
1000 assignop = type_store_instr[exprs[0]->expression.vtype];
1001 switch (exprs[0]->expression.vtype) {
1003 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1004 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1005 exprs[0], exprs[1]);
1008 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1009 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1010 exprs[0], exprs[1]);
1013 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1014 type_name[exprs[0]->expression.vtype],
1015 type_name[exprs[1]->expression.vtype]);
1019 case opid2('*','='):
1020 case opid2('/','='):
1021 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1022 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1023 exprs[0]->expression.vtype == TYPE_VECTOR))
1025 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1026 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1027 parseerror(parser, "invalid types used in expression: %s and %s",
1031 if (ast_istype(exprs[0], ast_entfield))
1032 assignop = type_storep_instr[exprs[0]->expression.vtype];
1034 assignop = type_store_instr[exprs[0]->expression.vtype];
1035 switch (exprs[0]->expression.vtype) {
1037 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1038 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1039 exprs[0], exprs[1]);
1042 if (op->id == opid2('*','=')) {
1043 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1044 exprs[0], exprs[1]);
1046 /* there's no DIV_VF */
1047 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1048 (ast_expression*)parser_const_float_1(parser),
1052 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1057 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1058 type_name[exprs[0]->expression.vtype],
1059 type_name[exprs[1]->expression.vtype]);
1063 case opid2('&','='):
1064 case opid2('|','='):
1065 if (NotSameType(TYPE_FLOAT)) {
1066 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1067 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1068 parseerror(parser, "invalid types used in expression: %s and %s",
1072 if (ast_istype(exprs[0], ast_entfield))
1073 assignop = type_storep_instr[exprs[0]->expression.vtype];
1075 assignop = type_store_instr[exprs[0]->expression.vtype];
1076 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1077 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1078 exprs[0], exprs[1]);
1080 case opid3('&','~','='):
1081 /* This is like: a &= ~(b);
1082 * But QC has no bitwise-not, so we implement it as
1085 if (NotSameType(TYPE_FLOAT)) {
1086 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1087 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1088 parseerror(parser, "invalid types used in expression: %s and %s",
1092 if (ast_istype(exprs[0], ast_entfield))
1093 assignop = type_storep_instr[exprs[0]->expression.vtype];
1095 assignop = type_store_instr[exprs[0]->expression.vtype];
1096 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1099 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1105 parseerror(parser, "failed to apply operand %s", op->op);
1109 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1110 vec_push(sy->out, syexp(ctx, out));
1114 static bool parser_close_call(parser_t *parser, shunt *sy)
1116 /* was a function call */
1117 ast_expression *fun;
1123 vec_shrinkby(sy->ops, 1);
1124 fid = sy->ops[vec_size(sy->ops)].off;
1126 /* out[fid] is the function
1127 * everything above is parameters...
1128 * 0 params = nothing
1129 * 1 params = ast_expression
1133 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1134 parseerror(parser, "internal error: function call needs function and parameter list...");
1138 fun = sy->out[fid].out;
1140 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1142 parseerror(parser, "out of memory");
1146 if (fid+1 == vec_size(sy->out)) {
1149 } else if (fid+2 == vec_size(sy->out)) {
1151 vec_shrinkby(sy->out, 1);
1152 params = sy->out[vec_size(sy->out)].block;
1156 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1158 paramcount = vec_size(params->exprs);
1159 call->params = params->exprs;
1160 params->exprs = NULL;
1163 if (!ast_call_check_types(call))
1166 parseerror(parser, "invalid function call");
1170 /* overwrite fid, the function, with a call */
1171 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1173 if (fun->expression.vtype != TYPE_FUNCTION) {
1174 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1178 if (!fun->expression.next) {
1179 parseerror(parser, "could not determine function return type");
1182 if (vec_size(fun->expression.params) != paramcount &&
1183 !(fun->expression.variadic &&
1184 vec_size(fun->expression.params) < paramcount))
1187 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1189 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1190 if (opts_standard == COMPILER_GMQCC)
1193 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1194 " -> `%s` has been declared here: %s:%i",
1195 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1196 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1198 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1199 " -> `%s` has been declared here: %s:%i",
1200 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1201 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1207 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1208 "too %s parameters for call to %s: expected %i, got %i\n"
1209 " -> `%s` has been declared here: %s:%i",
1210 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1211 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1213 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1214 "too %s parameters for function call: 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);
1225 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1227 if (!vec_size(sy->ops)) {
1228 parseerror(parser, "unmatched closing paren");
1231 /* this would for bit a + (x) because there are no operators inside (x)
1232 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1233 parseerror(parser, "empty parenthesis expression");
1237 while (vec_size(sy->ops)) {
1238 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1239 if (!parser_close_call(parser, sy))
1243 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1244 vec_shrinkby(sy->ops, 1);
1245 return !functions_only;
1247 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1250 /* pop off the parenthesis */
1251 vec_shrinkby(sy->ops, 1);
1252 /* then apply the index operator */
1253 if (!parser_sy_pop(parser, sy))
1257 if (!parser_sy_pop(parser, sy))
1263 static void parser_reclassify_token(parser_t *parser)
1266 for (i = 0; i < operator_count; ++i) {
1267 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1268 parser->tok = TOKEN_OPERATOR;
1274 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1276 ast_expression *expr = NULL;
1278 bool wantop = false;
1279 bool gotmemberof = false;
1281 /* count the parens because an if starts with one, so the
1282 * end of a condition is an unmatched closing paren
1290 parser->lex->flags.noops = false;
1292 parser_reclassify_token(parser);
1297 gotmemberof = false;
1299 parser->memberof = 0;
1301 if (parser->tok == TOKEN_IDENT)
1303 ast_expression *var;
1305 parseerror(parser, "expected operator or end of statement");
1310 if (opts_standard == COMPILER_GMQCC)
1312 if (parser->memberof == TYPE_ENTITY) {
1313 /* still get vars first since there could be a fieldpointer */
1314 var = parser_find_var(parser, parser_tokval(parser));
1316 var = parser_find_field(parser, parser_tokval(parser));
1318 else if (parser->memberof == TYPE_VECTOR)
1320 parseerror(parser, "TODO: implement effective vector member access");
1323 else if (parser->memberof) {
1324 parseerror(parser, "namespace for member not found");
1328 var = parser_find_var(parser, parser_tokval(parser));
1330 var = parser_find_var(parser, parser_tokval(parser));
1332 var = parser_find_field(parser, parser_tokval(parser));
1335 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1338 if (ast_istype(var, ast_value))
1339 ((ast_value*)var)->uses++;
1340 vec_push(sy.out, syexp(parser_ctx(parser), var));
1341 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1343 else if (parser->tok == TOKEN_FLOATCONST) {
1346 parseerror(parser, "expected operator or end of statement, got constant");
1350 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1353 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1354 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1356 else if (parser->tok == TOKEN_INTCONST) {
1359 parseerror(parser, "expected operator or end of statement, got constant");
1363 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1366 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1367 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1369 else if (parser->tok == TOKEN_STRINGCONST) {
1372 parseerror(parser, "expected operator or end of statement, got constant");
1376 val = parser_const_string(parser, parser_tokval(parser));
1379 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1380 DEBUGSHUNTDO(con_out("push string\n"));
1382 else if (parser->tok == TOKEN_VECTORCONST) {
1385 parseerror(parser, "expected operator or end of statement, got constant");
1389 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1392 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1393 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1394 parser_token(parser)->constval.v.x,
1395 parser_token(parser)->constval.v.y,
1396 parser_token(parser)->constval.v.z));
1398 else if (parser->tok == '(') {
1399 parseerror(parser, "internal error: '(' should be classified as operator");
1402 else if (parser->tok == '[') {
1403 parseerror(parser, "internal error: '[' should be classified as operator");
1406 else if (parser->tok == ')') {
1408 DEBUGSHUNTDO(con_out("do[op] )\n"));
1412 /* we do expect an operator next */
1413 /* closing an opening paren */
1414 if (!parser_close_paren(parser, &sy, false))
1417 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1421 /* allowed for function calls */
1422 if (!parser_close_paren(parser, &sy, true))
1427 else if (parser->tok == ']') {
1429 parseerror(parser, "operand expected");
1433 if (!parser_close_paren(parser, &sy, false))
1437 else if (parser->tok != TOKEN_OPERATOR) {
1439 parseerror(parser, "expected operator or end of statement");
1446 /* classify the operator */
1447 const oper_info *op;
1448 const oper_info *olast = NULL;
1450 for (o = 0; o < operator_count; ++o) {
1451 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1452 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1453 !strcmp(parser_tokval(parser), operators[o].op))
1458 if (o == operator_count) {
1459 /* no operator found... must be the end of the statement */
1462 /* found an operator */
1465 /* when declaring variables, a comma starts a new variable */
1466 if (op->id == opid1(',') && !parens && stopatcomma) {
1467 /* fixup the token */
1472 /* a colon without a pervious question mark cannot be a ternary */
1473 if (!ternaries && op->id == opid2(':','?')) {
1478 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1479 olast = &operators[vec_last(sy.ops).etype-1];
1482 (op->prec < olast->prec) ||
1483 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1485 if (!parser_sy_pop(parser, &sy))
1487 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1488 olast = &operators[vec_last(sy.ops).etype-1];
1493 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1494 /* for gmqcc standard: open up the namespace of the previous type */
1495 ast_expression *prevex = vec_last(sy.out).out;
1497 parseerror(parser, "unexpected member operator");
1500 if (prevex->expression.vtype == TYPE_ENTITY)
1501 parser->memberof = TYPE_ENTITY;
1502 else if (prevex->expression.vtype == TYPE_VECTOR)
1503 parser->memberof = TYPE_VECTOR;
1505 parseerror(parser, "type error: type has no members");
1511 if (op->id == opid1('(')) {
1513 size_t sycount = vec_size(sy.out);
1514 DEBUGSHUNTDO(con_out("push [op] (\n"));
1516 /* we expected an operator, this is the function-call operator */
1517 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1520 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1521 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1524 } else if (op->id == opid1('[')) {
1526 parseerror(parser, "unexpected array subscript");
1530 /* push both the operator and the paren, this makes life easier */
1531 vec_push(sy.ops, syop(parser_ctx(parser), op));
1532 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1534 } else if (op->id == opid2('?',':')) {
1536 vec_push(sy.ops, syop(parser_ctx(parser), op));
1539 } else if (op->id == opid2(':','?')) {
1540 /* we don't push this operator */
1544 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1545 vec_push(sy.ops, syop(parser_ctx(parser), op));
1546 wantop = !!(op->flags & OP_SUFFIX);
1549 if (!parser_next(parser)) {
1552 if (parser->tok == ';' ||
1553 (!parens && parser->tok == ']'))
1559 while (vec_size(sy.ops)) {
1560 if (!parser_sy_pop(parser, &sy))
1564 parser->lex->flags.noops = true;
1565 if (!vec_size(sy.out)) {
1566 parseerror(parser, "empty expression");
1569 expr = sy.out[0].out;
1572 DEBUGSHUNTDO(con_out("shunt done\n"));
1576 parser->lex->flags.noops = true;
1582 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1584 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1587 if (!parser_next(parser)) {
1594 static void parser_enterblock(parser_t *parser)
1596 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1597 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1598 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1599 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1602 static bool parser_leaveblock(parser_t *parser)
1605 size_t locals, typedefs;
1607 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1608 parseerror(parser, "internal error: parser_leaveblock with no block");
1612 util_htdel(vec_last(parser->variables));
1613 vec_pop(parser->variables);
1614 if (!vec_size(parser->_blocklocals)) {
1615 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1619 locals = vec_last(parser->_blocklocals);
1620 vec_pop(parser->_blocklocals);
1621 while (vec_size(parser->_locals) != locals) {
1622 ast_expression *e = vec_last(parser->_locals);
1623 ast_value *v = (ast_value*)e;
1624 vec_pop(parser->_locals);
1625 if (ast_istype(e, ast_value) && !v->uses) {
1626 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1631 typedefs = vec_last(parser->_blocktypedefs);
1632 while (vec_size(parser->_typedefs) != typedefs) {
1633 ast_delete(vec_last(parser->_typedefs));
1634 vec_pop(parser->_typedefs);
1636 util_htdel(vec_last(parser->typedefs));
1637 vec_pop(parser->typedefs);
1642 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1644 vec_push(parser->_locals, e);
1645 util_htset(vec_last(parser->variables), name, (void*)e);
1648 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1651 ast_expression *cond, *ontrue, *onfalse = NULL;
1654 lex_ctx ctx = parser_ctx(parser);
1656 (void)block; /* not touching */
1658 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1659 if (!parser_next(parser)) {
1660 parseerror(parser, "expected condition or 'not'");
1663 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1665 if (!parser_next(parser)) {
1666 parseerror(parser, "expected condition in parenthesis");
1670 if (parser->tok != '(') {
1671 parseerror(parser, "expected 'if' condition in parenthesis");
1674 /* parse into the expression */
1675 if (!parser_next(parser)) {
1676 parseerror(parser, "expected 'if' condition after opening paren");
1679 /* parse the condition */
1680 cond = parse_expression_leave(parser, false);
1684 if (parser->tok != ')') {
1685 parseerror(parser, "expected closing paren after 'if' condition");
1689 /* parse into the 'then' branch */
1690 if (!parser_next(parser)) {
1691 parseerror(parser, "expected statement for on-true branch of 'if'");
1695 ontrue = parse_statement_or_block(parser);
1700 /* check for an else */
1701 if (!strcmp(parser_tokval(parser), "else")) {
1702 /* parse into the 'else' branch */
1703 if (!parser_next(parser)) {
1704 parseerror(parser, "expected on-false branch after 'else'");
1709 onfalse = parse_statement_or_block(parser);
1718 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1720 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1721 *out = (ast_expression*)ifthen;
1725 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1728 ast_expression *cond, *ontrue;
1730 lex_ctx ctx = parser_ctx(parser);
1732 (void)block; /* not touching */
1734 /* skip the 'while' and check for opening paren */
1735 if (!parser_next(parser) || parser->tok != '(') {
1736 parseerror(parser, "expected 'while' condition in parenthesis");
1739 /* parse into the expression */
1740 if (!parser_next(parser)) {
1741 parseerror(parser, "expected 'while' condition after opening paren");
1744 /* parse the condition */
1745 cond = parse_expression_leave(parser, false);
1749 if (parser->tok != ')') {
1750 parseerror(parser, "expected closing paren after 'while' condition");
1754 /* parse into the 'then' branch */
1755 if (!parser_next(parser)) {
1756 parseerror(parser, "expected while-loop body");
1760 ontrue = parse_statement_or_block(parser);
1766 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1767 *out = (ast_expression*)aloop;
1771 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1774 ast_expression *cond, *ontrue;
1776 lex_ctx ctx = parser_ctx(parser);
1778 (void)block; /* not touching */
1780 /* skip the 'do' and get the body */
1781 if (!parser_next(parser)) {
1782 parseerror(parser, "expected loop body");
1785 ontrue = parse_statement_or_block(parser);
1789 /* expect the "while" */
1790 if (parser->tok != TOKEN_KEYWORD ||
1791 strcmp(parser_tokval(parser), "while"))
1793 parseerror(parser, "expected 'while' and condition");
1798 /* skip the 'while' and check for opening paren */
1799 if (!parser_next(parser) || parser->tok != '(') {
1800 parseerror(parser, "expected 'while' condition in parenthesis");
1804 /* parse into the expression */
1805 if (!parser_next(parser)) {
1806 parseerror(parser, "expected 'while' condition after opening paren");
1810 /* parse the condition */
1811 cond = parse_expression_leave(parser, false);
1815 if (parser->tok != ')') {
1816 parseerror(parser, "expected closing paren after 'while' condition");
1822 if (!parser_next(parser) || parser->tok != ';') {
1823 parseerror(parser, "expected semicolon after condition");
1829 if (!parser_next(parser)) {
1830 parseerror(parser, "parse error");
1836 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1837 *out = (ast_expression*)aloop;
1841 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1844 ast_expression *initexpr, *cond, *increment, *ontrue;
1848 lex_ctx ctx = parser_ctx(parser);
1850 parser_enterblock(parser);
1857 /* skip the 'while' and check for opening paren */
1858 if (!parser_next(parser) || parser->tok != '(') {
1859 parseerror(parser, "expected 'for' expressions in parenthesis");
1862 /* parse into the expression */
1863 if (!parser_next(parser)) {
1864 parseerror(parser, "expected 'for' initializer after opening paren");
1869 if (parser->tok == TOKEN_IDENT)
1870 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
1872 if (typevar || parser->tok == TOKEN_TYPENAME) {
1873 if (opts_standard != COMPILER_GMQCC) {
1874 if (parsewarning(parser, WARN_EXTENSIONS,
1875 "current standard does not allow variable declarations in for-loop initializers"))
1879 parseerror(parser, "TODO: assignment of new variables to be non-const");
1881 if (!parse_variable(parser, block, true, false, typevar))
1884 else if (parser->tok != ';')
1886 initexpr = parse_expression_leave(parser, false);
1891 /* move on to condition */
1892 if (parser->tok != ';') {
1893 parseerror(parser, "expected semicolon after for-loop initializer");
1896 if (!parser_next(parser)) {
1897 parseerror(parser, "expected for-loop condition");
1901 /* parse the condition */
1902 if (parser->tok != ';') {
1903 cond = parse_expression_leave(parser, false);
1908 /* move on to incrementor */
1909 if (parser->tok != ';') {
1910 parseerror(parser, "expected semicolon after for-loop initializer");
1913 if (!parser_next(parser)) {
1914 parseerror(parser, "expected for-loop condition");
1918 /* parse the incrementor */
1919 if (parser->tok != ')') {
1920 increment = parse_expression_leave(parser, false);
1923 if (!ast_istype(increment, ast_store) &&
1924 !ast_istype(increment, ast_call) &&
1925 !ast_istype(increment, ast_binstore))
1927 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1933 if (parser->tok != ')') {
1934 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1937 /* parse into the 'then' branch */
1938 if (!parser_next(parser)) {
1939 parseerror(parser, "expected for-loop body");
1942 ontrue = parse_statement_or_block(parser);
1947 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1948 *out = (ast_expression*)aloop;
1950 if (!parser_leaveblock(parser))
1954 if (initexpr) ast_delete(initexpr);
1955 if (cond) ast_delete(cond);
1956 if (increment) ast_delete(increment);
1957 (void)!parser_leaveblock(parser);
1961 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1963 ast_expression *exp = NULL;
1964 ast_return *ret = NULL;
1965 ast_value *expected = parser->function->vtype;
1967 (void)block; /* not touching */
1969 if (!parser_next(parser)) {
1970 parseerror(parser, "expected return expression");
1974 if (parser->tok != ';') {
1975 exp = parse_expression(parser, false);
1979 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1980 parseerror(parser, "return with invalid expression");
1983 ret = ast_return_new(exp->expression.node.context, exp);
1989 if (!parser_next(parser))
1990 parseerror(parser, "parse error");
1991 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1992 if (opts_standard != COMPILER_GMQCC)
1993 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1995 parseerror(parser, "return without value");
1997 ret = ast_return_new(parser_ctx(parser), NULL);
1999 *out = (ast_expression*)ret;
2003 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2005 lex_ctx ctx = parser_ctx(parser);
2007 (void)block; /* not touching */
2009 if (!parser_next(parser) || parser->tok != ';') {
2010 parseerror(parser, "expected semicolon");
2014 if (!parser_next(parser))
2015 parseerror(parser, "parse error");
2017 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2021 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2023 ast_expression *operand;
2025 ast_switch *switchnode;
2026 ast_switch_case swcase;
2028 lex_ctx ctx = parser_ctx(parser);
2030 (void)block; /* not touching */
2032 /* parse over the opening paren */
2033 if (!parser_next(parser) || parser->tok != '(') {
2034 parseerror(parser, "expected switch operand in parenthesis");
2038 /* parse into the expression */
2039 if (!parser_next(parser)) {
2040 parseerror(parser, "expected switch operand");
2043 /* parse the operand */
2044 operand = parse_expression_leave(parser, false);
2048 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2049 opval = (ast_value*)operand;
2050 if (!ast_istype(operand, ast_value) || !opval->isconst) {
2051 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2057 switchnode = ast_switch_new(ctx, operand);
2060 if (parser->tok != ')') {
2061 ast_delete(switchnode);
2062 parseerror(parser, "expected closing paren after 'switch' operand");
2066 /* parse over the opening paren */
2067 if (!parser_next(parser) || parser->tok != '{') {
2068 ast_delete(switchnode);
2069 parseerror(parser, "expected list of cases");
2073 if (!parser_next(parser)) {
2074 ast_delete(switchnode);
2075 parseerror(parser, "expected 'case' or 'default'");
2080 while (parser->tok != '}') {
2081 ast_block *caseblock;
2083 if (parser->tok != TOKEN_KEYWORD) {
2084 ast_delete(switchnode);
2085 parseerror(parser, "expected 'case' or 'default'");
2088 if (!strcmp(parser_tokval(parser), "case")) {
2089 if (!parser_next(parser)) {
2090 ast_delete(switchnode);
2091 parseerror(parser, "expected expression for case");
2094 swcase.value = parse_expression_leave(parser, false);
2095 if (!swcase.value) {
2096 ast_delete(switchnode);
2097 parseerror(parser, "expected expression for case");
2101 else if (!strcmp(parser_tokval(parser), "default")) {
2102 swcase.value = NULL;
2103 if (!parser_next(parser)) {
2104 ast_delete(switchnode);
2105 parseerror(parser, "expected colon");
2110 /* Now the colon and body */
2111 if (parser->tok != ':') {
2112 if (swcase.value) ast_unref(swcase.value);
2113 ast_delete(switchnode);
2114 parseerror(parser, "expected colon");
2118 if (!parser_next(parser)) {
2119 if (swcase.value) ast_unref(swcase.value);
2120 ast_delete(switchnode);
2121 parseerror(parser, "expected statements or case");
2124 caseblock = ast_block_new(parser_ctx(parser));
2126 if (swcase.value) ast_unref(swcase.value);
2127 ast_delete(switchnode);
2130 swcase.code = (ast_expression*)caseblock;
2131 vec_push(switchnode->cases, swcase);
2133 ast_expression *expr;
2134 if (parser->tok == '}')
2136 if (parser->tok == TOKEN_KEYWORD) {
2137 if (!strcmp(parser_tokval(parser), "case") ||
2138 !strcmp(parser_tokval(parser), "default"))
2143 if (!parse_statement(parser, caseblock, &expr, true)) {
2144 ast_delete(switchnode);
2149 vec_push(caseblock->exprs, expr);
2154 if (parser->tok != '}') {
2155 ast_delete(switchnode);
2156 parseerror(parser, "expected closing paren of case list");
2159 if (!parser_next(parser)) {
2160 ast_delete(switchnode);
2161 parseerror(parser, "parse error after switch");
2164 *out = (ast_expression*)switchnode;
2168 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2170 ast_value *typevar = NULL;
2171 if (parser->tok == TOKEN_IDENT)
2172 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2174 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2176 /* local variable */
2178 parseerror(parser, "cannot declare a variable from here");
2181 if (opts_standard == COMPILER_QCC) {
2182 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2185 if (!parse_variable(parser, block, false, false, typevar))
2190 else if (parser->tok == TOKEN_KEYWORD)
2192 if (!strcmp(parser_tokval(parser), "local"))
2195 parseerror(parser, "cannot declare a local variable here");
2198 if (!parser_next(parser)) {
2199 parseerror(parser, "expected variable declaration");
2202 if (!parse_variable(parser, block, true, false, NULL))
2207 else if (!strcmp(parser_tokval(parser), "return"))
2209 return parse_return(parser, block, out);
2211 else if (!strcmp(parser_tokval(parser), "if"))
2213 return parse_if(parser, block, out);
2215 else if (!strcmp(parser_tokval(parser), "while"))
2217 return parse_while(parser, block, out);
2219 else if (!strcmp(parser_tokval(parser), "do"))
2221 return parse_dowhile(parser, block, out);
2223 else if (!strcmp(parser_tokval(parser), "for"))
2225 if (opts_standard == COMPILER_QCC) {
2226 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2229 return parse_for(parser, block, out);
2231 else if (!strcmp(parser_tokval(parser), "break"))
2233 return parse_break_continue(parser, block, out, false);
2235 else if (!strcmp(parser_tokval(parser), "continue"))
2237 return parse_break_continue(parser, block, out, true);
2239 else if (!strcmp(parser_tokval(parser), "switch"))
2241 return parse_switch(parser, block, out);
2243 else if (!strcmp(parser_tokval(parser), "case") ||
2244 !strcmp(parser_tokval(parser), "default"))
2247 parseerror(parser, "unexpected 'case' label");
2252 else if (!strcmp(parser_tokval(parser), "typedef"))
2254 if (!parser_next(parser)) {
2255 parseerror(parser, "expected type definition after 'typedef'");
2258 return parse_typedef(parser);
2260 parseerror(parser, "Unexpected keyword");
2263 else if (parser->tok == '{')
2266 inner = parse_block(parser, false);
2269 *out = (ast_expression*)inner;
2274 ast_expression *exp = parse_expression(parser, false);
2278 if (!ast_istype(exp, ast_store) &&
2279 !ast_istype(exp, ast_call) &&
2280 !ast_istype(exp, ast_binstore))
2282 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2289 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2293 parser_enterblock(parser);
2295 if (!parser_next(parser)) { /* skip the '{' */
2296 parseerror(parser, "expected function body");
2300 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2302 ast_expression *expr = NULL;
2303 if (parser->tok == '}')
2306 if (!parse_statement(parser, block, &expr, false)) {
2307 /* parseerror(parser, "parse error"); */
2313 vec_push(block->exprs, expr);
2316 if (parser->tok != '}') {
2319 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2321 if (!vec_size(block->exprs) ||
2322 !ast_istype(vec_last(block->exprs), ast_return))
2324 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2330 (void)parser_next(parser);
2334 if (!parser_leaveblock(parser))
2336 return retval && !!block;
2339 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2342 block = ast_block_new(parser_ctx(parser));
2345 if (!parse_block_into(parser, block, warnreturn)) {
2346 ast_block_delete(block);
2352 static ast_expression* parse_statement_or_block(parser_t *parser)
2354 ast_expression *expr = NULL;
2355 if (parser->tok == '{')
2356 return (ast_expression*)parse_block(parser, false);
2357 if (!parse_statement(parser, NULL, &expr, false))
2362 static bool create_vector_members(ast_value *var, ast_member **me)
2365 size_t len = strlen(var->name);
2367 for (i = 0; i < 3; ++i) {
2368 char *name = mem_a(len+3);
2369 memcpy(name, var->name, len);
2371 name[len+1] = 'x'+i;
2373 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2382 do { ast_member_delete(me[--i]); } while(i);
2386 static bool parse_function_body(parser_t *parser, ast_value *var)
2388 ast_block *block = NULL;
2393 ast_expression *framenum = NULL;
2394 ast_expression *nextthink = NULL;
2395 /* None of the following have to be deleted */
2396 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2397 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2398 bool has_frame_think;
2402 has_frame_think = false;
2403 old = parser->function;
2405 if (var->expression.variadic) {
2406 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2407 "variadic function with implementation will not be able to access additional parameters"))
2413 if (parser->tok == '[') {
2414 /* got a frame definition: [ framenum, nextthink ]
2415 * this translates to:
2416 * self.frame = framenum;
2417 * self.nextthink = time + 0.1;
2418 * self.think = nextthink;
2422 fld_think = parser_find_field(parser, "think");
2423 fld_nextthink = parser_find_field(parser, "nextthink");
2424 fld_frame = parser_find_field(parser, "frame");
2425 if (!fld_think || !fld_nextthink || !fld_frame) {
2426 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2427 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2430 gbl_time = parser_find_global(parser, "time");
2431 gbl_self = parser_find_global(parser, "self");
2432 if (!gbl_time || !gbl_self) {
2433 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2434 parseerror(parser, "please declare the following globals: `time`, `self`");
2438 if (!parser_next(parser))
2441 framenum = parse_expression_leave(parser, true);
2443 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2446 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2447 ast_unref(framenum);
2448 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2452 if (parser->tok != ',') {
2453 ast_unref(framenum);
2454 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2455 parseerror(parser, "Got a %i\n", parser->tok);
2459 if (!parser_next(parser)) {
2460 ast_unref(framenum);
2464 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2466 /* qc allows the use of not-yet-declared functions here
2467 * - this automatically creates a prototype */
2468 ast_value *thinkfunc;
2469 ast_expression *functype = fld_think->expression.next;
2471 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2472 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2473 ast_unref(framenum);
2474 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2478 if (!parser_next(parser)) {
2479 ast_unref(framenum);
2480 ast_delete(thinkfunc);
2484 vec_push(parser->globals, (ast_expression*)thinkfunc);
2485 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2486 nextthink = (ast_expression*)thinkfunc;
2489 nextthink = parse_expression_leave(parser, true);
2491 ast_unref(framenum);
2492 parseerror(parser, "expected a think-function in [frame,think] notation");
2497 if (!ast_istype(nextthink, ast_value)) {
2498 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2502 if (retval && parser->tok != ']') {
2503 parseerror(parser, "expected closing `]` for [frame,think] notation");
2507 if (retval && !parser_next(parser)) {
2511 if (retval && parser->tok != '{') {
2512 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2517 ast_unref(nextthink);
2518 ast_unref(framenum);
2522 has_frame_think = true;
2525 block = ast_block_new(parser_ctx(parser));
2527 parseerror(parser, "failed to allocate block");
2528 if (has_frame_think) {
2529 ast_unref(nextthink);
2530 ast_unref(framenum);
2535 if (has_frame_think) {
2537 ast_expression *self_frame;
2538 ast_expression *self_nextthink;
2539 ast_expression *self_think;
2540 ast_expression *time_plus_1;
2541 ast_store *store_frame;
2542 ast_store *store_nextthink;
2543 ast_store *store_think;
2545 ctx = parser_ctx(parser);
2546 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2547 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2548 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2550 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2551 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2553 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2554 if (self_frame) ast_delete(self_frame);
2555 if (self_nextthink) ast_delete(self_nextthink);
2556 if (self_think) ast_delete(self_think);
2557 if (time_plus_1) ast_delete(time_plus_1);
2563 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2564 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2565 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2568 ast_delete(self_frame);
2571 if (!store_nextthink) {
2572 ast_delete(self_nextthink);
2576 ast_delete(self_think);
2580 if (store_frame) ast_delete(store_frame);
2581 if (store_nextthink) ast_delete(store_nextthink);
2582 if (store_think) ast_delete(store_think);
2585 vec_push(block->exprs, (ast_expression*)store_frame);
2586 vec_push(block->exprs, (ast_expression*)store_nextthink);
2587 vec_push(block->exprs, (ast_expression*)store_think);
2591 parseerror(parser, "failed to generate code for [frame,think]");
2592 ast_unref(nextthink);
2593 ast_unref(framenum);
2599 parser_enterblock(parser);
2601 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2603 ast_value *param = var->expression.params[parami];
2606 if (param->expression.vtype != TYPE_VECTOR &&
2607 (param->expression.vtype != TYPE_FIELD ||
2608 param->expression.next->expression.vtype != TYPE_VECTOR))
2613 if (!create_vector_members(param, me)) {
2614 ast_block_delete(block);
2618 for (e = 0; e < 3; ++e) {
2619 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2620 ast_block_collect(block, (ast_expression*)me[e]);
2624 func = ast_function_new(ast_ctx(var), var->name, var);
2626 parseerror(parser, "failed to allocate function for `%s`", var->name);
2627 ast_block_delete(block);
2630 vec_push(parser->functions, func);
2632 parser->function = func;
2633 if (!parse_block_into(parser, block, true)) {
2634 ast_block_delete(block);
2638 vec_push(func->blocks, block);
2640 parser->function = old;
2641 if (!parser_leaveblock(parser))
2643 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2644 parseerror(parser, "internal error: local scopes left");
2648 if (parser->tok == ';')
2649 return parser_next(parser);
2650 else if (opts_standard == COMPILER_QCC)
2651 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2655 vec_pop(parser->functions);
2656 ast_function_delete(func);
2657 var->constval.vfunc = NULL;
2660 (void)!parser_leaveblock(parser);
2661 parser->function = old;
2665 static ast_expression *array_accessor_split(
2670 ast_expression *left,
2671 ast_expression *right
2677 lex_ctx ctx = ast_ctx(array);
2679 if (!left || !right) {
2680 if (left) ast_delete(left);
2681 if (right) ast_delete(right);
2685 cmp = ast_binary_new(ctx, INSTR_LT,
2686 (ast_expression*)index,
2687 (ast_expression*)parser_const_float(parser, middle));
2691 parseerror(parser, "internal error: failed to create comparison for array setter");
2695 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2697 ast_delete(cmp); /* will delete left and right */
2698 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2702 return (ast_expression*)ifthen;
2705 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2707 lex_ctx ctx = ast_ctx(array);
2709 if (from+1 == afterend) {
2710 /* set this value */
2713 ast_array_index *subscript;
2715 int assignop = type_store_instr[value->expression.vtype];
2717 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2718 assignop = INSTR_STORE_V;
2720 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2724 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2726 ast_delete(subscript);
2730 block = ast_block_new(ctx);
2736 vec_push(block->exprs, (ast_expression*)st);
2738 ret = ast_return_new(ctx, NULL);
2744 vec_push(block->exprs, (ast_expression*)ret);
2746 return (ast_expression*)block;
2748 ast_expression *left, *right;
2749 size_t diff = afterend - from;
2750 size_t middle = from + diff/2;
2751 left = array_setter_node(parser, array, index, value, from, middle);
2752 right = array_setter_node(parser, array, index, value, middle, afterend);
2753 return array_accessor_split(parser, array, index, middle, left, right);
2757 static ast_expression *array_field_setter_node(
2766 lex_ctx ctx = ast_ctx(array);
2768 if (from+1 == afterend) {
2769 /* set this value */
2772 ast_entfield *entfield;
2773 ast_array_index *subscript;
2775 int assignop = type_storep_instr[value->expression.vtype];
2777 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2778 assignop = INSTR_STOREP_V;
2780 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2784 entfield = ast_entfield_new_force(ctx,
2785 (ast_expression*)entity,
2786 (ast_expression*)subscript,
2787 (ast_expression*)subscript);
2789 ast_delete(subscript);
2793 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2795 ast_delete(entfield);
2799 block = ast_block_new(ctx);
2805 vec_push(block->exprs, (ast_expression*)st);
2807 ret = ast_return_new(ctx, NULL);
2813 vec_push(block->exprs, (ast_expression*)ret);
2815 return (ast_expression*)block;
2817 ast_expression *left, *right;
2818 size_t diff = afterend - from;
2819 size_t middle = from + diff/2;
2820 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2821 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2822 return array_accessor_split(parser, array, index, middle, left, right);
2826 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2828 lex_ctx ctx = ast_ctx(array);
2830 if (from+1 == afterend) {
2832 ast_array_index *subscript;
2834 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2838 ret = ast_return_new(ctx, (ast_expression*)subscript);
2840 ast_delete(subscript);
2844 return (ast_expression*)ret;
2846 ast_expression *left, *right;
2847 size_t diff = afterend - from;
2848 size_t middle = from + diff/2;
2849 left = array_getter_node(parser, array, index, from, middle);
2850 right = array_getter_node(parser, array, index, middle, afterend);
2851 return array_accessor_split(parser, array, index, middle, left, right);
2855 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2857 ast_function *func = NULL;
2858 ast_value *fval = NULL;
2859 ast_block *body = NULL;
2861 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2863 parseerror(parser, "failed to create accessor function value");
2867 func = ast_function_new(ast_ctx(array), funcname, fval);
2870 parseerror(parser, "failed to create accessor function node");
2874 body = ast_block_new(ast_ctx(array));
2876 parseerror(parser, "failed to create block for array accessor");
2882 vec_push(func->blocks, body);
2885 vec_push(parser->accessors, fval);
2890 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2892 ast_expression *root = NULL;
2893 ast_value *index = NULL;
2894 ast_value *value = NULL;
2898 if (!ast_istype(array->expression.next, ast_value)) {
2899 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2903 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2905 func = fval->constval.vfunc;
2906 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2908 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2909 value = ast_value_copy((ast_value*)array->expression.next);
2911 if (!index || !value) {
2912 parseerror(parser, "failed to create locals for array accessor");
2915 (void)!ast_value_set_name(value, "value"); /* not important */
2916 vec_push(fval->expression.params, index);
2917 vec_push(fval->expression.params, value);
2919 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2921 parseerror(parser, "failed to build accessor search tree");
2925 vec_push(func->blocks[0]->exprs, root);
2926 array->setter = fval;
2929 if (index) ast_delete(index);
2930 if (value) ast_delete(value);
2931 if (root) ast_delete(root);
2937 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2939 ast_expression *root = NULL;
2940 ast_value *entity = NULL;
2941 ast_value *index = NULL;
2942 ast_value *value = NULL;
2946 if (!ast_istype(array->expression.next, ast_value)) {
2947 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2951 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2953 func = fval->constval.vfunc;
2954 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2956 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2957 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2958 value = ast_value_copy((ast_value*)array->expression.next);
2959 if (!entity || !index || !value) {
2960 parseerror(parser, "failed to create locals for array accessor");
2963 (void)!ast_value_set_name(value, "value"); /* not important */
2964 vec_push(fval->expression.params, entity);
2965 vec_push(fval->expression.params, index);
2966 vec_push(fval->expression.params, value);
2968 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2970 parseerror(parser, "failed to build accessor search tree");
2974 vec_push(func->blocks[0]->exprs, root);
2975 array->setter = fval;
2978 if (entity) ast_delete(entity);
2979 if (index) ast_delete(index);
2980 if (value) ast_delete(value);
2981 if (root) ast_delete(root);
2987 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2989 ast_expression *root = NULL;
2990 ast_value *index = NULL;
2994 /* NOTE: checking array->expression.next rather than elemtype since
2995 * for fields elemtype is a temporary fieldtype.
2997 if (!ast_istype(array->expression.next, ast_value)) {
2998 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3002 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3004 func = fval->constval.vfunc;
3005 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3007 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3010 parseerror(parser, "failed to create locals for array accessor");
3013 vec_push(fval->expression.params, index);
3015 root = array_getter_node(parser, array, index, 0, array->expression.count);
3017 parseerror(parser, "failed to build accessor search tree");
3021 vec_push(func->blocks[0]->exprs, root);
3022 array->getter = fval;
3025 if (index) ast_delete(index);
3026 if (root) ast_delete(root);
3032 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3033 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3041 bool variadic = false;
3043 ctx = parser_ctx(parser);
3045 /* for the sake of less code we parse-in in this function */
3046 if (!parser_next(parser)) {
3047 parseerror(parser, "expected parameter list");
3053 /* parse variables until we hit a closing paren */
3054 while (parser->tok != ')') {
3056 /* there must be commas between them */
3057 if (parser->tok != ',') {
3058 parseerror(parser, "expected comma or end of parameter list");
3061 if (!parser_next(parser)) {
3062 parseerror(parser, "expected parameter");
3068 if (parser->tok == TOKEN_DOTS) {
3069 /* '...' indicates a varargs function */
3071 if (!parser_next(parser)) {
3072 parseerror(parser, "expected parameter");
3075 if (parser->tok != ')') {
3076 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3082 /* for anything else just parse a typename */
3083 param = parse_typename(parser, NULL, NULL);
3086 vec_push(params, param);
3087 if (param->expression.vtype >= TYPE_VARIANT) {
3088 char typename[1024];
3089 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3090 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3097 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3098 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3101 if (!parser_next(parser)) {
3102 parseerror(parser, "parse error after typename");
3106 /* now turn 'var' into a function type */
3107 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3108 fval->expression.next = (ast_expression*)var;
3109 fval->expression.variadic = variadic;
3112 var->expression.params = params;
3119 for (i = 0; i < vec_size(params); ++i)
3120 ast_delete(params[i]);
3125 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3127 ast_expression *cexp;
3128 ast_value *cval, *tmp;
3131 ctx = parser_ctx(parser);
3133 if (!parser_next(parser)) {
3135 parseerror(parser, "expected array-size");
3139 cexp = parse_expression_leave(parser, true);
3141 if (!cexp || !ast_istype(cexp, ast_value)) {
3145 parseerror(parser, "expected array-size as constant positive integer");
3148 cval = (ast_value*)cexp;
3150 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3151 tmp->expression.next = (ast_expression*)var;
3154 if (cval->expression.vtype == TYPE_INTEGER)
3155 tmp->expression.count = cval->constval.vint;
3156 else if (cval->expression.vtype == TYPE_FLOAT)
3157 tmp->expression.count = cval->constval.vfloat;
3161 parseerror(parser, "array-size must be a positive integer constant");
3166 if (parser->tok != ']') {
3168 parseerror(parser, "expected ']' after array-size");
3171 if (!parser_next(parser)) {
3173 parseerror(parser, "error after parsing array size");
3179 /* Parse a complete typename.
3180 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3181 * but when parsing variables separated by comma
3182 * 'storebase' should point to where the base-type should be kept.
3183 * The base type makes up every bit of type information which comes *before* the
3186 * The following will be parsed in its entirety:
3188 * The 'basetype' in this case is 'void()'
3189 * and if there's a comma after it, say:
3191 * then the type-information 'void()' can be stored in 'storebase'
3193 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3195 ast_value *var, *tmp;
3198 const char *name = NULL;
3199 bool isfield = false;
3200 bool wasarray = false;
3201 size_t morefields = 0;
3203 ctx = parser_ctx(parser);
3205 /* types may start with a dot */
3206 if (parser->tok == '.') {
3208 /* if we parsed a dot we need a typename now */
3209 if (!parser_next(parser)) {
3210 parseerror(parser, "expected typename for field definition");
3214 /* Further dots are handled seperately because they won't be part of the
3217 while (parser->tok == '.') {
3219 if (!parser_next(parser)) {
3220 parseerror(parser, "expected typename for field definition");
3225 if (parser->tok == TOKEN_IDENT)
3226 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3227 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3228 parseerror(parser, "expected typename");
3233 /* generate the basic type value */
3234 if (cached_typedef) {
3235 var = ast_value_copy(cached_typedef);
3236 ast_value_set_name(var, "<type(from_def)>");
3238 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3240 for (; morefields; --morefields) {
3241 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3242 tmp->expression.next = (ast_expression*)var;
3246 /* do not yet turn into a field - remember:
3247 * .void() foo; is a field too
3248 * .void()() foo; is a function
3252 if (!parser_next(parser)) {
3254 parseerror(parser, "parse error after typename");
3258 /* an opening paren now starts the parameter-list of a function
3259 * this is where original-QC has parameter lists.
3260 * We allow a single parameter list here.
3261 * Much like fteqcc we don't allow `float()() x`
3263 if (parser->tok == '(') {
3264 var = parse_parameter_list(parser, var);
3269 /* store the base if requested */
3271 *storebase = ast_value_copy(var);
3273 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3274 tmp->expression.next = (ast_expression*)*storebase;
3279 /* there may be a name now */
3280 if (parser->tok == TOKEN_IDENT) {
3281 name = util_strdup(parser_tokval(parser));
3283 if (!parser_next(parser)) {
3285 parseerror(parser, "error after variable or field declaration");
3290 /* now this may be an array */
3291 if (parser->tok == '[') {
3293 var = parse_arraysize(parser, var);
3298 /* This is the point where we can turn it into a field */
3300 /* turn it into a field if desired */
3301 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3302 tmp->expression.next = (ast_expression*)var;
3306 /* now there may be function parens again */
3307 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3308 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3309 if (parser->tok == '(' && wasarray)
3310 parseerror(parser, "arrays as part of a return type is not supported");
3311 while (parser->tok == '(') {
3312 var = parse_parameter_list(parser, var);
3321 /* finally name it */
3323 if (!ast_value_set_name(var, name)) {
3325 parseerror(parser, "internal error: failed to set name");
3328 /* free the name, ast_value_set_name duplicates */
3335 static bool parse_typedef(parser_t *parser)
3337 ast_value *typevar, *oldtype;
3338 ast_expression *old;
3340 typevar = parse_typename(parser, NULL, NULL);
3345 if ( (old = parser_find_var(parser, typevar->name)) ) {
3346 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3347 " -> `%s` has been declared here: %s:%i",
3348 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3349 ast_delete(typevar);
3353 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3354 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3355 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3356 ast_delete(typevar);
3360 vec_push(parser->_typedefs, typevar);
3361 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3363 if (parser->tok != ';') {
3364 parseerror(parser, "expected semicolon after typedef");
3367 if (!parser_next(parser)) {
3368 parseerror(parser, "parse error after typedef");
3375 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const, ast_value *cached_typedef)
3379 ast_expression *old;
3383 ast_value *basetype = NULL;
3385 bool isparam = false;
3386 bool isvector = false;
3387 bool cleanvar = true;
3388 bool wasarray = false;
3392 /* get the first complete variable */
3393 var = parse_typename(parser, &basetype, cached_typedef);
3396 ast_delete(basetype);
3404 /* Part 0: finish the type */
3405 if (parser->tok == '(') {
3406 if (opts_standard == COMPILER_QCC)
3407 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3408 var = parse_parameter_list(parser, var);
3414 /* we only allow 1-dimensional arrays */
3415 if (parser->tok == '[') {
3417 var = parse_arraysize(parser, var);
3423 if (parser->tok == '(' && wasarray) {
3424 parseerror(parser, "arrays as part of a return type is not supported");
3425 /* we'll still parse the type completely for now */
3427 /* for functions returning functions */
3428 while (parser->tok == '(') {
3429 if (opts_standard == COMPILER_QCC)
3430 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3431 var = parse_parameter_list(parser, var);
3439 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3440 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3441 * is then filled with the previous definition and the parameter-names replaced.
3444 /* Deal with end_sys_ vars */
3446 if (!strcmp(var->name, "end_sys_globals")) {
3447 parser->crc_globals = vec_size(parser->globals);
3450 else if (!strcmp(var->name, "end_sys_fields")) {
3451 parser->crc_fields = vec_size(parser->fields);
3454 if (was_end && var->expression.vtype == TYPE_FIELD) {
3455 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3456 "global '%s' hint should not be a field",
3457 parser_tokval(parser)))
3464 if (!nofields && var->expression.vtype == TYPE_FIELD)
3466 /* deal with field declarations */
3467 old = parser_find_field(parser, var->name);
3469 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3470 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3479 parseerror(parser, "field `%s` already declared here: %s:%i",
3480 var->name, ast_ctx(old).file, ast_ctx(old).line);
3485 if (opts_standard == COMPILER_QCC &&
3486 (old = parser_find_global(parser, var->name)))
3488 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3489 parseerror(parser, "field `%s` already declared here: %s:%i",
3490 var->name, ast_ctx(old).file, ast_ctx(old).line);
3497 /* deal with other globals */
3498 old = parser_find_global(parser, var->name);
3499 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3501 /* This is a function which had a prototype */
3502 if (!ast_istype(old, ast_value)) {
3503 parseerror(parser, "internal error: prototype is not an ast_value");
3507 proto = (ast_value*)old;
3508 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3509 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3511 ast_ctx(proto).file, ast_ctx(proto).line);
3515 /* we need the new parameter-names */
3516 for (i = 0; i < vec_size(proto->expression.params); ++i)
3517 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3525 if (opts_standard == COMPILER_GMQCC) {
3526 parseerror(parser, "global `%s` already declared here: %s:%i",
3527 var->name, ast_ctx(old).file, ast_ctx(old).line);
3531 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3532 "global `%s` already declared here: %s:%i",
3533 var->name, ast_ctx(old).file, ast_ctx(old).line))
3540 if (opts_standard == COMPILER_QCC &&
3541 (old = parser_find_field(parser, var->name)))
3543 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3544 parseerror(parser, "global `%s` already declared here: %s:%i",
3545 var->name, ast_ctx(old).file, ast_ctx(old).line);
3552 else /* it's not a global */
3554 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3555 if (old && !isparam) {
3556 parseerror(parser, "local `%s` already declared here: %s:%i",
3557 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3561 old = parser_find_local(parser, var->name, 0, &isparam);
3562 if (old && isparam) {
3563 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3564 "local `%s` is shadowing a parameter", var->name))
3566 parseerror(parser, "local `%s` already declared here: %s:%i",
3567 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3571 if (opts_standard != COMPILER_GMQCC) {
3580 var->isconst = true;
3583 * Create the global/local, and deal with vector types.
3586 if (var->expression.vtype == TYPE_VECTOR)
3588 else if (var->expression.vtype == TYPE_FIELD &&
3589 var->expression.next->expression.vtype == TYPE_VECTOR)
3593 if (!create_vector_members(var, me)) {
3600 /* deal with global variables, fields, functions */
3601 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3602 vec_push(parser->fields, (ast_expression*)var);
3603 util_htset(parser->htfields, var->name, var);
3605 for (i = 0; i < 3; ++i) {
3606 vec_push(parser->fields, (ast_expression*)me[i]);
3607 util_htset(parser->htfields, me[i]->name, me[i]);
3612 vec_push(parser->globals, (ast_expression*)var);
3613 util_htset(parser->htglobals, var->name, var);
3615 for (i = 0; i < 3; ++i) {
3616 vec_push(parser->globals, (ast_expression*)me[i]);
3617 util_htset(parser->htglobals, me[i]->name, me[i]);
3622 vec_push(localblock->locals, var);
3623 parser_addlocal(parser, var->name, (ast_expression*)var);
3625 for (i = 0; i < 3; ++i) {
3626 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3627 ast_block_collect(localblock, (ast_expression*)me[i]);
3633 me[0] = me[1] = me[2] = NULL;
3638 if (var->expression.vtype == TYPE_ARRAY) {
3640 snprintf(name, sizeof(name), "%s##SET", var->name);
3641 if (!parser_create_array_setter(parser, var, name))
3643 snprintf(name, sizeof(name), "%s##GET", var->name);
3644 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3647 else if (!localblock && !nofields &&
3648 var->expression.vtype == TYPE_FIELD &&
3649 var->expression.next->expression.vtype == TYPE_ARRAY)
3652 ast_expression *telem;
3654 ast_value *array = (ast_value*)var->expression.next;
3656 if (!ast_istype(var->expression.next, ast_value)) {
3657 parseerror(parser, "internal error: field element type must be an ast_value");
3661 snprintf(name, sizeof(name), "%s##SETF", var->name);
3662 if (!parser_create_array_field_setter(parser, array, name))
3665 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3666 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3667 tfield->expression.next = telem;
3668 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3669 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3677 if (parser->tok == ';') {
3678 ast_delete(basetype);
3679 if (!parser_next(parser)) {
3680 parseerror(parser, "error after variable declaration");
3686 if (parser->tok == ',')
3689 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3690 parseerror(parser, "missing comma or semicolon while parsing variables");
3694 if (localblock && opts_standard == COMPILER_QCC) {
3695 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3696 "initializing expression turns variable `%s` into a constant in this standard",
3703 if (parser->tok != '{') {
3704 if (parser->tok != '=') {
3705 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
3709 if (!parser_next(parser)) {
3710 parseerror(parser, "error parsing initializer");
3714 else if (opts_standard == COMPILER_QCC) {
3715 parseerror(parser, "expected '=' before function body in this standard");
3718 if (parser->tok == '#') {
3719 ast_function *func = NULL;
3722 parseerror(parser, "cannot declare builtins within functions");
3725 if (var->expression.vtype != TYPE_FUNCTION) {
3726 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3729 if (!parser_next(parser)) {
3730 parseerror(parser, "expected builtin number");
3733 if (parser->tok != TOKEN_INTCONST) {
3734 parseerror(parser, "builtin number must be an integer constant");
3737 if (parser_token(parser)->constval.i <= 0) {
3738 parseerror(parser, "builtin number must be an integer greater than zero");
3743 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3744 "builtin `%s` has already been defined\n"
3745 " -> previous declaration here: %s:%i",
3746 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3750 func = ast_function_new(ast_ctx(var), var->name, var);
3752 parseerror(parser, "failed to allocate function for `%s`", var->name);
3755 vec_push(parser->functions, func);
3757 func->builtin = -parser_token(parser)->constval.i;
3760 if (!parser_next(parser)) {
3761 parseerror(parser, "expected comma or semicolon");
3763 ast_function_delete(func);
3764 var->constval.vfunc = NULL;
3768 else if (parser->tok == '{' || parser->tok == '[')
3771 parseerror(parser, "cannot declare functions within functions");
3775 if (!parse_function_body(parser, var))
3777 ast_delete(basetype);
3780 ast_expression *cexp;
3783 cexp = parse_expression_leave(parser, true);
3788 cval = (ast_value*)cexp;
3789 if (!ast_istype(cval, ast_value) || !cval->isconst)
3790 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3793 var->isconst = true;
3794 if (cval->expression.vtype == TYPE_STRING)
3795 var->constval.vstring = parser_strdup(cval->constval.vstring);
3797 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3801 shunt sy = { NULL, NULL };
3802 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3803 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3804 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3805 if (!parser_sy_pop(parser, &sy))
3808 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3809 parseerror(parser, "internal error: leaked operands");
3810 vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3818 if (parser->tok == ',') {
3819 if (!parser_next(parser)) {
3820 parseerror(parser, "expected another variable");
3824 if (parser->tok != TOKEN_IDENT) {
3825 parseerror(parser, "expected another variable");
3828 var = ast_value_copy(basetype);
3830 ast_value_set_name(var, parser_tokval(parser));
3831 if (!parser_next(parser)) {
3832 parseerror(parser, "error parsing variable declaration");
3838 if (parser->tok != ';') {
3839 parseerror(parser, "missing semicolon after variables");
3843 if (!parser_next(parser)) {
3844 parseerror(parser, "parse error after variable declaration");
3848 ast_delete(basetype);
3852 if (cleanvar && var)
3854 ast_delete(basetype);
3858 ast_delete(basetype);
3859 if (cleanvar && var)
3861 if (me[0]) ast_member_delete(me[0]);
3862 if (me[1]) ast_member_delete(me[1]);
3863 if (me[2]) ast_member_delete(me[2]);
3867 static bool parser_global_statement(parser_t *parser)
3869 ast_value *istype = NULL;
3870 if (parser->tok == TOKEN_IDENT)
3871 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
3873 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3875 return parse_variable(parser, NULL, false, false, istype);
3877 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3879 if (!strcmp(parser_tokval(parser), "var")) {
3880 if (!parser_next(parser)) {
3881 parseerror(parser, "expected variable declaration after 'var'");
3884 return parse_variable(parser, NULL, true, false, NULL);
3887 else if (parser->tok == TOKEN_KEYWORD)
3889 if (!strcmp(parser_tokval(parser), "const")) {
3890 if (!parser_next(parser)) {
3891 parseerror(parser, "expected variable declaration after 'const'");
3894 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
3895 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
3896 if (!parser_next(parser)) {
3897 parseerror(parser, "expected variable declaration after 'const var'");
3901 return parse_variable(parser, NULL, true, true, NULL);
3903 else if (!strcmp(parser_tokval(parser), "typedef")) {
3904 if (!parser_next(parser)) {
3905 parseerror(parser, "expected type definition after 'typedef'");
3908 return parse_typedef(parser);
3910 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3913 else if (parser->tok == '$')
3915 if (!parser_next(parser)) {
3916 parseerror(parser, "parse error");
3922 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3928 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3930 return util_crc16(old, str, strlen(str));
3933 static void progdefs_crc_file(const char *str)
3935 /* write to progdefs.h here */
3939 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3941 old = progdefs_crc_sum(old, str);
3942 progdefs_crc_file(str);
3946 static void generate_checksum(parser_t *parser)
3948 uint16_t crc = 0xFFFF;
3952 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3953 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3955 progdefs_crc_file("\tint\tpad;\n");
3956 progdefs_crc_file("\tint\tofs_return[3];\n");
3957 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3958 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3959 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3960 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3961 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3962 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3963 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3964 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3966 for (i = 0; i < parser->crc_globals; ++i) {
3967 if (!ast_istype(parser->globals[i], ast_value))
3969 value = (ast_value*)(parser->globals[i]);
3970 switch (value->expression.vtype) {
3971 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3972 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3973 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3974 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3976 crc = progdefs_crc_both(crc, "\tint\t");
3979 crc = progdefs_crc_both(crc, value->name);
3980 crc = progdefs_crc_both(crc, ";\n");
3982 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3983 for (i = 0; i < parser->crc_fields; ++i) {
3984 if (!ast_istype(parser->fields[i], ast_value))
3986 value = (ast_value*)(parser->fields[i]);
3987 switch (value->expression.next->expression.vtype) {
3988 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3989 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3990 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3991 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3993 crc = progdefs_crc_both(crc, "\tint\t");
3996 crc = progdefs_crc_both(crc, value->name);
3997 crc = progdefs_crc_both(crc, ";\n");
3999 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4004 static parser_t *parser;
4010 parser = (parser_t*)mem_a(sizeof(parser_t));
4014 memset(parser, 0, sizeof(*parser));
4016 for (i = 0; i < operator_count; ++i) {
4017 if (operators[i].id == opid1('=')) {
4018 parser->assign_op = operators+i;
4022 if (!parser->assign_op) {
4023 printf("internal error: initializing parser: failed to find assign operator\n");
4028 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4029 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4030 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4031 vec_push(parser->_blocktypedefs, 0);
4035 bool parser_compile()
4037 /* initial lexer/parser state */
4038 parser->lex->flags.noops = true;
4040 if (parser_next(parser))
4042 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4044 if (!parser_global_statement(parser)) {
4045 if (parser->tok == TOKEN_EOF)
4046 parseerror(parser, "unexpected eof");
4047 else if (!parser->errors)
4048 parseerror(parser, "there have been errors, bailing out");
4049 lex_close(parser->lex);
4055 parseerror(parser, "parse error");
4056 lex_close(parser->lex);
4061 lex_close(parser->lex);
4064 return !parser->errors;
4067 bool parser_compile_file(const char *filename)
4069 parser->lex = lex_open(filename);
4071 con_err("failed to open file \"%s\"\n", filename);
4074 return parser_compile();
4077 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4079 parser->lex = lex_open_string(str, len, name);
4081 con_err("failed to create lexer for string \"%s\"\n", name);
4084 return parser_compile();
4087 bool parser_compile_string(const char *name, const char *str)
4089 parser->lex = lex_open_string(str, strlen(str), name);
4091 con_err("failed to create lexer for string \"%s\"\n", name);
4094 return parser_compile();
4097 void parser_cleanup()
4100 for (i = 0; i < vec_size(parser->accessors); ++i) {
4101 ast_delete(parser->accessors[i]->constval.vfunc);
4102 parser->accessors[i]->constval.vfunc = NULL;
4103 ast_delete(parser->accessors[i]);
4105 for (i = 0; i < vec_size(parser->functions); ++i) {
4106 ast_delete(parser->functions[i]);
4108 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4109 ast_delete(parser->imm_vector[i]);
4111 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4112 ast_delete(parser->imm_string[i]);
4114 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4115 ast_delete(parser->imm_float[i]);
4117 for (i = 0; i < vec_size(parser->fields); ++i) {
4118 ast_delete(parser->fields[i]);
4120 for (i = 0; i < vec_size(parser->globals); ++i) {
4121 ast_delete(parser->globals[i]);
4123 vec_free(parser->accessors);
4124 vec_free(parser->functions);
4125 vec_free(parser->imm_vector);
4126 vec_free(parser->imm_string);
4127 vec_free(parser->imm_float);
4128 vec_free(parser->globals);
4129 vec_free(parser->fields);
4131 for (i = 0; i < vec_size(parser->variables); ++i)
4132 util_htdel(parser->variables[i]);
4133 vec_free(parser->variables);
4134 vec_free(parser->_blocklocals);
4135 vec_free(parser->_locals);
4137 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4138 ast_delete(parser->_typedefs[i]);
4139 vec_free(parser->_typedefs);
4140 for (i = 0; i < vec_size(parser->typedefs); ++i)
4141 util_htdel(parser->typedefs[i]);
4142 vec_free(parser->typedefs);
4143 vec_free(parser->_blocktypedefs);
4148 bool parser_finish(const char *output)
4154 if (!parser->errors)
4156 ir = ir_builder_new("gmqcc_out");
4158 con_out("failed to allocate builder\n");
4162 for (i = 0; i < vec_size(parser->fields); ++i) {
4165 if (!ast_istype(parser->fields[i], ast_value))
4167 field = (ast_value*)parser->fields[i];
4168 isconst = field->isconst;
4169 field->isconst = false;
4170 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4171 con_out("failed to generate field %s\n", field->name);
4172 ir_builder_delete(ir);
4177 ast_expression *subtype;
4178 field->isconst = true;
4179 subtype = field->expression.next;
4180 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4181 if (subtype->expression.vtype == TYPE_FIELD)
4182 ifld->fieldtype = subtype->expression.next->expression.vtype;
4183 else if (subtype->expression.vtype == TYPE_FUNCTION)
4184 ifld->outtype = subtype->expression.next->expression.vtype;
4185 (void)!ir_value_set_field(field->ir_v, ifld);
4188 for (i = 0; i < vec_size(parser->globals); ++i) {
4190 if (!ast_istype(parser->globals[i], ast_value))
4192 asvalue = (ast_value*)(parser->globals[i]);
4193 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
4194 if (strcmp(asvalue->name, "end_sys_globals") &&
4195 strcmp(asvalue->name, "end_sys_fields"))
4197 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4198 "unused global: `%s`", asvalue->name);
4201 if (!ast_global_codegen(asvalue, ir, false)) {
4202 con_out("failed to generate global %s\n", asvalue->name);
4203 ir_builder_delete(ir);
4207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4208 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4209 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4210 ir_builder_delete(ir);
4214 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4215 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4216 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4217 ir_builder_delete(ir);
4221 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4222 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4223 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4224 ir_builder_delete(ir);
4228 for (i = 0; i < vec_size(parser->globals); ++i) {
4230 if (!ast_istype(parser->globals[i], ast_value))
4232 asvalue = (ast_value*)(parser->globals[i]);
4233 if (asvalue->setter) {
4234 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4235 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4236 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4238 printf("failed to generate setter for %s\n", asvalue->name);
4239 ir_builder_delete(ir);
4243 if (asvalue->getter) {
4244 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4245 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4246 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4248 printf("failed to generate getter for %s\n", asvalue->name);
4249 ir_builder_delete(ir);
4254 for (i = 0; i < vec_size(parser->fields); ++i) {
4256 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4258 if (!ast_istype((ast_expression*)asvalue, ast_value))
4260 if (asvalue->expression.vtype != TYPE_ARRAY)
4262 if (asvalue->setter) {
4263 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4264 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4265 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4267 printf("failed to generate setter for %s\n", asvalue->name);
4268 ir_builder_delete(ir);
4272 if (asvalue->getter) {
4273 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4274 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4275 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4277 printf("failed to generate getter for %s\n", asvalue->name);
4278 ir_builder_delete(ir);
4283 for (i = 0; i < vec_size(parser->functions); ++i) {
4284 if (!ast_function_codegen(parser->functions[i], ir)) {
4285 con_out("failed to generate function %s\n", parser->functions[i]->name);
4286 ir_builder_delete(ir);
4291 ir_builder_dump(ir, con_out);
4292 for (i = 0; i < vec_size(parser->functions); ++i) {
4293 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4294 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4295 ir_builder_delete(ir);
4302 ir_builder_dump(ir, con_out);
4304 generate_checksum(parser);
4306 if (!ir_builder_generate(ir, output)) {
4307 con_out("*** failed to generate output file\n");
4308 ir_builder_delete(ir);
4313 ir_builder_delete(ir);
4317 con_out("*** there were compile errors\n");