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;
390 if (!sy->ops_count) {
391 parseerror(parser, "internal error: missing operator");
395 if (sy->ops[sy->ops_count-1].paren) {
396 parseerror(parser, "unmatched parenthesis");
400 op = &operators[sy->ops[sy->ops_count-1].etype - 1];
401 ctx = sy->ops[sy->ops_count-1].ctx;
403 DEBUGSHUNTDO(printf("apply %s\n", op->op));
405 if (sy->out_count < op->operands) {
406 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", sy->out_count,
407 op->op, (int)op->id);
413 sy->out_count -= op->operands;
414 for (i = 0; i < op->operands; ++i) {
415 exprs[i] = sy->out[sy->out_count+i].out;
416 blocks[i] = sy->out[sy->out_count+i].block;
417 asvalue[i] = (ast_value*)exprs[i];
420 if (blocks[0] && !blocks[0]->exprs_count && op->id != opid1(',')) {
421 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
425 #define NotSameType(T) \
426 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
427 exprs[0]->expression.vtype != T)
428 #define CanConstFold1(A) \
429 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
430 #define CanConstFold(A, B) \
431 (CanConstFold1(A) && CanConstFold1(B))
432 #define ConstV(i) (asvalue[(i)]->constval.vvec)
433 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
434 #define ConstS(i) (asvalue[(i)]->constval.vstring)
438 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
442 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
443 if (exprs[1]->expression.vtype != TYPE_FIELD) {
444 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
447 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
449 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
450 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
454 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
461 if (!ast_block_exprs_add(blocks[0], exprs[1]))
464 blocks[0] = ast_block_new(ctx);
465 if (!ast_block_exprs_add(blocks[0], exprs[0]) ||
466 !ast_block_exprs_add(blocks[0], exprs[1]))
471 if (!ast_block_set_type(blocks[0], exprs[1]))
474 sy->out[sy->out_count++] = syblock(ctx, blocks[0]);
478 switch (exprs[0]->expression.vtype) {
480 if (CanConstFold1(exprs[0]))
481 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
483 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
484 (ast_expression*)parser_const_float_0(parser),
488 if (CanConstFold1(exprs[0]))
489 out = (ast_expression*)parser_const_vector_f(parser,
490 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
492 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
493 (ast_expression*)parser_const_vector_0(parser),
497 parseerror(parser, "invalid types used in expression: cannot negate type %s",
498 type_name[exprs[0]->expression.vtype]);
504 switch (exprs[0]->expression.vtype) {
506 if (CanConstFold1(exprs[0]))
507 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
509 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
512 if (CanConstFold1(exprs[0]))
513 out = (ast_expression*)parser_const_float(parser,
514 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
516 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
519 if (CanConstFold1(exprs[0]))
520 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
522 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
524 /* we don't constant-fold NOT for these types */
526 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
529 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
532 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
533 type_name[exprs[0]->expression.vtype]);
539 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
540 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
542 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
543 type_name[exprs[0]->expression.vtype],
544 type_name[exprs[1]->expression.vtype]);
547 switch (exprs[0]->expression.vtype) {
549 if (CanConstFold(exprs[0], exprs[1]))
551 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
554 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
557 if (CanConstFold(exprs[0], exprs[1]))
558 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
560 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
563 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
564 type_name[exprs[0]->expression.vtype],
565 type_name[exprs[1]->expression.vtype]);
570 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
571 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
573 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
574 type_name[exprs[1]->expression.vtype],
575 type_name[exprs[0]->expression.vtype]);
578 switch (exprs[0]->expression.vtype) {
580 if (CanConstFold(exprs[0], exprs[1]))
581 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
583 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
586 if (CanConstFold(exprs[0], exprs[1]))
587 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
589 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
592 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
593 type_name[exprs[1]->expression.vtype],
594 type_name[exprs[0]->expression.vtype]);
599 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
600 exprs[0]->expression.vtype != TYPE_VECTOR &&
601 exprs[0]->expression.vtype != TYPE_FLOAT &&
602 exprs[1]->expression.vtype != TYPE_VECTOR &&
603 exprs[1]->expression.vtype != TYPE_FLOAT)
605 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
606 type_name[exprs[1]->expression.vtype],
607 type_name[exprs[0]->expression.vtype]);
610 switch (exprs[0]->expression.vtype) {
612 if (exprs[1]->expression.vtype == TYPE_VECTOR)
614 if (CanConstFold(exprs[0], exprs[1]))
615 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
617 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
621 if (CanConstFold(exprs[0], exprs[1]))
622 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
624 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
628 if (exprs[1]->expression.vtype == TYPE_FLOAT)
630 if (CanConstFold(exprs[0], exprs[1]))
631 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
633 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
637 if (CanConstFold(exprs[0], exprs[1]))
638 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
640 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
644 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
645 type_name[exprs[1]->expression.vtype],
646 type_name[exprs[0]->expression.vtype]);
651 if (NotSameType(TYPE_FLOAT)) {
652 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
653 type_name[exprs[0]->expression.vtype],
654 type_name[exprs[1]->expression.vtype]);
657 if (CanConstFold(exprs[0], exprs[1]))
658 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
660 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
664 parseerror(parser, "qc does not have a modulo operator");
668 if (NotSameType(TYPE_FLOAT)) {
669 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
670 type_name[exprs[0]->expression.vtype],
671 type_name[exprs[1]->expression.vtype]);
674 if (CanConstFold(exprs[0], exprs[1]))
675 out = (ast_expression*)parser_const_float(parser,
676 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
677 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
679 out = (ast_expression*)ast_binary_new(ctx,
680 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
684 parseerror(parser, "TODO: bitxor");
689 case opid3('<','<','='):
690 case opid3('>','>','='):
691 parseerror(parser, "TODO: shifts");
695 generated_op += 1; /* INSTR_OR */
697 generated_op += INSTR_AND;
698 if (NotSameType(TYPE_FLOAT)) {
699 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
700 type_name[exprs[0]->expression.vtype],
701 type_name[exprs[1]->expression.vtype]);
702 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
703 parseerror(parser, "TODO: optional early out");
706 if (opts_standard == COMPILER_GMQCC)
707 printf("TODO: early out logic\n");
708 if (CanConstFold(exprs[0], exprs[1]))
709 out = (ast_expression*)parser_const_float(parser,
710 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
712 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
716 generated_op += 1; /* INSTR_GT */
718 generated_op += 1; /* INSTR_LT */
719 case opid2('>', '='):
720 generated_op += 1; /* INSTR_GE */
721 case opid2('<', '='):
722 generated_op += INSTR_LE;
723 if (NotSameType(TYPE_FLOAT)) {
724 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
725 type_name[exprs[0]->expression.vtype],
726 type_name[exprs[1]->expression.vtype]);
729 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
731 case opid2('!', '='):
732 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
733 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
734 type_name[exprs[0]->expression.vtype],
735 type_name[exprs[1]->expression.vtype]);
738 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
740 case opid2('=', '='):
741 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
742 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
743 type_name[exprs[0]->expression.vtype],
744 type_name[exprs[1]->expression.vtype]);
747 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
751 if (ast_istype(exprs[0], ast_entfield)) {
752 ast_expression *field = ((ast_entfield*)exprs[0])->field;
753 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
754 exprs[0]->expression.vtype == TYPE_FIELD &&
755 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
757 assignop = type_storep_instr[TYPE_VECTOR];
760 assignop = type_storep_instr[exprs[0]->expression.vtype];
761 if (!ast_compare_type(field->expression.next, exprs[1])) {
764 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
765 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
766 if (opts_standard == COMPILER_QCC &&
767 field->expression.next->expression.vtype == TYPE_FUNCTION &&
768 exprs[1]->expression.vtype == TYPE_FUNCTION)
770 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
771 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
777 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
782 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
783 exprs[0]->expression.vtype == TYPE_FIELD &&
784 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
786 assignop = type_store_instr[TYPE_VECTOR];
789 assignop = type_store_instr[exprs[0]->expression.vtype];
790 if (!ast_compare_type(exprs[0], exprs[1])) {
793 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
794 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
795 if (opts_standard == COMPILER_QCC &&
796 exprs[0]->expression.vtype == TYPE_FUNCTION &&
797 exprs[1]->expression.vtype == TYPE_FUNCTION)
799 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
800 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
806 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
809 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
813 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
814 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
816 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
817 type_name[exprs[0]->expression.vtype],
818 type_name[exprs[1]->expression.vtype]);
821 if (ast_istype(exprs[0], ast_entfield))
822 assignop = type_storep_instr[exprs[0]->expression.vtype];
824 assignop = type_store_instr[exprs[0]->expression.vtype];
825 switch (exprs[0]->expression.vtype) {
827 out = (ast_expression*)ast_binstore_new(ctx, assignop,
828 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
832 out = (ast_expression*)ast_binstore_new(ctx, assignop,
833 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
837 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
838 type_name[exprs[0]->expression.vtype],
839 type_name[exprs[1]->expression.vtype]);
847 parseerror(parser, "failed to apply operand %s", op->op);
851 DEBUGSHUNTDO(printf("applied %s\n", op->op));
852 sy->out[sy->out_count++] = syexp(ctx, out);
856 static bool parser_close_call(parser_t *parser, shunt *sy)
858 /* was a function call */
866 fid = sy->ops[sy->ops_count].off;
868 /* out[fid] is the function
869 * everything above is parameters...
871 * 1 params = ast_expression
875 if (sy->out_count < 1 || sy->out_count <= fid) {
876 parseerror(parser, "internal error: function call needs function and parameter list...");
880 fun = sy->out[fid].out;
882 call = ast_call_new(sy->ops[sy->ops_count].ctx, fun);
884 parseerror(parser, "out of memory");
888 if (fid+1 == sy->out_count) {
891 } else if (fid+2 == sy->out_count) {
894 params = sy->out[sy->out_count].block;
898 if (!ast_call_params_add(call, sy->out[sy->out_count].out)) {
899 ast_delete(sy->out[sy->out_count].out);
900 parseerror(parser, "out of memory");
904 paramcount = params->exprs_count;
905 MEM_VECTOR_MOVE(params, exprs, call, params);
908 if (!ast_call_check_types(call))
911 parseerror(parser, "invalid function call");
915 /* overwrite fid, the function, with a call */
916 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
918 if (fun->expression.vtype != TYPE_FUNCTION) {
919 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
923 if (!fun->expression.next) {
924 parseerror(parser, "could not determine function return type");
927 if (fun->expression.params_count != paramcount &&
928 !(fun->expression.variadic &&
929 fun->expression.params_count < paramcount))
932 const char *fewmany = (fun->expression.params_count > paramcount) ? "few" : "many";
934 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
935 if (opts_standard == COMPILER_GMQCC)
938 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
939 " -> `%s` has been declared here: %s:%i",
940 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
941 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
943 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
944 " -> `%s` has been declared here: %s:%i",
945 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
946 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
952 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
953 "too %s parameters for call to %s: expected %i, got %i\n"
954 " -> `%s` has been declared here: %s:%i",
955 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
956 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
958 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
959 "too %s parameters for function call: 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);
970 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
972 if (!sy->ops_count) {
973 parseerror(parser, "unmatched closing paren");
976 /* this would for bit a + (x) because there are no operators inside (x)
977 if (sy->ops[sy->ops_count-1].paren == 1) {
978 parseerror(parser, "empty parenthesis expression");
982 while (sy->ops_count) {
983 if (sy->ops[sy->ops_count-1].paren == 'f') {
984 if (!parser_close_call(parser, sy))
988 if (sy->ops[sy->ops_count-1].paren == 1) {
990 return !functions_only;
992 if (!parser_sy_pop(parser, sy))
998 static void parser_reclassify_token(parser_t *parser)
1001 for (i = 0; i < operator_count; ++i) {
1002 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1003 parser->tok = TOKEN_OPERATOR;
1009 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1011 ast_expression *expr = NULL;
1013 bool wantop = false;
1014 bool gotmemberof = false;
1016 /* count the parens because an if starts with one, so the
1017 * end of a condition is an unmatched closing paren
1021 MEM_VECTOR_INIT(&sy, out);
1022 MEM_VECTOR_INIT(&sy, ops);
1024 parser->lex->flags.noops = false;
1026 parser_reclassify_token(parser);
1031 gotmemberof = false;
1033 parser->memberof = 0;
1035 if (parser->tok == TOKEN_IDENT)
1037 ast_expression *var;
1039 parseerror(parser, "expected operator or end of statement");
1044 if (opts_standard == COMPILER_GMQCC)
1046 if (parser->memberof == TYPE_ENTITY) {
1047 /* still get vars first since there could be a fieldpointer */
1048 var = parser_find_var(parser, parser_tokval(parser));
1050 var = parser_find_field(parser, parser_tokval(parser));
1052 else if (parser->memberof == TYPE_VECTOR)
1054 parseerror(parser, "TODO: implement effective vector member access");
1057 else if (parser->memberof) {
1058 parseerror(parser, "namespace for member not found");
1062 var = parser_find_var(parser, parser_tokval(parser));
1064 var = parser_find_var(parser, parser_tokval(parser));
1066 var = parser_find_field(parser, parser_tokval(parser));
1069 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1072 if (ast_istype(var, ast_value))
1073 ((ast_value*)var)->uses++;
1074 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), var))) {
1075 parseerror(parser, "out of memory");
1078 DEBUGSHUNTDO(printf("push %s\n", parser_tokval(parser)));
1080 else if (parser->tok == TOKEN_FLOATCONST) {
1083 parseerror(parser, "expected operator or end of statement, got constant");
1087 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1090 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1091 parseerror(parser, "out of memory");
1094 DEBUGSHUNTDO(printf("push %g\n", parser_token(parser)->constval.f));
1096 else if (parser->tok == TOKEN_INTCONST) {
1099 parseerror(parser, "expected operator or end of statement, got constant");
1103 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1106 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1107 parseerror(parser, "out of memory");
1110 DEBUGSHUNTDO(printf("push %i\n", parser_token(parser)->constval.i));
1112 else if (parser->tok == TOKEN_STRINGCONST) {
1115 parseerror(parser, "expected operator or end of statement, got constant");
1119 val = parser_const_string(parser, parser_tokval(parser));
1122 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1123 parseerror(parser, "out of memory");
1126 DEBUGSHUNTDO(printf("push string\n"));
1128 else if (parser->tok == TOKEN_VECTORCONST) {
1131 parseerror(parser, "expected operator or end of statement, got constant");
1135 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1138 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1139 parseerror(parser, "out of memory");
1142 DEBUGSHUNTDO(printf("push '%g %g %g'\n",
1143 parser_token(parser)->constval.v.x,
1144 parser_token(parser)->constval.v.y,
1145 parser_token(parser)->constval.v.z));
1147 else if (parser->tok == '(') {
1148 parseerror(parser, "internal error: '(' should be classified as operator");
1151 else if (parser->tok == ')') {
1153 DEBUGSHUNTDO(printf("do[op] )\n"));
1157 /* we do expect an operator next */
1158 /* closing an opening paren */
1159 if (!parser_close_paren(parser, &sy, false))
1162 DEBUGSHUNTDO(printf("do[nop] )\n"));
1166 /* allowed for function calls */
1167 if (!parser_close_paren(parser, &sy, true))
1172 else if (parser->tok != TOKEN_OPERATOR) {
1174 parseerror(parser, "expected operator or end of statement");
1181 /* classify the operator */
1182 /* TODO: suffix operators */
1183 const oper_info *op;
1184 const oper_info *olast = NULL;
1186 for (o = 0; o < operator_count; ++o) {
1187 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1188 !(operators[o].flags & OP_SUFFIX) && /* remove this */
1189 !strcmp(parser_tokval(parser), operators[o].op))
1194 if (o == operator_count) {
1195 /* no operator found... must be the end of the statement */
1198 /* found an operator */
1201 /* when declaring variables, a comma starts a new variable */
1202 if (op->id == opid1(',') && !parens && stopatcomma) {
1203 /* fixup the token */
1208 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1209 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1212 (op->prec < olast->prec) ||
1213 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1215 if (!parser_sy_pop(parser, &sy))
1217 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1218 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1223 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1224 /* for gmqcc standard: open up the namespace of the previous type */
1225 ast_expression *prevex = sy.out[sy.out_count-1].out;
1227 parseerror(parser, "unexpected member operator");
1230 if (prevex->expression.vtype == TYPE_ENTITY)
1231 parser->memberof = TYPE_ENTITY;
1232 else if (prevex->expression.vtype == TYPE_VECTOR)
1233 parser->memberof = TYPE_VECTOR;
1235 parseerror(parser, "type error: type has no members");
1241 if (op->id == opid1('(')) {
1243 DEBUGSHUNTDO(printf("push [op] (\n"));
1245 /* we expected an operator, this is the function-call operator */
1246 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 'f', sy.out_count-1))) {
1247 parseerror(parser, "out of memory");
1252 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 1, 0))) {
1253 parseerror(parser, "out of memory");
1256 DEBUGSHUNTDO(printf("push [nop] (\n"));
1260 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1261 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1266 if (!parser_next(parser)) {
1269 if (parser->tok == ';' || parser->tok == ']') {
1274 while (sy.ops_count) {
1275 if (!parser_sy_pop(parser, &sy))
1279 parser->lex->flags.noops = true;
1280 if (!sy.out_count) {
1281 parseerror(parser, "empty expression");
1284 expr = sy.out[0].out;
1285 MEM_VECTOR_CLEAR(&sy, out);
1286 MEM_VECTOR_CLEAR(&sy, ops);
1287 DEBUGSHUNTDO(printf("shunt done\n"));
1291 parser->lex->flags.noops = true;
1292 MEM_VECTOR_CLEAR(&sy, out);
1293 MEM_VECTOR_CLEAR(&sy, ops);
1297 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1299 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1302 if (!parser_next(parser)) {
1309 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1312 ast_expression *cond, *ontrue, *onfalse = NULL;
1314 lex_ctx ctx = parser_ctx(parser);
1316 /* skip the 'if' and check for opening paren */
1317 if (!parser_next(parser) || parser->tok != '(') {
1318 parseerror(parser, "expected 'if' condition in parenthesis");
1321 /* parse into the expression */
1322 if (!parser_next(parser)) {
1323 parseerror(parser, "expected 'if' condition after opening paren");
1326 /* parse the condition */
1327 cond = parse_expression_leave(parser, false);
1331 if (parser->tok != ')') {
1332 parseerror(parser, "expected closing paren after 'if' condition");
1336 /* parse into the 'then' branch */
1337 if (!parser_next(parser)) {
1338 parseerror(parser, "expected statement for on-true branch of 'if'");
1342 ontrue = parse_statement_or_block(parser);
1347 /* check for an else */
1348 if (!strcmp(parser_tokval(parser), "else")) {
1349 /* parse into the 'else' branch */
1350 if (!parser_next(parser)) {
1351 parseerror(parser, "expected on-false branch after 'else'");
1356 onfalse = parse_statement_or_block(parser);
1364 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1365 *out = (ast_expression*)ifthen;
1369 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1372 ast_expression *cond, *ontrue;
1374 lex_ctx ctx = parser_ctx(parser);
1376 /* skip the 'while' and check for opening paren */
1377 if (!parser_next(parser) || parser->tok != '(') {
1378 parseerror(parser, "expected 'while' condition in parenthesis");
1381 /* parse into the expression */
1382 if (!parser_next(parser)) {
1383 parseerror(parser, "expected 'while' condition after opening paren");
1386 /* parse the condition */
1387 cond = parse_expression_leave(parser, false);
1391 if (parser->tok != ')') {
1392 parseerror(parser, "expected closing paren after 'while' condition");
1396 /* parse into the 'then' branch */
1397 if (!parser_next(parser)) {
1398 parseerror(parser, "expected while-loop body");
1402 ontrue = parse_statement_or_block(parser);
1408 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1409 *out = (ast_expression*)aloop;
1413 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1416 ast_expression *cond, *ontrue;
1418 lex_ctx ctx = parser_ctx(parser);
1420 /* skip the 'do' and get the body */
1421 if (!parser_next(parser)) {
1422 parseerror(parser, "expected loop body");
1425 ontrue = parse_statement_or_block(parser);
1429 /* expect the "while" */
1430 if (parser->tok != TOKEN_KEYWORD ||
1431 strcmp(parser_tokval(parser), "while"))
1433 parseerror(parser, "expected 'while' and condition");
1438 /* skip the 'while' and check for opening paren */
1439 if (!parser_next(parser) || parser->tok != '(') {
1440 parseerror(parser, "expected 'while' condition in parenthesis");
1444 /* parse into the expression */
1445 if (!parser_next(parser)) {
1446 parseerror(parser, "expected 'while' condition after opening paren");
1450 /* parse the condition */
1451 cond = parse_expression_leave(parser, false);
1455 if (parser->tok != ')') {
1456 parseerror(parser, "expected closing paren after 'while' condition");
1462 if (!parser_next(parser) || parser->tok != ';') {
1463 parseerror(parser, "expected semicolon after condition");
1469 if (!parser_next(parser)) {
1470 parseerror(parser, "parse error");
1476 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1477 *out = (ast_expression*)aloop;
1481 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1484 ast_expression *initexpr, *cond, *increment, *ontrue;
1485 size_t oldblocklocal;
1488 lex_ctx ctx = parser_ctx(parser);
1490 oldblocklocal = parser->blocklocal;
1491 parser->blocklocal = parser->locals_count;
1498 /* skip the 'while' and check for opening paren */
1499 if (!parser_next(parser) || parser->tok != '(') {
1500 parseerror(parser, "expected 'for' expressions in parenthesis");
1503 /* parse into the expression */
1504 if (!parser_next(parser)) {
1505 parseerror(parser, "expected 'for' initializer after opening paren");
1509 if (parser->tok == TOKEN_TYPENAME) {
1510 if (opts_standard != COMPILER_GMQCC) {
1511 if (parsewarning(parser, WARN_EXTENSIONS,
1512 "current standard does not allow variable declarations in for-loop initializers"))
1516 parseerror(parser, "TODO: assignment of new variables to be non-const");
1518 if (!parse_variable(parser, block, true))
1521 else if (parser->tok != ';')
1523 initexpr = parse_expression_leave(parser, false);
1528 /* move on to condition */
1529 if (parser->tok != ';') {
1530 parseerror(parser, "expected semicolon after for-loop initializer");
1533 if (!parser_next(parser)) {
1534 parseerror(parser, "expected for-loop condition");
1538 /* parse the condition */
1539 if (parser->tok != ';') {
1540 cond = parse_expression_leave(parser, false);
1545 /* move on to incrementor */
1546 if (parser->tok != ';') {
1547 parseerror(parser, "expected semicolon after for-loop initializer");
1550 if (!parser_next(parser)) {
1551 parseerror(parser, "expected for-loop condition");
1555 /* parse the incrementor */
1556 if (parser->tok != ')') {
1557 increment = parse_expression_leave(parser, false);
1560 if (!ast_istype(increment, ast_store) &&
1561 !ast_istype(increment, ast_call) &&
1562 !ast_istype(increment, ast_binstore))
1564 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1570 if (parser->tok != ')') {
1571 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1574 /* parse into the 'then' branch */
1575 if (!parser_next(parser)) {
1576 parseerror(parser, "expected for-loop body");
1579 ontrue = parse_statement_or_block(parser);
1584 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1585 *out = (ast_expression*)aloop;
1587 while (parser->locals_count > parser->blocklocal)
1588 retval = retval && parser_pop_local(parser);
1589 parser->blocklocal = oldblocklocal;
1592 if (initexpr) ast_delete(initexpr);
1593 if (cond) ast_delete(cond);
1594 if (increment) ast_delete(increment);
1595 while (parser->locals_count > parser->blocklocal)
1596 (void)!parser_pop_local(parser);
1597 parser->blocklocal = oldblocklocal;
1601 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1603 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1605 /* local variable */
1607 parseerror(parser, "cannot declare a variable from here");
1610 if (opts_standard == COMPILER_QCC) {
1611 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1614 if (!parse_variable(parser, block, false))
1619 else if (parser->tok == TOKEN_KEYWORD)
1621 if (!strcmp(parser_tokval(parser), "local"))
1624 parseerror(parser, "cannot declare a local variable here");
1627 if (!parser_next(parser)) {
1628 parseerror(parser, "expected variable declaration");
1631 if (!parse_variable(parser, block, true))
1636 else if (!strcmp(parser_tokval(parser), "return"))
1638 ast_expression *exp = NULL;
1639 ast_return *ret = NULL;
1640 ast_value *expected = parser->function->vtype;
1642 if (!parser_next(parser)) {
1643 parseerror(parser, "expected return expression");
1647 if (parser->tok != ';') {
1648 exp = parse_expression(parser, false);
1652 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1653 parseerror(parser, "return with invalid expression");
1656 ret = ast_return_new(exp->expression.node.context, exp);
1662 if (!parser_next(parser))
1663 parseerror(parser, "parse error");
1664 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1665 if (opts_standard != COMPILER_GMQCC)
1666 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1668 parseerror(parser, "return without value");
1670 ret = ast_return_new(parser_ctx(parser), NULL);
1672 *out = (ast_expression*)ret;
1675 else if (!strcmp(parser_tokval(parser), "if"))
1677 return parse_if(parser, block, out);
1679 else if (!strcmp(parser_tokval(parser), "while"))
1681 return parse_while(parser, block, out);
1683 else if (!strcmp(parser_tokval(parser), "do"))
1685 return parse_dowhile(parser, block, out);
1687 else if (!strcmp(parser_tokval(parser), "for"))
1689 if (opts_standard == COMPILER_QCC) {
1690 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1693 return parse_for(parser, block, out);
1695 parseerror(parser, "Unexpected keyword");
1698 else if (parser->tok == '{')
1701 inner = parse_block(parser, false);
1704 *out = (ast_expression*)inner;
1709 ast_expression *exp = parse_expression(parser, false);
1713 if (!ast_istype(exp, ast_store) &&
1714 !ast_istype(exp, ast_call) &&
1715 !ast_istype(exp, ast_binstore))
1717 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1724 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1727 parser->locals_count--;
1729 ve = &parser->locals[parser->locals_count];
1730 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1731 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1734 mem_d(parser->locals[parser->locals_count].name);
1738 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1740 size_t oldblocklocal;
1743 oldblocklocal = parser->blocklocal;
1744 parser->blocklocal = parser->locals_count;
1746 if (!parser_next(parser)) { /* skip the '{' */
1747 parseerror(parser, "expected function body");
1751 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1753 ast_expression *expr;
1754 if (parser->tok == '}')
1757 if (!parse_statement(parser, block, &expr)) {
1758 /* parseerror(parser, "parse error"); */
1764 if (!ast_block_exprs_add(block, expr)) {
1771 if (parser->tok != '}') {
1774 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1776 if (!block->exprs_count ||
1777 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1779 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1785 (void)parser_next(parser);
1789 while (parser->locals_count > parser->blocklocal)
1790 retval = retval && parser_pop_local(parser);
1791 parser->blocklocal = oldblocklocal;
1795 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1798 block = ast_block_new(parser_ctx(parser));
1801 if (!parse_block_into(parser, block, warnreturn)) {
1802 ast_block_delete(block);
1808 static ast_expression* parse_statement_or_block(parser_t *parser)
1810 ast_expression *expr = NULL;
1811 if (parser->tok == '{')
1812 return (ast_expression*)parse_block(parser, false);
1813 if (!parse_statement(parser, NULL, &expr))
1819 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1822 size_t len = strlen(var->name);
1824 for (i = 0; i < 3; ++i) {
1825 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1829 ve[i].name = (char*)mem_a(len+3);
1831 ast_delete(ve[i].var);
1835 memcpy(ve[i].name, var->name, len);
1836 ve[i].name[len] = '_';
1837 ve[i].name[len+1] = 'x'+i;
1838 ve[i].name[len+2] = 0;
1847 ast_delete(ve[i].var);
1854 static bool parse_function_body(parser_t *parser, ast_value *var)
1856 ast_block *block = NULL;
1861 ast_expression *framenum = NULL;
1862 ast_expression *nextthink = NULL;
1863 /* None of the following have to be deleted */
1864 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1865 ast_expression *gbl_time = NULL, *gbl_self = NULL;
1866 bool has_frame_think;
1870 has_frame_think = false;
1871 old = parser->function;
1873 if (var->expression.variadic) {
1874 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1875 "variadic function with implementation will not be able to access additional parameters"))
1881 if (parser->tok == '[') {
1882 /* got a frame definition: [ framenum, nextthink ]
1883 * this translates to:
1884 * self.frame = framenum;
1885 * self.nextthink = time + 0.1;
1886 * self.think = nextthink;
1890 fld_think = parser_find_field(parser, "think");
1891 fld_nextthink = parser_find_field(parser, "nextthink");
1892 fld_frame = parser_find_field(parser, "frame");
1893 if (!fld_think || !fld_nextthink || !fld_frame) {
1894 parseerror(parser, "cannot use [frame,think] notation without the required fields");
1895 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1898 gbl_time = parser_find_global(parser, "time");
1899 gbl_self = parser_find_global(parser, "self");
1900 if (!gbl_time || !gbl_self) {
1901 parseerror(parser, "cannot use [frame,think] notation without the required globals");
1902 parseerror(parser, "please declare the following globals: `time`, `self`");
1906 if (!parser_next(parser))
1909 framenum = parse_expression_leave(parser, true);
1911 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1914 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1915 ast_unref(framenum);
1916 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1920 if (parser->tok != ',') {
1921 ast_unref(framenum);
1922 parseerror(parser, "expected comma after frame number in [frame,think] notation");
1923 parseerror(parser, "Got a %i\n", parser->tok);
1927 if (!parser_next(parser)) {
1928 ast_unref(framenum);
1932 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1934 /* qc allows the use of not-yet-declared functions here
1935 * - this automatically creates a prototype */
1937 ast_value *thinkfunc;
1938 ast_expression *functype = fld_think->expression.next;
1940 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1941 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1942 ast_unref(framenum);
1943 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1947 if (!parser_next(parser)) {
1948 ast_unref(framenum);
1949 ast_delete(thinkfunc);
1953 varent.var = (ast_expression*)thinkfunc;
1954 varent.name = util_strdup(thinkfunc->name);
1955 if (!parser_t_globals_add(parser, varent)) {
1956 ast_unref(framenum);
1957 ast_delete(thinkfunc);
1960 nextthink = (ast_expression*)thinkfunc;
1963 nextthink = parse_expression_leave(parser, true);
1965 ast_unref(framenum);
1966 parseerror(parser, "expected a think-function in [frame,think] notation");
1971 if (!ast_istype(nextthink, ast_value)) {
1972 parseerror(parser, "think-function in [frame,think] notation must be a constant");
1976 if (retval && parser->tok != ']') {
1977 parseerror(parser, "expected closing `]` for [frame,think] notation");
1981 if (retval && !parser_next(parser)) {
1985 if (retval && parser->tok != '{') {
1986 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
1991 ast_unref(nextthink);
1992 ast_unref(framenum);
1996 has_frame_think = true;
1999 block = ast_block_new(parser_ctx(parser));
2001 parseerror(parser, "failed to allocate block");
2002 if (has_frame_think) {
2003 ast_unref(nextthink);
2004 ast_unref(framenum);
2009 if (has_frame_think) {
2011 ast_expression *self_frame;
2012 ast_expression *self_nextthink;
2013 ast_expression *self_think;
2014 ast_expression *time_plus_1;
2015 ast_store *store_frame;
2016 ast_store *store_nextthink;
2017 ast_store *store_think;
2019 ctx = parser_ctx(parser);
2020 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2021 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2022 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2024 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2025 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2027 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2028 if (self_frame) ast_delete(self_frame);
2029 if (self_nextthink) ast_delete(self_nextthink);
2030 if (self_think) ast_delete(self_think);
2031 if (time_plus_1) ast_delete(time_plus_1);
2037 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2038 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2039 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2042 ast_delete(self_frame);
2045 if (!store_nextthink) {
2046 ast_delete(self_nextthink);
2050 ast_delete(self_think);
2054 if (store_frame) ast_delete(store_frame);
2055 if (store_nextthink) ast_delete(store_nextthink);
2056 if (store_think) ast_delete(store_think);
2059 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2060 ast_delete(store_frame);
2061 ast_delete(store_nextthink);
2062 ast_delete(store_think);
2066 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2067 ast_delete(store_nextthink);
2068 ast_delete(store_think);
2072 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2074 ast_delete(store_think);
2080 parseerror(parser, "failed to generate code for [frame,think]");
2081 ast_unref(nextthink);
2082 ast_unref(framenum);
2088 for (parami = 0; parami < var->expression.params_count; ++parami) {
2091 ast_value *param = var->expression.params[parami];
2093 if (param->expression.vtype != TYPE_VECTOR &&
2094 (param->expression.vtype != TYPE_FIELD ||
2095 param->expression.next->expression.vtype != TYPE_VECTOR))
2100 if (!create_vector_members(parser, param, ve)) {
2101 ast_block_delete(block);
2105 for (e = 0; e < 3; ++e) {
2106 if (!parser_t_locals_add(parser, ve[e]))
2108 if (!ast_block_collect(block, ve[e].var)) {
2109 parser->locals_count--;
2112 ve[e].var = NULL; /* collected */
2115 parser->locals -= e;
2120 ast_block_delete(block);
2125 func = ast_function_new(ast_ctx(var), var->name, var);
2127 parseerror(parser, "failed to allocate function for `%s`", var->name);
2128 ast_block_delete(block);
2131 if (!parser_t_functions_add(parser, func)) {
2132 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2133 ast_block_delete(block);
2137 parser->function = func;
2138 if (!parse_block_into(parser, block, true)) {
2139 ast_block_delete(block);
2143 if (!ast_function_blocks_add(func, block)) {
2144 ast_block_delete(block);
2148 parser->function = old;
2149 while (parser->locals_count)
2150 retval = retval && parser_pop_local(parser);
2152 if (parser->tok == ';')
2153 return parser_next(parser);
2154 else if (opts_standard == COMPILER_QCC)
2155 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2159 parser->functions_count--;
2161 ast_function_delete(func);
2162 var->constval.vfunc = NULL;
2165 while (parser->locals_count) {
2166 parser->locals_count--;
2167 mem_d(parser->locals[parser->locals_count].name);
2169 parser->function = old;
2174 MEM_VECTOR_MAKE(ast_value*, p);
2176 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2178 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2179 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2187 bool variadic = false;
2189 ctx = parser_ctx(parser);
2191 /* for the sake of less code we parse-in in this function */
2192 if (!parser_next(parser)) {
2193 parseerror(parser, "expected parameter list");
2197 MEM_VECTOR_INIT(¶ms, p);
2199 /* parse variables until we hit a closing paren */
2200 while (parser->tok != ')') {
2202 /* there must be commas between them */
2203 if (parser->tok != ',') {
2204 parseerror(parser, "expected comma or end of parameter list");
2207 if (!parser_next(parser)) {
2208 parseerror(parser, "expected parameter");
2214 if (parser->tok == TOKEN_DOTS) {
2215 /* '...' indicates a varargs function */
2217 if (!parser_next(parser)) {
2218 parseerror(parser, "expected parameter");
2221 if (parser->tok != ')') {
2222 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2228 /* for anything else just parse a typename */
2229 param = parse_typename(parser, NULL);
2232 if (!paramlist_t_p_add(¶ms, param))
2238 if (params.p_count > 8)
2239 parseerror(parser, "more than 8 parameters are currently not supported");
2242 if (!parser_next(parser)) {
2243 parseerror(parser, "parse error after typename");
2247 /* now turn 'var' into a function type */
2248 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2249 fval->expression.next = (ast_expression*)var;
2250 fval->expression.variadic = variadic;
2253 MEM_VECTOR_MOVE(¶ms, p, &var->expression, params);
2259 for (i = 0; i < params.p_count; ++i)
2260 ast_delete(params.p[i]);
2261 MEM_VECTOR_CLEAR(¶ms, p);
2265 /* Parse a complete typename.
2266 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2267 * but when parsing variables separated by comma
2268 * 'storebase' should point to where the base-type should be kept.
2269 * The base type makes up every bit of type information which comes *before* the
2272 * The following will be parsed in its entirety:
2274 * The 'basetype' in this case is 'void()'
2275 * and if there's a comma after it, say:
2277 * then the type-information 'void()' can be stored in 'storebase'
2279 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2281 ast_value *var, *tmp;
2284 const char *name = NULL;
2285 bool isfield = false;
2287 ctx = parser_ctx(parser);
2289 /* types may start with a dot */
2290 if (parser->tok == '.') {
2292 /* if we parsed a dot we need a typename now */
2293 if (!parser_next(parser)) {
2294 parseerror(parser, "expected typename for field definition");
2297 if (parser->tok != TOKEN_TYPENAME) {
2298 parseerror(parser, "expected typename");
2303 /* generate the basic type value */
2304 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2305 /* do not yet turn into a field - remember:
2306 * .void() foo; is a field too
2307 * .void()() foo; is a function
2311 if (!parser_next(parser)) {
2313 parseerror(parser, "parse error after typename");
2317 /* an opening paren now starts the parameter-list of a function */
2318 if (parser->tok == '(') {
2319 var = parse_parameter_list(parser, var);
2323 /* This is the point where we can turn it into a field */
2325 /* turn it into a field if desired */
2326 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2327 tmp->expression.next = (ast_expression*)var;
2331 while (parser->tok == '(') {
2332 var = parse_parameter_list(parser, var);
2337 /* store the base if requested */
2339 *storebase = ast_value_copy(var);
2342 /* there may be a name now */
2343 if (parser->tok == TOKEN_IDENT) {
2344 name = util_strdup(parser_tokval(parser));
2346 if (!parser_next(parser)) {
2347 parseerror(parser, "error after variable or field declaration");
2352 /* now there may be function parens again */
2353 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2354 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2355 while (parser->tok == '(') {
2356 var = parse_parameter_list(parser, var);
2364 /* finally name it */
2366 if (!ast_value_set_name(var, name)) {
2368 parseerror(parser, "internal error: failed to set name");
2371 /* free the name, ast_value_set_name duplicates */
2378 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2382 ast_expression *old;
2386 ast_value *basetype = NULL;
2388 bool isparam = false;
2389 bool isvector = false;
2390 bool cleanvar = true;
2392 varentry_t varent, ve[3];
2394 /* get the first complete variable */
2395 var = parse_typename(parser, &basetype);
2398 ast_delete(basetype);
2402 memset(&varent, 0, sizeof(varent));
2403 memset(&ve, 0, sizeof(ve));
2408 /* Part 0: finish the type */
2409 while (parser->tok == '(') {
2410 if (opts_standard == COMPILER_QCC)
2411 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2412 var = parse_parameter_list(parser, var);
2420 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2421 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2422 * is then filled with the previous definition and the parameter-names replaced.
2425 /* Deal with end_sys_ vars */
2427 if (!strcmp(var->name, "end_sys_globals")) {
2428 parser->crc_globals = parser->globals_count;
2431 else if (!strcmp(var->name, "end_sys_fields")) {
2432 parser->crc_fields = parser->fields_count;
2435 if (was_end && var->expression.vtype == TYPE_FIELD) {
2436 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2437 "global '%s' hint should not be a field",
2438 parser_tokval(parser)))
2445 if (!nofields && var->expression.vtype == TYPE_FIELD)
2447 /* deal with field declarations */
2448 old = parser_find_field(parser, var->name);
2450 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2451 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2460 parseerror(parser, "field `%s` already declared here: %s:%i",
2461 var->name, ast_ctx(old).file, ast_ctx(old).line);
2466 if (opts_standard == COMPILER_QCC &&
2467 (old = parser_find_global(parser, var->name)))
2469 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2470 parseerror(parser, "field `%s` already declared here: %s:%i",
2471 var->name, ast_ctx(old).file, ast_ctx(old).line);
2478 /* deal with other globals */
2479 old = parser_find_global(parser, var->name);
2480 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2482 /* This is a function which had a prototype */
2483 if (!ast_istype(old, ast_value)) {
2484 parseerror(parser, "internal error: prototype is not an ast_value");
2488 proto = (ast_value*)old;
2489 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2490 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2492 ast_ctx(proto).file, ast_ctx(proto).line);
2496 /* we need the new parameter-names */
2497 for (i = 0; i < proto->expression.params_count; ++i)
2498 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2506 parseerror(parser, "global `%s` already declared here: %s:%i",
2507 var->name, ast_ctx(old).file, ast_ctx(old).line);
2511 if (opts_standard == COMPILER_QCC &&
2512 (old = parser_find_field(parser, var->name)))
2514 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2515 parseerror(parser, "global `%s` already declared here: %s:%i",
2516 var->name, ast_ctx(old).file, ast_ctx(old).line);
2523 else /* it's not a global */
2525 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2526 if (old && !isparam) {
2527 parseerror(parser, "local `%s` already declared here: %s:%i",
2528 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2532 old = parser_find_local(parser, var->name, 0, &isparam);
2533 if (old && isparam) {
2534 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2535 "local `%s` is shadowing a parameter", var->name))
2537 parseerror(parser, "local `%s` already declared here: %s:%i",
2538 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2542 if (opts_standard != COMPILER_GMQCC) {
2551 * Create the global/local, and deal with vector types.
2554 if (var->expression.vtype == TYPE_VECTOR)
2556 else if (var->expression.vtype == TYPE_FIELD &&
2557 var->expression.next->expression.vtype == TYPE_VECTOR)
2561 if (!create_vector_members(parser, var, ve)) {
2567 varent.name = util_strdup(var->name);
2568 varent.var = (ast_expression*)var;
2571 /* deal with global variables, fields, functions */
2572 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2573 if (!(retval = parser_t_fields_add(parser, varent)))
2576 for (i = 0; i < 3; ++i) {
2577 if (!(retval = parser_t_fields_add(parser, ve[i])))
2581 parser->fields_count -= i+1;
2587 if (!(retval = parser_t_globals_add(parser, varent)))
2590 for (i = 0; i < 3; ++i) {
2591 if (!(retval = parser_t_globals_add(parser, ve[i])))
2595 parser->globals_count -= i+1;
2601 if (!(retval = parser_t_locals_add(parser, varent)))
2603 if (!(retval = ast_block_locals_add(localblock, var))) {
2604 parser->locals_count--;
2608 for (i = 0; i < 3; ++i) {
2609 if (!(retval = parser_t_locals_add(parser, ve[i])))
2611 if (!(retval = ast_block_collect(localblock, ve[i].var)))
2613 ve[i].var = NULL; /* from here it's being collected in the block */
2616 parser->locals_count -= i+1;
2617 localblock->locals_count--;
2624 ve[0].name = ve[1].name = ve[2].name = NULL;
2625 ve[0].var = ve[1].var = ve[2].var = NULL;
2630 if (parser->tok == ';') {
2631 ast_delete(basetype);
2632 if (!parser_next(parser)) {
2633 parseerror(parser, "error after variable declaration");
2639 if (parser->tok == ',')
2642 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
2643 parseerror(parser, "missing comma or semicolon while parsing variables");
2647 if (localblock && opts_standard == COMPILER_QCC) {
2648 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
2649 "initializing expression turns variable `%s` into a constant in this standard",
2656 if (parser->tok != '{') {
2657 if (parser->tok != '=') {
2658 parseerror(parser, "missing semicolon or initializer");
2662 if (!parser_next(parser)) {
2663 parseerror(parser, "error parsing initializer");
2667 else if (opts_standard == COMPILER_QCC) {
2668 parseerror(parser, "expected '=' before function body in this standard");
2671 if (parser->tok == '#') {
2675 parseerror(parser, "cannot declare builtins within functions");
2678 if (var->expression.vtype != TYPE_FUNCTION) {
2679 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
2682 if (!parser_next(parser)) {
2683 parseerror(parser, "expected builtin number");
2686 if (parser->tok != TOKEN_INTCONST) {
2687 parseerror(parser, "builtin number must be an integer constant");
2690 if (parser_token(parser)->constval.i <= 0) {
2691 parseerror(parser, "builtin number must be an integer greater than zero");
2695 func = ast_function_new(ast_ctx(var), var->name, var);
2697 parseerror(parser, "failed to allocate function for `%s`", var->name);
2700 if (!parser_t_functions_add(parser, func)) {
2701 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2702 ast_function_delete(func);
2703 var->constval.vfunc = NULL;
2707 func->builtin = -parser_token(parser)->constval.i;
2709 if (!parser_next(parser)) {
2710 parseerror(parser, "expected comma or semicolon");
2711 ast_function_delete(func);
2712 var->constval.vfunc = NULL;
2716 else if (parser->tok == '{' || parser->tok == '[')
2719 parseerror(parser, "cannot declare functions within functions");
2723 if (!parse_function_body(parser, var))
2725 ast_delete(basetype);
2728 ast_expression *cexp;
2731 cexp = parse_expression_leave(parser, true);
2736 cval = (ast_value*)cexp;
2737 if (!ast_istype(cval, ast_value) || !cval->isconst)
2738 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
2741 var->isconst = true;
2742 if (cval->expression.vtype == TYPE_STRING)
2743 var->constval.vstring = parser_strdup(cval->constval.vstring);
2745 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
2750 MEM_VECTOR_INIT(&sy, out);
2751 MEM_VECTOR_INIT(&sy, ops);
2752 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
2753 !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
2754 !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
2756 parseerror(parser, "internal error: failed to prepare initializer");
2759 else if (!parser_sy_pop(parser, &sy))
2762 if (sy.out_count != 1 && sy.ops_count != 0)
2763 parseerror(parser, "internal error: leaked operands");
2764 else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
2765 parseerror(parser, "failed to create intializing expression");
2766 ast_unref(sy.out[0].out);
2770 MEM_VECTOR_CLEAR(&sy, out);
2771 MEM_VECTOR_CLEAR(&sy, ops);
2776 if (parser->tok == ',') {
2777 if (!parser_next(parser)) {
2778 parseerror(parser, "expected another variable");
2782 if (parser->tok != TOKEN_IDENT) {
2783 parseerror(parser, "expected another variable");
2786 var = ast_value_copy(basetype);
2788 ast_value_set_name(var, parser_tokval(parser));
2789 if (!parser_next(parser)) {
2790 parseerror(parser, "error parsing variable declaration");
2796 if (parser->tok != ';') {
2797 parseerror(parser, "missing semicolon after variables");
2801 if (!parser_next(parser)) {
2802 parseerror(parser, "parse error after variable declaration");
2806 ast_delete(basetype);
2810 if (cleanvar && var)
2812 ast_delete(basetype);
2816 ast_delete(basetype);
2817 if (cleanvar && var)
2819 if (varent.name) mem_d(varent.name);
2820 if (ve[0].name) mem_d(ve[0].name);
2821 if (ve[1].name) mem_d(ve[1].name);
2822 if (ve[2].name) mem_d(ve[2].name);
2823 if (ve[0].var) mem_d(ve[0].var);
2824 if (ve[1].var) mem_d(ve[1].var);
2825 if (ve[2].var) mem_d(ve[2].var);
2829 static bool parser_global_statement(parser_t *parser)
2831 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2833 return parse_variable(parser, NULL, false);
2835 else if (parser->tok == TOKEN_KEYWORD)
2837 /* handle 'var' and 'const' */
2838 if (!strcmp(parser_tokval(parser), "var")) {
2839 if (!parser_next(parser)) {
2840 parseerror(parser, "expected variable declaration after 'var'");
2843 return parse_variable(parser, NULL, true);
2847 else if (parser->tok == '$')
2849 if (!parser_next(parser)) {
2850 parseerror(parser, "parse error");
2856 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
2862 static parser_t *parser;
2867 parser = (parser_t*)mem_a(sizeof(parser_t));
2871 memset(parser, 0, sizeof(*parser));
2873 for (i = 0; i < operator_count; ++i) {
2874 if (operators[i].id == opid1('=')) {
2875 parser->assign_op = operators+i;
2879 if (!parser->assign_op) {
2880 printf("internal error: initializing parser: failed to find assign operator\n");
2887 bool parser_compile(const char *filename)
2889 parser->lex = lex_open(filename);
2891 printf("failed to open file \"%s\"\n", filename);
2895 /* initial lexer/parser state */
2896 parser->lex->flags.noops = true;
2898 if (parser_next(parser))
2900 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2902 if (!parser_global_statement(parser)) {
2903 if (parser->tok == TOKEN_EOF)
2904 parseerror(parser, "unexpected eof");
2905 else if (!parser->errors)
2906 parseerror(parser, "there have been errors, bailing out");
2907 lex_close(parser->lex);
2913 parseerror(parser, "parse error");
2914 lex_close(parser->lex);
2919 lex_close(parser->lex);
2922 return !parser->errors;
2925 void parser_cleanup()
2928 for (i = 0; i < parser->functions_count; ++i) {
2929 ast_delete(parser->functions[i]);
2931 for (i = 0; i < parser->imm_vector_count; ++i) {
2932 ast_delete(parser->imm_vector[i]);
2934 for (i = 0; i < parser->imm_string_count; ++i) {
2935 ast_delete(parser->imm_string[i]);
2937 for (i = 0; i < parser->imm_float_count; ++i) {
2938 ast_delete(parser->imm_float[i]);
2940 for (i = 0; i < parser->fields_count; ++i) {
2941 ast_delete(parser->fields[i].var);
2942 mem_d(parser->fields[i].name);
2944 for (i = 0; i < parser->globals_count; ++i) {
2945 ast_delete(parser->globals[i].var);
2946 mem_d(parser->globals[i].name);
2948 MEM_VECTOR_CLEAR(parser, functions);
2949 MEM_VECTOR_CLEAR(parser, imm_vector);
2950 MEM_VECTOR_CLEAR(parser, imm_string);
2951 MEM_VECTOR_CLEAR(parser, imm_float);
2952 MEM_VECTOR_CLEAR(parser, globals);
2953 MEM_VECTOR_CLEAR(parser, fields);
2954 MEM_VECTOR_CLEAR(parser, locals);
2959 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
2961 return util_crc16(old, str, strlen(str));
2964 static void progdefs_crc_file(const char *str)
2966 /* write to progdefs.h here */
2969 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
2971 old = progdefs_crc_sum(old, str);
2972 progdefs_crc_file(str);
2976 static void generate_checksum(parser_t *parser)
2978 uint16_t crc = 0xFFFF;
2981 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
2982 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
2984 progdefs_crc_file("\tint\tpad;\n");
2985 progdefs_crc_file("\tint\tofs_return[3];\n");
2986 progdefs_crc_file("\tint\tofs_parm0[3];\n");
2987 progdefs_crc_file("\tint\tofs_parm1[3];\n");
2988 progdefs_crc_file("\tint\tofs_parm2[3];\n");
2989 progdefs_crc_file("\tint\tofs_parm3[3];\n");
2990 progdefs_crc_file("\tint\tofs_parm4[3];\n");
2991 progdefs_crc_file("\tint\tofs_parm5[3];\n");
2992 progdefs_crc_file("\tint\tofs_parm6[3];\n");
2993 progdefs_crc_file("\tint\tofs_parm7[3];\n");
2995 for (i = 0; i < parser->crc_globals; ++i) {
2996 if (!ast_istype(parser->globals[i].var, ast_value))
2998 switch (parser->globals[i].var->expression.vtype) {
2999 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3000 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3001 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3002 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3004 crc = progdefs_crc_both(crc, "\tint\t");
3007 crc = progdefs_crc_both(crc, parser->globals[i].name);
3008 crc = progdefs_crc_both(crc, ";\n");
3010 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3011 for (i = 0; i < parser->crc_fields; ++i) {
3012 if (!ast_istype(parser->fields[i].var, ast_value))
3014 switch (parser->fields[i].var->expression.next->expression.vtype) {
3015 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3016 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3017 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3018 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3020 crc = progdefs_crc_both(crc, "\tint\t");
3023 crc = progdefs_crc_both(crc, parser->fields[i].name);
3024 crc = progdefs_crc_both(crc, ";\n");
3026 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3031 bool parser_finish(const char *output)
3037 if (!parser->errors)
3039 ir = ir_builder_new("gmqcc_out");
3041 printf("failed to allocate builder\n");
3045 for (i = 0; i < parser->fields_count; ++i) {
3048 if (!ast_istype(parser->fields[i].var, ast_value))
3050 field = (ast_value*)parser->fields[i].var;
3051 isconst = field->isconst;
3052 field->isconst = false;
3053 if (!ast_global_codegen((ast_value*)field, ir, true)) {
3054 printf("failed to generate field %s\n", field->name);
3055 ir_builder_delete(ir);
3060 ast_expression *subtype;
3061 field->isconst = true;
3062 subtype = field->expression.next;
3063 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3064 if (subtype->expression.vtype == TYPE_FIELD)
3065 ifld->fieldtype = subtype->expression.next->expression.vtype;
3066 else if (subtype->expression.vtype == TYPE_FUNCTION)
3067 ifld->outtype = subtype->expression.next->expression.vtype;
3068 (void)!ir_value_set_field(field->ir_v, ifld);
3071 for (i = 0; i < parser->globals_count; ++i) {
3073 if (!ast_istype(parser->globals[i].var, ast_value))
3075 asvalue = (ast_value*)(parser->globals[i].var);
3076 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3077 if (strcmp(asvalue->name, "end_sys_globals") &&
3078 strcmp(asvalue->name, "end_sys_fields"))
3080 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3081 "unused global: `%s`", asvalue->name);
3084 if (!ast_global_codegen(asvalue, ir, false)) {
3085 printf("failed to generate global %s\n", parser->globals[i].name);
3086 ir_builder_delete(ir);
3090 for (i = 0; i < parser->imm_float_count; ++i) {
3091 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3092 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3093 ir_builder_delete(ir);
3097 for (i = 0; i < parser->imm_string_count; ++i) {
3098 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3099 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3100 ir_builder_delete(ir);
3104 for (i = 0; i < parser->imm_vector_count; ++i) {
3105 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3106 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3107 ir_builder_delete(ir);
3111 for (i = 0; i < parser->functions_count; ++i) {
3112 if (!ast_function_codegen(parser->functions[i], ir)) {
3113 printf("failed to generate function %s\n", parser->functions[i]->name);
3114 ir_builder_delete(ir);
3117 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3118 printf("failed to finalize function %s\n", parser->functions[i]->name);
3119 ir_builder_delete(ir);
3126 ir_builder_dump(ir, printf);
3128 generate_checksum(parser);
3130 if (!ir_builder_generate(ir, output)) {
3131 printf("*** failed to generate output file\n");
3132 ir_builder_delete(ir);
3137 ir_builder_delete(ir);
3141 printf("*** there were compile errors\n");