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 == '[') {
1152 parseerror(parser, "internal error: '[' should be classified as operator");
1155 else if (parser->tok == ')') {
1157 DEBUGSHUNTDO(printf("do[op] )\n"));
1161 /* we do expect an operator next */
1162 /* closing an opening paren */
1163 if (!parser_close_paren(parser, &sy, false))
1166 DEBUGSHUNTDO(printf("do[nop] )\n"));
1170 /* allowed for function calls */
1171 if (!parser_close_paren(parser, &sy, true))
1176 else if (parser->tok != TOKEN_OPERATOR) {
1178 parseerror(parser, "expected operator or end of statement");
1185 /* classify the operator */
1186 /* TODO: suffix operators */
1187 const oper_info *op;
1188 const oper_info *olast = NULL;
1190 for (o = 0; o < operator_count; ++o) {
1191 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1192 !(operators[o].flags & OP_SUFFIX) && /* remove this */
1193 !strcmp(parser_tokval(parser), operators[o].op))
1198 if (o == operator_count) {
1199 /* no operator found... must be the end of the statement */
1202 /* found an operator */
1205 /* when declaring variables, a comma starts a new variable */
1206 if (op->id == opid1(',') && !parens && stopatcomma) {
1207 /* fixup the token */
1212 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1213 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1216 (op->prec < olast->prec) ||
1217 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1219 if (!parser_sy_pop(parser, &sy))
1221 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1222 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1227 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1228 /* for gmqcc standard: open up the namespace of the previous type */
1229 ast_expression *prevex = sy.out[sy.out_count-1].out;
1231 parseerror(parser, "unexpected member operator");
1234 if (prevex->expression.vtype == TYPE_ENTITY)
1235 parser->memberof = TYPE_ENTITY;
1236 else if (prevex->expression.vtype == TYPE_VECTOR)
1237 parser->memberof = TYPE_VECTOR;
1239 parseerror(parser, "type error: type has no members");
1245 if (op->id == opid1('(')) {
1247 DEBUGSHUNTDO(printf("push [op] (\n"));
1249 /* we expected an operator, this is the function-call operator */
1250 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 'f', sy.out_count-1))) {
1251 parseerror(parser, "out of memory");
1256 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), 1, 0))) {
1257 parseerror(parser, "out of memory");
1260 DEBUGSHUNTDO(printf("push [nop] (\n"));
1264 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1265 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1270 if (!parser_next(parser)) {
1273 if (parser->tok == ';' || parser->tok == ']') {
1278 while (sy.ops_count) {
1279 if (!parser_sy_pop(parser, &sy))
1283 parser->lex->flags.noops = true;
1284 if (!sy.out_count) {
1285 parseerror(parser, "empty expression");
1288 expr = sy.out[0].out;
1289 MEM_VECTOR_CLEAR(&sy, out);
1290 MEM_VECTOR_CLEAR(&sy, ops);
1291 DEBUGSHUNTDO(printf("shunt done\n"));
1295 parser->lex->flags.noops = true;
1296 MEM_VECTOR_CLEAR(&sy, out);
1297 MEM_VECTOR_CLEAR(&sy, ops);
1301 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1303 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1306 if (!parser_next(parser)) {
1313 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1316 ast_expression *cond, *ontrue, *onfalse = NULL;
1318 lex_ctx ctx = parser_ctx(parser);
1320 /* skip the 'if' and check for opening paren */
1321 if (!parser_next(parser) || parser->tok != '(') {
1322 parseerror(parser, "expected 'if' condition in parenthesis");
1325 /* parse into the expression */
1326 if (!parser_next(parser)) {
1327 parseerror(parser, "expected 'if' condition after opening paren");
1330 /* parse the condition */
1331 cond = parse_expression_leave(parser, false);
1335 if (parser->tok != ')') {
1336 parseerror(parser, "expected closing paren after 'if' condition");
1340 /* parse into the 'then' branch */
1341 if (!parser_next(parser)) {
1342 parseerror(parser, "expected statement for on-true branch of 'if'");
1346 ontrue = parse_statement_or_block(parser);
1351 /* check for an else */
1352 if (!strcmp(parser_tokval(parser), "else")) {
1353 /* parse into the 'else' branch */
1354 if (!parser_next(parser)) {
1355 parseerror(parser, "expected on-false branch after 'else'");
1360 onfalse = parse_statement_or_block(parser);
1368 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1369 *out = (ast_expression*)ifthen;
1373 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1376 ast_expression *cond, *ontrue;
1378 lex_ctx ctx = parser_ctx(parser);
1380 /* skip the 'while' and check for opening paren */
1381 if (!parser_next(parser) || parser->tok != '(') {
1382 parseerror(parser, "expected 'while' condition in parenthesis");
1385 /* parse into the expression */
1386 if (!parser_next(parser)) {
1387 parseerror(parser, "expected 'while' condition after opening paren");
1390 /* parse the condition */
1391 cond = parse_expression_leave(parser, false);
1395 if (parser->tok != ')') {
1396 parseerror(parser, "expected closing paren after 'while' condition");
1400 /* parse into the 'then' branch */
1401 if (!parser_next(parser)) {
1402 parseerror(parser, "expected while-loop body");
1406 ontrue = parse_statement_or_block(parser);
1412 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1413 *out = (ast_expression*)aloop;
1417 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1420 ast_expression *cond, *ontrue;
1422 lex_ctx ctx = parser_ctx(parser);
1424 /* skip the 'do' and get the body */
1425 if (!parser_next(parser)) {
1426 parseerror(parser, "expected loop body");
1429 ontrue = parse_statement_or_block(parser);
1433 /* expect the "while" */
1434 if (parser->tok != TOKEN_KEYWORD ||
1435 strcmp(parser_tokval(parser), "while"))
1437 parseerror(parser, "expected 'while' and condition");
1442 /* skip the 'while' and check for opening paren */
1443 if (!parser_next(parser) || parser->tok != '(') {
1444 parseerror(parser, "expected 'while' condition in parenthesis");
1448 /* parse into the expression */
1449 if (!parser_next(parser)) {
1450 parseerror(parser, "expected 'while' condition after opening paren");
1454 /* parse the condition */
1455 cond = parse_expression_leave(parser, false);
1459 if (parser->tok != ')') {
1460 parseerror(parser, "expected closing paren after 'while' condition");
1466 if (!parser_next(parser) || parser->tok != ';') {
1467 parseerror(parser, "expected semicolon after condition");
1473 if (!parser_next(parser)) {
1474 parseerror(parser, "parse error");
1480 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1481 *out = (ast_expression*)aloop;
1485 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1488 ast_expression *initexpr, *cond, *increment, *ontrue;
1489 size_t oldblocklocal;
1492 lex_ctx ctx = parser_ctx(parser);
1494 oldblocklocal = parser->blocklocal;
1495 parser->blocklocal = parser->locals_count;
1502 /* skip the 'while' and check for opening paren */
1503 if (!parser_next(parser) || parser->tok != '(') {
1504 parseerror(parser, "expected 'for' expressions in parenthesis");
1507 /* parse into the expression */
1508 if (!parser_next(parser)) {
1509 parseerror(parser, "expected 'for' initializer after opening paren");
1513 if (parser->tok == TOKEN_TYPENAME) {
1514 if (opts_standard != COMPILER_GMQCC) {
1515 if (parsewarning(parser, WARN_EXTENSIONS,
1516 "current standard does not allow variable declarations in for-loop initializers"))
1520 parseerror(parser, "TODO: assignment of new variables to be non-const");
1522 if (!parse_variable(parser, block, true))
1525 else if (parser->tok != ';')
1527 initexpr = parse_expression_leave(parser, false);
1532 /* move on to condition */
1533 if (parser->tok != ';') {
1534 parseerror(parser, "expected semicolon after for-loop initializer");
1537 if (!parser_next(parser)) {
1538 parseerror(parser, "expected for-loop condition");
1542 /* parse the condition */
1543 if (parser->tok != ';') {
1544 cond = parse_expression_leave(parser, false);
1549 /* move on to incrementor */
1550 if (parser->tok != ';') {
1551 parseerror(parser, "expected semicolon after for-loop initializer");
1554 if (!parser_next(parser)) {
1555 parseerror(parser, "expected for-loop condition");
1559 /* parse the incrementor */
1560 if (parser->tok != ')') {
1561 increment = parse_expression_leave(parser, false);
1564 if (!ast_istype(increment, ast_store) &&
1565 !ast_istype(increment, ast_call) &&
1566 !ast_istype(increment, ast_binstore))
1568 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1574 if (parser->tok != ')') {
1575 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1578 /* parse into the 'then' branch */
1579 if (!parser_next(parser)) {
1580 parseerror(parser, "expected for-loop body");
1583 ontrue = parse_statement_or_block(parser);
1588 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1589 *out = (ast_expression*)aloop;
1591 while (parser->locals_count > parser->blocklocal)
1592 retval = retval && parser_pop_local(parser);
1593 parser->blocklocal = oldblocklocal;
1596 if (initexpr) ast_delete(initexpr);
1597 if (cond) ast_delete(cond);
1598 if (increment) ast_delete(increment);
1599 while (parser->locals_count > parser->blocklocal)
1600 (void)!parser_pop_local(parser);
1601 parser->blocklocal = oldblocklocal;
1605 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1607 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1609 /* local variable */
1611 parseerror(parser, "cannot declare a variable from here");
1614 if (opts_standard == COMPILER_QCC) {
1615 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1618 if (!parse_variable(parser, block, false))
1623 else if (parser->tok == TOKEN_KEYWORD)
1625 if (!strcmp(parser_tokval(parser), "local"))
1628 parseerror(parser, "cannot declare a local variable here");
1631 if (!parser_next(parser)) {
1632 parseerror(parser, "expected variable declaration");
1635 if (!parse_variable(parser, block, true))
1640 else if (!strcmp(parser_tokval(parser), "return"))
1642 ast_expression *exp = NULL;
1643 ast_return *ret = NULL;
1644 ast_value *expected = parser->function->vtype;
1646 if (!parser_next(parser)) {
1647 parseerror(parser, "expected return expression");
1651 if (parser->tok != ';') {
1652 exp = parse_expression(parser, false);
1656 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1657 parseerror(parser, "return with invalid expression");
1660 ret = ast_return_new(exp->expression.node.context, exp);
1666 if (!parser_next(parser))
1667 parseerror(parser, "parse error");
1668 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1669 if (opts_standard != COMPILER_GMQCC)
1670 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1672 parseerror(parser, "return without value");
1674 ret = ast_return_new(parser_ctx(parser), NULL);
1676 *out = (ast_expression*)ret;
1679 else if (!strcmp(parser_tokval(parser), "if"))
1681 return parse_if(parser, block, out);
1683 else if (!strcmp(parser_tokval(parser), "while"))
1685 return parse_while(parser, block, out);
1687 else if (!strcmp(parser_tokval(parser), "do"))
1689 return parse_dowhile(parser, block, out);
1691 else if (!strcmp(parser_tokval(parser), "for"))
1693 if (opts_standard == COMPILER_QCC) {
1694 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1697 return parse_for(parser, block, out);
1699 parseerror(parser, "Unexpected keyword");
1702 else if (parser->tok == '{')
1705 inner = parse_block(parser, false);
1708 *out = (ast_expression*)inner;
1713 ast_expression *exp = parse_expression(parser, false);
1717 if (!ast_istype(exp, ast_store) &&
1718 !ast_istype(exp, ast_call) &&
1719 !ast_istype(exp, ast_binstore))
1721 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1728 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1731 parser->locals_count--;
1733 ve = &parser->locals[parser->locals_count];
1734 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1735 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1738 mem_d(parser->locals[parser->locals_count].name);
1742 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1744 size_t oldblocklocal;
1747 oldblocklocal = parser->blocklocal;
1748 parser->blocklocal = parser->locals_count;
1750 if (!parser_next(parser)) { /* skip the '{' */
1751 parseerror(parser, "expected function body");
1755 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1757 ast_expression *expr;
1758 if (parser->tok == '}')
1761 if (!parse_statement(parser, block, &expr)) {
1762 /* parseerror(parser, "parse error"); */
1768 if (!ast_block_exprs_add(block, expr)) {
1775 if (parser->tok != '}') {
1778 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1780 if (!block->exprs_count ||
1781 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1783 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1789 (void)parser_next(parser);
1793 while (parser->locals_count > parser->blocklocal)
1794 retval = retval && parser_pop_local(parser);
1795 parser->blocklocal = oldblocklocal;
1799 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1802 block = ast_block_new(parser_ctx(parser));
1805 if (!parse_block_into(parser, block, warnreturn)) {
1806 ast_block_delete(block);
1812 static ast_expression* parse_statement_or_block(parser_t *parser)
1814 ast_expression *expr = NULL;
1815 if (parser->tok == '{')
1816 return (ast_expression*)parse_block(parser, false);
1817 if (!parse_statement(parser, NULL, &expr))
1823 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1826 size_t len = strlen(var->name);
1828 for (i = 0; i < 3; ++i) {
1829 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1833 ve[i].name = (char*)mem_a(len+3);
1835 ast_delete(ve[i].var);
1839 memcpy(ve[i].name, var->name, len);
1840 ve[i].name[len] = '_';
1841 ve[i].name[len+1] = 'x'+i;
1842 ve[i].name[len+2] = 0;
1851 ast_delete(ve[i].var);
1858 static bool parse_function_body(parser_t *parser, ast_value *var)
1860 ast_block *block = NULL;
1865 ast_expression *framenum = NULL;
1866 ast_expression *nextthink = NULL;
1867 /* None of the following have to be deleted */
1868 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1869 ast_expression *gbl_time = NULL, *gbl_self = NULL;
1870 bool has_frame_think;
1874 has_frame_think = false;
1875 old = parser->function;
1877 if (var->expression.variadic) {
1878 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1879 "variadic function with implementation will not be able to access additional parameters"))
1885 if (parser->tok == '[') {
1886 /* got a frame definition: [ framenum, nextthink ]
1887 * this translates to:
1888 * self.frame = framenum;
1889 * self.nextthink = time + 0.1;
1890 * self.think = nextthink;
1894 fld_think = parser_find_field(parser, "think");
1895 fld_nextthink = parser_find_field(parser, "nextthink");
1896 fld_frame = parser_find_field(parser, "frame");
1897 if (!fld_think || !fld_nextthink || !fld_frame) {
1898 parseerror(parser, "cannot use [frame,think] notation without the required fields");
1899 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1902 gbl_time = parser_find_global(parser, "time");
1903 gbl_self = parser_find_global(parser, "self");
1904 if (!gbl_time || !gbl_self) {
1905 parseerror(parser, "cannot use [frame,think] notation without the required globals");
1906 parseerror(parser, "please declare the following globals: `time`, `self`");
1910 if (!parser_next(parser))
1913 framenum = parse_expression_leave(parser, true);
1915 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1918 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1919 ast_unref(framenum);
1920 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1924 if (parser->tok != ',') {
1925 ast_unref(framenum);
1926 parseerror(parser, "expected comma after frame number in [frame,think] notation");
1927 parseerror(parser, "Got a %i\n", parser->tok);
1931 if (!parser_next(parser)) {
1932 ast_unref(framenum);
1936 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1938 /* qc allows the use of not-yet-declared functions here
1939 * - this automatically creates a prototype */
1941 ast_value *thinkfunc;
1942 ast_expression *functype = fld_think->expression.next;
1944 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1945 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1946 ast_unref(framenum);
1947 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1951 if (!parser_next(parser)) {
1952 ast_unref(framenum);
1953 ast_delete(thinkfunc);
1957 varent.var = (ast_expression*)thinkfunc;
1958 varent.name = util_strdup(thinkfunc->name);
1959 if (!parser_t_globals_add(parser, varent)) {
1960 ast_unref(framenum);
1961 ast_delete(thinkfunc);
1964 nextthink = (ast_expression*)thinkfunc;
1967 nextthink = parse_expression_leave(parser, true);
1969 ast_unref(framenum);
1970 parseerror(parser, "expected a think-function in [frame,think] notation");
1975 if (!ast_istype(nextthink, ast_value)) {
1976 parseerror(parser, "think-function in [frame,think] notation must be a constant");
1980 if (retval && parser->tok != ']') {
1981 parseerror(parser, "expected closing `]` for [frame,think] notation");
1985 if (retval && !parser_next(parser)) {
1989 if (retval && parser->tok != '{') {
1990 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
1995 ast_unref(nextthink);
1996 ast_unref(framenum);
2000 has_frame_think = true;
2003 block = ast_block_new(parser_ctx(parser));
2005 parseerror(parser, "failed to allocate block");
2006 if (has_frame_think) {
2007 ast_unref(nextthink);
2008 ast_unref(framenum);
2013 if (has_frame_think) {
2015 ast_expression *self_frame;
2016 ast_expression *self_nextthink;
2017 ast_expression *self_think;
2018 ast_expression *time_plus_1;
2019 ast_store *store_frame;
2020 ast_store *store_nextthink;
2021 ast_store *store_think;
2023 ctx = parser_ctx(parser);
2024 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2025 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2026 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2028 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2029 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2031 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2032 if (self_frame) ast_delete(self_frame);
2033 if (self_nextthink) ast_delete(self_nextthink);
2034 if (self_think) ast_delete(self_think);
2035 if (time_plus_1) ast_delete(time_plus_1);
2041 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2042 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2043 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2046 ast_delete(self_frame);
2049 if (!store_nextthink) {
2050 ast_delete(self_nextthink);
2054 ast_delete(self_think);
2058 if (store_frame) ast_delete(store_frame);
2059 if (store_nextthink) ast_delete(store_nextthink);
2060 if (store_think) ast_delete(store_think);
2063 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2064 ast_delete(store_frame);
2065 ast_delete(store_nextthink);
2066 ast_delete(store_think);
2070 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2071 ast_delete(store_nextthink);
2072 ast_delete(store_think);
2076 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2078 ast_delete(store_think);
2084 parseerror(parser, "failed to generate code for [frame,think]");
2085 ast_unref(nextthink);
2086 ast_unref(framenum);
2092 for (parami = 0; parami < var->expression.params_count; ++parami) {
2095 ast_value *param = var->expression.params[parami];
2097 if (param->expression.vtype != TYPE_VECTOR &&
2098 (param->expression.vtype != TYPE_FIELD ||
2099 param->expression.next->expression.vtype != TYPE_VECTOR))
2104 if (!create_vector_members(parser, param, ve)) {
2105 ast_block_delete(block);
2109 for (e = 0; e < 3; ++e) {
2110 if (!parser_t_locals_add(parser, ve[e]))
2112 if (!ast_block_collect(block, ve[e].var)) {
2113 parser->locals_count--;
2116 ve[e].var = NULL; /* collected */
2119 parser->locals -= e;
2124 ast_block_delete(block);
2129 func = ast_function_new(ast_ctx(var), var->name, var);
2131 parseerror(parser, "failed to allocate function for `%s`", var->name);
2132 ast_block_delete(block);
2135 if (!parser_t_functions_add(parser, func)) {
2136 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2137 ast_block_delete(block);
2141 parser->function = func;
2142 if (!parse_block_into(parser, block, true)) {
2143 ast_block_delete(block);
2147 if (!ast_function_blocks_add(func, block)) {
2148 ast_block_delete(block);
2152 parser->function = old;
2153 while (parser->locals_count)
2154 retval = retval && parser_pop_local(parser);
2156 if (parser->tok == ';')
2157 return parser_next(parser);
2158 else if (opts_standard == COMPILER_QCC)
2159 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2163 parser->functions_count--;
2165 ast_function_delete(func);
2166 var->constval.vfunc = NULL;
2169 while (parser->locals_count) {
2170 parser->locals_count--;
2171 mem_d(parser->locals[parser->locals_count].name);
2173 parser->function = old;
2178 MEM_VECTOR_MAKE(ast_value*, p);
2180 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2182 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2183 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2191 bool variadic = false;
2193 ctx = parser_ctx(parser);
2195 /* for the sake of less code we parse-in in this function */
2196 if (!parser_next(parser)) {
2197 parseerror(parser, "expected parameter list");
2201 MEM_VECTOR_INIT(¶ms, p);
2203 /* parse variables until we hit a closing paren */
2204 while (parser->tok != ')') {
2206 /* there must be commas between them */
2207 if (parser->tok != ',') {
2208 parseerror(parser, "expected comma or end of parameter list");
2211 if (!parser_next(parser)) {
2212 parseerror(parser, "expected parameter");
2218 if (parser->tok == TOKEN_DOTS) {
2219 /* '...' indicates a varargs function */
2221 if (!parser_next(parser)) {
2222 parseerror(parser, "expected parameter");
2225 if (parser->tok != ')') {
2226 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2232 /* for anything else just parse a typename */
2233 param = parse_typename(parser, NULL);
2236 if (!paramlist_t_p_add(¶ms, param))
2242 if (params.p_count > 8)
2243 parseerror(parser, "more than 8 parameters are currently not supported");
2246 if (!parser_next(parser)) {
2247 parseerror(parser, "parse error after typename");
2251 /* now turn 'var' into a function type */
2252 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2253 fval->expression.next = (ast_expression*)var;
2254 fval->expression.variadic = variadic;
2257 MEM_VECTOR_MOVE(¶ms, p, &var->expression, params);
2263 for (i = 0; i < params.p_count; ++i)
2264 ast_delete(params.p[i]);
2265 MEM_VECTOR_CLEAR(¶ms, p);
2269 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2271 ast_expression *cexp;
2272 ast_value *cval, *tmp;
2275 ctx = parser_ctx(parser);
2277 if (!parser_next(parser)) {
2279 parseerror(parser, "expected array-size");
2283 cexp = parse_expression_leave(parser, true);
2285 if (!cexp || !ast_istype(cexp, ast_value)) {
2289 parseerror(parser, "expected array-size as constant positive integer");
2292 cval = (ast_value*)cexp;
2294 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2295 tmp->expression.next = (ast_expression*)var;
2298 if (cval->expression.vtype == TYPE_INTEGER)
2299 tmp->expression.count = cval->constval.vint;
2300 else if (cval->expression.vtype == TYPE_FLOAT)
2301 tmp->expression.count = cval->constval.vfloat;
2305 parseerror(parser, "array-size must be a positive integer constant");
2310 if (parser->tok != ']') {
2312 parseerror(parser, "expected ']' after array-size");
2315 if (!parser_next(parser)) {
2317 parseerror(parser, "error after parsing array size");
2323 /* Parse a complete typename.
2324 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2325 * but when parsing variables separated by comma
2326 * 'storebase' should point to where the base-type should be kept.
2327 * The base type makes up every bit of type information which comes *before* the
2330 * The following will be parsed in its entirety:
2332 * The 'basetype' in this case is 'void()'
2333 * and if there's a comma after it, say:
2335 * then the type-information 'void()' can be stored in 'storebase'
2337 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2339 ast_value *var, *tmp;
2342 const char *name = NULL;
2343 bool isfield = false;
2345 ctx = parser_ctx(parser);
2347 /* types may start with a dot */
2348 if (parser->tok == '.') {
2350 /* if we parsed a dot we need a typename now */
2351 if (!parser_next(parser)) {
2352 parseerror(parser, "expected typename for field definition");
2355 if (parser->tok != TOKEN_TYPENAME) {
2356 parseerror(parser, "expected typename");
2361 /* generate the basic type value */
2362 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2363 /* do not yet turn into a field - remember:
2364 * .void() foo; is a field too
2365 * .void()() foo; is a function
2369 if (!parser_next(parser)) {
2371 parseerror(parser, "parse error after typename");
2375 /* an opening paren now starts the parameter-list of a function
2376 * this is where original-QC has parameter lists.
2377 * We allow a single parameter list here.
2378 * Much like fteqcc we don't allow `float()() x`
2380 if (parser->tok == '(') {
2381 var = parse_parameter_list(parser, var);
2386 /* store the base if requested */
2388 *storebase = ast_value_copy(var);
2390 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2391 tmp->expression.next = (ast_expression*)*storebase;
2396 /* there may be a name now */
2397 if (parser->tok == TOKEN_IDENT) {
2398 name = util_strdup(parser_tokval(parser));
2400 if (!parser_next(parser)) {
2402 parseerror(parser, "error after variable or field declaration");
2407 /* now this may be an array */
2408 if (parser->tok == '[') {
2409 var = parse_arraysize(parser, var);
2414 /* This is the point where we can turn it into a field */
2416 /* turn it into a field if desired */
2417 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2418 tmp->expression.next = (ast_expression*)var;
2422 /* now there may be function parens again */
2423 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2424 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2425 while (parser->tok == '(') {
2426 var = parse_parameter_list(parser, var);
2435 /* finally name it */
2437 if (!ast_value_set_name(var, name)) {
2439 parseerror(parser, "internal error: failed to set name");
2442 /* free the name, ast_value_set_name duplicates */
2449 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2453 ast_expression *old;
2457 ast_value *basetype = NULL;
2459 bool isparam = false;
2460 bool isvector = false;
2461 bool cleanvar = true;
2462 bool wasarray = false;
2464 varentry_t varent, ve[3];
2466 /* get the first complete variable */
2467 var = parse_typename(parser, &basetype);
2470 ast_delete(basetype);
2474 memset(&varent, 0, sizeof(varent));
2475 memset(&ve, 0, sizeof(ve));
2481 /* Part 0: finish the type */
2482 if (parser->tok == '(') {
2483 if (opts_standard == COMPILER_QCC)
2484 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2485 var = parse_parameter_list(parser, var);
2491 /* we only allow 1-dimensional arrays */
2492 if (parser->tok == '[') {
2494 var = parse_arraysize(parser, var);
2500 if (parser->tok == '(' && wasarray) {
2501 parseerror(parser, "functions cannot return arrays");
2502 /* we'll still parse the type completely for now */
2504 /* for functions returning functions */
2505 while (parser->tok == '(') {
2506 if (opts_standard == COMPILER_QCC)
2507 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2508 var = parse_parameter_list(parser, var);
2516 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2517 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2518 * is then filled with the previous definition and the parameter-names replaced.
2521 /* Deal with end_sys_ vars */
2523 if (!strcmp(var->name, "end_sys_globals")) {
2524 parser->crc_globals = parser->globals_count;
2527 else if (!strcmp(var->name, "end_sys_fields")) {
2528 parser->crc_fields = parser->fields_count;
2531 if (was_end && var->expression.vtype == TYPE_FIELD) {
2532 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2533 "global '%s' hint should not be a field",
2534 parser_tokval(parser)))
2541 if (!nofields && var->expression.vtype == TYPE_FIELD)
2543 /* deal with field declarations */
2544 old = parser_find_field(parser, var->name);
2546 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2547 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2556 parseerror(parser, "field `%s` already declared here: %s:%i",
2557 var->name, ast_ctx(old).file, ast_ctx(old).line);
2562 if (opts_standard == COMPILER_QCC &&
2563 (old = parser_find_global(parser, var->name)))
2565 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2566 parseerror(parser, "field `%s` already declared here: %s:%i",
2567 var->name, ast_ctx(old).file, ast_ctx(old).line);
2574 /* deal with other globals */
2575 old = parser_find_global(parser, var->name);
2576 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2578 /* This is a function which had a prototype */
2579 if (!ast_istype(old, ast_value)) {
2580 parseerror(parser, "internal error: prototype is not an ast_value");
2584 proto = (ast_value*)old;
2585 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2586 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2588 ast_ctx(proto).file, ast_ctx(proto).line);
2592 /* we need the new parameter-names */
2593 for (i = 0; i < proto->expression.params_count; ++i)
2594 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2602 parseerror(parser, "global `%s` already declared here: %s:%i",
2603 var->name, ast_ctx(old).file, ast_ctx(old).line);
2607 if (opts_standard == COMPILER_QCC &&
2608 (old = parser_find_field(parser, var->name)))
2610 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2611 parseerror(parser, "global `%s` already declared here: %s:%i",
2612 var->name, ast_ctx(old).file, ast_ctx(old).line);
2619 else /* it's not a global */
2621 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2622 if (old && !isparam) {
2623 parseerror(parser, "local `%s` already declared here: %s:%i",
2624 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2628 old = parser_find_local(parser, var->name, 0, &isparam);
2629 if (old && isparam) {
2630 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2631 "local `%s` is shadowing a parameter", var->name))
2633 parseerror(parser, "local `%s` already declared here: %s:%i",
2634 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2638 if (opts_standard != COMPILER_GMQCC) {
2647 * Create the global/local, and deal with vector types.
2650 if (var->expression.vtype == TYPE_VECTOR)
2652 else if (var->expression.vtype == TYPE_FIELD &&
2653 var->expression.next->expression.vtype == TYPE_VECTOR)
2657 if (!create_vector_members(parser, var, ve)) {
2663 varent.name = util_strdup(var->name);
2664 varent.var = (ast_expression*)var;
2667 /* deal with global variables, fields, functions */
2668 if (!nofields && var->expression.vtype == TYPE_FIELD) {
2669 if (!(retval = parser_t_fields_add(parser, varent)))
2672 for (i = 0; i < 3; ++i) {
2673 if (!(retval = parser_t_fields_add(parser, ve[i])))
2677 parser->fields_count -= i+1;
2683 if (!(retval = parser_t_globals_add(parser, varent)))
2686 for (i = 0; i < 3; ++i) {
2687 if (!(retval = parser_t_globals_add(parser, ve[i])))
2691 parser->globals_count -= i+1;
2697 if (!(retval = parser_t_locals_add(parser, varent)))
2699 if (!(retval = ast_block_locals_add(localblock, var))) {
2700 parser->locals_count--;
2704 for (i = 0; i < 3; ++i) {
2705 if (!(retval = parser_t_locals_add(parser, ve[i])))
2707 if (!(retval = ast_block_collect(localblock, ve[i].var)))
2709 ve[i].var = NULL; /* from here it's being collected in the block */
2712 parser->locals_count -= i+1;
2713 localblock->locals_count--;
2720 ve[0].name = ve[1].name = ve[2].name = NULL;
2721 ve[0].var = ve[1].var = ve[2].var = NULL;
2726 if (parser->tok == ';') {
2727 ast_delete(basetype);
2728 if (!parser_next(parser)) {
2729 parseerror(parser, "error after variable declaration");
2735 if (parser->tok == ',')
2738 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
2739 parseerror(parser, "missing comma or semicolon while parsing variables");
2743 if (localblock && opts_standard == COMPILER_QCC) {
2744 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
2745 "initializing expression turns variable `%s` into a constant in this standard",
2752 if (parser->tok != '{') {
2753 if (parser->tok != '=') {
2754 parseerror(parser, "missing semicolon or initializer");
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "error parsing initializer");
2763 else if (opts_standard == COMPILER_QCC) {
2764 parseerror(parser, "expected '=' before function body in this standard");
2767 if (parser->tok == '#') {
2771 parseerror(parser, "cannot declare builtins within functions");
2774 if (var->expression.vtype != TYPE_FUNCTION) {
2775 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
2778 if (!parser_next(parser)) {
2779 parseerror(parser, "expected builtin number");
2782 if (parser->tok != TOKEN_INTCONST) {
2783 parseerror(parser, "builtin number must be an integer constant");
2786 if (parser_token(parser)->constval.i <= 0) {
2787 parseerror(parser, "builtin number must be an integer greater than zero");
2791 func = ast_function_new(ast_ctx(var), var->name, var);
2793 parseerror(parser, "failed to allocate function for `%s`", var->name);
2796 if (!parser_t_functions_add(parser, func)) {
2797 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2798 ast_function_delete(func);
2799 var->constval.vfunc = NULL;
2803 func->builtin = -parser_token(parser)->constval.i;
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "expected comma or semicolon");
2807 ast_function_delete(func);
2808 var->constval.vfunc = NULL;
2812 else if (parser->tok == '{' || parser->tok == '[')
2815 parseerror(parser, "cannot declare functions within functions");
2819 if (!parse_function_body(parser, var))
2821 ast_delete(basetype);
2824 ast_expression *cexp;
2827 cexp = parse_expression_leave(parser, true);
2832 cval = (ast_value*)cexp;
2833 if (!ast_istype(cval, ast_value) || !cval->isconst)
2834 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
2837 var->isconst = true;
2838 if (cval->expression.vtype == TYPE_STRING)
2839 var->constval.vstring = parser_strdup(cval->constval.vstring);
2841 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
2846 MEM_VECTOR_INIT(&sy, out);
2847 MEM_VECTOR_INIT(&sy, ops);
2848 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
2849 !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
2850 !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
2852 parseerror(parser, "internal error: failed to prepare initializer");
2855 else if (!parser_sy_pop(parser, &sy))
2858 if (sy.out_count != 1 && sy.ops_count != 0)
2859 parseerror(parser, "internal error: leaked operands");
2860 else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
2861 parseerror(parser, "failed to create intializing expression");
2862 ast_unref(sy.out[0].out);
2866 MEM_VECTOR_CLEAR(&sy, out);
2867 MEM_VECTOR_CLEAR(&sy, ops);
2872 if (parser->tok == ',') {
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "expected another variable");
2878 if (parser->tok != TOKEN_IDENT) {
2879 parseerror(parser, "expected another variable");
2882 var = ast_value_copy(basetype);
2884 ast_value_set_name(var, parser_tokval(parser));
2885 if (!parser_next(parser)) {
2886 parseerror(parser, "error parsing variable declaration");
2892 if (parser->tok != ';') {
2893 parseerror(parser, "missing semicolon after variables");
2897 if (!parser_next(parser)) {
2898 parseerror(parser, "parse error after variable declaration");
2902 ast_delete(basetype);
2906 if (cleanvar && var)
2908 ast_delete(basetype);
2912 ast_delete(basetype);
2913 if (cleanvar && var)
2915 if (varent.name) mem_d(varent.name);
2916 if (ve[0].name) mem_d(ve[0].name);
2917 if (ve[1].name) mem_d(ve[1].name);
2918 if (ve[2].name) mem_d(ve[2].name);
2919 if (ve[0].var) mem_d(ve[0].var);
2920 if (ve[1].var) mem_d(ve[1].var);
2921 if (ve[2].var) mem_d(ve[2].var);
2925 static bool parser_global_statement(parser_t *parser)
2927 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2929 return parse_variable(parser, NULL, false);
2931 else if (parser->tok == TOKEN_KEYWORD)
2933 /* handle 'var' and 'const' */
2934 if (!strcmp(parser_tokval(parser), "var")) {
2935 if (!parser_next(parser)) {
2936 parseerror(parser, "expected variable declaration after 'var'");
2939 return parse_variable(parser, NULL, true);
2943 else if (parser->tok == '$')
2945 if (!parser_next(parser)) {
2946 parseerror(parser, "parse error");
2952 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
2958 static parser_t *parser;
2963 parser = (parser_t*)mem_a(sizeof(parser_t));
2967 memset(parser, 0, sizeof(*parser));
2969 for (i = 0; i < operator_count; ++i) {
2970 if (operators[i].id == opid1('=')) {
2971 parser->assign_op = operators+i;
2975 if (!parser->assign_op) {
2976 printf("internal error: initializing parser: failed to find assign operator\n");
2983 bool parser_compile(const char *filename)
2985 parser->lex = lex_open(filename);
2987 printf("failed to open file \"%s\"\n", filename);
2991 /* initial lexer/parser state */
2992 parser->lex->flags.noops = true;
2994 if (parser_next(parser))
2996 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2998 if (!parser_global_statement(parser)) {
2999 if (parser->tok == TOKEN_EOF)
3000 parseerror(parser, "unexpected eof");
3001 else if (!parser->errors)
3002 parseerror(parser, "there have been errors, bailing out");
3003 lex_close(parser->lex);
3009 parseerror(parser, "parse error");
3010 lex_close(parser->lex);
3015 lex_close(parser->lex);
3018 return !parser->errors;
3021 void parser_cleanup()
3024 for (i = 0; i < parser->functions_count; ++i) {
3025 ast_delete(parser->functions[i]);
3027 for (i = 0; i < parser->imm_vector_count; ++i) {
3028 ast_delete(parser->imm_vector[i]);
3030 for (i = 0; i < parser->imm_string_count; ++i) {
3031 ast_delete(parser->imm_string[i]);
3033 for (i = 0; i < parser->imm_float_count; ++i) {
3034 ast_delete(parser->imm_float[i]);
3036 for (i = 0; i < parser->fields_count; ++i) {
3037 ast_delete(parser->fields[i].var);
3038 mem_d(parser->fields[i].name);
3040 for (i = 0; i < parser->globals_count; ++i) {
3041 ast_delete(parser->globals[i].var);
3042 mem_d(parser->globals[i].name);
3044 MEM_VECTOR_CLEAR(parser, functions);
3045 MEM_VECTOR_CLEAR(parser, imm_vector);
3046 MEM_VECTOR_CLEAR(parser, imm_string);
3047 MEM_VECTOR_CLEAR(parser, imm_float);
3048 MEM_VECTOR_CLEAR(parser, globals);
3049 MEM_VECTOR_CLEAR(parser, fields);
3050 MEM_VECTOR_CLEAR(parser, locals);
3055 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3057 return util_crc16(old, str, strlen(str));
3060 static void progdefs_crc_file(const char *str)
3062 /* write to progdefs.h here */
3065 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3067 old = progdefs_crc_sum(old, str);
3068 progdefs_crc_file(str);
3072 static void generate_checksum(parser_t *parser)
3074 uint16_t crc = 0xFFFF;
3077 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3078 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3080 progdefs_crc_file("\tint\tpad;\n");
3081 progdefs_crc_file("\tint\tofs_return[3];\n");
3082 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3083 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3084 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3085 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3086 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3087 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3088 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3089 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3091 for (i = 0; i < parser->crc_globals; ++i) {
3092 if (!ast_istype(parser->globals[i].var, ast_value))
3094 switch (parser->globals[i].var->expression.vtype) {
3095 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3096 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3097 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3098 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3100 crc = progdefs_crc_both(crc, "\tint\t");
3103 crc = progdefs_crc_both(crc, parser->globals[i].name);
3104 crc = progdefs_crc_both(crc, ";\n");
3106 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3107 for (i = 0; i < parser->crc_fields; ++i) {
3108 if (!ast_istype(parser->fields[i].var, ast_value))
3110 switch (parser->fields[i].var->expression.next->expression.vtype) {
3111 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3112 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3113 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3114 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3116 crc = progdefs_crc_both(crc, "\tint\t");
3119 crc = progdefs_crc_both(crc, parser->fields[i].name);
3120 crc = progdefs_crc_both(crc, ";\n");
3122 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3127 bool parser_finish(const char *output)
3133 if (!parser->errors)
3135 ir = ir_builder_new("gmqcc_out");
3137 printf("failed to allocate builder\n");
3141 for (i = 0; i < parser->fields_count; ++i) {
3144 if (!ast_istype(parser->fields[i].var, ast_value))
3146 field = (ast_value*)parser->fields[i].var;
3147 isconst = field->isconst;
3148 field->isconst = false;
3149 if (!ast_global_codegen((ast_value*)field, ir, true)) {
3150 printf("failed to generate field %s\n", field->name);
3151 ir_builder_delete(ir);
3156 ast_expression *subtype;
3157 field->isconst = true;
3158 subtype = field->expression.next;
3159 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3160 if (subtype->expression.vtype == TYPE_FIELD)
3161 ifld->fieldtype = subtype->expression.next->expression.vtype;
3162 else if (subtype->expression.vtype == TYPE_FUNCTION)
3163 ifld->outtype = subtype->expression.next->expression.vtype;
3164 (void)!ir_value_set_field(field->ir_v, ifld);
3167 for (i = 0; i < parser->globals_count; ++i) {
3169 if (!ast_istype(parser->globals[i].var, ast_value))
3171 asvalue = (ast_value*)(parser->globals[i].var);
3172 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3173 if (strcmp(asvalue->name, "end_sys_globals") &&
3174 strcmp(asvalue->name, "end_sys_fields"))
3176 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3177 "unused global: `%s`", asvalue->name);
3180 if (!ast_global_codegen(asvalue, ir, false)) {
3181 printf("failed to generate global %s\n", parser->globals[i].name);
3182 ir_builder_delete(ir);
3186 for (i = 0; i < parser->imm_float_count; ++i) {
3187 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3188 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3189 ir_builder_delete(ir);
3193 for (i = 0; i < parser->imm_string_count; ++i) {
3194 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3195 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3196 ir_builder_delete(ir);
3200 for (i = 0; i < parser->imm_vector_count; ++i) {
3201 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3202 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3203 ir_builder_delete(ir);
3207 for (i = 0; i < parser->functions_count; ++i) {
3208 if (!ast_function_codegen(parser->functions[i], ir)) {
3209 printf("failed to generate function %s\n", parser->functions[i]->name);
3210 ir_builder_delete(ir);
3213 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3214 printf("failed to finalize function %s\n", parser->functions[i]->name);
3215 ir_builder_delete(ir);
3222 ir_builder_dump(ir, printf);
3224 generate_checksum(parser);
3226 if (!ir_builder_generate(ir, output)) {
3227 printf("*** failed to generate output file\n");
3228 ir_builder_delete(ir);
3233 ir_builder_delete(ir);
3237 printf("*** there were compile errors\n");