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
40 ast_function **functions;
41 ast_value **imm_float;
42 ast_value **imm_string;
43 ast_value **imm_vector;
45 /* must be deleted first, they reference immediates and values */
46 ast_value **accessors;
48 ast_value *imm_float_zero;
49 ast_value *imm_float_one;
50 ast_value *imm_vector_zero;
55 ast_function *function;
61 /* we store the '=' operator info */
62 const oper_info *assign_op;
64 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
65 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
66 * anything else: type error
72 static bool GMQCC_WARN parser_pop_local(parser_t *parser);
73 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const);
74 static ast_block* parse_block(parser_t *parser, bool warnreturn);
75 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
76 static ast_expression* parse_statement_or_block(parser_t *parser);
77 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
78 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
79 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
81 static void parseerror(parser_t *parser, const char *fmt, ...)
88 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
92 /* returns true if it counts as an error */
93 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
96 int lvl = LVL_WARNING;
98 if (!OPTS_WARN(warntype))
107 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
113 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
116 int lvl = LVL_WARNING;
118 if (!OPTS_WARN(warntype))
125 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
131 /**********************************************************************
132 * some maths used for constant folding
135 vector vec3_add(vector a, vector b)
144 vector vec3_sub(vector a, vector b)
153 qcfloat vec3_mulvv(vector a, vector b)
155 return (a.x * b.x + a.y * b.y + a.z * b.z);
158 vector vec3_mulvf(vector a, float b)
167 /**********************************************************************
171 bool parser_next(parser_t *parser)
173 /* lex_do kills the previous token */
174 parser->tok = lex_do(parser->lex);
175 if (parser->tok == TOKEN_EOF)
177 if (parser->tok >= TOKEN_ERROR) {
178 parseerror(parser, "lex error");
184 #define parser_tokval(p) ((p)->lex->tok.value)
185 #define parser_token(p) (&((p)->lex->tok))
186 #define parser_ctx(p) ((p)->lex->tok.ctx)
188 static ast_value* parser_const_float(parser_t *parser, double d)
192 for (i = 0; i < vec_size(parser->imm_float); ++i) {
193 const double compare = parser->imm_float[i]->constval.vfloat;
194 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
195 return parser->imm_float[i];
197 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
199 out->constval.vfloat = d;
200 vec_push(parser->imm_float, out);
204 static ast_value* parser_const_float_0(parser_t *parser)
206 if (!parser->imm_float_zero)
207 parser->imm_float_zero = parser_const_float(parser, 0);
208 return parser->imm_float_zero;
211 static ast_value* parser_const_float_1(parser_t *parser)
213 if (!parser->imm_float_one)
214 parser->imm_float_one = parser_const_float(parser, 1);
215 return parser->imm_float_one;
218 static char *parser_strdup(const char *str)
221 /* actually dup empty strings */
222 char *out = mem_a(1);
226 return util_strdup(str);
229 static ast_value* parser_const_string(parser_t *parser, const char *str)
233 for (i = 0; i < vec_size(parser->imm_string); ++i) {
234 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
235 return parser->imm_string[i];
237 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
239 out->constval.vstring = parser_strdup(str);
240 vec_push(parser->imm_string, out);
244 static ast_value* parser_const_vector(parser_t *parser, vector v)
248 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
249 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
250 return parser->imm_vector[i];
252 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
254 out->constval.vvec = v;
255 vec_push(parser->imm_vector, out);
259 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
265 return parser_const_vector(parser, v);
268 static ast_value* parser_const_vector_0(parser_t *parser)
270 if (!parser->imm_vector_zero)
271 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
272 return parser->imm_vector_zero;
275 static ast_expression* parser_find_field(parser_t *parser, const char *name)
278 for (i = 0; i < vec_size(parser->fields); ++i) {
279 if (!strcmp(parser->fields[i].name, name))
280 return parser->fields[i].var;
285 static ast_expression* parser_find_global(parser_t *parser, const char *name)
288 for (i = 0; i < vec_size(parser->globals); ++i) {
289 if (!strcmp(parser->globals[i].name, name))
290 return parser->globals[i].var;
295 static ast_expression* parser_find_param(parser_t *parser, const char *name)
299 if (!parser->function)
301 fun = parser->function->vtype;
302 for (i = 0; i < vec_size(fun->expression.params); ++i) {
303 if (!strcmp(fun->expression.params[i]->name, name))
304 return (ast_expression*)(fun->expression.params[i]);
309 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
313 for (i = vec_size(parser->locals); i > upto;) {
315 if (!strcmp(parser->locals[i].name, name))
316 return parser->locals[i].var;
319 return parser_find_param(parser, name);
322 static ast_expression* parser_find_var(parser_t *parser, const char *name)
326 v = parser_find_local(parser, name, 0, &dummy);
327 if (!v) v = parser_find_global(parser, name);
333 size_t etype; /* 0 = expression, others are operators */
337 ast_block *block; /* for commas and function calls */
346 #define SY_PAREN_EXPR '('
347 #define SY_PAREN_FUNC 'f'
348 #define SY_PAREN_INDEX '['
350 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
361 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
365 e.out = (ast_expression*)v;
372 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
374 e.etype = 1 + (op - operators);
383 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
395 # define DEBUGSHUNTDO(x) x
397 # define DEBUGSHUNTDO(x)
400 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
401 * so we need to rotate it to become ent.(foo[n]).
403 static bool rotate_entfield_array_index_nodes(ast_expression **out)
405 ast_array_index *index;
406 ast_entfield *entfield;
410 ast_expression *entity;
412 lex_ctx ctx = ast_ctx(*out);
414 if (!ast_istype(*out, ast_array_index))
416 index = (ast_array_index*)*out;
418 if (!ast_istype(index->array, ast_entfield))
420 entfield = (ast_entfield*)index->array;
422 if (!ast_istype(entfield->field, ast_value))
424 field = (ast_value*)entfield->field;
427 entity = entfield->entity;
431 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
432 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
433 *out = (ast_expression*)entfield;
438 static bool parser_sy_pop(parser_t *parser, shunt *sy)
442 ast_expression *out = NULL;
443 ast_expression *exprs[3];
444 ast_block *blocks[3];
445 ast_value *asvalue[3];
446 size_t i, assignop, addop, subop;
447 qcint generated_op = 0;
452 if (!vec_size(sy->ops)) {
453 parseerror(parser, "internal error: missing operator");
457 if (vec_last(sy->ops).paren) {
458 parseerror(parser, "unmatched parenthesis");
462 op = &operators[vec_last(sy->ops).etype - 1];
463 ctx = vec_last(sy->ops).ctx;
465 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
467 if (vec_size(sy->out) < op->operands) {
468 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
469 op->op, (int)op->id);
473 vec_shrinkby(sy->ops, 1);
475 vec_shrinkby(sy->out, op->operands);
476 for (i = 0; i < op->operands; ++i) {
477 exprs[i] = sy->out[vec_size(sy->out)+i].out;
478 blocks[i] = sy->out[vec_size(sy->out)+i].block;
479 asvalue[i] = (ast_value*)exprs[i];
482 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
483 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
487 #define NotSameType(T) \
488 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
489 exprs[0]->expression.vtype != T)
490 #define CanConstFold1(A) \
491 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
492 #define CanConstFold(A, B) \
493 (CanConstFold1(A) && CanConstFold1(B))
494 #define ConstV(i) (asvalue[(i)]->constval.vvec)
495 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
496 #define ConstS(i) (asvalue[(i)]->constval.vstring)
500 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
504 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
505 if (exprs[1]->expression.vtype != TYPE_FIELD) {
506 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
509 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
511 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
512 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
516 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
522 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
523 !(exprs[0]->expression.vtype == TYPE_FIELD &&
524 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
526 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
527 parseerror(parser, "cannot index value of type %s", ty1);
530 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
531 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
532 parseerror(parser, "index must be of type float, not %s", ty1);
535 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
536 if (rotate_entfield_array_index_nodes(&out))
538 if (opts_standard != COMPILER_GMQCC) {
539 /* this error doesn't need to make us bail out */
540 (void)!parsewarning(parser, WARN_EXTENSIONS,
541 "accessing array-field members of an entity without parenthesis\n"
542 " -> this is an extension from -std=gmqcc");
549 vec_push(blocks[0]->exprs, exprs[1]);
551 blocks[0] = ast_block_new(ctx);
552 vec_push(blocks[0]->exprs, exprs[0]);
553 vec_push(blocks[0]->exprs, exprs[1]);
555 if (!ast_block_set_type(blocks[0], exprs[1]))
558 vec_push(sy->out, syblock(ctx, blocks[0]));
562 switch (exprs[0]->expression.vtype) {
564 if (CanConstFold1(exprs[0]))
565 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
567 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
568 (ast_expression*)parser_const_float_0(parser),
572 if (CanConstFold1(exprs[0]))
573 out = (ast_expression*)parser_const_vector_f(parser,
574 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
576 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
577 (ast_expression*)parser_const_vector_0(parser),
581 parseerror(parser, "invalid types used in expression: cannot negate type %s",
582 type_name[exprs[0]->expression.vtype]);
588 switch (exprs[0]->expression.vtype) {
590 if (CanConstFold1(exprs[0]))
591 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
593 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
596 if (CanConstFold1(exprs[0]))
597 out = (ast_expression*)parser_const_float(parser,
598 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
600 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
603 if (CanConstFold1(exprs[0]))
604 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
606 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
608 /* we don't constant-fold NOT for these types */
610 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
613 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
616 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
617 type_name[exprs[0]->expression.vtype]);
623 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
624 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
626 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
627 type_name[exprs[0]->expression.vtype],
628 type_name[exprs[1]->expression.vtype]);
631 switch (exprs[0]->expression.vtype) {
633 if (CanConstFold(exprs[0], exprs[1]))
635 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
638 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
641 if (CanConstFold(exprs[0], exprs[1]))
642 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
644 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
647 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
648 type_name[exprs[0]->expression.vtype],
649 type_name[exprs[1]->expression.vtype]);
654 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
655 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
657 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
658 type_name[exprs[1]->expression.vtype],
659 type_name[exprs[0]->expression.vtype]);
662 switch (exprs[0]->expression.vtype) {
664 if (CanConstFold(exprs[0], exprs[1]))
665 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
667 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
670 if (CanConstFold(exprs[0], exprs[1]))
671 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
673 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
676 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
677 type_name[exprs[1]->expression.vtype],
678 type_name[exprs[0]->expression.vtype]);
683 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
684 exprs[0]->expression.vtype != TYPE_VECTOR &&
685 exprs[0]->expression.vtype != TYPE_FLOAT &&
686 exprs[1]->expression.vtype != TYPE_VECTOR &&
687 exprs[1]->expression.vtype != TYPE_FLOAT)
689 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
690 type_name[exprs[1]->expression.vtype],
691 type_name[exprs[0]->expression.vtype]);
694 switch (exprs[0]->expression.vtype) {
696 if (exprs[1]->expression.vtype == TYPE_VECTOR)
698 if (CanConstFold(exprs[0], exprs[1]))
699 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
701 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
705 if (CanConstFold(exprs[0], exprs[1]))
706 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
708 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
712 if (exprs[1]->expression.vtype == TYPE_FLOAT)
714 if (CanConstFold(exprs[0], exprs[1]))
715 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
717 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
721 if (CanConstFold(exprs[0], exprs[1]))
722 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
728 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
729 type_name[exprs[1]->expression.vtype],
730 type_name[exprs[0]->expression.vtype]);
735 if (NotSameType(TYPE_FLOAT)) {
736 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
737 type_name[exprs[0]->expression.vtype],
738 type_name[exprs[1]->expression.vtype]);
741 if (CanConstFold(exprs[0], exprs[1]))
742 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
744 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
748 parseerror(parser, "qc does not have a modulo operator");
752 if (NotSameType(TYPE_FLOAT)) {
753 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
754 type_name[exprs[0]->expression.vtype],
755 type_name[exprs[1]->expression.vtype]);
758 if (CanConstFold(exprs[0], exprs[1]))
759 out = (ast_expression*)parser_const_float(parser,
760 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
761 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
763 out = (ast_expression*)ast_binary_new(ctx,
764 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
768 parseerror(parser, "TODO: bitxor");
773 case opid3('<','<','='):
774 case opid3('>','>','='):
775 parseerror(parser, "TODO: shifts");
779 generated_op += 1; /* INSTR_OR */
781 generated_op += INSTR_AND;
782 if (NotSameType(TYPE_FLOAT)) {
783 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
784 type_name[exprs[0]->expression.vtype],
785 type_name[exprs[1]->expression.vtype]);
786 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
787 parseerror(parser, "TODO: optional early out");
790 if (opts_standard == COMPILER_GMQCC)
791 con_out("TODO: early out logic\n");
792 if (CanConstFold(exprs[0], exprs[1]))
793 out = (ast_expression*)parser_const_float(parser,
794 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
796 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
800 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
801 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
802 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
803 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
806 if (CanConstFold1(exprs[0]))
807 out = (ConstF(0) ? exprs[1] : exprs[2]);
809 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
813 generated_op += 1; /* INSTR_GT */
815 generated_op += 1; /* INSTR_LT */
816 case opid2('>', '='):
817 generated_op += 1; /* INSTR_GE */
818 case opid2('<', '='):
819 generated_op += INSTR_LE;
820 if (NotSameType(TYPE_FLOAT)) {
821 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
822 type_name[exprs[0]->expression.vtype],
823 type_name[exprs[1]->expression.vtype]);
826 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
828 case opid2('!', '='):
829 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
830 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
831 type_name[exprs[0]->expression.vtype],
832 type_name[exprs[1]->expression.vtype]);
835 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
837 case opid2('=', '='):
838 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
839 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
840 type_name[exprs[0]->expression.vtype],
841 type_name[exprs[1]->expression.vtype]);
844 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
848 if (ast_istype(exprs[0], ast_entfield)) {
849 ast_expression *field = ((ast_entfield*)exprs[0])->field;
850 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
851 exprs[0]->expression.vtype == TYPE_FIELD &&
852 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
854 assignop = type_storep_instr[TYPE_VECTOR];
857 assignop = type_storep_instr[exprs[0]->expression.vtype];
858 if (!ast_compare_type(field->expression.next, exprs[1])) {
859 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
860 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
861 if (opts_standard == COMPILER_QCC &&
862 field->expression.next->expression.vtype == TYPE_FUNCTION &&
863 exprs[1]->expression.vtype == TYPE_FUNCTION)
865 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
866 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
872 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
877 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
878 exprs[0]->expression.vtype == TYPE_FIELD &&
879 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
881 assignop = type_store_instr[TYPE_VECTOR];
884 assignop = type_store_instr[exprs[0]->expression.vtype];
887 if (assignop == AINSTR_END) {
888 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
889 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
890 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
892 else if (!ast_compare_type(exprs[0], exprs[1])) {
893 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
894 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
895 if (opts_standard == COMPILER_QCC &&
896 exprs[0]->expression.vtype == TYPE_FUNCTION &&
897 exprs[1]->expression.vtype == TYPE_FUNCTION)
899 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
900 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
906 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
909 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
911 case opid3('+','+','P'):
912 case opid3('-','-','P'):
914 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
915 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
916 parseerror(parser, "invalid type for prefix increment: %s", ty1);
919 if (op->id == opid3('+','+','P'))
923 if (ast_istype(exprs[0], ast_entfield)) {
924 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
926 (ast_expression*)parser_const_float_1(parser));
928 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
930 (ast_expression*)parser_const_float_1(parser));
933 case opid3('S','+','+'):
934 case opid3('S','-','-'):
936 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
937 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
938 parseerror(parser, "invalid type for suffix increment: %s", ty1);
941 if (op->id == opid3('S','+','+')) {
948 if (ast_istype(exprs[0], ast_entfield)) {
949 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
951 (ast_expression*)parser_const_float_1(parser));
953 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
955 (ast_expression*)parser_const_float_1(parser));
959 out = (ast_expression*)ast_binary_new(ctx, subop,
961 (ast_expression*)parser_const_float_1(parser));
965 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
966 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
968 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
969 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
970 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
974 if (ast_istype(exprs[0], ast_entfield))
975 assignop = type_storep_instr[exprs[0]->expression.vtype];
977 assignop = type_store_instr[exprs[0]->expression.vtype];
978 switch (exprs[0]->expression.vtype) {
980 out = (ast_expression*)ast_binstore_new(ctx, assignop,
981 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
985 out = (ast_expression*)ast_binstore_new(ctx, assignop,
986 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
990 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
991 type_name[exprs[0]->expression.vtype],
992 type_name[exprs[1]->expression.vtype]);
998 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
999 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1000 exprs[0]->expression.vtype == TYPE_VECTOR))
1002 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1003 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1004 parseerror(parser, "invalid types used in expression: %s and %s",
1008 if (ast_istype(exprs[0], ast_entfield))
1009 assignop = type_storep_instr[exprs[0]->expression.vtype];
1011 assignop = type_store_instr[exprs[0]->expression.vtype];
1012 switch (exprs[0]->expression.vtype) {
1014 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1015 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1016 exprs[0], exprs[1]);
1019 if (op->id == opid2('*','=')) {
1020 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1021 exprs[0], exprs[1]);
1023 /* there's no DIV_VF */
1024 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1025 (ast_expression*)parser_const_float_1(parser),
1029 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1034 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1035 type_name[exprs[0]->expression.vtype],
1036 type_name[exprs[1]->expression.vtype]);
1040 case opid2('&','='):
1041 case opid2('|','='):
1042 if (NotSameType(TYPE_FLOAT)) {
1043 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1044 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1045 parseerror(parser, "invalid types used in expression: %s and %s",
1049 if (ast_istype(exprs[0], ast_entfield))
1050 assignop = type_storep_instr[exprs[0]->expression.vtype];
1052 assignop = type_store_instr[exprs[0]->expression.vtype];
1053 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1054 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1055 exprs[0], exprs[1]);
1057 case opid3('&','~','='):
1058 /* This is like: a &= ~(b);
1059 * But QC has no bitwise-not, so we implement it as
1062 if (NotSameType(TYPE_FLOAT)) {
1063 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1064 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1065 parseerror(parser, "invalid types used in expression: %s and %s",
1069 if (ast_istype(exprs[0], ast_entfield))
1070 assignop = type_storep_instr[exprs[0]->expression.vtype];
1072 assignop = type_store_instr[exprs[0]->expression.vtype];
1073 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1076 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1082 parseerror(parser, "failed to apply operand %s", op->op);
1086 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1087 vec_push(sy->out, syexp(ctx, out));
1091 static bool parser_close_call(parser_t *parser, shunt *sy)
1093 /* was a function call */
1094 ast_expression *fun;
1100 vec_shrinkby(sy->ops, 1);
1101 fid = sy->ops[vec_size(sy->ops)].off;
1103 /* out[fid] is the function
1104 * everything above is parameters...
1105 * 0 params = nothing
1106 * 1 params = ast_expression
1110 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1111 parseerror(parser, "internal error: function call needs function and parameter list...");
1115 fun = sy->out[fid].out;
1117 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1119 parseerror(parser, "out of memory");
1123 if (fid+1 == vec_size(sy->out)) {
1126 } else if (fid+2 == vec_size(sy->out)) {
1128 vec_shrinkby(sy->out, 1);
1129 params = sy->out[vec_size(sy->out)].block;
1133 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1135 paramcount = vec_size(params->exprs);
1136 call->params = params->exprs;
1137 params->exprs = NULL;
1140 if (!ast_call_check_types(call))
1143 parseerror(parser, "invalid function call");
1147 /* overwrite fid, the function, with a call */
1148 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1150 if (fun->expression.vtype != TYPE_FUNCTION) {
1151 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1155 if (!fun->expression.next) {
1156 parseerror(parser, "could not determine function return type");
1159 if (vec_size(fun->expression.params) != paramcount &&
1160 !(fun->expression.variadic &&
1161 vec_size(fun->expression.params) < paramcount))
1164 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1166 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1167 if (opts_standard == COMPILER_GMQCC)
1170 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1171 " -> `%s` has been declared here: %s:%i",
1172 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1173 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1175 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1176 " -> `%s` has been declared here: %s:%i",
1177 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1178 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1184 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1185 "too %s parameters for call to %s: expected %i, got %i\n"
1186 " -> `%s` has been declared here: %s:%i",
1187 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1188 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1190 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1191 "too %s parameters for function call: expected %i, got %i\n"
1192 " -> `%s` has been declared here: %s:%i",
1193 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1194 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1202 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1204 if (!vec_size(sy->ops)) {
1205 parseerror(parser, "unmatched closing paren");
1208 /* this would for bit a + (x) because there are no operators inside (x)
1209 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1210 parseerror(parser, "empty parenthesis expression");
1214 while (vec_size(sy->ops)) {
1215 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1216 if (!parser_close_call(parser, sy))
1220 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1221 vec_shrinkby(sy->ops, 1);
1222 return !functions_only;
1224 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1227 /* pop off the parenthesis */
1228 vec_shrinkby(sy->ops, 1);
1229 /* then apply the index operator */
1230 if (!parser_sy_pop(parser, sy))
1234 if (!parser_sy_pop(parser, sy))
1240 static void parser_reclassify_token(parser_t *parser)
1243 for (i = 0; i < operator_count; ++i) {
1244 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1245 parser->tok = TOKEN_OPERATOR;
1251 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1253 ast_expression *expr = NULL;
1255 bool wantop = false;
1256 bool gotmemberof = false;
1258 /* count the parens because an if starts with one, so the
1259 * end of a condition is an unmatched closing paren
1267 parser->lex->flags.noops = false;
1269 parser_reclassify_token(parser);
1274 gotmemberof = false;
1276 parser->memberof = 0;
1278 if (parser->tok == TOKEN_IDENT)
1280 ast_expression *var;
1282 parseerror(parser, "expected operator or end of statement");
1287 if (opts_standard == COMPILER_GMQCC)
1289 if (parser->memberof == TYPE_ENTITY) {
1290 /* still get vars first since there could be a fieldpointer */
1291 var = parser_find_var(parser, parser_tokval(parser));
1293 var = parser_find_field(parser, parser_tokval(parser));
1295 else if (parser->memberof == TYPE_VECTOR)
1297 parseerror(parser, "TODO: implement effective vector member access");
1300 else if (parser->memberof) {
1301 parseerror(parser, "namespace for member not found");
1305 var = parser_find_var(parser, parser_tokval(parser));
1307 var = parser_find_var(parser, parser_tokval(parser));
1309 var = parser_find_field(parser, parser_tokval(parser));
1312 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1315 if (ast_istype(var, ast_value))
1316 ((ast_value*)var)->uses++;
1317 vec_push(sy.out, syexp(parser_ctx(parser), var));
1318 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1320 else if (parser->tok == TOKEN_FLOATCONST) {
1323 parseerror(parser, "expected operator or end of statement, got constant");
1327 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1330 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1331 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1333 else if (parser->tok == TOKEN_INTCONST) {
1336 parseerror(parser, "expected operator or end of statement, got constant");
1340 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1343 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1344 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1346 else if (parser->tok == TOKEN_STRINGCONST) {
1349 parseerror(parser, "expected operator or end of statement, got constant");
1353 val = parser_const_string(parser, parser_tokval(parser));
1356 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1357 DEBUGSHUNTDO(con_out("push string\n"));
1359 else if (parser->tok == TOKEN_VECTORCONST) {
1362 parseerror(parser, "expected operator or end of statement, got constant");
1366 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1369 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1370 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1371 parser_token(parser)->constval.v.x,
1372 parser_token(parser)->constval.v.y,
1373 parser_token(parser)->constval.v.z));
1375 else if (parser->tok == '(') {
1376 parseerror(parser, "internal error: '(' should be classified as operator");
1379 else if (parser->tok == '[') {
1380 parseerror(parser, "internal error: '[' should be classified as operator");
1383 else if (parser->tok == ')') {
1385 DEBUGSHUNTDO(con_out("do[op] )\n"));
1389 /* we do expect an operator next */
1390 /* closing an opening paren */
1391 if (!parser_close_paren(parser, &sy, false))
1394 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1398 /* allowed for function calls */
1399 if (!parser_close_paren(parser, &sy, true))
1404 else if (parser->tok == ']') {
1406 parseerror(parser, "operand expected");
1410 if (!parser_close_paren(parser, &sy, false))
1414 else if (parser->tok != TOKEN_OPERATOR) {
1416 parseerror(parser, "expected operator or end of statement");
1423 /* classify the operator */
1424 const oper_info *op;
1425 const oper_info *olast = NULL;
1427 for (o = 0; o < operator_count; ++o) {
1428 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1429 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1430 !strcmp(parser_tokval(parser), operators[o].op))
1435 if (o == operator_count) {
1436 /* no operator found... must be the end of the statement */
1439 /* found an operator */
1442 /* when declaring variables, a comma starts a new variable */
1443 if (op->id == opid1(',') && !parens && stopatcomma) {
1444 /* fixup the token */
1449 /* a colon without a pervious question mark cannot be a ternary */
1450 if (!ternaries && op->id == opid2(':','?')) {
1455 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1456 olast = &operators[vec_last(sy.ops).etype-1];
1459 (op->prec < olast->prec) ||
1460 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1462 if (!parser_sy_pop(parser, &sy))
1464 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1465 olast = &operators[vec_last(sy.ops).etype-1];
1470 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1471 /* for gmqcc standard: open up the namespace of the previous type */
1472 ast_expression *prevex = vec_last(sy.out).out;
1474 parseerror(parser, "unexpected member operator");
1477 if (prevex->expression.vtype == TYPE_ENTITY)
1478 parser->memberof = TYPE_ENTITY;
1479 else if (prevex->expression.vtype == TYPE_VECTOR)
1480 parser->memberof = TYPE_VECTOR;
1482 parseerror(parser, "type error: type has no members");
1488 if (op->id == opid1('(')) {
1490 size_t sycount = vec_size(sy.out);
1491 DEBUGSHUNTDO(con_out("push [op] (\n"));
1493 /* we expected an operator, this is the function-call operator */
1494 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1497 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1498 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1501 } else if (op->id == opid1('[')) {
1503 parseerror(parser, "unexpected array subscript");
1507 /* push both the operator and the paren, this makes life easier */
1508 vec_push(sy.ops, syop(parser_ctx(parser), op));
1509 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1511 } else if (op->id == opid2('?',':')) {
1513 vec_push(sy.ops, syop(parser_ctx(parser), op));
1516 } else if (op->id == opid2(':','?')) {
1517 /* we don't push this operator */
1521 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1522 vec_push(sy.ops, syop(parser_ctx(parser), op));
1523 wantop = !!(op->flags & OP_SUFFIX);
1526 if (!parser_next(parser)) {
1529 if (parser->tok == ';' ||
1530 (!parens && parser->tok == ']'))
1536 while (vec_size(sy.ops)) {
1537 if (!parser_sy_pop(parser, &sy))
1541 parser->lex->flags.noops = true;
1542 if (!vec_size(sy.out)) {
1543 parseerror(parser, "empty expression");
1546 expr = sy.out[0].out;
1549 DEBUGSHUNTDO(con_out("shunt done\n"));
1553 parser->lex->flags.noops = true;
1559 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1561 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1564 if (!parser_next(parser)) {
1571 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1574 ast_expression *cond, *ontrue, *onfalse = NULL;
1577 lex_ctx ctx = parser_ctx(parser);
1579 (void)block; /* not touching */
1581 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1582 if (!parser_next(parser)) {
1583 parseerror(parser, "expected condition or 'not'");
1586 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1588 if (!parser_next(parser)) {
1589 parseerror(parser, "expected condition in parenthesis");
1593 if (parser->tok != '(') {
1594 parseerror(parser, "expected 'if' condition in parenthesis");
1597 /* parse into the expression */
1598 if (!parser_next(parser)) {
1599 parseerror(parser, "expected 'if' condition after opening paren");
1602 /* parse the condition */
1603 cond = parse_expression_leave(parser, false);
1607 if (parser->tok != ')') {
1608 parseerror(parser, "expected closing paren after 'if' condition");
1612 /* parse into the 'then' branch */
1613 if (!parser_next(parser)) {
1614 parseerror(parser, "expected statement for on-true branch of 'if'");
1618 ontrue = parse_statement_or_block(parser);
1623 /* check for an else */
1624 if (!strcmp(parser_tokval(parser), "else")) {
1625 /* parse into the 'else' branch */
1626 if (!parser_next(parser)) {
1627 parseerror(parser, "expected on-false branch after 'else'");
1632 onfalse = parse_statement_or_block(parser);
1641 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1643 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1644 *out = (ast_expression*)ifthen;
1648 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1651 ast_expression *cond, *ontrue;
1653 lex_ctx ctx = parser_ctx(parser);
1655 (void)block; /* not touching */
1657 /* skip the 'while' and check for opening paren */
1658 if (!parser_next(parser) || parser->tok != '(') {
1659 parseerror(parser, "expected 'while' condition in parenthesis");
1662 /* parse into the expression */
1663 if (!parser_next(parser)) {
1664 parseerror(parser, "expected 'while' condition after opening paren");
1667 /* parse the condition */
1668 cond = parse_expression_leave(parser, false);
1672 if (parser->tok != ')') {
1673 parseerror(parser, "expected closing paren after 'while' condition");
1677 /* parse into the 'then' branch */
1678 if (!parser_next(parser)) {
1679 parseerror(parser, "expected while-loop body");
1683 ontrue = parse_statement_or_block(parser);
1689 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1690 *out = (ast_expression*)aloop;
1694 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1697 ast_expression *cond, *ontrue;
1699 lex_ctx ctx = parser_ctx(parser);
1701 (void)block; /* not touching */
1703 /* skip the 'do' and get the body */
1704 if (!parser_next(parser)) {
1705 parseerror(parser, "expected loop body");
1708 ontrue = parse_statement_or_block(parser);
1712 /* expect the "while" */
1713 if (parser->tok != TOKEN_KEYWORD ||
1714 strcmp(parser_tokval(parser), "while"))
1716 parseerror(parser, "expected 'while' and condition");
1721 /* skip the 'while' and check for opening paren */
1722 if (!parser_next(parser) || parser->tok != '(') {
1723 parseerror(parser, "expected 'while' condition in parenthesis");
1727 /* parse into the expression */
1728 if (!parser_next(parser)) {
1729 parseerror(parser, "expected 'while' condition after opening paren");
1733 /* parse the condition */
1734 cond = parse_expression_leave(parser, false);
1738 if (parser->tok != ')') {
1739 parseerror(parser, "expected closing paren after 'while' condition");
1745 if (!parser_next(parser) || parser->tok != ';') {
1746 parseerror(parser, "expected semicolon after condition");
1752 if (!parser_next(parser)) {
1753 parseerror(parser, "parse error");
1759 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1760 *out = (ast_expression*)aloop;
1764 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1767 ast_expression *initexpr, *cond, *increment, *ontrue;
1768 size_t oldblocklocal;
1771 lex_ctx ctx = parser_ctx(parser);
1773 oldblocklocal = parser->blocklocal;
1774 parser->blocklocal = vec_size(parser->locals);
1781 /* skip the 'while' and check for opening paren */
1782 if (!parser_next(parser) || parser->tok != '(') {
1783 parseerror(parser, "expected 'for' expressions in parenthesis");
1786 /* parse into the expression */
1787 if (!parser_next(parser)) {
1788 parseerror(parser, "expected 'for' initializer after opening paren");
1792 if (parser->tok == TOKEN_TYPENAME) {
1793 if (opts_standard != COMPILER_GMQCC) {
1794 if (parsewarning(parser, WARN_EXTENSIONS,
1795 "current standard does not allow variable declarations in for-loop initializers"))
1799 parseerror(parser, "TODO: assignment of new variables to be non-const");
1801 if (!parse_variable(parser, block, true, false))
1804 else if (parser->tok != ';')
1806 initexpr = parse_expression_leave(parser, false);
1811 /* move on to condition */
1812 if (parser->tok != ';') {
1813 parseerror(parser, "expected semicolon after for-loop initializer");
1816 if (!parser_next(parser)) {
1817 parseerror(parser, "expected for-loop condition");
1821 /* parse the condition */
1822 if (parser->tok != ';') {
1823 cond = parse_expression_leave(parser, false);
1828 /* move on to incrementor */
1829 if (parser->tok != ';') {
1830 parseerror(parser, "expected semicolon after for-loop initializer");
1833 if (!parser_next(parser)) {
1834 parseerror(parser, "expected for-loop condition");
1838 /* parse the incrementor */
1839 if (parser->tok != ')') {
1840 increment = parse_expression_leave(parser, false);
1843 if (!ast_istype(increment, ast_store) &&
1844 !ast_istype(increment, ast_call) &&
1845 !ast_istype(increment, ast_binstore))
1847 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1853 if (parser->tok != ')') {
1854 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1857 /* parse into the 'then' branch */
1858 if (!parser_next(parser)) {
1859 parseerror(parser, "expected for-loop body");
1862 ontrue = parse_statement_or_block(parser);
1867 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1868 *out = (ast_expression*)aloop;
1870 while (vec_size(parser->locals) > parser->blocklocal)
1871 retval = retval && parser_pop_local(parser);
1872 parser->blocklocal = oldblocklocal;
1875 if (initexpr) ast_delete(initexpr);
1876 if (cond) ast_delete(cond);
1877 if (increment) ast_delete(increment);
1878 while (vec_size(parser->locals) > parser->blocklocal)
1879 (void)!parser_pop_local(parser);
1880 parser->blocklocal = oldblocklocal;
1884 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1886 ast_expression *exp = NULL;
1887 ast_return *ret = NULL;
1888 ast_value *expected = parser->function->vtype;
1890 (void)block; /* not touching */
1892 if (!parser_next(parser)) {
1893 parseerror(parser, "expected return expression");
1897 if (parser->tok != ';') {
1898 exp = parse_expression(parser, false);
1902 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1903 parseerror(parser, "return with invalid expression");
1906 ret = ast_return_new(exp->expression.node.context, exp);
1912 if (!parser_next(parser))
1913 parseerror(parser, "parse error");
1914 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1915 if (opts_standard != COMPILER_GMQCC)
1916 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1918 parseerror(parser, "return without value");
1920 ret = ast_return_new(parser_ctx(parser), NULL);
1922 *out = (ast_expression*)ret;
1926 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1928 lex_ctx ctx = parser_ctx(parser);
1930 (void)block; /* not touching */
1932 if (!parser_next(parser) || parser->tok != ';') {
1933 parseerror(parser, "expected semicolon");
1937 if (!parser_next(parser))
1938 parseerror(parser, "parse error");
1940 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1944 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
1946 ast_expression *operand;
1948 ast_switch *switchnode;
1949 ast_switch_case swcase;
1951 lex_ctx ctx = parser_ctx(parser);
1953 (void)block; /* not touching */
1955 /* parse over the opening paren */
1956 if (!parser_next(parser) || parser->tok != '(') {
1957 parseerror(parser, "expected switch operand in parenthesis");
1961 /* parse into the expression */
1962 if (!parser_next(parser)) {
1963 parseerror(parser, "expected switch operand");
1966 /* parse the operand */
1967 operand = parse_expression_leave(parser, false);
1971 if (!OPTS_FLAG(RELAXED_SWITCH)) {
1972 opval = (ast_value*)operand;
1973 if (!ast_istype(operand, ast_value) || !opval->isconst) {
1974 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
1980 switchnode = ast_switch_new(ctx, operand);
1983 if (parser->tok != ')') {
1984 ast_delete(switchnode);
1985 parseerror(parser, "expected closing paren after 'switch' operand");
1989 /* parse over the opening paren */
1990 if (!parser_next(parser) || parser->tok != '{') {
1991 ast_delete(switchnode);
1992 parseerror(parser, "expected list of cases");
1996 if (!parser_next(parser)) {
1997 ast_delete(switchnode);
1998 parseerror(parser, "expected 'case' or 'default'");
2003 while (parser->tok != '}') {
2004 ast_block *caseblock;
2006 if (parser->tok != TOKEN_KEYWORD) {
2007 ast_delete(switchnode);
2008 parseerror(parser, "expected 'case' or 'default'");
2011 if (!strcmp(parser_tokval(parser), "case")) {
2012 if (!parser_next(parser)) {
2013 ast_delete(switchnode);
2014 parseerror(parser, "expected expression for case");
2017 swcase.value = parse_expression_leave(parser, false);
2018 if (!swcase.value) {
2019 ast_delete(switchnode);
2020 parseerror(parser, "expected expression for case");
2024 else if (!strcmp(parser_tokval(parser), "default")) {
2025 swcase.value = NULL;
2026 if (!parser_next(parser)) {
2027 ast_delete(switchnode);
2028 parseerror(parser, "expected colon");
2033 /* Now the colon and body */
2034 if (parser->tok != ':') {
2035 if (swcase.value) ast_unref(swcase.value);
2036 ast_delete(switchnode);
2037 parseerror(parser, "expected colon");
2041 if (!parser_next(parser)) {
2042 if (swcase.value) ast_unref(swcase.value);
2043 ast_delete(switchnode);
2044 parseerror(parser, "expected statements or case");
2047 caseblock = ast_block_new(parser_ctx(parser));
2049 if (swcase.value) ast_unref(swcase.value);
2050 ast_delete(switchnode);
2053 swcase.code = (ast_expression*)caseblock;
2054 vec_push(switchnode->cases, swcase);
2056 ast_expression *expr;
2057 if (parser->tok == '}')
2059 if (parser->tok == TOKEN_KEYWORD) {
2060 if (!strcmp(parser_tokval(parser), "case") ||
2061 !strcmp(parser_tokval(parser), "default"))
2066 if (!parse_statement(parser, caseblock, &expr, true)) {
2067 ast_delete(switchnode);
2072 vec_push(caseblock->exprs, expr);
2077 if (parser->tok != '}') {
2078 ast_delete(switchnode);
2079 parseerror(parser, "expected closing paren of case list");
2082 if (!parser_next(parser)) {
2083 ast_delete(switchnode);
2084 parseerror(parser, "parse error after switch");
2087 *out = (ast_expression*)switchnode;
2091 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2093 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2095 /* local variable */
2097 parseerror(parser, "cannot declare a variable from here");
2100 if (opts_standard == COMPILER_QCC) {
2101 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2104 if (!parse_variable(parser, block, false, false))
2109 else if (parser->tok == TOKEN_KEYWORD)
2111 if (!strcmp(parser_tokval(parser), "local"))
2114 parseerror(parser, "cannot declare a local variable here");
2117 if (!parser_next(parser)) {
2118 parseerror(parser, "expected variable declaration");
2121 if (!parse_variable(parser, block, true, false))
2126 else if (!strcmp(parser_tokval(parser), "return"))
2128 return parse_return(parser, block, out);
2130 else if (!strcmp(parser_tokval(parser), "if"))
2132 return parse_if(parser, block, out);
2134 else if (!strcmp(parser_tokval(parser), "while"))
2136 return parse_while(parser, block, out);
2138 else if (!strcmp(parser_tokval(parser), "do"))
2140 return parse_dowhile(parser, block, out);
2142 else if (!strcmp(parser_tokval(parser), "for"))
2144 if (opts_standard == COMPILER_QCC) {
2145 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2148 return parse_for(parser, block, out);
2150 else if (!strcmp(parser_tokval(parser), "break"))
2152 return parse_break_continue(parser, block, out, false);
2154 else if (!strcmp(parser_tokval(parser), "continue"))
2156 return parse_break_continue(parser, block, out, true);
2158 else if (!strcmp(parser_tokval(parser), "switch"))
2160 return parse_switch(parser, block, out);
2162 else if (!strcmp(parser_tokval(parser), "case") ||
2163 !strcmp(parser_tokval(parser), "default"))
2166 parseerror(parser, "unexpected 'case' label");
2171 parseerror(parser, "Unexpected keyword");
2174 else if (parser->tok == '{')
2177 inner = parse_block(parser, false);
2180 *out = (ast_expression*)inner;
2185 ast_expression *exp = parse_expression(parser, false);
2189 if (!ast_istype(exp, ast_store) &&
2190 !ast_istype(exp, ast_call) &&
2191 !ast_istype(exp, ast_binstore))
2193 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2200 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
2205 ve = &vec_last(parser->locals);
2206 if (!parser->errors) {
2207 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
2208 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
2213 vec_pop(parser->locals);
2217 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2219 size_t oldblocklocal;
2222 oldblocklocal = parser->blocklocal;
2223 parser->blocklocal = vec_size(parser->locals);
2225 if (!parser_next(parser)) { /* skip the '{' */
2226 parseerror(parser, "expected function body");
2230 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2232 ast_expression *expr;
2233 if (parser->tok == '}')
2236 if (!parse_statement(parser, block, &expr, false)) {
2237 /* parseerror(parser, "parse error"); */
2243 vec_push(block->exprs, expr);
2246 if (parser->tok != '}') {
2249 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2251 if (!vec_size(block->exprs) ||
2252 !ast_istype(vec_last(block->exprs), ast_return))
2254 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2260 (void)parser_next(parser);
2264 while (vec_size(parser->locals) > parser->blocklocal)
2265 retval = retval && parser_pop_local(parser);
2266 parser->blocklocal = oldblocklocal;
2270 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2273 block = ast_block_new(parser_ctx(parser));
2276 if (!parse_block_into(parser, block, warnreturn)) {
2277 ast_block_delete(block);
2283 static ast_expression* parse_statement_or_block(parser_t *parser)
2285 ast_expression *expr = NULL;
2286 if (parser->tok == '{')
2287 return (ast_expression*)parse_block(parser, false);
2288 if (!parse_statement(parser, NULL, &expr, false))
2294 static bool create_vector_members(ast_value *var, varentry_t *ve)
2297 size_t len = strlen(var->name);
2299 for (i = 0; i < 3; ++i) {
2300 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
2304 ve[i].name = (char*)mem_a(len+3);
2306 ast_delete(ve[i].var);
2310 memcpy(ve[i].name, var->name, len);
2311 ve[i].name[len] = '_';
2312 ve[i].name[len+1] = 'x'+i;
2313 ve[i].name[len+2] = 0;
2322 ast_delete(ve[i].var);
2329 static bool parse_function_body(parser_t *parser, ast_value *var)
2331 ast_block *block = NULL;
2336 ast_expression *framenum = NULL;
2337 ast_expression *nextthink = NULL;
2338 /* None of the following have to be deleted */
2339 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2340 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2341 bool has_frame_think;
2345 has_frame_think = false;
2346 old = parser->function;
2348 if (var->expression.variadic) {
2349 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2350 "variadic function with implementation will not be able to access additional parameters"))
2356 if (parser->tok == '[') {
2357 /* got a frame definition: [ framenum, nextthink ]
2358 * this translates to:
2359 * self.frame = framenum;
2360 * self.nextthink = time + 0.1;
2361 * self.think = nextthink;
2365 fld_think = parser_find_field(parser, "think");
2366 fld_nextthink = parser_find_field(parser, "nextthink");
2367 fld_frame = parser_find_field(parser, "frame");
2368 if (!fld_think || !fld_nextthink || !fld_frame) {
2369 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2370 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2373 gbl_time = parser_find_global(parser, "time");
2374 gbl_self = parser_find_global(parser, "self");
2375 if (!gbl_time || !gbl_self) {
2376 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2377 parseerror(parser, "please declare the following globals: `time`, `self`");
2381 if (!parser_next(parser))
2384 framenum = parse_expression_leave(parser, true);
2386 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2389 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2390 ast_unref(framenum);
2391 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2395 if (parser->tok != ',') {
2396 ast_unref(framenum);
2397 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2398 parseerror(parser, "Got a %i\n", parser->tok);
2402 if (!parser_next(parser)) {
2403 ast_unref(framenum);
2407 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2409 /* qc allows the use of not-yet-declared functions here
2410 * - this automatically creates a prototype */
2412 ast_value *thinkfunc;
2413 ast_expression *functype = fld_think->expression.next;
2415 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2416 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2417 ast_unref(framenum);
2418 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2422 if (!parser_next(parser)) {
2423 ast_unref(framenum);
2424 ast_delete(thinkfunc);
2428 varent.var = (ast_expression*)thinkfunc;
2429 varent.name = util_strdup(thinkfunc->name);
2430 vec_push(parser->globals, varent);
2431 nextthink = (ast_expression*)thinkfunc;
2434 nextthink = parse_expression_leave(parser, true);
2436 ast_unref(framenum);
2437 parseerror(parser, "expected a think-function in [frame,think] notation");
2442 if (!ast_istype(nextthink, ast_value)) {
2443 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2447 if (retval && parser->tok != ']') {
2448 parseerror(parser, "expected closing `]` for [frame,think] notation");
2452 if (retval && !parser_next(parser)) {
2456 if (retval && parser->tok != '{') {
2457 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2462 ast_unref(nextthink);
2463 ast_unref(framenum);
2467 has_frame_think = true;
2470 block = ast_block_new(parser_ctx(parser));
2472 parseerror(parser, "failed to allocate block");
2473 if (has_frame_think) {
2474 ast_unref(nextthink);
2475 ast_unref(framenum);
2480 if (has_frame_think) {
2482 ast_expression *self_frame;
2483 ast_expression *self_nextthink;
2484 ast_expression *self_think;
2485 ast_expression *time_plus_1;
2486 ast_store *store_frame;
2487 ast_store *store_nextthink;
2488 ast_store *store_think;
2490 ctx = parser_ctx(parser);
2491 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2492 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2493 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2495 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2496 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2498 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2499 if (self_frame) ast_delete(self_frame);
2500 if (self_nextthink) ast_delete(self_nextthink);
2501 if (self_think) ast_delete(self_think);
2502 if (time_plus_1) ast_delete(time_plus_1);
2508 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2509 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2510 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2513 ast_delete(self_frame);
2516 if (!store_nextthink) {
2517 ast_delete(self_nextthink);
2521 ast_delete(self_think);
2525 if (store_frame) ast_delete(store_frame);
2526 if (store_nextthink) ast_delete(store_nextthink);
2527 if (store_think) ast_delete(store_think);
2530 vec_push(block->exprs, (ast_expression*)store_frame);
2531 vec_push(block->exprs, (ast_expression*)store_nextthink);
2532 vec_push(block->exprs, (ast_expression*)store_think);
2536 parseerror(parser, "failed to generate code for [frame,think]");
2537 ast_unref(nextthink);
2538 ast_unref(framenum);
2544 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2547 ast_value *param = var->expression.params[parami];
2549 if (param->expression.vtype != TYPE_VECTOR &&
2550 (param->expression.vtype != TYPE_FIELD ||
2551 param->expression.next->expression.vtype != TYPE_VECTOR))
2556 if (!create_vector_members(param, ve)) {
2557 ast_block_delete(block);
2561 for (e = 0; e < 3; ++e) {
2562 vec_push(parser->locals, ve[e]);
2563 ast_block_collect(block, ve[e].var);
2564 ve[e].var = NULL; /* collected */
2568 func = ast_function_new(ast_ctx(var), var->name, var);
2570 parseerror(parser, "failed to allocate function for `%s`", var->name);
2571 ast_block_delete(block);
2574 vec_push(parser->functions, func);
2576 parser->function = func;
2577 if (!parse_block_into(parser, block, true)) {
2578 ast_block_delete(block);
2582 vec_push(func->blocks, block);
2584 parser->function = old;
2585 while (vec_size(parser->locals))
2586 retval = retval && parser_pop_local(parser);
2588 if (parser->tok == ';')
2589 return parser_next(parser);
2590 else if (opts_standard == COMPILER_QCC)
2591 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2595 vec_pop(parser->functions);
2596 ast_function_delete(func);
2597 var->constval.vfunc = NULL;
2600 while (vec_size(parser->locals)) {
2601 mem_d(vec_last(parser->locals).name);
2602 vec_pop(parser->locals);
2604 parser->function = old;
2608 static ast_expression *array_accessor_split(
2613 ast_expression *left,
2614 ast_expression *right
2620 lex_ctx ctx = ast_ctx(array);
2622 if (!left || !right) {
2623 if (left) ast_delete(left);
2624 if (right) ast_delete(right);
2628 cmp = ast_binary_new(ctx, INSTR_LT,
2629 (ast_expression*)index,
2630 (ast_expression*)parser_const_float(parser, middle));
2634 parseerror(parser, "internal error: failed to create comparison for array setter");
2638 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2640 ast_delete(cmp); /* will delete left and right */
2641 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2645 return (ast_expression*)ifthen;
2648 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2650 lex_ctx ctx = ast_ctx(array);
2652 if (from+1 == afterend) {
2653 /* set this value */
2656 ast_array_index *subscript;
2658 int assignop = type_store_instr[value->expression.vtype];
2660 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2661 assignop = INSTR_STORE_V;
2663 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2667 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2669 ast_delete(subscript);
2673 block = ast_block_new(ctx);
2679 vec_push(block->exprs, (ast_expression*)st);
2681 ret = ast_return_new(ctx, NULL);
2687 vec_push(block->exprs, (ast_expression*)ret);
2689 return (ast_expression*)block;
2691 ast_expression *left, *right;
2692 size_t diff = afterend - from;
2693 size_t middle = from + diff/2;
2694 left = array_setter_node(parser, array, index, value, from, middle);
2695 right = array_setter_node(parser, array, index, value, middle, afterend);
2696 return array_accessor_split(parser, array, index, middle, left, right);
2700 static ast_expression *array_field_setter_node(
2709 lex_ctx ctx = ast_ctx(array);
2711 if (from+1 == afterend) {
2712 /* set this value */
2715 ast_entfield *entfield;
2716 ast_array_index *subscript;
2718 int assignop = type_storep_instr[value->expression.vtype];
2720 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2721 assignop = INSTR_STOREP_V;
2723 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2727 entfield = ast_entfield_new_force(ctx,
2728 (ast_expression*)entity,
2729 (ast_expression*)subscript,
2730 (ast_expression*)subscript);
2732 ast_delete(subscript);
2736 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2738 ast_delete(entfield);
2742 block = ast_block_new(ctx);
2748 vec_push(block->exprs, (ast_expression*)st);
2750 ret = ast_return_new(ctx, NULL);
2756 vec_push(block->exprs, (ast_expression*)ret);
2758 return (ast_expression*)block;
2760 ast_expression *left, *right;
2761 size_t diff = afterend - from;
2762 size_t middle = from + diff/2;
2763 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2764 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2765 return array_accessor_split(parser, array, index, middle, left, right);
2769 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2771 lex_ctx ctx = ast_ctx(array);
2773 if (from+1 == afterend) {
2775 ast_array_index *subscript;
2777 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2781 ret = ast_return_new(ctx, (ast_expression*)subscript);
2783 ast_delete(subscript);
2787 return (ast_expression*)ret;
2789 ast_expression *left, *right;
2790 size_t diff = afterend - from;
2791 size_t middle = from + diff/2;
2792 left = array_getter_node(parser, array, index, from, middle);
2793 right = array_getter_node(parser, array, index, middle, afterend);
2794 return array_accessor_split(parser, array, index, middle, left, right);
2798 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2800 ast_function *func = NULL;
2801 ast_value *fval = NULL;
2802 ast_block *body = NULL;
2804 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2806 parseerror(parser, "failed to create accessor function value");
2810 func = ast_function_new(ast_ctx(array), funcname, fval);
2813 parseerror(parser, "failed to create accessor function node");
2817 body = ast_block_new(ast_ctx(array));
2819 parseerror(parser, "failed to create block for array accessor");
2825 vec_push(func->blocks, body);
2828 vec_push(parser->accessors, fval);
2833 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2835 ast_expression *root = NULL;
2836 ast_value *index = NULL;
2837 ast_value *value = NULL;
2841 if (!ast_istype(array->expression.next, ast_value)) {
2842 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2846 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2848 func = fval->constval.vfunc;
2849 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2851 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2852 value = ast_value_copy((ast_value*)array->expression.next);
2854 if (!index || !value) {
2855 parseerror(parser, "failed to create locals for array accessor");
2858 (void)!ast_value_set_name(value, "value"); /* not important */
2859 vec_push(fval->expression.params, index);
2860 vec_push(fval->expression.params, value);
2862 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2864 parseerror(parser, "failed to build accessor search tree");
2868 vec_push(func->blocks[0]->exprs, root);
2869 array->setter = fval;
2872 if (index) ast_delete(index);
2873 if (value) ast_delete(value);
2874 if (root) ast_delete(root);
2880 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2882 ast_expression *root = NULL;
2883 ast_value *entity = NULL;
2884 ast_value *index = NULL;
2885 ast_value *value = NULL;
2889 if (!ast_istype(array->expression.next, ast_value)) {
2890 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2894 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2896 func = fval->constval.vfunc;
2897 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2899 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2900 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2901 value = ast_value_copy((ast_value*)array->expression.next);
2902 if (!entity || !index || !value) {
2903 parseerror(parser, "failed to create locals for array accessor");
2906 (void)!ast_value_set_name(value, "value"); /* not important */
2907 vec_push(fval->expression.params, entity);
2908 vec_push(fval->expression.params, index);
2909 vec_push(fval->expression.params, value);
2911 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2913 parseerror(parser, "failed to build accessor search tree");
2917 vec_push(func->blocks[0]->exprs, root);
2918 array->setter = fval;
2921 if (entity) ast_delete(entity);
2922 if (index) ast_delete(index);
2923 if (value) ast_delete(value);
2924 if (root) ast_delete(root);
2930 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2932 ast_expression *root = NULL;
2933 ast_value *index = NULL;
2937 /* NOTE: checking array->expression.next rather than elemtype since
2938 * for fields elemtype is a temporary fieldtype.
2940 if (!ast_istype(array->expression.next, ast_value)) {
2941 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2945 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2947 func = fval->constval.vfunc;
2948 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2950 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2953 parseerror(parser, "failed to create locals for array accessor");
2956 vec_push(fval->expression.params, index);
2958 root = array_getter_node(parser, array, index, 0, array->expression.count);
2960 parseerror(parser, "failed to build accessor search tree");
2964 vec_push(func->blocks[0]->exprs, root);
2965 array->getter = fval;
2968 if (index) ast_delete(index);
2969 if (root) ast_delete(root);
2975 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2976 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2984 bool variadic = false;
2986 ctx = parser_ctx(parser);
2988 /* for the sake of less code we parse-in in this function */
2989 if (!parser_next(parser)) {
2990 parseerror(parser, "expected parameter list");
2996 /* parse variables until we hit a closing paren */
2997 while (parser->tok != ')') {
2999 /* there must be commas between them */
3000 if (parser->tok != ',') {
3001 parseerror(parser, "expected comma or end of parameter list");
3004 if (!parser_next(parser)) {
3005 parseerror(parser, "expected parameter");
3011 if (parser->tok == TOKEN_DOTS) {
3012 /* '...' indicates a varargs function */
3014 if (!parser_next(parser)) {
3015 parseerror(parser, "expected parameter");
3018 if (parser->tok != ')') {
3019 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3025 /* for anything else just parse a typename */
3026 param = parse_typename(parser, NULL);
3029 vec_push(params, param);
3030 if (param->expression.vtype >= TYPE_VARIANT) {
3031 char typename[1024];
3032 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3033 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3040 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3041 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3044 if (!parser_next(parser)) {
3045 parseerror(parser, "parse error after typename");
3049 /* now turn 'var' into a function type */
3050 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3051 fval->expression.next = (ast_expression*)var;
3052 fval->expression.variadic = variadic;
3055 var->expression.params = params;
3062 for (i = 0; i < vec_size(params); ++i)
3063 ast_delete(params[i]);
3068 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3070 ast_expression *cexp;
3071 ast_value *cval, *tmp;
3074 ctx = parser_ctx(parser);
3076 if (!parser_next(parser)) {
3078 parseerror(parser, "expected array-size");
3082 cexp = parse_expression_leave(parser, true);
3084 if (!cexp || !ast_istype(cexp, ast_value)) {
3088 parseerror(parser, "expected array-size as constant positive integer");
3091 cval = (ast_value*)cexp;
3093 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3094 tmp->expression.next = (ast_expression*)var;
3097 if (cval->expression.vtype == TYPE_INTEGER)
3098 tmp->expression.count = cval->constval.vint;
3099 else if (cval->expression.vtype == TYPE_FLOAT)
3100 tmp->expression.count = cval->constval.vfloat;
3104 parseerror(parser, "array-size must be a positive integer constant");
3109 if (parser->tok != ']') {
3111 parseerror(parser, "expected ']' after array-size");
3114 if (!parser_next(parser)) {
3116 parseerror(parser, "error after parsing array size");
3122 /* Parse a complete typename.
3123 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3124 * but when parsing variables separated by comma
3125 * 'storebase' should point to where the base-type should be kept.
3126 * The base type makes up every bit of type information which comes *before* the
3129 * The following will be parsed in its entirety:
3131 * The 'basetype' in this case is 'void()'
3132 * and if there's a comma after it, say:
3134 * then the type-information 'void()' can be stored in 'storebase'
3136 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
3138 ast_value *var, *tmp;
3141 const char *name = NULL;
3142 bool isfield = false;
3143 bool wasarray = false;
3145 ctx = parser_ctx(parser);
3147 /* types may start with a dot */
3148 if (parser->tok == '.') {
3150 /* if we parsed a dot we need a typename now */
3151 if (!parser_next(parser)) {
3152 parseerror(parser, "expected typename for field definition");
3155 if (parser->tok != TOKEN_TYPENAME) {
3156 parseerror(parser, "expected typename");
3161 /* generate the basic type value */
3162 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3163 /* do not yet turn into a field - remember:
3164 * .void() foo; is a field too
3165 * .void()() foo; is a function
3169 if (!parser_next(parser)) {
3171 parseerror(parser, "parse error after typename");
3175 /* an opening paren now starts the parameter-list of a function
3176 * this is where original-QC has parameter lists.
3177 * We allow a single parameter list here.
3178 * Much like fteqcc we don't allow `float()() x`
3180 if (parser->tok == '(') {
3181 var = parse_parameter_list(parser, var);
3186 /* store the base if requested */
3188 *storebase = ast_value_copy(var);
3190 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3191 tmp->expression.next = (ast_expression*)*storebase;
3196 /* there may be a name now */
3197 if (parser->tok == TOKEN_IDENT) {
3198 name = util_strdup(parser_tokval(parser));
3200 if (!parser_next(parser)) {
3202 parseerror(parser, "error after variable or field declaration");
3207 /* now this may be an array */
3208 if (parser->tok == '[') {
3210 var = parse_arraysize(parser, var);
3215 /* This is the point where we can turn it into a field */
3217 /* turn it into a field if desired */
3218 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3219 tmp->expression.next = (ast_expression*)var;
3223 /* now there may be function parens again */
3224 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3225 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3226 if (parser->tok == '(' && wasarray)
3227 parseerror(parser, "arrays as part of a return type is not supported");
3228 while (parser->tok == '(') {
3229 var = parse_parameter_list(parser, var);
3238 /* finally name it */
3240 if (!ast_value_set_name(var, name)) {
3242 parseerror(parser, "internal error: failed to set name");
3245 /* free the name, ast_value_set_name duplicates */
3252 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const)
3256 ast_expression *old;
3260 ast_value *basetype = NULL;
3262 bool isparam = false;
3263 bool isvector = false;
3264 bool cleanvar = true;
3265 bool wasarray = false;
3267 varentry_t varent, ve[3];
3269 /* get the first complete variable */
3270 var = parse_typename(parser, &basetype);
3273 ast_delete(basetype);
3277 memset(&varent, 0, sizeof(varent));
3278 memset(&ve, 0, sizeof(ve));
3284 /* Part 0: finish the type */
3285 if (parser->tok == '(') {
3286 if (opts_standard == COMPILER_QCC)
3287 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3288 var = parse_parameter_list(parser, var);
3294 /* we only allow 1-dimensional arrays */
3295 if (parser->tok == '[') {
3297 var = parse_arraysize(parser, var);
3303 if (parser->tok == '(' && wasarray) {
3304 parseerror(parser, "arrays as part of a return type is not supported");
3305 /* we'll still parse the type completely for now */
3307 /* for functions returning functions */
3308 while (parser->tok == '(') {
3309 if (opts_standard == COMPILER_QCC)
3310 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3311 var = parse_parameter_list(parser, var);
3319 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3320 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3321 * is then filled with the previous definition and the parameter-names replaced.
3324 /* Deal with end_sys_ vars */
3326 if (!strcmp(var->name, "end_sys_globals")) {
3327 parser->crc_globals = vec_size(parser->globals);
3330 else if (!strcmp(var->name, "end_sys_fields")) {
3331 parser->crc_fields = vec_size(parser->fields);
3334 if (was_end && var->expression.vtype == TYPE_FIELD) {
3335 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3336 "global '%s' hint should not be a field",
3337 parser_tokval(parser)))
3344 if (!nofields && var->expression.vtype == TYPE_FIELD)
3346 /* deal with field declarations */
3347 old = parser_find_field(parser, var->name);
3349 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3350 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3359 parseerror(parser, "field `%s` already declared here: %s:%i",
3360 var->name, ast_ctx(old).file, ast_ctx(old).line);
3365 if (opts_standard == COMPILER_QCC &&
3366 (old = parser_find_global(parser, var->name)))
3368 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3369 parseerror(parser, "field `%s` already declared here: %s:%i",
3370 var->name, ast_ctx(old).file, ast_ctx(old).line);
3377 /* deal with other globals */
3378 old = parser_find_global(parser, var->name);
3379 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3381 /* This is a function which had a prototype */
3382 if (!ast_istype(old, ast_value)) {
3383 parseerror(parser, "internal error: prototype is not an ast_value");
3387 proto = (ast_value*)old;
3388 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3389 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3391 ast_ctx(proto).file, ast_ctx(proto).line);
3395 /* we need the new parameter-names */
3396 for (i = 0; i < vec_size(proto->expression.params); ++i)
3397 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3405 if (opts_standard == COMPILER_GMQCC) {
3406 parseerror(parser, "global `%s` already declared here: %s:%i",
3407 var->name, ast_ctx(old).file, ast_ctx(old).line);
3411 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3412 "global `%s` already declared here: %s:%i",
3413 var->name, ast_ctx(old).file, ast_ctx(old).line))
3420 if (opts_standard == COMPILER_QCC &&
3421 (old = parser_find_field(parser, var->name)))
3423 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3424 parseerror(parser, "global `%s` already declared here: %s:%i",
3425 var->name, ast_ctx(old).file, ast_ctx(old).line);
3432 else /* it's not a global */
3434 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
3435 if (old && !isparam) {
3436 parseerror(parser, "local `%s` already declared here: %s:%i",
3437 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3441 old = parser_find_local(parser, var->name, 0, &isparam);
3442 if (old && isparam) {
3443 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3444 "local `%s` is shadowing a parameter", var->name))
3446 parseerror(parser, "local `%s` already declared here: %s:%i",
3447 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3451 if (opts_standard != COMPILER_GMQCC) {
3460 var->isconst = true;
3463 * Create the global/local, and deal with vector types.
3466 if (var->expression.vtype == TYPE_VECTOR)
3468 else if (var->expression.vtype == TYPE_FIELD &&
3469 var->expression.next->expression.vtype == TYPE_VECTOR)
3473 if (!create_vector_members(var, ve)) {
3479 varent.name = util_strdup(var->name);
3480 varent.var = (ast_expression*)var;
3483 /* deal with global variables, fields, functions */
3484 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3485 vec_push(parser->fields, varent);
3487 for (i = 0; i < 3; ++i)
3488 vec_push(parser->fields, ve[i]);
3492 vec_push(parser->globals, varent);
3494 for (i = 0; i < 3; ++i)
3495 vec_push(parser->globals, ve[i]);
3499 vec_push(parser->locals, varent);
3500 vec_push(localblock->locals, var);
3502 for (i = 0; i < 3; ++i) {
3503 vec_push(parser->locals, ve[i]);
3504 ast_block_collect(localblock, ve[i].var);
3505 ve[i].var = NULL; /* from here it's being collected in the block */
3511 ve[0].name = ve[1].name = ve[2].name = NULL;
3512 ve[0].var = ve[1].var = ve[2].var = NULL;
3518 if (var->expression.vtype == TYPE_ARRAY) {
3520 snprintf(name, sizeof(name), "%s##SET", var->name);
3521 if (!parser_create_array_setter(parser, var, name))
3523 snprintf(name, sizeof(name), "%s##GET", var->name);
3524 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3527 else if (!localblock && !nofields &&
3528 var->expression.vtype == TYPE_FIELD &&
3529 var->expression.next->expression.vtype == TYPE_ARRAY)
3532 ast_expression *telem;
3534 ast_value *array = (ast_value*)var->expression.next;
3536 if (!ast_istype(var->expression.next, ast_value)) {
3537 parseerror(parser, "internal error: field element type must be an ast_value");
3541 snprintf(name, sizeof(name), "%s##SETF", var->name);
3542 if (!parser_create_array_field_setter(parser, array, name))
3545 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3546 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3547 tfield->expression.next = telem;
3548 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3549 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3557 if (parser->tok == ';') {
3558 ast_delete(basetype);
3559 if (!parser_next(parser)) {
3560 parseerror(parser, "error after variable declaration");
3566 if (parser->tok == ',')
3569 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3570 parseerror(parser, "missing comma or semicolon while parsing variables");
3574 if (localblock && opts_standard == COMPILER_QCC) {
3575 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3576 "initializing expression turns variable `%s` into a constant in this standard",
3583 if (parser->tok != '{') {
3584 if (parser->tok != '=') {
3585 parseerror(parser, "missing semicolon or initializer");
3589 if (!parser_next(parser)) {
3590 parseerror(parser, "error parsing initializer");
3594 else if (opts_standard == COMPILER_QCC) {
3595 parseerror(parser, "expected '=' before function body in this standard");
3598 if (parser->tok == '#') {
3602 parseerror(parser, "cannot declare builtins within functions");
3605 if (var->expression.vtype != TYPE_FUNCTION) {
3606 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3609 if (!parser_next(parser)) {
3610 parseerror(parser, "expected builtin number");
3613 if (parser->tok != TOKEN_INTCONST) {
3614 parseerror(parser, "builtin number must be an integer constant");
3617 if (parser_token(parser)->constval.i <= 0) {
3618 parseerror(parser, "builtin number must be an integer greater than zero");
3623 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3624 "builtin `%s` has already been defined\n"
3625 " -> previous declaration here: %s:%i",
3626 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3630 func = ast_function_new(ast_ctx(var), var->name, var);
3632 parseerror(parser, "failed to allocate function for `%s`", var->name);
3635 vec_push(parser->functions, func);
3637 func->builtin = -parser_token(parser)->constval.i;
3640 if (!parser_next(parser)) {
3641 parseerror(parser, "expected comma or semicolon");
3642 ast_function_delete(func);
3643 var->constval.vfunc = NULL;
3647 else if (parser->tok == '{' || parser->tok == '[')
3650 parseerror(parser, "cannot declare functions within functions");
3654 if (!parse_function_body(parser, var))
3656 ast_delete(basetype);
3659 ast_expression *cexp;
3662 cexp = parse_expression_leave(parser, true);
3667 cval = (ast_value*)cexp;
3668 if (!ast_istype(cval, ast_value) || !cval->isconst)
3669 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3672 var->isconst = true;
3673 if (cval->expression.vtype == TYPE_STRING)
3674 var->constval.vstring = parser_strdup(cval->constval.vstring);
3676 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3680 shunt sy = { NULL, NULL };
3681 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3682 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3683 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3684 if (!parser_sy_pop(parser, &sy))
3687 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3688 parseerror(parser, "internal error: leaked operands");
3689 vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3697 if (parser->tok == ',') {
3698 if (!parser_next(parser)) {
3699 parseerror(parser, "expected another variable");
3703 if (parser->tok != TOKEN_IDENT) {
3704 parseerror(parser, "expected another variable");
3707 var = ast_value_copy(basetype);
3709 ast_value_set_name(var, parser_tokval(parser));
3710 if (!parser_next(parser)) {
3711 parseerror(parser, "error parsing variable declaration");
3717 if (parser->tok != ';') {
3718 parseerror(parser, "missing semicolon after variables");
3722 if (!parser_next(parser)) {
3723 parseerror(parser, "parse error after variable declaration");
3727 ast_delete(basetype);
3731 if (cleanvar && var)
3733 ast_delete(basetype);
3737 ast_delete(basetype);
3738 if (cleanvar && var)
3740 if (varent.name) mem_d(varent.name);
3741 if (ve[0].name) mem_d(ve[0].name);
3742 if (ve[1].name) mem_d(ve[1].name);
3743 if (ve[2].name) mem_d(ve[2].name);
3744 if (ve[0].var) mem_d(ve[0].var);
3745 if (ve[1].var) mem_d(ve[1].var);
3746 if (ve[2].var) mem_d(ve[2].var);
3750 static bool parser_global_statement(parser_t *parser)
3752 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3754 return parse_variable(parser, NULL, false, false);
3756 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3758 if (!strcmp(parser_tokval(parser), "var")) {
3759 if (!parser_next(parser)) {
3760 parseerror(parser, "expected variable declaration after 'var'");
3763 return parse_variable(parser, NULL, true, false);
3766 else if (parser->tok == TOKEN_KEYWORD)
3768 if (!strcmp(parser_tokval(parser), "const")) {
3769 if (!parser_next(parser)) {
3770 parseerror(parser, "expected variable declaration after 'const'");
3773 return parse_variable(parser, NULL, true, true);
3775 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3778 else if (parser->tok == '$')
3780 if (!parser_next(parser)) {
3781 parseerror(parser, "parse error");
3787 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3793 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3795 return util_crc16(old, str, strlen(str));
3798 static void progdefs_crc_file(const char *str)
3800 /* write to progdefs.h here */
3804 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3806 old = progdefs_crc_sum(old, str);
3807 progdefs_crc_file(str);
3811 static void generate_checksum(parser_t *parser)
3813 uint16_t crc = 0xFFFF;
3816 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3817 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3819 progdefs_crc_file("\tint\tpad;\n");
3820 progdefs_crc_file("\tint\tofs_return[3];\n");
3821 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3822 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3823 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3824 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3825 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3826 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3827 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3828 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3830 for (i = 0; i < parser->crc_globals; ++i) {
3831 if (!ast_istype(parser->globals[i].var, ast_value))
3833 switch (parser->globals[i].var->expression.vtype) {
3834 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3835 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3836 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3837 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3839 crc = progdefs_crc_both(crc, "\tint\t");
3842 crc = progdefs_crc_both(crc, parser->globals[i].name);
3843 crc = progdefs_crc_both(crc, ";\n");
3845 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3846 for (i = 0; i < parser->crc_fields; ++i) {
3847 if (!ast_istype(parser->fields[i].var, ast_value))
3849 switch (parser->fields[i].var->expression.next->expression.vtype) {
3850 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3851 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3852 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3853 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3855 crc = progdefs_crc_both(crc, "\tint\t");
3858 crc = progdefs_crc_both(crc, parser->fields[i].name);
3859 crc = progdefs_crc_both(crc, ";\n");
3861 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3866 static parser_t *parser;
3871 parser = (parser_t*)mem_a(sizeof(parser_t));
3875 memset(parser, 0, sizeof(*parser));
3877 for (i = 0; i < operator_count; ++i) {
3878 if (operators[i].id == opid1('=')) {
3879 parser->assign_op = operators+i;
3883 if (!parser->assign_op) {
3884 printf("internal error: initializing parser: failed to find assign operator\n");
3891 bool parser_compile()
3893 /* initial lexer/parser state */
3894 parser->lex->flags.noops = true;
3896 if (parser_next(parser))
3898 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3900 if (!parser_global_statement(parser)) {
3901 if (parser->tok == TOKEN_EOF)
3902 parseerror(parser, "unexpected eof");
3903 else if (!parser->errors)
3904 parseerror(parser, "there have been errors, bailing out");
3905 lex_close(parser->lex);
3911 parseerror(parser, "parse error");
3912 lex_close(parser->lex);
3917 lex_close(parser->lex);
3920 return !parser->errors;
3923 bool parser_compile_file(const char *filename)
3925 parser->lex = lex_open(filename);
3927 con_err("failed to open file \"%s\"\n", filename);
3930 return parser_compile();
3933 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3935 parser->lex = lex_open_string(str, len, name);
3937 con_err("failed to create lexer for string \"%s\"\n", name);
3940 return parser_compile();
3943 bool parser_compile_string(const char *name, const char *str)
3945 parser->lex = lex_open_string(str, strlen(str), name);
3947 con_err("failed to create lexer for string \"%s\"\n", name);
3950 return parser_compile();
3953 void parser_cleanup()
3956 for (i = 0; i < vec_size(parser->accessors); ++i) {
3957 ast_delete(parser->accessors[i]->constval.vfunc);
3958 parser->accessors[i]->constval.vfunc = NULL;
3959 ast_delete(parser->accessors[i]);
3961 for (i = 0; i < vec_size(parser->functions); ++i) {
3962 ast_delete(parser->functions[i]);
3964 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3965 ast_delete(parser->imm_vector[i]);
3967 for (i = 0; i < vec_size(parser->imm_string); ++i) {
3968 ast_delete(parser->imm_string[i]);
3970 for (i = 0; i < vec_size(parser->imm_float); ++i) {
3971 ast_delete(parser->imm_float[i]);
3973 for (i = 0; i < vec_size(parser->fields); ++i) {
3974 ast_delete(parser->fields[i].var);
3975 mem_d(parser->fields[i].name);
3977 for (i = 0; i < vec_size(parser->globals); ++i) {
3978 ast_delete(parser->globals[i].var);
3979 mem_d(parser->globals[i].name);
3981 vec_free(parser->accessors);
3982 vec_free(parser->functions);
3983 vec_free(parser->imm_vector);
3984 vec_free(parser->imm_string);
3985 vec_free(parser->imm_float);
3986 vec_free(parser->globals);
3987 vec_free(parser->fields);
3988 vec_free(parser->locals);
3993 bool parser_finish(const char *output)
3999 if (!parser->errors)
4001 ir = ir_builder_new("gmqcc_out");
4003 con_out("failed to allocate builder\n");
4007 for (i = 0; i < vec_size(parser->fields); ++i) {
4010 if (!ast_istype(parser->fields[i].var, ast_value))
4012 field = (ast_value*)parser->fields[i].var;
4013 isconst = field->isconst;
4014 field->isconst = false;
4015 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4016 con_out("failed to generate field %s\n", field->name);
4017 ir_builder_delete(ir);
4022 ast_expression *subtype;
4023 field->isconst = true;
4024 subtype = field->expression.next;
4025 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4026 if (subtype->expression.vtype == TYPE_FIELD)
4027 ifld->fieldtype = subtype->expression.next->expression.vtype;
4028 else if (subtype->expression.vtype == TYPE_FUNCTION)
4029 ifld->outtype = subtype->expression.next->expression.vtype;
4030 (void)!ir_value_set_field(field->ir_v, ifld);
4033 for (i = 0; i < vec_size(parser->globals); ++i) {
4035 if (!ast_istype(parser->globals[i].var, ast_value))
4037 asvalue = (ast_value*)(parser->globals[i].var);
4038 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
4039 if (strcmp(asvalue->name, "end_sys_globals") &&
4040 strcmp(asvalue->name, "end_sys_fields"))
4042 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4043 "unused global: `%s`", asvalue->name);
4046 if (!ast_global_codegen(asvalue, ir, false)) {
4047 con_out("failed to generate global %s\n", parser->globals[i].name);
4048 ir_builder_delete(ir);
4052 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4053 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4054 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4055 ir_builder_delete(ir);
4059 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4060 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4061 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4062 ir_builder_delete(ir);
4066 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4067 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4068 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4069 ir_builder_delete(ir);
4073 for (i = 0; i < vec_size(parser->globals); ++i) {
4075 if (!ast_istype(parser->globals[i].var, ast_value))
4077 asvalue = (ast_value*)(parser->globals[i].var);
4078 if (asvalue->setter) {
4079 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4080 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4081 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4083 printf("failed to generate setter for %s\n", parser->globals[i].name);
4084 ir_builder_delete(ir);
4088 if (asvalue->getter) {
4089 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4090 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4091 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4093 printf("failed to generate getter for %s\n", parser->globals[i].name);
4094 ir_builder_delete(ir);
4099 for (i = 0; i < vec_size(parser->fields); ++i) {
4101 asvalue = (ast_value*)(parser->fields[i].var->expression.next);
4103 if (!ast_istype((ast_expression*)asvalue, ast_value))
4105 if (asvalue->expression.vtype != TYPE_ARRAY)
4107 if (asvalue->setter) {
4108 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4109 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4110 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4112 printf("failed to generate setter for %s\n", parser->fields[i].name);
4113 ir_builder_delete(ir);
4117 if (asvalue->getter) {
4118 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4119 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4120 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4122 printf("failed to generate getter for %s\n", parser->fields[i].name);
4123 ir_builder_delete(ir);
4128 for (i = 0; i < vec_size(parser->functions); ++i) {
4129 if (!ast_function_codegen(parser->functions[i], ir)) {
4130 con_out("failed to generate function %s\n", parser->functions[i]->name);
4131 ir_builder_delete(ir);
4136 ir_builder_dump(ir, con_out);
4137 for (i = 0; i < vec_size(parser->functions); ++i) {
4138 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4139 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4140 ir_builder_delete(ir);
4147 ir_builder_dump(ir, con_out);
4149 generate_checksum(parser);
4151 if (!ir_builder_generate(ir, output)) {
4152 con_out("*** failed to generate output file\n");
4153 ir_builder_delete(ir);
4158 ir_builder_delete(ir);
4162 con_out("*** there were compile errors\n");