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
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
59 ast_function *function;
61 /* All the labels the function defined...
62 * Should they be in ast_function instead?
67 /* A list of hashtables for each scope */
73 /* not to be used directly, we use the hash table */
74 ast_expression **_locals;
76 ast_value **_typedefs;
77 size_t *_blocktypedefs;
82 /* we store the '=' operator info */
83 const oper_info *assign_op;
85 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
86 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
87 * anything else: type error
91 /* Keep track of our ternary vs parenthesis nesting state.
92 * If we reach a 'comma' operator in a ternary without a paren,
93 * we shall trigger -Wternary-precedence.
95 enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
98 static void parser_enterblock(parser_t *parser);
99 static bool parser_leaveblock(parser_t *parser);
100 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
101 static bool parse_typedef(parser_t *parser);
102 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef);
103 static ast_block* parse_block(parser_t *parser);
104 static bool parse_block_into(parser_t *parser, ast_block *block);
105 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
106 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
107 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
108 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
110 static void parseerror(parser_t *parser, const char *fmt, ...)
117 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
121 /* returns true if it counts as an error */
122 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
125 int lvl = LVL_WARNING;
127 if (!OPTS_WARN(warntype))
136 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "warning", fmt, ap);
142 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
145 int lvl = LVL_WARNING;
147 if (!OPTS_WARN(warntype))
154 con_vprintmsg(lvl, ctx.file, ctx.line, "warning", fmt, ap);
160 /**********************************************************************
161 * some maths used for constant folding
164 vector vec3_add(vector a, vector b)
173 vector vec3_sub(vector a, vector b)
182 qcfloat vec3_mulvv(vector a, vector b)
184 return (a.x * b.x + a.y * b.y + a.z * b.z);
187 vector vec3_mulvf(vector a, float b)
196 /**********************************************************************
200 bool parser_next(parser_t *parser)
202 /* lex_do kills the previous token */
203 parser->tok = lex_do(parser->lex);
204 if (parser->tok == TOKEN_EOF)
206 if (parser->tok >= TOKEN_ERROR) {
207 parseerror(parser, "lex error");
213 #define parser_tokval(p) ((p)->lex->tok.value)
214 #define parser_token(p) (&((p)->lex->tok))
215 #define parser_ctx(p) ((p)->lex->tok.ctx)
217 static ast_value* parser_const_float(parser_t *parser, double d)
221 for (i = 0; i < vec_size(parser->imm_float); ++i) {
222 const double compare = parser->imm_float[i]->constval.vfloat;
223 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
224 return parser->imm_float[i];
226 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
228 out->hasvalue = true;
229 out->constval.vfloat = d;
230 vec_push(parser->imm_float, out);
234 static ast_value* parser_const_float_0(parser_t *parser)
236 if (!parser->imm_float_zero)
237 parser->imm_float_zero = parser_const_float(parser, 0);
238 return parser->imm_float_zero;
241 static ast_value* parser_const_float_1(parser_t *parser)
243 if (!parser->imm_float_one)
244 parser->imm_float_one = parser_const_float(parser, 1);
245 return parser->imm_float_one;
248 static char *parser_strdup(const char *str)
251 /* actually dup empty strings */
252 char *out = mem_a(1);
256 return util_strdup(str);
259 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
263 for (i = 0; i < vec_size(parser->imm_string); ++i) {
264 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
265 return parser->imm_string[i];
269 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
270 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
272 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
274 out->hasvalue = true;
275 out->constval.vstring = parser_strdup(str);
276 vec_push(parser->imm_string, out);
280 static ast_value* parser_const_vector(parser_t *parser, vector v)
284 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
285 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
286 return parser->imm_vector[i];
288 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
290 out->hasvalue = true;
291 out->constval.vvec = v;
292 vec_push(parser->imm_vector, out);
296 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
302 return parser_const_vector(parser, v);
305 static ast_value* parser_const_vector_0(parser_t *parser)
307 if (!parser->imm_vector_zero)
308 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
309 return parser->imm_vector_zero;
312 static ast_expression* parser_find_field(parser_t *parser, const char *name)
314 return util_htget(parser->htfields, name);
317 static ast_expression* parser_find_global(parser_t *parser, const char *name)
319 return util_htget(parser->htglobals, name);
322 static ast_expression* parser_find_param(parser_t *parser, const char *name)
326 if (!parser->function)
328 fun = parser->function->vtype;
329 for (i = 0; i < vec_size(fun->expression.params); ++i) {
330 if (!strcmp(fun->expression.params[i]->name, name))
331 return (ast_expression*)(fun->expression.params[i]);
336 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
341 hash = util_hthash(parser->htglobals, name);
344 for (i = vec_size(parser->variables); i > upto;) {
346 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
350 return parser_find_param(parser, name);
353 static ast_expression* parser_find_var(parser_t *parser, const char *name)
357 v = parser_find_local(parser, name, 0, &dummy);
358 if (!v) v = parser_find_global(parser, name);
362 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
366 hash = util_hthash(parser->typedefs[0], name);
368 for (i = vec_size(parser->typedefs); i > upto;) {
370 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
378 size_t etype; /* 0 = expression, others are operators */
382 ast_block *block; /* for commas and function calls */
391 #define SY_PAREN_EXPR '('
392 #define SY_PAREN_FUNC 'f'
393 #define SY_PAREN_INDEX '['
394 #define SY_PAREN_TERNARY '?'
396 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
407 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
411 e.out = (ast_expression*)v;
418 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
420 e.etype = 1 + (op - operators);
429 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
441 # define DEBUGSHUNTDO(x) x
443 # define DEBUGSHUNTDO(x)
446 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
447 * so we need to rotate it to become ent.(foo[n]).
449 static bool rotate_entfield_array_index_nodes(ast_expression **out)
451 ast_array_index *index;
452 ast_entfield *entfield;
456 ast_expression *entity;
458 lex_ctx ctx = ast_ctx(*out);
460 if (!ast_istype(*out, ast_array_index))
462 index = (ast_array_index*)*out;
464 if (!ast_istype(index->array, ast_entfield))
466 entfield = (ast_entfield*)index->array;
468 if (!ast_istype(entfield->field, ast_value))
470 field = (ast_value*)entfield->field;
473 entity = entfield->entity;
477 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
478 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
479 *out = (ast_expression*)entfield;
484 static bool parser_sy_pop(parser_t *parser, shunt *sy)
488 ast_expression *out = NULL;
489 ast_expression *exprs[3];
490 ast_block *blocks[3];
491 ast_value *asvalue[3];
492 ast_binstore *asbinstore;
493 size_t i, assignop, addop, subop;
494 qcint generated_op = 0;
499 if (!vec_size(sy->ops)) {
500 parseerror(parser, "internal error: missing operator");
504 if (vec_last(sy->ops).paren) {
505 parseerror(parser, "unmatched parenthesis");
509 op = &operators[vec_last(sy->ops).etype - 1];
510 ctx = vec_last(sy->ops).ctx;
512 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
514 if (vec_size(sy->out) < op->operands) {
515 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
516 op->op, (int)op->id);
520 vec_shrinkby(sy->ops, 1);
522 /* op(:?) has no input and no output */
526 vec_shrinkby(sy->out, op->operands);
527 for (i = 0; i < op->operands; ++i) {
528 exprs[i] = sy->out[vec_size(sy->out)+i].out;
529 blocks[i] = sy->out[vec_size(sy->out)+i].block;
530 asvalue[i] = (ast_value*)exprs[i];
533 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
534 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
538 #define NotSameType(T) \
539 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
540 exprs[0]->expression.vtype != T)
541 #define CanConstFold1(A) \
542 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST))
543 #define CanConstFold(A, B) \
544 (CanConstFold1(A) && CanConstFold1(B))
545 #define ConstV(i) (asvalue[(i)]->constval.vvec)
546 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
547 #define ConstS(i) (asvalue[(i)]->constval.vstring)
551 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
555 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
556 if (exprs[1]->expression.vtype != TYPE_FIELD) {
557 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
560 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
562 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
563 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
567 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
573 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
574 !(exprs[0]->expression.vtype == TYPE_FIELD &&
575 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
577 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
578 parseerror(parser, "cannot index value of type %s", ty1);
581 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
582 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
583 parseerror(parser, "index must be of type float, not %s", ty1);
586 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
587 if (rotate_entfield_array_index_nodes(&out))
590 /* This is not broken in fteqcc anymore */
591 if (opts_standard != COMPILER_GMQCC) {
592 /* this error doesn't need to make us bail out */
593 (void)!parsewarning(parser, WARN_EXTENSIONS,
594 "accessing array-field members of an entity without parenthesis\n"
595 " -> this is an extension from -std=gmqcc");
603 ast_block_add_expr(blocks[0], exprs[1]);
605 blocks[0] = ast_block_new(ctx);
606 ast_block_add_expr(blocks[0], exprs[0]);
607 ast_block_add_expr(blocks[0], exprs[1]);
609 if (!ast_block_set_type(blocks[0], exprs[1]))
612 vec_push(sy->out, syblock(ctx, blocks[0]));
619 switch (exprs[0]->expression.vtype) {
621 if (CanConstFold1(exprs[0]))
622 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
624 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
625 (ast_expression*)parser_const_float_0(parser),
629 if (CanConstFold1(exprs[0]))
630 out = (ast_expression*)parser_const_vector_f(parser,
631 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
633 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
634 (ast_expression*)parser_const_vector_0(parser),
638 parseerror(parser, "invalid types used in expression: cannot negate type %s",
639 type_name[exprs[0]->expression.vtype]);
645 switch (exprs[0]->expression.vtype) {
647 if (CanConstFold1(exprs[0]))
648 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
650 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
653 if (CanConstFold1(exprs[0]))
654 out = (ast_expression*)parser_const_float(parser,
655 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
657 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
660 if (CanConstFold1(exprs[0]))
661 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
663 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
665 /* we don't constant-fold NOT for these types */
667 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
670 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
673 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
674 type_name[exprs[0]->expression.vtype]);
680 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
681 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
683 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
684 type_name[exprs[0]->expression.vtype],
685 type_name[exprs[1]->expression.vtype]);
688 switch (exprs[0]->expression.vtype) {
690 if (CanConstFold(exprs[0], exprs[1]))
692 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
695 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
698 if (CanConstFold(exprs[0], exprs[1]))
699 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
701 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
704 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
705 type_name[exprs[0]->expression.vtype],
706 type_name[exprs[1]->expression.vtype]);
711 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
712 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
714 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
715 type_name[exprs[1]->expression.vtype],
716 type_name[exprs[0]->expression.vtype]);
719 switch (exprs[0]->expression.vtype) {
721 if (CanConstFold(exprs[0], exprs[1]))
722 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
727 if (CanConstFold(exprs[0], exprs[1]))
728 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
730 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
733 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
734 type_name[exprs[1]->expression.vtype],
735 type_name[exprs[0]->expression.vtype]);
740 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
741 exprs[0]->expression.vtype != TYPE_VECTOR &&
742 exprs[0]->expression.vtype != TYPE_FLOAT &&
743 exprs[1]->expression.vtype != TYPE_VECTOR &&
744 exprs[1]->expression.vtype != TYPE_FLOAT)
746 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
747 type_name[exprs[1]->expression.vtype],
748 type_name[exprs[0]->expression.vtype]);
751 switch (exprs[0]->expression.vtype) {
753 if (exprs[1]->expression.vtype == TYPE_VECTOR)
755 if (CanConstFold(exprs[0], exprs[1]))
756 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
758 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
762 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
765 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
769 if (exprs[1]->expression.vtype == TYPE_FLOAT)
771 if (CanConstFold(exprs[0], exprs[1]))
772 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
774 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
778 if (CanConstFold(exprs[0], exprs[1]))
779 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
781 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
785 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
786 type_name[exprs[1]->expression.vtype],
787 type_name[exprs[0]->expression.vtype]);
792 if (NotSameType(TYPE_FLOAT)) {
793 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
794 type_name[exprs[0]->expression.vtype],
795 type_name[exprs[1]->expression.vtype]);
798 if (CanConstFold(exprs[0], exprs[1]))
799 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
801 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
805 parseerror(parser, "qc does not have a modulo operator");
809 if (NotSameType(TYPE_FLOAT)) {
810 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
811 type_name[exprs[0]->expression.vtype],
812 type_name[exprs[1]->expression.vtype]);
815 if (CanConstFold(exprs[0], exprs[1]))
816 out = (ast_expression*)parser_const_float(parser,
817 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
818 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
820 out = (ast_expression*)ast_binary_new(ctx,
821 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
825 parseerror(parser, "TODO: bitxor");
830 case opid3('<','<','='):
831 case opid3('>','>','='):
832 parseerror(parser, "TODO: shifts");
836 generated_op += 1; /* INSTR_OR */
838 generated_op += INSTR_AND;
840 if (NotSameType(TYPE_FLOAT)) {
841 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
842 type_name[exprs[0]->expression.vtype],
843 type_name[exprs[1]->expression.vtype]);
844 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
845 parseerror(parser, "TODO: optional early out");
849 if (opts_standard == COMPILER_GMQCC)
850 con_out("TODO: early out logic\n");
851 if (CanConstFold(exprs[0], exprs[1]))
852 out = (ast_expression*)parser_const_float(parser,
853 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
855 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
859 if (vec_last(parser->pot) != POT_TERNARY2) {
860 parseerror(parser, "mismatched parenthesis/ternary");
863 vec_pop(parser->pot);
864 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
865 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
866 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
867 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
870 if (CanConstFold1(exprs[0]))
871 out = (ConstF(0) ? exprs[1] : exprs[2]);
873 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
877 generated_op += 1; /* INSTR_GT */
879 generated_op += 1; /* INSTR_LT */
880 case opid2('>', '='):
881 generated_op += 1; /* INSTR_GE */
882 case opid2('<', '='):
883 generated_op += INSTR_LE;
884 if (NotSameType(TYPE_FLOAT)) {
885 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
886 type_name[exprs[0]->expression.vtype],
887 type_name[exprs[1]->expression.vtype]);
890 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
892 case opid2('!', '='):
893 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
894 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
895 type_name[exprs[0]->expression.vtype],
896 type_name[exprs[1]->expression.vtype]);
899 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
901 case opid2('=', '='):
902 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
903 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
904 type_name[exprs[0]->expression.vtype],
905 type_name[exprs[1]->expression.vtype]);
908 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
912 if (ast_istype(exprs[0], ast_entfield)) {
913 ast_expression *field = ((ast_entfield*)exprs[0])->field;
914 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
915 exprs[0]->expression.vtype == TYPE_FIELD &&
916 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
918 assignop = type_storep_instr[TYPE_VECTOR];
921 assignop = type_storep_instr[exprs[0]->expression.vtype];
922 if (!ast_compare_type(field->expression.next, exprs[1])) {
923 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
924 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
926 field->expression.next->expression.vtype == TYPE_FUNCTION &&
927 exprs[1]->expression.vtype == TYPE_FUNCTION)
929 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
930 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
936 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
941 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
942 exprs[0]->expression.vtype == TYPE_FIELD &&
943 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
945 assignop = type_store_instr[TYPE_VECTOR];
948 assignop = type_store_instr[exprs[0]->expression.vtype];
951 if (assignop == AINSTR_END) {
952 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
956 else if (!ast_compare_type(exprs[0], exprs[1])) {
957 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
958 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
959 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
960 exprs[0]->expression.vtype == TYPE_FUNCTION &&
961 exprs[1]->expression.vtype == TYPE_FUNCTION)
963 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
964 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
970 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
973 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
974 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
976 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
978 case opid3('+','+','P'):
979 case opid3('-','-','P'):
981 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
982 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
983 parseerror(parser, "invalid type for prefix increment: %s", ty1);
986 if (op->id == opid3('+','+','P'))
990 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
991 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
993 if (ast_istype(exprs[0], ast_entfield)) {
994 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
996 (ast_expression*)parser_const_float_1(parser));
998 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1000 (ast_expression*)parser_const_float_1(parser));
1003 case opid3('S','+','+'):
1004 case opid3('S','-','-'):
1006 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1007 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1008 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1011 if (op->id == opid3('S','+','+')) {
1012 addop = INSTR_ADD_F;
1013 subop = INSTR_SUB_F;
1015 addop = INSTR_SUB_F;
1016 subop = INSTR_ADD_F;
1018 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1019 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1021 if (ast_istype(exprs[0], ast_entfield)) {
1022 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1024 (ast_expression*)parser_const_float_1(parser));
1026 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1028 (ast_expression*)parser_const_float_1(parser));
1032 out = (ast_expression*)ast_binary_new(ctx, subop,
1034 (ast_expression*)parser_const_float_1(parser));
1036 case opid2('+','='):
1037 case opid2('-','='):
1038 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1039 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1041 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1042 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1043 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1047 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1048 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1050 if (ast_istype(exprs[0], ast_entfield))
1051 assignop = type_storep_instr[exprs[0]->expression.vtype];
1053 assignop = type_store_instr[exprs[0]->expression.vtype];
1054 switch (exprs[0]->expression.vtype) {
1056 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1057 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1058 exprs[0], exprs[1]);
1061 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1062 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1063 exprs[0], exprs[1]);
1066 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1067 type_name[exprs[0]->expression.vtype],
1068 type_name[exprs[1]->expression.vtype]);
1072 case opid2('*','='):
1073 case opid2('/','='):
1074 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1075 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1076 exprs[0]->expression.vtype == TYPE_VECTOR))
1078 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1079 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080 parseerror(parser, "invalid types used in expression: %s and %s",
1084 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1085 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1087 if (ast_istype(exprs[0], ast_entfield))
1088 assignop = type_storep_instr[exprs[0]->expression.vtype];
1090 assignop = type_store_instr[exprs[0]->expression.vtype];
1091 switch (exprs[0]->expression.vtype) {
1093 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1094 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1095 exprs[0], exprs[1]);
1098 if (op->id == opid2('*','=')) {
1099 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1100 exprs[0], exprs[1]);
1102 /* there's no DIV_VF */
1103 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1104 (ast_expression*)parser_const_float_1(parser),
1108 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1113 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1114 type_name[exprs[0]->expression.vtype],
1115 type_name[exprs[1]->expression.vtype]);
1119 case opid2('&','='):
1120 case opid2('|','='):
1121 if (NotSameType(TYPE_FLOAT)) {
1122 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124 parseerror(parser, "invalid types used in expression: %s and %s",
1128 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1129 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1131 if (ast_istype(exprs[0], ast_entfield))
1132 assignop = type_storep_instr[exprs[0]->expression.vtype];
1134 assignop = type_store_instr[exprs[0]->expression.vtype];
1135 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1136 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1137 exprs[0], exprs[1]);
1139 case opid3('&','~','='):
1140 /* This is like: a &= ~(b);
1141 * But QC has no bitwise-not, so we implement it as
1144 if (NotSameType(TYPE_FLOAT)) {
1145 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1146 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1147 parseerror(parser, "invalid types used in expression: %s and %s",
1151 if (ast_istype(exprs[0], ast_entfield))
1152 assignop = type_storep_instr[exprs[0]->expression.vtype];
1154 assignop = type_store_instr[exprs[0]->expression.vtype];
1155 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1158 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1159 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1161 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1162 asbinstore->keep_dest = true;
1163 out = (ast_expression*)asbinstore;
1169 parseerror(parser, "failed to apply operand %s", op->op);
1173 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1174 vec_push(sy->out, syexp(ctx, out));
1178 static bool parser_close_call(parser_t *parser, shunt *sy)
1180 /* was a function call */
1181 ast_expression *fun;
1187 vec_shrinkby(sy->ops, 1);
1188 fid = sy->ops[vec_size(sy->ops)].off;
1190 /* out[fid] is the function
1191 * everything above is parameters...
1192 * 0 params = nothing
1193 * 1 params = ast_expression
1197 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1198 parseerror(parser, "internal error: function call needs function and parameter list...");
1202 fun = sy->out[fid].out;
1204 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1206 parseerror(parser, "out of memory");
1210 if (fid+1 == vec_size(sy->out)) {
1213 } else if (fid+2 == vec_size(sy->out)) {
1215 vec_shrinkby(sy->out, 1);
1216 params = sy->out[vec_size(sy->out)].block;
1220 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1222 paramcount = vec_size(params->exprs);
1223 call->params = params->exprs;
1224 params->exprs = NULL;
1227 if (!ast_call_check_types(call))
1230 parseerror(parser, "invalid function call");
1234 /* overwrite fid, the function, with a call */
1235 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1237 if (fun->expression.vtype != TYPE_FUNCTION) {
1238 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1242 if (!fun->expression.next) {
1243 parseerror(parser, "could not determine function return type");
1246 if (vec_size(fun->expression.params) != paramcount &&
1247 !(fun->expression.variadic &&
1248 vec_size(fun->expression.params) < paramcount))
1251 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1253 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1254 if (opts_standard == COMPILER_GMQCC)
1257 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1258 " -> `%s` has been declared here: %s:%i",
1259 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1260 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1262 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1263 " -> `%s` has been declared here: %s:%i",
1264 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1265 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1271 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1272 "too %s parameters for call to %s: expected %i, got %i\n"
1273 " -> `%s` has been declared here: %s:%i",
1274 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1275 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1277 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1278 "too %s parameters for function call: expected %i, got %i\n"
1279 " -> `%s` has been declared here: %s:%i",
1280 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1281 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1289 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1291 if (!vec_size(sy->ops)) {
1292 parseerror(parser, "unmatched closing paren");
1295 /* this would for bit a + (x) because there are no operators inside (x)
1296 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1297 parseerror(parser, "empty parenthesis expression");
1301 while (vec_size(sy->ops)) {
1302 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1303 if (!parser_close_call(parser, sy))
1307 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1308 vec_shrinkby(sy->ops, 1);
1309 return !functions_only;
1311 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1314 /* pop off the parenthesis */
1315 vec_shrinkby(sy->ops, 1);
1316 /* then apply the index operator */
1317 if (!parser_sy_pop(parser, sy))
1321 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1324 if (vec_last(parser->pot) != POT_TERNARY1) {
1325 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1328 vec_last(parser->pot) = POT_TERNARY2;
1329 /* pop off the parenthesis */
1330 vec_shrinkby(sy->ops, 1);
1333 if (!parser_sy_pop(parser, sy))
1339 static void parser_reclassify_token(parser_t *parser)
1342 for (i = 0; i < operator_count; ++i) {
1343 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1344 parser->tok = TOKEN_OPERATOR;
1350 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1352 ast_expression *expr = NULL;
1354 bool wantop = false;
1355 bool gotmemberof = false;
1357 /* count the parens because an if starts with one, so the
1358 * end of a condition is an unmatched closing paren
1366 parser->lex->flags.noops = false;
1368 parser_reclassify_token(parser);
1373 gotmemberof = false;
1375 parser->memberof = 0;
1377 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1378 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1380 /* a translatable string */
1384 parseerror(parser, "expected operator or end of statement, got constant");
1388 parser->lex->flags.noops = true;
1389 if (!parser_next(parser) || parser->tok != '(') {
1390 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1393 parser->lex->flags.noops = false;
1394 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1395 parseerror(parser, "expected a constant string in translatable-string extension");
1398 val = parser_const_string(parser, parser_tokval(parser), true);
1402 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1403 DEBUGSHUNTDO(con_out("push string\n"));
1405 if (!parser_next(parser) || parser->tok != ')') {
1406 parseerror(parser, "expected closing paren after translatable string");
1410 else if (parser->tok == TOKEN_IDENT)
1412 ast_expression *var;
1414 parseerror(parser, "expected operator or end of statement");
1419 if (opts_standard == COMPILER_GMQCC)
1421 if (parser->memberof == TYPE_ENTITY) {
1422 /* still get vars first since there could be a fieldpointer */
1423 var = parser_find_var(parser, parser_tokval(parser));
1425 var = parser_find_field(parser, parser_tokval(parser));
1427 else if (parser->memberof == TYPE_VECTOR)
1429 parseerror(parser, "TODO: implement effective vector member access");
1432 else if (parser->memberof) {
1433 parseerror(parser, "namespace for member not found");
1437 var = parser_find_var(parser, parser_tokval(parser));
1439 var = parser_find_var(parser, parser_tokval(parser));
1441 var = parser_find_field(parser, parser_tokval(parser));
1444 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1447 if (ast_istype(var, ast_value)) {
1448 ((ast_value*)var)->uses++;
1450 else if (ast_istype(var, ast_member)) {
1451 ast_member *mem = (ast_member*)var;
1452 if (ast_istype(mem->owner, ast_value))
1453 ((ast_value*)(mem->owner))->uses++;
1455 vec_push(sy.out, syexp(parser_ctx(parser), var));
1456 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1458 else if (parser->tok == TOKEN_FLOATCONST) {
1461 parseerror(parser, "expected operator or end of statement, got constant");
1465 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1468 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1469 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1471 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1474 parseerror(parser, "expected operator or end of statement, got constant");
1478 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1481 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1482 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1484 else if (parser->tok == TOKEN_STRINGCONST) {
1487 parseerror(parser, "expected operator or end of statement, got constant");
1491 val = parser_const_string(parser, parser_tokval(parser), false);
1494 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1495 DEBUGSHUNTDO(con_out("push string\n"));
1497 else if (parser->tok == TOKEN_VECTORCONST) {
1500 parseerror(parser, "expected operator or end of statement, got constant");
1504 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1507 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1508 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1509 parser_token(parser)->constval.v.x,
1510 parser_token(parser)->constval.v.y,
1511 parser_token(parser)->constval.v.z));
1513 else if (parser->tok == '(') {
1514 parseerror(parser, "internal error: '(' should be classified as operator");
1517 else if (parser->tok == '[') {
1518 parseerror(parser, "internal error: '[' should be classified as operator");
1521 else if (parser->tok == ')') {
1523 DEBUGSHUNTDO(con_out("do[op] )\n"));
1527 /* we do expect an operator next */
1528 /* closing an opening paren */
1529 if (!parser_close_paren(parser, &sy, false))
1531 if (vec_last(parser->pot) != POT_PAREN) {
1532 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1535 vec_pop(parser->pot);
1537 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1541 /* allowed for function calls */
1542 if (!parser_close_paren(parser, &sy, true))
1544 if (vec_last(parser->pot) != POT_PAREN) {
1545 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1548 vec_pop(parser->pot);
1552 else if (parser->tok == ']') {
1554 parseerror(parser, "operand expected");
1558 if (!parser_close_paren(parser, &sy, false))
1560 if (vec_last(parser->pot) != POT_PAREN) {
1561 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1564 vec_pop(parser->pot);
1567 else if (parser->tok != TOKEN_OPERATOR) {
1569 parseerror(parser, "expected operator or end of statement");
1576 /* classify the operator */
1577 const oper_info *op;
1578 const oper_info *olast = NULL;
1580 for (o = 0; o < operator_count; ++o) {
1581 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1582 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1583 !strcmp(parser_tokval(parser), operators[o].op))
1588 if (o == operator_count) {
1589 /* no operator found... must be the end of the statement */
1592 /* found an operator */
1595 /* when declaring variables, a comma starts a new variable */
1596 if (op->id == opid1(',') && !parens && stopatcomma) {
1597 /* fixup the token */
1602 /* a colon without a pervious question mark cannot be a ternary */
1603 if (!ternaries && op->id == opid2(':','?')) {
1608 if (op->id == opid1(',')) {
1609 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1610 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1614 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1615 olast = &operators[vec_last(sy.ops).etype-1];
1618 (op->prec < olast->prec) ||
1619 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1621 if (!parser_sy_pop(parser, &sy))
1623 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1624 olast = &operators[vec_last(sy.ops).etype-1];
1629 if (op->id == opid1('.') && opts_standard == COMPILER_GMQCC) {
1630 /* for gmqcc standard: open up the namespace of the previous type */
1631 ast_expression *prevex = vec_last(sy.out).out;
1633 parseerror(parser, "unexpected member operator");
1636 if (prevex->expression.vtype == TYPE_ENTITY)
1637 parser->memberof = TYPE_ENTITY;
1638 else if (prevex->expression.vtype == TYPE_VECTOR)
1639 parser->memberof = TYPE_VECTOR;
1641 parseerror(parser, "type error: type has no members");
1647 if (op->id == opid1('(')) {
1649 size_t sycount = vec_size(sy.out);
1650 DEBUGSHUNTDO(con_out("push [op] (\n"));
1651 ++parens; vec_push(parser->pot, POT_PAREN);
1652 /* we expected an operator, this is the function-call operator */
1653 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1655 ++parens; vec_push(parser->pot, POT_PAREN);
1656 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1657 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1660 } else if (op->id == opid1('[')) {
1662 parseerror(parser, "unexpected array subscript");
1665 ++parens; vec_push(parser->pot, POT_PAREN);
1666 /* push both the operator and the paren, this makes life easier */
1667 vec_push(sy.ops, syop(parser_ctx(parser), op));
1668 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1670 } else if (op->id == opid2('?',':')) {
1672 vec_push(sy.ops, syop(parser_ctx(parser), op));
1673 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1676 vec_push(parser->pot, POT_TERNARY1);
1677 } else if (op->id == opid2(':','?')) {
1678 if (!vec_size(parser->pot)) {
1679 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1682 if (vec_last(parser->pot) != POT_TERNARY1) {
1683 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1686 if (!parser_close_paren(parser, &sy, false))
1688 vec_push(sy.ops, syop(parser_ctx(parser), op));
1692 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1693 vec_push(sy.ops, syop(parser_ctx(parser), op));
1694 wantop = !!(op->flags & OP_SUFFIX);
1697 if (!parser_next(parser)) {
1700 if (parser->tok == ';' ||
1701 (!parens && parser->tok == ']'))
1707 while (vec_size(sy.ops)) {
1708 if (!parser_sy_pop(parser, &sy))
1712 parser->lex->flags.noops = true;
1713 if (!vec_size(sy.out)) {
1714 parseerror(parser, "empty expression");
1717 expr = sy.out[0].out;
1720 DEBUGSHUNTDO(con_out("shunt done\n"));
1721 if (vec_size(parser->pot)) {
1722 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1725 vec_free(parser->pot);
1729 parser->lex->flags.noops = true;
1735 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1737 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1740 if (!parser_next(parser)) {
1747 static void parser_enterblock(parser_t *parser)
1749 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1750 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1751 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1752 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1753 vec_push(parser->_block_ctx, parser_ctx(parser));
1756 static bool parser_leaveblock(parser_t *parser)
1759 size_t locals, typedefs;
1761 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1762 parseerror(parser, "internal error: parser_leaveblock with no block");
1766 util_htdel(vec_last(parser->variables));
1767 vec_pop(parser->variables);
1768 if (!vec_size(parser->_blocklocals)) {
1769 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1773 locals = vec_last(parser->_blocklocals);
1774 vec_pop(parser->_blocklocals);
1775 while (vec_size(parser->_locals) != locals) {
1776 ast_expression *e = vec_last(parser->_locals);
1777 ast_value *v = (ast_value*)e;
1778 vec_pop(parser->_locals);
1779 if (ast_istype(e, ast_value) && !v->uses) {
1780 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1787 typedefs = vec_last(parser->_blocktypedefs);
1788 while (vec_size(parser->_typedefs) != typedefs) {
1789 ast_delete(vec_last(parser->_typedefs));
1790 vec_pop(parser->_typedefs);
1792 util_htdel(vec_last(parser->typedefs));
1793 vec_pop(parser->typedefs);
1795 vec_pop(parser->_block_ctx);
1799 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1801 vec_push(parser->_locals, e);
1802 util_htset(vec_last(parser->variables), name, (void*)e);
1805 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1808 ast_expression *cond, *ontrue, *onfalse = NULL;
1811 lex_ctx ctx = parser_ctx(parser);
1813 (void)block; /* not touching */
1815 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1816 if (!parser_next(parser)) {
1817 parseerror(parser, "expected condition or 'not'");
1820 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1822 if (!parser_next(parser)) {
1823 parseerror(parser, "expected condition in parenthesis");
1827 if (parser->tok != '(') {
1828 parseerror(parser, "expected 'if' condition in parenthesis");
1831 /* parse into the expression */
1832 if (!parser_next(parser)) {
1833 parseerror(parser, "expected 'if' condition after opening paren");
1836 /* parse the condition */
1837 cond = parse_expression_leave(parser, false);
1841 if (parser->tok != ')') {
1842 parseerror(parser, "expected closing paren after 'if' condition");
1846 /* parse into the 'then' branch */
1847 if (!parser_next(parser)) {
1848 parseerror(parser, "expected statement for on-true branch of 'if'");
1852 if (!parse_statement_or_block(parser, &ontrue)) {
1856 /* check for an else */
1857 if (!strcmp(parser_tokval(parser), "else")) {
1858 /* parse into the 'else' branch */
1859 if (!parser_next(parser)) {
1860 parseerror(parser, "expected on-false branch after 'else'");
1865 if (!parse_statement_or_block(parser, &onfalse)) {
1873 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1875 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1876 *out = (ast_expression*)ifthen;
1880 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1883 ast_expression *cond, *ontrue;
1885 lex_ctx ctx = parser_ctx(parser);
1887 (void)block; /* not touching */
1889 /* skip the 'while' and check for opening paren */
1890 if (!parser_next(parser) || parser->tok != '(') {
1891 parseerror(parser, "expected 'while' condition in parenthesis");
1894 /* parse into the expression */
1895 if (!parser_next(parser)) {
1896 parseerror(parser, "expected 'while' condition after opening paren");
1899 /* parse the condition */
1900 cond = parse_expression_leave(parser, false);
1904 if (parser->tok != ')') {
1905 parseerror(parser, "expected closing paren after 'while' condition");
1909 /* parse into the 'then' branch */
1910 if (!parser_next(parser)) {
1911 parseerror(parser, "expected while-loop body");
1915 if (!parse_statement_or_block(parser, &ontrue)) {
1920 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1921 *out = (ast_expression*)aloop;
1925 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1928 ast_expression *cond, *ontrue;
1930 lex_ctx ctx = parser_ctx(parser);
1932 (void)block; /* not touching */
1934 /* skip the 'do' and get the body */
1935 if (!parser_next(parser)) {
1936 parseerror(parser, "expected loop body");
1939 if (!parse_statement_or_block(parser, &ontrue))
1942 /* expect the "while" */
1943 if (parser->tok != TOKEN_KEYWORD ||
1944 strcmp(parser_tokval(parser), "while"))
1946 parseerror(parser, "expected 'while' and condition");
1951 /* skip the 'while' and check for opening paren */
1952 if (!parser_next(parser) || parser->tok != '(') {
1953 parseerror(parser, "expected 'while' condition in parenthesis");
1957 /* parse into the expression */
1958 if (!parser_next(parser)) {
1959 parseerror(parser, "expected 'while' condition after opening paren");
1963 /* parse the condition */
1964 cond = parse_expression_leave(parser, false);
1968 if (parser->tok != ')') {
1969 parseerror(parser, "expected closing paren after 'while' condition");
1975 if (!parser_next(parser) || parser->tok != ';') {
1976 parseerror(parser, "expected semicolon after condition");
1982 if (!parser_next(parser)) {
1983 parseerror(parser, "parse error");
1989 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1990 *out = (ast_expression*)aloop;
1994 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1997 ast_expression *initexpr, *cond, *increment, *ontrue;
2001 lex_ctx ctx = parser_ctx(parser);
2003 parser_enterblock(parser);
2010 /* skip the 'while' and check for opening paren */
2011 if (!parser_next(parser) || parser->tok != '(') {
2012 parseerror(parser, "expected 'for' expressions in parenthesis");
2015 /* parse into the expression */
2016 if (!parser_next(parser)) {
2017 parseerror(parser, "expected 'for' initializer after opening paren");
2022 if (parser->tok == TOKEN_IDENT)
2023 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2025 if (typevar || parser->tok == TOKEN_TYPENAME) {
2026 if (opts_standard != COMPILER_GMQCC) {
2027 if (parsewarning(parser, WARN_EXTENSIONS,
2028 "current standard does not allow variable declarations in for-loop initializers"))
2031 if (!parse_variable(parser, block, true, CV_VAR, typevar))
2034 else if (parser->tok != ';')
2036 initexpr = parse_expression_leave(parser, false);
2041 /* move on to condition */
2042 if (parser->tok != ';') {
2043 parseerror(parser, "expected semicolon after for-loop initializer");
2046 if (!parser_next(parser)) {
2047 parseerror(parser, "expected for-loop condition");
2051 /* parse the condition */
2052 if (parser->tok != ';') {
2053 cond = parse_expression_leave(parser, false);
2058 /* move on to incrementor */
2059 if (parser->tok != ';') {
2060 parseerror(parser, "expected semicolon after for-loop initializer");
2063 if (!parser_next(parser)) {
2064 parseerror(parser, "expected for-loop condition");
2068 /* parse the incrementor */
2069 if (parser->tok != ')') {
2070 increment = parse_expression_leave(parser, false);
2073 if (!ast_side_effects(increment)) {
2074 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2080 if (parser->tok != ')') {
2081 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2084 /* parse into the 'then' branch */
2085 if (!parser_next(parser)) {
2086 parseerror(parser, "expected for-loop body");
2089 if (!parse_statement_or_block(parser, &ontrue))
2092 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2093 *out = (ast_expression*)aloop;
2095 if (!parser_leaveblock(parser))
2099 if (initexpr) ast_delete(initexpr);
2100 if (cond) ast_delete(cond);
2101 if (increment) ast_delete(increment);
2102 (void)!parser_leaveblock(parser);
2106 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2108 ast_expression *exp = NULL;
2109 ast_return *ret = NULL;
2110 ast_value *expected = parser->function->vtype;
2112 lex_ctx ctx = parser_ctx(parser);
2114 (void)block; /* not touching */
2116 if (!parser_next(parser)) {
2117 parseerror(parser, "expected return expression");
2121 if (parser->tok != ';') {
2122 exp = parse_expression(parser, false);
2126 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2127 parseerror(parser, "return with invalid expression");
2130 ret = ast_return_new(exp->expression.node.context, exp);
2136 if (!parser_next(parser))
2137 parseerror(parser, "parse error");
2138 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2139 if (opts_standard != COMPILER_GMQCC)
2140 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2142 parseerror(parser, "return without value");
2144 ret = ast_return_new(ctx, NULL);
2146 *out = (ast_expression*)ret;
2150 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2152 lex_ctx ctx = parser_ctx(parser);
2154 (void)block; /* not touching */
2156 if (!parser_next(parser) || parser->tok != ';') {
2157 parseerror(parser, "expected semicolon");
2161 if (!parser_next(parser))
2162 parseerror(parser, "parse error");
2164 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2168 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2170 ast_expression *operand;
2173 ast_switch *switchnode;
2174 ast_switch_case swcase;
2176 lex_ctx ctx = parser_ctx(parser);
2178 (void)block; /* not touching */
2181 /* parse over the opening paren */
2182 if (!parser_next(parser) || parser->tok != '(') {
2183 parseerror(parser, "expected switch operand in parenthesis");
2187 /* parse into the expression */
2188 if (!parser_next(parser)) {
2189 parseerror(parser, "expected switch operand");
2192 /* parse the operand */
2193 operand = parse_expression_leave(parser, false);
2197 switchnode = ast_switch_new(ctx, operand);
2200 if (parser->tok != ')') {
2201 ast_delete(switchnode);
2202 parseerror(parser, "expected closing paren after 'switch' operand");
2206 /* parse over the opening paren */
2207 if (!parser_next(parser) || parser->tok != '{') {
2208 ast_delete(switchnode);
2209 parseerror(parser, "expected list of cases");
2213 if (!parser_next(parser)) {
2214 ast_delete(switchnode);
2215 parseerror(parser, "expected 'case' or 'default'");
2219 /* new block; allow some variables to be declared here */
2220 parser_enterblock(parser);
2223 if (parser->tok == TOKEN_IDENT)
2224 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2225 if (typevar || parser->tok == TOKEN_TYPENAME) {
2226 if (!parse_variable(parser, block, false, CV_NONE, typevar)) {
2227 ast_delete(switchnode);
2232 if (!strcmp(parser_tokval(parser), "var") ||
2233 !strcmp(parser_tokval(parser), "local"))
2235 if (!parser_next(parser)) {
2236 parseerror(parser, "expected variable declaration");
2237 ast_delete(switchnode);
2240 if (!parse_variable(parser, block, false, CV_VAR, NULL)) {
2241 ast_delete(switchnode);
2246 if (!strcmp(parser_tokval(parser), "const")) {
2247 if (!parser_next(parser)) {
2248 parseerror(parser, "expected variable declaration");
2249 ast_delete(switchnode);
2252 if (!strcmp(parser_tokval(parser), "var")) {
2253 if (!parser_next(parser)) {
2254 parseerror(parser, "expected variable declaration");
2255 ast_delete(switchnode);
2259 if (!parse_variable(parser, block, false, CV_CONST, NULL)) {
2260 ast_delete(switchnode);
2269 while (parser->tok != '}') {
2270 ast_block *caseblock;
2272 if (parser->tok != TOKEN_KEYWORD) {
2273 ast_delete(switchnode);
2274 parseerror(parser, "expected 'case' or 'default'");
2277 if (!strcmp(parser_tokval(parser), "case")) {
2278 if (!parser_next(parser)) {
2279 ast_delete(switchnode);
2280 parseerror(parser, "expected expression for case");
2283 swcase.value = parse_expression_leave(parser, false);
2284 if (!swcase.value) {
2285 ast_delete(switchnode);
2286 parseerror(parser, "expected expression for case");
2289 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2290 opval = (ast_value*)swcase.value;
2291 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2292 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2298 else if (!strcmp(parser_tokval(parser), "default")) {
2299 swcase.value = NULL;
2300 if (!parser_next(parser)) {
2301 ast_delete(switchnode);
2302 parseerror(parser, "expected colon");
2307 /* Now the colon and body */
2308 if (parser->tok != ':') {
2309 if (swcase.value) ast_unref(swcase.value);
2310 ast_delete(switchnode);
2311 parseerror(parser, "expected colon");
2315 if (!parser_next(parser)) {
2316 if (swcase.value) ast_unref(swcase.value);
2317 ast_delete(switchnode);
2318 parseerror(parser, "expected statements or case");
2321 caseblock = ast_block_new(parser_ctx(parser));
2323 if (swcase.value) ast_unref(swcase.value);
2324 ast_delete(switchnode);
2327 swcase.code = (ast_expression*)caseblock;
2328 vec_push(switchnode->cases, swcase);
2330 ast_expression *expr;
2331 if (parser->tok == '}')
2333 if (parser->tok == TOKEN_KEYWORD) {
2334 if (!strcmp(parser_tokval(parser), "case") ||
2335 !strcmp(parser_tokval(parser), "default"))
2340 if (!parse_statement(parser, caseblock, &expr, true)) {
2341 ast_delete(switchnode);
2346 ast_block_add_expr(caseblock, expr);
2350 parser_leaveblock(parser);
2353 if (parser->tok != '}') {
2354 ast_delete(switchnode);
2355 parseerror(parser, "expected closing paren of case list");
2358 if (!parser_next(parser)) {
2359 ast_delete(switchnode);
2360 parseerror(parser, "parse error after switch");
2363 *out = (ast_expression*)switchnode;
2367 static bool parse_goto(parser_t *parser, ast_expression **out)
2372 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2373 parseerror(parser, "expected label name after `goto`");
2377 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2379 for (i = 0; i < vec_size(parser->labels); ++i) {
2380 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2381 ast_goto_set_label(gt, parser->labels[i]);
2385 if (i == vec_size(parser->labels))
2386 vec_push(parser->gotos, gt);
2388 if (!parser_next(parser) || parser->tok != ';') {
2389 parseerror(parser, "semicolon expected after goto label");
2392 if (!parser_next(parser)) {
2393 parseerror(parser, "parse error after goto");
2397 *out = (ast_expression*)gt;
2401 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2404 ast_value *typevar = NULL;
2407 if (parser->tok == TOKEN_IDENT)
2408 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2410 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2412 /* local variable */
2414 parseerror(parser, "cannot declare a variable from here");
2417 if (opts_standard == COMPILER_QCC) {
2418 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2421 if (!parse_variable(parser, block, false, CV_NONE, typevar))
2426 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
2430 else if (parser->tok == TOKEN_KEYWORD)
2432 if (!strcmp(parser_tokval(parser), "local") ||
2433 !strcmp(parser_tokval(parser), "const") ||
2434 !strcmp(parser_tokval(parser), "var"))
2437 if (parser_tokval(parser)[0] == 'c')
2439 else if (parser_tokval(parser)[0] == 'v')
2445 parseerror(parser, "cannot declare a local variable here");
2448 if (!parser_next(parser)) {
2449 parseerror(parser, "expected variable declaration");
2452 if (!parse_variable(parser, block, true, cvq, NULL))
2457 else if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2462 if (!parser_next(parser)) {
2463 parseerror(parser, "parse error after __builtin_debug_printtype");
2467 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2469 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2470 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2471 if (!parser_next(parser)) {
2472 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2478 if (!parse_statement(parser, block, out, allow_cases))
2481 con_out("__builtin_debug_printtype: got no output node\n");
2484 ast_type_to_string(*out, ty, sizeof(ty));
2485 con_out("__builtin_debug_printtype: `%s`\n", ty);
2490 else if (!strcmp(parser_tokval(parser), "return"))
2492 return parse_return(parser, block, out);
2494 else if (!strcmp(parser_tokval(parser), "if"))
2496 return parse_if(parser, block, out);
2498 else if (!strcmp(parser_tokval(parser), "while"))
2500 return parse_while(parser, block, out);
2502 else if (!strcmp(parser_tokval(parser), "do"))
2504 return parse_dowhile(parser, block, out);
2506 else if (!strcmp(parser_tokval(parser), "for"))
2508 if (opts_standard == COMPILER_QCC) {
2509 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2512 return parse_for(parser, block, out);
2514 else if (!strcmp(parser_tokval(parser), "break"))
2516 return parse_break_continue(parser, block, out, false);
2518 else if (!strcmp(parser_tokval(parser), "continue"))
2520 return parse_break_continue(parser, block, out, true);
2522 else if (!strcmp(parser_tokval(parser), "switch"))
2524 return parse_switch(parser, block, out);
2526 else if (!strcmp(parser_tokval(parser), "case") ||
2527 !strcmp(parser_tokval(parser), "default"))
2530 parseerror(parser, "unexpected 'case' label");
2535 else if (!strcmp(parser_tokval(parser), "goto"))
2537 return parse_goto(parser, out);
2539 else if (!strcmp(parser_tokval(parser), "typedef"))
2541 if (!parser_next(parser)) {
2542 parseerror(parser, "expected type definition after 'typedef'");
2545 return parse_typedef(parser);
2547 parseerror(parser, "Unexpected keyword");
2550 else if (parser->tok == '{')
2553 inner = parse_block(parser);
2556 *out = (ast_expression*)inner;
2559 else if (parser->tok == ':')
2563 if (!parser_next(parser)) {
2564 parseerror(parser, "expected label name");
2567 if (parser->tok != TOKEN_IDENT) {
2568 parseerror(parser, "label must be an identifier");
2571 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2574 vec_push(parser->labels, label);
2575 *out = (ast_expression*)label;
2576 if (!parser_next(parser)) {
2577 parseerror(parser, "parse error after label");
2580 for (i = 0; i < vec_size(parser->gotos); ++i) {
2581 if (!strcmp(parser->gotos[i]->name, label->name)) {
2582 ast_goto_set_label(parser->gotos[i], label);
2583 vec_remove(parser->gotos, i, 1);
2589 else if (parser->tok == ';')
2591 if (!parser_next(parser)) {
2592 parseerror(parser, "parse error after empty statement");
2599 ast_expression *exp = parse_expression(parser, false);
2603 if (!ast_side_effects(exp)) {
2604 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2611 static bool parse_block_into(parser_t *parser, ast_block *block)
2615 parser_enterblock(parser);
2617 if (!parser_next(parser)) { /* skip the '{' */
2618 parseerror(parser, "expected function body");
2622 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2624 ast_expression *expr = NULL;
2625 if (parser->tok == '}')
2628 if (!parse_statement(parser, block, &expr, false)) {
2629 /* parseerror(parser, "parse error"); */
2635 ast_block_add_expr(block, expr);
2638 if (parser->tok != '}') {
2641 (void)parser_next(parser);
2645 if (!parser_leaveblock(parser))
2647 return retval && !!block;
2650 static ast_block* parse_block(parser_t *parser)
2653 block = ast_block_new(parser_ctx(parser));
2656 if (!parse_block_into(parser, block)) {
2657 ast_block_delete(block);
2663 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2665 if (parser->tok == '{') {
2666 *out = (ast_expression*)parse_block(parser);
2669 return parse_statement(parser, NULL, out, false);
2672 static bool create_vector_members(ast_value *var, ast_member **me)
2675 size_t len = strlen(var->name);
2677 for (i = 0; i < 3; ++i) {
2678 char *name = mem_a(len+3);
2679 memcpy(name, var->name, len);
2681 name[len+1] = 'x'+i;
2683 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2692 do { ast_member_delete(me[--i]); } while(i);
2696 static bool parse_function_body(parser_t *parser, ast_value *var)
2698 ast_block *block = NULL;
2703 ast_expression *framenum = NULL;
2704 ast_expression *nextthink = NULL;
2705 /* None of the following have to be deleted */
2706 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2707 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2708 bool has_frame_think;
2712 has_frame_think = false;
2713 old = parser->function;
2715 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2716 parseerror(parser, "gotos/labels leaking");
2720 if (var->expression.variadic) {
2721 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2722 "variadic function with implementation will not be able to access additional parameters"))
2728 if (parser->tok == '[') {
2729 /* got a frame definition: [ framenum, nextthink ]
2730 * this translates to:
2731 * self.frame = framenum;
2732 * self.nextthink = time + 0.1;
2733 * self.think = nextthink;
2737 fld_think = parser_find_field(parser, "think");
2738 fld_nextthink = parser_find_field(parser, "nextthink");
2739 fld_frame = parser_find_field(parser, "frame");
2740 if (!fld_think || !fld_nextthink || !fld_frame) {
2741 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2742 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2745 gbl_time = parser_find_global(parser, "time");
2746 gbl_self = parser_find_global(parser, "self");
2747 if (!gbl_time || !gbl_self) {
2748 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2749 parseerror(parser, "please declare the following globals: `time`, `self`");
2753 if (!parser_next(parser))
2756 framenum = parse_expression_leave(parser, true);
2758 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2761 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2762 ast_unref(framenum);
2763 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2767 if (parser->tok != ',') {
2768 ast_unref(framenum);
2769 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2770 parseerror(parser, "Got a %i\n", parser->tok);
2774 if (!parser_next(parser)) {
2775 ast_unref(framenum);
2779 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2781 /* qc allows the use of not-yet-declared functions here
2782 * - this automatically creates a prototype */
2783 ast_value *thinkfunc;
2784 ast_expression *functype = fld_think->expression.next;
2786 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2787 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2788 ast_unref(framenum);
2789 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2793 if (!parser_next(parser)) {
2794 ast_unref(framenum);
2795 ast_delete(thinkfunc);
2799 vec_push(parser->globals, (ast_expression*)thinkfunc);
2800 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2801 nextthink = (ast_expression*)thinkfunc;
2804 nextthink = parse_expression_leave(parser, true);
2806 ast_unref(framenum);
2807 parseerror(parser, "expected a think-function in [frame,think] notation");
2812 if (!ast_istype(nextthink, ast_value)) {
2813 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2817 if (retval && parser->tok != ']') {
2818 parseerror(parser, "expected closing `]` for [frame,think] notation");
2822 if (retval && !parser_next(parser)) {
2826 if (retval && parser->tok != '{') {
2827 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2832 ast_unref(nextthink);
2833 ast_unref(framenum);
2837 has_frame_think = true;
2840 block = ast_block_new(parser_ctx(parser));
2842 parseerror(parser, "failed to allocate block");
2843 if (has_frame_think) {
2844 ast_unref(nextthink);
2845 ast_unref(framenum);
2850 if (has_frame_think) {
2852 ast_expression *self_frame;
2853 ast_expression *self_nextthink;
2854 ast_expression *self_think;
2855 ast_expression *time_plus_1;
2856 ast_store *store_frame;
2857 ast_store *store_nextthink;
2858 ast_store *store_think;
2860 ctx = parser_ctx(parser);
2861 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2862 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2863 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2865 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2866 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2868 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2869 if (self_frame) ast_delete(self_frame);
2870 if (self_nextthink) ast_delete(self_nextthink);
2871 if (self_think) ast_delete(self_think);
2872 if (time_plus_1) ast_delete(time_plus_1);
2878 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2879 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2880 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2883 ast_delete(self_frame);
2886 if (!store_nextthink) {
2887 ast_delete(self_nextthink);
2891 ast_delete(self_think);
2895 if (store_frame) ast_delete(store_frame);
2896 if (store_nextthink) ast_delete(store_nextthink);
2897 if (store_think) ast_delete(store_think);
2900 ast_block_add_expr(block, (ast_expression*)store_frame);
2901 ast_block_add_expr(block, (ast_expression*)store_nextthink);
2902 ast_block_add_expr(block, (ast_expression*)store_think);
2906 parseerror(parser, "failed to generate code for [frame,think]");
2907 ast_unref(nextthink);
2908 ast_unref(framenum);
2914 parser_enterblock(parser);
2916 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2918 ast_value *param = var->expression.params[parami];
2921 if (param->expression.vtype != TYPE_VECTOR &&
2922 (param->expression.vtype != TYPE_FIELD ||
2923 param->expression.next->expression.vtype != TYPE_VECTOR))
2928 if (!create_vector_members(param, me)) {
2929 ast_block_delete(block);
2933 for (e = 0; e < 3; ++e) {
2934 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
2935 ast_block_collect(block, (ast_expression*)me[e]);
2939 func = ast_function_new(ast_ctx(var), var->name, var);
2941 parseerror(parser, "failed to allocate function for `%s`", var->name);
2942 ast_block_delete(block);
2945 vec_push(parser->functions, func);
2947 parser->function = func;
2948 if (!parse_block_into(parser, block)) {
2949 ast_block_delete(block);
2953 vec_push(func->blocks, block);
2955 parser->function = old;
2956 if (!parser_leaveblock(parser))
2958 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
2959 parseerror(parser, "internal error: local scopes left");
2963 if (parser->tok == ';')
2964 return parser_next(parser);
2965 else if (opts_standard == COMPILER_QCC)
2966 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
2970 vec_pop(parser->functions);
2971 ast_function_delete(func);
2972 var->constval.vfunc = NULL;
2975 (void)!parser_leaveblock(parser);
2976 parser->function = old;
2980 static ast_expression *array_accessor_split(
2985 ast_expression *left,
2986 ast_expression *right
2992 lex_ctx ctx = ast_ctx(array);
2994 if (!left || !right) {
2995 if (left) ast_delete(left);
2996 if (right) ast_delete(right);
3000 cmp = ast_binary_new(ctx, INSTR_LT,
3001 (ast_expression*)index,
3002 (ast_expression*)parser_const_float(parser, middle));
3006 parseerror(parser, "internal error: failed to create comparison for array setter");
3010 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3012 ast_delete(cmp); /* will delete left and right */
3013 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3017 return (ast_expression*)ifthen;
3020 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3022 lex_ctx ctx = ast_ctx(array);
3024 if (from+1 == afterend) {
3025 /* set this value */
3028 ast_array_index *subscript;
3030 int assignop = type_store_instr[value->expression.vtype];
3032 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3033 assignop = INSTR_STORE_V;
3035 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3039 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3041 ast_delete(subscript);
3045 block = ast_block_new(ctx);
3051 ast_block_add_expr(block, (ast_expression*)st);
3053 ret = ast_return_new(ctx, NULL);
3059 ast_block_add_expr(block, (ast_expression*)ret);
3061 return (ast_expression*)block;
3063 ast_expression *left, *right;
3064 size_t diff = afterend - from;
3065 size_t middle = from + diff/2;
3066 left = array_setter_node(parser, array, index, value, from, middle);
3067 right = array_setter_node(parser, array, index, value, middle, afterend);
3068 return array_accessor_split(parser, array, index, middle, left, right);
3072 static ast_expression *array_field_setter_node(
3081 lex_ctx ctx = ast_ctx(array);
3083 if (from+1 == afterend) {
3084 /* set this value */
3087 ast_entfield *entfield;
3088 ast_array_index *subscript;
3090 int assignop = type_storep_instr[value->expression.vtype];
3092 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3093 assignop = INSTR_STOREP_V;
3095 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3099 entfield = ast_entfield_new_force(ctx,
3100 (ast_expression*)entity,
3101 (ast_expression*)subscript,
3102 (ast_expression*)subscript);
3104 ast_delete(subscript);
3108 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3110 ast_delete(entfield);
3114 block = ast_block_new(ctx);
3120 ast_block_add_expr(block, (ast_expression*)st);
3122 ret = ast_return_new(ctx, NULL);
3128 ast_block_add_expr(block, (ast_expression*)ret);
3130 return (ast_expression*)block;
3132 ast_expression *left, *right;
3133 size_t diff = afterend - from;
3134 size_t middle = from + diff/2;
3135 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3136 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3137 return array_accessor_split(parser, array, index, middle, left, right);
3141 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3143 lex_ctx ctx = ast_ctx(array);
3145 if (from+1 == afterend) {
3147 ast_array_index *subscript;
3149 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3153 ret = ast_return_new(ctx, (ast_expression*)subscript);
3155 ast_delete(subscript);
3159 return (ast_expression*)ret;
3161 ast_expression *left, *right;
3162 size_t diff = afterend - from;
3163 size_t middle = from + diff/2;
3164 left = array_getter_node(parser, array, index, from, middle);
3165 right = array_getter_node(parser, array, index, middle, afterend);
3166 return array_accessor_split(parser, array, index, middle, left, right);
3170 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3172 ast_function *func = NULL;
3173 ast_value *fval = NULL;
3174 ast_block *body = NULL;
3176 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3178 parseerror(parser, "failed to create accessor function value");
3182 func = ast_function_new(ast_ctx(array), funcname, fval);
3185 parseerror(parser, "failed to create accessor function node");
3189 body = ast_block_new(ast_ctx(array));
3191 parseerror(parser, "failed to create block for array accessor");
3197 vec_push(func->blocks, body);
3200 vec_push(parser->accessors, fval);
3205 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3207 ast_expression *root = NULL;
3208 ast_value *index = NULL;
3209 ast_value *value = NULL;
3213 if (!ast_istype(array->expression.next, ast_value)) {
3214 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3218 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3220 func = fval->constval.vfunc;
3221 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3223 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3224 value = ast_value_copy((ast_value*)array->expression.next);
3226 if (!index || !value) {
3227 parseerror(parser, "failed to create locals for array accessor");
3230 (void)!ast_value_set_name(value, "value"); /* not important */
3231 vec_push(fval->expression.params, index);
3232 vec_push(fval->expression.params, value);
3234 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3236 parseerror(parser, "failed to build accessor search tree");
3240 ast_block_add_expr(func->blocks[0], root);
3241 array->setter = fval;
3244 if (index) ast_delete(index);
3245 if (value) ast_delete(value);
3246 if (root) ast_delete(root);
3252 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3254 ast_expression *root = NULL;
3255 ast_value *entity = NULL;
3256 ast_value *index = NULL;
3257 ast_value *value = NULL;
3261 if (!ast_istype(array->expression.next, ast_value)) {
3262 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3266 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3268 func = fval->constval.vfunc;
3269 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3271 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3272 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3273 value = ast_value_copy((ast_value*)array->expression.next);
3274 if (!entity || !index || !value) {
3275 parseerror(parser, "failed to create locals for array accessor");
3278 (void)!ast_value_set_name(value, "value"); /* not important */
3279 vec_push(fval->expression.params, entity);
3280 vec_push(fval->expression.params, index);
3281 vec_push(fval->expression.params, value);
3283 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3285 parseerror(parser, "failed to build accessor search tree");
3289 ast_block_add_expr(func->blocks[0], root);
3290 array->setter = fval;
3293 if (entity) ast_delete(entity);
3294 if (index) ast_delete(index);
3295 if (value) ast_delete(value);
3296 if (root) ast_delete(root);
3302 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3304 ast_expression *root = NULL;
3305 ast_value *index = NULL;
3309 /* NOTE: checking array->expression.next rather than elemtype since
3310 * for fields elemtype is a temporary fieldtype.
3312 if (!ast_istype(array->expression.next, ast_value)) {
3313 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3317 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3319 func = fval->constval.vfunc;
3320 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3322 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3325 parseerror(parser, "failed to create locals for array accessor");
3328 vec_push(fval->expression.params, index);
3330 root = array_getter_node(parser, array, index, 0, array->expression.count);
3332 parseerror(parser, "failed to build accessor search tree");
3336 ast_block_add_expr(func->blocks[0], root);
3337 array->getter = fval;
3340 if (index) ast_delete(index);
3341 if (root) ast_delete(root);
3347 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3348 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3356 bool variadic = false;
3358 ctx = parser_ctx(parser);
3360 /* for the sake of less code we parse-in in this function */
3361 if (!parser_next(parser)) {
3362 parseerror(parser, "expected parameter list");
3368 /* parse variables until we hit a closing paren */
3369 while (parser->tok != ')') {
3371 /* there must be commas between them */
3372 if (parser->tok != ',') {
3373 parseerror(parser, "expected comma or end of parameter list");
3376 if (!parser_next(parser)) {
3377 parseerror(parser, "expected parameter");
3383 if (parser->tok == TOKEN_DOTS) {
3384 /* '...' indicates a varargs function */
3386 if (!parser_next(parser)) {
3387 parseerror(parser, "expected parameter");
3390 if (parser->tok != ')') {
3391 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3397 /* for anything else just parse a typename */
3398 param = parse_typename(parser, NULL, NULL);
3401 vec_push(params, param);
3402 if (param->expression.vtype >= TYPE_VARIANT) {
3403 char typename[1024];
3404 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3405 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3411 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3415 if (vec_size(params) > 8 && opts_standard == COMPILER_QCC)
3416 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3419 if (!parser_next(parser)) {
3420 parseerror(parser, "parse error after typename");
3424 /* now turn 'var' into a function type */
3425 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3426 fval->expression.next = (ast_expression*)var;
3427 fval->expression.variadic = variadic;
3430 var->expression.params = params;
3437 for (i = 0; i < vec_size(params); ++i)
3438 ast_delete(params[i]);
3443 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3445 ast_expression *cexp;
3446 ast_value *cval, *tmp;
3449 ctx = parser_ctx(parser);
3451 if (!parser_next(parser)) {
3453 parseerror(parser, "expected array-size");
3457 cexp = parse_expression_leave(parser, true);
3459 if (!cexp || !ast_istype(cexp, ast_value)) {
3463 parseerror(parser, "expected array-size as constant positive integer");
3466 cval = (ast_value*)cexp;
3468 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3469 tmp->expression.next = (ast_expression*)var;
3472 if (cval->expression.vtype == TYPE_INTEGER)
3473 tmp->expression.count = cval->constval.vint;
3474 else if (cval->expression.vtype == TYPE_FLOAT)
3475 tmp->expression.count = cval->constval.vfloat;
3479 parseerror(parser, "array-size must be a positive integer constant");
3484 if (parser->tok != ']') {
3486 parseerror(parser, "expected ']' after array-size");
3489 if (!parser_next(parser)) {
3491 parseerror(parser, "error after parsing array size");
3497 /* Parse a complete typename.
3498 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3499 * but when parsing variables separated by comma
3500 * 'storebase' should point to where the base-type should be kept.
3501 * The base type makes up every bit of type information which comes *before* the
3504 * The following will be parsed in its entirety:
3506 * The 'basetype' in this case is 'void()'
3507 * and if there's a comma after it, say:
3509 * then the type-information 'void()' can be stored in 'storebase'
3511 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3513 ast_value *var, *tmp;
3516 const char *name = NULL;
3517 bool isfield = false;
3518 bool wasarray = false;
3519 size_t morefields = 0;
3521 ctx = parser_ctx(parser);
3523 /* types may start with a dot */
3524 if (parser->tok == '.') {
3526 /* if we parsed a dot we need a typename now */
3527 if (!parser_next(parser)) {
3528 parseerror(parser, "expected typename for field definition");
3532 /* Further dots are handled seperately because they won't be part of the
3535 while (parser->tok == '.') {
3537 if (!parser_next(parser)) {
3538 parseerror(parser, "expected typename for field definition");
3543 if (parser->tok == TOKEN_IDENT)
3544 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3545 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3546 parseerror(parser, "expected typename");
3550 /* generate the basic type value */
3551 if (cached_typedef) {
3552 var = ast_value_copy(cached_typedef);
3553 ast_value_set_name(var, "<type(from_def)>");
3555 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3557 for (; morefields; --morefields) {
3558 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3559 tmp->expression.next = (ast_expression*)var;
3563 /* do not yet turn into a field - remember:
3564 * .void() foo; is a field too
3565 * .void()() foo; is a function
3569 if (!parser_next(parser)) {
3571 parseerror(parser, "parse error after typename");
3575 /* an opening paren now starts the parameter-list of a function
3576 * this is where original-QC has parameter lists.
3577 * We allow a single parameter list here.
3578 * Much like fteqcc we don't allow `float()() x`
3580 if (parser->tok == '(') {
3581 var = parse_parameter_list(parser, var);
3586 /* store the base if requested */
3588 *storebase = ast_value_copy(var);
3590 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3591 tmp->expression.next = (ast_expression*)*storebase;
3596 /* there may be a name now */
3597 if (parser->tok == TOKEN_IDENT) {
3598 name = util_strdup(parser_tokval(parser));
3600 if (!parser_next(parser)) {
3602 parseerror(parser, "error after variable or field declaration");
3607 /* now this may be an array */
3608 if (parser->tok == '[') {
3610 var = parse_arraysize(parser, var);
3615 /* This is the point where we can turn it into a field */
3617 /* turn it into a field if desired */
3618 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3619 tmp->expression.next = (ast_expression*)var;
3623 /* now there may be function parens again */
3624 if (parser->tok == '(' && opts_standard == COMPILER_QCC)
3625 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3626 if (parser->tok == '(' && wasarray)
3627 parseerror(parser, "arrays as part of a return type is not supported");
3628 while (parser->tok == '(') {
3629 var = parse_parameter_list(parser, var);
3638 /* finally name it */
3640 if (!ast_value_set_name(var, name)) {
3642 parseerror(parser, "internal error: failed to set name");
3645 /* free the name, ast_value_set_name duplicates */
3652 static bool parse_typedef(parser_t *parser)
3654 ast_value *typevar, *oldtype;
3655 ast_expression *old;
3657 typevar = parse_typename(parser, NULL, NULL);
3662 if ( (old = parser_find_var(parser, typevar->name)) ) {
3663 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3664 " -> `%s` has been declared here: %s:%i",
3665 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3666 ast_delete(typevar);
3670 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3671 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3672 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3673 ast_delete(typevar);
3677 vec_push(parser->_typedefs, typevar);
3678 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3680 if (parser->tok != ';') {
3681 parseerror(parser, "expected semicolon after typedef");
3684 if (!parser_next(parser)) {
3685 parseerror(parser, "parse error after typedef");
3692 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef)
3696 ast_expression *old;
3700 ast_value *basetype = NULL;
3702 bool isparam = false;
3703 bool isvector = false;
3704 bool cleanvar = true;
3705 bool wasarray = false;
3709 /* get the first complete variable */
3710 var = parse_typename(parser, &basetype, cached_typedef);
3713 ast_delete(basetype);
3721 /* Part 0: finish the type */
3722 if (parser->tok == '(') {
3723 if (opts_standard == COMPILER_QCC)
3724 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3725 var = parse_parameter_list(parser, var);
3731 /* we only allow 1-dimensional arrays */
3732 if (parser->tok == '[') {
3734 var = parse_arraysize(parser, var);
3740 if (parser->tok == '(' && wasarray) {
3741 parseerror(parser, "arrays as part of a return type is not supported");
3742 /* we'll still parse the type completely for now */
3744 /* for functions returning functions */
3745 while (parser->tok == '(') {
3746 if (opts_standard == COMPILER_QCC)
3747 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3748 var = parse_parameter_list(parser, var);
3755 var->cvq = qualifier;
3758 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3759 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3760 * is then filled with the previous definition and the parameter-names replaced.
3763 /* Deal with end_sys_ vars */
3765 if (!strcmp(var->name, "end_sys_globals")) {
3766 parser->crc_globals = vec_size(parser->globals);
3769 else if (!strcmp(var->name, "end_sys_fields")) {
3770 parser->crc_fields = vec_size(parser->fields);
3773 if (was_end && var->expression.vtype == TYPE_FIELD) {
3774 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3775 "global '%s' hint should not be a field",
3776 parser_tokval(parser)))
3783 if (!nofields && var->expression.vtype == TYPE_FIELD)
3785 /* deal with field declarations */
3786 old = parser_find_field(parser, var->name);
3788 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3789 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3798 parseerror(parser, "field `%s` already declared here: %s:%i",
3799 var->name, ast_ctx(old).file, ast_ctx(old).line);
3804 if (opts_standard == COMPILER_QCC &&
3805 (old = parser_find_global(parser, var->name)))
3807 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3808 parseerror(parser, "field `%s` already declared here: %s:%i",
3809 var->name, ast_ctx(old).file, ast_ctx(old).line);
3816 /* deal with other globals */
3817 old = parser_find_global(parser, var->name);
3818 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3820 /* This is a function which had a prototype */
3821 if (!ast_istype(old, ast_value)) {
3822 parseerror(parser, "internal error: prototype is not an ast_value");
3826 proto = (ast_value*)old;
3827 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3828 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3830 ast_ctx(proto).file, ast_ctx(proto).line);
3834 /* we need the new parameter-names */
3835 for (i = 0; i < vec_size(proto->expression.params); ++i)
3836 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3844 if (opts_standard == COMPILER_GMQCC) {
3845 parseerror(parser, "global `%s` already declared here: %s:%i",
3846 var->name, ast_ctx(old).file, ast_ctx(old).line);
3850 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3851 "global `%s` already declared here: %s:%i",
3852 var->name, ast_ctx(old).file, ast_ctx(old).line))
3857 proto = (ast_value*)old;
3858 if (!ast_istype(old, ast_value)) {
3859 parseerror(parser, "internal error: not an ast_value");
3868 if (opts_standard == COMPILER_QCC &&
3869 (old = parser_find_field(parser, var->name)))
3871 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3872 parseerror(parser, "global `%s` already declared here: %s:%i",
3873 var->name, ast_ctx(old).file, ast_ctx(old).line);
3880 else /* it's not a global */
3882 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3883 if (old && !isparam) {
3884 parseerror(parser, "local `%s` already declared here: %s:%i",
3885 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3889 old = parser_find_local(parser, var->name, 0, &isparam);
3890 if (old && isparam) {
3891 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3892 "local `%s` is shadowing a parameter", var->name))
3894 parseerror(parser, "local `%s` already declared here: %s:%i",
3895 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3899 if (opts_standard != COMPILER_GMQCC) {
3908 * Create the global/local, and deal with vector types.
3911 if (var->expression.vtype == TYPE_VECTOR)
3913 else if (var->expression.vtype == TYPE_FIELD &&
3914 var->expression.next->expression.vtype == TYPE_VECTOR)
3918 if (!create_vector_members(var, me)) {
3925 /* deal with global variables, fields, functions */
3926 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
3927 var->isfield = true;
3928 vec_push(parser->fields, (ast_expression*)var);
3929 util_htset(parser->htfields, var->name, var);
3931 for (i = 0; i < 3; ++i) {
3932 vec_push(parser->fields, (ast_expression*)me[i]);
3933 util_htset(parser->htfields, me[i]->name, me[i]);
3938 vec_push(parser->globals, (ast_expression*)var);
3939 util_htset(parser->htglobals, var->name, var);
3941 for (i = 0; i < 3; ++i) {
3942 vec_push(parser->globals, (ast_expression*)me[i]);
3943 util_htset(parser->htglobals, me[i]->name, me[i]);
3948 vec_push(localblock->locals, var);
3949 parser_addlocal(parser, var->name, (ast_expression*)var);
3951 for (i = 0; i < 3; ++i) {
3952 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
3953 ast_block_collect(localblock, (ast_expression*)me[i]);
3959 me[0] = me[1] = me[2] = NULL;
3964 if (var->expression.vtype == TYPE_ARRAY) {
3966 snprintf(name, sizeof(name), "%s##SET", var->name);
3967 if (!parser_create_array_setter(parser, var, name))
3969 snprintf(name, sizeof(name), "%s##GET", var->name);
3970 if (!parser_create_array_getter(parser, var, var->expression.next, name))
3973 else if (!localblock && !nofields &&
3974 var->expression.vtype == TYPE_FIELD &&
3975 var->expression.next->expression.vtype == TYPE_ARRAY)
3978 ast_expression *telem;
3980 ast_value *array = (ast_value*)var->expression.next;
3982 if (!ast_istype(var->expression.next, ast_value)) {
3983 parseerror(parser, "internal error: field element type must be an ast_value");
3987 snprintf(name, sizeof(name), "%s##SETF", var->name);
3988 if (!parser_create_array_field_setter(parser, array, name))
3991 telem = ast_type_copy(ast_ctx(var), array->expression.next);
3992 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
3993 tfield->expression.next = telem;
3994 snprintf(name, sizeof(name), "%s##GETFP", var->name);
3995 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4003 if (parser->tok == ';') {
4004 ast_delete(basetype);
4005 if (!parser_next(parser)) {
4006 parseerror(parser, "error after variable declaration");
4012 if (parser->tok == ',')
4016 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4019 parseerror(parser, "missing comma or semicolon while parsing variables");
4023 if (localblock && opts_standard == COMPILER_QCC) {
4024 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4025 "initializing expression turns variable `%s` into a constant in this standard",
4032 if (parser->tok != '{') {
4033 if (parser->tok != '=') {
4034 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4038 if (!parser_next(parser)) {
4039 parseerror(parser, "error parsing initializer");
4043 else if (opts_standard == COMPILER_QCC) {
4044 parseerror(parser, "expected '=' before function body in this standard");
4047 if (parser->tok == '#') {
4048 ast_function *func = NULL;
4051 parseerror(parser, "cannot declare builtins within functions");
4054 if (var->expression.vtype != TYPE_FUNCTION) {
4055 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4058 if (!parser_next(parser)) {
4059 parseerror(parser, "expected builtin number");
4062 if (parser->tok != TOKEN_INTCONST) {
4063 parseerror(parser, "builtin number must be an integer constant");
4066 if (parser_token(parser)->constval.i < 0) {
4067 parseerror(parser, "builtin number must be an integer greater than zero");
4071 if (var->hasvalue) {
4072 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4073 "builtin `%s` has already been defined\n"
4074 " -> previous declaration here: %s:%i",
4075 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4079 func = ast_function_new(ast_ctx(var), var->name, var);
4081 parseerror(parser, "failed to allocate function for `%s`", var->name);
4084 vec_push(parser->functions, func);
4086 func->builtin = -parser_token(parser)->constval.i-1;
4089 if (!parser_next(parser)) {
4090 parseerror(parser, "expected comma or semicolon");
4092 ast_function_delete(func);
4093 var->constval.vfunc = NULL;
4097 else if (parser->tok == '{' || parser->tok == '[')
4101 parseerror(parser, "cannot declare functions within functions");
4106 ast_ctx(proto) = parser_ctx(parser);
4108 if (!parse_function_body(parser, var))
4110 ast_delete(basetype);
4111 for (i = 0; i < vec_size(parser->gotos); ++i)
4112 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4113 vec_free(parser->gotos);
4114 vec_free(parser->labels);
4117 ast_expression *cexp;
4120 cexp = parse_expression_leave(parser, true);
4125 cval = (ast_value*)cexp;
4126 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4127 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4130 if (opts_standard != COMPILER_GMQCC &&
4131 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4132 qualifier != CV_VAR)
4134 var->cvq = CV_CONST;
4136 var->hasvalue = true;
4137 if (cval->expression.vtype == TYPE_STRING)
4138 var->constval.vstring = parser_strdup(cval->constval.vstring);
4139 else if (cval->expression.vtype == TYPE_FIELD)
4140 var->constval.vfield = cval;
4142 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4147 shunt sy = { NULL, NULL };
4150 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4151 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4152 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4153 if (!parser_sy_pop(parser, &sy))
4156 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4157 parseerror(parser, "internal error: leaked operands");
4158 ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out);
4167 if (parser->tok == ',') {
4168 if (!parser_next(parser)) {
4169 parseerror(parser, "expected another variable");
4173 if (parser->tok != TOKEN_IDENT) {
4174 parseerror(parser, "expected another variable");
4177 var = ast_value_copy(basetype);
4179 ast_value_set_name(var, parser_tokval(parser));
4180 if (!parser_next(parser)) {
4181 parseerror(parser, "error parsing variable declaration");
4187 if (parser->tok != ';') {
4188 parseerror(parser, "missing semicolon after variables");
4192 if (!parser_next(parser)) {
4193 parseerror(parser, "parse error after variable declaration");
4197 ast_delete(basetype);
4201 if (cleanvar && var)
4203 ast_delete(basetype);
4207 ast_delete(basetype);
4208 if (cleanvar && var)
4210 if (me[0]) ast_member_delete(me[0]);
4211 if (me[1]) ast_member_delete(me[1]);
4212 if (me[2]) ast_member_delete(me[2]);
4216 static bool parser_global_statement(parser_t *parser)
4218 ast_value *istype = NULL;
4219 if (parser->tok == TOKEN_IDENT)
4220 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4222 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4224 return parse_variable(parser, NULL, false, CV_NONE, istype);
4226 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var"))
4228 if (!strcmp(parser_tokval(parser), "var")) {
4229 if (!parser_next(parser)) {
4230 parseerror(parser, "expected variable declaration after 'var'");
4233 if (parser->tok == TOKEN_KEYWORD && !strcmp(parser_tokval(parser), "const")) {
4234 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `const` after 'var' qualifier");
4235 if (!parser_next(parser)) {
4236 parseerror(parser, "expected variable declaration after 'const var'");
4240 return parse_variable(parser, NULL, true, CV_VAR, NULL);
4243 else if (parser->tok == TOKEN_KEYWORD)
4245 if (!strcmp(parser_tokval(parser), "const")) {
4246 if (!parser_next(parser)) {
4247 parseerror(parser, "expected variable declaration after 'const'");
4250 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "var")) {
4251 (void)!parsewarning(parser, WARN_CONST_VAR, "ignoring `var` after const qualifier");
4252 if (!parser_next(parser)) {
4253 parseerror(parser, "expected variable declaration after 'const var'");
4257 return parse_variable(parser, NULL, true, CV_CONST, NULL);
4259 else if (!strcmp(parser_tokval(parser), "typedef")) {
4260 if (!parser_next(parser)) {
4261 parseerror(parser, "expected type definition after 'typedef'");
4264 return parse_typedef(parser);
4266 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4269 else if (parser->tok == '$')
4271 if (!parser_next(parser)) {
4272 parseerror(parser, "parse error");
4278 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4284 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4286 return util_crc16(old, str, strlen(str));
4289 static void progdefs_crc_file(const char *str)
4291 /* write to progdefs.h here */
4295 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4297 old = progdefs_crc_sum(old, str);
4298 progdefs_crc_file(str);
4302 static void generate_checksum(parser_t *parser)
4304 uint16_t crc = 0xFFFF;
4308 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4309 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4311 progdefs_crc_file("\tint\tpad;\n");
4312 progdefs_crc_file("\tint\tofs_return[3];\n");
4313 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4314 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4315 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4316 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4317 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4318 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4319 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4320 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4322 for (i = 0; i < parser->crc_globals; ++i) {
4323 if (!ast_istype(parser->globals[i], ast_value))
4325 value = (ast_value*)(parser->globals[i]);
4326 switch (value->expression.vtype) {
4327 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4328 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4329 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4330 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4332 crc = progdefs_crc_both(crc, "\tint\t");
4335 crc = progdefs_crc_both(crc, value->name);
4336 crc = progdefs_crc_both(crc, ";\n");
4338 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4339 for (i = 0; i < parser->crc_fields; ++i) {
4340 if (!ast_istype(parser->fields[i], ast_value))
4342 value = (ast_value*)(parser->fields[i]);
4343 switch (value->expression.next->expression.vtype) {
4344 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4345 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4346 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4347 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4349 crc = progdefs_crc_both(crc, "\tint\t");
4352 crc = progdefs_crc_both(crc, value->name);
4353 crc = progdefs_crc_both(crc, ";\n");
4355 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4360 static parser_t *parser;
4366 parser = (parser_t*)mem_a(sizeof(parser_t));
4370 memset(parser, 0, sizeof(*parser));
4372 for (i = 0; i < operator_count; ++i) {
4373 if (operators[i].id == opid1('=')) {
4374 parser->assign_op = operators+i;
4378 if (!parser->assign_op) {
4379 printf("internal error: initializing parser: failed to find assign operator\n");
4384 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4385 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4386 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4387 vec_push(parser->_blocktypedefs, 0);
4391 bool parser_compile()
4393 /* initial lexer/parser state */
4394 parser->lex->flags.noops = true;
4396 if (parser_next(parser))
4398 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4400 if (!parser_global_statement(parser)) {
4401 if (parser->tok == TOKEN_EOF)
4402 parseerror(parser, "unexpected eof");
4403 else if (!parser->errors)
4404 parseerror(parser, "there have been errors, bailing out");
4405 lex_close(parser->lex);
4411 parseerror(parser, "parse error");
4412 lex_close(parser->lex);
4417 lex_close(parser->lex);
4420 return !parser->errors;
4423 bool parser_compile_file(const char *filename)
4425 parser->lex = lex_open(filename);
4427 con_err("failed to open file \"%s\"\n", filename);
4430 return parser_compile();
4433 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4435 parser->lex = lex_open_string(str, len, name);
4437 con_err("failed to create lexer for string \"%s\"\n", name);
4440 return parser_compile();
4443 bool parser_compile_string(const char *name, const char *str)
4445 parser->lex = lex_open_string(str, strlen(str), name);
4447 con_err("failed to create lexer for string \"%s\"\n", name);
4450 return parser_compile();
4453 void parser_cleanup()
4456 for (i = 0; i < vec_size(parser->accessors); ++i) {
4457 ast_delete(parser->accessors[i]->constval.vfunc);
4458 parser->accessors[i]->constval.vfunc = NULL;
4459 ast_delete(parser->accessors[i]);
4461 for (i = 0; i < vec_size(parser->functions); ++i) {
4462 ast_delete(parser->functions[i]);
4464 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4465 ast_delete(parser->imm_vector[i]);
4467 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4468 ast_delete(parser->imm_string[i]);
4470 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4471 ast_delete(parser->imm_float[i]);
4473 for (i = 0; i < vec_size(parser->fields); ++i) {
4474 ast_delete(parser->fields[i]);
4476 for (i = 0; i < vec_size(parser->globals); ++i) {
4477 ast_delete(parser->globals[i]);
4479 vec_free(parser->accessors);
4480 vec_free(parser->functions);
4481 vec_free(parser->imm_vector);
4482 vec_free(parser->imm_string);
4483 vec_free(parser->imm_float);
4484 vec_free(parser->globals);
4485 vec_free(parser->fields);
4487 for (i = 0; i < vec_size(parser->variables); ++i)
4488 util_htdel(parser->variables[i]);
4489 vec_free(parser->variables);
4490 vec_free(parser->_blocklocals);
4491 vec_free(parser->_locals);
4493 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4494 ast_delete(parser->_typedefs[i]);
4495 vec_free(parser->_typedefs);
4496 for (i = 0; i < vec_size(parser->typedefs); ++i)
4497 util_htdel(parser->typedefs[i]);
4498 vec_free(parser->typedefs);
4499 vec_free(parser->_blocktypedefs);
4501 vec_free(parser->_block_ctx);
4503 vec_free(parser->labels);
4504 vec_free(parser->gotos);
4509 bool parser_finish(const char *output)
4515 if (!parser->errors)
4517 ir = ir_builder_new("gmqcc_out");
4519 con_out("failed to allocate builder\n");
4523 for (i = 0; i < vec_size(parser->fields); ++i) {
4526 if (!ast_istype(parser->fields[i], ast_value))
4528 field = (ast_value*)parser->fields[i];
4529 hasvalue = field->hasvalue;
4530 field->hasvalue = false;
4531 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4532 con_out("failed to generate field %s\n", field->name);
4533 ir_builder_delete(ir);
4538 ast_expression *subtype;
4539 field->hasvalue = true;
4540 subtype = field->expression.next;
4541 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4542 if (subtype->expression.vtype == TYPE_FIELD)
4543 ifld->fieldtype = subtype->expression.next->expression.vtype;
4544 else if (subtype->expression.vtype == TYPE_FUNCTION)
4545 ifld->outtype = subtype->expression.next->expression.vtype;
4546 (void)!ir_value_set_field(field->ir_v, ifld);
4549 for (i = 0; i < vec_size(parser->globals); ++i) {
4551 if (!ast_istype(parser->globals[i], ast_value))
4553 asvalue = (ast_value*)(parser->globals[i]);
4554 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4555 if (strcmp(asvalue->name, "end_sys_globals") &&
4556 strcmp(asvalue->name, "end_sys_fields"))
4558 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4559 "unused global: `%s`", asvalue->name);
4562 if (!ast_global_codegen(asvalue, ir, false)) {
4563 con_out("failed to generate global %s\n", asvalue->name);
4564 ir_builder_delete(ir);
4568 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4569 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4570 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4571 ir_builder_delete(ir);
4575 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4576 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4577 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4578 ir_builder_delete(ir);
4582 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4583 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4584 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4585 ir_builder_delete(ir);
4589 for (i = 0; i < vec_size(parser->globals); ++i) {
4591 if (!ast_istype(parser->globals[i], ast_value))
4593 asvalue = (ast_value*)(parser->globals[i]);
4594 if (!ast_generate_accessors(asvalue, ir)) {
4595 ir_builder_delete(ir);
4599 for (i = 0; i < vec_size(parser->fields); ++i) {
4601 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4603 if (!ast_istype((ast_expression*)asvalue, ast_value))
4605 if (asvalue->expression.vtype != TYPE_ARRAY)
4607 if (!ast_generate_accessors(asvalue, ir)) {
4608 ir_builder_delete(ir);
4612 for (i = 0; i < vec_size(parser->functions); ++i) {
4613 if (!ast_function_codegen(parser->functions[i], ir)) {
4614 con_out("failed to generate function %s\n", parser->functions[i]->name);
4615 ir_builder_delete(ir);
4620 ir_builder_dump(ir, con_out);
4621 for (i = 0; i < vec_size(parser->functions); ++i) {
4622 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4623 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4624 ir_builder_delete(ir);
4631 ir_builder_dump(ir, con_out);
4633 generate_checksum(parser);
4635 if (!ir_builder_generate(ir, output)) {
4636 con_out("*** failed to generate output file\n");
4637 ir_builder_delete(ir);
4642 ir_builder_delete(ir);
4646 con_out("*** there were compile errors\n");