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 #define SY_PAREN_EXPR '('
330 #define SY_PAREN_FUNC 'f'
331 #define SY_PAREN_INDEX '['
333 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
344 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
348 e.out = (ast_expression*)v;
355 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
357 e.etype = 1 + (op - operators);
366 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
378 # define DEBUGSHUNTDO(x) x
380 # define DEBUGSHUNTDO(x)
383 static bool parser_sy_pop(parser_t *parser, shunt *sy)
387 ast_expression *out = NULL;
388 ast_expression *exprs[3];
389 ast_block *blocks[3];
390 ast_value *asvalue[3];
392 qcint generated_op = 0;
397 if (!sy->ops_count) {
398 parseerror(parser, "internal error: missing operator");
402 if (sy->ops[sy->ops_count-1].paren) {
403 parseerror(parser, "unmatched parenthesis");
407 op = &operators[sy->ops[sy->ops_count-1].etype - 1];
408 ctx = sy->ops[sy->ops_count-1].ctx;
410 DEBUGSHUNTDO(printf("apply %s\n", op->op));
412 if (sy->out_count < op->operands) {
413 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", sy->out_count,
414 op->op, (int)op->id);
420 sy->out_count -= op->operands;
421 for (i = 0; i < op->operands; ++i) {
422 exprs[i] = sy->out[sy->out_count+i].out;
423 blocks[i] = sy->out[sy->out_count+i].block;
424 asvalue[i] = (ast_value*)exprs[i];
427 if (blocks[0] && !blocks[0]->exprs_count && op->id != opid1(',')) {
428 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
432 #define NotSameType(T) \
433 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
434 exprs[0]->expression.vtype != T)
435 #define CanConstFold1(A) \
436 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
437 #define CanConstFold(A, B) \
438 (CanConstFold1(A) && CanConstFold1(B))
439 #define ConstV(i) (asvalue[(i)]->constval.vvec)
440 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
441 #define ConstS(i) (asvalue[(i)]->constval.vstring)
445 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
449 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
450 if (exprs[1]->expression.vtype != TYPE_FIELD) {
451 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
454 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
456 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
457 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
461 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
468 if (!ast_block_exprs_add(blocks[0], exprs[1]))
471 blocks[0] = ast_block_new(ctx);
472 if (!ast_block_exprs_add(blocks[0], exprs[0]) ||
473 !ast_block_exprs_add(blocks[0], exprs[1]))
478 if (!ast_block_set_type(blocks[0], exprs[1]))
481 sy->out[sy->out_count++] = syblock(ctx, blocks[0]);
485 switch (exprs[0]->expression.vtype) {
487 if (CanConstFold1(exprs[0]))
488 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
490 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
491 (ast_expression*)parser_const_float_0(parser),
495 if (CanConstFold1(exprs[0]))
496 out = (ast_expression*)parser_const_vector_f(parser,
497 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
499 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
500 (ast_expression*)parser_const_vector_0(parser),
504 parseerror(parser, "invalid types used in expression: cannot negate type %s",
505 type_name[exprs[0]->expression.vtype]);
511 switch (exprs[0]->expression.vtype) {
513 if (CanConstFold1(exprs[0]))
514 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
516 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
519 if (CanConstFold1(exprs[0]))
520 out = (ast_expression*)parser_const_float(parser,
521 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
523 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
526 if (CanConstFold1(exprs[0]))
527 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
529 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
531 /* we don't constant-fold NOT for these types */
533 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
536 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
539 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
540 type_name[exprs[0]->expression.vtype]);
546 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
547 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
549 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
550 type_name[exprs[0]->expression.vtype],
551 type_name[exprs[1]->expression.vtype]);
554 switch (exprs[0]->expression.vtype) {
556 if (CanConstFold(exprs[0], exprs[1]))
558 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
561 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
564 if (CanConstFold(exprs[0], exprs[1]))
565 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
567 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
570 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
571 type_name[exprs[0]->expression.vtype],
572 type_name[exprs[1]->expression.vtype]);
577 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
578 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
580 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
581 type_name[exprs[1]->expression.vtype],
582 type_name[exprs[0]->expression.vtype]);
585 switch (exprs[0]->expression.vtype) {
587 if (CanConstFold(exprs[0], exprs[1]))
588 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
590 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
593 if (CanConstFold(exprs[0], exprs[1]))
594 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
596 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
599 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
600 type_name[exprs[1]->expression.vtype],
601 type_name[exprs[0]->expression.vtype]);
606 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
607 exprs[0]->expression.vtype != TYPE_VECTOR &&
608 exprs[0]->expression.vtype != TYPE_FLOAT &&
609 exprs[1]->expression.vtype != TYPE_VECTOR &&
610 exprs[1]->expression.vtype != TYPE_FLOAT)
612 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
613 type_name[exprs[1]->expression.vtype],
614 type_name[exprs[0]->expression.vtype]);
617 switch (exprs[0]->expression.vtype) {
619 if (exprs[1]->expression.vtype == TYPE_VECTOR)
621 if (CanConstFold(exprs[0], exprs[1]))
622 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
624 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
628 if (CanConstFold(exprs[0], exprs[1]))
629 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
631 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
635 if (exprs[1]->expression.vtype == TYPE_FLOAT)
637 if (CanConstFold(exprs[0], exprs[1]))
638 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
640 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
644 if (CanConstFold(exprs[0], exprs[1]))
645 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
647 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
651 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
652 type_name[exprs[1]->expression.vtype],
653 type_name[exprs[0]->expression.vtype]);
658 if (NotSameType(TYPE_FLOAT)) {
659 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
660 type_name[exprs[0]->expression.vtype],
661 type_name[exprs[1]->expression.vtype]);
664 if (CanConstFold(exprs[0], exprs[1]))
665 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
667 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
671 parseerror(parser, "qc does not have a modulo operator");
675 if (NotSameType(TYPE_FLOAT)) {
676 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
677 type_name[exprs[0]->expression.vtype],
678 type_name[exprs[1]->expression.vtype]);
681 if (CanConstFold(exprs[0], exprs[1]))
682 out = (ast_expression*)parser_const_float(parser,
683 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
684 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
686 out = (ast_expression*)ast_binary_new(ctx,
687 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
691 parseerror(parser, "TODO: bitxor");
696 case opid3('<','<','='):
697 case opid3('>','>','='):
698 parseerror(parser, "TODO: shifts");
702 generated_op += 1; /* INSTR_OR */
704 generated_op += INSTR_AND;
705 if (NotSameType(TYPE_FLOAT)) {
706 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
707 type_name[exprs[0]->expression.vtype],
708 type_name[exprs[1]->expression.vtype]);
709 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
710 parseerror(parser, "TODO: optional early out");
713 if (opts_standard == COMPILER_GMQCC)
714 printf("TODO: early out logic\n");
715 if (CanConstFold(exprs[0], exprs[1]))
716 out = (ast_expression*)parser_const_float(parser,
717 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
719 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
723 generated_op += 1; /* INSTR_GT */
725 generated_op += 1; /* INSTR_LT */
726 case opid2('>', '='):
727 generated_op += 1; /* INSTR_GE */
728 case opid2('<', '='):
729 generated_op += INSTR_LE;
730 if (NotSameType(TYPE_FLOAT)) {
731 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
732 type_name[exprs[0]->expression.vtype],
733 type_name[exprs[1]->expression.vtype]);
736 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
738 case opid2('!', '='):
739 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
740 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
741 type_name[exprs[0]->expression.vtype],
742 type_name[exprs[1]->expression.vtype]);
745 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
747 case opid2('=', '='):
748 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
749 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
750 type_name[exprs[0]->expression.vtype],
751 type_name[exprs[1]->expression.vtype]);
754 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
758 if (ast_istype(exprs[0], ast_entfield)) {
759 ast_expression *field = ((ast_entfield*)exprs[0])->field;
760 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
761 exprs[0]->expression.vtype == TYPE_FIELD &&
762 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
764 assignop = type_storep_instr[TYPE_VECTOR];
767 assignop = type_storep_instr[exprs[0]->expression.vtype];
768 if (!ast_compare_type(field->expression.next, exprs[1])) {
769 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
770 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
771 if (opts_standard == COMPILER_QCC &&
772 field->expression.next->expression.vtype == TYPE_FUNCTION &&
773 exprs[1]->expression.vtype == TYPE_FUNCTION)
775 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
776 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
782 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
787 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
788 exprs[0]->expression.vtype == TYPE_FIELD &&
789 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
791 assignop = type_store_instr[TYPE_VECTOR];
794 assignop = type_store_instr[exprs[0]->expression.vtype];
797 if (assignop == AINSTR_END) {
798 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
799 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
800 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
802 else if (!ast_compare_type(exprs[0], exprs[1])) {
803 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
804 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
805 if (opts_standard == COMPILER_QCC &&
806 exprs[0]->expression.vtype == TYPE_FUNCTION &&
807 exprs[1]->expression.vtype == TYPE_FUNCTION)
809 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
810 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
816 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
819 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
823 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
824 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
826 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
827 type_name[exprs[0]->expression.vtype],
828 type_name[exprs[1]->expression.vtype]);
831 if (ast_istype(exprs[0], ast_entfield))
832 assignop = type_storep_instr[exprs[0]->expression.vtype];
834 assignop = type_store_instr[exprs[0]->expression.vtype];
835 switch (exprs[0]->expression.vtype) {
837 out = (ast_expression*)ast_binstore_new(ctx, assignop,
838 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
842 out = (ast_expression*)ast_binstore_new(ctx, assignop,
843 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
847 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
848 type_name[exprs[0]->expression.vtype],
849 type_name[exprs[1]->expression.vtype]);
857 parseerror(parser, "failed to apply operand %s", op->op);
861 DEBUGSHUNTDO(printf("applied %s\n", op->op));
862 sy->out[sy->out_count++] = syexp(ctx, out);
866 static bool parser_close_call(parser_t *parser, shunt *sy)
868 /* was a function call */
876 fid = sy->ops[sy->ops_count].off;
878 /* out[fid] is the function
879 * everything above is parameters...
881 * 1 params = ast_expression
885 if (sy->out_count < 1 || sy->out_count <= fid) {
886 parseerror(parser, "internal error: function call needs function and parameter list...");
890 fun = sy->out[fid].out;
892 call = ast_call_new(sy->ops[sy->ops_count].ctx, fun);
894 parseerror(parser, "out of memory");
898 if (fid+1 == sy->out_count) {
901 } else if (fid+2 == sy->out_count) {
904 params = sy->out[sy->out_count].block;
908 if (!ast_call_params_add(call, sy->out[sy->out_count].out)) {
909 ast_delete(sy->out[sy->out_count].out);
910 parseerror(parser, "out of memory");
914 paramcount = params->exprs_count;
915 MEM_VECTOR_MOVE(params, exprs, call, params);
918 if (!ast_call_check_types(call))
921 parseerror(parser, "invalid function call");
925 /* overwrite fid, the function, with a call */
926 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
928 if (fun->expression.vtype != TYPE_FUNCTION) {
929 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
933 if (!fun->expression.next) {
934 parseerror(parser, "could not determine function return type");
937 if (fun->expression.params_count != paramcount &&
938 !(fun->expression.variadic &&
939 fun->expression.params_count < paramcount))
942 const char *fewmany = (fun->expression.params_count > paramcount) ? "few" : "many";
944 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
945 if (opts_standard == COMPILER_GMQCC)
948 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
949 " -> `%s` has been declared here: %s:%i",
950 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
951 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
953 parseerror(parser, "too %s parameters for function call: 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);
962 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
963 "too %s parameters for call to %s: expected %i, got %i\n"
964 " -> `%s` has been declared here: %s:%i",
965 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
966 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
968 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
969 "too %s parameters for function call: expected %i, got %i\n"
970 " -> `%s` has been declared here: %s:%i",
971 fewmany, fval->name, (int)fun->expression.params_count, (int)paramcount,
972 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
980 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
982 if (!sy->ops_count) {
983 parseerror(parser, "unmatched closing paren");
986 /* this would for bit a + (x) because there are no operators inside (x)
987 if (sy->ops[sy->ops_count-1].paren == 1) {
988 parseerror(parser, "empty parenthesis expression");
992 while (sy->ops_count) {
993 if (sy->ops[sy->ops_count-1].paren == SY_PAREN_FUNC) {
994 if (!parser_close_call(parser, sy))
998 if (sy->ops[sy->ops_count-1].paren == SY_PAREN_EXPR) {
1000 return !functions_only;
1002 if (sy->ops[sy->ops_count-1].paren == SY_PAREN_INDEX) {
1006 if (!parser_sy_pop(parser, sy))
1012 static void parser_reclassify_token(parser_t *parser)
1015 for (i = 0; i < operator_count; ++i) {
1016 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1017 parser->tok = TOKEN_OPERATOR;
1023 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1025 ast_expression *expr = NULL;
1027 bool wantop = false;
1028 bool gotmemberof = false;
1030 /* count the parens because an if starts with one, so the
1031 * end of a condition is an unmatched closing paren
1035 MEM_VECTOR_INIT(&sy, out);
1036 MEM_VECTOR_INIT(&sy, ops);
1038 parser->lex->flags.noops = false;
1040 parser_reclassify_token(parser);
1045 gotmemberof = false;
1047 parser->memberof = 0;
1049 if (parser->tok == TOKEN_IDENT)
1051 ast_expression *var;
1053 parseerror(parser, "expected operator or end of statement");
1058 if (opts_standard == COMPILER_GMQCC)
1060 if (parser->memberof == TYPE_ENTITY) {
1061 /* still get vars first since there could be a fieldpointer */
1062 var = parser_find_var(parser, parser_tokval(parser));
1064 var = parser_find_field(parser, parser_tokval(parser));
1066 else if (parser->memberof == TYPE_VECTOR)
1068 parseerror(parser, "TODO: implement effective vector member access");
1071 else if (parser->memberof) {
1072 parseerror(parser, "namespace for member not found");
1076 var = parser_find_var(parser, parser_tokval(parser));
1078 var = parser_find_var(parser, parser_tokval(parser));
1080 var = parser_find_field(parser, parser_tokval(parser));
1083 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1086 if (ast_istype(var, ast_value))
1087 ((ast_value*)var)->uses++;
1088 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), var))) {
1089 parseerror(parser, "out of memory");
1092 DEBUGSHUNTDO(printf("push %s\n", parser_tokval(parser)));
1094 else if (parser->tok == TOKEN_FLOATCONST) {
1097 parseerror(parser, "expected operator or end of statement, got constant");
1101 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1104 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1105 parseerror(parser, "out of memory");
1108 DEBUGSHUNTDO(printf("push %g\n", parser_token(parser)->constval.f));
1110 else if (parser->tok == TOKEN_INTCONST) {
1113 parseerror(parser, "expected operator or end of statement, got constant");
1117 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1120 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1121 parseerror(parser, "out of memory");
1124 DEBUGSHUNTDO(printf("push %i\n", parser_token(parser)->constval.i));
1126 else if (parser->tok == TOKEN_STRINGCONST) {
1129 parseerror(parser, "expected operator or end of statement, got constant");
1133 val = parser_const_string(parser, parser_tokval(parser));
1136 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1137 parseerror(parser, "out of memory");
1140 DEBUGSHUNTDO(printf("push string\n"));
1142 else if (parser->tok == TOKEN_VECTORCONST) {
1145 parseerror(parser, "expected operator or end of statement, got constant");
1149 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1152 if (!shunt_out_add(&sy, syexp(parser_ctx(parser), (ast_expression*)val))) {
1153 parseerror(parser, "out of memory");
1156 DEBUGSHUNTDO(printf("push '%g %g %g'\n",
1157 parser_token(parser)->constval.v.x,
1158 parser_token(parser)->constval.v.y,
1159 parser_token(parser)->constval.v.z));
1161 else if (parser->tok == '(') {
1162 parseerror(parser, "internal error: '(' should be classified as operator");
1165 else if (parser->tok == '[') {
1166 parseerror(parser, "internal error: '[' should be classified as operator");
1169 else if (parser->tok == ')') {
1171 DEBUGSHUNTDO(printf("do[op] )\n"));
1175 /* we do expect an operator next */
1176 /* closing an opening paren */
1177 if (!parser_close_paren(parser, &sy, false))
1180 DEBUGSHUNTDO(printf("do[nop] )\n"));
1184 /* allowed for function calls */
1185 if (!parser_close_paren(parser, &sy, true))
1190 else if (parser->tok == ']') {
1192 parseerror(parser, "operand expected");
1196 if (!parser_close_paren(parser, &sy, false))
1200 else if (parser->tok != TOKEN_OPERATOR) {
1202 parseerror(parser, "expected operator or end of statement");
1209 /* classify the operator */
1210 /* TODO: suffix operators */
1211 const oper_info *op;
1212 const oper_info *olast = NULL;
1214 for (o = 0; o < operator_count; ++o) {
1215 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1216 !(operators[o].flags & OP_SUFFIX) && /* remove this */
1217 !strcmp(parser_tokval(parser), operators[o].op))
1222 if (o == operator_count) {
1223 /* no operator found... must be the end of the statement */
1226 /* found an operator */
1229 /* when declaring variables, a comma starts a new variable */
1230 if (op->id == opid1(',') && !parens && stopatcomma) {
1231 /* fixup the token */
1236 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1237 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1240 (op->prec < olast->prec) ||
1241 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1243 if (!parser_sy_pop(parser, &sy))
1245 if (sy.ops_count && !sy.ops[sy.ops_count-1].paren)
1246 olast = &operators[sy.ops[sy.ops_count-1].etype-1];
1251 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1252 /* for gmqcc standard: open up the namespace of the previous type */
1253 ast_expression *prevex = sy.out[sy.out_count-1].out;
1255 parseerror(parser, "unexpected member operator");
1258 if (prevex->expression.vtype == TYPE_ENTITY)
1259 parser->memberof = TYPE_ENTITY;
1260 else if (prevex->expression.vtype == TYPE_VECTOR)
1261 parser->memberof = TYPE_VECTOR;
1263 parseerror(parser, "type error: type has no members");
1269 if (op->id == opid1('(')) {
1271 DEBUGSHUNTDO(printf("push [op] (\n"));
1273 /* we expected an operator, this is the function-call operator */
1274 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_FUNC, sy.out_count-1))) {
1275 parseerror(parser, "out of memory");
1280 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0))) {
1281 parseerror(parser, "out of memory");
1284 DEBUGSHUNTDO(printf("push [nop] (\n"));
1287 } else if (op->id == opid1('[')) {
1289 parseerror(parser, "unexpected array subscript");
1293 if (!shunt_ops_add(&sy, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0))) {
1294 parseerror(parser, "out of memory");
1298 DEBUGSHUNTDO(printf("push operator %s\n", op->op));
1299 if (!shunt_ops_add(&sy, syop(parser_ctx(parser), op)))
1304 if (!parser_next(parser)) {
1307 if (parser->tok == ';' || parser->tok == ']') {
1312 while (sy.ops_count) {
1313 if (!parser_sy_pop(parser, &sy))
1317 parser->lex->flags.noops = true;
1318 if (!sy.out_count) {
1319 parseerror(parser, "empty expression");
1322 expr = sy.out[0].out;
1323 MEM_VECTOR_CLEAR(&sy, out);
1324 MEM_VECTOR_CLEAR(&sy, ops);
1325 DEBUGSHUNTDO(printf("shunt done\n"));
1329 parser->lex->flags.noops = true;
1330 MEM_VECTOR_CLEAR(&sy, out);
1331 MEM_VECTOR_CLEAR(&sy, ops);
1335 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1337 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1340 if (!parser_next(parser)) {
1347 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1350 ast_expression *cond, *ontrue, *onfalse = NULL;
1352 lex_ctx ctx = parser_ctx(parser);
1354 /* skip the 'if' and check for opening paren */
1355 if (!parser_next(parser) || parser->tok != '(') {
1356 parseerror(parser, "expected 'if' condition in parenthesis");
1359 /* parse into the expression */
1360 if (!parser_next(parser)) {
1361 parseerror(parser, "expected 'if' condition after opening paren");
1364 /* parse the condition */
1365 cond = parse_expression_leave(parser, false);
1369 if (parser->tok != ')') {
1370 parseerror(parser, "expected closing paren after 'if' condition");
1374 /* parse into the 'then' branch */
1375 if (!parser_next(parser)) {
1376 parseerror(parser, "expected statement for on-true branch of 'if'");
1380 ontrue = parse_statement_or_block(parser);
1385 /* check for an else */
1386 if (!strcmp(parser_tokval(parser), "else")) {
1387 /* parse into the 'else' branch */
1388 if (!parser_next(parser)) {
1389 parseerror(parser, "expected on-false branch after 'else'");
1394 onfalse = parse_statement_or_block(parser);
1402 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1403 *out = (ast_expression*)ifthen;
1407 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1410 ast_expression *cond, *ontrue;
1412 lex_ctx ctx = parser_ctx(parser);
1414 /* skip the 'while' and check for opening paren */
1415 if (!parser_next(parser) || parser->tok != '(') {
1416 parseerror(parser, "expected 'while' condition in parenthesis");
1419 /* parse into the expression */
1420 if (!parser_next(parser)) {
1421 parseerror(parser, "expected 'while' condition after opening paren");
1424 /* parse the condition */
1425 cond = parse_expression_leave(parser, false);
1429 if (parser->tok != ')') {
1430 parseerror(parser, "expected closing paren after 'while' condition");
1434 /* parse into the 'then' branch */
1435 if (!parser_next(parser)) {
1436 parseerror(parser, "expected while-loop body");
1440 ontrue = parse_statement_or_block(parser);
1446 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1447 *out = (ast_expression*)aloop;
1451 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1454 ast_expression *cond, *ontrue;
1456 lex_ctx ctx = parser_ctx(parser);
1458 /* skip the 'do' and get the body */
1459 if (!parser_next(parser)) {
1460 parseerror(parser, "expected loop body");
1463 ontrue = parse_statement_or_block(parser);
1467 /* expect the "while" */
1468 if (parser->tok != TOKEN_KEYWORD ||
1469 strcmp(parser_tokval(parser), "while"))
1471 parseerror(parser, "expected 'while' and condition");
1476 /* skip the 'while' and check for opening paren */
1477 if (!parser_next(parser) || parser->tok != '(') {
1478 parseerror(parser, "expected 'while' condition in parenthesis");
1482 /* parse into the expression */
1483 if (!parser_next(parser)) {
1484 parseerror(parser, "expected 'while' condition after opening paren");
1488 /* parse the condition */
1489 cond = parse_expression_leave(parser, false);
1493 if (parser->tok != ')') {
1494 parseerror(parser, "expected closing paren after 'while' condition");
1500 if (!parser_next(parser) || parser->tok != ';') {
1501 parseerror(parser, "expected semicolon after condition");
1507 if (!parser_next(parser)) {
1508 parseerror(parser, "parse error");
1514 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1515 *out = (ast_expression*)aloop;
1519 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1522 ast_expression *initexpr, *cond, *increment, *ontrue;
1523 size_t oldblocklocal;
1526 lex_ctx ctx = parser_ctx(parser);
1528 oldblocklocal = parser->blocklocal;
1529 parser->blocklocal = parser->locals_count;
1536 /* skip the 'while' and check for opening paren */
1537 if (!parser_next(parser) || parser->tok != '(') {
1538 parseerror(parser, "expected 'for' expressions in parenthesis");
1541 /* parse into the expression */
1542 if (!parser_next(parser)) {
1543 parseerror(parser, "expected 'for' initializer after opening paren");
1547 if (parser->tok == TOKEN_TYPENAME) {
1548 if (opts_standard != COMPILER_GMQCC) {
1549 if (parsewarning(parser, WARN_EXTENSIONS,
1550 "current standard does not allow variable declarations in for-loop initializers"))
1554 parseerror(parser, "TODO: assignment of new variables to be non-const");
1556 if (!parse_variable(parser, block, true))
1559 else if (parser->tok != ';')
1561 initexpr = parse_expression_leave(parser, false);
1566 /* move on to condition */
1567 if (parser->tok != ';') {
1568 parseerror(parser, "expected semicolon after for-loop initializer");
1571 if (!parser_next(parser)) {
1572 parseerror(parser, "expected for-loop condition");
1576 /* parse the condition */
1577 if (parser->tok != ';') {
1578 cond = parse_expression_leave(parser, false);
1583 /* move on to incrementor */
1584 if (parser->tok != ';') {
1585 parseerror(parser, "expected semicolon after for-loop initializer");
1588 if (!parser_next(parser)) {
1589 parseerror(parser, "expected for-loop condition");
1593 /* parse the incrementor */
1594 if (parser->tok != ')') {
1595 increment = parse_expression_leave(parser, false);
1598 if (!ast_istype(increment, ast_store) &&
1599 !ast_istype(increment, ast_call) &&
1600 !ast_istype(increment, ast_binstore))
1602 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1608 if (parser->tok != ')') {
1609 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1612 /* parse into the 'then' branch */
1613 if (!parser_next(parser)) {
1614 parseerror(parser, "expected for-loop body");
1617 ontrue = parse_statement_or_block(parser);
1622 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1623 *out = (ast_expression*)aloop;
1625 while (parser->locals_count > parser->blocklocal)
1626 retval = retval && parser_pop_local(parser);
1627 parser->blocklocal = oldblocklocal;
1630 if (initexpr) ast_delete(initexpr);
1631 if (cond) ast_delete(cond);
1632 if (increment) ast_delete(increment);
1633 while (parser->locals_count > parser->blocklocal)
1634 (void)!parser_pop_local(parser);
1635 parser->blocklocal = oldblocklocal;
1639 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out)
1641 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
1643 /* local variable */
1645 parseerror(parser, "cannot declare a variable from here");
1648 if (opts_standard == COMPILER_QCC) {
1649 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
1652 if (!parse_variable(parser, block, false))
1657 else if (parser->tok == TOKEN_KEYWORD)
1659 if (!strcmp(parser_tokval(parser), "local"))
1662 parseerror(parser, "cannot declare a local variable here");
1665 if (!parser_next(parser)) {
1666 parseerror(parser, "expected variable declaration");
1669 if (!parse_variable(parser, block, true))
1674 else if (!strcmp(parser_tokval(parser), "return"))
1676 ast_expression *exp = NULL;
1677 ast_return *ret = NULL;
1678 ast_value *expected = parser->function->vtype;
1680 if (!parser_next(parser)) {
1681 parseerror(parser, "expected return expression");
1685 if (parser->tok != ';') {
1686 exp = parse_expression(parser, false);
1690 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1691 parseerror(parser, "return with invalid expression");
1694 ret = ast_return_new(exp->expression.node.context, exp);
1700 if (!parser_next(parser))
1701 parseerror(parser, "parse error");
1702 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1703 if (opts_standard != COMPILER_GMQCC)
1704 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1706 parseerror(parser, "return without value");
1708 ret = ast_return_new(parser_ctx(parser), NULL);
1710 *out = (ast_expression*)ret;
1713 else if (!strcmp(parser_tokval(parser), "if"))
1715 return parse_if(parser, block, out);
1717 else if (!strcmp(parser_tokval(parser), "while"))
1719 return parse_while(parser, block, out);
1721 else if (!strcmp(parser_tokval(parser), "do"))
1723 return parse_dowhile(parser, block, out);
1725 else if (!strcmp(parser_tokval(parser), "for"))
1727 if (opts_standard == COMPILER_QCC) {
1728 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
1731 return parse_for(parser, block, out);
1733 parseerror(parser, "Unexpected keyword");
1736 else if (parser->tok == '{')
1739 inner = parse_block(parser, false);
1742 *out = (ast_expression*)inner;
1747 ast_expression *exp = parse_expression(parser, false);
1751 if (!ast_istype(exp, ast_store) &&
1752 !ast_istype(exp, ast_call) &&
1753 !ast_istype(exp, ast_binstore))
1755 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1762 static bool GMQCC_WARN parser_pop_local(parser_t *parser)
1765 parser->locals_count--;
1767 ve = &parser->locals[parser->locals_count];
1768 if (ast_istype(ve->var, ast_value) && !(((ast_value*)(ve->var))->uses)) {
1769 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", ve->name))
1772 mem_d(parser->locals[parser->locals_count].name);
1776 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
1778 size_t oldblocklocal;
1781 oldblocklocal = parser->blocklocal;
1782 parser->blocklocal = parser->locals_count;
1784 if (!parser_next(parser)) { /* skip the '{' */
1785 parseerror(parser, "expected function body");
1789 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
1791 ast_expression *expr;
1792 if (parser->tok == '}')
1795 if (!parse_statement(parser, block, &expr)) {
1796 /* parseerror(parser, "parse error"); */
1802 if (!ast_block_exprs_add(block, expr)) {
1809 if (parser->tok != '}') {
1812 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
1814 if (!block->exprs_count ||
1815 !ast_istype(block->exprs[block->exprs_count-1], ast_return))
1817 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
1823 (void)parser_next(parser);
1827 while (parser->locals_count > parser->blocklocal)
1828 retval = retval && parser_pop_local(parser);
1829 parser->blocklocal = oldblocklocal;
1833 static ast_block* parse_block(parser_t *parser, bool warnreturn)
1836 block = ast_block_new(parser_ctx(parser));
1839 if (!parse_block_into(parser, block, warnreturn)) {
1840 ast_block_delete(block);
1846 static ast_expression* parse_statement_or_block(parser_t *parser)
1848 ast_expression *expr = NULL;
1849 if (parser->tok == '{')
1850 return (ast_expression*)parse_block(parser, false);
1851 if (!parse_statement(parser, NULL, &expr))
1857 static bool create_vector_members(parser_t *parser, ast_value *var, varentry_t *ve)
1860 size_t len = strlen(var->name);
1862 for (i = 0; i < 3; ++i) {
1863 ve[i].var = (ast_expression*)ast_member_new(ast_ctx(var), (ast_expression*)var, i);
1867 ve[i].name = (char*)mem_a(len+3);
1869 ast_delete(ve[i].var);
1873 memcpy(ve[i].name, var->name, len);
1874 ve[i].name[len] = '_';
1875 ve[i].name[len+1] = 'x'+i;
1876 ve[i].name[len+2] = 0;
1885 ast_delete(ve[i].var);
1892 static bool parse_function_body(parser_t *parser, ast_value *var)
1894 ast_block *block = NULL;
1899 ast_expression *framenum = NULL;
1900 ast_expression *nextthink = NULL;
1901 /* None of the following have to be deleted */
1902 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
1903 ast_expression *gbl_time = NULL, *gbl_self = NULL;
1904 bool has_frame_think;
1908 has_frame_think = false;
1909 old = parser->function;
1911 if (var->expression.variadic) {
1912 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
1913 "variadic function with implementation will not be able to access additional parameters"))
1919 if (parser->tok == '[') {
1920 /* got a frame definition: [ framenum, nextthink ]
1921 * this translates to:
1922 * self.frame = framenum;
1923 * self.nextthink = time + 0.1;
1924 * self.think = nextthink;
1928 fld_think = parser_find_field(parser, "think");
1929 fld_nextthink = parser_find_field(parser, "nextthink");
1930 fld_frame = parser_find_field(parser, "frame");
1931 if (!fld_think || !fld_nextthink || !fld_frame) {
1932 parseerror(parser, "cannot use [frame,think] notation without the required fields");
1933 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
1936 gbl_time = parser_find_global(parser, "time");
1937 gbl_self = parser_find_global(parser, "self");
1938 if (!gbl_time || !gbl_self) {
1939 parseerror(parser, "cannot use [frame,think] notation without the required globals");
1940 parseerror(parser, "please declare the following globals: `time`, `self`");
1944 if (!parser_next(parser))
1947 framenum = parse_expression_leave(parser, true);
1949 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
1952 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
1953 ast_unref(framenum);
1954 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
1958 if (parser->tok != ',') {
1959 ast_unref(framenum);
1960 parseerror(parser, "expected comma after frame number in [frame,think] notation");
1961 parseerror(parser, "Got a %i\n", parser->tok);
1965 if (!parser_next(parser)) {
1966 ast_unref(framenum);
1970 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
1972 /* qc allows the use of not-yet-declared functions here
1973 * - this automatically creates a prototype */
1975 ast_value *thinkfunc;
1976 ast_expression *functype = fld_think->expression.next;
1978 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
1979 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
1980 ast_unref(framenum);
1981 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
1985 if (!parser_next(parser)) {
1986 ast_unref(framenum);
1987 ast_delete(thinkfunc);
1991 varent.var = (ast_expression*)thinkfunc;
1992 varent.name = util_strdup(thinkfunc->name);
1993 if (!parser_t_globals_add(parser, varent)) {
1994 ast_unref(framenum);
1995 ast_delete(thinkfunc);
1998 nextthink = (ast_expression*)thinkfunc;
2001 nextthink = parse_expression_leave(parser, true);
2003 ast_unref(framenum);
2004 parseerror(parser, "expected a think-function in [frame,think] notation");
2009 if (!ast_istype(nextthink, ast_value)) {
2010 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2014 if (retval && parser->tok != ']') {
2015 parseerror(parser, "expected closing `]` for [frame,think] notation");
2019 if (retval && !parser_next(parser)) {
2023 if (retval && parser->tok != '{') {
2024 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2029 ast_unref(nextthink);
2030 ast_unref(framenum);
2034 has_frame_think = true;
2037 block = ast_block_new(parser_ctx(parser));
2039 parseerror(parser, "failed to allocate block");
2040 if (has_frame_think) {
2041 ast_unref(nextthink);
2042 ast_unref(framenum);
2047 if (has_frame_think) {
2049 ast_expression *self_frame;
2050 ast_expression *self_nextthink;
2051 ast_expression *self_think;
2052 ast_expression *time_plus_1;
2053 ast_store *store_frame;
2054 ast_store *store_nextthink;
2055 ast_store *store_think;
2057 ctx = parser_ctx(parser);
2058 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2059 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2060 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2062 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2063 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2065 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2066 if (self_frame) ast_delete(self_frame);
2067 if (self_nextthink) ast_delete(self_nextthink);
2068 if (self_think) ast_delete(self_think);
2069 if (time_plus_1) ast_delete(time_plus_1);
2075 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2076 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2077 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2080 ast_delete(self_frame);
2083 if (!store_nextthink) {
2084 ast_delete(self_nextthink);
2088 ast_delete(self_think);
2092 if (store_frame) ast_delete(store_frame);
2093 if (store_nextthink) ast_delete(store_nextthink);
2094 if (store_think) ast_delete(store_think);
2097 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_frame)) {
2098 ast_delete(store_frame);
2099 ast_delete(store_nextthink);
2100 ast_delete(store_think);
2104 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_nextthink)) {
2105 ast_delete(store_nextthink);
2106 ast_delete(store_think);
2110 if (retval && !ast_block_exprs_add(block, (ast_expression*)store_think) )
2112 ast_delete(store_think);
2118 parseerror(parser, "failed to generate code for [frame,think]");
2119 ast_unref(nextthink);
2120 ast_unref(framenum);
2126 for (parami = 0; parami < var->expression.params_count; ++parami) {
2129 ast_value *param = var->expression.params[parami];
2131 if (param->expression.vtype != TYPE_VECTOR &&
2132 (param->expression.vtype != TYPE_FIELD ||
2133 param->expression.next->expression.vtype != TYPE_VECTOR))
2138 if (!create_vector_members(parser, param, ve)) {
2139 ast_block_delete(block);
2143 for (e = 0; e < 3; ++e) {
2144 if (!parser_t_locals_add(parser, ve[e]))
2146 if (!ast_block_collect(block, ve[e].var)) {
2147 parser->locals_count--;
2150 ve[e].var = NULL; /* collected */
2153 parser->locals -= e;
2158 ast_block_delete(block);
2163 func = ast_function_new(ast_ctx(var), var->name, var);
2165 parseerror(parser, "failed to allocate function for `%s`", var->name);
2166 ast_block_delete(block);
2169 if (!parser_t_functions_add(parser, func)) {
2170 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
2171 ast_block_delete(block);
2175 parser->function = func;
2176 if (!parse_block_into(parser, block, true)) {
2177 ast_block_delete(block);
2181 if (!ast_function_blocks_add(func, block)) {
2182 ast_block_delete(block);
2186 parser->function = old;
2187 while (parser->locals_count)
2188 retval = retval && parser_pop_local(parser);
2190 if (parser->tok == ';')
2191 return parser_next(parser);
2192 else if (opts_standard == COMPILER_QCC)
2193 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2197 parser->functions_count--;
2199 ast_function_delete(func);
2200 var->constval.vfunc = NULL;
2203 while (parser->locals_count) {
2204 parser->locals_count--;
2205 mem_d(parser->locals[parser->locals_count].name);
2207 parser->function = old;
2211 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2213 lex_ctx ctx = ast_ctx(array);
2215 if (from+1 == afterend) {
2219 ast_array_index *subscript;
2220 int assignop = type_store_instr[value->expression.vtype];
2222 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2223 assignop = INSTR_STORE_V;
2225 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2229 ast_store *st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2231 ast_delete(subscript);
2235 block = ast_block_new(ctx);
2241 if (!ast_block_exprs_add(block, (ast_expression*)st)) {
2246 ret = ast_return_new(ctx, NULL);
2252 if (!ast_block_exprs_add(block, (ast_expression*)ret)) {
2257 return (ast_expression*)block;
2260 ast_expression *left, *right;
2263 size_t diff = afterend - from;
2264 size_t middle = from + diff/2;
2266 left = array_setter_node(parser, array, index, value, from, middle);
2267 right = array_setter_node(parser, array, index, value, middle, afterend);
2268 if (!left || !right) {
2269 if (left) ast_delete(left);
2270 if (right) ast_delete(right);
2274 cmp = ast_binary_new(ctx, INSTR_LT,
2275 (ast_expression*)index,
2276 (ast_expression*)parser_const_float(parser, from + diff/2));
2280 parseerror(parser, "internal error: failed to create comparison for array setter");
2284 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2286 ast_delete(cmp); /* will delete left and right */
2287 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2291 return (ast_expression*)ifthen;
2295 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2297 lex_ctx ctx = ast_ctx(array);
2299 if (from+1 == afterend) {
2301 ast_array_index *subscript;
2303 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2307 ret = ast_return_new(ctx, (ast_expression*)subscript);
2309 ast_delete(subscript);
2313 return (ast_expression*)ret;
2316 ast_expression *left, *right;
2319 size_t diff = afterend - from;
2320 size_t middle = from + diff/2;
2322 left = array_getter_node(parser, array, index, from, middle);
2323 right = array_getter_node(parser, array, index, middle, afterend);
2324 if (!left || !right) {
2325 if (left) ast_delete(left);
2326 if (right) ast_delete(right);
2330 cmp = ast_binary_new(ctx, INSTR_LT,
2331 (ast_expression*)index,
2332 (ast_expression*)parser_const_float(parser, from + diff/2));
2336 parseerror(parser, "internal error: failed to create comparison for array setter");
2340 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2342 ast_delete(cmp); /* will delete left and right */
2343 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2347 return (ast_expression*)ifthen;
2351 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2353 ast_expression *root = NULL;
2354 ast_function *func = NULL;
2355 ast_value *fval = NULL;
2357 ast_value *index, *value;
2359 if (!ast_istype(array->expression.next, ast_value)) {
2360 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2364 body = ast_block_new(ast_ctx(array));
2366 parseerror(parser, "failed to create block for array accessor");
2370 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2371 value = ast_value_copy((ast_value*)array->expression.next);
2373 if (!index || !value) {
2375 if (index) ast_delete(index);
2376 if (value) ast_delete(value);
2377 parseerror(parser, "failed to create locals for array accessor");
2381 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2383 parseerror(parser, "failed to build accessor search tree");
2387 if (!ast_block_exprs_add(body, root)) {
2388 parseerror(parser, "failed to build accessor search block");
2392 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2394 parseerror(parser, "failed to create accessor function value");
2397 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2399 (void)!ast_value_set_name(value, "value"); /* not important */
2400 if (!ast_expression_common_params_add(&fval->expression, index)) {
2401 parseerror(parser, "failed to build array setter");
2404 if (!ast_expression_common_params_add(&fval->expression, value)) {
2406 parseerror(parser, "failed to build array setter");
2410 func = ast_function_new(ast_ctx(array), funcname, fval);
2412 parseerror(parser, "failed to create accessor function node");
2416 if (!ast_function_blocks_add(func, body))
2419 array->setter = fval;
2427 if (root) ast_delete(root);
2428 if (func) ast_delete(func);
2429 if (fval) ast_delete(fval);
2433 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const char *funcname)
2435 ast_expression *root = NULL;
2436 ast_function *func = NULL;
2437 ast_value *fval = NULL;
2441 if (!ast_istype(array->expression.next, ast_value)) {
2442 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2446 body = ast_block_new(ast_ctx(array));
2448 parseerror(parser, "failed to create block for array accessor");
2452 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2456 if (index) ast_delete(index);
2457 parseerror(parser, "failed to create locals for array accessor");
2461 root = array_getter_node(parser, array, index, 0, array->expression.count);
2463 parseerror(parser, "failed to build accessor search tree");
2467 if (!ast_block_exprs_add(body, root)) {
2468 parseerror(parser, "failed to build accessor search block");
2472 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2474 parseerror(parser, "failed to create accessor function value");
2477 fval->expression.next = ast_type_copy(ast_ctx(array), array->expression.next);
2479 if (!ast_expression_common_params_add(&fval->expression, index)) {
2480 parseerror(parser, "failed to build array setter");
2484 func = ast_function_new(ast_ctx(array), funcname, fval);
2486 parseerror(parser, "failed to create accessor function node");
2490 if (!ast_function_blocks_add(func, body))
2493 array->getter = fval;
2500 if (root) ast_delete(root);
2501 if (func) ast_delete(func);
2502 if (fval) ast_delete(fval);
2507 MEM_VECTOR_MAKE(ast_value*, p);
2509 MEM_VEC_FUNCTIONS(paramlist_t, ast_value*, p)
2511 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2512 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2520 bool variadic = false;
2522 ctx = parser_ctx(parser);
2524 /* for the sake of less code we parse-in in this function */
2525 if (!parser_next(parser)) {
2526 parseerror(parser, "expected parameter list");
2530 MEM_VECTOR_INIT(¶ms, p);
2532 /* parse variables until we hit a closing paren */
2533 while (parser->tok != ')') {
2535 /* there must be commas between them */
2536 if (parser->tok != ',') {
2537 parseerror(parser, "expected comma or end of parameter list");
2540 if (!parser_next(parser)) {
2541 parseerror(parser, "expected parameter");
2547 if (parser->tok == TOKEN_DOTS) {
2548 /* '...' indicates a varargs function */
2550 if (!parser_next(parser)) {
2551 parseerror(parser, "expected parameter");
2554 if (parser->tok != ')') {
2555 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
2561 /* for anything else just parse a typename */
2562 param = parse_typename(parser, NULL);
2565 if (!paramlist_t_p_add(¶ms, param)) {
2569 if (param->expression.vtype >= TYPE_VARIANT) {
2570 char typename[1024];
2571 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
2572 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
2579 if (params.p_count > 8)
2580 parseerror(parser, "more than 8 parameters are currently not supported");
2583 if (!parser_next(parser)) {
2584 parseerror(parser, "parse error after typename");
2588 /* now turn 'var' into a function type */
2589 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
2590 fval->expression.next = (ast_expression*)var;
2591 fval->expression.variadic = variadic;
2594 MEM_VECTOR_MOVE(¶ms, p, &var->expression, params);
2600 for (i = 0; i < params.p_count; ++i)
2601 ast_delete(params.p[i]);
2602 MEM_VECTOR_CLEAR(¶ms, p);
2606 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
2608 ast_expression *cexp;
2609 ast_value *cval, *tmp;
2612 ctx = parser_ctx(parser);
2614 if (!parser_next(parser)) {
2616 parseerror(parser, "expected array-size");
2620 cexp = parse_expression_leave(parser, true);
2622 if (!cexp || !ast_istype(cexp, ast_value)) {
2626 parseerror(parser, "expected array-size as constant positive integer");
2629 cval = (ast_value*)cexp;
2631 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
2632 tmp->expression.next = (ast_expression*)var;
2635 if (cval->expression.vtype == TYPE_INTEGER)
2636 tmp->expression.count = cval->constval.vint;
2637 else if (cval->expression.vtype == TYPE_FLOAT)
2638 tmp->expression.count = cval->constval.vfloat;
2642 parseerror(parser, "array-size must be a positive integer constant");
2647 if (parser->tok != ']') {
2649 parseerror(parser, "expected ']' after array-size");
2652 if (!parser_next(parser)) {
2654 parseerror(parser, "error after parsing array size");
2660 /* Parse a complete typename.
2661 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
2662 * but when parsing variables separated by comma
2663 * 'storebase' should point to where the base-type should be kept.
2664 * The base type makes up every bit of type information which comes *before* the
2667 * The following will be parsed in its entirety:
2669 * The 'basetype' in this case is 'void()'
2670 * and if there's a comma after it, say:
2672 * then the type-information 'void()' can be stored in 'storebase'
2674 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
2676 ast_value *var, *tmp;
2679 const char *name = NULL;
2680 bool isfield = false;
2681 bool wasarray = false;
2683 ctx = parser_ctx(parser);
2685 /* types may start with a dot */
2686 if (parser->tok == '.') {
2688 /* if we parsed a dot we need a typename now */
2689 if (!parser_next(parser)) {
2690 parseerror(parser, "expected typename for field definition");
2693 if (parser->tok != TOKEN_TYPENAME) {
2694 parseerror(parser, "expected typename");
2699 /* generate the basic type value */
2700 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
2701 /* do not yet turn into a field - remember:
2702 * .void() foo; is a field too
2703 * .void()() foo; is a function
2707 if (!parser_next(parser)) {
2709 parseerror(parser, "parse error after typename");
2713 /* an opening paren now starts the parameter-list of a function
2714 * this is where original-QC has parameter lists.
2715 * We allow a single parameter list here.
2716 * Much like fteqcc we don't allow `float()() x`
2718 if (parser->tok == '(') {
2719 var = parse_parameter_list(parser, var);
2724 /* store the base if requested */
2726 *storebase = ast_value_copy(var);
2728 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2729 tmp->expression.next = (ast_expression*)*storebase;
2734 /* there may be a name now */
2735 if (parser->tok == TOKEN_IDENT) {
2736 name = util_strdup(parser_tokval(parser));
2738 if (!parser_next(parser)) {
2740 parseerror(parser, "error after variable or field declaration");
2745 /* now this may be an array */
2746 if (parser->tok == '[') {
2748 var = parse_arraysize(parser, var);
2753 /* This is the point where we can turn it into a field */
2755 /* turn it into a field if desired */
2756 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
2757 tmp->expression.next = (ast_expression*)var;
2761 /* now there may be function parens again */
2762 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
2763 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2764 if (parser->tok == '(' && wasarray)
2765 parseerror(parser, "arrays as part of a return type is not supported");
2766 while (parser->tok == '(') {
2767 var = parse_parameter_list(parser, var);
2776 /* finally name it */
2778 if (!ast_value_set_name(var, name)) {
2780 parseerror(parser, "internal error: failed to set name");
2783 /* free the name, ast_value_set_name duplicates */
2790 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields)
2794 ast_expression *old;
2798 ast_value *basetype = NULL;
2800 bool isparam = false;
2801 bool isvector = false;
2802 bool cleanvar = true;
2803 bool wasarray = false;
2805 varentry_t varent, ve[3];
2807 /* get the first complete variable */
2808 var = parse_typename(parser, &basetype);
2811 ast_delete(basetype);
2815 memset(&varent, 0, sizeof(varent));
2816 memset(&ve, 0, sizeof(ve));
2822 /* Part 0: finish the type */
2823 if (parser->tok == '(') {
2824 if (opts_standard == COMPILER_QCC)
2825 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2826 var = parse_parameter_list(parser, var);
2832 /* we only allow 1-dimensional arrays */
2833 if (parser->tok == '[') {
2835 var = parse_arraysize(parser, var);
2841 if (parser->tok == '(' && wasarray) {
2842 parseerror(parser, "arrays as part of a return type is not supported");
2843 /* we'll still parse the type completely for now */
2845 /* for functions returning functions */
2846 while (parser->tok == '(') {
2847 if (opts_standard == COMPILER_QCC)
2848 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
2849 var = parse_parameter_list(parser, var);
2857 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
2858 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
2859 * is then filled with the previous definition and the parameter-names replaced.
2862 /* Deal with end_sys_ vars */
2864 if (!strcmp(var->name, "end_sys_globals")) {
2865 parser->crc_globals = parser->globals_count;
2868 else if (!strcmp(var->name, "end_sys_fields")) {
2869 parser->crc_fields = parser->fields_count;
2872 if (was_end && var->expression.vtype == TYPE_FIELD) {
2873 if (parsewarning(parser, WARN_END_SYS_FIELDS,
2874 "global '%s' hint should not be a field",
2875 parser_tokval(parser)))
2882 if (!nofields && var->expression.vtype == TYPE_FIELD)
2884 /* deal with field declarations */
2885 old = parser_find_field(parser, var->name);
2887 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
2888 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
2897 parseerror(parser, "field `%s` already declared here: %s:%i",
2898 var->name, ast_ctx(old).file, ast_ctx(old).line);
2903 if (opts_standard == COMPILER_QCC &&
2904 (old = parser_find_global(parser, var->name)))
2906 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2907 parseerror(parser, "field `%s` already declared here: %s:%i",
2908 var->name, ast_ctx(old).file, ast_ctx(old).line);
2915 /* deal with other globals */
2916 old = parser_find_global(parser, var->name);
2917 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
2919 /* This is a function which had a prototype */
2920 if (!ast_istype(old, ast_value)) {
2921 parseerror(parser, "internal error: prototype is not an ast_value");
2925 proto = (ast_value*)old;
2926 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
2927 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
2929 ast_ctx(proto).file, ast_ctx(proto).line);
2933 /* we need the new parameter-names */
2934 for (i = 0; i < proto->expression.params_count; ++i)
2935 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
2943 parseerror(parser, "global `%s` already declared here: %s:%i",
2944 var->name, ast_ctx(old).file, ast_ctx(old).line);
2948 if (opts_standard == COMPILER_QCC &&
2949 (old = parser_find_field(parser, var->name)))
2951 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
2952 parseerror(parser, "global `%s` already declared here: %s:%i",
2953 var->name, ast_ctx(old).file, ast_ctx(old).line);
2960 else /* it's not a global */
2962 old = parser_find_local(parser, var->name, parser->blocklocal, &isparam);
2963 if (old && !isparam) {
2964 parseerror(parser, "local `%s` already declared here: %s:%i",
2965 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2969 old = parser_find_local(parser, var->name, 0, &isparam);
2970 if (old && isparam) {
2971 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
2972 "local `%s` is shadowing a parameter", var->name))
2974 parseerror(parser, "local `%s` already declared here: %s:%i",
2975 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
2979 if (opts_standard != COMPILER_GMQCC) {
2988 * Create the global/local, and deal with vector types.
2991 if (var->expression.vtype == TYPE_VECTOR)
2993 else if (var->expression.vtype == TYPE_FIELD &&
2994 var->expression.next->expression.vtype == TYPE_VECTOR)
2998 if (!create_vector_members(parser, var, ve)) {
3004 varent.name = util_strdup(var->name);
3005 varent.var = (ast_expression*)var;
3008 /* deal with global variables, fields, functions */
3009 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3010 if (!(retval = parser_t_fields_add(parser, varent)))
3013 for (i = 0; i < 3; ++i) {
3014 if (!(retval = parser_t_fields_add(parser, ve[i])))
3018 parser->fields_count -= i+1;
3024 if (!(retval = parser_t_globals_add(parser, varent)))
3027 for (i = 0; i < 3; ++i) {
3028 if (!(retval = parser_t_globals_add(parser, ve[i])))
3032 parser->globals_count -= i+1;
3038 if (!(retval = parser_t_locals_add(parser, varent)))
3040 if (!(retval = ast_block_locals_add(localblock, var))) {
3041 parser->locals_count--;
3045 for (i = 0; i < 3; ++i) {
3046 if (!(retval = parser_t_locals_add(parser, ve[i])))
3048 if (!(retval = ast_block_collect(localblock, ve[i].var)))
3050 ve[i].var = NULL; /* from here it's being collected in the block */
3053 parser->locals_count -= i+1;
3054 localblock->locals_count--;
3061 ve[0].name = ve[1].name = ve[2].name = NULL;
3062 ve[0].var = ve[1].var = ve[2].var = NULL;
3068 if (var->expression.vtype == TYPE_ARRAY) {
3070 snprintf(name, sizeof(name), "%s::SET", var->name);
3071 if (!parser_create_array_setter(parser, var, name))
3073 snprintf(name, sizeof(name), "%s::GET", var->name);
3074 if (!parser_create_array_getter(parser, var, name))
3079 if (parser->tok == ';') {
3080 ast_delete(basetype);
3081 if (!parser_next(parser)) {
3082 parseerror(parser, "error after variable declaration");
3088 if (parser->tok == ',')
3091 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3092 parseerror(parser, "missing comma or semicolon while parsing variables");
3096 if (localblock && opts_standard == COMPILER_QCC) {
3097 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3098 "initializing expression turns variable `%s` into a constant in this standard",
3105 if (parser->tok != '{') {
3106 if (parser->tok != '=') {
3107 parseerror(parser, "missing semicolon or initializer");
3111 if (!parser_next(parser)) {
3112 parseerror(parser, "error parsing initializer");
3116 else if (opts_standard == COMPILER_QCC) {
3117 parseerror(parser, "expected '=' before function body in this standard");
3120 if (parser->tok == '#') {
3124 parseerror(parser, "cannot declare builtins within functions");
3127 if (var->expression.vtype != TYPE_FUNCTION) {
3128 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3131 if (!parser_next(parser)) {
3132 parseerror(parser, "expected builtin number");
3135 if (parser->tok != TOKEN_INTCONST) {
3136 parseerror(parser, "builtin number must be an integer constant");
3139 if (parser_token(parser)->constval.i <= 0) {
3140 parseerror(parser, "builtin number must be an integer greater than zero");
3144 func = ast_function_new(ast_ctx(var), var->name, var);
3146 parseerror(parser, "failed to allocate function for `%s`", var->name);
3149 if (!parser_t_functions_add(parser, func)) {
3150 parseerror(parser, "failed to allocate slot for function `%s`", var->name);
3151 ast_function_delete(func);
3152 var->constval.vfunc = NULL;
3156 func->builtin = -parser_token(parser)->constval.i;
3158 if (!parser_next(parser)) {
3159 parseerror(parser, "expected comma or semicolon");
3160 ast_function_delete(func);
3161 var->constval.vfunc = NULL;
3165 else if (parser->tok == '{' || parser->tok == '[')
3168 parseerror(parser, "cannot declare functions within functions");
3172 if (!parse_function_body(parser, var))
3174 ast_delete(basetype);
3177 ast_expression *cexp;
3180 cexp = parse_expression_leave(parser, true);
3185 cval = (ast_value*)cexp;
3186 if (!ast_istype(cval, ast_value) || !cval->isconst)
3187 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3190 var->isconst = true;
3191 if (cval->expression.vtype == TYPE_STRING)
3192 var->constval.vstring = parser_strdup(cval->constval.vstring);
3194 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3199 MEM_VECTOR_INIT(&sy, out);
3200 MEM_VECTOR_INIT(&sy, ops);
3201 if (!shunt_out_add(&sy, syexp(ast_ctx(var), (ast_expression*)var)) ||
3202 !shunt_out_add(&sy, syexp(ast_ctx(cexp), (ast_expression*)cexp)) ||
3203 !shunt_ops_add(&sy, syop(ast_ctx(var), parser->assign_op)))
3205 parseerror(parser, "internal error: failed to prepare initializer");
3208 else if (!parser_sy_pop(parser, &sy))
3211 if (sy.out_count != 1 && sy.ops_count != 0)
3212 parseerror(parser, "internal error: leaked operands");
3213 else if (!ast_block_exprs_add(localblock, (ast_expression*)sy.out[0].out)) {
3214 parseerror(parser, "failed to create intializing expression");
3215 ast_unref(sy.out[0].out);
3219 MEM_VECTOR_CLEAR(&sy, out);
3220 MEM_VECTOR_CLEAR(&sy, ops);
3225 if (parser->tok == ',') {
3226 if (!parser_next(parser)) {
3227 parseerror(parser, "expected another variable");
3231 if (parser->tok != TOKEN_IDENT) {
3232 parseerror(parser, "expected another variable");
3235 var = ast_value_copy(basetype);
3237 ast_value_set_name(var, parser_tokval(parser));
3238 if (!parser_next(parser)) {
3239 parseerror(parser, "error parsing variable declaration");
3245 if (parser->tok != ';') {
3246 parseerror(parser, "missing semicolon after variables");
3250 if (!parser_next(parser)) {
3251 parseerror(parser, "parse error after variable declaration");
3255 ast_delete(basetype);
3259 if (cleanvar && var)
3261 ast_delete(basetype);
3265 ast_delete(basetype);
3266 if (cleanvar && var)
3268 if (varent.name) mem_d(varent.name);
3269 if (ve[0].name) mem_d(ve[0].name);
3270 if (ve[1].name) mem_d(ve[1].name);
3271 if (ve[2].name) mem_d(ve[2].name);
3272 if (ve[0].var) mem_d(ve[0].var);
3273 if (ve[1].var) mem_d(ve[1].var);
3274 if (ve[2].var) mem_d(ve[2].var);
3278 static bool parser_global_statement(parser_t *parser)
3280 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3282 return parse_variable(parser, NULL, false);
3284 else if (parser->tok == TOKEN_KEYWORD)
3286 /* handle 'var' and 'const' */
3287 if (!strcmp(parser_tokval(parser), "var")) {
3288 if (!parser_next(parser)) {
3289 parseerror(parser, "expected variable declaration after 'var'");
3292 return parse_variable(parser, NULL, true);
3296 else if (parser->tok == '$')
3298 if (!parser_next(parser)) {
3299 parseerror(parser, "parse error");
3305 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3311 static parser_t *parser;
3316 parser = (parser_t*)mem_a(sizeof(parser_t));
3320 memset(parser, 0, sizeof(*parser));
3322 for (i = 0; i < operator_count; ++i) {
3323 if (operators[i].id == opid1('=')) {
3324 parser->assign_op = operators+i;
3328 if (!parser->assign_op) {
3329 printf("internal error: initializing parser: failed to find assign operator\n");
3336 bool parser_compile(const char *filename)
3338 parser->lex = lex_open(filename);
3340 printf("failed to open file \"%s\"\n", filename);
3344 /* initial lexer/parser state */
3345 parser->lex->flags.noops = true;
3347 if (parser_next(parser))
3349 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3351 if (!parser_global_statement(parser)) {
3352 if (parser->tok == TOKEN_EOF)
3353 parseerror(parser, "unexpected eof");
3354 else if (!parser->errors)
3355 parseerror(parser, "there have been errors, bailing out");
3356 lex_close(parser->lex);
3362 parseerror(parser, "parse error");
3363 lex_close(parser->lex);
3368 lex_close(parser->lex);
3371 return !parser->errors;
3374 void parser_cleanup()
3377 for (i = 0; i < parser->functions_count; ++i) {
3378 ast_delete(parser->functions[i]);
3380 for (i = 0; i < parser->imm_vector_count; ++i) {
3381 ast_delete(parser->imm_vector[i]);
3383 for (i = 0; i < parser->imm_string_count; ++i) {
3384 ast_delete(parser->imm_string[i]);
3386 for (i = 0; i < parser->imm_float_count; ++i) {
3387 ast_delete(parser->imm_float[i]);
3389 for (i = 0; i < parser->fields_count; ++i) {
3390 ast_delete(parser->fields[i].var);
3391 mem_d(parser->fields[i].name);
3393 for (i = 0; i < parser->globals_count; ++i) {
3394 ast_delete(parser->globals[i].var);
3395 mem_d(parser->globals[i].name);
3397 MEM_VECTOR_CLEAR(parser, functions);
3398 MEM_VECTOR_CLEAR(parser, imm_vector);
3399 MEM_VECTOR_CLEAR(parser, imm_string);
3400 MEM_VECTOR_CLEAR(parser, imm_float);
3401 MEM_VECTOR_CLEAR(parser, globals);
3402 MEM_VECTOR_CLEAR(parser, fields);
3403 MEM_VECTOR_CLEAR(parser, locals);
3408 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3410 return util_crc16(old, str, strlen(str));
3413 static void progdefs_crc_file(const char *str)
3415 /* write to progdefs.h here */
3418 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3420 old = progdefs_crc_sum(old, str);
3421 progdefs_crc_file(str);
3425 static void generate_checksum(parser_t *parser)
3427 uint16_t crc = 0xFFFF;
3430 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3431 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3433 progdefs_crc_file("\tint\tpad;\n");
3434 progdefs_crc_file("\tint\tofs_return[3];\n");
3435 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3436 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3437 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3438 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3439 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3440 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3441 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3442 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3444 for (i = 0; i < parser->crc_globals; ++i) {
3445 if (!ast_istype(parser->globals[i].var, ast_value))
3447 switch (parser->globals[i].var->expression.vtype) {
3448 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3449 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3450 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3451 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3453 crc = progdefs_crc_both(crc, "\tint\t");
3456 crc = progdefs_crc_both(crc, parser->globals[i].name);
3457 crc = progdefs_crc_both(crc, ";\n");
3459 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3460 for (i = 0; i < parser->crc_fields; ++i) {
3461 if (!ast_istype(parser->fields[i].var, ast_value))
3463 switch (parser->fields[i].var->expression.next->expression.vtype) {
3464 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3465 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3466 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3467 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3469 crc = progdefs_crc_both(crc, "\tint\t");
3472 crc = progdefs_crc_both(crc, parser->fields[i].name);
3473 crc = progdefs_crc_both(crc, ";\n");
3475 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3480 bool parser_finish(const char *output)
3486 if (!parser->errors)
3488 ir = ir_builder_new("gmqcc_out");
3490 printf("failed to allocate builder\n");
3494 for (i = 0; i < parser->fields_count; ++i) {
3497 if (!ast_istype(parser->fields[i].var, ast_value))
3499 field = (ast_value*)parser->fields[i].var;
3500 isconst = field->isconst;
3501 field->isconst = false;
3502 if (!ast_global_codegen((ast_value*)field, ir, true)) {
3503 printf("failed to generate field %s\n", field->name);
3504 ir_builder_delete(ir);
3509 ast_expression *subtype;
3510 field->isconst = true;
3511 subtype = field->expression.next;
3512 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
3513 if (subtype->expression.vtype == TYPE_FIELD)
3514 ifld->fieldtype = subtype->expression.next->expression.vtype;
3515 else if (subtype->expression.vtype == TYPE_FUNCTION)
3516 ifld->outtype = subtype->expression.next->expression.vtype;
3517 (void)!ir_value_set_field(field->ir_v, ifld);
3520 for (i = 0; i < parser->globals_count; ++i) {
3522 if (!ast_istype(parser->globals[i].var, ast_value))
3524 asvalue = (ast_value*)(parser->globals[i].var);
3525 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
3526 if (strcmp(asvalue->name, "end_sys_globals") &&
3527 strcmp(asvalue->name, "end_sys_fields"))
3529 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
3530 "unused global: `%s`", asvalue->name);
3533 if (!ast_global_codegen(asvalue, ir, false)) {
3534 printf("failed to generate global %s\n", parser->globals[i].name);
3535 ir_builder_delete(ir);
3539 for (i = 0; i < parser->imm_float_count; ++i) {
3540 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
3541 printf("failed to generate global %s\n", parser->imm_float[i]->name);
3542 ir_builder_delete(ir);
3546 for (i = 0; i < parser->imm_string_count; ++i) {
3547 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
3548 printf("failed to generate global %s\n", parser->imm_string[i]->name);
3549 ir_builder_delete(ir);
3553 for (i = 0; i < parser->imm_vector_count; ++i) {
3554 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
3555 printf("failed to generate global %s\n", parser->imm_vector[i]->name);
3556 ir_builder_delete(ir);
3560 for (i = 0; i < parser->globals_count; ++i) {
3562 if (!ast_istype(parser->globals[i].var, ast_value))
3564 asvalue = (ast_value*)(parser->globals[i].var);
3565 if (asvalue->setter) {
3566 if (!ast_global_codegen(asvalue->setter, ir, false) ||
3567 !ast_function_codegen(asvalue->setter->constval.vfunc, ir))
3569 printf("failed to generate setter for %s\n", parser->globals[i].name);
3570 ir_builder_delete(ir);
3574 if (asvalue->getter) {
3575 if (!ast_global_codegen(asvalue->getter, ir, false) ||
3576 !ast_function_codegen(asvalue->getter->constval.vfunc, ir))
3578 printf("failed to generate getter for %s\n", parser->globals[i].name);
3579 ir_builder_delete(ir);
3584 for (i = 0; i < parser->functions_count; ++i) {
3585 if (!ast_function_codegen(parser->functions[i], ir)) {
3586 printf("failed to generate function %s\n", parser->functions[i]->name);
3587 ir_builder_delete(ir);
3590 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
3591 printf("failed to finalize function %s\n", parser->functions[i]->name);
3592 ir_builder_delete(ir);
3599 ir_builder_dump(ir, printf);
3601 generate_checksum(parser);
3603 if (!ir_builder_generate(ir, output)) {
3604 printf("*** failed to generate output file\n");
3605 ir_builder_delete(ir);
3610 ir_builder_delete(ir);
3614 printf("*** there were compile errors\n");