18 ast_function **functions;
19 ast_value **imm_float;
20 ast_value **imm_string;
21 ast_value **imm_vector;
23 /* must be deleted first, they reference immediates and values */
24 ast_value **accessors;
26 ast_value *imm_float_zero;
27 ast_value *imm_vector_zero;
32 ast_function *function;
38 /* we store the '=' operator info */
39 const oper_info *assign_op;
41 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
42 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
43 * anything else: type error
49 static bool GMQCC_WARN parser_pop_local(parser_t *parser);
50 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields);
51 static ast_block* parse_block(parser_t *parser, bool warnreturn);
52 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
53 static ast_expression* parse_statement_or_block(parser_t *parser);
54 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
55 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
56 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
58 static void parseerror(parser_t *parser, const char *fmt, ...)
65 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
69 /* returns true if it counts as an error */
70 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
73 int lvl = LVL_WARNING;
75 if (!OPTS_WARN(warntype))
84 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
90 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
93 int lvl = LVL_WARNING;
95 if (!OPTS_WARN(warntype))
102 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
108 /**********************************************************************
109 * some maths used for constant folding
112 vector vec3_add(vector a, vector b)
121 vector vec3_sub(vector a, vector b)
130 qcfloat vec3_mulvv(vector a, vector b)
132 return (a.x * b.x + a.y * b.y + a.z * b.z);
135 vector vec3_mulvf(vector a, float b)
144 /**********************************************************************
148 bool parser_next(parser_t *parser)
150 /* lex_do kills the previous token */
151 parser->tok = lex_do(parser->lex);
152 if (parser->tok == TOKEN_EOF)
154 if (parser->tok >= TOKEN_ERROR) {
155 parseerror(parser, "lex error");
161 #define parser_tokval(p) ((p)->lex->tok.value)
162 #define parser_token(p) (&((p)->lex->tok))
163 #define parser_ctx(p) ((p)->lex->tok.ctx)
165 static ast_value* parser_const_float(parser_t *parser, double d)
169 for (i = 0; i < vec_size(parser->imm_float); ++i) {
170 if ((double)(parser->imm_float[i]->constval.vfloat) == d)
171 return parser->imm_float[i];
173 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
175 out->constval.vfloat = d;
176 vec_push(parser->imm_float, out);
180 static ast_value* parser_const_float_0(parser_t *parser)
182 if (!parser->imm_float_zero)
183 parser->imm_float_zero = parser_const_float(parser, 0);
184 return parser->imm_float_zero;
187 static char *parser_strdup(const char *str)
190 /* actually dup empty strings */
191 char *out = mem_a(1);
195 return util_strdup(str);
198 static ast_value* parser_const_string(parser_t *parser, const char *str)
202 for (i = 0; i < vec_size(parser->imm_string); ++i) {
203 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
204 return parser->imm_string[i];
206 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
208 out->constval.vstring = parser_strdup(str);
209 vec_push(parser->imm_string, out);
213 static ast_value* parser_const_vector(parser_t *parser, vector v)
217 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
218 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
219 return parser->imm_vector[i];
221 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
223 out->constval.vvec = v;
224 vec_push(parser->imm_vector, out);
228 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
234 return parser_const_vector(parser, v);
237 static ast_value* parser_const_vector_0(parser_t *parser)
239 if (!parser->imm_vector_zero)
240 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
241 return parser->imm_vector_zero;
244 static ast_expression* parser_find_field(parser_t *parser, const char *name)
247 for (i = 0; i < vec_size(parser->fields); ++i) {
248 if (!strcmp(parser->fields[i].name, name))
249 return parser->fields[i].var;
254 static ast_expression* parser_find_global(parser_t *parser, const char *name)
257 for (i = 0; i < vec_size(parser->globals); ++i) {
258 if (!strcmp(parser->globals[i].name, name))
259 return parser->globals[i].var;
264 static ast_expression* parser_find_param(parser_t *parser, const char *name)
268 if (!parser->function)
270 fun = parser->function->vtype;
271 for (i = 0; i < vec_size(fun->expression.params); ++i) {
272 if (!strcmp(fun->expression.params[i]->name, name))
273 return (ast_expression*)(fun->expression.params[i]);
278 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
282 for (i = vec_size(parser->locals); i > upto;) {
284 if (!strcmp(parser->locals[i].name, name))
285 return parser->locals[i].var;
288 return parser_find_param(parser, name);
291 static ast_expression* parser_find_var(parser_t *parser, const char *name)
295 v = parser_find_local(parser, name, 0, &dummy);
296 if (!v) v = parser_find_global(parser, name);
302 size_t etype; /* 0 = expression, others are operators */
306 ast_block *block; /* for commas and function calls */
315 #define SY_PAREN_EXPR '('
316 #define SY_PAREN_FUNC 'f'
317 #define SY_PAREN_INDEX '['
319 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
330 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
334 e.out = (ast_expression*)v;
341 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
343 e.etype = 1 + (op - operators);
352 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
364 # define DEBUGSHUNTDO(x) x
366 # define DEBUGSHUNTDO(x)
369 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
370 * so we need to rotate it to become ent.(foo[n]).
372 static bool rotate_entfield_array_index_nodes(ast_expression **out)
374 ast_array_index *index;
375 ast_entfield *entfield;
379 ast_expression *entity;
381 lex_ctx ctx = ast_ctx(*out);
383 if (!ast_istype(*out, ast_array_index))
385 index = (ast_array_index*)*out;
387 if (!ast_istype(index->array, ast_entfield))
389 entfield = (ast_entfield*)index->array;
391 if (!ast_istype(entfield->field, ast_value))
393 field = (ast_value*)entfield->field;
396 entity = entfield->entity;
400 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
401 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
402 *out = (ast_expression*)entfield;
407 static bool parser_sy_pop(parser_t *parser, shunt *sy)
411 ast_expression *out = NULL;
412 ast_expression *exprs[3];
413 ast_block *blocks[3];
414 ast_value *asvalue[3];
416 qcint generated_op = 0;
421 if (!vec_size(sy->ops)) {
422 parseerror(parser, "internal error: missing operator");
426 if (vec_last(sy->ops).paren) {
427 parseerror(parser, "unmatched parenthesis");
431 op = &operators[vec_last(sy->ops).etype - 1];
432 ctx = vec_last(sy->ops).ctx;
434 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
436 if (vec_size(sy->out) < op->operands) {
437 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
438 op->op, (int)op->id);
442 vec_shrinkby(sy->ops, 1);
444 vec_shrinkby(sy->out, op->operands);
445 for (i = 0; i < op->operands; ++i) {
446 exprs[i] = sy->out[vec_size(sy->out)+i].out;
447 blocks[i] = sy->out[vec_size(sy->out)+i].block;
448 asvalue[i] = (ast_value*)exprs[i];
451 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
452 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
456 #define NotSameType(T) \
457 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
458 exprs[0]->expression.vtype != T)
459 #define CanConstFold1(A) \
460 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
461 #define CanConstFold(A, B) \
462 (CanConstFold1(A) && CanConstFold1(B))
463 #define ConstV(i) (asvalue[(i)]->constval.vvec)
464 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
465 #define ConstS(i) (asvalue[(i)]->constval.vstring)
469 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
473 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
474 if (exprs[1]->expression.vtype != TYPE_FIELD) {
475 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
478 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
480 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
481 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
485 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
491 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
492 !(exprs[0]->expression.vtype == TYPE_FIELD &&
493 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
495 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
496 parseerror(parser, "cannot index value of type %s", ty1);
499 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
500 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
501 parseerror(parser, "index must be of type float, not %s", ty1);
504 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
505 if (rotate_entfield_array_index_nodes(&out))
507 if (opts_standard != COMPILER_GMQCC) {
508 /* this error doesn't need to make us bail out */
509 (void)!parsewarning(parser, WARN_EXTENSIONS,
510 "accessing array-field members of an entity without parenthesis\n"
511 " -> this is an extension from -std=gmqcc");
518 vec_push(blocks[0]->exprs, exprs[1]);
520 blocks[0] = ast_block_new(ctx);
521 vec_push(blocks[0]->exprs, exprs[0]);
522 vec_push(blocks[0]->exprs, exprs[1]);
524 if (!ast_block_set_type(blocks[0], exprs[1]))
527 vec_push(sy->out, syblock(ctx, blocks[0]));
531 switch (exprs[0]->expression.vtype) {
533 if (CanConstFold1(exprs[0]))
534 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
536 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
537 (ast_expression*)parser_const_float_0(parser),
541 if (CanConstFold1(exprs[0]))
542 out = (ast_expression*)parser_const_vector_f(parser,
543 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
545 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
546 (ast_expression*)parser_const_vector_0(parser),
550 parseerror(parser, "invalid types used in expression: cannot negate type %s",
551 type_name[exprs[0]->expression.vtype]);
557 switch (exprs[0]->expression.vtype) {
559 if (CanConstFold1(exprs[0]))
560 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
562 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
565 if (CanConstFold1(exprs[0]))
566 out = (ast_expression*)parser_const_float(parser,
567 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
569 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
572 if (CanConstFold1(exprs[0]))
573 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
575 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
577 /* we don't constant-fold NOT for these types */
579 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
582 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
585 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
586 type_name[exprs[0]->expression.vtype]);
592 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
593 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
595 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
596 type_name[exprs[0]->expression.vtype],
597 type_name[exprs[1]->expression.vtype]);
600 switch (exprs[0]->expression.vtype) {
602 if (CanConstFold(exprs[0], exprs[1]))
604 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
607 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
610 if (CanConstFold(exprs[0], exprs[1]))
611 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
613 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
616 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
617 type_name[exprs[0]->expression.vtype],
618 type_name[exprs[1]->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 subtract type %s from %s",
627 type_name[exprs[1]->expression.vtype],
628 type_name[exprs[0]->expression.vtype]);
631 switch (exprs[0]->expression.vtype) {
633 if (CanConstFold(exprs[0], exprs[1]))
634 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
636 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
639 if (CanConstFold(exprs[0], exprs[1]))
640 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
642 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
645 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
646 type_name[exprs[1]->expression.vtype],
647 type_name[exprs[0]->expression.vtype]);
652 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
653 exprs[0]->expression.vtype != TYPE_VECTOR &&
654 exprs[0]->expression.vtype != TYPE_FLOAT &&
655 exprs[1]->expression.vtype != TYPE_VECTOR &&
656 exprs[1]->expression.vtype != TYPE_FLOAT)
658 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
659 type_name[exprs[1]->expression.vtype],
660 type_name[exprs[0]->expression.vtype]);
663 switch (exprs[0]->expression.vtype) {
665 if (exprs[1]->expression.vtype == TYPE_VECTOR)
667 if (CanConstFold(exprs[0], exprs[1]))
668 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
670 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
674 if (CanConstFold(exprs[0], exprs[1]))
675 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
677 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
681 if (exprs[1]->expression.vtype == TYPE_FLOAT)
683 if (CanConstFold(exprs[0], exprs[1]))
684 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
686 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
690 if (CanConstFold(exprs[0], exprs[1]))
691 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
693 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
697 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
698 type_name[exprs[1]->expression.vtype],
699 type_name[exprs[0]->expression.vtype]);
704 if (NotSameType(TYPE_FLOAT)) {
705 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
706 type_name[exprs[0]->expression.vtype],
707 type_name[exprs[1]->expression.vtype]);
710 if (CanConstFold(exprs[0], exprs[1]))
711 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
713 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
717 parseerror(parser, "qc does not have a modulo operator");
721 if (NotSameType(TYPE_FLOAT)) {
722 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
723 type_name[exprs[0]->expression.vtype],
724 type_name[exprs[1]->expression.vtype]);
727 if (CanConstFold(exprs[0], exprs[1]))
728 out = (ast_expression*)parser_const_float(parser,
729 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
730 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
732 out = (ast_expression*)ast_binary_new(ctx,
733 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
737 parseerror(parser, "TODO: bitxor");
742 case opid3('<','<','='):
743 case opid3('>','>','='):
744 parseerror(parser, "TODO: shifts");
748 generated_op += 1; /* INSTR_OR */
750 generated_op += INSTR_AND;
751 if (NotSameType(TYPE_FLOAT)) {
752 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
753 type_name[exprs[0]->expression.vtype],
754 type_name[exprs[1]->expression.vtype]);
755 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
756 parseerror(parser, "TODO: optional early out");
759 if (opts_standard == COMPILER_GMQCC)
760 con_out("TODO: early out logic\n");
761 if (CanConstFold(exprs[0], exprs[1]))
762 out = (ast_expression*)parser_const_float(parser,
763 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
765 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
769 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
770 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
771 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
772 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
775 if (CanConstFold1(exprs[0]))
776 out = (ConstF(0) ? exprs[1] : exprs[2]);
778 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
782 generated_op += 1; /* INSTR_GT */
784 generated_op += 1; /* INSTR_LT */
785 case opid2('>', '='):
786 generated_op += 1; /* INSTR_GE */
787 case opid2('<', '='):
788 generated_op += INSTR_LE;
789 if (NotSameType(TYPE_FLOAT)) {
790 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
791 type_name[exprs[0]->expression.vtype],
792 type_name[exprs[1]->expression.vtype]);
795 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
797 case opid2('!', '='):
798 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
799 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
800 type_name[exprs[0]->expression.vtype],
801 type_name[exprs[1]->expression.vtype]);
804 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
806 case opid2('=', '='):
807 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
808 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
809 type_name[exprs[0]->expression.vtype],
810 type_name[exprs[1]->expression.vtype]);
813 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
817 if (ast_istype(exprs[0], ast_entfield)) {
818 ast_expression *field = ((ast_entfield*)exprs[0])->field;
819 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
820 exprs[0]->expression.vtype == TYPE_FIELD &&
821 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
823 assignop = type_storep_instr[TYPE_VECTOR];
826 assignop = type_storep_instr[exprs[0]->expression.vtype];
827 if (!ast_compare_type(field->expression.next, exprs[1])) {
828 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
829 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
830 if (opts_standard == COMPILER_QCC &&
831 field->expression.next->expression.vtype == TYPE_FUNCTION &&
832 exprs[1]->expression.vtype == TYPE_FUNCTION)
834 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
835 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
841 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
846 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
847 exprs[0]->expression.vtype == TYPE_FIELD &&
848 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
850 assignop = type_store_instr[TYPE_VECTOR];
853 assignop = type_store_instr[exprs[0]->expression.vtype];
856 if (assignop == AINSTR_END) {
857 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
858 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
859 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
861 else if (!ast_compare_type(exprs[0], exprs[1])) {
862 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
863 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
864 if (opts_standard == COMPILER_QCC &&
865 exprs[0]->expression.vtype == TYPE_FUNCTION &&
866 exprs[1]->expression.vtype == TYPE_FUNCTION)
868 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
869 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
875 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
878 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
882 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
883 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
885 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
886 type_name[exprs[0]->expression.vtype],
887 type_name[exprs[1]->expression.vtype]);
890 if (ast_istype(exprs[0], ast_entfield))
891 assignop = type_storep_instr[exprs[0]->expression.vtype];
893 assignop = type_store_instr[exprs[0]->expression.vtype];
894 switch (exprs[0]->expression.vtype) {
896 out = (ast_expression*)ast_binstore_new(ctx, assignop,
897 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
901 out = (ast_expression*)ast_binstore_new(ctx, assignop,
902 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
906 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
907 type_name[exprs[0]->expression.vtype],
908 type_name[exprs[1]->expression.vtype]);
916 parseerror(parser, "failed to apply operand %s", op->op);
920 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
921 vec_push(sy->out, syexp(ctx, out));
925 static bool parser_close_call(parser_t *parser, shunt *sy)
927 /* was a function call */
934 vec_shrinkby(sy->ops, 1);
935 fid = sy->ops[vec_size(sy->ops)].off;
937 /* out[fid] is the function
938 * everything above is parameters...
940 * 1 params = ast_expression
944 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
945 parseerror(parser, "internal error: function call needs function and parameter list...");
949 fun = sy->out[fid].out;
951 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
953 parseerror(parser, "out of memory");
957 if (fid+1 == vec_size(sy->out)) {
960 } else if (fid+2 == vec_size(sy->out)) {
962 vec_shrinkby(sy->out, 1);
963 params = sy->out[vec_size(sy->out)].block;
967 vec_push(call->params, sy->out[vec_size(sy->out)].out);
969 paramcount = vec_size(params->exprs);
970 call->params = params->exprs;
971 params->exprs = NULL;
974 if (!ast_call_check_types(call))
977 parseerror(parser, "invalid function call");
981 /* overwrite fid, the function, with a call */
982 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
984 if (fun->expression.vtype != TYPE_FUNCTION) {
985 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
989 if (!fun->expression.next) {
990 parseerror(parser, "could not determine function return type");
993 if (vec_size(fun->expression.params) != paramcount &&
994 !(fun->expression.variadic &&
995 vec_size(fun->expression.params) < paramcount))
998 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1000 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1001 if (opts_standard == COMPILER_GMQCC)
1004 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1005 " -> `%s` has been declared here: %s:%i",
1006 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1007 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1009 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1010 " -> `%s` has been declared here: %s:%i",
1011 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1012 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1018 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1019 "too %s parameters for call to %s: expected %i, got %i\n"
1020 " -> `%s` has been declared here: %s:%i",
1021 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1022 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1024 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1025 "too %s parameters for function call: expected %i, got %i\n"
1026 " -> `%s` has been declared here: %s:%i",
1027 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1028 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1036 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1038 if (!vec_size(sy->ops)) {
1039 parseerror(parser, "unmatched closing paren");
1042 /* this would for bit a + (x) because there are no operators inside (x)
1043 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1044 parseerror(parser, "empty parenthesis expression");
1048 while (vec_size(sy->ops)) {
1049 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1050 if (!parser_close_call(parser, sy))
1054 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1055 vec_shrinkby(sy->ops, 1);
1056 return !functions_only;
1058 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1061 /* pop off the parenthesis */
1062 vec_shrinkby(sy->ops, 1);
1063 /* then apply the index operator */
1064 if (!parser_sy_pop(parser, sy))
1068 if (!parser_sy_pop(parser, sy))
1074 static void parser_reclassify_token(parser_t *parser)
1077 for (i = 0; i < operator_count; ++i) {
1078 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1079 parser->tok = TOKEN_OPERATOR;
1085 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1087 ast_expression *expr = NULL;
1089 bool wantop = false;
1090 bool gotmemberof = false;
1092 /* count the parens because an if starts with one, so the
1093 * end of a condition is an unmatched closing paren
1101 parser->lex->flags.noops = false;
1103 parser_reclassify_token(parser);
1108 gotmemberof = false;
1110 parser->memberof = 0;
1112 if (parser->tok == TOKEN_IDENT)
1114 ast_expression *var;
1116 parseerror(parser, "expected operator or end of statement");
1121 if (opts_standard == COMPILER_GMQCC)
1123 if (parser->memberof == TYPE_ENTITY) {
1124 /* still get vars first since there could be a fieldpointer */
1125 var = parser_find_var(parser, parser_tokval(parser));
1127 var = parser_find_field(parser, parser_tokval(parser));
1129 else if (parser->memberof == TYPE_VECTOR)
1131 parseerror(parser, "TODO: implement effective vector member access");
1134 else if (parser->memberof) {
1135 parseerror(parser, "namespace for member not found");
1139 var = parser_find_var(parser, parser_tokval(parser));
1141 var = parser_find_var(parser, parser_tokval(parser));
1143 var = parser_find_field(parser, parser_tokval(parser));
1146 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1149 if (ast_istype(var, ast_value))
1150 ((ast_value*)var)->uses++;
1151 vec_push(sy.out, syexp(parser_ctx(parser), var));
1152 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1154 else if (parser->tok == TOKEN_FLOATCONST) {
1157 parseerror(parser, "expected operator or end of statement, got constant");
1161 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1164 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1165 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1167 else if (parser->tok == TOKEN_INTCONST) {
1170 parseerror(parser, "expected operator or end of statement, got constant");
1174 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1177 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1178 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1180 else if (parser->tok == TOKEN_STRINGCONST) {
1183 parseerror(parser, "expected operator or end of statement, got constant");
1187 val = parser_const_string(parser, parser_tokval(parser));
1190 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1191 DEBUGSHUNTDO(con_out("push string\n"));
1193 else if (parser->tok == TOKEN_VECTORCONST) {
1196 parseerror(parser, "expected operator or end of statement, got constant");
1200 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1203 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1204 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1205 parser_token(parser)->constval.v.x,
1206 parser_token(parser)->constval.v.y,
1207 parser_token(parser)->constval.v.z));
1209 else if (parser->tok == '(') {
1210 parseerror(parser, "internal error: '(' should be classified as operator");
1213 else if (parser->tok == '[') {
1214 parseerror(parser, "internal error: '[' should be classified as operator");
1217 else if (parser->tok == ')') {
1219 DEBUGSHUNTDO(con_out("do[op] )\n"));
1223 /* we do expect an operator next */
1224 /* closing an opening paren */
1225 if (!parser_close_paren(parser, &sy, false))
1228 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1232 /* allowed for function calls */
1233 if (!parser_close_paren(parser, &sy, true))
1238 else if (parser->tok == ']') {
1240 parseerror(parser, "operand expected");
1244 if (!parser_close_paren(parser, &sy, false))
1248 else if (parser->tok != TOKEN_OPERATOR) {
1250 parseerror(parser, "expected operator or end of statement");
1257 /* classify the operator */
1258 /* TODO: suffix operators */
1259 const oper_info *op;
1260 const oper_info *olast = NULL;
1262 for (o = 0; o < operator_count; ++o) {
1263 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1264 !(operators[o].flags & OP_SUFFIX) && /* remove this */
1265 !strcmp(parser_tokval(parser), operators[o].op))
1270 if (o == operator_count) {
1271 /* no operator found... must be the end of the statement */
1274 /* found an operator */
1277 /* when declaring variables, a comma starts a new variable */
1278 if (op->id == opid1(',') && !parens && stopatcomma) {
1279 /* fixup the token */
1284 /* a colon without a pervious question mark cannot be a ternary */
1285 if (!ternaries && op->id == opid2(':','?')) {
1290 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1291 olast = &operators[vec_last(sy.ops).etype-1];
1294 (op->prec < olast->prec) ||
1295 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1297 if (!parser_sy_pop(parser, &sy))
1299 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1300 olast = &operators[vec_last(sy.ops).etype-1];
1305 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1306 /* for gmqcc standard: open up the namespace of the previous type */
1307 ast_expression *prevex = vec_last(sy.out).out;
1309 parseerror(parser, "unexpected member operator");
1312 if (prevex->expression.vtype == TYPE_ENTITY)
1313 parser->memberof = TYPE_ENTITY;
1314 else if (prevex->expression.vtype == TYPE_VECTOR)
1315 parser->memberof = TYPE_VECTOR;
1317 parseerror(parser, "type error: type has no members");
1323 if (op->id == opid1('(')) {
1325 size_t sycount = vec_size(sy.out);
1326 DEBUGSHUNTDO(con_out("push [op] (\n"));
1328 /* we expected an operator, this is the function-call operator */
1329 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1332 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1333 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1336 } else if (op->id == opid1('[')) {
1338 parseerror(parser, "unexpected array subscript");
1342 /* push both the operator and the paren, this makes life easier */
1343 vec_push(sy.ops, syop(parser_ctx(parser), op));
1344 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1346 } else if (op->id == opid2('?',':')) {
1348 vec_push(sy.ops, syop(parser_ctx(parser), op));
1351 } else if (op->id == opid2(':','?')) {
1352 /* we don't push this operator */
1356 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1357 vec_push(sy.ops, syop(parser_ctx(parser), op));
1361 if (!parser_next(parser)) {
1364 if (parser->tok == ';' ||
1365 (!parens && parser->tok == ']'))
1371 while (vec_size(sy.ops)) {
1372 if (!parser_sy_pop(parser, &sy))
1376 parser->lex->flags.noops = true;
1377 if (!vec_size(sy.out)) {
1378 parseerror(parser, "empty expression");
1381 expr = sy.out[0].out;
1384 DEBUGSHUNTDO(con_out("shunt done\n"));
1388 parser->lex->flags.noops = true;
1394 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1396 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1399 if (!parser_next(parser)) {
1406 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1409 ast_expression *cond, *ontrue, *onfalse = NULL;
1412 lex_ctx ctx = parser_ctx(parser);
1414 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1415 if (!parser_next(parser)) {
1416 parseerror(parser, "expected condition or 'not'");
1419 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1421 if (!parser_next(parser)) {
1422 parseerror(parser, "expected condition in parenthesis");
1426 if (parser->tok != '(') {
1427 parseerror(parser, "expected 'if' condition in parenthesis");
1430 /* parse into the expression */
1431 if (!parser_next(parser)) {
1432 parseerror(parser, "expected 'if' condition after opening paren");
1435 /* parse the condition */
1436 cond = parse_expression_leave(parser, false);
1440 if (parser->tok != ')') {
1441 parseerror(parser, "expected closing paren after 'if' condition");
1445 /* parse into the 'then' branch */
1446 if (!parser_next(parser)) {
1447 parseerror(parser, "expected statement for on-true branch of 'if'");
1451 ontrue = parse_statement_or_block(parser);
1456 /* check for an else */
1457 if (!strcmp(parser_tokval(parser), "else")) {
1458 /* parse into the 'else' branch */
1459 if (!parser_next(parser)) {
1460 parseerror(parser, "expected on-false branch after 'else'");
1465 onfalse = parse_statement_or_block(parser);
1474 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1476 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1477 *out = (ast_expression*)ifthen;
1481 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1484 ast_expression *cond, *ontrue;
1486 lex_ctx ctx = parser_ctx(parser);
1488 /* skip the 'while' and check for opening paren */
1489 if (!parser_next(parser) || parser->tok != '(') {
1490 parseerror(parser, "expected 'while' condition in parenthesis");
1493 /* parse into the expression */
1494 if (!parser_next(parser)) {
1495 parseerror(parser, "expected 'while' condition after opening paren");
1498 /* parse the condition */
1499 cond = parse_expression_leave(parser, false);
1503 if (parser->tok != ')') {
1504 parseerror(parser, "expected closing paren after 'while' condition");
1508 /* parse into the 'then' branch */
1509 if (!parser_next(parser)) {
1510 parseerror(parser, "expected while-loop body");
1514 ontrue = parse_statement_or_block(parser);
1520 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1521 *out = (ast_expression*)aloop;
1525 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1528 ast_expression *cond, *ontrue;
1530 lex_ctx ctx = parser_ctx(parser);
1532 /* skip the 'do' and get the body */
1533 if (!parser_next(parser)) {
1534 parseerror(parser, "expected loop body");
1537 ontrue = parse_statement_or_block(parser);
1541 /* expect the "while" */
1542 if (parser->tok != TOKEN_KEYWORD ||
1543 strcmp(parser_tokval(parser), "while"))
1545 parseerror(parser, "expected 'while' and condition");
1550 /* skip the 'while' and check for opening paren */
1551 if (!parser_next(parser) || parser->tok != '(') {
1552 parseerror(parser, "expected 'while' condition in parenthesis");
1556 /* parse into the expression */
1557 if (!parser_next(parser)) {
1558 parseerror(parser, "expected 'while' condition after opening paren");
1562 /* parse the condition */
1563 cond = parse_expression_leave(parser, false);
1567 if (parser->tok != ')') {
1568 parseerror(parser, "expected closing paren after 'while' condition");
1574 if (!parser_next(parser) || parser->tok != ';') {
1575 parseerror(parser, "expected semicolon after condition");
1581 if (!parser_next(parser)) {
1582 parseerror(parser, "parse error");
1588 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1589 *out = (ast_expression*)aloop;
1593 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1596 ast_expression *initexpr, *cond, *increment, *ontrue;
1597 size_t oldblocklocal;
1600 lex_ctx ctx = parser_ctx(parser);
1602 oldblocklocal = parser->blocklocal;
1603 parser->blocklocal = vec_size(parser->locals);
1610 /* skip the 'while' and check for opening paren */
1611 if (!parser_next(parser) || parser->tok != '(') {
1612 parseerror(parser, "expected 'for' expressions in parenthesis");
1615 /* parse into the expression */
1616 if (!parser_next(parser)) {
1617 parseerror(parser, "expected 'for' initializer after opening paren");
1621 if (parser->tok == TOKEN_TYPENAME) {
1622 if (opts_standard != COMPILER_GMQCC) {
1623 if (parsewarning(parser, WARN_EXTENSIONS,
1624 "current standard does not allow variable declarations in for-loop initializers"))
1628 parseerror(parser, "TODO: assignment of new variables to be non-const");
1630 if (!parse_variable(parser, block, true))
1633 else if (parser->tok != ';')
1635 initexpr = parse_expression_leave(parser, false);
1640 /* move on to condition */
1641 if (parser->tok != ';') {
1642 parseerror(parser, "expected semicolon after for-loop initializer");
1645 if (!parser_next(parser)) {
1646 parseerror(parser, "expected for-loop condition");
1650 /* parse the condition */
1651 if (parser->tok != ';') {
1652 cond = parse_expression_leave(parser, false);
1657 /* move on to incrementor */
1658 if (parser->tok != ';') {
1659 parseerror(parser, "expected semicolon after for-loop initializer");
1662 if (!parser_next(parser)) {
1663 parseerror(parser, "expected for-loop condition");
1667 /* parse the incrementor */
1668 if (parser->tok != ')') {
1669 increment = parse_expression_leave(parser, false);
1672 if (!ast_istype(increment, ast_store) &&
1673 !ast_istype(increment, ast_call) &&
1674 !ast_istype(increment, ast_binstore))
1676 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1682 if (parser->tok != ')') {
1683 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1686 /* parse into the 'then' branch */
1687 if (!parser_next(parser)) {
1688 parseerror(parser, "expected for-loop body");
1691 ontrue = parse_statement_or_block(parser);
1696 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1697 *out = (ast_expression*)aloop;
1699 while (vec_size(parser->locals) > parser->blocklocal)
1700 retval = retval && parser_pop_local(parser);
1701 parser->blocklocal = oldblocklocal;
1704 if (initexpr) ast_delete(initexpr);
1705 if (cond) ast_delete(cond);
1706 if (increment) ast_delete(increment);
1707 while (vec_size(parser->locals) > parser->blocklocal)
1708 (void)!parser_pop_local(parser);
1709 parser->blocklocal = oldblocklocal;
1713 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1715 ast_expression *exp = NULL;
1716 ast_return *ret = NULL;
1717 ast_value *expected = parser->function->vtype;
1719 if (!parser_next(parser)) {
1720 parseerror(parser, "expected return expression");
1724 if (parser->tok != ';') {
1725 exp = parse_expression(parser, false);
1729 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1730 parseerror(parser, "return with invalid expression");
1733 ret = ast_return_new(exp->expression.node.context, exp);
1739 if (!parser_next(parser))
1740 parseerror(parser, "parse error");
1741 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1742 if (opts_standard != COMPILER_GMQCC)
1743 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1745 parseerror(parser, "return without value");
1747 ret = ast_return_new(parser_ctx(parser), NULL);
1749 *out = (ast_expression*)ret;
1753 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1755 lex_ctx ctx = parser_ctx(parser);
1757 if (!parser_next(parser) || parser->tok != ';') {
1758 parseerror(parser, "expected semicolon");
1762 if (!parser_next(parser))
1763 parseerror(parser, "parse error");
1765 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1769 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
1771 ast_expression *operand;
1773 ast_switch *switchnode;
1774 ast_switch_case swcase;
1776 lex_ctx ctx = parser_ctx(parser);
1778 /* parse over the opening paren */
1779 if (!parser_next(parser) || parser->tok != '(') {
1780 parseerror(parser, "expected switch operand in parenthesis");
1784 /* parse into the expression */
1785 if (!parser_next(parser)) {
1786 parseerror(parser, "expected switch operand");
1789 /* parse the operand */
1790 operand = parse_expression_leave(parser, false);
1794 if (!OPTS_FLAG(RELAXED_SWITCH)) {
1795 opval = (ast_value*)operand;
1796 if (!ast_istype(operand, ast_value) || !opval->isconst) {
1797 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
1803 switchnode = ast_switch_new(ctx, operand);
1806 if (parser->tok != ')') {
1807 ast_delete(switchnode);
1808 parseerror(parser, "expected closing paren after 'switch' operand");
1812 /* parse over the opening paren */
1813 if (!parser_next(parser) || parser->tok != '{') {
1814 ast_delete(switchnode);
1815 parseerror(parser, "expected list of cases");
1819 if (!parser_next(parser)) {
1820 ast_delete(switchnode);
1821 parseerror(parser, "expected 'case' or 'default'");
1826 while (parser->tok != '}') {
1827 ast_block *caseblock;
1829 if (parser->tok != TOKEN_KEYWORD) {
1830 ast_delete(switchnode);
1831 parseerror(parser, "expected 'case' or 'default'");
1834 if (!strcmp(parser_tokval(parser), "case")) {
1835 if (!parser_next(parser)) {
1836 ast_delete(switchnode);
1837 parseerror(parser, "expected expression for case");
1840 swcase.value = parse_expression_leave(parser, false);
1841 if (!swcase.value) {
1842 ast_delete(switchnode);
1843 parseerror(parser, "expected expression for case");
1847 else if (!strcmp(parser_tokval(parser), "default")) {
1848 swcase.value = NULL;
1849 if (!parser_next(parser)) {
1850 ast_delete(switchnode);
1851 parseerror(parser, "expected colon");
1856 /* Now the colon and body */
1857 if (parser->tok != ':') {
1858 if (swcase.value) ast_unref(swcase.value);
1859 ast_delete(switchnode);
1860 parseerror(parser, "expected colon");
1864 if (!parser_next(parser)) {
1865 if (swcase.value) ast_unref(swcase.value);
1866 ast_delete(switchnode);
1867 parseerror(parser, "expected statements or case");
1870 caseblock = ast_block_new(parser_ctx(parser));
1872 if (swcase.value) ast_unref(swcase.value);
1873 ast_delete(switchnode);
1876 swcase.code = (ast_expression*)caseblock;
1877 vec_push(switchnode->cases, swcase);
1879 ast_expression *expr;
1880 if (parser->tok == '}')
1882 if (parser->tok == TOKEN_KEYWORD) {
1883 if (!strcmp(parser_tokval(parser), "case") ||
1884 !strcmp(parser_tokval(parser), "default"))
1889 if (!parse_statement(parser, caseblock, &expr, true)) {
1890 ast_delete(switchnode);
1895 vec_push(caseblock->exprs, expr);
1900 if (parser->tok != '}') {
1901 ast_delete(switchnode);
1902 parseerror(parser, "expected closing paren of case list");
1905 if (!parser_next(parser)) {
1906 ast_delete(switchnode);
1907 parseerror(parser, "parse error after switch");
1910 *out = (ast_expression*)switchnode;
1914 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
1916 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1918 /* local variable */
1920 parseerror(parser, "cannot declare a variable from here");
1923 if (opts_standard == COMPILER_QCC) {
1924 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1927 if (!parse_variable(parser, block, false))
1932 else if (parser->tok == TOKEN_KEYWORD)
1934 if (!strcmp(parser_tokval(parser), "local"))
1937 parseerror(parser, "cannot declare a local variable here");
1940 if (!parser_next(parser)) {
1941 parseerror(parser, "expected variable declaration");
1944 if (!parse_variable(parser, block, true))
1949 else if (!strcmp(parser_tokval(parser), "return"))
1951 return parse_return(parser, block, out);
1953 else if (!strcmp(parser_tokval(parser), "if"))
1955 return parse_if(parser, block, out);
1957 else if (!strcmp(parser_tokval(parser), "while"))
1959 return parse_while(parser, block, out);
1961 else if (!strcmp(parser_tokval(parser), "do"))
1963 return parse_dowhile(parser, block, out);
1965 else if (!strcmp(parser_tokval(parser), "for"))
1967 if (opts_standard == COMPILER_QCC) {
1968 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1971 return parse_for(parser, block, out);
1973 else if (!strcmp(parser_tokval(parser), "break"))
1975 return parse_break_continue(parser, block, out, false);
1977 else if (!strcmp(parser_tokval(parser), "continue"))
1979 return parse_break_continue(parser, block, out, true);
1981 else if (!strcmp(parser_tokval(parser), "switch"))
1983 return parse_switch(parser, block, out);
1985 else if (!strcmp(parser_tokval(parser), "case") ||
1986 !strcmp(parser_tokval(parser), "default"))
1989 parseerror(parser, "unexpected 'case' label");
1994 parseerror(parser, "Unexpected keyword");
1997 else if (parser->tok == '{')
2000 inner = parse_block(parser, false);
2003 *out = (ast_expression*)inner;
2008 ast_expression *exp = parse_expression(parser, false);
2012 if (!ast_istype(exp, ast_store) &&
2013 !ast_istype(exp, ast_call) &&
2014 !ast_istype(exp, ast_binstore))
2016 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2023 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
2028 ve = &vec_last(parser->locals);
2029 if (!parser->errors) {
2030 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
2031 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
2036 vec_pop(parser->locals);
2040 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2042 size_t oldblocklocal;
2045 oldblocklocal = parser->blocklocal;
2046 parser->blocklocal = vec_size(parser->locals);
2048 if (!parser_next(parser)) { /* skip the '{' */
2049 parseerror(parser, "expected function body");
2053 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2055 ast_expression *expr;
2056 if (parser->tok == '}')
2059 if (!parse_statement(parser, block, &expr, false)) {
2060 /* parseerror(parser, "parse error"); */
2066 vec_push(block->exprs, expr);
2069 if (parser->tok != '}') {
2072 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2074 if (!vec_size(block->exprs) ||
2075 !ast_istype(vec_last(block->exprs), ast_return))
2077 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2083 (void)parser_next(parser);
2087 while (vec_size(parser->locals) > parser->blocklocal)
2088 retval = retval && parser_pop_local(parser);
2089 parser->blocklocal = oldblocklocal;
2093 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2096 block = ast_block_new(parser_ctx(parser));
2099 if (!parse_block_into(parser, block, warnreturn)) {
2100 ast_block_delete(block);
2106 static ast_expression* parse_statement_or_block(parser_t *parser)
2108 ast_expression *expr = NULL;
2109 if (parser->tok == '{')
2110 return (ast_expression*)parse_block(parser, false);
2111 if (!parse_statement(parser, NULL, &expr, false))
2117 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
2120 size_t len = strlen(var->name);
2122 for (i = 0; i < 3; ++i) {
2123 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
2127 ve[i].name = (char*)mem_a(len+3);
2129 ast_delete(ve[i].var);
2133 memcpy(ve[i].name, var->name, len);
2134 ve[i].name[len] = '_';
2135 ve[i].name[len+1] = 'x'+i;
2136 ve[i].name[len+2] = 0;
2145 ast_delete(ve[i].var);
2152 static bool parse_function_body(parser_t *parser, ast_value *var)
2154 ast_block *block = NULL;
2159 ast_expression *framenum = NULL;
2160 ast_expression *nextthink = NULL;
2161 /* None of the following have to be deleted */
2162 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2163 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2164 bool has_frame_think;
2168 has_frame_think = false;
2169 old = parser->function;
2171 if (var->expression.variadic) {
2172 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2173 "variadic function with implementation will not be able to access additional parameters"))
2179 if (parser->tok == '[') {
2180 /* got a frame definition: [ framenum, nextthink ]
2181 * this translates to:
2182 * self.frame = framenum;
2183 * self.nextthink = time + 0.1;
2184 * self.think = nextthink;
2188 fld_think = parser_find_field(parser, "think");
2189 fld_nextthink = parser_find_field(parser, "nextthink");
2190 fld_frame = parser_find_field(parser, "frame");
2191 if (!fld_think || !fld_nextthink || !fld_frame) {
2192 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2193 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2196 gbl_time = parser_find_global(parser, "time");
2197 gbl_self = parser_find_global(parser, "self");
2198 if (!gbl_time || !gbl_self) {
2199 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2200 parseerror(parser, "please declare the following globals: `time`, `self`");
2204 if (!parser_next(parser))
2207 framenum = parse_expression_leave(parser, true);
2209 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2212 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2213 ast_unref(framenum);
2214 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2218 if (parser->tok != ',') {
2219 ast_unref(framenum);
2220 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2221 parseerror(parser, "Got a %i\n", parser->tok);
2225 if (!parser_next(parser)) {
2226 ast_unref(framenum);
2230 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2232 /* qc allows the use of not-yet-declared functions here
2233 * - this automatically creates a prototype */
2235 ast_value *thinkfunc;
2236 ast_expression *functype = fld_think->expression.next;
2238 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2239 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2240 ast_unref(framenum);
2241 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2245 if (!parser_next(parser)) {
2246 ast_unref(framenum);
2247 ast_delete(thinkfunc);
2251 varent.var = (ast_expression*)thinkfunc;
2252 varent.name = util_strdup(thinkfunc->name);
2253 vec_push(parser->globals, varent);
2254 nextthink = (ast_expression*)thinkfunc;
2257 nextthink = parse_expression_leave(parser, true);
2259 ast_unref(framenum);
2260 parseerror(parser, "expected a think-function in [frame,think] notation");
2265 if (!ast_istype(nextthink, ast_value)) {
2266 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2270 if (retval && parser->tok != ']') {
2271 parseerror(parser, "expected closing `]` for [frame,think] notation");
2275 if (retval && !parser_next(parser)) {
2279 if (retval && parser->tok != '{') {
2280 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2285 ast_unref(nextthink);
2286 ast_unref(framenum);
2290 has_frame_think = true;
2293 block = ast_block_new(parser_ctx(parser));
2295 parseerror(parser, "failed to allocate block");
2296 if (has_frame_think) {
2297 ast_unref(nextthink);
2298 ast_unref(framenum);
2303 if (has_frame_think) {
2305 ast_expression *self_frame;
2306 ast_expression *self_nextthink;
2307 ast_expression *self_think;
2308 ast_expression *time_plus_1;
2309 ast_store *store_frame;
2310 ast_store *store_nextthink;
2311 ast_store *store_think;
2313 ctx = parser_ctx(parser);
2314 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2315 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2316 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2318 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2319 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2321 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2322 if (self_frame) ast_delete(self_frame);
2323 if (self_nextthink) ast_delete(self_nextthink);
2324 if (self_think) ast_delete(self_think);
2325 if (time_plus_1) ast_delete(time_plus_1);
2331 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2332 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2333 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2336 ast_delete(self_frame);
2339 if (!store_nextthink) {
2340 ast_delete(self_nextthink);
2344 ast_delete(self_think);
2348 if (store_frame) ast_delete(store_frame);
2349 if (store_nextthink) ast_delete(store_nextthink);
2350 if (store_think) ast_delete(store_think);
2353 vec_push(block->exprs, (ast_expression*)store_frame);
2354 vec_push(block->exprs, (ast_expression*)store_nextthink);
2355 vec_push(block->exprs, (ast_expression*)store_think);
2359 parseerror(parser, "failed to generate code for [frame,think]");
2360 ast_unref(nextthink);
2361 ast_unref(framenum);
2367 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2370 ast_value *param = var->expression.params[parami];
2372 if (param->expression.vtype != TYPE_VECTOR &&
2373 (param->expression.vtype != TYPE_FIELD ||
2374 param->expression.next->expression.vtype != TYPE_VECTOR))
2379 if (!create_vector_members(parser, param, ve)) {
2380 ast_block_delete(block);
2384 for (e = 0; e < 3; ++e) {
2385 vec_push(parser->locals, ve[e]);
2386 ast_block_collect(block, ve[e].var);
2387 ve[e].var = NULL; /* collected */
2391 func = ast_function_new(ast_ctx(var), var->name, var);
2393 parseerror(parser, "failed to allocate function for `%s`", var->name);
2394 ast_block_delete(block);
2397 vec_push(parser->functions, func);
2399 parser->function = func;
2400 if (!parse_block_into(parser, block, true)) {
2401 ast_block_delete(block);
2405 vec_push(func->blocks, block);
2407 parser->function = old;
2408 while (vec_size(parser->locals))
2409 retval = retval && parser_pop_local(parser);
2411 if (parser->tok == ';')
2412 return parser_next(parser);
2413 else if (opts_standard == COMPILER_QCC)
2414 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2418 vec_pop(parser->functions);
2419 ast_function_delete(func);
2420 var->constval.vfunc = NULL;
2423 while (vec_size(parser->locals)) {
2424 mem_d(vec_last(parser->locals).name);
2425 vec_pop(parser->locals);
2427 parser->function = old;
2431 static ast_expression *array_accessor_split(
2436 ast_expression *left,
2437 ast_expression *right
2443 lex_ctx ctx = ast_ctx(array);
2445 if (!left || !right) {
2446 if (left) ast_delete(left);
2447 if (right) ast_delete(right);
2451 cmp = ast_binary_new(ctx, INSTR_LT,
2452 (ast_expression*)index,
2453 (ast_expression*)parser_const_float(parser, middle));
2457 parseerror(parser, "internal error: failed to create comparison for array setter");
2461 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2463 ast_delete(cmp); /* will delete left and right */
2464 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2468 return (ast_expression*)ifthen;
2471 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2473 lex_ctx ctx = ast_ctx(array);
2475 if (from+1 == afterend) {
2479 ast_array_index *subscript;
2480 int assignop = type_store_instr[value->expression.vtype];
2482 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2483 assignop = INSTR_STORE_V;
2485 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2489 ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2491 ast_delete(subscript);
2495 block = ast_block_new(ctx);
2501 vec_push(block->exprs, (ast_expression*)st);
2503 ret = ast_return_new(ctx, NULL);
2509 vec_push(block->exprs, (ast_expression*)ret);
2511 return (ast_expression*)block;
2513 ast_expression *left, *right;
2514 size_t diff = afterend - from;
2515 size_t middle = from + diff/2;
2516 left = array_setter_node(parser, array, index, value, from, middle);
2517 right = array_setter_node(parser, array, index, value, middle, afterend);
2518 return array_accessor_split(parser, array, index, middle, left, right);
2522 static ast_expression *array_field_setter_node(
2531 lex_ctx ctx = ast_ctx(array);
2533 if (from+1 == afterend) {
2537 ast_entfield *entfield;
2538 ast_array_index *subscript;
2539 int assignop = type_storep_instr[value->expression.vtype];
2541 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2542 assignop = INSTR_STOREP_V;
2544 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2548 entfield = ast_entfield_new_force(ctx,
2549 (ast_expression*)entity,
2550 (ast_expression*)subscript,
2551 (ast_expression*)subscript);
2553 ast_delete(subscript);
2557 ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2559 ast_delete(entfield);
2563 block = ast_block_new(ctx);
2569 vec_push(block->exprs, (ast_expression*)st);
2571 ret = ast_return_new(ctx, NULL);
2577 vec_push(block->exprs, (ast_expression*)ret);
2579 return (ast_expression*)block;
2581 ast_expression *left, *right;
2582 size_t diff = afterend - from;
2583 size_t middle = from + diff/2;
2584 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2585 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2586 return array_accessor_split(parser, array, index, middle, left, right);
2590 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2592 lex_ctx ctx = ast_ctx(array);
2594 if (from+1 == afterend) {
2596 ast_array_index *subscript;
2598 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2602 ret = ast_return_new(ctx, (ast_expression*)subscript);
2604 ast_delete(subscript);
2608 return (ast_expression*)ret;
2610 ast_expression *left, *right;
2611 size_t diff = afterend - from;
2612 size_t middle = from + diff/2;
2613 left = array_getter_node(parser, array, index, from, middle);
2614 right = array_getter_node(parser, array, index, middle, afterend);
2615 return array_accessor_split(parser, array, index, middle, left, right);
2619 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2621 ast_function *func = NULL;
2622 ast_value *fval = NULL;
2623 ast_block *body = NULL;
2625 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2627 parseerror(parser, "failed to create accessor function value");
2631 func = ast_function_new(ast_ctx(array), funcname, fval);
2634 parseerror(parser, "failed to create accessor function node");
2638 body = ast_block_new(ast_ctx(array));
2640 parseerror(parser, "failed to create block for array accessor");
2646 vec_push(func->blocks, body);
2649 vec_push(parser->accessors, fval);
2654 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2656 ast_expression *root = NULL;
2657 ast_value *index = NULL;
2658 ast_value *value = NULL;
2662 if (!ast_istype(array->expression.next, ast_value)) {
2663 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2667 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2669 func = fval->constval.vfunc;
2670 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2672 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2673 value = ast_value_copy((ast_value*)array->expression.next);
2675 if (!index || !value) {
2676 parseerror(parser, "failed to create locals for array accessor");
2679 (void)!ast_value_set_name(value, "value"); /* not important */
2680 vec_push(fval->expression.params, index);
2681 vec_push(fval->expression.params, value);
2683 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2685 parseerror(parser, "failed to build accessor search tree");
2689 vec_push(func->blocks[0]->exprs, root);
2690 array->setter = fval;
2693 if (index) ast_delete(index);
2694 if (value) ast_delete(value);
2695 if (root) ast_delete(root);
2701 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2703 ast_expression *root = NULL;
2704 ast_value *entity = NULL;
2705 ast_value *index = NULL;
2706 ast_value *value = NULL;
2710 if (!ast_istype(array->expression.next, ast_value)) {
2711 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2715 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2717 func = fval->constval.vfunc;
2718 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2720 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2721 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2722 value = ast_value_copy((ast_value*)array->expression.next);
2723 if (!entity || !index || !value) {
2724 parseerror(parser, "failed to create locals for array accessor");
2727 (void)!ast_value_set_name(value, "value"); /* not important */
2728 vec_push(fval->expression.params, entity);
2729 vec_push(fval->expression.params, index);
2730 vec_push(fval->expression.params, value);
2732 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2734 parseerror(parser, "failed to build accessor search tree");
2738 vec_push(func->blocks[0]->exprs, root);
2739 array->setter = fval;
2742 if (entity) ast_delete(entity);
2743 if (index) ast_delete(index);
2744 if (value) ast_delete(value);
2745 if (root) ast_delete(root);
2751 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2753 ast_expression *root = NULL;
2754 ast_value *index = NULL;
2758 /* NOTE: checking array->expression.next rather than elemtype since
2759 * for fields elemtype is a temporary fieldtype.
2761 if (!ast_istype(array->expression.next, ast_value)) {
2762 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2766 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2768 func = fval->constval.vfunc;
2769 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2771 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2774 parseerror(parser, "failed to create locals for array accessor");
2777 vec_push(fval->expression.params, index);
2779 root = array_getter_node(parser, array, index, 0, array->expression.count);
2781 parseerror(parser, "failed to build accessor search tree");
2785 vec_push(func->blocks[0]->exprs, root);
2786 array->getter = fval;
2789 if (index) ast_delete(index);
2790 if (root) ast_delete(root);
2796 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2797 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2805 bool variadic = false;
2807 ctx = parser_ctx(parser);
2809 /* for the sake of less code we parse-in in this function */
2810 if (!parser_next(parser)) {
2811 parseerror(parser, "expected parameter list");
2817 /* parse variables until we hit a closing paren */
2818 while (parser->tok != ')') {
2820 /* there must be commas between them */
2821 if (parser->tok != ',') {
2822 parseerror(parser, "expected comma or end of parameter list");
2825 if (!parser_next(parser)) {
2826 parseerror(parser, "expected parameter");
2832 if (parser->tok == TOKEN_DOTS) {
2833 /* '...' indicates a varargs function */
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "expected parameter");
2839 if (parser->tok != ')') {
2840 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2846 /* for anything else just parse a typename */
2847 param = parse_typename(parser, NULL);
2850 vec_push(params, param);
2851 if (param->expression.vtype >= TYPE_VARIANT) {
2852 char typename[1024];
2853 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2854 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2861 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
2862 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
2865 if (!parser_next(parser)) {
2866 parseerror(parser, "parse error after typename");
2870 /* now turn 'var' into a function type */
2871 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2872 fval->expression.next = (ast_expression*)var;
2873 fval->expression.variadic = variadic;
2876 var->expression.params = params;
2883 for (i = 0; i < vec_size(params); ++i)
2884 ast_delete(params[i]);
2889 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2891 ast_expression *cexp;
2892 ast_value *cval, *tmp;
2895 ctx = parser_ctx(parser);
2897 if (!parser_next(parser)) {
2899 parseerror(parser, "expected array-size");
2903 cexp = parse_expression_leave(parser, true);
2905 if (!cexp || !ast_istype(cexp, ast_value)) {
2909 parseerror(parser, "expected array-size as constant positive integer");
2912 cval = (ast_value*)cexp;
2914 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2915 tmp->expression.next = (ast_expression*)var;
2918 if (cval->expression.vtype == TYPE_INTEGER)
2919 tmp->expression.count = cval->constval.vint;
2920 else if (cval->expression.vtype == TYPE_FLOAT)
2921 tmp->expression.count = cval->constval.vfloat;
2925 parseerror(parser, "array-size must be a positive integer constant");
2930 if (parser->tok != ']') {
2932 parseerror(parser, "expected ']' after array-size");
2935 if (!parser_next(parser)) {
2937 parseerror(parser, "error after parsing array size");
2943 /* Parse a complete typename.
2944 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2945 * but when parsing variables separated by comma
2946 * 'storebase' should point to where the base-type should be kept.
2947 * The base type makes up every bit of type information which comes *before* the
2950 * The following will be parsed in its entirety:
2952 * The 'basetype' in this case is 'void()'
2953 * and if there's a comma after it, say:
2955 * then the type-information 'void()' can be stored in 'storebase'
2957 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2959 ast_value *var, *tmp;
2962 const char *name = NULL;
2963 bool isfield = false;
2964 bool wasarray = false;
2966 ctx = parser_ctx(parser);
2968 /* types may start with a dot */
2969 if (parser->tok == '.') {
2971 /* if we parsed a dot we need a typename now */
2972 if (!parser_next(parser)) {
2973 parseerror(parser, "expected typename for field definition");
2976 if (parser->tok != TOKEN_TYPENAME) {
2977 parseerror(parser, "expected typename");
2982 /* generate the basic type value */
2983 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2984 /* do not yet turn into a field - remember:
2985 * .void() foo; is a field too
2986 * .void()() foo; is a function
2990 if (!parser_next(parser)) {
2992 parseerror(parser, "parse error after typename");
2996 /* an opening paren now starts the parameter-list of a function
2997 * this is where original-QC has parameter lists.
2998 * We allow a single parameter list here.
2999 * Much like fteqcc we don't allow `float()() x`
3001 if (parser->tok == '(') {
3002 var = parse_parameter_list(parser, var);
3007 /* store the base if requested */
3009 *storebase = ast_value_copy(var);
3011 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3012 tmp->expression.next = (ast_expression*)*storebase;
3017 /* there may be a name now */
3018 if (parser->tok == TOKEN_IDENT) {
3019 name = util_strdup(parser_tokval(parser));
3021 if (!parser_next(parser)) {
3023 parseerror(parser, "error after variable or field declaration");
3028 /* now this may be an array */
3029 if (parser->tok == '[') {
3031 var = parse_arraysize(parser, var);
3036 /* This is the point where we can turn it into a field */
3038 /* turn it into a field if desired */
3039 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3040 tmp->expression.next = (ast_expression*)var;
3044 /* now there may be function parens again */
3045 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3046 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3047 if (parser->tok == '(' && wasarray)
3048 parseerror(parser, "arrays as part of a return type is not supported");
3049 while (parser->tok == '(') {
3050 var = parse_parameter_list(parser, var);
3059 /* finally name it */
3061 if (!ast_value_set_name(var, name)) {
3063 parseerror(parser, "internal error: failed to set name");
3066 /* free the name, ast_value_set_name duplicates */
3073 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
3077 ast_expression *old;
3081 ast_value *basetype = NULL;
3083 bool isparam = false;
3084 bool isvector = false;
3085 bool cleanvar = true;
3086 bool wasarray = false;
3088 varentry_t varent, ve[3];
3090 /* get the first complete variable */
3091 var = parse_typename(parser, &basetype);
3094 ast_delete(basetype);
3098 memset(&varent, 0, sizeof(varent));
3099 memset(&ve, 0, sizeof(ve));
3105 /* Part 0: finish the type */
3106 if (parser->tok == '(') {
3107 if (opts_standard == COMPILER_QCC)
3108 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3109 var = parse_parameter_list(parser, var);
3115 /* we only allow 1-dimensional arrays */
3116 if (parser->tok == '[') {
3118 var = parse_arraysize(parser, var);
3124 if (parser->tok == '(' && wasarray) {
3125 parseerror(parser, "arrays as part of a return type is not supported");
3126 /* we'll still parse the type completely for now */
3128 /* for functions returning functions */
3129 while (parser->tok == '(') {
3130 if (opts_standard == COMPILER_QCC)
3131 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3132 var = parse_parameter_list(parser, var);
3140 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3141 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3142 * is then filled with the previous definition and the parameter-names replaced.
3145 /* Deal with end_sys_ vars */
3147 if (!strcmp(var->name, "end_sys_globals")) {
3148 parser->crc_globals = vec_size(parser->globals);
3151 else if (!strcmp(var->name, "end_sys_fields")) {
3152 parser->crc_fields = vec_size(parser->fields);
3155 if (was_end && var->expression.vtype == TYPE_FIELD) {
3156 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3157 "global '%s' hint should not be a field",
3158 parser_tokval(parser)))
3165 if (!nofields && var->expression.vtype == TYPE_FIELD)
3167 /* deal with field declarations */
3168 old = parser_find_field(parser, var->name);
3170 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3171 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3180 parseerror(parser, "field `%s` already declared here: %s:%i",
3181 var->name, ast_ctx(old).file, ast_ctx(old).line);
3186 if (opts_standard == COMPILER_QCC &&
3187 (old = parser_find_global(parser, var->name)))
3189 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3190 parseerror(parser, "field `%s` already declared here: %s:%i",
3191 var->name, ast_ctx(old).file, ast_ctx(old).line);
3198 /* deal with other globals */
3199 old = parser_find_global(parser, var->name);
3200 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3202 /* This is a function which had a prototype */
3203 if (!ast_istype(old, ast_value)) {
3204 parseerror(parser, "internal error: prototype is not an ast_value");
3208 proto = (ast_value*)old;
3209 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3210 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3212 ast_ctx(proto).file, ast_ctx(proto).line);
3216 /* we need the new parameter-names */
3217 for (i = 0; i < vec_size(proto->expression.params); ++i)
3218 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3226 parseerror(parser, "global `%s` already declared here: %s:%i",
3227 var->name, ast_ctx(old).file, ast_ctx(old).line);
3231 if (opts_standard == COMPILER_QCC &&
3232 (old = parser_find_field(parser, var->name)))
3234 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3235 parseerror(parser, "global `%s` already declared here: %s:%i",
3236 var->name, ast_ctx(old).file, ast_ctx(old).line);
3243 else /* it's not a global */
3245 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
3246 if (old && !isparam) {
3247 parseerror(parser, "local `%s` already declared here: %s:%i",
3248 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3252 old = parser_find_local(parser, var->name, 0, &isparam);
3253 if (old && isparam) {
3254 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3255 "local `%s` is shadowing a parameter", var->name))
3257 parseerror(parser, "local `%s` already declared here: %s:%i",
3258 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3262 if (opts_standard != COMPILER_GMQCC) {
3271 * Create the global/local, and deal with vector types.
3274 if (var->expression.vtype == TYPE_VECTOR)
3276 else if (var->expression.vtype == TYPE_FIELD &&
3277 var->expression.next->expression.vtype == TYPE_VECTOR)
3281 if (!create_vector_members(parser, var, ve)) {
3287 varent.name = util_strdup(var->name);
3288 varent.var = (ast_expression*)var;
3291 /* deal with global variables, fields, functions */
3292 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3293 vec_push(parser->fields, varent);
3295 for (i = 0; i < 3; ++i)
3296 vec_push(parser->fields, ve[i]);
3300 vec_push(parser->globals, varent);
3302 for (i = 0; i < 3; ++i)
3303 vec_push(parser->globals, ve[i]);
3307 vec_push(parser->locals, varent);
3308 vec_push(localblock->locals, var);
3310 for (i = 0; i < 3; ++i) {
3311 vec_push(parser->locals, ve[i]);
3312 ast_block_collect(localblock, ve[i].var);
3313 ve[i].var = NULL; /* from here it's being collected in the block */
3319 ve[0].name = ve[1].name = ve[2].name = NULL;
3320 ve[0].var = ve[1].var = ve[2].var = NULL;
3326 if (var->expression.vtype == TYPE_ARRAY) {
3328 snprintf(name, sizeof(name), "%s##SET", var->name);
3329 if (!parser_create_array_setter(parser, var, name))
3331 snprintf(name, sizeof(name), "%s##GET", var->name);
3332 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3335 else if (!localblock && !nofields &&
3336 var->expression.vtype == TYPE_FIELD &&
3337 var->expression.next->expression.vtype == TYPE_ARRAY)
3340 ast_expression *telem;
3342 ast_value *array = (ast_value*)var->expression.next;
3344 if (!ast_istype(var->expression.next, ast_value)) {
3345 parseerror(parser, "internal error: field element type must be an ast_value");
3349 snprintf(name, sizeof(name), "%s##SETF", var->name);
3350 if (!parser_create_array_field_setter(parser, array, name))
3353 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3354 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3355 tfield->expression.next = telem;
3356 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3357 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3365 if (parser->tok == ';') {
3366 ast_delete(basetype);
3367 if (!parser_next(parser)) {
3368 parseerror(parser, "error after variable declaration");
3374 if (parser->tok == ',')
3377 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3378 parseerror(parser, "missing comma or semicolon while parsing variables");
3382 if (localblock && opts_standard == COMPILER_QCC) {
3383 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3384 "initializing expression turns variable `%s` into a constant in this standard",
3391 if (parser->tok != '{') {
3392 if (parser->tok != '=') {
3393 parseerror(parser, "missing semicolon or initializer");
3397 if (!parser_next(parser)) {
3398 parseerror(parser, "error parsing initializer");
3402 else if (opts_standard == COMPILER_QCC) {
3403 parseerror(parser, "expected '=' before function body in this standard");
3406 if (parser->tok == '#') {
3410 parseerror(parser, "cannot declare builtins within functions");
3413 if (var->expression.vtype != TYPE_FUNCTION) {
3414 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3417 if (!parser_next(parser)) {
3418 parseerror(parser, "expected builtin number");
3421 if (parser->tok != TOKEN_INTCONST) {
3422 parseerror(parser, "builtin number must be an integer constant");
3425 if (parser_token(parser)->constval.i <= 0) {
3426 parseerror(parser, "builtin number must be an integer greater than zero");
3430 func = ast_function_new(ast_ctx(var), var->name, var);
3432 parseerror(parser, "failed to allocate function for `%s`", var->name);
3435 vec_push(parser->functions, func);
3437 func->builtin = -parser_token(parser)->constval.i;
3439 if (!parser_next(parser)) {
3440 parseerror(parser, "expected comma or semicolon");
3441 ast_function_delete(func);
3442 var->constval.vfunc = NULL;
3446 else if (parser->tok == '{' || parser->tok == '[')
3449 parseerror(parser, "cannot declare functions within functions");
3453 if (!parse_function_body(parser, var))
3455 ast_delete(basetype);
3458 ast_expression *cexp;
3461 cexp = parse_expression_leave(parser, true);
3466 cval = (ast_value*)cexp;
3467 if (!ast_istype(cval, ast_value) || !cval->isconst)
3468 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3471 var->isconst = true;
3472 if (cval->expression.vtype == TYPE_STRING)
3473 var->constval.vstring = parser_strdup(cval->constval.vstring);
3475 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3479 shunt sy = { NULL, NULL };
3480 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3481 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3482 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3483 if (!parser_sy_pop(parser, &sy))
3486 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3487 parseerror(parser, "internal error: leaked operands");
3488 vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3496 if (parser->tok == ',') {
3497 if (!parser_next(parser)) {
3498 parseerror(parser, "expected another variable");
3502 if (parser->tok != TOKEN_IDENT) {
3503 parseerror(parser, "expected another variable");
3506 var = ast_value_copy(basetype);
3508 ast_value_set_name(var, parser_tokval(parser));
3509 if (!parser_next(parser)) {
3510 parseerror(parser, "error parsing variable declaration");
3516 if (parser->tok != ';') {
3517 parseerror(parser, "missing semicolon after variables");
3521 if (!parser_next(parser)) {
3522 parseerror(parser, "parse error after variable declaration");
3526 ast_delete(basetype);
3530 if (cleanvar && var)
3532 ast_delete(basetype);
3536 ast_delete(basetype);
3537 if (cleanvar && var)
3539 if (varent.name) mem_d(varent.name);
3540 if (ve[0].name) mem_d(ve[0].name);
3541 if (ve[1].name) mem_d(ve[1].name);
3542 if (ve[2].name) mem_d(ve[2].name);
3543 if (ve[0].var) mem_d(ve[0].var);
3544 if (ve[1].var) mem_d(ve[1].var);
3545 if (ve[2].var) mem_d(ve[2].var);
3549 static bool parser_global_statement(parser_t *parser)
3551 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3553 return parse_variable(parser, NULL, false);
3555 else if (parser->tok == TOKEN_KEYWORD)
3557 /* handle 'var' and 'const' */
3558 if (!strcmp(parser_tokval(parser), "var")) {
3559 if (!parser_next(parser)) {
3560 parseerror(parser, "expected variable declaration after 'var'");
3563 return parse_variable(parser, NULL, true);
3567 else if (parser->tok == '$')
3569 if (!parser_next(parser)) {
3570 parseerror(parser, "parse error");
3576 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3582 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3584 return util_crc16(old, str, strlen(str));
3587 static void progdefs_crc_file(const char *str)
3589 /* write to progdefs.h here */
3592 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3594 old = progdefs_crc_sum(old, str);
3595 progdefs_crc_file(str);
3599 static void generate_checksum(parser_t *parser)
3601 uint16_t crc = 0xFFFF;
3604 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3605 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3607 progdefs_crc_file("\tint\tpad;\n");
3608 progdefs_crc_file("\tint\tofs_return[3];\n");
3609 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3610 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3611 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3612 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3613 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3614 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3615 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3616 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3618 for (i = 0; i < parser->crc_globals; ++i) {
3619 if (!ast_istype(parser->globals[i].var, ast_value))
3621 switch (parser->globals[i].var->expression.vtype) {
3622 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3623 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3624 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3625 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3627 crc = progdefs_crc_both(crc, "\tint\t");
3630 crc = progdefs_crc_both(crc, parser->globals[i].name);
3631 crc = progdefs_crc_both(crc, ";\n");
3633 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3634 for (i = 0; i < parser->crc_fields; ++i) {
3635 if (!ast_istype(parser->fields[i].var, ast_value))
3637 switch (parser->fields[i].var->expression.next->expression.vtype) {
3638 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3639 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3640 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3641 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3643 crc = progdefs_crc_both(crc, "\tint\t");
3646 crc = progdefs_crc_both(crc, parser->fields[i].name);
3647 crc = progdefs_crc_both(crc, ";\n");
3649 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3654 static parser_t *parser;
3659 parser = (parser_t*)mem_a(sizeof(parser_t));
3663 memset(parser, 0, sizeof(*parser));
3665 for (i = 0; i < operator_count; ++i) {
3666 if (operators[i].id == opid1('=')) {
3667 parser->assign_op = operators+i;
3671 if (!parser->assign_op) {
3672 printf("internal error: initializing parser: failed to find assign operator\n");
3679 bool parser_compile()
3681 /* initial lexer/parser state */
3682 parser->lex->flags.noops = true;
3684 if (parser_next(parser))
3686 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3688 if (!parser_global_statement(parser)) {
3689 if (parser->tok == TOKEN_EOF)
3690 parseerror(parser, "unexpected eof");
3691 else if (!parser->errors)
3692 parseerror(parser, "there have been errors, bailing out");
3693 lex_close(parser->lex);
3699 parseerror(parser, "parse error");
3700 lex_close(parser->lex);
3705 lex_close(parser->lex);
3708 return !parser->errors;
3711 bool parser_compile_file(const char *filename)
3713 parser->lex = lex_open(filename);
3715 con_err("failed to open file \"%s\"\n", filename);
3718 return parser_compile();
3721 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3723 parser->lex = lex_open_string(str, len, name);
3725 con_err("failed to create lexer for string \"%s\"\n", name);
3728 return parser_compile();
3731 bool parser_compile_string(const char *name, const char *str)
3733 parser->lex = lex_open_string(str, strlen(str), name);
3735 con_err("failed to create lexer for string \"%s\"\n", name);
3738 return parser_compile();
3741 void parser_cleanup()
3744 for (i = 0; i < vec_size(parser->accessors); ++i) {
3745 ast_delete(parser->accessors[i]->constval.vfunc);
3746 parser->accessors[i]->constval.vfunc = NULL;
3747 ast_delete(parser->accessors[i]);
3749 for (i = 0; i < vec_size(parser->functions); ++i) {
3750 ast_delete(parser->functions[i]);
3752 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3753 ast_delete(parser->imm_vector[i]);
3755 for (i = 0; i < vec_size(parser->imm_string); ++i) {
3756 ast_delete(parser->imm_string[i]);
3758 for (i = 0; i < vec_size(parser->imm_float); ++i) {
3759 ast_delete(parser->imm_float[i]);
3761 for (i = 0; i < vec_size(parser->fields); ++i) {
3762 ast_delete(parser->fields[i].var);
3763 mem_d(parser->fields[i].name);
3765 for (i = 0; i < vec_size(parser->globals); ++i) {
3766 ast_delete(parser->globals[i].var);
3767 mem_d(parser->globals[i].name);
3769 vec_free(parser->accessors);
3770 vec_free(parser->functions);
3771 vec_free(parser->imm_vector);
3772 vec_free(parser->imm_string);
3773 vec_free(parser->imm_float);
3774 vec_free(parser->globals);
3775 vec_free(parser->fields);
3776 vec_free(parser->locals);
3781 bool parser_finish(const char *output)
3787 if (!parser->errors)
3789 ir = ir_builder_new("gmqcc_out");
3791 con_out("failed to allocate builder\n");
3795 for (i = 0; i < vec_size(parser->fields); ++i) {
3798 if (!ast_istype(parser->fields[i].var, ast_value))
3800 field = (ast_value*)parser->fields[i].var;
3801 isconst = field->isconst;
3802 field->isconst = false;
3803 if (!ast_global_codegen((ast_value*)field, ir, true)) {
3804 con_out("failed to generate field %s\n", field->name);
3805 ir_builder_delete(ir);
3810 ast_expression *subtype;
3811 field->isconst = true;
3812 subtype = field->expression.next;
3813 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3814 if (subtype->expression.vtype == TYPE_FIELD)
3815 ifld->fieldtype = subtype->expression.next->expression.vtype;
3816 else if (subtype->expression.vtype == TYPE_FUNCTION)
3817 ifld->outtype = subtype->expression.next->expression.vtype;
3818 (void)!ir_value_set_field(field->ir_v, ifld);
3821 for (i = 0; i < vec_size(parser->globals); ++i) {
3823 if (!ast_istype(parser->globals[i].var, ast_value))
3825 asvalue = (ast_value*)(parser->globals[i].var);
3826 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3827 if (strcmp(asvalue->name, "end_sys_globals") &&
3828 strcmp(asvalue->name, "end_sys_fields"))
3830 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3831 "unused global: `%s`", asvalue->name);
3834 if (!ast_global_codegen(asvalue, ir, false)) {
3835 con_out("failed to generate global %s\n", parser->globals[i].name);
3836 ir_builder_delete(ir);
3840 for (i = 0; i < vec_size(parser->imm_float); ++i) {
3841 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3842 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
3843 ir_builder_delete(ir);
3847 for (i = 0; i < vec_size(parser->imm_string); ++i) {
3848 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3849 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
3850 ir_builder_delete(ir);
3854 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3855 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3856 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
3857 ir_builder_delete(ir);
3861 for (i = 0; i < vec_size(parser->globals); ++i) {
3863 if (!ast_istype(parser->globals[i].var, ast_value))
3865 asvalue = (ast_value*)(parser->globals[i].var);
3866 if (asvalue->setter) {
3867 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3868 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3869 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3871 printf("failed to generate setter for %s\n", parser->globals[i].name);
3872 ir_builder_delete(ir);
3876 if (asvalue->getter) {
3877 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3878 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3879 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3881 printf("failed to generate getter for %s\n", parser->globals[i].name);
3882 ir_builder_delete(ir);
3887 for (i = 0; i < vec_size(parser->fields); ++i) {
3889 asvalue = (ast_value*)(parser->fields[i].var->expression.next);
3891 if (!ast_istype((ast_expression*)asvalue, ast_value))
3893 if (asvalue->expression.vtype != TYPE_ARRAY)
3895 if (asvalue->setter) {
3896 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3897 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
3898 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
3900 printf("failed to generate setter for %s\n", parser->fields[i].name);
3901 ir_builder_delete(ir);
3905 if (asvalue->getter) {
3906 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3907 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
3908 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
3910 printf("failed to generate getter for %s\n", parser->fields[i].name);
3911 ir_builder_delete(ir);
3916 for (i = 0; i < vec_size(parser->functions); ++i) {
3917 if (!ast_function_codegen(parser->functions[i], ir)) {
3918 con_out("failed to generate function %s\n", parser->functions[i]->name);
3919 ir_builder_delete(ir);
3924 ir_builder_dump(ir, con_out);
3925 for (i = 0; i < vec_size(parser->functions); ++i) {
3926 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3927 con_out("failed to finalize function %s\n", parser->functions[i]->name);
3928 ir_builder_delete(ir);
3935 ir_builder_dump(ir, con_out);
3937 generate_checksum(parser);
3939 if (!ir_builder_generate(ir, output)) {
3940 con_out("*** failed to generate output file\n");
3941 ir_builder_delete(ir);
3946 ir_builder_delete(ir);
3950 con_out("*** there were compile errors\n");