5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define PARSER_HT_FIELDS 0
30 #define PARSER_HT_GLOBALS 1
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
40 ast_expression **globals;
41 ast_expression **fields;
42 ast_function **functions;
43 ast_value **imm_float;
44 ast_value **imm_string;
45 ast_value **imm_vector;
47 /* must be deleted first, they reference immediates and values */
48 ast_value **accessors;
50 ast_value *imm_float_zero;
51 ast_value *imm_float_one;
52 ast_value *imm_vector_zero;
57 ast_function *function;
59 /* A list of hashtables for each scope */
64 /* not to be used directly, we use the hash table */
65 ast_expression **_locals;
70 /* we store the '=' operator info */
71 const oper_info *assign_op;
73 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
74 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
75 * anything else: type error
80 static void parser_enterblock(parser_t *parser);
81 static bool parser_leaveblock(parser_t *parser);
82 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
83 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const);
84 static ast_block* parse_block(parser_t *parser, bool warnreturn);
85 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn);
86 static ast_expression* parse_statement_or_block(parser_t *parser);
87 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
88 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
89 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
91 static void parseerror(parser_t *parser, const char *fmt, ...)
98 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
102 /* returns true if it counts as an error */
103 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
106 int lvl = LVL_WARNING;
108 if (!OPTS_WARN(warntype))
117 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
123 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
126 int lvl = LVL_WARNING;
128 if (!OPTS_WARN(warntype))
135 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
141 /**********************************************************************
142 * some maths used for constant folding
145 vector vec3_add(vector a, vector b)
154 vector vec3_sub(vector a, vector b)
163 qcfloat vec3_mulvv(vector a, vector b)
165 return (a.x * b.x + a.y * b.y + a.z * b.z);
168 vector vec3_mulvf(vector a, float b)
177 /**********************************************************************
181 bool parser_next(parser_t *parser)
183 /* lex_do kills the previous token */
184 parser->tok = lex_do(parser->lex);
185 if (parser->tok == TOKEN_EOF)
187 if (parser->tok >= TOKEN_ERROR) {
188 parseerror(parser, "lex error");
194 #define parser_tokval(p) ((p)->lex->tok.value)
195 #define parser_token(p) (&((p)->lex->tok))
196 #define parser_ctx(p) ((p)->lex->tok.ctx)
198 static ast_value* parser_const_float(parser_t *parser, double d)
202 for (i = 0; i < vec_size(parser->imm_float); ++i) {
203 const double compare = parser->imm_float[i]->constval.vfloat;
204 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
205 return parser->imm_float[i];
207 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
209 out->constval.vfloat = d;
210 vec_push(parser->imm_float, out);
214 static ast_value* parser_const_float_0(parser_t *parser)
216 if (!parser->imm_float_zero)
217 parser->imm_float_zero = parser_const_float(parser, 0);
218 return parser->imm_float_zero;
221 static ast_value* parser_const_float_1(parser_t *parser)
223 if (!parser->imm_float_one)
224 parser->imm_float_one = parser_const_float(parser, 1);
225 return parser->imm_float_one;
228 static char *parser_strdup(const char *str)
231 /* actually dup empty strings */
232 char *out = mem_a(1);
236 return util_strdup(str);
239 static ast_value* parser_const_string(parser_t *parser, const char *str)
243 for (i = 0; i < vec_size(parser->imm_string); ++i) {
244 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
245 return parser->imm_string[i];
247 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
249 out->constval.vstring = parser_strdup(str);
250 vec_push(parser->imm_string, out);
254 static ast_value* parser_const_vector(parser_t *parser, vector v)
258 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
259 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
260 return parser->imm_vector[i];
262 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
264 out->constval.vvec = v;
265 vec_push(parser->imm_vector, out);
269 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
275 return parser_const_vector(parser, v);
278 static ast_value* parser_const_vector_0(parser_t *parser)
280 if (!parser->imm_vector_zero)
281 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
282 return parser->imm_vector_zero;
285 static ast_expression* parser_find_field(parser_t *parser, const char *name)
287 return util_htget(parser->htfields, name);
290 static ast_expression* parser_find_global(parser_t *parser, const char *name)
292 return util_htget(parser->htglobals, name);
295 static ast_expression* parser_find_param(parser_t *parser, const char *name)
299 if (!parser->function)
301 fun = parser->function->vtype;
302 for (i = 0; i < vec_size(fun->expression.params); ++i) {
303 if (!strcmp(fun->expression.params[i]->name, name))
304 return (ast_expression*)(fun->expression.params[i]);
309 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
314 hash = util_hthash(parser->htglobals, name);
317 for (i = vec_size(parser->variables); i > upto;) {
319 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
323 return parser_find_param(parser, name);
326 static ast_expression* parser_find_var(parser_t *parser, const char *name)
330 v = parser_find_local(parser, name, 0, &dummy);
331 if (!v) v = parser_find_global(parser, name);
337 size_t etype; /* 0 = expression, others are operators */
341 ast_block *block; /* for commas and function calls */
350 #define SY_PAREN_EXPR '('
351 #define SY_PAREN_FUNC 'f'
352 #define SY_PAREN_INDEX '['
354 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
365 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
369 e.out = (ast_expression*)v;
376 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
378 e.etype = 1 + (op - operators);
387 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
399 # define DEBUGSHUNTDO(x) x
401 # define DEBUGSHUNTDO(x)
404 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
405 * so we need to rotate it to become ent.(foo[n]).
407 static bool rotate_entfield_array_index_nodes(ast_expression **out)
409 ast_array_index *index;
410 ast_entfield *entfield;
414 ast_expression *entity;
416 lex_ctx ctx = ast_ctx(*out);
418 if (!ast_istype(*out, ast_array_index))
420 index = (ast_array_index*)*out;
422 if (!ast_istype(index->array, ast_entfield))
424 entfield = (ast_entfield*)index->array;
426 if (!ast_istype(entfield->field, ast_value))
428 field = (ast_value*)entfield->field;
431 entity = entfield->entity;
435 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
436 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
437 *out = (ast_expression*)entfield;
442 static bool parser_sy_pop(parser_t *parser, shunt *sy)
446 ast_expression *out = NULL;
447 ast_expression *exprs[3];
448 ast_block *blocks[3];
449 ast_value *asvalue[3];
450 size_t i, assignop, addop, subop;
451 qcint generated_op = 0;
456 if (!vec_size(sy->ops)) {
457 parseerror(parser, "internal error: missing operator");
461 if (vec_last(sy->ops).paren) {
462 parseerror(parser, "unmatched parenthesis");
466 op = &operators[vec_last(sy->ops).etype - 1];
467 ctx = vec_last(sy->ops).ctx;
469 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
471 if (vec_size(sy->out) < op->operands) {
472 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
473 op->op, (int)op->id);
477 vec_shrinkby(sy->ops, 1);
479 vec_shrinkby(sy->out, op->operands);
480 for (i = 0; i < op->operands; ++i) {
481 exprs[i] = sy->out[vec_size(sy->out)+i].out;
482 blocks[i] = sy->out[vec_size(sy->out)+i].block;
483 asvalue[i] = (ast_value*)exprs[i];
486 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
487 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
491 #define NotSameType(T) \
492 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
493 exprs[0]->expression.vtype != T)
494 #define CanConstFold1(A) \
495 (ast_istype((A), ast_value) && ((ast_value*)(A))->isconst)
496 #define CanConstFold(A, B) \
497 (CanConstFold1(A) && CanConstFold1(B))
498 #define ConstV(i) (asvalue[(i)]->constval.vvec)
499 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
500 #define ConstS(i) (asvalue[(i)]->constval.vstring)
504 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
508 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
509 if (exprs[1]->expression.vtype != TYPE_FIELD) {
510 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
513 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
515 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
516 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
520 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
526 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
527 !(exprs[0]->expression.vtype == TYPE_FIELD &&
528 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
530 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
531 parseerror(parser, "cannot index value of type %s", ty1);
534 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
535 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
536 parseerror(parser, "index must be of type float, not %s", ty1);
539 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
540 if (rotate_entfield_array_index_nodes(&out))
542 if (opts_standard != COMPILER_GMQCC) {
543 /* this error doesn't need to make us bail out */
544 (void)!parsewarning(parser, WARN_EXTENSIONS,
545 "accessing array-field members of an entity without parenthesis\n"
546 " -> this is an extension from -std=gmqcc");
553 vec_push(blocks[0]->exprs, exprs[1]);
555 blocks[0] = ast_block_new(ctx);
556 vec_push(blocks[0]->exprs, exprs[0]);
557 vec_push(blocks[0]->exprs, exprs[1]);
559 if (!ast_block_set_type(blocks[0], exprs[1]))
562 vec_push(sy->out, syblock(ctx, blocks[0]));
566 switch (exprs[0]->expression.vtype) {
568 if (CanConstFold1(exprs[0]))
569 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
571 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
572 (ast_expression*)parser_const_float_0(parser),
576 if (CanConstFold1(exprs[0]))
577 out = (ast_expression*)parser_const_vector_f(parser,
578 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
580 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
581 (ast_expression*)parser_const_vector_0(parser),
585 parseerror(parser, "invalid types used in expression: cannot negate type %s",
586 type_name[exprs[0]->expression.vtype]);
592 switch (exprs[0]->expression.vtype) {
594 if (CanConstFold1(exprs[0]))
595 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
597 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
600 if (CanConstFold1(exprs[0]))
601 out = (ast_expression*)parser_const_float(parser,
602 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
604 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
607 if (CanConstFold1(exprs[0]))
608 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
610 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
612 /* we don't constant-fold NOT for these types */
614 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
617 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
620 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
621 type_name[exprs[0]->expression.vtype]);
627 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
628 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
630 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
631 type_name[exprs[0]->expression.vtype],
632 type_name[exprs[1]->expression.vtype]);
635 switch (exprs[0]->expression.vtype) {
637 if (CanConstFold(exprs[0], exprs[1]))
639 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
642 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
645 if (CanConstFold(exprs[0], exprs[1]))
646 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
648 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
651 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
652 type_name[exprs[0]->expression.vtype],
653 type_name[exprs[1]->expression.vtype]);
658 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
659 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
661 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
662 type_name[exprs[1]->expression.vtype],
663 type_name[exprs[0]->expression.vtype]);
666 switch (exprs[0]->expression.vtype) {
668 if (CanConstFold(exprs[0], exprs[1]))
669 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
671 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
674 if (CanConstFold(exprs[0], exprs[1]))
675 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
677 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
680 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
681 type_name[exprs[1]->expression.vtype],
682 type_name[exprs[0]->expression.vtype]);
687 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
688 exprs[0]->expression.vtype != TYPE_VECTOR &&
689 exprs[0]->expression.vtype != TYPE_FLOAT &&
690 exprs[1]->expression.vtype != TYPE_VECTOR &&
691 exprs[1]->expression.vtype != TYPE_FLOAT)
693 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
694 type_name[exprs[1]->expression.vtype],
695 type_name[exprs[0]->expression.vtype]);
698 switch (exprs[0]->expression.vtype) {
700 if (exprs[1]->expression.vtype == TYPE_VECTOR)
702 if (CanConstFold(exprs[0], exprs[1]))
703 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
705 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
709 if (CanConstFold(exprs[0], exprs[1]))
710 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
712 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
716 if (exprs[1]->expression.vtype == TYPE_FLOAT)
718 if (CanConstFold(exprs[0], exprs[1]))
719 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
721 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
725 if (CanConstFold(exprs[0], exprs[1]))
726 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
728 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
732 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
733 type_name[exprs[1]->expression.vtype],
734 type_name[exprs[0]->expression.vtype]);
739 if (NotSameType(TYPE_FLOAT)) {
740 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
741 type_name[exprs[0]->expression.vtype],
742 type_name[exprs[1]->expression.vtype]);
745 if (CanConstFold(exprs[0], exprs[1]))
746 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
748 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
752 parseerror(parser, "qc does not have a modulo operator");
756 if (NotSameType(TYPE_FLOAT)) {
757 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
758 type_name[exprs[0]->expression.vtype],
759 type_name[exprs[1]->expression.vtype]);
762 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_float(parser,
764 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
765 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
767 out = (ast_expression*)ast_binary_new(ctx,
768 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
772 parseerror(parser, "TODO: bitxor");
777 case opid3('<','<','='):
778 case opid3('>','>','='):
779 parseerror(parser, "TODO: shifts");
783 generated_op += 1; /* INSTR_OR */
785 generated_op += INSTR_AND;
786 if (NotSameType(TYPE_FLOAT)) {
787 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
788 type_name[exprs[0]->expression.vtype],
789 type_name[exprs[1]->expression.vtype]);
790 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
791 parseerror(parser, "TODO: optional early out");
794 if (opts_standard == COMPILER_GMQCC)
795 con_out("TODO: early out logic\n");
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_float(parser,
798 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
800 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
804 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
805 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
806 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
807 parseerror(parser, "iperands of ternary expression must have the same type, got %s and %s", ty1, ty2);
810 if (CanConstFold1(exprs[0]))
811 out = (ConstF(0) ? exprs[1] : exprs[2]);
813 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
817 generated_op += 1; /* INSTR_GT */
819 generated_op += 1; /* INSTR_LT */
820 case opid2('>', '='):
821 generated_op += 1; /* INSTR_GE */
822 case opid2('<', '='):
823 generated_op += INSTR_LE;
824 if (NotSameType(TYPE_FLOAT)) {
825 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
826 type_name[exprs[0]->expression.vtype],
827 type_name[exprs[1]->expression.vtype]);
830 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
832 case opid2('!', '='):
833 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
834 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
835 type_name[exprs[0]->expression.vtype],
836 type_name[exprs[1]->expression.vtype]);
839 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
841 case opid2('=', '='):
842 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
843 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
844 type_name[exprs[0]->expression.vtype],
845 type_name[exprs[1]->expression.vtype]);
848 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
852 if (ast_istype(exprs[0], ast_entfield)) {
853 ast_expression *field = ((ast_entfield*)exprs[0])->field;
854 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
855 exprs[0]->expression.vtype == TYPE_FIELD &&
856 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
858 assignop = type_storep_instr[TYPE_VECTOR];
861 assignop = type_storep_instr[exprs[0]->expression.vtype];
862 if (!ast_compare_type(field->expression.next, exprs[1])) {
863 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
864 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
865 if (opts_standard == COMPILER_QCC &&
866 field->expression.next->expression.vtype == TYPE_FUNCTION &&
867 exprs[1]->expression.vtype == TYPE_FUNCTION)
869 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
870 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
876 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
881 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
882 exprs[0]->expression.vtype == TYPE_FIELD &&
883 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
885 assignop = type_store_instr[TYPE_VECTOR];
888 assignop = type_store_instr[exprs[0]->expression.vtype];
891 if (assignop == AINSTR_END) {
892 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
893 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
894 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
896 else if (!ast_compare_type(exprs[0], exprs[1])) {
897 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
898 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
899 if (opts_standard == COMPILER_QCC &&
900 exprs[0]->expression.vtype == TYPE_FUNCTION &&
901 exprs[1]->expression.vtype == TYPE_FUNCTION)
903 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
904 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
910 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
913 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
915 case opid3('+','+','P'):
916 case opid3('-','-','P'):
918 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
919 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
920 parseerror(parser, "invalid type for prefix increment: %s", ty1);
923 if (op->id == opid3('+','+','P'))
927 if (ast_istype(exprs[0], ast_entfield)) {
928 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
930 (ast_expression*)parser_const_float_1(parser));
932 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
934 (ast_expression*)parser_const_float_1(parser));
937 case opid3('S','+','+'):
938 case opid3('S','-','-'):
940 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
941 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
942 parseerror(parser, "invalid type for suffix increment: %s", ty1);
945 if (op->id == opid3('S','+','+')) {
952 if (ast_istype(exprs[0], ast_entfield)) {
953 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
955 (ast_expression*)parser_const_float_1(parser));
957 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
959 (ast_expression*)parser_const_float_1(parser));
963 out = (ast_expression*)ast_binary_new(ctx, subop,
965 (ast_expression*)parser_const_float_1(parser));
969 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
970 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
972 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
973 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
974 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
978 if (ast_istype(exprs[0], ast_entfield))
979 assignop = type_storep_instr[exprs[0]->expression.vtype];
981 assignop = type_store_instr[exprs[0]->expression.vtype];
982 switch (exprs[0]->expression.vtype) {
984 out = (ast_expression*)ast_binstore_new(ctx, assignop,
985 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
989 out = (ast_expression*)ast_binstore_new(ctx, assignop,
990 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
994 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
995 type_name[exprs[0]->expression.vtype],
996 type_name[exprs[1]->expression.vtype]);
1000 case opid2('*','='):
1001 case opid2('/','='):
1002 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1003 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1004 exprs[0]->expression.vtype == TYPE_VECTOR))
1006 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1007 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1008 parseerror(parser, "invalid types used in expression: %s and %s",
1012 if (ast_istype(exprs[0], ast_entfield))
1013 assignop = type_storep_instr[exprs[0]->expression.vtype];
1015 assignop = type_store_instr[exprs[0]->expression.vtype];
1016 switch (exprs[0]->expression.vtype) {
1018 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1019 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1020 exprs[0], exprs[1]);
1023 if (op->id == opid2('*','=')) {
1024 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1025 exprs[0], exprs[1]);
1027 /* there's no DIV_VF */
1028 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1029 (ast_expression*)parser_const_float_1(parser),
1033 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1038 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1039 type_name[exprs[0]->expression.vtype],
1040 type_name[exprs[1]->expression.vtype]);
1044 case opid2('&','='):
1045 case opid2('|','='):
1046 if (NotSameType(TYPE_FLOAT)) {
1047 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1048 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1049 parseerror(parser, "invalid types used in expression: %s and %s",
1053 if (ast_istype(exprs[0], ast_entfield))
1054 assignop = type_storep_instr[exprs[0]->expression.vtype];
1056 assignop = type_store_instr[exprs[0]->expression.vtype];
1057 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1058 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1059 exprs[0], exprs[1]);
1061 case opid3('&','~','='):
1062 /* This is like: a &= ~(b);
1063 * But QC has no bitwise-not, so we implement it as
1066 if (NotSameType(TYPE_FLOAT)) {
1067 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1068 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1069 parseerror(parser, "invalid types used in expression: %s and %s",
1073 if (ast_istype(exprs[0], ast_entfield))
1074 assignop = type_storep_instr[exprs[0]->expression.vtype];
1076 assignop = type_store_instr[exprs[0]->expression.vtype];
1077 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1080 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1086 parseerror(parser, "failed to apply operand %s", op->op);
1090 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1091 vec_push(sy->out, syexp(ctx, out));
1095 static bool parser_close_call(parser_t *parser, shunt *sy)
1097 /* was a function call */
1098 ast_expression *fun;
1104 vec_shrinkby(sy->ops, 1);
1105 fid = sy->ops[vec_size(sy->ops)].off;
1107 /* out[fid] is the function
1108 * everything above is parameters...
1109 * 0 params = nothing
1110 * 1 params = ast_expression
1114 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1115 parseerror(parser, "internal error: function call needs function and parameter list...");
1119 fun = sy->out[fid].out;
1121 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1123 parseerror(parser, "out of memory");
1127 if (fid+1 == vec_size(sy->out)) {
1130 } else if (fid+2 == vec_size(sy->out)) {
1132 vec_shrinkby(sy->out, 1);
1133 params = sy->out[vec_size(sy->out)].block;
1137 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1139 paramcount = vec_size(params->exprs);
1140 call->params = params->exprs;
1141 params->exprs = NULL;
1144 if (!ast_call_check_types(call))
1147 parseerror(parser, "invalid function call");
1151 /* overwrite fid, the function, with a call */
1152 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1154 if (fun->expression.vtype != TYPE_FUNCTION) {
1155 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1159 if (!fun->expression.next) {
1160 parseerror(parser, "could not determine function return type");
1163 if (vec_size(fun->expression.params) != paramcount &&
1164 !(fun->expression.variadic &&
1165 vec_size(fun->expression.params) < paramcount))
1168 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1170 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1171 if (opts_standard == COMPILER_GMQCC)
1174 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1175 " -> `%s` has been declared here: %s:%i",
1176 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1177 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1179 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1180 " -> `%s` has been declared here: %s:%i",
1181 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1182 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1188 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1189 "too %s parameters for call to %s: expected %i, got %i\n"
1190 " -> `%s` has been declared here: %s:%i",
1191 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1192 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1194 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1195 "too %s parameters for function call: expected %i, got %i\n"
1196 " -> `%s` has been declared here: %s:%i",
1197 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1198 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1206 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1208 if (!vec_size(sy->ops)) {
1209 parseerror(parser, "unmatched closing paren");
1212 /* this would for bit a + (x) because there are no operators inside (x)
1213 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1214 parseerror(parser, "empty parenthesis expression");
1218 while (vec_size(sy->ops)) {
1219 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1220 if (!parser_close_call(parser, sy))
1224 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1225 vec_shrinkby(sy->ops, 1);
1226 return !functions_only;
1228 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1231 /* pop off the parenthesis */
1232 vec_shrinkby(sy->ops, 1);
1233 /* then apply the index operator */
1234 if (!parser_sy_pop(parser, sy))
1238 if (!parser_sy_pop(parser, sy))
1244 static void parser_reclassify_token(parser_t *parser)
1247 for (i = 0; i < operator_count; ++i) {
1248 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1249 parser->tok = TOKEN_OPERATOR;
1255 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1257 ast_expression *expr = NULL;
1259 bool wantop = false;
1260 bool gotmemberof = false;
1262 /* count the parens because an if starts with one, so the
1263 * end of a condition is an unmatched closing paren
1271 parser->lex->flags.noops = false;
1273 parser_reclassify_token(parser);
1278 gotmemberof = false;
1280 parser->memberof = 0;
1282 if (parser->tok == TOKEN_IDENT)
1284 ast_expression *var;
1286 parseerror(parser, "expected operator or end of statement");
1291 if (opts_standard == COMPILER_GMQCC)
1293 if (parser->memberof == TYPE_ENTITY) {
1294 /* still get vars first since there could be a fieldpointer */
1295 var = parser_find_var(parser, parser_tokval(parser));
1297 var = parser_find_field(parser, parser_tokval(parser));
1299 else if (parser->memberof == TYPE_VECTOR)
1301 parseerror(parser, "TODO: implement effective vector member access");
1304 else if (parser->memberof) {
1305 parseerror(parser, "namespace for member not found");
1309 var = parser_find_var(parser, parser_tokval(parser));
1311 var = parser_find_var(parser, parser_tokval(parser));
1313 var = parser_find_field(parser, parser_tokval(parser));
1316 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1319 if (ast_istype(var, ast_value))
1320 ((ast_value*)var)->uses++;
1321 vec_push(sy.out, syexp(parser_ctx(parser), var));
1322 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1324 else if (parser->tok == TOKEN_FLOATCONST) {
1327 parseerror(parser, "expected operator or end of statement, got constant");
1331 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1334 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1335 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1337 else if (parser->tok == TOKEN_INTCONST) {
1340 parseerror(parser, "expected operator or end of statement, got constant");
1344 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1347 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1348 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1350 else if (parser->tok == TOKEN_STRINGCONST) {
1353 parseerror(parser, "expected operator or end of statement, got constant");
1357 val = parser_const_string(parser, parser_tokval(parser));
1360 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1361 DEBUGSHUNTDO(con_out("push string\n"));
1363 else if (parser->tok == TOKEN_VECTORCONST) {
1366 parseerror(parser, "expected operator or end of statement, got constant");
1370 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1373 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1374 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1375 parser_token(parser)->constval.v.x,
1376 parser_token(parser)->constval.v.y,
1377 parser_token(parser)->constval.v.z));
1379 else if (parser->tok == '(') {
1380 parseerror(parser, "internal error: '(' should be classified as operator");
1383 else if (parser->tok == '[') {
1384 parseerror(parser, "internal error: '[' should be classified as operator");
1387 else if (parser->tok == ')') {
1389 DEBUGSHUNTDO(con_out("do[op] )\n"));
1393 /* we do expect an operator next */
1394 /* closing an opening paren */
1395 if (!parser_close_paren(parser, &sy, false))
1398 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1402 /* allowed for function calls */
1403 if (!parser_close_paren(parser, &sy, true))
1408 else if (parser->tok == ']') {
1410 parseerror(parser, "operand expected");
1414 if (!parser_close_paren(parser, &sy, false))
1418 else if (parser->tok != TOKEN_OPERATOR) {
1420 parseerror(parser, "expected operator or end of statement");
1427 /* classify the operator */
1428 const oper_info *op;
1429 const oper_info *olast = NULL;
1431 for (o = 0; o < operator_count; ++o) {
1432 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1433 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1434 !strcmp(parser_tokval(parser), operators[o].op))
1439 if (o == operator_count) {
1440 /* no operator found... must be the end of the statement */
1443 /* found an operator */
1446 /* when declaring variables, a comma starts a new variable */
1447 if (op->id == opid1(',') && !parens && stopatcomma) {
1448 /* fixup the token */
1453 /* a colon without a pervious question mark cannot be a ternary */
1454 if (!ternaries && op->id == opid2(':','?')) {
1459 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1460 olast = &operators[vec_last(sy.ops).etype-1];
1463 (op->prec < olast->prec) ||
1464 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1466 if (!parser_sy_pop(parser, &sy))
1468 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1469 olast = &operators[vec_last(sy.ops).etype-1];
1474 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1475 /* for gmqcc standard: open up the namespace of the previous type */
1476 ast_expression *prevex = vec_last(sy.out).out;
1478 parseerror(parser, "unexpected member operator");
1481 if (prevex->expression.vtype == TYPE_ENTITY)
1482 parser->memberof = TYPE_ENTITY;
1483 else if (prevex->expression.vtype == TYPE_VECTOR)
1484 parser->memberof = TYPE_VECTOR;
1486 parseerror(parser, "type error: type has no members");
1492 if (op->id == opid1('(')) {
1494 size_t sycount = vec_size(sy.out);
1495 DEBUGSHUNTDO(con_out("push [op] (\n"));
1497 /* we expected an operator, this is the function-call operator */
1498 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1501 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1502 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1505 } else if (op->id == opid1('[')) {
1507 parseerror(parser, "unexpected array subscript");
1511 /* push both the operator and the paren, this makes life easier */
1512 vec_push(sy.ops, syop(parser_ctx(parser), op));
1513 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1515 } else if (op->id == opid2('?',':')) {
1517 vec_push(sy.ops, syop(parser_ctx(parser), op));
1520 } else if (op->id == opid2(':','?')) {
1521 /* we don't push this operator */
1525 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1526 vec_push(sy.ops, syop(parser_ctx(parser), op));
1527 wantop = !!(op->flags & OP_SUFFIX);
1530 if (!parser_next(parser)) {
1533 if (parser->tok == ';' ||
1534 (!parens && parser->tok == ']'))
1540 while (vec_size(sy.ops)) {
1541 if (!parser_sy_pop(parser, &sy))
1545 parser->lex->flags.noops = true;
1546 if (!vec_size(sy.out)) {
1547 parseerror(parser, "empty expression");
1550 expr = sy.out[0].out;
1553 DEBUGSHUNTDO(con_out("shunt done\n"));
1557 parser->lex->flags.noops = true;
1563 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1565 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1568 if (!parser_next(parser)) {
1575 static void parser_enterblock(parser_t *parser)
1577 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1578 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1581 static bool parser_leaveblock(parser_t *parser)
1586 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1587 parseerror(parser, "internal error: parser_leaveblock with no block");
1591 util_htdel(vec_last(parser->variables));
1592 vec_pop(parser->variables);
1593 if (!vec_size(parser->_blocklocals)) {
1594 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1598 locals = vec_last(parser->_blocklocals);
1599 vec_pop(parser->_blocklocals);
1600 while (vec_size(parser->_locals) != locals) {
1601 ast_expression *e = vec_last(parser->_locals);
1602 ast_value *v = (ast_value*)e;
1603 vec_pop(parser->_locals);
1604 if (ast_istype(e, ast_value) && !v->uses) {
1605 if (parsewarning(parser, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1613 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1615 vec_push(parser->_locals, e);
1616 util_htset(vec_last(parser->variables), name, (void*)e);
1619 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1622 ast_expression *cond, *ontrue, *onfalse = NULL;
1625 lex_ctx ctx = parser_ctx(parser);
1627 (void)block; /* not touching */
1629 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1630 if (!parser_next(parser)) {
1631 parseerror(parser, "expected condition or 'not'");
1634 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "not")) {
1636 if (!parser_next(parser)) {
1637 parseerror(parser, "expected condition in parenthesis");
1641 if (parser->tok != '(') {
1642 parseerror(parser, "expected 'if' condition in parenthesis");
1645 /* parse into the expression */
1646 if (!parser_next(parser)) {
1647 parseerror(parser, "expected 'if' condition after opening paren");
1650 /* parse the condition */
1651 cond = parse_expression_leave(parser, false);
1655 if (parser->tok != ')') {
1656 parseerror(parser, "expected closing paren after 'if' condition");
1660 /* parse into the 'then' branch */
1661 if (!parser_next(parser)) {
1662 parseerror(parser, "expected statement for on-true branch of 'if'");
1666 ontrue = parse_statement_or_block(parser);
1671 /* check for an else */
1672 if (!strcmp(parser_tokval(parser), "else")) {
1673 /* parse into the 'else' branch */
1674 if (!parser_next(parser)) {
1675 parseerror(parser, "expected on-false branch after 'else'");
1680 onfalse = parse_statement_or_block(parser);
1689 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1691 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1692 *out = (ast_expression*)ifthen;
1696 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1699 ast_expression *cond, *ontrue;
1701 lex_ctx ctx = parser_ctx(parser);
1703 (void)block; /* not touching */
1705 /* skip the 'while' and check for opening paren */
1706 if (!parser_next(parser) || parser->tok != '(') {
1707 parseerror(parser, "expected 'while' condition in parenthesis");
1710 /* parse into the expression */
1711 if (!parser_next(parser)) {
1712 parseerror(parser, "expected 'while' condition after opening paren");
1715 /* parse the condition */
1716 cond = parse_expression_leave(parser, false);
1720 if (parser->tok != ')') {
1721 parseerror(parser, "expected closing paren after 'while' condition");
1725 /* parse into the 'then' branch */
1726 if (!parser_next(parser)) {
1727 parseerror(parser, "expected while-loop body");
1731 ontrue = parse_statement_or_block(parser);
1737 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1738 *out = (ast_expression*)aloop;
1742 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1745 ast_expression *cond, *ontrue;
1747 lex_ctx ctx = parser_ctx(parser);
1749 (void)block; /* not touching */
1751 /* skip the 'do' and get the body */
1752 if (!parser_next(parser)) {
1753 parseerror(parser, "expected loop body");
1756 ontrue = parse_statement_or_block(parser);
1760 /* expect the "while" */
1761 if (parser->tok != TOKEN_KEYWORD ||
1762 strcmp(parser_tokval(parser), "while"))
1764 parseerror(parser, "expected 'while' and condition");
1769 /* skip the 'while' and check for opening paren */
1770 if (!parser_next(parser) || parser->tok != '(') {
1771 parseerror(parser, "expected 'while' condition in parenthesis");
1775 /* parse into the expression */
1776 if (!parser_next(parser)) {
1777 parseerror(parser, "expected 'while' condition after opening paren");
1781 /* parse the condition */
1782 cond = parse_expression_leave(parser, false);
1786 if (parser->tok != ')') {
1787 parseerror(parser, "expected closing paren after 'while' condition");
1793 if (!parser_next(parser) || parser->tok != ';') {
1794 parseerror(parser, "expected semicolon after condition");
1800 if (!parser_next(parser)) {
1801 parseerror(parser, "parse error");
1807 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1808 *out = (ast_expression*)aloop;
1812 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1815 ast_expression *initexpr, *cond, *increment, *ontrue;
1818 lex_ctx ctx = parser_ctx(parser);
1820 parser_enterblock(parser);
1827 /* skip the 'while' and check for opening paren */
1828 if (!parser_next(parser) || parser->tok != '(') {
1829 parseerror(parser, "expected 'for' expressions in parenthesis");
1832 /* parse into the expression */
1833 if (!parser_next(parser)) {
1834 parseerror(parser, "expected 'for' initializer after opening paren");
1838 if (parser->tok == TOKEN_TYPENAME) {
1839 if (opts_standard != COMPILER_GMQCC) {
1840 if (parsewarning(parser, WARN_EXTENSIONS,
1841 "current standard does not allow variable declarations in for-loop initializers"))
1845 parseerror(parser, "TODO: assignment of new variables to be non-const");
1847 if (!parse_variable(parser, block, true, false))
1850 else if (parser->tok != ';')
1852 initexpr = parse_expression_leave(parser, false);
1857 /* move on to condition */
1858 if (parser->tok != ';') {
1859 parseerror(parser, "expected semicolon after for-loop initializer");
1862 if (!parser_next(parser)) {
1863 parseerror(parser, "expected for-loop condition");
1867 /* parse the condition */
1868 if (parser->tok != ';') {
1869 cond = parse_expression_leave(parser, false);
1874 /* move on to incrementor */
1875 if (parser->tok != ';') {
1876 parseerror(parser, "expected semicolon after for-loop initializer");
1879 if (!parser_next(parser)) {
1880 parseerror(parser, "expected for-loop condition");
1884 /* parse the incrementor */
1885 if (parser->tok != ')') {
1886 increment = parse_expression_leave(parser, false);
1889 if (!ast_istype(increment, ast_store) &&
1890 !ast_istype(increment, ast_call) &&
1891 !ast_istype(increment, ast_binstore))
1893 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
1899 if (parser->tok != ')') {
1900 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
1903 /* parse into the 'then' branch */
1904 if (!parser_next(parser)) {
1905 parseerror(parser, "expected for-loop body");
1908 ontrue = parse_statement_or_block(parser);
1913 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
1914 *out = (ast_expression*)aloop;
1916 if (!parser_leaveblock(parser))
1920 if (initexpr) ast_delete(initexpr);
1921 if (cond) ast_delete(cond);
1922 if (increment) ast_delete(increment);
1923 (void)!parser_leaveblock(parser);
1927 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
1929 ast_expression *exp = NULL;
1930 ast_return *ret = NULL;
1931 ast_value *expected = parser->function->vtype;
1933 (void)block; /* not touching */
1935 if (!parser_next(parser)) {
1936 parseerror(parser, "expected return expression");
1940 if (parser->tok != ';') {
1941 exp = parse_expression(parser, false);
1945 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
1946 parseerror(parser, "return with invalid expression");
1949 ret = ast_return_new(exp->expression.node.context, exp);
1955 if (!parser_next(parser))
1956 parseerror(parser, "parse error");
1957 if (expected->expression.next->expression.vtype != TYPE_VOID) {
1958 if (opts_standard != COMPILER_GMQCC)
1959 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
1961 parseerror(parser, "return without value");
1963 ret = ast_return_new(parser_ctx(parser), NULL);
1965 *out = (ast_expression*)ret;
1969 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
1971 lex_ctx ctx = parser_ctx(parser);
1973 (void)block; /* not touching */
1975 if (!parser_next(parser) || parser->tok != ';') {
1976 parseerror(parser, "expected semicolon");
1980 if (!parser_next(parser))
1981 parseerror(parser, "parse error");
1983 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
1987 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
1989 ast_expression *operand;
1991 ast_switch *switchnode;
1992 ast_switch_case swcase;
1994 lex_ctx ctx = parser_ctx(parser);
1996 (void)block; /* not touching */
1998 /* parse over the opening paren */
1999 if (!parser_next(parser) || parser->tok != '(') {
2000 parseerror(parser, "expected switch operand in parenthesis");
2004 /* parse into the expression */
2005 if (!parser_next(parser)) {
2006 parseerror(parser, "expected switch operand");
2009 /* parse the operand */
2010 operand = parse_expression_leave(parser, false);
2014 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2015 opval = (ast_value*)operand;
2016 if (!ast_istype(operand, ast_value) || !opval->isconst) {
2017 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2023 switchnode = ast_switch_new(ctx, operand);
2026 if (parser->tok != ')') {
2027 ast_delete(switchnode);
2028 parseerror(parser, "expected closing paren after 'switch' operand");
2032 /* parse over the opening paren */
2033 if (!parser_next(parser) || parser->tok != '{') {
2034 ast_delete(switchnode);
2035 parseerror(parser, "expected list of cases");
2039 if (!parser_next(parser)) {
2040 ast_delete(switchnode);
2041 parseerror(parser, "expected 'case' or 'default'");
2046 while (parser->tok != '}') {
2047 ast_block *caseblock;
2049 if (parser->tok != TOKEN_KEYWORD) {
2050 ast_delete(switchnode);
2051 parseerror(parser, "expected 'case' or 'default'");
2054 if (!strcmp(parser_tokval(parser), "case")) {
2055 if (!parser_next(parser)) {
2056 ast_delete(switchnode);
2057 parseerror(parser, "expected expression for case");
2060 swcase.value = parse_expression_leave(parser, false);
2061 if (!swcase.value) {
2062 ast_delete(switchnode);
2063 parseerror(parser, "expected expression for case");
2067 else if (!strcmp(parser_tokval(parser), "default")) {
2068 swcase.value = NULL;
2069 if (!parser_next(parser)) {
2070 ast_delete(switchnode);
2071 parseerror(parser, "expected colon");
2076 /* Now the colon and body */
2077 if (parser->tok != ':') {
2078 if (swcase.value) ast_unref(swcase.value);
2079 ast_delete(switchnode);
2080 parseerror(parser, "expected colon");
2084 if (!parser_next(parser)) {
2085 if (swcase.value) ast_unref(swcase.value);
2086 ast_delete(switchnode);
2087 parseerror(parser, "expected statements or case");
2090 caseblock = ast_block_new(parser_ctx(parser));
2092 if (swcase.value) ast_unref(swcase.value);
2093 ast_delete(switchnode);
2096 swcase.code = (ast_expression*)caseblock;
2097 vec_push(switchnode->cases, swcase);
2099 ast_expression *expr;
2100 if (parser->tok == '}')
2102 if (parser->tok == TOKEN_KEYWORD) {
2103 if (!strcmp(parser_tokval(parser), "case") ||
2104 !strcmp(parser_tokval(parser), "default"))
2109 if (!parse_statement(parser, caseblock, &expr, true)) {
2110 ast_delete(switchnode);
2115 vec_push(caseblock->exprs, expr);
2120 if (parser->tok != '}') {
2121 ast_delete(switchnode);
2122 parseerror(parser, "expected closing paren of case list");
2125 if (!parser_next(parser)) {
2126 ast_delete(switchnode);
2127 parseerror(parser, "parse error after switch");
2130 *out = (ast_expression*)switchnode;
2134 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2136 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2138 /* local variable */
2140 parseerror(parser, "cannot declare a variable from here");
2143 if (opts_standard == COMPILER_QCC) {
2144 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2147 if (!parse_variable(parser, block, false, false))
2152 else if (parser->tok == TOKEN_KEYWORD)
2154 if (!strcmp(parser_tokval(parser), "local"))
2157 parseerror(parser, "cannot declare a local variable here");
2160 if (!parser_next(parser)) {
2161 parseerror(parser, "expected variable declaration");
2164 if (!parse_variable(parser, block, true, false))
2169 else if (!strcmp(parser_tokval(parser), "return"))
2171 return parse_return(parser, block, out);
2173 else if (!strcmp(parser_tokval(parser), "if"))
2175 return parse_if(parser, block, out);
2177 else if (!strcmp(parser_tokval(parser), "while"))
2179 return parse_while(parser, block, out);
2181 else if (!strcmp(parser_tokval(parser), "do"))
2183 return parse_dowhile(parser, block, out);
2185 else if (!strcmp(parser_tokval(parser), "for"))
2187 if (opts_standard == COMPILER_QCC) {
2188 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2191 return parse_for(parser, block, out);
2193 else if (!strcmp(parser_tokval(parser), "break"))
2195 return parse_break_continue(parser, block, out, false);
2197 else if (!strcmp(parser_tokval(parser), "continue"))
2199 return parse_break_continue(parser, block, out, true);
2201 else if (!strcmp(parser_tokval(parser), "switch"))
2203 return parse_switch(parser, block, out);
2205 else if (!strcmp(parser_tokval(parser), "case") ||
2206 !strcmp(parser_tokval(parser), "default"))
2209 parseerror(parser, "unexpected 'case' label");
2214 parseerror(parser, "Unexpected keyword");
2217 else if (parser->tok == '{')
2220 inner = parse_block(parser, false);
2223 *out = (ast_expression*)inner;
2228 ast_expression *exp = parse_expression(parser, false);
2232 if (!ast_istype(exp, ast_store) &&
2233 !ast_istype(exp, ast_call) &&
2234 !ast_istype(exp, ast_binstore))
2236 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2243 static bool parse_block_into(parser_t *parser, ast_block *block, bool warnreturn)
2247 parser_enterblock(parser);
2249 if (!parser_next(parser)) { /* skip the '{' */
2250 parseerror(parser, "expected function body");
2254 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2256 ast_expression *expr;
2257 if (parser->tok == '}')
2260 if (!parse_statement(parser, block, &expr, false)) {
2261 /* parseerror(parser, "parse error"); */
2267 vec_push(block->exprs, expr);
2270 if (parser->tok != '}') {
2273 if (warnreturn && parser->function->vtype->expression.next->expression.vtype != TYPE_VOID)
2275 if (!vec_size(block->exprs) ||
2276 !ast_istype(vec_last(block->exprs), ast_return))
2278 if (parsewarning(parser, WARN_MISSING_RETURN_VALUES, "control reaches end of non-void function")) {
2284 (void)parser_next(parser);
2288 if (!parser_leaveblock(parser))
2293 static ast_block* parse_block(parser_t *parser, bool warnreturn)
2296 block = ast_block_new(parser_ctx(parser));
2299 if (!parse_block_into(parser, block, warnreturn)) {
2300 ast_block_delete(block);
2306 static ast_expression* parse_statement_or_block(parser_t *parser)
2308 ast_expression *expr = NULL;
2309 if (parser->tok == '{')
2310 return (ast_expression*)parse_block(parser, false);
2311 if (!parse_statement(parser, NULL, &expr, false))
2316 static bool create_vector_members(ast_value *var, ast_member **me)
2319 size_t len = strlen(var->name);
2321 for (i = 0; i < 3; ++i) {
2322 char *name = mem_a(len+3);
2323 memcpy(name, var->name, len);
2325 name[len+1] = 'x'+i;
2327 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2336 do { ast_member_delete(me[--i]); } while(i);
2340 static bool parse_function_body(parser_t *parser, ast_value *var)
2342 ast_block *block = NULL;
2347 ast_expression *framenum = NULL;
2348 ast_expression *nextthink = NULL;
2349 /* None of the following have to be deleted */
2350 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2351 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2352 bool has_frame_think;
2356 has_frame_think = false;
2357 old = parser->function;
2359 if (var->expression.variadic) {
2360 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2361 "variadic function with implementation will not be able to access additional parameters"))
2367 if (parser->tok == '[') {
2368 /* got a frame definition: [ framenum, nextthink ]
2369 * this translates to:
2370 * self.frame = framenum;
2371 * self.nextthink = time + 0.1;
2372 * self.think = nextthink;
2376 fld_think = parser_find_field(parser, "think");
2377 fld_nextthink = parser_find_field(parser, "nextthink");
2378 fld_frame = parser_find_field(parser, "frame");
2379 if (!fld_think || !fld_nextthink || !fld_frame) {
2380 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2381 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2384 gbl_time = parser_find_global(parser, "time");
2385 gbl_self = parser_find_global(parser, "self");
2386 if (!gbl_time || !gbl_self) {
2387 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2388 parseerror(parser, "please declare the following globals: `time`, `self`");
2392 if (!parser_next(parser))
2395 framenum = parse_expression_leave(parser, true);
2397 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2400 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->isconst) {
2401 ast_unref(framenum);
2402 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2406 if (parser->tok != ',') {
2407 ast_unref(framenum);
2408 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2409 parseerror(parser, "Got a %i\n", parser->tok);
2413 if (!parser_next(parser)) {
2414 ast_unref(framenum);
2418 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2420 /* qc allows the use of not-yet-declared functions here
2421 * - this automatically creates a prototype */
2422 ast_value *thinkfunc;
2423 ast_expression *functype = fld_think->expression.next;
2425 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2426 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2427 ast_unref(framenum);
2428 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2432 if (!parser_next(parser)) {
2433 ast_unref(framenum);
2434 ast_delete(thinkfunc);
2438 vec_push(parser->globals, (ast_expression*)thinkfunc);
2439 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2440 nextthink = (ast_expression*)thinkfunc;
2443 nextthink = parse_expression_leave(parser, true);
2445 ast_unref(framenum);
2446 parseerror(parser, "expected a think-function in [frame,think] notation");
2451 if (!ast_istype(nextthink, ast_value)) {
2452 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2456 if (retval && parser->tok != ']') {
2457 parseerror(parser, "expected closing `]` for [frame,think] notation");
2461 if (retval && !parser_next(parser)) {
2465 if (retval && parser->tok != '{') {
2466 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2471 ast_unref(nextthink);
2472 ast_unref(framenum);
2476 has_frame_think = true;
2479 block = ast_block_new(parser_ctx(parser));
2481 parseerror(parser, "failed to allocate block");
2482 if (has_frame_think) {
2483 ast_unref(nextthink);
2484 ast_unref(framenum);
2489 if (has_frame_think) {
2491 ast_expression *self_frame;
2492 ast_expression *self_nextthink;
2493 ast_expression *self_think;
2494 ast_expression *time_plus_1;
2495 ast_store *store_frame;
2496 ast_store *store_nextthink;
2497 ast_store *store_think;
2499 ctx = parser_ctx(parser);
2500 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2501 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2502 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2504 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2505 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2507 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2508 if (self_frame) ast_delete(self_frame);
2509 if (self_nextthink) ast_delete(self_nextthink);
2510 if (self_think) ast_delete(self_think);
2511 if (time_plus_1) ast_delete(time_plus_1);
2517 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2518 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2519 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2522 ast_delete(self_frame);
2525 if (!store_nextthink) {
2526 ast_delete(self_nextthink);
2530 ast_delete(self_think);
2534 if (store_frame) ast_delete(store_frame);
2535 if (store_nextthink) ast_delete(store_nextthink);
2536 if (store_think) ast_delete(store_think);
2539 vec_push(block->exprs, (ast_expression*)store_frame);
2540 vec_push(block->exprs, (ast_expression*)store_nextthink);
2541 vec_push(block->exprs, (ast_expression*)store_think);
2545 parseerror(parser, "failed to generate code for [frame,think]");
2546 ast_unref(nextthink);
2547 ast_unref(framenum);
2553 parser_enterblock(parser);
2555 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2557 ast_value *param = var->expression.params[parami];
2560 if (param->expression.vtype != TYPE_VECTOR &&
2561 (param->expression.vtype != TYPE_FIELD ||
2562 param->expression.next->expression.vtype != TYPE_VECTOR))
2567 if (!create_vector_members(param, me)) {
2568 ast_block_delete(block);
2572 for (e = 0; e < 3; ++e) {
2573 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2574 ast_block_collect(block, (ast_expression*)me[e]);
2578 func = ast_function_new(ast_ctx(var), var->name, var);
2580 parseerror(parser, "failed to allocate function for `%s`", var->name);
2581 ast_block_delete(block);
2584 vec_push(parser->functions, func);
2586 parser->function = func;
2587 if (!parse_block_into(parser, block, true)) {
2588 ast_block_delete(block);
2592 vec_push(func->blocks, block);
2594 parser->function = old;
2595 if (!parser_leaveblock(parser))
2597 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2598 parseerror(parser, "internal error: local scopes left");
2602 if (parser->tok == ';')
2603 return parser_next(parser);
2604 else if (opts_standard == COMPILER_QCC)
2605 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2609 vec_pop(parser->functions);
2610 ast_function_delete(func);
2611 var->constval.vfunc = NULL;
2614 (void)!parser_leaveblock(parser);
2615 parser->function = old;
2619 static ast_expression *array_accessor_split(
2624 ast_expression *left,
2625 ast_expression *right
2631 lex_ctx ctx = ast_ctx(array);
2633 if (!left || !right) {
2634 if (left) ast_delete(left);
2635 if (right) ast_delete(right);
2639 cmp = ast_binary_new(ctx, INSTR_LT,
2640 (ast_expression*)index,
2641 (ast_expression*)parser_const_float(parser, middle));
2645 parseerror(parser, "internal error: failed to create comparison for array setter");
2649 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
2651 ast_delete(cmp); /* will delete left and right */
2652 parseerror(parser, "internal error: failed to create conditional jump for array setter");
2656 return (ast_expression*)ifthen;
2659 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
2661 lex_ctx ctx = ast_ctx(array);
2663 if (from+1 == afterend) {
2664 /* set this value */
2667 ast_array_index *subscript;
2669 int assignop = type_store_instr[value->expression.vtype];
2671 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2672 assignop = INSTR_STORE_V;
2674 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2678 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
2680 ast_delete(subscript);
2684 block = ast_block_new(ctx);
2690 vec_push(block->exprs, (ast_expression*)st);
2692 ret = ast_return_new(ctx, NULL);
2698 vec_push(block->exprs, (ast_expression*)ret);
2700 return (ast_expression*)block;
2702 ast_expression *left, *right;
2703 size_t diff = afterend - from;
2704 size_t middle = from + diff/2;
2705 left = array_setter_node(parser, array, index, value, from, middle);
2706 right = array_setter_node(parser, array, index, value, middle, afterend);
2707 return array_accessor_split(parser, array, index, middle, left, right);
2711 static ast_expression *array_field_setter_node(
2720 lex_ctx ctx = ast_ctx(array);
2722 if (from+1 == afterend) {
2723 /* set this value */
2726 ast_entfield *entfield;
2727 ast_array_index *subscript;
2729 int assignop = type_storep_instr[value->expression.vtype];
2731 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
2732 assignop = INSTR_STOREP_V;
2734 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2738 entfield = ast_entfield_new_force(ctx,
2739 (ast_expression*)entity,
2740 (ast_expression*)subscript,
2741 (ast_expression*)subscript);
2743 ast_delete(subscript);
2747 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
2749 ast_delete(entfield);
2753 block = ast_block_new(ctx);
2759 vec_push(block->exprs, (ast_expression*)st);
2761 ret = ast_return_new(ctx, NULL);
2767 vec_push(block->exprs, (ast_expression*)ret);
2769 return (ast_expression*)block;
2771 ast_expression *left, *right;
2772 size_t diff = afterend - from;
2773 size_t middle = from + diff/2;
2774 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
2775 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
2776 return array_accessor_split(parser, array, index, middle, left, right);
2780 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
2782 lex_ctx ctx = ast_ctx(array);
2784 if (from+1 == afterend) {
2786 ast_array_index *subscript;
2788 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
2792 ret = ast_return_new(ctx, (ast_expression*)subscript);
2794 ast_delete(subscript);
2798 return (ast_expression*)ret;
2800 ast_expression *left, *right;
2801 size_t diff = afterend - from;
2802 size_t middle = from + diff/2;
2803 left = array_getter_node(parser, array, index, from, middle);
2804 right = array_getter_node(parser, array, index, middle, afterend);
2805 return array_accessor_split(parser, array, index, middle, left, right);
2809 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
2811 ast_function *func = NULL;
2812 ast_value *fval = NULL;
2813 ast_block *body = NULL;
2815 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
2817 parseerror(parser, "failed to create accessor function value");
2821 func = ast_function_new(ast_ctx(array), funcname, fval);
2824 parseerror(parser, "failed to create accessor function node");
2828 body = ast_block_new(ast_ctx(array));
2830 parseerror(parser, "failed to create block for array accessor");
2836 vec_push(func->blocks, body);
2839 vec_push(parser->accessors, fval);
2844 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
2846 ast_expression *root = NULL;
2847 ast_value *index = NULL;
2848 ast_value *value = NULL;
2852 if (!ast_istype(array->expression.next, ast_value)) {
2853 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2857 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2859 func = fval->constval.vfunc;
2860 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2862 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2863 value = ast_value_copy((ast_value*)array->expression.next);
2865 if (!index || !value) {
2866 parseerror(parser, "failed to create locals for array accessor");
2869 (void)!ast_value_set_name(value, "value"); /* not important */
2870 vec_push(fval->expression.params, index);
2871 vec_push(fval->expression.params, value);
2873 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
2875 parseerror(parser, "failed to build accessor search tree");
2879 vec_push(func->blocks[0]->exprs, root);
2880 array->setter = fval;
2883 if (index) ast_delete(index);
2884 if (value) ast_delete(value);
2885 if (root) ast_delete(root);
2891 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
2893 ast_expression *root = NULL;
2894 ast_value *entity = NULL;
2895 ast_value *index = NULL;
2896 ast_value *value = NULL;
2900 if (!ast_istype(array->expression.next, ast_value)) {
2901 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2905 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2907 func = fval->constval.vfunc;
2908 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
2910 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
2911 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2912 value = ast_value_copy((ast_value*)array->expression.next);
2913 if (!entity || !index || !value) {
2914 parseerror(parser, "failed to create locals for array accessor");
2917 (void)!ast_value_set_name(value, "value"); /* not important */
2918 vec_push(fval->expression.params, entity);
2919 vec_push(fval->expression.params, index);
2920 vec_push(fval->expression.params, value);
2922 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
2924 parseerror(parser, "failed to build accessor search tree");
2928 vec_push(func->blocks[0]->exprs, root);
2929 array->setter = fval;
2932 if (entity) ast_delete(entity);
2933 if (index) ast_delete(index);
2934 if (value) ast_delete(value);
2935 if (root) ast_delete(root);
2941 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
2943 ast_expression *root = NULL;
2944 ast_value *index = NULL;
2948 /* NOTE: checking array->expression.next rather than elemtype since
2949 * for fields elemtype is a temporary fieldtype.
2951 if (!ast_istype(array->expression.next, ast_value)) {
2952 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
2956 if (!parser_create_array_accessor(parser, array, funcname, &fval))
2958 func = fval->constval.vfunc;
2959 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
2961 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
2964 parseerror(parser, "failed to create locals for array accessor");
2967 vec_push(fval->expression.params, index);
2969 root = array_getter_node(parser, array, index, 0, array->expression.count);
2971 parseerror(parser, "failed to build accessor search tree");
2975 vec_push(func->blocks[0]->exprs, root);
2976 array->getter = fval;
2979 if (index) ast_delete(index);
2980 if (root) ast_delete(root);
2986 static ast_value *parse_typename(parser_t *parser, ast_value **storebase);
2987 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
2995 bool variadic = false;
2997 ctx = parser_ctx(parser);
2999 /* for the sake of less code we parse-in in this function */
3000 if (!parser_next(parser)) {
3001 parseerror(parser, "expected parameter list");
3007 /* parse variables until we hit a closing paren */
3008 while (parser->tok != ')') {
3010 /* there must be commas between them */
3011 if (parser->tok != ',') {
3012 parseerror(parser, "expected comma or end of parameter list");
3015 if (!parser_next(parser)) {
3016 parseerror(parser, "expected parameter");
3022 if (parser->tok == TOKEN_DOTS) {
3023 /* '...' indicates a varargs function */
3025 if (!parser_next(parser)) {
3026 parseerror(parser, "expected parameter");
3029 if (parser->tok != ')') {
3030 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3036 /* for anything else just parse a typename */
3037 param = parse_typename(parser, NULL);
3040 vec_push(params, param);
3041 if (param->expression.vtype >= TYPE_VARIANT) {
3042 char typename[1024];
3043 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3044 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3051 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3052 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3055 if (!parser_next(parser)) {
3056 parseerror(parser, "parse error after typename");
3060 /* now turn 'var' into a function type */
3061 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3062 fval->expression.next = (ast_expression*)var;
3063 fval->expression.variadic = variadic;
3066 var->expression.params = params;
3073 for (i = 0; i < vec_size(params); ++i)
3074 ast_delete(params[i]);
3079 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3081 ast_expression *cexp;
3082 ast_value *cval, *tmp;
3085 ctx = parser_ctx(parser);
3087 if (!parser_next(parser)) {
3089 parseerror(parser, "expected array-size");
3093 cexp = parse_expression_leave(parser, true);
3095 if (!cexp || !ast_istype(cexp, ast_value)) {
3099 parseerror(parser, "expected array-size as constant positive integer");
3102 cval = (ast_value*)cexp;
3104 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3105 tmp->expression.next = (ast_expression*)var;
3108 if (cval->expression.vtype == TYPE_INTEGER)
3109 tmp->expression.count = cval->constval.vint;
3110 else if (cval->expression.vtype == TYPE_FLOAT)
3111 tmp->expression.count = cval->constval.vfloat;
3115 parseerror(parser, "array-size must be a positive integer constant");
3120 if (parser->tok != ']') {
3122 parseerror(parser, "expected ']' after array-size");
3125 if (!parser_next(parser)) {
3127 parseerror(parser, "error after parsing array size");
3133 /* Parse a complete typename.
3134 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3135 * but when parsing variables separated by comma
3136 * 'storebase' should point to where the base-type should be kept.
3137 * The base type makes up every bit of type information which comes *before* the
3140 * The following will be parsed in its entirety:
3142 * The 'basetype' in this case is 'void()'
3143 * and if there's a comma after it, say:
3145 * then the type-information 'void()' can be stored in 'storebase'
3147 static ast_value *parse_typename(parser_t *parser, ast_value **storebase)
3149 ast_value *var, *tmp;
3152 const char *name = NULL;
3153 bool isfield = false;
3154 bool wasarray = false;
3156 ctx = parser_ctx(parser);
3158 /* types may start with a dot */
3159 if (parser->tok == '.') {
3161 /* if we parsed a dot we need a typename now */
3162 if (!parser_next(parser)) {
3163 parseerror(parser, "expected typename for field definition");
3166 if (parser->tok != TOKEN_TYPENAME) {
3167 parseerror(parser, "expected typename");
3172 /* generate the basic type value */
3173 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3174 /* do not yet turn into a field - remember:
3175 * .void() foo; is a field too
3176 * .void()() foo; is a function
3180 if (!parser_next(parser)) {
3182 parseerror(parser, "parse error after typename");
3186 /* an opening paren now starts the parameter-list of a function
3187 * this is where original-QC has parameter lists.
3188 * We allow a single parameter list here.
3189 * Much like fteqcc we don't allow `float()() x`
3191 if (parser->tok == '(') {
3192 var = parse_parameter_list(parser, var);
3197 /* store the base if requested */
3199 *storebase = ast_value_copy(var);
3201 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3202 tmp->expression.next = (ast_expression*)*storebase;
3207 /* there may be a name now */
3208 if (parser->tok == TOKEN_IDENT) {
3209 name = util_strdup(parser_tokval(parser));
3211 if (!parser_next(parser)) {
3213 parseerror(parser, "error after variable or field declaration");
3218 /* now this may be an array */
3219 if (parser->tok == '[') {
3221 var = parse_arraysize(parser, var);
3226 /* This is the point where we can turn it into a field */
3228 /* turn it into a field if desired */
3229 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3230 tmp->expression.next = (ast_expression*)var;
3234 /* now there may be function parens again */
3235 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3236 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3237 if (parser->tok == '(' && wasarray)
3238 parseerror(parser, "arrays as part of a return type is not supported");
3239 while (parser->tok == '(') {
3240 var = parse_parameter_list(parser, var);
3249 /* finally name it */
3251 if (!ast_value_set_name(var, name)) {
3253 parseerror(parser, "internal error: failed to set name");
3256 /* free the name, ast_value_set_name duplicates */
3263 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, bool is_const)
3267 ast_expression *old;
3271 ast_value *basetype = NULL;
3273 bool isparam = false;
3274 bool isvector = false;
3275 bool cleanvar = true;
3276 bool wasarray = false;
3280 /* get the first complete variable */
3281 var = parse_typename(parser, &basetype);
3284 ast_delete(basetype);
3292 /* Part 0: finish the type */
3293 if (parser->tok == '(') {
3294 if (opts_standard == COMPILER_QCC)
3295 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3296 var = parse_parameter_list(parser, var);
3302 /* we only allow 1-dimensional arrays */
3303 if (parser->tok == '[') {
3305 var = parse_arraysize(parser, var);
3311 if (parser->tok == '(' && wasarray) {
3312 parseerror(parser, "arrays as part of a return type is not supported");
3313 /* we'll still parse the type completely for now */
3315 /* for functions returning functions */
3316 while (parser->tok == '(') {
3317 if (opts_standard == COMPILER_QCC)
3318 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3319 var = parse_parameter_list(parser, var);
3327 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3328 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3329 * is then filled with the previous definition and the parameter-names replaced.
3332 /* Deal with end_sys_ vars */
3334 if (!strcmp(var->name, "end_sys_globals")) {
3335 parser->crc_globals = vec_size(parser->globals);
3338 else if (!strcmp(var->name, "end_sys_fields")) {
3339 parser->crc_fields = vec_size(parser->fields);
3342 if (was_end && var->expression.vtype == TYPE_FIELD) {
3343 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3344 "global '%s' hint should not be a field",
3345 parser_tokval(parser)))
3352 if (!nofields && var->expression.vtype == TYPE_FIELD)
3354 /* deal with field declarations */
3355 old = parser_find_field(parser, var->name);
3357 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3358 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3367 parseerror(parser, "field `%s` already declared here: %s:%i",
3368 var->name, ast_ctx(old).file, ast_ctx(old).line);
3373 if (opts_standard == COMPILER_QCC &&
3374 (old = parser_find_global(parser, var->name)))
3376 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3377 parseerror(parser, "field `%s` already declared here: %s:%i",
3378 var->name, ast_ctx(old).file, ast_ctx(old).line);
3385 /* deal with other globals */
3386 old = parser_find_global(parser, var->name);
3387 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3389 /* This is a function which had a prototype */
3390 if (!ast_istype(old, ast_value)) {
3391 parseerror(parser, "internal error: prototype is not an ast_value");
3395 proto = (ast_value*)old;
3396 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3397 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3399 ast_ctx(proto).file, ast_ctx(proto).line);
3403 /* we need the new parameter-names */
3404 for (i = 0; i < vec_size(proto->expression.params); ++i)
3405 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3413 if (opts_standard == COMPILER_GMQCC) {
3414 parseerror(parser, "global `%s` already declared here: %s:%i",
3415 var->name, ast_ctx(old).file, ast_ctx(old).line);
3419 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3420 "global `%s` already declared here: %s:%i",
3421 var->name, ast_ctx(old).file, ast_ctx(old).line))
3428 if (opts_standard == COMPILER_QCC &&
3429 (old = parser_find_field(parser, var->name)))
3431 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3432 parseerror(parser, "global `%s` already declared here: %s:%i",
3433 var->name, ast_ctx(old).file, ast_ctx(old).line);
3440 else /* it's not a global */
3442 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3443 if (old && !isparam) {
3444 parseerror(parser, "local `%s` already declared here: %s:%i",
3445 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3449 old = parser_find_local(parser, var->name, 0, &isparam);
3450 if (old && isparam) {
3451 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3452 "local `%s` is shadowing a parameter", var->name))
3454 parseerror(parser, "local `%s` already declared here: %s:%i",
3455 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3459 if (opts_standard != COMPILER_GMQCC) {
3468 var->isconst = true;
3471 * Create the global/local, and deal with vector types.
3474 if (var->expression.vtype == TYPE_VECTOR)
3476 else if (var->expression.vtype == TYPE_FIELD &&
3477 var->expression.next->expression.vtype == TYPE_VECTOR)
3481 if (!create_vector_members(var, me)) {
3488 /* deal with global variables, fields, functions */
3489 if (!nofields && var->expression.vtype == TYPE_FIELD) {
3490 vec_push(parser->fields, (ast_expression*)var);
3491 util_htset(parser->htfields, var->name, var);
3493 for (i = 0; i < 3; ++i) {
3494 vec_push(parser->fields, (ast_expression*)me[i]);
3495 util_htset(parser->htfields, me[i]->name, me[i]);
3500 vec_push(parser->globals, (ast_expression*)var);
3501 util_htset(parser->htglobals, var->name, var);
3503 for (i = 0; i < 3; ++i) {
3504 vec_push(parser->globals, (ast_expression*)me[i]);
3505 util_htset(parser->htglobals, me[i]->name, me[i]);
3510 vec_push(localblock->locals, var);
3511 parser_addlocal(parser, var->name, (ast_expression*)var);
3513 for (i = 0; i < 3; ++i) {
3514 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3515 ast_block_collect(localblock, (ast_expression*)me[i]);
3520 me[0] = me[1] = me[2] = NULL;
3526 if (var->expression.vtype == TYPE_ARRAY) {
3528 snprintf(name, sizeof(name), "%s##SET", var->name);
3529 if (!parser_create_array_setter(parser, var, name))
3531 snprintf(name, sizeof(name), "%s##GET", var->name);
3532 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3535 else if (!localblock && !nofields &&
3536 var->expression.vtype == TYPE_FIELD &&
3537 var->expression.next->expression.vtype == TYPE_ARRAY)
3540 ast_expression *telem;
3542 ast_value *array = (ast_value*)var->expression.next;
3544 if (!ast_istype(var->expression.next, ast_value)) {
3545 parseerror(parser, "internal error: field element type must be an ast_value");
3549 snprintf(name, sizeof(name), "%s##SETF", var->name);
3550 if (!parser_create_array_field_setter(parser, array, name))
3553 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3554 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3555 tfield->expression.next = telem;
3556 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3557 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
3565 if (parser->tok == ';') {
3566 ast_delete(basetype);
3567 if (!parser_next(parser)) {
3568 parseerror(parser, "error after variable declaration");
3574 if (parser->tok == ',')
3577 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
3578 parseerror(parser, "missing comma or semicolon while parsing variables");
3582 if (localblock && opts_standard == COMPILER_QCC) {
3583 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
3584 "initializing expression turns variable `%s` into a constant in this standard",
3591 if (parser->tok != '{') {
3592 if (parser->tok != '=') {
3593 parseerror(parser, "missing semicolon or initializer");
3597 if (!parser_next(parser)) {
3598 parseerror(parser, "error parsing initializer");
3602 else if (opts_standard == COMPILER_QCC) {
3603 parseerror(parser, "expected '=' before function body in this standard");
3606 if (parser->tok == '#') {
3610 parseerror(parser, "cannot declare builtins within functions");
3613 if (var->expression.vtype != TYPE_FUNCTION) {
3614 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
3617 if (!parser_next(parser)) {
3618 parseerror(parser, "expected builtin number");
3621 if (parser->tok != TOKEN_INTCONST) {
3622 parseerror(parser, "builtin number must be an integer constant");
3625 if (parser_token(parser)->constval.i <= 0) {
3626 parseerror(parser, "builtin number must be an integer greater than zero");
3631 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
3632 "builtin `%s` has already been defined\n"
3633 " -> previous declaration here: %s:%i",
3634 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
3638 func = ast_function_new(ast_ctx(var), var->name, var);
3640 parseerror(parser, "failed to allocate function for `%s`", var->name);
3643 vec_push(parser->functions, func);
3645 func->builtin = -parser_token(parser)->constval.i;
3648 if (!parser_next(parser)) {
3649 parseerror(parser, "expected comma or semicolon");
3650 ast_function_delete(func);
3651 var->constval.vfunc = NULL;
3655 else if (parser->tok == '{' || parser->tok == '[')
3658 parseerror(parser, "cannot declare functions within functions");
3662 if (!parse_function_body(parser, var))
3664 ast_delete(basetype);
3667 ast_expression *cexp;
3670 cexp = parse_expression_leave(parser, true);
3675 cval = (ast_value*)cexp;
3676 if (!ast_istype(cval, ast_value) || !cval->isconst)
3677 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
3680 var->isconst = true;
3681 if (cval->expression.vtype == TYPE_STRING)
3682 var->constval.vstring = parser_strdup(cval->constval.vstring);
3684 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
3688 shunt sy = { NULL, NULL };
3689 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
3690 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
3691 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
3692 if (!parser_sy_pop(parser, &sy))
3695 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
3696 parseerror(parser, "internal error: leaked operands");
3697 vec_push(localblock->exprs, (ast_expression*)sy.out[0].out);
3705 if (parser->tok == ',') {
3706 if (!parser_next(parser)) {
3707 parseerror(parser, "expected another variable");
3711 if (parser->tok != TOKEN_IDENT) {
3712 parseerror(parser, "expected another variable");
3715 var = ast_value_copy(basetype);
3717 ast_value_set_name(var, parser_tokval(parser));
3718 if (!parser_next(parser)) {
3719 parseerror(parser, "error parsing variable declaration");
3725 if (parser->tok != ';') {
3726 parseerror(parser, "missing semicolon after variables");
3730 if (!parser_next(parser)) {
3731 parseerror(parser, "parse error after variable declaration");
3735 ast_delete(basetype);
3739 if (cleanvar && var)
3741 ast_delete(basetype);
3745 ast_delete(basetype);
3746 if (cleanvar && var)
3748 if (me[0]) ast_member_delete(me[0]);
3749 if (me[1]) ast_member_delete(me[1]);
3750 if (me[2]) ast_member_delete(me[2]);
3754 static bool parser_global_statement(parser_t *parser)
3756 if (parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3758 return parse_variable(parser, NULL, false, false);
3760 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
3762 if (!strcmp(parser_tokval(parser), "var")) {
3763 if (!parser_next(parser)) {
3764 parseerror(parser, "expected variable declaration after 'var'");
3767 return parse_variable(parser, NULL, true, false);
3770 else if (parser->tok == TOKEN_KEYWORD)
3772 if (!strcmp(parser_tokval(parser), "const")) {
3773 if (!parser_next(parser)) {
3774 parseerror(parser, "expected variable declaration after 'const'");
3777 return parse_variable(parser, NULL, true, true);
3779 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
3782 else if (parser->tok == '$')
3784 if (!parser_next(parser)) {
3785 parseerror(parser, "parse error");
3791 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
3797 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
3799 return util_crc16(old, str, strlen(str));
3802 static void progdefs_crc_file(const char *str)
3804 /* write to progdefs.h here */
3808 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
3810 old = progdefs_crc_sum(old, str);
3811 progdefs_crc_file(str);
3815 static void generate_checksum(parser_t *parser)
3817 uint16_t crc = 0xFFFF;
3821 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
3822 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
3824 progdefs_crc_file("\tint\tpad;\n");
3825 progdefs_crc_file("\tint\tofs_return[3];\n");
3826 progdefs_crc_file("\tint\tofs_parm0[3];\n");
3827 progdefs_crc_file("\tint\tofs_parm1[3];\n");
3828 progdefs_crc_file("\tint\tofs_parm2[3];\n");
3829 progdefs_crc_file("\tint\tofs_parm3[3];\n");
3830 progdefs_crc_file("\tint\tofs_parm4[3];\n");
3831 progdefs_crc_file("\tint\tofs_parm5[3];\n");
3832 progdefs_crc_file("\tint\tofs_parm6[3];\n");
3833 progdefs_crc_file("\tint\tofs_parm7[3];\n");
3835 for (i = 0; i < parser->crc_globals; ++i) {
3836 if (!ast_istype(parser->globals[i], ast_value))
3838 value = (ast_value*)(parser->globals[i]);
3839 switch (value->expression.vtype) {
3840 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3841 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3842 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3843 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3845 crc = progdefs_crc_both(crc, "\tint\t");
3848 crc = progdefs_crc_both(crc, value->name);
3849 crc = progdefs_crc_both(crc, ";\n");
3851 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
3852 for (i = 0; i < parser->crc_fields; ++i) {
3853 if (!ast_istype(parser->fields[i], ast_value))
3855 value = (ast_value*)(parser->fields[i]);
3856 switch (value->expression.next->expression.vtype) {
3857 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
3858 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
3859 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
3860 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
3862 crc = progdefs_crc_both(crc, "\tint\t");
3865 crc = progdefs_crc_both(crc, value->name);
3866 crc = progdefs_crc_both(crc, ";\n");
3868 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
3873 static parser_t *parser;
3879 parser = (parser_t*)mem_a(sizeof(parser_t));
3883 memset(parser, 0, sizeof(*parser));
3885 for (i = 0; i < operator_count; ++i) {
3886 if (operators[i].id == opid1('=')) {
3887 parser->assign_op = operators+i;
3891 if (!parser->assign_op) {
3892 printf("internal error: initializing parser: failed to find assign operator\n");
3897 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
3898 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
3902 bool parser_compile()
3904 /* initial lexer/parser state */
3905 parser->lex->flags.noops = true;
3907 if (parser_next(parser))
3909 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3911 if (!parser_global_statement(parser)) {
3912 if (parser->tok == TOKEN_EOF)
3913 parseerror(parser, "unexpected eof");
3914 else if (!parser->errors)
3915 parseerror(parser, "there have been errors, bailing out");
3916 lex_close(parser->lex);
3922 parseerror(parser, "parse error");
3923 lex_close(parser->lex);
3928 lex_close(parser->lex);
3931 return !parser->errors;
3934 bool parser_compile_file(const char *filename)
3936 parser->lex = lex_open(filename);
3938 con_err("failed to open file \"%s\"\n", filename);
3941 return parser_compile();
3944 bool parser_compile_string_len(const char *name, const char *str, size_t len)
3946 parser->lex = lex_open_string(str, len, name);
3948 con_err("failed to create lexer for string \"%s\"\n", name);
3951 return parser_compile();
3954 bool parser_compile_string(const char *name, const char *str)
3956 parser->lex = lex_open_string(str, strlen(str), name);
3958 con_err("failed to create lexer for string \"%s\"\n", name);
3961 return parser_compile();
3964 void parser_cleanup()
3967 for (i = 0; i < vec_size(parser->accessors); ++i) {
3968 ast_delete(parser->accessors[i]->constval.vfunc);
3969 parser->accessors[i]->constval.vfunc = NULL;
3970 ast_delete(parser->accessors[i]);
3972 for (i = 0; i < vec_size(parser->functions); ++i) {
3973 ast_delete(parser->functions[i]);
3975 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
3976 ast_delete(parser->imm_vector[i]);
3978 for (i = 0; i < vec_size(parser->imm_string); ++i) {
3979 ast_delete(parser->imm_string[i]);
3981 for (i = 0; i < vec_size(parser->imm_float); ++i) {
3982 ast_delete(parser->imm_float[i]);
3984 for (i = 0; i < vec_size(parser->fields); ++i) {
3985 ast_delete(parser->fields[i]);
3987 for (i = 0; i < vec_size(parser->globals); ++i) {
3988 ast_delete(parser->globals[i]);
3990 vec_free(parser->accessors);
3991 vec_free(parser->functions);
3992 vec_free(parser->imm_vector);
3993 vec_free(parser->imm_string);
3994 vec_free(parser->imm_float);
3995 vec_free(parser->globals);
3996 vec_free(parser->fields);
3998 for (i = 0; i < vec_size(parser->variables); ++i)
3999 util_htdel(parser->variables[i]);
4000 vec_free(parser->variables);
4005 bool parser_finish(const char *output)
4011 if (!parser->errors)
4013 ir = ir_builder_new("gmqcc_out");
4015 con_out("failed to allocate builder\n");
4019 for (i = 0; i < vec_size(parser->fields); ++i) {
4022 if (!ast_istype(parser->fields[i], ast_value))
4024 field = (ast_value*)parser->fields[i];
4025 isconst = field->isconst;
4026 field->isconst = false;
4027 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4028 con_out("failed to generate field %s\n", field->name);
4029 ir_builder_delete(ir);
4034 ast_expression *subtype;
4035 field->isconst = true;
4036 subtype = field->expression.next;
4037 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4038 if (subtype->expression.vtype == TYPE_FIELD)
4039 ifld->fieldtype = subtype->expression.next->expression.vtype;
4040 else if (subtype->expression.vtype == TYPE_FUNCTION)
4041 ifld->outtype = subtype->expression.next->expression.vtype;
4042 (void)!ir_value_set_field(field->ir_v, ifld);
4045 for (i = 0; i < vec_size(parser->globals); ++i) {
4047 if (!ast_istype(parser->globals[i], ast_value))
4049 asvalue = (ast_value*)(parser->globals[i]);
4050 if (!asvalue->uses && !asvalue->isconst && asvalue->expression.vtype != TYPE_FUNCTION) {
4051 if (strcmp(asvalue->name, "end_sys_globals") &&
4052 strcmp(asvalue->name, "end_sys_fields"))
4054 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4055 "unused global: `%s`", asvalue->name);
4058 if (!ast_global_codegen(asvalue, ir, false)) {
4059 con_out("failed to generate global %s\n", asvalue->name);
4060 ir_builder_delete(ir);
4064 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4065 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4066 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4067 ir_builder_delete(ir);
4071 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4072 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4073 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4074 ir_builder_delete(ir);
4078 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4079 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4080 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4081 ir_builder_delete(ir);
4085 for (i = 0; i < vec_size(parser->globals); ++i) {
4087 if (!ast_istype(parser->globals[i], ast_value))
4089 asvalue = (ast_value*)(parser->globals[i]);
4090 if (asvalue->setter) {
4091 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4092 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4093 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4095 printf("failed to generate setter for %s\n", asvalue->name);
4096 ir_builder_delete(ir);
4100 if (asvalue->getter) {
4101 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4102 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4103 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4105 printf("failed to generate getter for %s\n", asvalue->name);
4106 ir_builder_delete(ir);
4111 for (i = 0; i < vec_size(parser->fields); ++i) {
4113 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4115 if (!ast_istype((ast_expression*)asvalue, ast_value))
4117 if (asvalue->expression.vtype != TYPE_ARRAY)
4119 if (asvalue->setter) {
4120 if (!ast_global_codegen(asvalue->setter, ir, false) ||
4121 !ast_function_codegen(asvalue->setter->constval.vfunc, ir) ||
4122 !ir_function_finalize(asvalue->setter->constval.vfunc->ir_func))
4124 printf("failed to generate setter for %s\n", asvalue->name);
4125 ir_builder_delete(ir);
4129 if (asvalue->getter) {
4130 if (!ast_global_codegen(asvalue->getter, ir, false) ||
4131 !ast_function_codegen(asvalue->getter->constval.vfunc, ir) ||
4132 !ir_function_finalize(asvalue->getter->constval.vfunc->ir_func))
4134 printf("failed to generate getter for %s\n", asvalue->name);
4135 ir_builder_delete(ir);
4140 for (i = 0; i < vec_size(parser->functions); ++i) {
4141 if (!ast_function_codegen(parser->functions[i], ir)) {
4142 con_out("failed to generate function %s\n", parser->functions[i]->name);
4143 ir_builder_delete(ir);
4148 ir_builder_dump(ir, con_out);
4149 for (i = 0; i < vec_size(parser->functions); ++i) {
4150 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4151 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4152 ir_builder_delete(ir);
4159 ir_builder_dump(ir, con_out);
4161 generate_checksum(parser);
4163 if (!ir_builder_generate(ir, output)) {
4164 con_out("*** failed to generate output file\n");
4165 ir_builder_delete(ir);
4170 ir_builder_delete(ir);
4174 con_out("*** there were compile errors\n");