16 MEM_VECTOR_MAKE(varentry_t, globals);
17 MEM_VECTOR_MAKE(varentry_t, fields);
18 MEM_VECTOR_MAKE(ast_function*, functions);
19 MEM_VECTOR_MAKE(ast_value*, imm_float);
20 MEM_VECTOR_MAKE(ast_value*, imm_string);
21 MEM_VECTOR_MAKE(ast_value*, imm_vector);
23 ast_value *imm_float_zero;
24 ast_value *imm_vector_zero;
29 ast_function *function;
30 MEM_VECTOR_MAKE(varentry_t, locals);
35 /* we store the '=' operator info */
36 const oper_info *assign_op;
38 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
39 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
40 * anything else: type error
45 MEM_VEC_FUNCTIONS(parser_t, varentry_t, globals)
46 MEM_VEC_FUNCTIONS(parser_t, varentry_t, fields)
47 MEM_VEC_FUNCTIONS(parser_t, ast_value*, imm_float)
48 MEM_VEC_FUNCTIONS(parser_t, ast_value*, imm_string)
49 MEM_VEC_FUNCTIONS(parser_t, ast_value*, imm_vector)
50 MEM_VEC_FUNCTIONS(parser_t, varentry_t, locals)
51 MEM_VEC_FUNCTIONS(parser_t, ast_function*, functions)
53 static bool GMQCC_WARN parser_pop_local(parser_t *parser);
54 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields);
55 static ast_block* parse_block(parser_t *parser, bool warnreturn);
56 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
57 static ast_expression* parse_statement_or_block(parser_t *parser);
58 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
59 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
61 static void parseerror(parser_t *parser, const char *fmt, ...)
68 vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
72 /* returns true if it counts as an error */
73 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
76 int lvl = LVL_WARNING;
78 if (!OPTS_WARN(warntype))
87 vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
93 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
96 int lvl = LVL_WARNING;
98 if (!OPTS_WARN(warntype))
105 vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
111 /**********************************************************************
112 * some maths used for constant folding
115 vector vec3_add(vector a, vector b)
124 vector vec3_sub(vector a, vector b)
133 qcfloat vec3_mulvv(vector a, vector b)
135 return (a.x * b.x + a.y * b.y + a.z * b.z);
138 vector vec3_mulvf(vector a, float b)
147 /**********************************************************************
151 bool parser_next(parser_t *parser)
153 /* lex_do kills the previous token */
154 parser->tok = lex_do(parser->lex);
155 if (parser->tok == TOKEN_EOF)
157 if (parser->tok >= TOKEN_ERROR) {
158 parseerror(parser, "lex error");
164 #define parser_tokval(p) ((p)->lex->tok.value)
165 #define parser_token(p) (&((p)->lex->tok))
166 #define parser_ctx(p) ((p)->lex->tok.ctx)
168 static ast_value* parser_const_float(parser_t *parser, double d)
172 for (i = 0; i < parser->imm_float_count; ++i) {
173 if (parser->imm_float[i]->constval.vfloat == d)
174 return parser->imm_float[i];
176 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
178 out->constval.vfloat = d;
179 if (!parser_t_imm_float_add(parser, out)) {
180 ast_value_delete(out);
186 static ast_value* parser_const_float_0(parser_t *parser)
188 if (!parser->imm_float_zero)
189 parser->imm_float_zero = parser_const_float(parser, 0);
190 return parser->imm_float_zero;
193 static char *parser_strdup(const char *str)
196 /* actually dup empty strings */
197 char *out = mem_a(1);
201 return util_strdup(str);
204 static ast_value* parser_const_string(parser_t *parser, const char *str)
208 for (i = 0; i < parser->imm_string_count; ++i) {
209 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
210 return parser->imm_string[i];
212 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
214 out->constval.vstring = parser_strdup(str);
215 if (!parser_t_imm_string_add(parser, out)) {
216 ast_value_delete(out);
222 static ast_value* parser_const_vector(parser_t *parser, vector v)
226 for (i = 0; i < parser->imm_vector_count; ++i) {
227 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
228 return parser->imm_vector[i];
230 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
232 out->constval.vvec = v;
233 if (!parser_t_imm_vector_add(parser, out)) {
234 ast_value_delete(out);
240 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
246 return parser_const_vector(parser, v);
249 static ast_value* parser_const_vector_0(parser_t *parser)
251 if (!parser->imm_vector_zero)
252 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
253 return parser->imm_vector_zero;
256 static ast_expression* parser_find_field(parser_t *parser, const char *name)
259 for (i = 0; i < parser->fields_count; ++i) {
260 if (!strcmp(parser->fields[i].name, name))
261 return parser->fields[i].var;
266 static ast_expression* parser_find_global(parser_t *parser, const char *name)
269 for (i = 0; i < parser->globals_count; ++i) {
270 if (!strcmp(parser->globals[i].name, name))
271 return parser->globals[i].var;
276 static ast_expression* parser_find_param(parser_t *parser, const char *name)
280 if (!parser->function)
282 fun = parser->function->vtype;
283 for (i = 0; i < fun->expression.params_count; ++i) {
284 if (!strcmp(fun->expression.params[i]->name, name))
285 return (ast_expression*)(fun->expression.params[i]);
290 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
294 for (i = parser->locals_count; i > upto;) {
296 if (!strcmp(parser->locals[i].name, name))
297 return parser->locals[i].var;
300 return parser_find_param(parser, name);
303 static ast_expression* parser_find_var(parser_t *parser, const char *name)
307 v = parser_find_local(parser, name, 0, &dummy);
308 if (!v) v = parser_find_global(parser, name);
314 size_t etype; /* 0 = expression, others are operators */
318 ast_block *block; /* for commas and function calls */
323 MEM_VECTOR_MAKE(sy_elem, out);
324 MEM_VECTOR_MAKE(sy_elem, ops);
326 MEM_VEC_FUNCTIONS(shunt, sy_elem, out)
327 MEM_VEC_FUNCTIONS(shunt, sy_elem, ops)
329 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
340 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
344 e.out = (ast_expression*)v;
351 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
353 e.etype = 1 + (op - operators);
362 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
374 # define DEBUGSHUNTDO(x) x
376 # define DEBUGSHUNTDO(x)
379 static bool parser_sy_pop(parser_t *parser, shunt *sy)
383 ast_expression *out = NULL;
384 ast_expression *exprs[3];
385 ast_block *blocks[3];
386 ast_value *asvalue[3];
388 qcint generated_op = 0;
393 if (!sy->ops_count) {
394 parseerror(parser, "internal error: missing operator");
398 if (sy->ops[sy->ops_count-1].paren) {
399 parseerror(parser, "unmatched parenthesis");
403 op = &operators[sy->ops[sy->ops_count-1].etype - 1];
404 ctx = sy->ops[sy->ops_count-1].ctx;
406 DEBUGSHUNTDO(printf("apply %s\n", op->op));
408 if (sy->out_count < op->operands) {
409 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", sy->out_count,
410 op->op, (int)op->id);
416 sy->out_count -= op->operands;
417 for (i = 0; i < op->operands; ++i) {
418 exprs[i] = sy->out[sy->out_count+i].out;
419 blocks[i] = sy->out[sy->out_count+i].block;
420 asvalue[i] = (ast_value*)exprs[i];
423 if (blocks[0] && !blocks[0]->exprs_count && op->id != opid1(',')) {
424 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
428 #define NotSameType(T) \
429 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
430 exprs[0]->expression.vtype != T)
431 #define CanConstFold1(A) \
432 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
433 #define CanConstFold(A, B) \
434 (CanConstFold1(A) && CanConstFold1(B))
435 #define ConstV(i) (asvalue[(i)]->constval.vvec)
436 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
437 #define ConstS(i) (asvalue[(i)]->constval.vstring)
441 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
445 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
446 if (exprs[1]->expression.vtype != TYPE_FIELD) {
447 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
450 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
452 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
453 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
457 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
464 if (!ast_block_exprs_add(blocks[0], exprs[1]))
467 blocks[0] = ast_block_new(ctx);
468 if (!ast_block_exprs_add(blocks[0], exprs[0]) ||
469 !ast_block_exprs_add(blocks[0], exprs[1]))
474 if (!ast_block_set_type(blocks[0], exprs[1]))
477 sy->out[sy->out_count++] = syblock(ctx, blocks[0]);
481 switch (exprs[0]->expression.vtype) {
483 if (CanConstFold1(exprs[0]))
484 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
486 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
487 (ast_expression*)parser_const_float_0(parser),
491 if (CanConstFold1(exprs[0]))
492 out = (ast_expression*)parser_const_vector_f(parser,
493 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
495 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
496 (ast_expression*)parser_const_vector_0(parser),
500 parseerror(parser, "invalid types used in expression: cannot negate type %s",
501 type_name[exprs[0]->expression.vtype]);
507 switch (exprs[0]->expression.vtype) {
509 if (CanConstFold1(exprs[0]))
510 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
512 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
515 if (CanConstFold1(exprs[0]))
516 out = (ast_expression*)parser_const_float(parser,
517 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
519 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
522 if (CanConstFold1(exprs[0]))
523 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
525 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
527 /* we don't constant-fold NOT for these types */
529 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
532 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
535 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
536 type_name[exprs[0]->expression.vtype]);
542 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
543 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
545 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
546 type_name[exprs[0]->expression.vtype],
547 type_name[exprs[1]->expression.vtype]);
550 switch (exprs[0]->expression.vtype) {
552 if (CanConstFold(exprs[0], exprs[1]))
554 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
557 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
560 if (CanConstFold(exprs[0], exprs[1]))
561 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
563 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
566 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
567 type_name[exprs[0]->expression.vtype],
568 type_name[exprs[1]->expression.vtype]);
573 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
574 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
576 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
577 type_name[exprs[1]->expression.vtype],
578 type_name[exprs[0]->expression.vtype]);
581 switch (exprs[0]->expression.vtype) {
583 if (CanConstFold(exprs[0], exprs[1]))
584 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
586 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
589 if (CanConstFold(exprs[0], exprs[1]))
590 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
592 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
595 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
596 type_name[exprs[1]->expression.vtype],
597 type_name[exprs[0]->expression.vtype]);
602 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
603 exprs[0]->expression.vtype != TYPE_VECTOR &&
604 exprs[0]->expression.vtype != TYPE_FLOAT &&
605 exprs[1]->expression.vtype != TYPE_VECTOR &&
606 exprs[1]->expression.vtype != TYPE_FLOAT)
608 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
609 type_name[exprs[1]->expression.vtype],
610 type_name[exprs[0]->expression.vtype]);
613 switch (exprs[0]->expression.vtype) {
615 if (exprs[1]->expression.vtype == TYPE_VECTOR)
617 if (CanConstFold(exprs[0], exprs[1]))
618 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
620 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
624 if (CanConstFold(exprs[0], exprs[1]))
625 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
627 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
631 if (exprs[1]->expression.vtype == TYPE_FLOAT)
633 if (CanConstFold(exprs[0], exprs[1]))
634 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
636 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
640 if (CanConstFold(exprs[0], exprs[1]))
641 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
643 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
647 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
648 type_name[exprs[1]->expression.vtype],
649 type_name[exprs[0]->expression.vtype]);
654 if (NotSameType(TYPE_FLOAT)) {
655 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
656 type_name[exprs[0]->expression.vtype],
657 type_name[exprs[1]->expression.vtype]);
660 if (CanConstFold(exprs[0], exprs[1]))
661 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
663 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
667 parseerror(parser, "qc does not have a modulo operator");
671 if (NotSameType(TYPE_FLOAT)) {
672 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
673 type_name[exprs[0]->expression.vtype],
674 type_name[exprs[1]->expression.vtype]);
677 if (CanConstFold(exprs[0], exprs[1]))
678 out = (ast_expression*)parser_const_float(parser,
679 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
680 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
682 out = (ast_expression*)ast_binary_new(ctx,
683 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
687 parseerror(parser, "TODO: bitxor");
692 case opid3('<','<','='):
693 case opid3('>','>','='):
694 parseerror(parser, "TODO: shifts");
698 generated_op += 1; /* INSTR_OR */
700 generated_op += INSTR_AND;
701 if (NotSameType(TYPE_FLOAT)) {
702 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
703 type_name[exprs[0]->expression.vtype],
704 type_name[exprs[1]->expression.vtype]);
705 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
706 parseerror(parser, "TODO: optional early out");
709 if (opts_standard == COMPILER_GMQCC)
710 printf("TODO: early out logic\n");
711 if (CanConstFold(exprs[0], exprs[1]))
712 out = (ast_expression*)parser_const_float(parser,
713 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
715 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
719 generated_op += 1; /* INSTR_GT */
721 generated_op += 1; /* INSTR_LT */
722 case opid2('>', '='):
723 generated_op += 1; /* INSTR_GE */
724 case opid2('<', '='):
725 generated_op += INSTR_LE;
726 if (NotSameType(TYPE_FLOAT)) {
727 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
728 type_name[exprs[0]->expression.vtype],
729 type_name[exprs[1]->expression.vtype]);
732 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
734 case opid2('!', '='):
735 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
736 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
737 type_name[exprs[0]->expression.vtype],
738 type_name[exprs[1]->expression.vtype]);
741 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
743 case opid2('=', '='):
744 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
745 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
746 type_name[exprs[0]->expression.vtype],
747 type_name[exprs[1]->expression.vtype]);
750 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
754 if (ast_istype(exprs[0], ast_entfield)) {
755 ast_expression *field = ((ast_entfield*)exprs[0])->field;
756 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
757 exprs[0]->expression.vtype == TYPE_FIELD &&
758 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
760 assignop = type_storep_instr[TYPE_VECTOR];
763 assignop = type_storep_instr[exprs[0]->expression.vtype];
764 if (!ast_compare_type(field->expression.next, exprs[1])) {
765 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
766 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
767 if (opts_standard == COMPILER_QCC &&
768 field->expression.next->expression.vtype == TYPE_FUNCTION &&
769 exprs[1]->expression.vtype == TYPE_FUNCTION)
771 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
772 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
778 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
783 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
784 exprs[0]->expression.vtype == TYPE_FIELD &&
785 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
787 assignop = type_store_instr[TYPE_VECTOR];
790 assignop = type_store_instr[exprs[0]->expression.vtype];
793 if (assignop == AINSTR_END) {
794 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
795 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
796 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
798 else if (!ast_compare_type(exprs[0], exprs[1])) {
799 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
800 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
801 if (opts_standard == COMPILER_QCC &&
802 exprs[0]->expression.vtype == TYPE_FUNCTION &&
803 exprs[1]->expression.vtype == TYPE_FUNCTION)
805 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
806 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
812 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
815 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
819 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
820 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
822 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
823 type_name[exprs[0]->expression.vtype],
824 type_name[exprs[1]->expression.vtype]);
827 if (ast_istype(exprs[0], ast_entfield))
828 assignop = type_storep_instr[exprs[0]->expression.vtype];
830 assignop = type_store_instr[exprs[0]->expression.vtype];
831 switch (exprs[0]->expression.vtype) {
833 out = (ast_expression*)ast_binstore_new(ctx, assignop,
834 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
838 out = (ast_expression*)ast_binstore_new(ctx, assignop,
839 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
843 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
844 type_name[exprs[0]->expression.vtype],
845 type_name[exprs[1]->expression.vtype]);
853 parseerror(parser, "failed to apply operand %s", op->op);
857 DEBUGSHUNTDO(printf("applied %s\n", op->op));
858 sy->out[sy->out_count++] = syexp(ctx, out);
862 static bool parser_close_call(parser_t *parser, shunt *sy)
864 /* was a function call */
872 fid = sy->ops[sy->ops_count].off;
874 /* out[fid] is the function
875 * everything above is parameters...
877 * 1 params = ast_expression
881 if (sy->out_count < 1 || sy->out_count <= fid) {
882 parseerror(parser, "internal error: function call needs function and parameter list...");
886 fun = sy->out[fid].out;
888 call = ast_call_new(sy->ops[sy->ops_count].ctx, fun);
890 parseerror(parser, "out of memory");
894 if (fid+1 == sy->out_count) {
897 } else if (fid+2 == sy->out_count) {
900 params = sy->out[sy->out_count].block;
904 if (!ast_call_params_add(call, sy->out[sy->out_count].out)) {
905 ast_delete(sy->out[sy->out_count].out);
906 parseerror(parser, "out of memory");
910 paramcount = params->exprs_count;
911 MEM_VECTOR_MOVE(params, exprs, call, params);
914 if (!ast_call_check_types(call))
917 parseerror(parser, "invalid function call");
921 /* overwrite fid, the function, with a call */
922 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
924 if (fun->expression.vtype != TYPE_FUNCTION) {
925 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
929 if (!fun->expression.next) {
930 parseerror(parser, "could not determine function return type");
933 if (fun->expression.params_count != paramcount &&
934 !(fun->expression.variadic &&
935 fun->expression.params_count < paramcount))
938 const char *fewmany = (fun->expression.params_count > paramcount) ? "few" : "many";
940 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
941 if (opts_standard == COMPILER_GMQCC)
944 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
945 " -> `%s` has been declared here: %s:%i",
946 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
947 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
949 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
950 " -> `%s` has been declared here: %s:%i",
951 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
952 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
958 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
959 "too %s parameters for call to %s: expected %i, got %i\n"
960 " -> `%s` has been declared here: %s:%i",
961 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
962 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
964 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
965 "too %s parameters for function call: expected %i, got %i\n"
966 " -> `%s` has been declared here: %s:%i",
967 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
968 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
976 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
978 if (!sy->ops_count) {
979 parseerror(parser, "unmatched closing paren");
982 /* this would for bit a + (x) because there are no operators inside (x)
983 if (sy->ops[sy->ops_count-1].paren == 1) {
984 parseerror(parser, "empty parenthesis expression");
988 while (sy->ops_count) {
989 if (sy->ops[sy->ops_count-1].paren == 'f') {
990 if (!parser_close_call(parser, sy))
994 if (sy->ops[sy->ops_count-1].paren == 1) {
996 return !functions_only;
998 if (!parser_sy_pop(parser, sy))
1004 static void parser_reclassify_token(parser_t *parser)
1007 for (i = 0; i < operator_count; ++i) {
1008 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1009 parser->tok = TOKEN_OPERATOR;
1015 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1017 ast_expression *expr = NULL;
1019 bool wantop = false;
1020 bool gotmemberof = false;
1022 /* count the parens because an if starts with one, so the
1023 * end of a condition is an unmatched closing paren
1027 MEM_VECTOR_INIT(&sy, out);
1028 MEM_VECTOR_INIT(&sy, ops);
1030 parser->lex->flags.noops = false;
1032 parser_reclassify_token(parser);
1037 gotmemberof = false;
1039 parser->memberof = 0;
1041 if (parser->tok == TOKEN_IDENT)
1043 ast_expression *var;
1045 parseerror(parser, "expected operator or end of statement");
1050 if (opts_standard == COMPILER_GMQCC)
1052 if (parser->memberof == TYPE_ENTITY) {
1053 /* still get vars first since there could be a fieldpointer */
1054 var = parser_find_var(parser, parser_tokval(parser));
1056 var = parser_find_field(parser, parser_tokval(parser));
1058 else if (parser->memberof == TYPE_VECTOR)
1060 parseerror(parser, "TODO: implement effective vector member access");
1063 else if (parser->memberof) {
1064 parseerror(parser, "namespace for member not found");
1068 var = parser_find_var(parser, parser_tokval(parser));
1070 var = parser_find_var(parser, parser_tokval(parser));
1072 var = parser_find_field(parser, parser_tokval(parser));
1075 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1078 if (ast_istype(var, ast_value))
1079 ((ast_value*)var)->uses++;
1080 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), var))) {
1081 parseerror(parser, "out of memory");
1084 DEBUGSHUNTDO(printf("push %s\n", parser_tokval(parser)));
1086 else if (parser->tok == TOKEN_FLOATCONST) {
1089 parseerror(parser, "expected operator or end of statement, got constant");
1093 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1096 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1097 parseerror(parser, "out of memory");
1100 DEBUGSHUNTDO(printf("push %g\n", parser_token(parser)->constval.f));
1102 else if (parser->tok == TOKEN_INTCONST) {
1105 parseerror(parser, "expected operator or end of statement, got constant");
1109 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1112 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1113 parseerror(parser, "out of memory");
1116 DEBUGSHUNTDO(printf("push %i\n", parser_token(parser)->constval.i));
1118 else if (parser->tok == TOKEN_STRINGCONST) {
1121 parseerror(parser, "expected operator or end of statement, got constant");
1125 val = parser_const_string(parser, parser_tokval(parser));
1128 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1129 parseerror(parser, "out of memory");
1132 DEBUGSHUNTDO(printf("push string\n"));
1134 else if (parser->tok == TOKEN_VECTORCONST) {
1137 parseerror(parser, "expected operator or end of statement, got constant");
1141 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1144 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1145 parseerror(parser, "out of memory");
1148 DEBUGSHUNTDO(printf("push '%g %g %g'\n",
1149 parser_token(parser)->constval.v.x,
1150 parser_token(parser)->constval.v.y,
1151 parser_token(parser)->constval.v.z));
1153 else if (parser->tok == '(') {
1154 parseerror(parser, "internal error: '(' should be classified as operator");
1157 else if (parser->tok == '[') {
1158 parseerror(parser, "internal error: '[' should be classified as operator");
1161 else if (parser->tok == ')') {
1163 DEBUGSHUNTDO(printf("do[op] )\n"));
1167 /* we do expect an operator next */
1168 /* closing an opening paren */
1169 if (!parser_close_paren(parser, &sy, false))
1172 DEBUGSHUNTDO(printf("do[nop] )\n"));
1176 /* allowed for function calls */
1177 if (!parser_close_paren(parser, &sy, true))
1182 else if (parser->tok != TOKEN_OPERATOR) {
1184 parseerror(parser, "expected operator or end of statement");
1191 /* classify the operator */
1192 /* TODO: suffix operators */
1193 const oper_info *op;
1194 const oper_info *olast = NULL;
1196 for (o = 0; o < operator_count; ++o) {
1197 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1198 !(operators[o].flags & OP_SUFFIX) && /* remove this */
1199 !strcmp(parser_tokval(parser), operators[o].op))
1204 if (o == operator_count) {
1205 /* no operator found... must be the end of the statement */
1208 /* found an operator */
1211 /* when declaring variables, a comma starts a new variable */
1212 if (op->id == opid1(',') && !parens && stopatcomma) {
1213 /* fixup the token */
1218 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1219 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1222 (op->prec < olast->prec) ||
1223 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1225 if (!parser_sy_pop(parser, &sy))
1227 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1228 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1233 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1234 /* for gmqcc standard: open up the namespace of the previous type */
1235 ast_expression *prevex = sy.out[sy.out_count-1].out;
1237 parseerror(parser, "unexpected member operator");
1240 if (prevex->expression.vtype == TYPE_ENTITY)
1241 parser->memberof = TYPE_ENTITY;
1242 else if (prevex->expression.vtype == TYPE_VECTOR)
1243 parser->memberof = TYPE_VECTOR;
1245 parseerror(parser, "type error: type has no members");
1251 if (op->id == opid1('(')) {
1253 DEBUGSHUNTDO(printf("push [op] (\n"));
1255 /* we expected an operator, this is the function-call operator */
1256 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 'f', sy.out_count-1))) {
1257 parseerror(parser, "out of memory");
1262 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 1, 0))) {
1263 parseerror(parser, "out of memory");
1266 DEBUGSHUNTDO(printf("push [nop] (\n"));
1270 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1271 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1276 if (!parser_next(parser)) {
1279 if (parser->tok == ';' || parser->tok == ']') {
1284 while (sy.ops_count) {
1285 if (!parser_sy_pop(parser, &sy))
1289 parser->lex->flags.noops = true;
1290 if (!sy.out_count) {
1291 parseerror(parser, "empty expression");
1294 expr = sy.out[0].out;
1295 MEM_VECTOR_CLEAR(&sy, out);
1296 MEM_VECTOR_CLEAR(&sy, ops);
1297 DEBUGSHUNTDO(printf("shunt done\n"));
1301 parser->lex->flags.noops = true;
1302 MEM_VECTOR_CLEAR(&sy, out);
1303 MEM_VECTOR_CLEAR(&sy, ops);
1307 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1309 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1312 if (!parser_next(parser)) {
1319 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1322 ast_expression *cond, *ontrue, *onfalse = NULL;
1324 lex_ctx ctx = parser_ctx(parser);
1326 /* skip the 'if' and check for opening paren */
1327 if (!parser_next(parser) || parser->tok != '(') {
1328 parseerror(parser, "expected 'if' condition in parenthesis");
1331 /* parse into the expression */
1332 if (!parser_next(parser)) {
1333 parseerror(parser, "expected 'if' condition after opening paren");
1336 /* parse the condition */
1337 cond = parse_expression_leave(parser, false);
1341 if (parser->tok != ')') {
1342 parseerror(parser, "expected closing paren after 'if' condition");
1346 /* parse into the 'then' branch */
1347 if (!parser_next(parser)) {
1348 parseerror(parser, "expected statement for on-true branch of 'if'");
1352 ontrue = parse_statement_or_block(parser);
1357 /* check for an else */
1358 if (!strcmp(parser_tokval(parser), "else")) {
1359 /* parse into the 'else' branch */
1360 if (!parser_next(parser)) {
1361 parseerror(parser, "expected on-false branch after 'else'");
1366 onfalse = parse_statement_or_block(parser);
1374 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1375 *out = (ast_expression*)ifthen;
1379 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1382 ast_expression *cond, *ontrue;
1384 lex_ctx ctx = parser_ctx(parser);
1386 /* skip the 'while' and check for opening paren */
1387 if (!parser_next(parser) || parser->tok != '(') {
1388 parseerror(parser, "expected 'while' condition in parenthesis");
1391 /* parse into the expression */
1392 if (!parser_next(parser)) {
1393 parseerror(parser, "expected 'while' condition after opening paren");
1396 /* parse the condition */
1397 cond = parse_expression_leave(parser, false);
1401 if (parser->tok != ')') {
1402 parseerror(parser, "expected closing paren after 'while' condition");
1406 /* parse into the 'then' branch */
1407 if (!parser_next(parser)) {
1408 parseerror(parser, "expected while-loop body");
1412 ontrue = parse_statement_or_block(parser);
1418 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1419 *out = (ast_expression*)aloop;
1423 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1426 ast_expression *cond, *ontrue;
1428 lex_ctx ctx = parser_ctx(parser);
1430 /* skip the 'do' and get the body */
1431 if (!parser_next(parser)) {
1432 parseerror(parser, "expected loop body");
1435 ontrue = parse_statement_or_block(parser);
1439 /* expect the "while" */
1440 if (parser->tok != TOKEN_KEYWORD ||
1441 strcmp(parser_tokval(parser), "while"))
1443 parseerror(parser, "expected 'while' and condition");
1448 /* skip the 'while' and check for opening paren */
1449 if (!parser_next(parser) || parser->tok != '(') {
1450 parseerror(parser, "expected 'while' condition in parenthesis");
1454 /* parse into the expression */
1455 if (!parser_next(parser)) {
1456 parseerror(parser, "expected 'while' condition after opening paren");
1460 /* parse the condition */
1461 cond = parse_expression_leave(parser, false);
1465 if (parser->tok != ')') {
1466 parseerror(parser, "expected closing paren after 'while' condition");
1472 if (!parser_next(parser) || parser->tok != ';') {
1473 parseerror(parser, "expected semicolon after condition");
1479 if (!parser_next(parser)) {
1480 parseerror(parser, "parse error");
1486 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1487 *out = (ast_expression*)aloop;
1491 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1494 ast_expression *initexpr, *cond, *increment, *ontrue;
1495 size_t oldblocklocal;
1498 lex_ctx ctx = parser_ctx(parser);
1500 oldblocklocal = parser->blocklocal;
1501 parser->blocklocal = parser->locals_count;
1508 /* skip the 'while' and check for opening paren */
1509 if (!parser_next(parser) || parser->tok != '(') {
1510 parseerror(parser, "expected 'for' expressions in parenthesis");
1513 /* parse into the expression */
1514 if (!parser_next(parser)) {
1515 parseerror(parser, "expected 'for' initializer after opening paren");
1519 if (parser->tok == TOKEN_TYPENAME) {
1520 if (opts_standard != COMPILER_GMQCC) {
1521 if (parsewarning(parser, WARN_EXTENSIONS,
1522 "current standard does not allow variable declarations in for-loop initializers"))
1526 parseerror(parser, "TODO: assignment of new variables to be non-const");
1528 if (!parse_variable(parser, block, true))
1531 else if (parser->tok != ';')
1533 initexpr = parse_expression_leave(parser, false);
1538 /* move on to condition */
1539 if (parser->tok != ';') {
1540 parseerror(parser, "expected semicolon after for-loop initializer");
1543 if (!parser_next(parser)) {
1544 parseerror(parser, "expected for-loop condition");
1548 /* parse the condition */
1549 if (parser->tok != ';') {
1550 cond = parse_expression_leave(parser, false);
1555 /* move on to incrementor */
1556 if (parser->tok != ';') {
1557 parseerror(parser, "expected semicolon after for-loop initializer");
1560 if (!parser_next(parser)) {
1561 parseerror(parser, "expected for-loop condition");
1565 /* parse the incrementor */
1566 if (parser->tok != ')') {
1567 increment = parse_expression_leave(parser, false);
1570 if (!ast_istype(increment, ast_store) &&
1571 !ast_istype(increment, ast_call) &&
1572 !ast_istype(increment, ast_binstore))
1574 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1580 if (parser->tok != ')') {
1581 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1584 /* parse into the 'then' branch */
1585 if (!parser_next(parser)) {
1586 parseerror(parser, "expected for-loop body");
1589 ontrue = parse_statement_or_block(parser);
1594 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1595 *out = (ast_expression*)aloop;
1597 while (parser->locals_count > parser->blocklocal)
1598 retval = retval && parser_pop_local(parser);
1599 parser->blocklocal = oldblocklocal;
1602 if (initexpr) ast_delete(initexpr);
1603 if (cond) ast_delete(cond);
1604 if (increment) ast_delete(increment);
1605 while (parser->locals_count > parser->blocklocal)
1606 (void)!parser_pop_local(parser);
1607 parser->blocklocal = oldblocklocal;
1611 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1613 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1615 /* local variable */
1617 parseerror(parser, "cannot declare a variable from here");
1620 if (opts_standard == COMPILER_QCC) {
1621 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1624 if (!parse_variable(parser, block, false))
1629 else if (parser->tok == TOKEN_KEYWORD)
1631 if (!strcmp(parser_tokval(parser), "local"))
1634 parseerror(parser, "cannot declare a local variable here");
1637 if (!parser_next(parser)) {
1638 parseerror(parser, "expected variable declaration");
1641 if (!parse_variable(parser, block, true))
1646 else if (!strcmp(parser_tokval(parser), "return"))
1648 ast_expression *exp = NULL;
1649 ast_return *ret = NULL;
1650 ast_value *expected = parser->function->vtype;
1652 if (!parser_next(parser)) {
1653 parseerror(parser, "expected return expression");
1657 if (parser->tok != ';') {
1658 exp = parse_expression(parser, false);
1662 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1663 parseerror(parser, "return with invalid expression");
1666 ret = ast_return_new(exp->expression.node.context, exp);
1672 if (!parser_next(parser))
1673 parseerror(parser, "parse error");
1674 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1675 if (opts_standard != COMPILER_GMQCC)
1676 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1678 parseerror(parser, "return without value");
1680 ret = ast_return_new(parser_ctx(parser), NULL);
1682 *out = (ast_expression*)ret;
1685 else if (!strcmp(parser_tokval(parser), "if"))
1687 return parse_if(parser, block, out);
1689 else if (!strcmp(parser_tokval(parser), "while"))
1691 return parse_while(parser, block, out);
1693 else if (!strcmp(parser_tokval(parser), "do"))
1695 return parse_dowhile(parser, block, out);
1697 else if (!strcmp(parser_tokval(parser), "for"))
1699 if (opts_standard == COMPILER_QCC) {
1700 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1703 return parse_for(parser, block, out);
1705 parseerror(parser, "Unexpected keyword");
1708 else if (parser->tok == '{')
1711 inner = parse_block(parser, false);
1714 *out = (ast_expression*)inner;
1719 ast_expression *exp = parse_expression(parser, false);
1723 if (!ast_istype(exp, ast_store) &&
1724 !ast_istype(exp, ast_call) &&
1725 !ast_istype(exp, ast_binstore))
1727 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1734 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1737 parser->locals_count--;
1739 ve = &parser->locals[parser->locals_count];
1740 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1741 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1744 mem_d(parser->locals[parser->locals_count].name);
1748 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1750 size_t oldblocklocal;
1753 oldblocklocal = parser->blocklocal;
1754 parser->blocklocal = parser->locals_count;
1756 if (!parser_next(parser)) { /* skip the '{' */
1757 parseerror(parser, "expected function body");
1761 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1763 ast_expression *expr;
1764 if (parser->tok == '}')
1767 if (!parse_statement(parser, block, &expr)) {
1768 /* parseerror(parser, "parse error"); */
1774 if (!ast_block_exprs_add(block, expr)) {
1781 if (parser->tok != '}') {
1784 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1786 if (!block->exprs_count ||
1787 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1789 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1795 (void)parser_next(parser);
1799 while (parser->locals_count > parser->blocklocal)
1800 retval = retval && parser_pop_local(parser);
1801 parser->blocklocal = oldblocklocal;
1805 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1808 block = ast_block_new(parser_ctx(parser));
1811 if (!parse_block_into(parser, block, warnreturn)) {
1812 ast_block_delete(block);
1818 static ast_expression* parse_statement_or_block(parser_t *parser)
1820 ast_expression *expr = NULL;
1821 if (parser->tok == '{')
1822 return (ast_expression*)parse_block(parser, false);
1823 if (!parse_statement(parser, NULL, &expr))
1829 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1832 size_t len = strlen(var->name);
1834 for (i = 0; i < 3; ++i) {
1835 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1839 ve[i].name = (char*)mem_a(len+3);
1841 ast_delete(ve[i].var);
1845 memcpy(ve[i].name, var->name, len);
1846 ve[i].name[len] = '_';
1847 ve[i].name[len+1] = 'x'+i;
1848 ve[i].name[len+2] = 0;
1857 ast_delete(ve[i].var);
1864 static bool parse_function_body(parser_t *parser, ast_value *var)
1866 ast_block *block = NULL;
1871 ast_expression *framenum = NULL;
1872 ast_expression *nextthink = NULL;
1873 /* None of the following have to be deleted */
1874 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1875 ast_expression *gbl_time = NULL, *gbl_self = NULL;
1876 bool has_frame_think;
1880 has_frame_think = false;
1881 old = parser->function;
1883 if (var->expression.variadic) {
1884 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1885 "variadic function with implementation will not be able to access additional parameters"))
1891 if (parser->tok == '[') {
1892 /* got a frame definition: [ framenum, nextthink ]
1893 * this translates to:
1894 * self.frame = framenum;
1895 * self.nextthink = time + 0.1;
1896 * self.think = nextthink;
1900 fld_think = parser_find_field(parser, "think");
1901 fld_nextthink = parser_find_field(parser, "nextthink");
1902 fld_frame = parser_find_field(parser, "frame");
1903 if (!fld_think || !fld_nextthink || !fld_frame) {
1904 parseerror(parser, "cannot use [frame,think] notation without the required fields");
1905 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1908 gbl_time = parser_find_global(parser, "time");
1909 gbl_self = parser_find_global(parser, "self");
1910 if (!gbl_time || !gbl_self) {
1911 parseerror(parser, "cannot use [frame,think] notation without the required globals");
1912 parseerror(parser, "please declare the following globals: `time`, `self`");
1916 if (!parser_next(parser))
1919 framenum = parse_expression_leave(parser, true);
1921 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1924 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1925 ast_unref(framenum);
1926 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1930 if (parser->tok != ',') {
1931 ast_unref(framenum);
1932 parseerror(parser, "expected comma after frame number in [frame,think] notation");
1933 parseerror(parser, "Got a %i\n", parser->tok);
1937 if (!parser_next(parser)) {
1938 ast_unref(framenum);
1942 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1944 /* qc allows the use of not-yet-declared functions here
1945 * - this automatically creates a prototype */
1947 ast_value *thinkfunc;
1948 ast_expression *functype = fld_think->expression.next;
1950 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1951 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1952 ast_unref(framenum);
1953 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1957 if (!parser_next(parser)) {
1958 ast_unref(framenum);
1959 ast_delete(thinkfunc);
1963 varent.var = (ast_expression*)thinkfunc;
1964 varent.name = util_strdup(thinkfunc->name);
1965 if (!parser_t_globals_add(parser, varent)) {
1966 ast_unref(framenum);
1967 ast_delete(thinkfunc);
1970 nextthink = (ast_expression*)thinkfunc;
1973 nextthink = parse_expression_leave(parser, true);
1975 ast_unref(framenum);
1976 parseerror(parser, "expected a think-function in [frame,think] notation");
1981 if (!ast_istype(nextthink, ast_value)) {
1982 parseerror(parser, "think-function in [frame,think] notation must be a constant");
1986 if (retval && parser->tok != ']') {
1987 parseerror(parser, "expected closing `]` for [frame,think] notation");
1991 if (retval && !parser_next(parser)) {
1995 if (retval && parser->tok != '{') {
1996 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2001 ast_unref(nextthink);
2002 ast_unref(framenum);
2006 has_frame_think = true;
2009 block = ast_block_new(parser_ctx(parser));
2011 parseerror(parser, "failed to allocate block");
2012 if (has_frame_think) {
2013 ast_unref(nextthink);
2014 ast_unref(framenum);
2019 if (has_frame_think) {
2021 ast_expression *self_frame;
2022 ast_expression *self_nextthink;
2023 ast_expression *self_think;
2024 ast_expression *time_plus_1;
2025 ast_store *store_frame;
2026 ast_store *store_nextthink;
2027 ast_store *store_think;
2029 ctx = parser_ctx(parser);
2030 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2031 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2032 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2034 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2035 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2037 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2038 if (self_frame) ast_delete(self_frame);
2039 if (self_nextthink) ast_delete(self_nextthink);
2040 if (self_think) ast_delete(self_think);
2041 if (time_plus_1) ast_delete(time_plus_1);
2047 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2048 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2049 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2052 ast_delete(self_frame);
2055 if (!store_nextthink) {
2056 ast_delete(self_nextthink);
2060 ast_delete(self_think);
2064 if (store_frame) ast_delete(store_frame);
2065 if (store_nextthink) ast_delete(store_nextthink);
2066 if (store_think) ast_delete(store_think);
2069 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2070 ast_delete(store_frame);
2071 ast_delete(store_nextthink);
2072 ast_delete(store_think);
2076 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2077 ast_delete(store_nextthink);
2078 ast_delete(store_think);
2082 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2084 ast_delete(store_think);
2090 parseerror(parser, "failed to generate code for [frame,think]");
2091 ast_unref(nextthink);
2092 ast_unref(framenum);
2098 for (parami = 0; parami < var->expression.params_count; ++parami) {
2101 ast_value *param = var->expression.params[parami];
2103 if (param->expression.vtype != TYPE_VECTOR &&
2104 (param->expression.vtype != TYPE_FIELD ||
2105 param->expression.next->expression.vtype != TYPE_VECTOR))
2110 if (!create_vector_members(parser, param, ve)) {
2111 ast_block_delete(block);
2115 for (e = 0; e < 3; ++e) {
2116 if (!parser_t_locals_add(parser, ve[e]))
2118 if (!ast_block_collect(block, ve[e].var)) {
2119 parser->locals_count--;
2122 ve[e].var = NULL; /* collected */
2125 parser->locals -= e;
2130 ast_block_delete(block);
2135 func = ast_function_new(ast_ctx(var), var->name, var);
2137 parseerror(parser, "failed to allocate function for `%s`", var->name);
2138 ast_block_delete(block);
2141 if (!parser_t_functions_add(parser, func)) {
2142 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2143 ast_block_delete(block);
2147 parser->function = func;
2148 if (!parse_block_into(parser, block, true)) {
2149 ast_block_delete(block);
2153 if (!ast_function_blocks_add(func, block)) {
2154 ast_block_delete(block);
2158 parser->function = old;
2159 while (parser->locals_count)
2160 retval = retval && parser_pop_local(parser);
2162 if (parser->tok == ';')
2163 return parser_next(parser);
2164 else if (opts_standard == COMPILER_QCC)
2165 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2169 parser->functions_count--;
2171 ast_function_delete(func);
2172 var->constval.vfunc = NULL;
2175 while (parser->locals_count) {
2176 parser->locals_count--;
2177 mem_d(parser->locals[parser->locals_count].name);
2179 parser->function = old;
2184 MEM_VECTOR_MAKE(ast_value*, p);
2186 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2188 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2189 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2197 bool variadic = false;
2199 ctx = parser_ctx(parser);
2201 /* for the sake of less code we parse-in in this function */
2202 if (!parser_next(parser)) {
2203 parseerror(parser, "expected parameter list");
2207 MEM_VECTOR_INIT(¶ms, p);
2209 /* parse variables until we hit a closing paren */
2210 while (parser->tok != ')') {
2212 /* there must be commas between them */
2213 if (parser->tok != ',') {
2214 parseerror(parser, "expected comma or end of parameter list");
2217 if (!parser_next(parser)) {
2218 parseerror(parser, "expected parameter");
2224 if (parser->tok == TOKEN_DOTS) {
2225 /* '...' indicates a varargs function */
2227 if (!parser_next(parser)) {
2228 parseerror(parser, "expected parameter");
2231 if (parser->tok != ')') {
2232 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2238 /* for anything else just parse a typename */
2239 param = parse_typename(parser, NULL);
2242 if (!paramlist_t_p_add(¶ms, param))
2248 if (params.p_count > 8)
2249 parseerror(parser, "more than 8 parameters are currently not supported");
2252 if (!parser_next(parser)) {
2253 parseerror(parser, "parse error after typename");
2257 /* now turn 'var' into a function type */
2258 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2259 fval->expression.next = (ast_expression*)var;
2260 fval->expression.variadic = variadic;
2263 MEM_VECTOR_MOVE(¶ms, p, &var->expression, params);
2269 for (i = 0; i < params.p_count; ++i)
2270 ast_delete(params.p[i]);
2271 MEM_VECTOR_CLEAR(¶ms, p);
2275 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2277 ast_expression *cexp;
2278 ast_value *cval, *tmp;
2281 ctx = parser_ctx(parser);
2283 if (!parser_next(parser)) {
2285 parseerror(parser, "expected array-size");
2289 cexp = parse_expression_leave(parser, true);
2291 if (!cexp || !ast_istype(cexp, ast_value)) {
2295 parseerror(parser, "expected array-size as constant positive integer");
2298 cval = (ast_value*)cexp;
2300 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2301 tmp->expression.next = (ast_expression*)var;
2304 if (cval->expression.vtype == TYPE_INTEGER)
2305 tmp->expression.count = cval->constval.vint;
2306 else if (cval->expression.vtype == TYPE_FLOAT)
2307 tmp->expression.count = cval->constval.vfloat;
2311 parseerror(parser, "array-size must be a positive integer constant");
2316 if (parser->tok != ']') {
2318 parseerror(parser, "expected ']' after array-size");
2321 if (!parser_next(parser)) {
2323 parseerror(parser, "error after parsing array size");
2329 /* Parse a complete typename.
2330 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2331 * but when parsing variables separated by comma
2332 * 'storebase' should point to where the base-type should be kept.
2333 * The base type makes up every bit of type information which comes *before* the
2336 * The following will be parsed in its entirety:
2338 * The 'basetype' in this case is 'void()'
2339 * and if there's a comma after it, say:
2341 * then the type-information 'void()' can be stored in 'storebase'
2343 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2345 ast_value *var, *tmp;
2348 const char *name = NULL;
2349 bool isfield = false;
2351 ctx = parser_ctx(parser);
2353 /* types may start with a dot */
2354 if (parser->tok == '.') {
2356 /* if we parsed a dot we need a typename now */
2357 if (!parser_next(parser)) {
2358 parseerror(parser, "expected typename for field definition");
2361 if (parser->tok != TOKEN_TYPENAME) {
2362 parseerror(parser, "expected typename");
2367 /* generate the basic type value */
2368 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2369 /* do not yet turn into a field - remember:
2370 * .void() foo; is a field too
2371 * .void()() foo; is a function
2375 if (!parser_next(parser)) {
2377 parseerror(parser, "parse error after typename");
2381 /* an opening paren now starts the parameter-list of a function
2382 * this is where original-QC has parameter lists.
2383 * We allow a single parameter list here.
2384 * Much like fteqcc we don't allow `float()() x`
2386 if (parser->tok == '(') {
2387 var = parse_parameter_list(parser, var);
2392 /* store the base if requested */
2394 *storebase = ast_value_copy(var);
2396 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2397 tmp->expression.next = (ast_expression*)*storebase;
2402 /* there may be a name now */
2403 if (parser->tok == TOKEN_IDENT) {
2404 name = util_strdup(parser_tokval(parser));
2406 if (!parser_next(parser)) {
2408 parseerror(parser, "error after variable or field declaration");
2413 /* now this may be an array */
2414 if (parser->tok == '[') {
2415 var = parse_arraysize(parser, var);
2420 /* This is the point where we can turn it into a field */
2422 /* turn it into a field if desired */
2423 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2424 tmp->expression.next = (ast_expression*)var;
2428 /* now there may be function parens again */
2429 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2430 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2431 while (parser->tok == '(') {
2432 var = parse_parameter_list(parser, var);
2441 /* finally name it */
2443 if (!ast_value_set_name(var, name)) {
2445 parseerror(parser, "internal error: failed to set name");
2448 /* free the name, ast_value_set_name duplicates */
2455 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2459 ast_expression *old;
2463 ast_value *basetype = NULL;
2465 bool isparam = false;
2466 bool isvector = false;
2467 bool cleanvar = true;
2468 bool wasarray = false;
2470 varentry_t varent, ve[3];
2472 /* get the first complete variable */
2473 var = parse_typename(parser, &basetype);
2476 ast_delete(basetype);
2480 memset(&varent, 0, sizeof(varent));
2481 memset(&ve, 0, sizeof(ve));
2487 /* Part 0: finish the type */
2488 if (parser->tok == '(') {
2489 if (opts_standard == COMPILER_QCC)
2490 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2491 var = parse_parameter_list(parser, var);
2497 /* we only allow 1-dimensional arrays */
2498 if (parser->tok == '[') {
2500 var = parse_arraysize(parser, var);
2506 if (parser->tok == '(' && wasarray) {
2507 parseerror(parser, "functions cannot return arrays");
2508 /* we'll still parse the type completely for now */
2510 /* for functions returning functions */
2511 while (parser->tok == '(') {
2512 if (opts_standard == COMPILER_QCC)
2513 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2514 var = parse_parameter_list(parser, var);
2522 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2523 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2524 * is then filled with the previous definition and the parameter-names replaced.
2527 /* Deal with end_sys_ vars */
2529 if (!strcmp(var->name, "end_sys_globals")) {
2530 parser->crc_globals = parser->globals_count;
2533 else if (!strcmp(var->name, "end_sys_fields")) {
2534 parser->crc_fields = parser->fields_count;
2537 if (was_end && var->expression.vtype == TYPE_FIELD) {
2538 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2539 "global '%s' hint should not be a field",
2540 parser_tokval(parser)))
2547 if (!nofields && var->expression.vtype == TYPE_FIELD)
2549 /* deal with field declarations */
2550 old = parser_find_field(parser, var->name);
2552 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2553 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2562 parseerror(parser, "field `%s` already declared here: %s:%i",
2563 var->name, ast_ctx(old).file, ast_ctx(old).line);
2568 if (opts_standard == COMPILER_QCC &&
2569 (old = parser_find_global(parser, var->name)))
2571 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2572 parseerror(parser, "field `%s` already declared here: %s:%i",
2573 var->name, ast_ctx(old).file, ast_ctx(old).line);
2580 /* deal with other globals */
2581 old = parser_find_global(parser, var->name);
2582 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2584 /* This is a function which had a prototype */
2585 if (!ast_istype(old, ast_value)) {
2586 parseerror(parser, "internal error: prototype is not an ast_value");
2590 proto = (ast_value*)old;
2591 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2592 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2594 ast_ctx(proto).file, ast_ctx(proto).line);
2598 /* we need the new parameter-names */
2599 for (i = 0; i < proto->expression.params_count; ++i)
2600 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2608 parseerror(parser, "global `%s` already declared here: %s:%i",
2609 var->name, ast_ctx(old).file, ast_ctx(old).line);
2613 if (opts_standard == COMPILER_QCC &&
2614 (old = parser_find_field(parser, var->name)))
2616 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2617 parseerror(parser, "global `%s` already declared here: %s:%i",
2618 var->name, ast_ctx(old).file, ast_ctx(old).line);
2625 else /* it's not a global */
2627 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2628 if (old && !isparam) {
2629 parseerror(parser, "local `%s` already declared here: %s:%i",
2630 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2634 old = parser_find_local(parser, var->name, 0, &isparam);
2635 if (old && isparam) {
2636 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2637 "local `%s` is shadowing a parameter", var->name))
2639 parseerror(parser, "local `%s` already declared here: %s:%i",
2640 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2644 if (opts_standard != COMPILER_GMQCC) {
2653 * Create the global/local, and deal with vector types.
2656 if (var->expression.vtype == TYPE_VECTOR)
2658 else if (var->expression.vtype == TYPE_FIELD &&
2659 var->expression.next->expression.vtype == TYPE_VECTOR)
2663 if (!create_vector_members(parser, var, ve)) {
2669 varent.name = util_strdup(var->name);
2670 varent.var = (ast_expression*)var;
2673 /* deal with global variables, fields, functions */
2674 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2675 if (!(retval = parser_t_fields_add(parser, varent)))
2678 for (i = 0; i < 3; ++i) {
2679 if (!(retval = parser_t_fields_add(parser, ve[i])))
2683 parser->fields_count -= i+1;
2689 if (!(retval = parser_t_globals_add(parser, varent)))
2692 for (i = 0; i < 3; ++i) {
2693 if (!(retval = parser_t_globals_add(parser, ve[i])))
2697 parser->globals_count -= i+1;
2703 if (!(retval = parser_t_locals_add(parser, varent)))
2705 if (!(retval = ast_block_locals_add(localblock, var))) {
2706 parser->locals_count--;
2710 for (i = 0; i < 3; ++i) {
2711 if (!(retval = parser_t_locals_add(parser, ve[i])))
2713 if (!(retval = ast_block_collect(localblock, ve[i].var)))
2715 ve[i].var = NULL; /* from here it's being collected in the block */
2718 parser->locals_count -= i+1;
2719 localblock->locals_count--;
2726 ve[0].name = ve[1].name = ve[2].name = NULL;
2727 ve[0].var = ve[1].var = ve[2].var = NULL;
2732 if (parser->tok == ';') {
2733 ast_delete(basetype);
2734 if (!parser_next(parser)) {
2735 parseerror(parser, "error after variable declaration");
2741 if (parser->tok == ',')
2744 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
2745 parseerror(parser, "missing comma or semicolon while parsing variables");
2749 if (localblock && opts_standard == COMPILER_QCC) {
2750 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
2751 "initializing expression turns variable `%s` into a constant in this standard",
2758 if (parser->tok != '{') {
2759 if (parser->tok != '=') {
2760 parseerror(parser, "missing semicolon or initializer");
2764 if (!parser_next(parser)) {
2765 parseerror(parser, "error parsing initializer");
2769 else if (opts_standard == COMPILER_QCC) {
2770 parseerror(parser, "expected '=' before function body in this standard");
2773 if (parser->tok == '#') {
2777 parseerror(parser, "cannot declare builtins within functions");
2780 if (var->expression.vtype != TYPE_FUNCTION) {
2781 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
2784 if (!parser_next(parser)) {
2785 parseerror(parser, "expected builtin number");
2788 if (parser->tok != TOKEN_INTCONST) {
2789 parseerror(parser, "builtin number must be an integer constant");
2792 if (parser_token(parser)->constval.i <= 0) {
2793 parseerror(parser, "builtin number must be an integer greater than zero");
2797 func = ast_function_new(ast_ctx(var), var->name, var);
2799 parseerror(parser, "failed to allocate function for `%s`", var->name);
2802 if (!parser_t_functions_add(parser, func)) {
2803 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2804 ast_function_delete(func);
2805 var->constval.vfunc = NULL;
2809 func->builtin = -parser_token(parser)->constval.i;
2811 if (!parser_next(parser)) {
2812 parseerror(parser, "expected comma or semicolon");
2813 ast_function_delete(func);
2814 var->constval.vfunc = NULL;
2818 else if (parser->tok == '{' || parser->tok == '[')
2821 parseerror(parser, "cannot declare functions within functions");
2825 if (!parse_function_body(parser, var))
2827 ast_delete(basetype);
2830 ast_expression *cexp;
2833 cexp = parse_expression_leave(parser, true);
2838 cval = (ast_value*)cexp;
2839 if (!ast_istype(cval, ast_value) || !cval->isconst)
2840 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
2843 var->isconst = true;
2844 if (cval->expression.vtype == TYPE_STRING)
2845 var->constval.vstring = parser_strdup(cval->constval.vstring);
2847 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
2852 MEM_VECTOR_INIT(&sy, out);
2853 MEM_VECTOR_INIT(&sy, ops);
2854 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
2855 !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
2856 !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
2858 parseerror(parser, "internal error: failed to prepare initializer");
2861 else if (!parser_sy_pop(parser, &sy))
2864 if (sy.out_count != 1 && sy.ops_count != 0)
2865 parseerror(parser, "internal error: leaked operands");
2866 else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
2867 parseerror(parser, "failed to create intializing expression");
2868 ast_unref(sy.out[0].out);
2872 MEM_VECTOR_CLEAR(&sy, out);
2873 MEM_VECTOR_CLEAR(&sy, ops);
2878 if (parser->tok == ',') {
2879 if (!parser_next(parser)) {
2880 parseerror(parser, "expected another variable");
2884 if (parser->tok != TOKEN_IDENT) {
2885 parseerror(parser, "expected another variable");
2888 var = ast_value_copy(basetype);
2890 ast_value_set_name(var, parser_tokval(parser));
2891 if (!parser_next(parser)) {
2892 parseerror(parser, "error parsing variable declaration");
2898 if (parser->tok != ';') {
2899 parseerror(parser, "missing semicolon after variables");
2903 if (!parser_next(parser)) {
2904 parseerror(parser, "parse error after variable declaration");
2908 ast_delete(basetype);
2912 if (cleanvar && var)
2914 ast_delete(basetype);
2918 ast_delete(basetype);
2919 if (cleanvar && var)
2921 if (varent.name) mem_d(varent.name);
2922 if (ve[0].name) mem_d(ve[0].name);
2923 if (ve[1].name) mem_d(ve[1].name);
2924 if (ve[2].name) mem_d(ve[2].name);
2925 if (ve[0].var) mem_d(ve[0].var);
2926 if (ve[1].var) mem_d(ve[1].var);
2927 if (ve[2].var) mem_d(ve[2].var);
2931 static bool parser_global_statement(parser_t *parser)
2933 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2935 return parse_variable(parser, NULL, false);
2937 else if (parser->tok == TOKEN_KEYWORD)
2939 /* handle 'var' and 'const' */
2940 if (!strcmp(parser_tokval(parser), "var")) {
2941 if (!parser_next(parser)) {
2942 parseerror(parser, "expected variable declaration after 'var'");
2945 return parse_variable(parser, NULL, true);
2949 else if (parser->tok == '$')
2951 if (!parser_next(parser)) {
2952 parseerror(parser, "parse error");
2958 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
2964 static parser_t *parser;
2969 parser = (parser_t*)mem_a(sizeof(parser_t));
2973 memset(parser, 0, sizeof(*parser));
2975 for (i = 0; i < operator_count; ++i) {
2976 if (operators[i].id == opid1('=')) {
2977 parser->assign_op = operators+i;
2981 if (!parser->assign_op) {
2982 printf("internal error: initializing parser: failed to find assign operator\n");
2989 bool parser_compile(const char *filename)
2991 parser->lex = lex_open(filename);
2993 printf("failed to open file \"%s\"\n", filename);
2997 /* initial lexer/parser state */
2998 parser->lex->flags.noops = true;
3000 if (parser_next(parser))
3002 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3004 if (!parser_global_statement(parser)) {
3005 if (parser->tok == TOKEN_EOF)
3006 parseerror(parser, "unexpected eof");
3007 else if (!parser->errors)
3008 parseerror(parser, "there have been errors, bailing out");
3009 lex_close(parser->lex);
3015 parseerror(parser, "parse error");
3016 lex_close(parser->lex);
3021 lex_close(parser->lex);
3024 return !parser->errors;
3027 void parser_cleanup()
3030 for (i = 0; i < parser->functions_count; ++i) {
3031 ast_delete(parser->functions[i]);
3033 for (i = 0; i < parser->imm_vector_count; ++i) {
3034 ast_delete(parser->imm_vector[i]);
3036 for (i = 0; i < parser->imm_string_count; ++i) {
3037 ast_delete(parser->imm_string[i]);
3039 for (i = 0; i < parser->imm_float_count; ++i) {
3040 ast_delete(parser->imm_float[i]);
3042 for (i = 0; i < parser->fields_count; ++i) {
3043 ast_delete(parser->fields[i].var);
3044 mem_d(parser->fields[i].name);
3046 for (i = 0; i < parser->globals_count; ++i) {
3047 ast_delete(parser->globals[i].var);
3048 mem_d(parser->globals[i].name);
3050 MEM_VECTOR_CLEAR(parser, functions);
3051 MEM_VECTOR_CLEAR(parser, imm_vector);
3052 MEM_VECTOR_CLEAR(parser, imm_string);
3053 MEM_VECTOR_CLEAR(parser, imm_float);
3054 MEM_VECTOR_CLEAR(parser, globals);
3055 MEM_VECTOR_CLEAR(parser, fields);
3056 MEM_VECTOR_CLEAR(parser, locals);
3061 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3063 return util_crc16(old, str, strlen(str));
3066 static void progdefs_crc_file(const char *str)
3068 /* write to progdefs.h here */
3071 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3073 old = progdefs_crc_sum(old, str);
3074 progdefs_crc_file(str);
3078 static void generate_checksum(parser_t *parser)
3080 uint16_t crc = 0xFFFF;
3083 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3084 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3086 progdefs_crc_file("\tint\tpad;\n");
3087 progdefs_crc_file("\tint\tofs_return[3];\n");
3088 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3089 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3090 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3091 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3092 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3093 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3094 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3095 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3097 for (i = 0; i < parser->crc_globals; ++i) {
3098 if (!ast_istype(parser->globals[i].var, ast_value))
3100 switch (parser->globals[i].var->expression.vtype) {
3101 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3102 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3103 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3104 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3106 crc = progdefs_crc_both(crc, "\tint\t");
3109 crc = progdefs_crc_both(crc, parser->globals[i].name);
3110 crc = progdefs_crc_both(crc, ";\n");
3112 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3113 for (i = 0; i < parser->crc_fields; ++i) {
3114 if (!ast_istype(parser->fields[i].var, ast_value))
3116 switch (parser->fields[i].var->expression.next->expression.vtype) {
3117 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3118 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3119 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3120 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3122 crc = progdefs_crc_both(crc, "\tint\t");
3125 crc = progdefs_crc_both(crc, parser->fields[i].name);
3126 crc = progdefs_crc_both(crc, ";\n");
3128 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3133 bool parser_finish(const char *output)
3139 if (!parser->errors)
3141 ir = ir_builder_new("gmqcc_out");
3143 printf("failed to allocate builder\n");
3147 for (i = 0; i < parser->fields_count; ++i) {
3150 if (!ast_istype(parser->fields[i].var, ast_value))
3152 field = (ast_value*)parser->fields[i].var;
3153 isconst = field->isconst;
3154 field->isconst = false;
3155 if (!ast_global_codegen((ast_value*)field, ir, true)) {
3156 printf("failed to generate field %s\n", field->name);
3157 ir_builder_delete(ir);
3162 ast_expression *subtype;
3163 field->isconst = true;
3164 subtype = field->expression.next;
3165 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3166 if (subtype->expression.vtype == TYPE_FIELD)
3167 ifld->fieldtype = subtype->expression.next->expression.vtype;
3168 else if (subtype->expression.vtype == TYPE_FUNCTION)
3169 ifld->outtype = subtype->expression.next->expression.vtype;
3170 (void)!ir_value_set_field(field->ir_v, ifld);
3173 for (i = 0; i < parser->globals_count; ++i) {
3175 if (!ast_istype(parser->globals[i].var, ast_value))
3177 asvalue = (ast_value*)(parser->globals[i].var);
3178 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3179 if (strcmp(asvalue->name, "end_sys_globals") &&
3180 strcmp(asvalue->name, "end_sys_fields"))
3182 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3183 "unused global: `%s`", asvalue->name);
3186 if (!ast_global_codegen(asvalue, ir, false)) {
3187 printf("failed to generate global %s\n", parser->globals[i].name);
3188 ir_builder_delete(ir);
3192 for (i = 0; i < parser->imm_float_count; ++i) {
3193 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3194 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3195 ir_builder_delete(ir);
3199 for (i = 0; i < parser->imm_string_count; ++i) {
3200 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3201 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3202 ir_builder_delete(ir);
3206 for (i = 0; i < parser->imm_vector_count; ++i) {
3207 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3208 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3209 ir_builder_delete(ir);
3213 for (i = 0; i < parser->functions_count; ++i) {
3214 if (!ast_function_codegen(parser->functions[i], ir)) {
3215 printf("failed to generate function %s\n", parser->functions[i]->name);
3216 ir_builder_delete(ir);
3219 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3220 printf("failed to finalize function %s\n", parser->functions[i]->name);
3221 ir_builder_delete(ir);
3228 ir_builder_dump(ir, printf);
3230 generate_checksum(parser);
3232 if (!ir_builder_generate(ir, output)) {
3233 printf("*** failed to generate output file\n");
3234 ir_builder_delete(ir);
3239 ir_builder_delete(ir);
3243 printf("*** there were compile errors\n");