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;
101 static void parser_enterblock(parser_t *parser);
102 static bool parser_leaveblock(parser_t *parser);
103 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
104 static bool parse_typedef(parser_t *parser);
105 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref);
106 static ast_block* parse_block(parser_t *parser);
107 static bool parse_block_into(parser_t *parser, ast_block *block);
108 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
109 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
110 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
111 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
113 static void parseerror(parser_t *parser, const char *fmt, ...)
120 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
124 /* returns true if it counts as an error */
125 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
128 int lvl = LVL_WARNING;
130 if (!OPTS_WARN(warntype))
139 con_vprintmsg(lvl, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, (opts.werror ? "error" : "warning"), fmt, ap);
145 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
148 int lvl = LVL_WARNING;
150 if (!OPTS_WARN(warntype))
157 con_vprintmsg(lvl, ctx.file, ctx.line, (opts.werror ? "error" : "warning"), fmt, ap);
163 /**********************************************************************
164 * some maths used for constant folding
167 vector vec3_add(vector a, vector b)
176 vector vec3_sub(vector a, vector b)
185 qcfloat vec3_mulvv(vector a, vector b)
187 return (a.x * b.x + a.y * b.y + a.z * b.z);
190 vector vec3_mulvf(vector a, float b)
199 /**********************************************************************
203 bool parser_next(parser_t *parser)
205 /* lex_do kills the previous token */
206 parser->tok = lex_do(parser->lex);
207 if (parser->tok == TOKEN_EOF)
209 if (parser->tok >= TOKEN_ERROR) {
210 parseerror(parser, "lex error");
216 #define parser_tokval(p) ((p)->lex->tok.value)
217 #define parser_token(p) (&((p)->lex->tok))
218 #define parser_ctx(p) ((p)->lex->tok.ctx)
220 static ast_value* parser_const_float(parser_t *parser, double d)
224 for (i = 0; i < vec_size(parser->imm_float); ++i) {
225 const double compare = parser->imm_float[i]->constval.vfloat;
226 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
227 return parser->imm_float[i];
229 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
231 out->hasvalue = true;
232 out->constval.vfloat = d;
233 vec_push(parser->imm_float, out);
237 static ast_value* parser_const_float_0(parser_t *parser)
239 if (!parser->imm_float_zero)
240 parser->imm_float_zero = parser_const_float(parser, 0);
241 return parser->imm_float_zero;
244 static ast_value* parser_const_float_1(parser_t *parser)
246 if (!parser->imm_float_one)
247 parser->imm_float_one = parser_const_float(parser, 1);
248 return parser->imm_float_one;
251 static char *parser_strdup(const char *str)
254 /* actually dup empty strings */
255 char *out = mem_a(1);
259 return util_strdup(str);
262 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
266 for (i = 0; i < vec_size(parser->imm_string); ++i) {
267 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
268 return parser->imm_string[i];
272 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
273 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
275 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
277 out->hasvalue = true;
278 out->constval.vstring = parser_strdup(str);
279 vec_push(parser->imm_string, out);
283 static ast_value* parser_const_vector(parser_t *parser, vector v)
287 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
288 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
289 return parser->imm_vector[i];
291 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
293 out->hasvalue = true;
294 out->constval.vvec = v;
295 vec_push(parser->imm_vector, out);
299 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
305 return parser_const_vector(parser, v);
308 static ast_value* parser_const_vector_0(parser_t *parser)
310 if (!parser->imm_vector_zero)
311 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
312 return parser->imm_vector_zero;
315 static ast_expression* parser_find_field(parser_t *parser, const char *name)
317 return util_htget(parser->htfields, name);
320 static ast_expression* parser_find_global(parser_t *parser, const char *name)
322 return util_htget(parser->htglobals, name);
325 static ast_expression* parser_find_param(parser_t *parser, const char *name)
329 if (!parser->function)
331 fun = parser->function->vtype;
332 for (i = 0; i < vec_size(fun->expression.params); ++i) {
333 if (!strcmp(fun->expression.params[i]->name, name))
334 return (ast_expression*)(fun->expression.params[i]);
339 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
344 hash = util_hthash(parser->htglobals, name);
347 for (i = vec_size(parser->variables); i > upto;) {
349 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
353 return parser_find_param(parser, name);
356 static ast_expression* parser_find_var(parser_t *parser, const char *name)
360 v = parser_find_local(parser, name, 0, &dummy);
361 if (!v) v = parser_find_global(parser, name);
365 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
369 hash = util_hthash(parser->typedefs[0], name);
371 for (i = vec_size(parser->typedefs); i > upto;) {
373 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
381 size_t etype; /* 0 = expression, others are operators */
385 ast_block *block; /* for commas and function calls */
394 #define SY_PAREN_EXPR '('
395 #define SY_PAREN_FUNC 'f'
396 #define SY_PAREN_INDEX '['
397 #define SY_PAREN_TERNARY '?'
399 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
410 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
414 e.out = (ast_expression*)v;
421 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
423 e.etype = 1 + (op - operators);
432 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
444 # define DEBUGSHUNTDO(x) x
446 # define DEBUGSHUNTDO(x)
449 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
450 * so we need to rotate it to become ent.(foo[n]).
452 static bool rotate_entfield_array_index_nodes(ast_expression **out)
454 ast_array_index *index;
455 ast_entfield *entfield;
459 ast_expression *entity;
461 lex_ctx ctx = ast_ctx(*out);
463 if (!ast_istype(*out, ast_array_index))
465 index = (ast_array_index*)*out;
467 if (!ast_istype(index->array, ast_entfield))
469 entfield = (ast_entfield*)index->array;
471 if (!ast_istype(entfield->field, ast_value))
473 field = (ast_value*)entfield->field;
476 entity = entfield->entity;
480 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
481 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
482 *out = (ast_expression*)entfield;
487 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
491 ast_expression *out = NULL;
492 ast_expression *exprs[3];
493 ast_block *blocks[3];
494 ast_value *asvalue[3];
495 ast_binstore *asbinstore;
496 size_t i, assignop, addop, subop;
497 qcint generated_op = 0;
502 if (!vec_size(sy->ops)) {
503 parseerror(parser, "internal error: missing operator");
507 if (vec_last(sy->ops).paren) {
508 parseerror(parser, "unmatched parenthesis");
512 op = &operators[vec_last(sy->ops).etype - 1];
513 ctx = vec_last(sy->ops).ctx;
515 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
517 if (vec_size(sy->out) < op->operands) {
518 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
519 op->op, (int)op->id);
523 vec_shrinkby(sy->ops, 1);
525 /* op(:?) has no input and no output */
529 vec_shrinkby(sy->out, op->operands);
530 for (i = 0; i < op->operands; ++i) {
531 exprs[i] = sy->out[vec_size(sy->out)+i].out;
532 blocks[i] = sy->out[vec_size(sy->out)+i].block;
533 asvalue[i] = (ast_value*)exprs[i];
536 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
537 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
541 #define NotSameType(T) \
542 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
543 exprs[0]->expression.vtype != T)
544 #define CanConstFold1(A) \
545 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST))
546 #define CanConstFold(A, B) \
547 (CanConstFold1(A) && CanConstFold1(B))
548 #define ConstV(i) (asvalue[(i)]->constval.vvec)
549 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
550 #define ConstS(i) (asvalue[(i)]->constval.vstring)
554 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
558 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
559 if (exprs[1]->expression.vtype != TYPE_FIELD) {
560 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
563 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
565 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
566 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
570 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
576 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
577 !(exprs[0]->expression.vtype == TYPE_FIELD &&
578 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
580 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
581 parseerror(parser, "cannot index value of type %s", ty1);
584 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
585 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
586 parseerror(parser, "index must be of type float, not %s", ty1);
589 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
590 if (rotate_entfield_array_index_nodes(&out))
593 /* This is not broken in fteqcc anymore */
594 if (opts.standard != COMPILER_GMQCC) {
595 /* this error doesn't need to make us bail out */
596 (void)!parsewarning(parser, WARN_EXTENSIONS,
597 "accessing array-field members of an entity without parenthesis\n"
598 " -> this is an extension from -std=gmqcc");
606 if (!ast_block_add_expr(blocks[0], exprs[1]))
609 blocks[0] = ast_block_new(ctx);
610 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
611 !ast_block_add_expr(blocks[0], exprs[1]))
616 if (!ast_block_set_type(blocks[0], exprs[1]))
619 vec_push(sy->out, syblock(ctx, blocks[0]));
626 switch (exprs[0]->expression.vtype) {
628 if (CanConstFold1(exprs[0]))
629 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
631 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
632 (ast_expression*)parser_const_float_0(parser),
636 if (CanConstFold1(exprs[0]))
637 out = (ast_expression*)parser_const_vector_f(parser,
638 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
640 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
641 (ast_expression*)parser_const_vector_0(parser),
645 parseerror(parser, "invalid types used in expression: cannot negate type %s",
646 type_name[exprs[0]->expression.vtype]);
652 switch (exprs[0]->expression.vtype) {
654 if (CanConstFold1(exprs[0]))
655 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
657 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
660 if (CanConstFold1(exprs[0]))
661 out = (ast_expression*)parser_const_float(parser,
662 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
664 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
667 if (CanConstFold1(exprs[0]))
668 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
670 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
672 /* we don't constant-fold NOT for these types */
674 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
677 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
680 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
681 type_name[exprs[0]->expression.vtype]);
687 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
688 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
690 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
691 type_name[exprs[0]->expression.vtype],
692 type_name[exprs[1]->expression.vtype]);
695 switch (exprs[0]->expression.vtype) {
697 if (CanConstFold(exprs[0], exprs[1]))
699 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
702 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
705 if (CanConstFold(exprs[0], exprs[1]))
706 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
708 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
711 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
712 type_name[exprs[0]->expression.vtype],
713 type_name[exprs[1]->expression.vtype]);
718 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
719 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
721 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
722 type_name[exprs[1]->expression.vtype],
723 type_name[exprs[0]->expression.vtype]);
726 switch (exprs[0]->expression.vtype) {
728 if (CanConstFold(exprs[0], exprs[1]))
729 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
731 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
734 if (CanConstFold(exprs[0], exprs[1]))
735 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
737 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
740 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
741 type_name[exprs[1]->expression.vtype],
742 type_name[exprs[0]->expression.vtype]);
747 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
748 exprs[0]->expression.vtype != TYPE_VECTOR &&
749 exprs[0]->expression.vtype != TYPE_FLOAT &&
750 exprs[1]->expression.vtype != TYPE_VECTOR &&
751 exprs[1]->expression.vtype != TYPE_FLOAT)
753 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
754 type_name[exprs[1]->expression.vtype],
755 type_name[exprs[0]->expression.vtype]);
758 switch (exprs[0]->expression.vtype) {
760 if (exprs[1]->expression.vtype == TYPE_VECTOR)
762 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
765 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
769 if (CanConstFold(exprs[0], exprs[1]))
770 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
772 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
776 if (exprs[1]->expression.vtype == TYPE_FLOAT)
778 if (CanConstFold(exprs[0], exprs[1]))
779 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
781 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
785 if (CanConstFold(exprs[0], exprs[1]))
786 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
788 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
792 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
793 type_name[exprs[1]->expression.vtype],
794 type_name[exprs[0]->expression.vtype]);
799 if (NotSameType(TYPE_FLOAT)) {
800 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
801 type_name[exprs[0]->expression.vtype],
802 type_name[exprs[1]->expression.vtype]);
805 if (CanConstFold(exprs[0], exprs[1]))
806 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
808 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
812 parseerror(parser, "qc does not have a modulo operator");
816 if (NotSameType(TYPE_FLOAT)) {
817 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
818 type_name[exprs[0]->expression.vtype],
819 type_name[exprs[1]->expression.vtype]);
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser,
824 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
825 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
827 out = (ast_expression*)ast_binary_new(ctx,
828 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
832 parseerror(parser, "TODO: bitxor");
837 case opid3('<','<','='):
838 case opid3('>','>','='):
839 parseerror(parser, "TODO: shifts");
843 generated_op += 1; /* INSTR_OR */
845 generated_op += INSTR_AND;
847 if (NotSameType(TYPE_FLOAT)) {
848 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
849 type_name[exprs[0]->expression.vtype],
850 type_name[exprs[1]->expression.vtype]);
851 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
852 parseerror(parser, "TODO: optional early out");
856 if (opts.standard == COMPILER_GMQCC)
857 con_out("TODO: early out logic\n");
858 if (CanConstFold(exprs[0], exprs[1]))
859 out = (ast_expression*)parser_const_float(parser,
860 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
862 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
866 if (vec_last(parser->pot) != POT_TERNARY2) {
867 parseerror(parser, "mismatched parenthesis/ternary");
870 vec_pop(parser->pot);
871 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
872 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
873 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
874 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
877 if (CanConstFold1(exprs[0]))
878 out = (ConstF(0) ? exprs[1] : exprs[2]);
880 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
884 generated_op += 1; /* INSTR_GT */
886 generated_op += 1; /* INSTR_LT */
887 case opid2('>', '='):
888 generated_op += 1; /* INSTR_GE */
889 case opid2('<', '='):
890 generated_op += INSTR_LE;
891 if (NotSameType(TYPE_FLOAT)) {
892 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
893 type_name[exprs[0]->expression.vtype],
894 type_name[exprs[1]->expression.vtype]);
897 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
899 case opid2('!', '='):
900 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
901 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
902 type_name[exprs[0]->expression.vtype],
903 type_name[exprs[1]->expression.vtype]);
906 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
908 case opid2('=', '='):
909 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
910 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
911 type_name[exprs[0]->expression.vtype],
912 type_name[exprs[1]->expression.vtype]);
915 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
919 if (ast_istype(exprs[0], ast_entfield)) {
920 ast_expression *field = ((ast_entfield*)exprs[0])->field;
921 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
922 exprs[0]->expression.vtype == TYPE_FIELD &&
923 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
925 assignop = type_storep_instr[TYPE_VECTOR];
928 assignop = type_storep_instr[exprs[0]->expression.vtype];
929 if (assignop == AINSTR_END ||
930 !ast_compare_type(field->expression.next, exprs[1]))
932 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
933 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
934 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
935 field->expression.next->expression.vtype == TYPE_FUNCTION &&
936 exprs[1]->expression.vtype == TYPE_FUNCTION)
938 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
939 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
945 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
950 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
951 exprs[0]->expression.vtype == TYPE_FIELD &&
952 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
954 assignop = type_store_instr[TYPE_VECTOR];
957 assignop = type_store_instr[exprs[0]->expression.vtype];
960 if (assignop == AINSTR_END) {
961 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
962 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
963 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
965 else if (!ast_compare_type(exprs[0], exprs[1])) {
966 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
967 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
968 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
969 exprs[0]->expression.vtype == TYPE_FUNCTION &&
970 exprs[1]->expression.vtype == TYPE_FUNCTION)
972 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
973 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
979 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
982 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
983 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
985 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
987 case opid3('+','+','P'):
988 case opid3('-','-','P'):
990 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
991 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
992 parseerror(parser, "invalid type for prefix increment: %s", ty1);
995 if (op->id == opid3('+','+','P'))
999 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1000 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1002 if (ast_istype(exprs[0], ast_entfield)) {
1003 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1005 (ast_expression*)parser_const_float_1(parser));
1007 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1009 (ast_expression*)parser_const_float_1(parser));
1012 case opid3('S','+','+'):
1013 case opid3('S','-','-'):
1015 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1016 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1017 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1020 if (op->id == opid3('S','+','+')) {
1021 addop = INSTR_ADD_F;
1022 subop = INSTR_SUB_F;
1024 addop = INSTR_SUB_F;
1025 subop = INSTR_ADD_F;
1027 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1028 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1030 if (ast_istype(exprs[0], ast_entfield)) {
1031 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1033 (ast_expression*)parser_const_float_1(parser));
1035 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1037 (ast_expression*)parser_const_float_1(parser));
1041 out = (ast_expression*)ast_binary_new(ctx, subop,
1043 (ast_expression*)parser_const_float_1(parser));
1045 case opid2('+','='):
1046 case opid2('-','='):
1047 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1048 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1050 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1051 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1052 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1056 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1057 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1059 if (ast_istype(exprs[0], ast_entfield))
1060 assignop = type_storep_instr[exprs[0]->expression.vtype];
1062 assignop = type_store_instr[exprs[0]->expression.vtype];
1063 switch (exprs[0]->expression.vtype) {
1065 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1066 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1067 exprs[0], exprs[1]);
1070 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1071 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1072 exprs[0], exprs[1]);
1075 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1076 type_name[exprs[0]->expression.vtype],
1077 type_name[exprs[1]->expression.vtype]);
1081 case opid2('*','='):
1082 case opid2('/','='):
1083 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1084 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1085 exprs[0]->expression.vtype == TYPE_VECTOR))
1087 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1088 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1089 parseerror(parser, "invalid types used in expression: %s and %s",
1093 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1094 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1096 if (ast_istype(exprs[0], ast_entfield))
1097 assignop = type_storep_instr[exprs[0]->expression.vtype];
1099 assignop = type_store_instr[exprs[0]->expression.vtype];
1100 switch (exprs[0]->expression.vtype) {
1102 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1103 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1104 exprs[0], exprs[1]);
1107 if (op->id == opid2('*','=')) {
1108 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1109 exprs[0], exprs[1]);
1111 /* there's no DIV_VF */
1112 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1113 (ast_expression*)parser_const_float_1(parser),
1117 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1122 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1123 type_name[exprs[0]->expression.vtype],
1124 type_name[exprs[1]->expression.vtype]);
1128 case opid2('&','='):
1129 case opid2('|','='):
1130 if (NotSameType(TYPE_FLOAT)) {
1131 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1132 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1133 parseerror(parser, "invalid types used in expression: %s and %s",
1137 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1138 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1140 if (ast_istype(exprs[0], ast_entfield))
1141 assignop = type_storep_instr[exprs[0]->expression.vtype];
1143 assignop = type_store_instr[exprs[0]->expression.vtype];
1144 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1145 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1146 exprs[0], exprs[1]);
1148 case opid3('&','~','='):
1149 /* This is like: a &= ~(b);
1150 * But QC has no bitwise-not, so we implement it as
1153 if (NotSameType(TYPE_FLOAT)) {
1154 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1155 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1156 parseerror(parser, "invalid types used in expression: %s and %s",
1160 if (ast_istype(exprs[0], ast_entfield))
1161 assignop = type_storep_instr[exprs[0]->expression.vtype];
1163 assignop = type_store_instr[exprs[0]->expression.vtype];
1164 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1167 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1168 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1170 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1171 asbinstore->keep_dest = true;
1172 out = (ast_expression*)asbinstore;
1178 parseerror(parser, "failed to apply operand %s", op->op);
1182 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1183 vec_push(sy->out, syexp(ctx, out));
1187 static bool parser_close_call(parser_t *parser, shunt *sy)
1189 /* was a function call */
1190 ast_expression *fun;
1196 vec_shrinkby(sy->ops, 1);
1197 fid = sy->ops[vec_size(sy->ops)].off;
1199 /* out[fid] is the function
1200 * everything above is parameters...
1201 * 0 params = nothing
1202 * 1 params = ast_expression
1206 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1207 parseerror(parser, "internal error: function call needs function and parameter list...");
1211 fun = sy->out[fid].out;
1213 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1215 parseerror(parser, "out of memory");
1219 if (fid+1 == vec_size(sy->out)) {
1222 } else if (fid+2 == vec_size(sy->out)) {
1224 vec_shrinkby(sy->out, 1);
1225 params = sy->out[vec_size(sy->out)].block;
1229 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1231 paramcount = vec_size(params->exprs);
1232 call->params = params->exprs;
1233 params->exprs = NULL;
1236 if (!ast_call_check_types(call))
1239 parseerror(parser, "invalid function call");
1243 /* overwrite fid, the function, with a call */
1244 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1246 if (fun->expression.vtype != TYPE_FUNCTION) {
1247 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1251 if (!fun->expression.next) {
1252 parseerror(parser, "could not determine function return type");
1255 if (vec_size(fun->expression.params) != paramcount &&
1256 !(fun->expression.variadic &&
1257 vec_size(fun->expression.params) < paramcount))
1260 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1262 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1263 if (opts.standard == COMPILER_GMQCC)
1266 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1267 " -> `%s` has been declared here: %s:%i",
1268 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1269 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1271 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1272 " -> `%s` has been declared here: %s:%i",
1273 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1274 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1280 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1281 "too %s parameters for call to %s: expected %i, got %i\n"
1282 " -> `%s` has been declared here: %s:%i",
1283 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1284 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1286 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1287 "too %s parameters for function call: expected %i, got %i\n"
1288 " -> `%s` has been declared here: %s:%i",
1289 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1290 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1298 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1300 if (!vec_size(sy->ops)) {
1301 parseerror(parser, "unmatched closing paren");
1304 /* this would for bit a + (x) because there are no operators inside (x)
1305 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1306 parseerror(parser, "empty parenthesis expression");
1310 while (vec_size(sy->ops)) {
1311 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1312 if (!parser_close_call(parser, sy))
1316 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1317 vec_shrinkby(sy->ops, 1);
1318 return !functions_only;
1320 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1323 /* pop off the parenthesis */
1324 vec_shrinkby(sy->ops, 1);
1325 /* then apply the index operator */
1326 if (!parser_sy_apply_operator(parser, sy))
1330 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1333 if (vec_last(parser->pot) != POT_TERNARY1) {
1334 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1337 vec_last(parser->pot) = POT_TERNARY2;
1338 /* pop off the parenthesis */
1339 vec_shrinkby(sy->ops, 1);
1342 if (!parser_sy_apply_operator(parser, sy))
1348 static void parser_reclassify_token(parser_t *parser)
1351 for (i = 0; i < operator_count; ++i) {
1352 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1353 parser->tok = TOKEN_OPERATOR;
1359 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1361 ast_expression *expr = NULL;
1363 bool wantop = false;
1364 bool gotmemberof = false;
1366 /* count the parens because an if starts with one, so the
1367 * end of a condition is an unmatched closing paren
1375 parser->lex->flags.noops = false;
1377 parser_reclassify_token(parser);
1382 gotmemberof = false;
1384 parser->memberof = 0;
1386 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1387 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1389 /* a translatable string */
1393 parseerror(parser, "expected operator or end of statement, got constant");
1397 parser->lex->flags.noops = true;
1398 if (!parser_next(parser) || parser->tok != '(') {
1399 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1402 parser->lex->flags.noops = false;
1403 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1404 parseerror(parser, "expected a constant string in translatable-string extension");
1407 val = parser_const_string(parser, parser_tokval(parser), true);
1411 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1412 DEBUGSHUNTDO(con_out("push string\n"));
1414 if (!parser_next(parser) || parser->tok != ')') {
1415 parseerror(parser, "expected closing paren after translatable string");
1419 else if (parser->tok == TOKEN_IDENT)
1421 ast_expression *var;
1423 parseerror(parser, "expected operator or end of statement");
1428 if (opts.standard == COMPILER_GMQCC)
1430 if (parser->memberof == TYPE_ENTITY) {
1431 /* still get vars first since there could be a fieldpointer */
1432 var = parser_find_var(parser, parser_tokval(parser));
1434 var = parser_find_field(parser, parser_tokval(parser));
1436 else if (parser->memberof == TYPE_VECTOR)
1438 parseerror(parser, "TODO: implement effective vector member access");
1441 else if (parser->memberof) {
1442 parseerror(parser, "namespace for member not found");
1446 var = parser_find_var(parser, parser_tokval(parser));
1448 var = parser_find_var(parser, parser_tokval(parser));
1450 var = parser_find_field(parser, parser_tokval(parser));
1453 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1456 if (ast_istype(var, ast_value)) {
1457 ((ast_value*)var)->uses++;
1459 else if (ast_istype(var, ast_member)) {
1460 ast_member *mem = (ast_member*)var;
1461 if (ast_istype(mem->owner, ast_value))
1462 ((ast_value*)(mem->owner))->uses++;
1464 vec_push(sy.out, syexp(parser_ctx(parser), var));
1465 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1467 else if (parser->tok == TOKEN_FLOATCONST) {
1470 parseerror(parser, "expected operator or end of statement, got constant");
1474 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1477 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1478 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1480 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1483 parseerror(parser, "expected operator or end of statement, got constant");
1487 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1490 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1491 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1493 else if (parser->tok == TOKEN_STRINGCONST) {
1496 parseerror(parser, "expected operator or end of statement, got constant");
1500 val = parser_const_string(parser, parser_tokval(parser), false);
1503 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1504 DEBUGSHUNTDO(con_out("push string\n"));
1506 else if (parser->tok == TOKEN_VECTORCONST) {
1509 parseerror(parser, "expected operator or end of statement, got constant");
1513 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1516 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1517 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1518 parser_token(parser)->constval.v.x,
1519 parser_token(parser)->constval.v.y,
1520 parser_token(parser)->constval.v.z));
1522 else if (parser->tok == '(') {
1523 parseerror(parser, "internal error: '(' should be classified as operator");
1526 else if (parser->tok == '[') {
1527 parseerror(parser, "internal error: '[' should be classified as operator");
1530 else if (parser->tok == ')') {
1532 DEBUGSHUNTDO(con_out("do[op] )\n"));
1536 /* we do expect an operator next */
1537 /* closing an opening paren */
1538 if (!parser_close_paren(parser, &sy, false))
1540 if (vec_last(parser->pot) != POT_PAREN) {
1541 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1544 vec_pop(parser->pot);
1546 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1550 /* allowed for function calls */
1551 if (!parser_close_paren(parser, &sy, true))
1553 if (vec_last(parser->pot) != POT_PAREN) {
1554 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1557 vec_pop(parser->pot);
1561 else if (parser->tok == ']') {
1563 parseerror(parser, "operand expected");
1567 if (!parser_close_paren(parser, &sy, false))
1569 if (vec_last(parser->pot) != POT_PAREN) {
1570 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1573 vec_pop(parser->pot);
1576 else if (parser->tok == TOKEN_TYPENAME) {
1577 parseerror(parser, "unexpected typename");
1580 else if (parser->tok != TOKEN_OPERATOR) {
1582 parseerror(parser, "expected operator or end of statement");
1589 /* classify the operator */
1590 const oper_info *op;
1591 const oper_info *olast = NULL;
1593 for (o = 0; o < operator_count; ++o) {
1594 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1595 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1596 !strcmp(parser_tokval(parser), operators[o].op))
1601 if (o == operator_count) {
1602 /* no operator found... must be the end of the statement */
1605 /* found an operator */
1608 /* when declaring variables, a comma starts a new variable */
1609 if (op->id == opid1(',') && !parens && stopatcomma) {
1610 /* fixup the token */
1615 /* a colon without a pervious question mark cannot be a ternary */
1616 if (!ternaries && op->id == opid2(':','?')) {
1621 if (op->id == opid1(',')) {
1622 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1623 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1627 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1628 olast = &operators[vec_last(sy.ops).etype-1];
1631 (op->prec < olast->prec) ||
1632 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1634 if (!parser_sy_apply_operator(parser, &sy))
1636 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1637 olast = &operators[vec_last(sy.ops).etype-1];
1642 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1643 /* for gmqcc standard: open up the namespace of the previous type */
1644 ast_expression *prevex = vec_last(sy.out).out;
1646 parseerror(parser, "unexpected member operator");
1649 if (prevex->expression.vtype == TYPE_ENTITY)
1650 parser->memberof = TYPE_ENTITY;
1651 else if (prevex->expression.vtype == TYPE_VECTOR)
1652 parser->memberof = TYPE_VECTOR;
1654 parseerror(parser, "type error: type has no members");
1660 if (op->id == opid1('(')) {
1662 size_t sycount = vec_size(sy.out);
1663 DEBUGSHUNTDO(con_out("push [op] (\n"));
1664 ++parens; vec_push(parser->pot, POT_PAREN);
1665 /* we expected an operator, this is the function-call operator */
1666 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1668 ++parens; vec_push(parser->pot, POT_PAREN);
1669 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1670 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1673 } else if (op->id == opid1('[')) {
1675 parseerror(parser, "unexpected array subscript");
1678 ++parens; vec_push(parser->pot, POT_PAREN);
1679 /* push both the operator and the paren, this makes life easier */
1680 vec_push(sy.ops, syop(parser_ctx(parser), op));
1681 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1683 } else if (op->id == opid2('?',':')) {
1685 vec_push(sy.ops, syop(parser_ctx(parser), op));
1686 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1689 vec_push(parser->pot, POT_TERNARY1);
1690 } else if (op->id == opid2(':','?')) {
1691 if (!vec_size(parser->pot)) {
1692 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1695 if (vec_last(parser->pot) != POT_TERNARY1) {
1696 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1699 if (!parser_close_paren(parser, &sy, false))
1701 vec_push(sy.ops, syop(parser_ctx(parser), op));
1705 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1706 vec_push(sy.ops, syop(parser_ctx(parser), op));
1707 wantop = !!(op->flags & OP_SUFFIX);
1710 if (!parser_next(parser)) {
1713 if (parser->tok == ';' ||
1714 (!parens && parser->tok == ']'))
1720 while (vec_size(sy.ops)) {
1721 if (!parser_sy_apply_operator(parser, &sy))
1725 parser->lex->flags.noops = true;
1726 if (!vec_size(sy.out)) {
1727 parseerror(parser, "empty expression");
1730 expr = sy.out[0].out;
1733 DEBUGSHUNTDO(con_out("shunt done\n"));
1734 if (vec_size(parser->pot)) {
1735 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1738 vec_free(parser->pot);
1742 parser->lex->flags.noops = true;
1748 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1750 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1753 if (!parser_next(parser)) {
1760 static void parser_enterblock(parser_t *parser)
1762 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1763 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1764 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1765 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1766 vec_push(parser->_block_ctx, parser_ctx(parser));
1769 static bool parser_leaveblock(parser_t *parser)
1772 size_t locals, typedefs;
1774 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1775 parseerror(parser, "internal error: parser_leaveblock with no block");
1779 util_htdel(vec_last(parser->variables));
1780 vec_pop(parser->variables);
1781 if (!vec_size(parser->_blocklocals)) {
1782 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1786 locals = vec_last(parser->_blocklocals);
1787 vec_pop(parser->_blocklocals);
1788 while (vec_size(parser->_locals) != locals) {
1789 ast_expression *e = vec_last(parser->_locals);
1790 ast_value *v = (ast_value*)e;
1791 vec_pop(parser->_locals);
1792 if (ast_istype(e, ast_value) && !v->uses) {
1793 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1800 typedefs = vec_last(parser->_blocktypedefs);
1801 while (vec_size(parser->_typedefs) != typedefs) {
1802 ast_delete(vec_last(parser->_typedefs));
1803 vec_pop(parser->_typedefs);
1805 util_htdel(vec_last(parser->typedefs));
1806 vec_pop(parser->typedefs);
1808 vec_pop(parser->_block_ctx);
1812 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1814 vec_push(parser->_locals, e);
1815 util_htset(vec_last(parser->variables), name, (void*)e);
1818 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1821 ast_expression *cond, *ontrue, *onfalse = NULL;
1824 lex_ctx ctx = parser_ctx(parser);
1826 (void)block; /* not touching */
1828 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1829 if (!parser_next(parser)) {
1830 parseerror(parser, "expected condition or 'not'");
1833 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1835 if (!parser_next(parser)) {
1836 parseerror(parser, "expected condition in parenthesis");
1840 if (parser->tok != '(') {
1841 parseerror(parser, "expected 'if' condition in parenthesis");
1844 /* parse into the expression */
1845 if (!parser_next(parser)) {
1846 parseerror(parser, "expected 'if' condition after opening paren");
1849 /* parse the condition */
1850 cond = parse_expression_leave(parser, false);
1854 if (parser->tok != ')') {
1855 parseerror(parser, "expected closing paren after 'if' condition");
1859 /* parse into the 'then' branch */
1860 if (!parser_next(parser)) {
1861 parseerror(parser, "expected statement for on-true branch of 'if'");
1865 if (!parse_statement_or_block(parser, &ontrue)) {
1869 /* check for an else */
1870 if (!strcmp(parser_tokval(parser), "else")) {
1871 /* parse into the 'else' branch */
1872 if (!parser_next(parser)) {
1873 parseerror(parser, "expected on-false branch after 'else'");
1878 if (!parse_statement_or_block(parser, &onfalse)) {
1886 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1888 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1889 *out = (ast_expression*)ifthen;
1893 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1896 ast_expression *cond, *ontrue;
1898 lex_ctx ctx = parser_ctx(parser);
1900 (void)block; /* not touching */
1902 /* skip the 'while' and check for opening paren */
1903 if (!parser_next(parser) || parser->tok != '(') {
1904 parseerror(parser, "expected 'while' condition in parenthesis");
1907 /* parse into the expression */
1908 if (!parser_next(parser)) {
1909 parseerror(parser, "expected 'while' condition after opening paren");
1912 /* parse the condition */
1913 cond = parse_expression_leave(parser, false);
1917 if (parser->tok != ')') {
1918 parseerror(parser, "expected closing paren after 'while' condition");
1922 /* parse into the 'then' branch */
1923 if (!parser_next(parser)) {
1924 parseerror(parser, "expected while-loop body");
1928 if (!parse_statement_or_block(parser, &ontrue)) {
1933 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1934 *out = (ast_expression*)aloop;
1938 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1941 ast_expression *cond, *ontrue;
1943 lex_ctx ctx = parser_ctx(parser);
1945 (void)block; /* not touching */
1947 /* skip the 'do' and get the body */
1948 if (!parser_next(parser)) {
1949 parseerror(parser, "expected loop body");
1952 if (!parse_statement_or_block(parser, &ontrue))
1955 /* expect the "while" */
1956 if (parser->tok != TOKEN_KEYWORD ||
1957 strcmp(parser_tokval(parser), "while"))
1959 parseerror(parser, "expected 'while' and condition");
1964 /* skip the 'while' and check for opening paren */
1965 if (!parser_next(parser) || parser->tok != '(') {
1966 parseerror(parser, "expected 'while' condition in parenthesis");
1970 /* parse into the expression */
1971 if (!parser_next(parser)) {
1972 parseerror(parser, "expected 'while' condition after opening paren");
1976 /* parse the condition */
1977 cond = parse_expression_leave(parser, false);
1981 if (parser->tok != ')') {
1982 parseerror(parser, "expected closing paren after 'while' condition");
1988 if (!parser_next(parser) || parser->tok != ';') {
1989 parseerror(parser, "expected semicolon after condition");
1995 if (!parser_next(parser)) {
1996 parseerror(parser, "parse error");
2002 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
2003 *out = (ast_expression*)aloop;
2007 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2010 ast_expression *initexpr, *cond, *increment, *ontrue;
2014 lex_ctx ctx = parser_ctx(parser);
2016 parser_enterblock(parser);
2023 /* skip the 'while' and check for opening paren */
2024 if (!parser_next(parser) || parser->tok != '(') {
2025 parseerror(parser, "expected 'for' expressions in parenthesis");
2028 /* parse into the expression */
2029 if (!parser_next(parser)) {
2030 parseerror(parser, "expected 'for' initializer after opening paren");
2035 if (parser->tok == TOKEN_IDENT)
2036 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2038 if (typevar || parser->tok == TOKEN_TYPENAME) {
2039 if (opts.standard != COMPILER_GMQCC) {
2040 if (parsewarning(parser, WARN_EXTENSIONS,
2041 "current standard does not allow variable declarations in for-loop initializers"))
2044 if (!parse_variable(parser, block, true, CV_VAR, typevar, false))
2047 else if (parser->tok != ';')
2049 initexpr = parse_expression_leave(parser, false);
2054 /* move on to condition */
2055 if (parser->tok != ';') {
2056 parseerror(parser, "expected semicolon after for-loop initializer");
2059 if (!parser_next(parser)) {
2060 parseerror(parser, "expected for-loop condition");
2064 /* parse the condition */
2065 if (parser->tok != ';') {
2066 cond = parse_expression_leave(parser, false);
2071 /* move on to incrementor */
2072 if (parser->tok != ';') {
2073 parseerror(parser, "expected semicolon after for-loop initializer");
2076 if (!parser_next(parser)) {
2077 parseerror(parser, "expected for-loop condition");
2081 /* parse the incrementor */
2082 if (parser->tok != ')') {
2083 increment = parse_expression_leave(parser, false);
2086 if (!ast_side_effects(increment)) {
2087 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2093 if (parser->tok != ')') {
2094 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2097 /* parse into the 'then' branch */
2098 if (!parser_next(parser)) {
2099 parseerror(parser, "expected for-loop body");
2102 if (!parse_statement_or_block(parser, &ontrue))
2105 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2106 *out = (ast_expression*)aloop;
2108 if (!parser_leaveblock(parser))
2112 if (initexpr) ast_delete(initexpr);
2113 if (cond) ast_delete(cond);
2114 if (increment) ast_delete(increment);
2115 (void)!parser_leaveblock(parser);
2119 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2121 ast_expression *exp = NULL;
2122 ast_return *ret = NULL;
2123 ast_value *expected = parser->function->vtype;
2125 lex_ctx ctx = parser_ctx(parser);
2127 (void)block; /* not touching */
2129 if (!parser_next(parser)) {
2130 parseerror(parser, "expected return expression");
2134 if (parser->tok != ';') {
2135 exp = parse_expression(parser, false);
2139 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2140 parseerror(parser, "return with invalid expression");
2143 ret = ast_return_new(exp->expression.node.context, exp);
2149 if (!parser_next(parser))
2150 parseerror(parser, "parse error");
2151 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2152 if (opts.standard != COMPILER_GMQCC)
2153 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2155 parseerror(parser, "return without value");
2157 ret = ast_return_new(ctx, NULL);
2159 *out = (ast_expression*)ret;
2163 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2165 lex_ctx ctx = parser_ctx(parser);
2167 (void)block; /* not touching */
2169 if (!parser_next(parser) || parser->tok != ';') {
2170 parseerror(parser, "expected semicolon");
2174 if (!parser_next(parser))
2175 parseerror(parser, "parse error");
2177 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2181 /* returns true when it was a variable qualifier, false otherwise!
2182 * on error, cvq is set to CV_WRONG
2184 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref)
2186 bool had_const = false;
2187 bool had_var = false;
2188 bool had_noref = false;
2191 if (!strcmp(parser_tokval(parser), "const"))
2193 else if (!strcmp(parser_tokval(parser), "var"))
2195 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2197 else if (!strcmp(parser_tokval(parser), "noref"))
2199 else if (!had_const && !had_var && !had_noref) {
2204 if (!parser_next(parser))
2216 parseerror(parser, "parse error after variable qualifier");
2221 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2223 ast_expression *operand;
2226 ast_switch *switchnode;
2227 ast_switch_case swcase;
2232 lex_ctx ctx = parser_ctx(parser);
2234 (void)block; /* not touching */
2237 /* parse over the opening paren */
2238 if (!parser_next(parser) || parser->tok != '(') {
2239 parseerror(parser, "expected switch operand in parenthesis");
2243 /* parse into the expression */
2244 if (!parser_next(parser)) {
2245 parseerror(parser, "expected switch operand");
2248 /* parse the operand */
2249 operand = parse_expression_leave(parser, false);
2253 switchnode = ast_switch_new(ctx, operand);
2256 if (parser->tok != ')') {
2257 ast_delete(switchnode);
2258 parseerror(parser, "expected closing paren after 'switch' operand");
2262 /* parse over the opening paren */
2263 if (!parser_next(parser) || parser->tok != '{') {
2264 ast_delete(switchnode);
2265 parseerror(parser, "expected list of cases");
2269 if (!parser_next(parser)) {
2270 ast_delete(switchnode);
2271 parseerror(parser, "expected 'case' or 'default'");
2275 /* new block; allow some variables to be declared here */
2276 parser_enterblock(parser);
2279 if (parser->tok == TOKEN_IDENT)
2280 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2281 if (typevar || parser->tok == TOKEN_TYPENAME) {
2282 if (!parse_variable(parser, block, false, CV_NONE, typevar, false)) {
2283 ast_delete(switchnode);
2288 if (parse_var_qualifiers(parser, true, &cvq, &noref))
2290 if (cvq == CV_WRONG) {
2291 ast_delete(switchnode);
2294 if (!parse_variable(parser, block, false, cvq, NULL, noref)) {
2295 ast_delete(switchnode);
2304 while (parser->tok != '}') {
2305 ast_block *caseblock;
2307 if (parser->tok != TOKEN_KEYWORD) {
2308 ast_delete(switchnode);
2309 parseerror(parser, "expected 'case' or 'default'");
2312 if (!strcmp(parser_tokval(parser), "case")) {
2313 if (!parser_next(parser)) {
2314 ast_delete(switchnode);
2315 parseerror(parser, "expected expression for case");
2318 swcase.value = parse_expression_leave(parser, false);
2319 if (!swcase.value) {
2320 ast_delete(switchnode);
2321 parseerror(parser, "expected expression for case");
2324 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2325 opval = (ast_value*)swcase.value;
2326 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2327 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2333 else if (!strcmp(parser_tokval(parser), "default")) {
2334 swcase.value = NULL;
2335 if (!parser_next(parser)) {
2336 ast_delete(switchnode);
2337 parseerror(parser, "expected colon");
2342 /* Now the colon and body */
2343 if (parser->tok != ':') {
2344 if (swcase.value) ast_unref(swcase.value);
2345 ast_delete(switchnode);
2346 parseerror(parser, "expected colon");
2350 if (!parser_next(parser)) {
2351 if (swcase.value) ast_unref(swcase.value);
2352 ast_delete(switchnode);
2353 parseerror(parser, "expected statements or case");
2356 caseblock = ast_block_new(parser_ctx(parser));
2358 if (swcase.value) ast_unref(swcase.value);
2359 ast_delete(switchnode);
2362 swcase.code = (ast_expression*)caseblock;
2363 vec_push(switchnode->cases, swcase);
2365 ast_expression *expr;
2366 if (parser->tok == '}')
2368 if (parser->tok == TOKEN_KEYWORD) {
2369 if (!strcmp(parser_tokval(parser), "case") ||
2370 !strcmp(parser_tokval(parser), "default"))
2375 if (!parse_statement(parser, caseblock, &expr, true)) {
2376 ast_delete(switchnode);
2381 if (!ast_block_add_expr(caseblock, expr)) {
2382 ast_delete(switchnode);
2388 parser_leaveblock(parser);
2391 if (parser->tok != '}') {
2392 ast_delete(switchnode);
2393 parseerror(parser, "expected closing paren of case list");
2396 if (!parser_next(parser)) {
2397 ast_delete(switchnode);
2398 parseerror(parser, "parse error after switch");
2401 *out = (ast_expression*)switchnode;
2405 static bool parse_goto(parser_t *parser, ast_expression **out)
2410 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2411 parseerror(parser, "expected label name after `goto`");
2415 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2417 for (i = 0; i < vec_size(parser->labels); ++i) {
2418 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2419 ast_goto_set_label(gt, parser->labels[i]);
2423 if (i == vec_size(parser->labels))
2424 vec_push(parser->gotos, gt);
2426 if (!parser_next(parser) || parser->tok != ';') {
2427 parseerror(parser, "semicolon expected after goto label");
2430 if (!parser_next(parser)) {
2431 parseerror(parser, "parse error after goto");
2435 *out = (ast_expression*)gt;
2439 static bool parse_skipwhite(parser_t *parser)
2442 if (!parser_next(parser))
2444 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2445 return parser->tok < TOKEN_ERROR;
2448 static bool parse_eol(parser_t *parser)
2450 if (!parse_skipwhite(parser))
2452 return parser->tok == TOKEN_EOL;
2455 static bool parse_pragma_do(parser_t *parser)
2457 if (!parser_next(parser) ||
2458 parser->tok != TOKEN_IDENT ||
2459 strcmp(parser_tokval(parser), "pragma"))
2461 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2464 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2465 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2469 if (!strcmp(parser_tokval(parser), "noref")) {
2470 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2471 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2474 parser->noref = !!parser_token(parser)->constval.i;
2475 if (!parse_eol(parser)) {
2476 parseerror(parser, "parse error after `noref` pragma");
2482 parseerror(parser, "unrecognized hash-keyword: `%s`", parser_tokval(parser));
2489 static bool parse_pragma(parser_t *parser)
2492 parser->lex->flags.preprocessing = true;
2493 parser->lex->flags.mergelines = true;
2494 rv = parse_pragma_do(parser);
2495 if (parser->tok != TOKEN_EOL) {
2496 parseerror(parser, "junk after pragma");
2499 parser->lex->flags.preprocessing = false;
2500 parser->lex->flags.mergelines = false;
2501 if (!parser_next(parser)) {
2502 parseerror(parser, "parse error after pragma");
2508 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2512 ast_value *typevar = NULL;
2516 if (parser->tok == TOKEN_IDENT)
2517 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2519 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2521 /* local variable */
2523 parseerror(parser, "cannot declare a variable from here");
2526 if (opts.standard == COMPILER_QCC) {
2527 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2530 if (!parse_variable(parser, block, false, CV_NONE, typevar, false))
2534 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref))
2536 if (cvq == CV_WRONG)
2538 return parse_variable(parser, block, true, cvq, NULL, noref);
2540 else if (parser->tok == TOKEN_KEYWORD)
2542 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2547 if (!parser_next(parser)) {
2548 parseerror(parser, "parse error after __builtin_debug_printtype");
2552 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2554 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2555 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2556 if (!parser_next(parser)) {
2557 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2563 if (!parse_statement(parser, block, out, allow_cases))
2566 con_out("__builtin_debug_printtype: got no output node\n");
2569 ast_type_to_string(*out, ty, sizeof(ty));
2570 con_out("__builtin_debug_printtype: `%s`\n", ty);
2575 else if (!strcmp(parser_tokval(parser), "return"))
2577 return parse_return(parser, block, out);
2579 else if (!strcmp(parser_tokval(parser), "if"))
2581 return parse_if(parser, block, out);
2583 else if (!strcmp(parser_tokval(parser), "while"))
2585 return parse_while(parser, block, out);
2587 else if (!strcmp(parser_tokval(parser), "do"))
2589 return parse_dowhile(parser, block, out);
2591 else if (!strcmp(parser_tokval(parser), "for"))
2593 if (opts.standard == COMPILER_QCC) {
2594 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2597 return parse_for(parser, block, out);
2599 else if (!strcmp(parser_tokval(parser), "break"))
2601 return parse_break_continue(parser, block, out, false);
2603 else if (!strcmp(parser_tokval(parser), "continue"))
2605 return parse_break_continue(parser, block, out, true);
2607 else if (!strcmp(parser_tokval(parser), "switch"))
2609 return parse_switch(parser, block, out);
2611 else if (!strcmp(parser_tokval(parser), "case") ||
2612 !strcmp(parser_tokval(parser), "default"))
2615 parseerror(parser, "unexpected 'case' label");
2620 else if (!strcmp(parser_tokval(parser), "goto"))
2622 return parse_goto(parser, out);
2624 else if (!strcmp(parser_tokval(parser), "typedef"))
2626 if (!parser_next(parser)) {
2627 parseerror(parser, "expected type definition after 'typedef'");
2630 return parse_typedef(parser);
2632 parseerror(parser, "Unexpected keyword");
2635 else if (parser->tok == '{')
2638 inner = parse_block(parser);
2641 *out = (ast_expression*)inner;
2644 else if (parser->tok == ':')
2648 if (!parser_next(parser)) {
2649 parseerror(parser, "expected label name");
2652 if (parser->tok != TOKEN_IDENT) {
2653 parseerror(parser, "label must be an identifier");
2656 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2659 vec_push(parser->labels, label);
2660 *out = (ast_expression*)label;
2661 if (!parser_next(parser)) {
2662 parseerror(parser, "parse error after label");
2665 for (i = 0; i < vec_size(parser->gotos); ++i) {
2666 if (!strcmp(parser->gotos[i]->name, label->name)) {
2667 ast_goto_set_label(parser->gotos[i], label);
2668 vec_remove(parser->gotos, i, 1);
2674 else if (parser->tok == ';')
2676 if (!parser_next(parser)) {
2677 parseerror(parser, "parse error after empty statement");
2684 ast_expression *exp = parse_expression(parser, false);
2688 if (!ast_side_effects(exp)) {
2689 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2696 static bool parse_block_into(parser_t *parser, ast_block *block)
2700 parser_enterblock(parser);
2702 if (!parser_next(parser)) { /* skip the '{' */
2703 parseerror(parser, "expected function body");
2707 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2709 ast_expression *expr = NULL;
2710 if (parser->tok == '}')
2713 if (!parse_statement(parser, block, &expr, false)) {
2714 /* parseerror(parser, "parse error"); */
2720 if (!ast_block_add_expr(block, expr)) {
2727 if (parser->tok != '}') {
2730 (void)parser_next(parser);
2734 if (!parser_leaveblock(parser))
2736 return retval && !!block;
2739 static ast_block* parse_block(parser_t *parser)
2742 block = ast_block_new(parser_ctx(parser));
2745 if (!parse_block_into(parser, block)) {
2746 ast_block_delete(block);
2752 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2754 if (parser->tok == '{') {
2755 *out = (ast_expression*)parse_block(parser);
2758 return parse_statement(parser, NULL, out, false);
2761 static bool create_vector_members(ast_value *var, ast_member **me)
2764 size_t len = strlen(var->name);
2766 for (i = 0; i < 3; ++i) {
2767 char *name = mem_a(len+3);
2768 memcpy(name, var->name, len);
2770 name[len+1] = 'x'+i;
2772 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2781 do { ast_member_delete(me[--i]); } while(i);
2785 static bool parse_function_body(parser_t *parser, ast_value *var)
2787 ast_block *block = NULL;
2792 ast_expression *framenum = NULL;
2793 ast_expression *nextthink = NULL;
2794 /* None of the following have to be deleted */
2795 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2796 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2797 bool has_frame_think;
2801 has_frame_think = false;
2802 old = parser->function;
2804 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2805 parseerror(parser, "gotos/labels leaking");
2809 if (var->expression.variadic) {
2810 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2811 "variadic function with implementation will not be able to access additional parameters"))
2817 if (parser->tok == '[') {
2818 /* got a frame definition: [ framenum, nextthink ]
2819 * this translates to:
2820 * self.frame = framenum;
2821 * self.nextthink = time + 0.1;
2822 * self.think = nextthink;
2826 fld_think = parser_find_field(parser, "think");
2827 fld_nextthink = parser_find_field(parser, "nextthink");
2828 fld_frame = parser_find_field(parser, "frame");
2829 if (!fld_think || !fld_nextthink || !fld_frame) {
2830 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2831 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2834 gbl_time = parser_find_global(parser, "time");
2835 gbl_self = parser_find_global(parser, "self");
2836 if (!gbl_time || !gbl_self) {
2837 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2838 parseerror(parser, "please declare the following globals: `time`, `self`");
2842 if (!parser_next(parser))
2845 framenum = parse_expression_leave(parser, true);
2847 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2850 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2851 ast_unref(framenum);
2852 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2856 if (parser->tok != ',') {
2857 ast_unref(framenum);
2858 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2859 parseerror(parser, "Got a %i\n", parser->tok);
2863 if (!parser_next(parser)) {
2864 ast_unref(framenum);
2868 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2870 /* qc allows the use of not-yet-declared functions here
2871 * - this automatically creates a prototype */
2872 ast_value *thinkfunc;
2873 ast_expression *functype = fld_think->expression.next;
2875 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2876 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2877 ast_unref(framenum);
2878 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2882 if (!parser_next(parser)) {
2883 ast_unref(framenum);
2884 ast_delete(thinkfunc);
2888 vec_push(parser->globals, (ast_expression*)thinkfunc);
2889 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2890 nextthink = (ast_expression*)thinkfunc;
2893 nextthink = parse_expression_leave(parser, true);
2895 ast_unref(framenum);
2896 parseerror(parser, "expected a think-function in [frame,think] notation");
2901 if (!ast_istype(nextthink, ast_value)) {
2902 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2906 if (retval && parser->tok != ']') {
2907 parseerror(parser, "expected closing `]` for [frame,think] notation");
2911 if (retval && !parser_next(parser)) {
2915 if (retval && parser->tok != '{') {
2916 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2921 ast_unref(nextthink);
2922 ast_unref(framenum);
2926 has_frame_think = true;
2929 block = ast_block_new(parser_ctx(parser));
2931 parseerror(parser, "failed to allocate block");
2932 if (has_frame_think) {
2933 ast_unref(nextthink);
2934 ast_unref(framenum);
2939 if (has_frame_think) {
2941 ast_expression *self_frame;
2942 ast_expression *self_nextthink;
2943 ast_expression *self_think;
2944 ast_expression *time_plus_1;
2945 ast_store *store_frame;
2946 ast_store *store_nextthink;
2947 ast_store *store_think;
2949 ctx = parser_ctx(parser);
2950 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2951 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2952 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2954 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2955 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2957 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2958 if (self_frame) ast_delete(self_frame);
2959 if (self_nextthink) ast_delete(self_nextthink);
2960 if (self_think) ast_delete(self_think);
2961 if (time_plus_1) ast_delete(time_plus_1);
2967 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2968 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2969 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2972 ast_delete(self_frame);
2975 if (!store_nextthink) {
2976 ast_delete(self_nextthink);
2980 ast_delete(self_think);
2984 if (store_frame) ast_delete(store_frame);
2985 if (store_nextthink) ast_delete(store_nextthink);
2986 if (store_think) ast_delete(store_think);
2989 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
2990 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
2991 !ast_block_add_expr(block, (ast_expression*)store_think))
2998 parseerror(parser, "failed to generate code for [frame,think]");
2999 ast_unref(nextthink);
3000 ast_unref(framenum);
3006 parser_enterblock(parser);
3008 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3010 ast_value *param = var->expression.params[parami];
3013 if (param->expression.vtype != TYPE_VECTOR &&
3014 (param->expression.vtype != TYPE_FIELD ||
3015 param->expression.next->expression.vtype != TYPE_VECTOR))
3020 if (!create_vector_members(param, me)) {
3021 ast_block_delete(block);
3025 for (e = 0; e < 3; ++e) {
3026 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3027 ast_block_collect(block, (ast_expression*)me[e]);
3031 func = ast_function_new(ast_ctx(var), var->name, var);
3033 parseerror(parser, "failed to allocate function for `%s`", var->name);
3034 ast_block_delete(block);
3037 vec_push(parser->functions, func);
3039 parser->function = func;
3040 if (!parse_block_into(parser, block)) {
3041 ast_block_delete(block);
3045 vec_push(func->blocks, block);
3047 parser->function = old;
3048 if (!parser_leaveblock(parser))
3050 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3051 parseerror(parser, "internal error: local scopes left");
3055 if (parser->tok == ';')
3056 return parser_next(parser);
3057 else if (opts.standard == COMPILER_QCC)
3058 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3062 vec_pop(parser->functions);
3063 ast_function_delete(func);
3064 var->constval.vfunc = NULL;
3067 (void)!parser_leaveblock(parser);
3068 parser->function = old;
3072 static ast_expression *array_accessor_split(
3077 ast_expression *left,
3078 ast_expression *right
3084 lex_ctx ctx = ast_ctx(array);
3086 if (!left || !right) {
3087 if (left) ast_delete(left);
3088 if (right) ast_delete(right);
3092 cmp = ast_binary_new(ctx, INSTR_LT,
3093 (ast_expression*)index,
3094 (ast_expression*)parser_const_float(parser, middle));
3098 parseerror(parser, "internal error: failed to create comparison for array setter");
3102 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3104 ast_delete(cmp); /* will delete left and right */
3105 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3109 return (ast_expression*)ifthen;
3112 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3114 lex_ctx ctx = ast_ctx(array);
3116 if (from+1 == afterend) {
3117 /* set this value */
3120 ast_array_index *subscript;
3122 int assignop = type_store_instr[value->expression.vtype];
3124 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3125 assignop = INSTR_STORE_V;
3127 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3131 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3133 ast_delete(subscript);
3137 block = ast_block_new(ctx);
3143 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3148 ret = ast_return_new(ctx, NULL);
3154 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3159 return (ast_expression*)block;
3161 ast_expression *left, *right;
3162 size_t diff = afterend - from;
3163 size_t middle = from + diff/2;
3164 left = array_setter_node(parser, array, index, value, from, middle);
3165 right = array_setter_node(parser, array, index, value, middle, afterend);
3166 return array_accessor_split(parser, array, index, middle, left, right);
3170 static ast_expression *array_field_setter_node(
3179 lex_ctx ctx = ast_ctx(array);
3181 if (from+1 == afterend) {
3182 /* set this value */
3185 ast_entfield *entfield;
3186 ast_array_index *subscript;
3188 int assignop = type_storep_instr[value->expression.vtype];
3190 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3191 assignop = INSTR_STOREP_V;
3193 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3197 entfield = ast_entfield_new_force(ctx,
3198 (ast_expression*)entity,
3199 (ast_expression*)subscript,
3200 (ast_expression*)subscript);
3202 ast_delete(subscript);
3206 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3208 ast_delete(entfield);
3212 block = ast_block_new(ctx);
3218 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3223 ret = ast_return_new(ctx, NULL);
3229 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3234 return (ast_expression*)block;
3236 ast_expression *left, *right;
3237 size_t diff = afterend - from;
3238 size_t middle = from + diff/2;
3239 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3240 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3241 return array_accessor_split(parser, array, index, middle, left, right);
3245 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3247 lex_ctx ctx = ast_ctx(array);
3249 if (from+1 == afterend) {
3251 ast_array_index *subscript;
3253 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3257 ret = ast_return_new(ctx, (ast_expression*)subscript);
3259 ast_delete(subscript);
3263 return (ast_expression*)ret;
3265 ast_expression *left, *right;
3266 size_t diff = afterend - from;
3267 size_t middle = from + diff/2;
3268 left = array_getter_node(parser, array, index, from, middle);
3269 right = array_getter_node(parser, array, index, middle, afterend);
3270 return array_accessor_split(parser, array, index, middle, left, right);
3274 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3276 ast_function *func = NULL;
3277 ast_value *fval = NULL;
3278 ast_block *body = NULL;
3280 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3282 parseerror(parser, "failed to create accessor function value");
3286 func = ast_function_new(ast_ctx(array), funcname, fval);
3289 parseerror(parser, "failed to create accessor function node");
3293 body = ast_block_new(ast_ctx(array));
3295 parseerror(parser, "failed to create block for array accessor");
3301 vec_push(func->blocks, body);
3304 vec_push(parser->accessors, fval);
3309 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3311 ast_expression *root = NULL;
3312 ast_value *index = NULL;
3313 ast_value *value = NULL;
3317 if (!ast_istype(array->expression.next, ast_value)) {
3318 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3322 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3324 func = fval->constval.vfunc;
3325 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3327 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3328 value = ast_value_copy((ast_value*)array->expression.next);
3330 if (!index || !value) {
3331 parseerror(parser, "failed to create locals for array accessor");
3334 (void)!ast_value_set_name(value, "value"); /* not important */
3335 vec_push(fval->expression.params, index);
3336 vec_push(fval->expression.params, value);
3338 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3340 parseerror(parser, "failed to build accessor search tree");
3344 array->setter = fval;
3345 return ast_block_add_expr(func->blocks[0], root);
3347 if (index) ast_delete(index);
3348 if (value) ast_delete(value);
3349 if (root) ast_delete(root);
3355 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3357 ast_expression *root = NULL;
3358 ast_value *entity = NULL;
3359 ast_value *index = NULL;
3360 ast_value *value = NULL;
3364 if (!ast_istype(array->expression.next, ast_value)) {
3365 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3369 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3371 func = fval->constval.vfunc;
3372 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3374 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3375 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3376 value = ast_value_copy((ast_value*)array->expression.next);
3377 if (!entity || !index || !value) {
3378 parseerror(parser, "failed to create locals for array accessor");
3381 (void)!ast_value_set_name(value, "value"); /* not important */
3382 vec_push(fval->expression.params, entity);
3383 vec_push(fval->expression.params, index);
3384 vec_push(fval->expression.params, value);
3386 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3388 parseerror(parser, "failed to build accessor search tree");
3392 array->setter = fval;
3393 return ast_block_add_expr(func->blocks[0], root);
3395 if (entity) ast_delete(entity);
3396 if (index) ast_delete(index);
3397 if (value) ast_delete(value);
3398 if (root) ast_delete(root);
3404 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3406 ast_expression *root = NULL;
3407 ast_value *index = NULL;
3411 /* NOTE: checking array->expression.next rather than elemtype since
3412 * for fields elemtype is a temporary fieldtype.
3414 if (!ast_istype(array->expression.next, ast_value)) {
3415 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3419 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3421 func = fval->constval.vfunc;
3422 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3424 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3427 parseerror(parser, "failed to create locals for array accessor");
3430 vec_push(fval->expression.params, index);
3432 root = array_getter_node(parser, array, index, 0, array->expression.count);
3434 parseerror(parser, "failed to build accessor search tree");
3438 array->getter = fval;
3439 return ast_block_add_expr(func->blocks[0], root);
3441 if (index) ast_delete(index);
3442 if (root) ast_delete(root);
3448 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3449 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3457 bool variadic = false;
3459 ctx = parser_ctx(parser);
3461 /* for the sake of less code we parse-in in this function */
3462 if (!parser_next(parser)) {
3463 parseerror(parser, "expected parameter list");
3469 /* parse variables until we hit a closing paren */
3470 while (parser->tok != ')') {
3472 /* there must be commas between them */
3473 if (parser->tok != ',') {
3474 parseerror(parser, "expected comma or end of parameter list");
3477 if (!parser_next(parser)) {
3478 parseerror(parser, "expected parameter");
3484 if (parser->tok == TOKEN_DOTS) {
3485 /* '...' indicates a varargs function */
3487 if (!parser_next(parser)) {
3488 parseerror(parser, "expected parameter");
3491 if (parser->tok != ')') {
3492 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3498 /* for anything else just parse a typename */
3499 param = parse_typename(parser, NULL, NULL);
3502 vec_push(params, param);
3503 if (param->expression.vtype >= TYPE_VARIANT) {
3504 char typename[1024];
3505 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3506 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3512 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3516 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3517 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3520 if (!parser_next(parser)) {
3521 parseerror(parser, "parse error after typename");
3525 /* now turn 'var' into a function type */
3526 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3527 fval->expression.next = (ast_expression*)var;
3528 fval->expression.variadic = variadic;
3531 var->expression.params = params;
3538 for (i = 0; i < vec_size(params); ++i)
3539 ast_delete(params[i]);
3544 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3546 ast_expression *cexp;
3547 ast_value *cval, *tmp;
3550 ctx = parser_ctx(parser);
3552 if (!parser_next(parser)) {
3554 parseerror(parser, "expected array-size");
3558 cexp = parse_expression_leave(parser, true);
3560 if (!cexp || !ast_istype(cexp, ast_value)) {
3564 parseerror(parser, "expected array-size as constant positive integer");
3567 cval = (ast_value*)cexp;
3569 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3570 tmp->expression.next = (ast_expression*)var;
3573 if (cval->expression.vtype == TYPE_INTEGER)
3574 tmp->expression.count = cval->constval.vint;
3575 else if (cval->expression.vtype == TYPE_FLOAT)
3576 tmp->expression.count = cval->constval.vfloat;
3580 parseerror(parser, "array-size must be a positive integer constant");
3585 if (parser->tok != ']') {
3587 parseerror(parser, "expected ']' after array-size");
3590 if (!parser_next(parser)) {
3592 parseerror(parser, "error after parsing array size");
3598 /* Parse a complete typename.
3599 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3600 * but when parsing variables separated by comma
3601 * 'storebase' should point to where the base-type should be kept.
3602 * The base type makes up every bit of type information which comes *before* the
3605 * The following will be parsed in its entirety:
3607 * The 'basetype' in this case is 'void()'
3608 * and if there's a comma after it, say:
3610 * then the type-information 'void()' can be stored in 'storebase'
3612 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3614 ast_value *var, *tmp;
3617 const char *name = NULL;
3618 bool isfield = false;
3619 bool wasarray = false;
3620 size_t morefields = 0;
3622 ctx = parser_ctx(parser);
3624 /* types may start with a dot */
3625 if (parser->tok == '.') {
3627 /* if we parsed a dot we need a typename now */
3628 if (!parser_next(parser)) {
3629 parseerror(parser, "expected typename for field definition");
3633 /* Further dots are handled seperately because they won't be part of the
3636 while (parser->tok == '.') {
3638 if (!parser_next(parser)) {
3639 parseerror(parser, "expected typename for field definition");
3644 if (parser->tok == TOKEN_IDENT)
3645 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3646 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3647 parseerror(parser, "expected typename");
3651 /* generate the basic type value */
3652 if (cached_typedef) {
3653 var = ast_value_copy(cached_typedef);
3654 ast_value_set_name(var, "<type(from_def)>");
3656 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3658 for (; morefields; --morefields) {
3659 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3660 tmp->expression.next = (ast_expression*)var;
3664 /* do not yet turn into a field - remember:
3665 * .void() foo; is a field too
3666 * .void()() foo; is a function
3670 if (!parser_next(parser)) {
3672 parseerror(parser, "parse error after typename");
3676 /* an opening paren now starts the parameter-list of a function
3677 * this is where original-QC has parameter lists.
3678 * We allow a single parameter list here.
3679 * Much like fteqcc we don't allow `float()() x`
3681 if (parser->tok == '(') {
3682 var = parse_parameter_list(parser, var);
3687 /* store the base if requested */
3689 *storebase = ast_value_copy(var);
3691 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3692 tmp->expression.next = (ast_expression*)*storebase;
3697 /* there may be a name now */
3698 if (parser->tok == TOKEN_IDENT) {
3699 name = util_strdup(parser_tokval(parser));
3701 if (!parser_next(parser)) {
3703 parseerror(parser, "error after variable or field declaration");
3708 /* now this may be an array */
3709 if (parser->tok == '[') {
3711 var = parse_arraysize(parser, var);
3716 /* This is the point where we can turn it into a field */
3718 /* turn it into a field if desired */
3719 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3720 tmp->expression.next = (ast_expression*)var;
3724 /* now there may be function parens again */
3725 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3726 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3727 if (parser->tok == '(' && wasarray)
3728 parseerror(parser, "arrays as part of a return type is not supported");
3729 while (parser->tok == '(') {
3730 var = parse_parameter_list(parser, var);
3739 /* finally name it */
3741 if (!ast_value_set_name(var, name)) {
3743 parseerror(parser, "internal error: failed to set name");
3746 /* free the name, ast_value_set_name duplicates */
3753 static bool parse_typedef(parser_t *parser)
3755 ast_value *typevar, *oldtype;
3756 ast_expression *old;
3758 typevar = parse_typename(parser, NULL, NULL);
3763 if ( (old = parser_find_var(parser, typevar->name)) ) {
3764 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3765 " -> `%s` has been declared here: %s:%i",
3766 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3767 ast_delete(typevar);
3771 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3772 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3773 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3774 ast_delete(typevar);
3778 vec_push(parser->_typedefs, typevar);
3779 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3781 if (parser->tok != ';') {
3782 parseerror(parser, "expected semicolon after typedef");
3785 if (!parser_next(parser)) {
3786 parseerror(parser, "parse error after typedef");
3793 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref)
3797 ast_expression *old;
3801 ast_value *basetype = NULL;
3803 bool isparam = false;
3804 bool isvector = false;
3805 bool cleanvar = true;
3806 bool wasarray = false;
3810 /* get the first complete variable */
3811 var = parse_typename(parser, &basetype, cached_typedef);
3814 ast_delete(basetype);
3822 /* Part 0: finish the type */
3823 if (parser->tok == '(') {
3824 if (opts.standard == COMPILER_QCC)
3825 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3826 var = parse_parameter_list(parser, var);
3832 /* we only allow 1-dimensional arrays */
3833 if (parser->tok == '[') {
3835 var = parse_arraysize(parser, var);
3841 if (parser->tok == '(' && wasarray) {
3842 parseerror(parser, "arrays as part of a return type is not supported");
3843 /* we'll still parse the type completely for now */
3845 /* for functions returning functions */
3846 while (parser->tok == '(') {
3847 if (opts.standard == COMPILER_QCC)
3848 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3849 var = parse_parameter_list(parser, var);
3856 var->cvq = qualifier;
3857 /* in a noref section we simply bump the usecount */
3858 if (noref || parser->noref)
3862 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3863 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3864 * is then filled with the previous definition and the parameter-names replaced.
3867 /* Deal with end_sys_ vars */
3869 if (!strcmp(var->name, "end_sys_globals")) {
3871 parser->crc_globals = vec_size(parser->globals);
3874 else if (!strcmp(var->name, "end_sys_fields")) {
3876 parser->crc_fields = vec_size(parser->fields);
3879 if (was_end && var->expression.vtype == TYPE_FIELD) {
3880 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3881 "global '%s' hint should not be a field",
3882 parser_tokval(parser)))
3889 if (!nofields && var->expression.vtype == TYPE_FIELD)
3891 /* deal with field declarations */
3892 old = parser_find_field(parser, var->name);
3894 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3895 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3904 parseerror(parser, "field `%s` already declared here: %s:%i",
3905 var->name, ast_ctx(old).file, ast_ctx(old).line);
3910 if (opts.standard == COMPILER_QCC &&
3911 (old = parser_find_global(parser, var->name)))
3913 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3914 parseerror(parser, "field `%s` already declared here: %s:%i",
3915 var->name, ast_ctx(old).file, ast_ctx(old).line);
3922 /* deal with other globals */
3923 old = parser_find_global(parser, var->name);
3924 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3926 /* This is a function which had a prototype */
3927 if (!ast_istype(old, ast_value)) {
3928 parseerror(parser, "internal error: prototype is not an ast_value");
3932 proto = (ast_value*)old;
3933 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3934 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3936 ast_ctx(proto).file, ast_ctx(proto).line);
3940 /* we need the new parameter-names */
3941 for (i = 0; i < vec_size(proto->expression.params); ++i)
3942 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3950 if (opts.standard == COMPILER_GMQCC) {
3951 parseerror(parser, "global `%s` already declared here: %s:%i",
3952 var->name, ast_ctx(old).file, ast_ctx(old).line);
3956 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3957 "global `%s` already declared here: %s:%i",
3958 var->name, ast_ctx(old).file, ast_ctx(old).line))
3963 proto = (ast_value*)old;
3964 if (!ast_istype(old, ast_value)) {
3965 parseerror(parser, "internal error: not an ast_value");
3974 if (opts.standard == COMPILER_QCC &&
3975 (old = parser_find_field(parser, var->name)))
3977 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3978 parseerror(parser, "global `%s` already declared here: %s:%i",
3979 var->name, ast_ctx(old).file, ast_ctx(old).line);
3986 else /* it's not a global */
3988 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3989 if (old && !isparam) {
3990 parseerror(parser, "local `%s` already declared here: %s:%i",
3991 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3995 old = parser_find_local(parser, var->name, 0, &isparam);
3996 if (old && isparam) {
3997 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3998 "local `%s` is shadowing a parameter", var->name))
4000 parseerror(parser, "local `%s` already declared here: %s:%i",
4001 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4005 if (opts.standard != COMPILER_GMQCC) {
4014 * Create the global/local, and deal with vector types.
4017 if (var->expression.vtype == TYPE_VECTOR)
4019 else if (var->expression.vtype == TYPE_FIELD &&
4020 var->expression.next->expression.vtype == TYPE_VECTOR)
4024 if (!create_vector_members(var, me)) {
4031 /* deal with global variables, fields, functions */
4032 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4033 var->isfield = true;
4034 vec_push(parser->fields, (ast_expression*)var);
4035 util_htset(parser->htfields, var->name, var);
4037 for (i = 0; i < 3; ++i) {
4038 vec_push(parser->fields, (ast_expression*)me[i]);
4039 util_htset(parser->htfields, me[i]->name, me[i]);
4044 vec_push(parser->globals, (ast_expression*)var);
4045 util_htset(parser->htglobals, var->name, var);
4047 for (i = 0; i < 3; ++i) {
4048 vec_push(parser->globals, (ast_expression*)me[i]);
4049 util_htset(parser->htglobals, me[i]->name, me[i]);
4054 vec_push(localblock->locals, var);
4055 parser_addlocal(parser, var->name, (ast_expression*)var);
4057 for (i = 0; i < 3; ++i) {
4058 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4059 ast_block_collect(localblock, (ast_expression*)me[i]);
4065 me[0] = me[1] = me[2] = NULL;
4070 if (var->expression.vtype == TYPE_ARRAY) {
4072 snprintf(name, sizeof(name), "%s##SET", var->name);
4073 if (!parser_create_array_setter(parser, var, name))
4075 snprintf(name, sizeof(name), "%s##GET", var->name);
4076 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4079 else if (!localblock && !nofields &&
4080 var->expression.vtype == TYPE_FIELD &&
4081 var->expression.next->expression.vtype == TYPE_ARRAY)
4084 ast_expression *telem;
4086 ast_value *array = (ast_value*)var->expression.next;
4088 if (!ast_istype(var->expression.next, ast_value)) {
4089 parseerror(parser, "internal error: field element type must be an ast_value");
4093 snprintf(name, sizeof(name), "%s##SETF", var->name);
4094 if (!parser_create_array_field_setter(parser, array, name))
4097 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4098 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4099 tfield->expression.next = telem;
4100 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4101 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4109 if (parser->tok == ';') {
4110 ast_delete(basetype);
4111 if (!parser_next(parser)) {
4112 parseerror(parser, "error after variable declaration");
4118 if (parser->tok == ',')
4122 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4125 parseerror(parser, "missing comma or semicolon while parsing variables");
4129 if (localblock && opts.standard == COMPILER_QCC) {
4130 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4131 "initializing expression turns variable `%s` into a constant in this standard",
4138 if (parser->tok != '{') {
4139 if (parser->tok != '=') {
4140 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4144 if (!parser_next(parser)) {
4145 parseerror(parser, "error parsing initializer");
4149 else if (opts.standard == COMPILER_QCC) {
4150 parseerror(parser, "expected '=' before function body in this standard");
4153 if (parser->tok == '#') {
4154 ast_function *func = NULL;
4157 parseerror(parser, "cannot declare builtins within functions");
4160 if (var->expression.vtype != TYPE_FUNCTION) {
4161 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4164 if (!parser_next(parser)) {
4165 parseerror(parser, "expected builtin number");
4168 if (parser->tok != TOKEN_INTCONST) {
4169 parseerror(parser, "builtin number must be an integer constant");
4172 if (parser_token(parser)->constval.i < 0) {
4173 parseerror(parser, "builtin number must be an integer greater than zero");
4177 if (var->hasvalue) {
4178 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4179 "builtin `%s` has already been defined\n"
4180 " -> previous declaration here: %s:%i",
4181 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4185 func = ast_function_new(ast_ctx(var), var->name, var);
4187 parseerror(parser, "failed to allocate function for `%s`", var->name);
4190 vec_push(parser->functions, func);
4192 func->builtin = -parser_token(parser)->constval.i-1;
4195 if (!parser_next(parser)) {
4196 parseerror(parser, "expected comma or semicolon");
4198 ast_function_delete(func);
4199 var->constval.vfunc = NULL;
4203 else if (parser->tok == '{' || parser->tok == '[')
4207 parseerror(parser, "cannot declare functions within functions");
4212 ast_ctx(proto) = parser_ctx(parser);
4214 if (!parse_function_body(parser, var))
4216 ast_delete(basetype);
4217 for (i = 0; i < vec_size(parser->gotos); ++i)
4218 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4219 vec_free(parser->gotos);
4220 vec_free(parser->labels);
4223 ast_expression *cexp;
4226 cexp = parse_expression_leave(parser, true);
4231 cval = (ast_value*)cexp;
4232 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4233 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4236 if (opts.standard != COMPILER_GMQCC &&
4237 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4238 qualifier != CV_VAR)
4240 var->cvq = CV_CONST;
4242 var->hasvalue = true;
4243 if (cval->expression.vtype == TYPE_STRING)
4244 var->constval.vstring = parser_strdup(cval->constval.vstring);
4245 else if (cval->expression.vtype == TYPE_FIELD)
4246 var->constval.vfield = cval;
4248 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4253 shunt sy = { NULL, NULL };
4256 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4257 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4258 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4259 if (!parser_sy_apply_operator(parser, &sy))
4262 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4263 parseerror(parser, "internal error: leaked operands");
4264 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4274 if (parser->tok == ',') {
4275 if (!parser_next(parser)) {
4276 parseerror(parser, "expected another variable");
4280 if (parser->tok != TOKEN_IDENT) {
4281 parseerror(parser, "expected another variable");
4284 var = ast_value_copy(basetype);
4286 ast_value_set_name(var, parser_tokval(parser));
4287 if (!parser_next(parser)) {
4288 parseerror(parser, "error parsing variable declaration");
4294 if (parser->tok != ';') {
4295 parseerror(parser, "missing semicolon after variables");
4299 if (!parser_next(parser)) {
4300 parseerror(parser, "parse error after variable declaration");
4304 ast_delete(basetype);
4308 if (cleanvar && var)
4310 ast_delete(basetype);
4314 ast_delete(basetype);
4315 if (cleanvar && var)
4317 if (me[0]) ast_member_delete(me[0]);
4318 if (me[1]) ast_member_delete(me[1]);
4319 if (me[2]) ast_member_delete(me[2]);
4323 static bool parser_global_statement(parser_t *parser)
4327 ast_value *istype = NULL;
4329 if (parser->tok == TOKEN_IDENT)
4330 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4332 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4334 return parse_variable(parser, NULL, false, CV_NONE, istype, false);
4336 else if (parse_var_qualifiers(parser, false, &cvq, &noref))
4338 if (cvq == CV_WRONG)
4340 return parse_variable(parser, NULL, true, cvq, NULL, noref);
4342 else if (parser->tok == TOKEN_KEYWORD)
4344 if (!strcmp(parser_tokval(parser), "typedef")) {
4345 if (!parser_next(parser)) {
4346 parseerror(parser, "expected type definition after 'typedef'");
4349 return parse_typedef(parser);
4351 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4354 else if (parser->tok == '#')
4356 return parse_pragma(parser);
4358 else if (parser->tok == '$')
4360 if (!parser_next(parser)) {
4361 parseerror(parser, "parse error");
4367 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4373 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4375 return util_crc16(old, str, strlen(str));
4378 static void progdefs_crc_file(const char *str)
4380 /* write to progdefs.h here */
4384 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4386 old = progdefs_crc_sum(old, str);
4387 progdefs_crc_file(str);
4391 static void generate_checksum(parser_t *parser)
4393 uint16_t crc = 0xFFFF;
4397 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4398 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4400 progdefs_crc_file("\tint\tpad;\n");
4401 progdefs_crc_file("\tint\tofs_return[3];\n");
4402 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4403 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4404 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4405 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4406 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4407 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4408 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4409 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4411 for (i = 0; i < parser->crc_globals; ++i) {
4412 if (!ast_istype(parser->globals[i], ast_value))
4414 value = (ast_value*)(parser->globals[i]);
4415 switch (value->expression.vtype) {
4416 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4417 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4418 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4419 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4421 crc = progdefs_crc_both(crc, "\tint\t");
4424 crc = progdefs_crc_both(crc, value->name);
4425 crc = progdefs_crc_both(crc, ";\n");
4427 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4428 for (i = 0; i < parser->crc_fields; ++i) {
4429 if (!ast_istype(parser->fields[i], ast_value))
4431 value = (ast_value*)(parser->fields[i]);
4432 switch (value->expression.next->expression.vtype) {
4433 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4434 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4435 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4436 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4438 crc = progdefs_crc_both(crc, "\tint\t");
4441 crc = progdefs_crc_both(crc, value->name);
4442 crc = progdefs_crc_both(crc, ";\n");
4444 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4449 static parser_t *parser;
4455 parser = (parser_t*)mem_a(sizeof(parser_t));
4459 memset(parser, 0, sizeof(*parser));
4461 for (i = 0; i < operator_count; ++i) {
4462 if (operators[i].id == opid1('=')) {
4463 parser->assign_op = operators+i;
4467 if (!parser->assign_op) {
4468 printf("internal error: initializing parser: failed to find assign operator\n");
4473 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4474 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4475 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4476 vec_push(parser->_blocktypedefs, 0);
4480 bool parser_compile()
4482 /* initial lexer/parser state */
4483 parser->lex->flags.noops = true;
4485 if (parser_next(parser))
4487 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4489 if (!parser_global_statement(parser)) {
4490 if (parser->tok == TOKEN_EOF)
4491 parseerror(parser, "unexpected eof");
4492 else if (!parser->errors)
4493 parseerror(parser, "there have been errors, bailing out");
4494 lex_close(parser->lex);
4500 parseerror(parser, "parse error");
4501 lex_close(parser->lex);
4506 lex_close(parser->lex);
4509 return !parser->errors;
4512 bool parser_compile_file(const char *filename)
4514 parser->lex = lex_open(filename);
4516 con_err("failed to open file \"%s\"\n", filename);
4519 return parser_compile();
4522 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4524 parser->lex = lex_open_string(str, len, name);
4526 con_err("failed to create lexer for string \"%s\"\n", name);
4529 return parser_compile();
4532 bool parser_compile_string(const char *name, const char *str)
4534 parser->lex = lex_open_string(str, strlen(str), name);
4536 con_err("failed to create lexer for string \"%s\"\n", name);
4539 return parser_compile();
4542 void parser_cleanup()
4545 for (i = 0; i < vec_size(parser->accessors); ++i) {
4546 ast_delete(parser->accessors[i]->constval.vfunc);
4547 parser->accessors[i]->constval.vfunc = NULL;
4548 ast_delete(parser->accessors[i]);
4550 for (i = 0; i < vec_size(parser->functions); ++i) {
4551 ast_delete(parser->functions[i]);
4553 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4554 ast_delete(parser->imm_vector[i]);
4556 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4557 ast_delete(parser->imm_string[i]);
4559 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4560 ast_delete(parser->imm_float[i]);
4562 for (i = 0; i < vec_size(parser->fields); ++i) {
4563 ast_delete(parser->fields[i]);
4565 for (i = 0; i < vec_size(parser->globals); ++i) {
4566 ast_delete(parser->globals[i]);
4568 vec_free(parser->accessors);
4569 vec_free(parser->functions);
4570 vec_free(parser->imm_vector);
4571 vec_free(parser->imm_string);
4572 vec_free(parser->imm_float);
4573 vec_free(parser->globals);
4574 vec_free(parser->fields);
4576 for (i = 0; i < vec_size(parser->variables); ++i)
4577 util_htdel(parser->variables[i]);
4578 vec_free(parser->variables);
4579 vec_free(parser->_blocklocals);
4580 vec_free(parser->_locals);
4582 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4583 ast_delete(parser->_typedefs[i]);
4584 vec_free(parser->_typedefs);
4585 for (i = 0; i < vec_size(parser->typedefs); ++i)
4586 util_htdel(parser->typedefs[i]);
4587 vec_free(parser->typedefs);
4588 vec_free(parser->_blocktypedefs);
4590 vec_free(parser->_block_ctx);
4592 vec_free(parser->labels);
4593 vec_free(parser->gotos);
4598 bool parser_finish(const char *output)
4604 if (!parser->errors)
4606 ir = ir_builder_new("gmqcc_out");
4608 con_out("failed to allocate builder\n");
4612 for (i = 0; i < vec_size(parser->fields); ++i) {
4615 if (!ast_istype(parser->fields[i], ast_value))
4617 field = (ast_value*)parser->fields[i];
4618 hasvalue = field->hasvalue;
4619 field->hasvalue = false;
4620 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4621 con_out("failed to generate field %s\n", field->name);
4622 ir_builder_delete(ir);
4627 ast_expression *subtype;
4628 field->hasvalue = true;
4629 subtype = field->expression.next;
4630 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4631 if (subtype->expression.vtype == TYPE_FIELD)
4632 ifld->fieldtype = subtype->expression.next->expression.vtype;
4633 else if (subtype->expression.vtype == TYPE_FUNCTION)
4634 ifld->outtype = subtype->expression.next->expression.vtype;
4635 (void)!ir_value_set_field(field->ir_v, ifld);
4638 for (i = 0; i < vec_size(parser->globals); ++i) {
4640 if (!ast_istype(parser->globals[i], ast_value))
4642 asvalue = (ast_value*)(parser->globals[i]);
4643 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4644 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4645 "unused global: `%s`", asvalue->name);
4647 if (!ast_global_codegen(asvalue, ir, false)) {
4648 con_out("failed to generate global %s\n", asvalue->name);
4649 ir_builder_delete(ir);
4653 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4654 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4655 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4656 ir_builder_delete(ir);
4660 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4661 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4662 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4663 ir_builder_delete(ir);
4667 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4668 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4669 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4670 ir_builder_delete(ir);
4674 for (i = 0; i < vec_size(parser->globals); ++i) {
4676 if (!ast_istype(parser->globals[i], ast_value))
4678 asvalue = (ast_value*)(parser->globals[i]);
4679 if (!ast_generate_accessors(asvalue, ir)) {
4680 ir_builder_delete(ir);
4684 for (i = 0; i < vec_size(parser->fields); ++i) {
4686 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4688 if (!ast_istype((ast_expression*)asvalue, ast_value))
4690 if (asvalue->expression.vtype != TYPE_ARRAY)
4692 if (!ast_generate_accessors(asvalue, ir)) {
4693 ir_builder_delete(ir);
4697 for (i = 0; i < vec_size(parser->functions); ++i) {
4698 if (!ast_function_codegen(parser->functions[i], ir)) {
4699 con_out("failed to generate function %s\n", parser->functions[i]->name);
4700 ir_builder_delete(ir);
4705 ir_builder_dump(ir, con_out);
4706 for (i = 0; i < vec_size(parser->functions); ++i) {
4707 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4708 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4709 ir_builder_delete(ir);
4716 ir_builder_dump(ir, con_out);
4718 generate_checksum(parser);
4720 if (!ir_builder_generate(ir, output)) {
4721 con_out("*** failed to generate output file\n");
4722 ir_builder_delete(ir);
4727 ir_builder_delete(ir);
4731 con_out("*** there were compile errors\n");