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 /* beginning of locals */
30 #define PARSER_HT_LOCALS 2
32 #define PARSER_HT_SIZE 1024
33 #define TYPEDEF_HT_SIZE 16
35 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
40 ast_expression **globals;
41 ast_expression **fields;
42 ast_function **functions;
43 ast_value **imm_float;
44 ast_value **imm_string;
45 ast_value **imm_vector;
48 /* must be deleted first, they reference immediates and values */
49 ast_value **accessors;
51 ast_value *imm_float_zero;
52 ast_value *imm_float_one;
53 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 const char **continues;
69 /* A list of hashtables for each scope */
75 /* not to be used directly, we use the hash table */
76 ast_expression **_locals;
78 ast_value **_typedefs;
79 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.
101 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
103 static void parser_enterblock(parser_t *parser);
104 static bool parser_leaveblock(parser_t *parser);
105 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
106 static bool parse_typedef(parser_t *parser);
107 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static);
108 static ast_block* parse_block(parser_t *parser);
109 static bool parse_block_into(parser_t *parser, ast_block *block);
110 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
111 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
112 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
113 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
115 static void parseerror(parser_t *parser, const char *fmt, ...)
119 vcompile_error(parser->lex->tok.ctx, fmt, ap);
123 /* returns true if it counts as an error */
124 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
129 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
134 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
139 r = vcompile_warning(ctx, warntype, fmt, ap);
144 /**********************************************************************
145 * some maths used for constant folding
148 vector vec3_add(vector a, vector b)
157 vector vec3_sub(vector a, vector b)
166 qcfloat vec3_mulvv(vector a, vector b)
168 return (a.x * b.x + a.y * b.y + a.z * b.z);
171 vector vec3_mulvf(vector a, float b)
180 /**********************************************************************
184 bool parser_next(parser_t *parser)
186 /* lex_do kills the previous token */
187 parser->tok = lex_do(parser->lex);
188 if (parser->tok == TOKEN_EOF)
190 if (parser->tok >= TOKEN_ERROR) {
191 parseerror(parser, "lex error");
197 #define parser_tokval(p) ((p)->lex->tok.value)
198 #define parser_token(p) (&((p)->lex->tok))
199 #define parser_ctx(p) ((p)->lex->tok.ctx)
201 static ast_value* parser_const_float(parser_t *parser, double d)
205 for (i = 0; i < vec_size(parser->imm_float); ++i) {
206 const double compare = parser->imm_float[i]->constval.vfloat;
207 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
208 return parser->imm_float[i];
210 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
212 out->hasvalue = true;
213 out->constval.vfloat = d;
214 vec_push(parser->imm_float, out);
218 static ast_value* parser_const_float_0(parser_t *parser)
220 if (!parser->imm_float_zero)
221 parser->imm_float_zero = parser_const_float(parser, 0);
222 return parser->imm_float_zero;
225 static ast_value* parser_const_float_1(parser_t *parser)
227 if (!parser->imm_float_one)
228 parser->imm_float_one = parser_const_float(parser, 1);
229 return parser->imm_float_one;
232 static char *parser_strdup(const char *str)
235 /* actually dup empty strings */
236 char *out = (char*)mem_a(1);
240 return util_strdup(str);
243 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
247 for (i = 0; i < vec_size(parser->imm_string); ++i) {
248 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
249 return parser->imm_string[i];
253 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
254 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
256 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
258 out->hasvalue = true;
259 out->constval.vstring = parser_strdup(str);
260 vec_push(parser->imm_string, out);
264 static ast_value* parser_const_vector(parser_t *parser, vector v)
268 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
269 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
270 return parser->imm_vector[i];
272 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
274 out->hasvalue = true;
275 out->constval.vvec = v;
276 vec_push(parser->imm_vector, out);
280 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
286 return parser_const_vector(parser, v);
289 static ast_value* parser_const_vector_0(parser_t *parser)
291 if (!parser->imm_vector_zero)
292 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
293 return parser->imm_vector_zero;
296 static ast_expression* parser_find_field(parser_t *parser, const char *name)
298 return ( ast_expression*)util_htget(parser->htfields, name);
301 static ast_expression* parser_find_global(parser_t *parser, const char *name)
303 return (ast_expression*)util_htget(parser->htglobals, name);
306 static ast_expression* parser_find_param(parser_t *parser, const char *name)
310 if (!parser->function)
312 fun = parser->function->vtype;
313 for (i = 0; i < vec_size(fun->expression.params); ++i) {
314 if (!strcmp(fun->expression.params[i]->name, name))
315 return (ast_expression*)(fun->expression.params[i]);
320 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
325 hash = util_hthash(parser->htglobals, name);
328 for (i = vec_size(parser->variables); i > upto;) {
330 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
334 return parser_find_param(parser, name);
337 static ast_expression* parser_find_var(parser_t *parser, const char *name)
341 v = parser_find_local(parser, name, 0, &dummy);
342 if (!v) v = parser_find_global(parser, name);
346 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
350 hash = util_hthash(parser->typedefs[0], name);
352 for (i = vec_size(parser->typedefs); i > upto;) {
354 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
362 size_t etype; /* 0 = expression, others are operators */
366 ast_block *block; /* for commas and function calls */
375 #define SY_PAREN_EXPR '('
376 #define SY_PAREN_FUNC 'f'
377 #define SY_PAREN_INDEX '['
378 #define SY_PAREN_TERNARY '?'
380 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
391 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
395 e.out = (ast_expression*)v;
402 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
404 e.etype = 1 + (op - operators);
413 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
425 # define DEBUGSHUNTDO(x) x
427 # define DEBUGSHUNTDO(x)
430 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
431 * so we need to rotate it to become ent.(foo[n]).
433 static bool rotate_entfield_array_index_nodes(ast_expression **out)
435 ast_array_index *index;
436 ast_entfield *entfield;
440 ast_expression *entity;
442 lex_ctx ctx = ast_ctx(*out);
444 if (!ast_istype(*out, ast_array_index))
446 index = (ast_array_index*)*out;
448 if (!ast_istype(index->array, ast_entfield))
450 entfield = (ast_entfield*)index->array;
452 if (!ast_istype(entfield->field, ast_value))
454 field = (ast_value*)entfield->field;
457 entity = entfield->entity;
461 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
462 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
463 *out = (ast_expression*)entfield;
468 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
470 switch (v->expression.vtype) {
472 return !!v->constval.vfloat;
474 return !!v->constval.vint;
476 if (OPTS_FLAG(CORRECT_LOGIC))
477 return v->constval.vvec.x &&
478 v->constval.vvec.y &&
481 return !!(v->constval.vvec.x);
483 if (!v->constval.vstring)
485 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
487 return !!v->constval.vstring[0];
489 compile_error(ctx, "internal error: immediate_is_true on invalid type");
490 return !!v->constval.vfunc;
494 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
498 ast_expression *out = NULL;
499 ast_expression *exprs[3];
500 ast_block *blocks[3];
501 ast_value *asvalue[3];
502 ast_binstore *asbinstore;
503 size_t i, assignop, addop, subop;
504 qcint generated_op = 0;
509 if (!vec_size(sy->ops)) {
510 parseerror(parser, "internal error: missing operator");
514 if (vec_last(sy->ops).paren) {
515 parseerror(parser, "unmatched parenthesis");
519 op = &operators[vec_last(sy->ops).etype - 1];
520 ctx = vec_last(sy->ops).ctx;
522 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
524 if (vec_size(sy->out) < op->operands) {
525 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
526 op->op, (int)op->id);
530 vec_shrinkby(sy->ops, 1);
532 /* op(:?) has no input and no output */
536 vec_shrinkby(sy->out, op->operands);
537 for (i = 0; i < op->operands; ++i) {
538 exprs[i] = sy->out[vec_size(sy->out)+i].out;
539 blocks[i] = sy->out[vec_size(sy->out)+i].block;
540 asvalue[i] = (ast_value*)exprs[i];
543 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
544 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
548 #define NotSameType(T) \
549 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
550 exprs[0]->expression.vtype != T)
551 #define CanConstFold1(A) \
552 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
553 (A)->expression.vtype != TYPE_FUNCTION)
554 #define CanConstFold(A, B) \
555 (CanConstFold1(A) && CanConstFold1(B))
556 #define ConstV(i) (asvalue[(i)]->constval.vvec)
557 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
558 #define ConstS(i) (asvalue[(i)]->constval.vstring)
562 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
566 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
567 if (exprs[1]->expression.vtype != TYPE_FIELD) {
568 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
571 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
573 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
574 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
578 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
584 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
585 !(exprs[0]->expression.vtype == TYPE_FIELD &&
586 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
588 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
589 parseerror(parser, "cannot index value of type %s", ty1);
592 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
593 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
594 parseerror(parser, "index must be of type float, not %s", ty1);
597 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
598 if (rotate_entfield_array_index_nodes(&out))
601 /* This is not broken in fteqcc anymore */
602 if (opts.standard != COMPILER_GMQCC) {
603 /* this error doesn't need to make us bail out */
604 (void)!parsewarning(parser, WARN_EXTENSIONS,
605 "accessing array-field members of an entity without parenthesis\n"
606 " -> this is an extension from -std=gmqcc");
614 if (!ast_block_add_expr(blocks[0], exprs[1]))
617 blocks[0] = ast_block_new(ctx);
618 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
619 !ast_block_add_expr(blocks[0], exprs[1]))
624 if (!ast_block_set_type(blocks[0], exprs[1]))
627 vec_push(sy->out, syblock(ctx, blocks[0]));
634 switch (exprs[0]->expression.vtype) {
636 if (CanConstFold1(exprs[0]))
637 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
639 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
640 (ast_expression*)parser_const_float_0(parser),
644 if (CanConstFold1(exprs[0]))
645 out = (ast_expression*)parser_const_vector_f(parser,
646 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
648 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
649 (ast_expression*)parser_const_vector_0(parser),
653 parseerror(parser, "invalid types used in expression: cannot negate type %s",
654 type_name[exprs[0]->expression.vtype]);
660 switch (exprs[0]->expression.vtype) {
662 if (CanConstFold1(exprs[0]))
663 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
665 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
668 if (CanConstFold1(exprs[0]))
669 out = (ast_expression*)parser_const_float(parser,
670 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
672 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
675 if (CanConstFold1(exprs[0])) {
676 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
677 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
679 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
681 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
682 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
684 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
687 /* we don't constant-fold NOT for these types */
689 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
692 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
695 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
696 type_name[exprs[0]->expression.vtype]);
702 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
703 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
705 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
706 type_name[exprs[0]->expression.vtype],
707 type_name[exprs[1]->expression.vtype]);
710 switch (exprs[0]->expression.vtype) {
712 if (CanConstFold(exprs[0], exprs[1]))
714 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
717 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
720 if (CanConstFold(exprs[0], exprs[1]))
721 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
723 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
726 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
727 type_name[exprs[0]->expression.vtype],
728 type_name[exprs[1]->expression.vtype]);
733 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
734 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
736 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
737 type_name[exprs[1]->expression.vtype],
738 type_name[exprs[0]->expression.vtype]);
741 switch (exprs[0]->expression.vtype) {
743 if (CanConstFold(exprs[0], exprs[1]))
744 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
746 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
749 if (CanConstFold(exprs[0], exprs[1]))
750 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
752 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
755 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
756 type_name[exprs[1]->expression.vtype],
757 type_name[exprs[0]->expression.vtype]);
762 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
763 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
764 exprs[1]->expression.vtype == TYPE_FLOAT) &&
765 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
766 exprs[0]->expression.vtype == TYPE_FLOAT)
769 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
770 type_name[exprs[1]->expression.vtype],
771 type_name[exprs[0]->expression.vtype]);
774 switch (exprs[0]->expression.vtype) {
776 if (exprs[1]->expression.vtype == TYPE_VECTOR)
778 if (CanConstFold(exprs[0], exprs[1]))
779 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
781 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
785 if (CanConstFold(exprs[0], exprs[1]))
786 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
788 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
792 if (exprs[1]->expression.vtype == TYPE_FLOAT)
794 if (CanConstFold(exprs[0], exprs[1]))
795 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
797 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
801 if (CanConstFold(exprs[0], exprs[1]))
802 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
804 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
808 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
809 type_name[exprs[1]->expression.vtype],
810 type_name[exprs[0]->expression.vtype]);
815 if (NotSameType(TYPE_FLOAT)) {
816 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
817 type_name[exprs[0]->expression.vtype],
818 type_name[exprs[1]->expression.vtype]);
821 if (CanConstFold(exprs[0], exprs[1]))
822 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
824 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
828 parseerror(parser, "qc does not have a modulo operator");
832 if (NotSameType(TYPE_FLOAT)) {
833 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
834 type_name[exprs[0]->expression.vtype],
835 type_name[exprs[1]->expression.vtype]);
838 if (CanConstFold(exprs[0], exprs[1]))
839 out = (ast_expression*)parser_const_float(parser,
840 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
841 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
843 out = (ast_expression*)ast_binary_new(ctx,
844 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
848 parseerror(parser, "TODO: bitxor");
853 case opid3('<','<','='):
854 case opid3('>','>','='):
855 parseerror(parser, "TODO: shifts");
859 generated_op += 1; /* INSTR_OR */
861 generated_op += INSTR_AND;
863 if (NotSameType(TYPE_FLOAT)) {
864 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
865 type_name[exprs[0]->expression.vtype],
866 type_name[exprs[1]->expression.vtype]);
867 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
868 parseerror(parser, "TODO: optional early out");
872 if (CanConstFold(exprs[0], exprs[1]))
874 if (OPTS_FLAG(PERL_LOGIC)) {
875 if (immediate_is_true(ctx, asvalue[0]))
879 out = (ast_expression*)parser_const_float(parser,
880 ( (generated_op == INSTR_OR)
881 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
882 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
887 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
888 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
889 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
890 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
893 for (i = 0; i < 2; ++i) {
894 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
895 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
897 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
899 exprs[i] = out; out = NULL;
900 if (OPTS_FLAG(PERL_LOGIC)) {
901 /* here we want to keep the right expressions' type */
905 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
906 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
908 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
910 exprs[i] = out; out = NULL;
911 if (OPTS_FLAG(PERL_LOGIC)) {
912 /* here we want to keep the right expressions' type */
917 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
922 if (vec_last(parser->pot) != POT_TERNARY2) {
923 parseerror(parser, "mismatched parenthesis/ternary");
926 vec_pop(parser->pot);
927 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
928 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
929 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
930 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
933 if (CanConstFold1(exprs[0]))
934 out = (ConstF(0) ? exprs[1] : exprs[2]);
936 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
940 generated_op += 1; /* INSTR_GT */
942 generated_op += 1; /* INSTR_LT */
943 case opid2('>', '='):
944 generated_op += 1; /* INSTR_GE */
945 case opid2('<', '='):
946 generated_op += INSTR_LE;
947 if (NotSameType(TYPE_FLOAT)) {
948 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
949 type_name[exprs[0]->expression.vtype],
950 type_name[exprs[1]->expression.vtype]);
953 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
955 case opid2('!', '='):
956 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
957 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
958 type_name[exprs[0]->expression.vtype],
959 type_name[exprs[1]->expression.vtype]);
962 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
964 case opid2('=', '='):
965 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
966 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
967 type_name[exprs[0]->expression.vtype],
968 type_name[exprs[1]->expression.vtype]);
971 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
975 if (ast_istype(exprs[0], ast_entfield)) {
976 ast_expression *field = ((ast_entfield*)exprs[0])->field;
977 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
978 exprs[0]->expression.vtype == TYPE_FIELD &&
979 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
981 assignop = type_storep_instr[TYPE_VECTOR];
984 assignop = type_storep_instr[exprs[0]->expression.vtype];
985 if (assignop == AINSTR_END ||
986 !ast_compare_type(field->expression.next, exprs[1]))
988 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
989 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
990 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
991 field->expression.next->expression.vtype == TYPE_FUNCTION &&
992 exprs[1]->expression.vtype == TYPE_FUNCTION)
994 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
995 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
998 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1003 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1004 exprs[0]->expression.vtype == TYPE_FIELD &&
1005 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1007 assignop = type_store_instr[TYPE_VECTOR];
1010 assignop = type_store_instr[exprs[0]->expression.vtype];
1013 if (assignop == AINSTR_END) {
1014 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1015 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1016 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1018 else if (exprs[1]->expression.vtype != TYPE_NIL &&
1019 !ast_compare_type(exprs[0], exprs[1]))
1021 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1022 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1023 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1024 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1025 exprs[1]->expression.vtype == TYPE_FUNCTION)
1027 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1028 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1031 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1034 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1035 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1037 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1039 case opid3('+','+','P'):
1040 case opid3('-','-','P'):
1042 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1043 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1044 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1047 if (op->id == opid3('+','+','P'))
1048 addop = INSTR_ADD_F;
1050 addop = INSTR_SUB_F;
1051 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1052 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1054 if (ast_istype(exprs[0], ast_entfield)) {
1055 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1057 (ast_expression*)parser_const_float_1(parser));
1059 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1061 (ast_expression*)parser_const_float_1(parser));
1064 case opid3('S','+','+'):
1065 case opid3('S','-','-'):
1067 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1068 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1069 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1072 if (op->id == opid3('S','+','+')) {
1073 addop = INSTR_ADD_F;
1074 subop = INSTR_SUB_F;
1076 addop = INSTR_SUB_F;
1077 subop = INSTR_ADD_F;
1079 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1080 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1082 if (ast_istype(exprs[0], ast_entfield)) {
1083 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1085 (ast_expression*)parser_const_float_1(parser));
1087 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1089 (ast_expression*)parser_const_float_1(parser));
1093 out = (ast_expression*)ast_binary_new(ctx, subop,
1095 (ast_expression*)parser_const_float_1(parser));
1097 case opid2('+','='):
1098 case opid2('-','='):
1099 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1100 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1102 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1103 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1104 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1108 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1109 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1111 if (ast_istype(exprs[0], ast_entfield))
1112 assignop = type_storep_instr[exprs[0]->expression.vtype];
1114 assignop = type_store_instr[exprs[0]->expression.vtype];
1115 switch (exprs[0]->expression.vtype) {
1117 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1118 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1119 exprs[0], exprs[1]);
1122 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1123 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1124 exprs[0], exprs[1]);
1127 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1128 type_name[exprs[0]->expression.vtype],
1129 type_name[exprs[1]->expression.vtype]);
1133 case opid2('*','='):
1134 case opid2('/','='):
1135 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1136 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1137 exprs[0]->expression.vtype == TYPE_VECTOR))
1139 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1140 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1141 parseerror(parser, "invalid types used in expression: %s and %s",
1145 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1146 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1148 if (ast_istype(exprs[0], ast_entfield))
1149 assignop = type_storep_instr[exprs[0]->expression.vtype];
1151 assignop = type_store_instr[exprs[0]->expression.vtype];
1152 switch (exprs[0]->expression.vtype) {
1154 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1155 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1156 exprs[0], exprs[1]);
1159 if (op->id == opid2('*','=')) {
1160 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1161 exprs[0], exprs[1]);
1163 /* there's no DIV_VF */
1164 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1165 (ast_expression*)parser_const_float_1(parser),
1169 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1174 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1175 type_name[exprs[0]->expression.vtype],
1176 type_name[exprs[1]->expression.vtype]);
1180 case opid2('&','='):
1181 case opid2('|','='):
1182 if (NotSameType(TYPE_FLOAT)) {
1183 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1184 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1185 parseerror(parser, "invalid types used in expression: %s and %s",
1189 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1190 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1192 if (ast_istype(exprs[0], ast_entfield))
1193 assignop = type_storep_instr[exprs[0]->expression.vtype];
1195 assignop = type_store_instr[exprs[0]->expression.vtype];
1196 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1197 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1198 exprs[0], exprs[1]);
1200 case opid3('&','~','='):
1201 /* This is like: a &= ~(b);
1202 * But QC has no bitwise-not, so we implement it as
1205 if (NotSameType(TYPE_FLOAT)) {
1206 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1207 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1208 parseerror(parser, "invalid types used in expression: %s and %s",
1212 if (ast_istype(exprs[0], ast_entfield))
1213 assignop = type_storep_instr[exprs[0]->expression.vtype];
1215 assignop = type_store_instr[exprs[0]->expression.vtype];
1216 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1219 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1220 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1222 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1223 asbinstore->keep_dest = true;
1224 out = (ast_expression*)asbinstore;
1230 parseerror(parser, "failed to apply operand %s", op->op);
1234 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1235 vec_push(sy->out, syexp(ctx, out));
1239 static bool parser_close_call(parser_t *parser, shunt *sy)
1241 /* was a function call */
1242 ast_expression *fun;
1248 vec_shrinkby(sy->ops, 1);
1249 fid = sy->ops[vec_size(sy->ops)].off;
1251 /* out[fid] is the function
1252 * everything above is parameters...
1253 * 0 params = nothing
1254 * 1 params = ast_expression
1258 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1259 parseerror(parser, "internal error: function call needs function and parameter list...");
1263 fun = sy->out[fid].out;
1265 if (fun == intrinsic_debug_typestring) {
1267 if (fid+2 != vec_size(sy->out) ||
1268 vec_last(sy->out).block)
1270 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1273 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1274 ast_unref(vec_last(sy->out).out);
1275 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1276 (ast_expression*)parser_const_string(parser, ty, false));
1277 vec_shrinkby(sy->out, 1);
1281 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1283 parseerror(parser, "internal error: failed to create ast_call node");
1287 if (fid+1 == vec_size(sy->out)) {
1290 } else if (fid+2 == vec_size(sy->out)) {
1292 vec_shrinkby(sy->out, 1);
1293 params = sy->out[vec_size(sy->out)].block;
1297 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1299 paramcount = vec_size(params->exprs);
1300 call->params = params->exprs;
1301 params->exprs = NULL;
1304 (void)!ast_call_check_types(call);
1306 parseerror(parser, "invalid function call");
1310 /* overwrite fid, the function, with a call */
1311 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1313 if (fun->expression.vtype != TYPE_FUNCTION) {
1314 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1318 if (!fun->expression.next) {
1319 parseerror(parser, "could not determine function return type");
1322 if (vec_size(fun->expression.params) != paramcount &&
1323 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1324 vec_size(fun->expression.params) < paramcount))
1327 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1329 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1330 if (opts.standard == COMPILER_GMQCC)
1333 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1334 " -> `%s` has been declared here: %s:%i",
1335 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1336 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1338 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1339 " -> it has been declared here: %s:%i",
1340 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1341 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1347 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1348 "too %s parameters for call to %s: expected %i, got %i\n"
1349 " -> `%s` has been declared here: %s:%i",
1350 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1351 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1353 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1354 "too %s parameters for function call: expected %i, got %i\n"
1355 " -> it has been declared here: %s:%i",
1356 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1357 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1365 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1367 if (!vec_size(sy->ops)) {
1368 parseerror(parser, "unmatched closing paren");
1371 /* this would for bit a + (x) because there are no operators inside (x)
1372 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1373 parseerror(parser, "empty parenthesis expression");
1377 while (vec_size(sy->ops)) {
1378 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1379 if (!parser_close_call(parser, sy))
1383 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1384 vec_shrinkby(sy->ops, 1);
1385 return !functions_only;
1387 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1390 /* pop off the parenthesis */
1391 vec_shrinkby(sy->ops, 1);
1392 /* then apply the index operator */
1393 if (!parser_sy_apply_operator(parser, sy))
1397 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1400 if (vec_last(parser->pot) != POT_TERNARY1) {
1401 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1404 vec_last(parser->pot) = POT_TERNARY2;
1405 /* pop off the parenthesis */
1406 vec_shrinkby(sy->ops, 1);
1409 if (!parser_sy_apply_operator(parser, sy))
1415 static void parser_reclassify_token(parser_t *parser)
1418 for (i = 0; i < operator_count; ++i) {
1419 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1420 parser->tok = TOKEN_OPERATOR;
1426 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1428 ast_expression *expr = NULL;
1430 bool wantop = false;
1431 bool gotmemberof = false;
1433 /* count the parens because an if starts with one, so the
1434 * end of a condition is an unmatched closing paren
1442 parser->lex->flags.noops = false;
1444 parser_reclassify_token(parser);
1449 gotmemberof = false;
1451 parser->memberof = 0;
1453 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1454 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1456 /* a translatable string */
1460 parseerror(parser, "expected operator or end of statement, got constant");
1464 parser->lex->flags.noops = true;
1465 if (!parser_next(parser) || parser->tok != '(') {
1466 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1469 parser->lex->flags.noops = false;
1470 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1471 parseerror(parser, "expected a constant string in translatable-string extension");
1474 val = parser_const_string(parser, parser_tokval(parser), true);
1478 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1479 DEBUGSHUNTDO(con_out("push string\n"));
1481 if (!parser_next(parser) || parser->tok != ')') {
1482 parseerror(parser, "expected closing paren after translatable string");
1486 else if (parser->tok == TOKEN_IDENT)
1488 ast_expression *var;
1490 parseerror(parser, "expected operator or end of statement");
1495 if (opts.standard == COMPILER_GMQCC)
1497 if (parser->memberof == TYPE_ENTITY) {
1498 /* still get vars first since there could be a fieldpointer */
1499 var = parser_find_var(parser, parser_tokval(parser));
1501 var = parser_find_field(parser, parser_tokval(parser));
1503 else if (parser->memberof == TYPE_VECTOR)
1505 parseerror(parser, "TODO: implement effective vector member access");
1508 else if (parser->memberof) {
1509 parseerror(parser, "namespace for member not found");
1513 var = parser_find_var(parser, parser_tokval(parser));
1515 var = parser_find_var(parser, parser_tokval(parser));
1517 var = parser_find_field(parser, parser_tokval(parser));
1521 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1522 var = (ast_expression*)intrinsic_debug_typestring;
1527 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1533 if (ast_istype(var, ast_value)) {
1534 ((ast_value*)var)->uses++;
1536 else if (ast_istype(var, ast_member)) {
1537 ast_member *mem = (ast_member*)var;
1538 if (ast_istype(mem->owner, ast_value))
1539 ((ast_value*)(mem->owner))->uses++;
1542 vec_push(sy.out, syexp(parser_ctx(parser), var));
1543 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1545 else if (parser->tok == TOKEN_FLOATCONST) {
1548 parseerror(parser, "expected operator or end of statement, got constant");
1552 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1555 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1556 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1558 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1561 parseerror(parser, "expected operator or end of statement, got constant");
1565 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1568 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1569 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1571 else if (parser->tok == TOKEN_STRINGCONST) {
1574 parseerror(parser, "expected operator or end of statement, got constant");
1578 val = parser_const_string(parser, parser_tokval(parser), false);
1581 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1582 DEBUGSHUNTDO(con_out("push string\n"));
1584 else if (parser->tok == TOKEN_VECTORCONST) {
1587 parseerror(parser, "expected operator or end of statement, got constant");
1591 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1594 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1595 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1596 parser_token(parser)->constval.v.x,
1597 parser_token(parser)->constval.v.y,
1598 parser_token(parser)->constval.v.z));
1600 else if (parser->tok == '(') {
1601 parseerror(parser, "internal error: '(' should be classified as operator");
1604 else if (parser->tok == '[') {
1605 parseerror(parser, "internal error: '[' should be classified as operator");
1608 else if (parser->tok == ')') {
1610 DEBUGSHUNTDO(con_out("do[op] )\n"));
1614 /* we do expect an operator next */
1615 /* closing an opening paren */
1616 if (!parser_close_paren(parser, &sy, false))
1618 if (vec_last(parser->pot) != POT_PAREN) {
1619 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1622 vec_pop(parser->pot);
1624 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1628 /* allowed for function calls */
1629 if (!parser_close_paren(parser, &sy, true))
1631 if (vec_last(parser->pot) != POT_PAREN) {
1632 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1635 vec_pop(parser->pot);
1639 else if (parser->tok == ']') {
1641 parseerror(parser, "operand expected");
1645 if (!parser_close_paren(parser, &sy, false))
1647 if (vec_last(parser->pot) != POT_PAREN) {
1648 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1651 vec_pop(parser->pot);
1654 else if (parser->tok == TOKEN_TYPENAME) {
1655 parseerror(parser, "unexpected typename");
1658 else if (parser->tok != TOKEN_OPERATOR) {
1660 parseerror(parser, "expected operator or end of statement");
1667 /* classify the operator */
1668 const oper_info *op;
1669 const oper_info *olast = NULL;
1671 for (o = 0; o < operator_count; ++o) {
1672 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1673 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1674 !strcmp(parser_tokval(parser), operators[o].op))
1679 if (o == operator_count) {
1680 /* no operator found... must be the end of the statement */
1683 /* found an operator */
1686 /* when declaring variables, a comma starts a new variable */
1687 if (op->id == opid1(',') && !parens && stopatcomma) {
1688 /* fixup the token */
1693 /* a colon without a pervious question mark cannot be a ternary */
1694 if (!ternaries && op->id == opid2(':','?')) {
1699 if (op->id == opid1(',')) {
1700 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1701 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1705 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1706 olast = &operators[vec_last(sy.ops).etype-1];
1709 (op->prec < olast->prec) ||
1710 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1712 if (!parser_sy_apply_operator(parser, &sy))
1714 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1715 olast = &operators[vec_last(sy.ops).etype-1];
1720 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1721 /* for gmqcc standard: open up the namespace of the previous type */
1722 ast_expression *prevex = vec_last(sy.out).out;
1724 parseerror(parser, "unexpected member operator");
1727 if (prevex->expression.vtype == TYPE_ENTITY)
1728 parser->memberof = TYPE_ENTITY;
1729 else if (prevex->expression.vtype == TYPE_VECTOR)
1730 parser->memberof = TYPE_VECTOR;
1732 parseerror(parser, "type error: type has no members");
1738 if (op->id == opid1('(')) {
1740 size_t sycount = vec_size(sy.out);
1741 DEBUGSHUNTDO(con_out("push [op] (\n"));
1742 ++parens; vec_push(parser->pot, POT_PAREN);
1743 /* we expected an operator, this is the function-call operator */
1744 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1746 ++parens; vec_push(parser->pot, POT_PAREN);
1747 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1748 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1751 } else if (op->id == opid1('[')) {
1753 parseerror(parser, "unexpected array subscript");
1756 ++parens; vec_push(parser->pot, POT_PAREN);
1757 /* push both the operator and the paren, this makes life easier */
1758 vec_push(sy.ops, syop(parser_ctx(parser), op));
1759 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1761 } else if (op->id == opid2('?',':')) {
1762 vec_push(sy.ops, syop(parser_ctx(parser), op));
1763 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1766 vec_push(parser->pot, POT_TERNARY1);
1767 } else if (op->id == opid2(':','?')) {
1768 if (!vec_size(parser->pot)) {
1769 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1772 if (vec_last(parser->pot) != POT_TERNARY1) {
1773 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1776 if (!parser_close_paren(parser, &sy, false))
1778 vec_push(sy.ops, syop(parser_ctx(parser), op));
1782 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1783 vec_push(sy.ops, syop(parser_ctx(parser), op));
1784 wantop = !!(op->flags & OP_SUFFIX);
1787 if (!parser_next(parser)) {
1790 if (parser->tok == ';' ||
1791 (!parens && parser->tok == ']'))
1797 while (vec_size(sy.ops)) {
1798 if (!parser_sy_apply_operator(parser, &sy))
1802 parser->lex->flags.noops = true;
1803 if (!vec_size(sy.out)) {
1804 parseerror(parser, "empty expression");
1807 expr = sy.out[0].out;
1810 DEBUGSHUNTDO(con_out("shunt done\n"));
1811 if (vec_size(parser->pot)) {
1812 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1815 vec_free(parser->pot);
1819 parser->lex->flags.noops = true;
1825 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1827 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1830 if (!parser_next(parser)) {
1837 static void parser_enterblock(parser_t *parser)
1839 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1840 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1841 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1842 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1843 vec_push(parser->_block_ctx, parser_ctx(parser));
1846 static bool parser_leaveblock(parser_t *parser)
1849 size_t locals, typedefs;
1851 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1852 parseerror(parser, "internal error: parser_leaveblock with no block");
1856 util_htdel(vec_last(parser->variables));
1857 vec_pop(parser->variables);
1858 if (!vec_size(parser->_blocklocals)) {
1859 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1863 locals = vec_last(parser->_blocklocals);
1864 vec_pop(parser->_blocklocals);
1865 while (vec_size(parser->_locals) != locals) {
1866 ast_expression *e = vec_last(parser->_locals);
1867 ast_value *v = (ast_value*)e;
1868 vec_pop(parser->_locals);
1869 if (ast_istype(e, ast_value) && !v->uses) {
1870 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1875 typedefs = vec_last(parser->_blocktypedefs);
1876 while (vec_size(parser->_typedefs) != typedefs) {
1877 ast_delete(vec_last(parser->_typedefs));
1878 vec_pop(parser->_typedefs);
1880 util_htdel(vec_last(parser->typedefs));
1881 vec_pop(parser->typedefs);
1883 vec_pop(parser->_block_ctx);
1887 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1889 vec_push(parser->_locals, e);
1890 util_htset(vec_last(parser->variables), name, (void*)e);
1893 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1897 ast_expression *prev;
1899 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1902 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1905 parseerror(parser, "internal error: failed to process condition");
1910 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1912 /* vector types need to be cast to true booleans */
1913 ast_binary *bin = (ast_binary*)cond;
1914 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1916 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1918 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1921 parseerror(parser, "internal error: failed to process condition");
1928 unary = (ast_unary*)cond;
1929 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1931 cond = unary->operand;
1932 unary->operand = NULL;
1935 unary = (ast_unary*)cond;
1939 parseerror(parser, "internal error: failed to process condition");
1941 if (ifnot) *_ifnot = !*_ifnot;
1945 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1948 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1951 lex_ctx ctx = parser_ctx(parser);
1953 (void)block; /* not touching */
1955 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1956 if (!parser_next(parser)) {
1957 parseerror(parser, "expected condition or 'not'");
1960 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1962 if (!parser_next(parser)) {
1963 parseerror(parser, "expected condition in parenthesis");
1967 if (parser->tok != '(') {
1968 parseerror(parser, "expected 'if' condition in parenthesis");
1971 /* parse into the expression */
1972 if (!parser_next(parser)) {
1973 parseerror(parser, "expected 'if' 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 'if' condition");
1986 /* parse into the 'then' branch */
1987 if (!parser_next(parser)) {
1988 parseerror(parser, "expected statement for on-true branch of 'if'");
1992 if (!parse_statement_or_block(parser, &ontrue)) {
1996 /* check for an else */
1997 if (!strcmp(parser_tokval(parser), "else")) {
1998 /* parse into the 'else' branch */
1999 if (!parser_next(parser)) {
2000 parseerror(parser, "expected on-false branch after 'else'");
2005 if (!parse_statement_or_block(parser, &onfalse)) {
2012 cond = process_condition(parser, cond, &ifnot);
2014 if (ontrue) ast_delete(ontrue);
2015 if (onfalse) ast_delete(onfalse);
2020 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2022 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2023 *out = (ast_expression*)ifthen;
2027 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2028 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2033 /* skip the 'while' and get the body */
2034 if (!parser_next(parser)) {
2035 if (OPTS_FLAG(LOOP_LABELS))
2036 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2038 parseerror(parser, "expected 'while' condition in parenthesis");
2042 if (parser->tok == ':') {
2043 if (!OPTS_FLAG(LOOP_LABELS))
2044 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2045 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2046 parseerror(parser, "expected loop label");
2049 label = util_strdup(parser_tokval(parser));
2050 if (!parser_next(parser)) {
2052 parseerror(parser, "expected 'while' condition in parenthesis");
2057 if (parser->tok != '(') {
2058 parseerror(parser, "expected 'while' condition in parenthesis");
2062 vec_push(parser->breaks, label);
2063 vec_push(parser->continues, label);
2065 rv = parse_while_go(parser, block, out);
2068 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2069 parseerror(parser, "internal error: label stack corrupted");
2075 vec_pop(parser->breaks);
2076 vec_pop(parser->continues);
2081 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2084 ast_expression *cond, *ontrue;
2088 lex_ctx ctx = parser_ctx(parser);
2090 (void)block; /* not touching */
2092 /* parse into the expression */
2093 if (!parser_next(parser)) {
2094 parseerror(parser, "expected 'while' condition after opening paren");
2097 /* parse the condition */
2098 cond = parse_expression_leave(parser, false);
2102 if (parser->tok != ')') {
2103 parseerror(parser, "expected closing paren after 'while' condition");
2107 /* parse into the 'then' branch */
2108 if (!parser_next(parser)) {
2109 parseerror(parser, "expected while-loop body");
2113 if (!parse_statement_or_block(parser, &ontrue)) {
2118 cond = process_condition(parser, cond, &ifnot);
2123 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2124 *out = (ast_expression*)aloop;
2128 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2129 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2134 /* skip the 'do' and get the body */
2135 if (!parser_next(parser)) {
2136 if (OPTS_FLAG(LOOP_LABELS))
2137 parseerror(parser, "expected loop label or body");
2139 parseerror(parser, "expected loop body");
2143 if (parser->tok == ':') {
2144 if (!OPTS_FLAG(LOOP_LABELS))
2145 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2146 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2147 parseerror(parser, "expected loop label");
2150 label = util_strdup(parser_tokval(parser));
2151 if (!parser_next(parser)) {
2153 parseerror(parser, "expected loop body");
2158 vec_push(parser->breaks, label);
2159 vec_push(parser->continues, label);
2161 rv = parse_dowhile_go(parser, block, out);
2164 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2165 parseerror(parser, "internal error: label stack corrupted");
2171 vec_pop(parser->breaks);
2172 vec_pop(parser->continues);
2177 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2180 ast_expression *cond, *ontrue;
2184 lex_ctx ctx = parser_ctx(parser);
2186 (void)block; /* not touching */
2188 if (!parse_statement_or_block(parser, &ontrue))
2191 /* expect the "while" */
2192 if (parser->tok != TOKEN_KEYWORD ||
2193 strcmp(parser_tokval(parser), "while"))
2195 parseerror(parser, "expected 'while' and condition");
2200 /* skip the 'while' and check for opening paren */
2201 if (!parser_next(parser) || parser->tok != '(') {
2202 parseerror(parser, "expected 'while' condition in parenthesis");
2206 /* parse into the expression */
2207 if (!parser_next(parser)) {
2208 parseerror(parser, "expected 'while' condition after opening paren");
2212 /* parse the condition */
2213 cond = parse_expression_leave(parser, false);
2217 if (parser->tok != ')') {
2218 parseerror(parser, "expected closing paren after 'while' condition");
2224 if (!parser_next(parser) || parser->tok != ';') {
2225 parseerror(parser, "expected semicolon after condition");
2231 if (!parser_next(parser)) {
2232 parseerror(parser, "parse error");
2238 cond = process_condition(parser, cond, &ifnot);
2243 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2244 *out = (ast_expression*)aloop;
2248 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2249 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2254 /* skip the 'for' and check for opening paren */
2255 if (!parser_next(parser)) {
2256 if (OPTS_FLAG(LOOP_LABELS))
2257 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2259 parseerror(parser, "expected 'for' expressions in parenthesis");
2263 if (parser->tok == ':') {
2264 if (!OPTS_FLAG(LOOP_LABELS))
2265 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2266 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2267 parseerror(parser, "expected loop label");
2270 label = util_strdup(parser_tokval(parser));
2271 if (!parser_next(parser)) {
2273 parseerror(parser, "expected 'for' expressions in parenthesis");
2278 if (parser->tok != '(') {
2279 parseerror(parser, "expected 'for' expressions in parenthesis");
2283 vec_push(parser->breaks, label);
2284 vec_push(parser->continues, label);
2286 rv = parse_for_go(parser, block, out);
2289 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2290 parseerror(parser, "internal error: label stack corrupted");
2296 vec_pop(parser->breaks);
2297 vec_pop(parser->continues);
2301 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2304 ast_expression *initexpr, *cond, *increment, *ontrue;
2310 lex_ctx ctx = parser_ctx(parser);
2312 parser_enterblock(parser);
2319 /* parse into the expression */
2320 if (!parser_next(parser)) {
2321 parseerror(parser, "expected 'for' initializer after opening paren");
2326 if (parser->tok == TOKEN_IDENT)
2327 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2329 if (typevar || parser->tok == TOKEN_TYPENAME) {
2330 if (opts.standard != COMPILER_GMQCC) {
2331 if (parsewarning(parser, WARN_EXTENSIONS,
2332 "current standard does not allow variable declarations in for-loop initializers"))
2335 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, false))
2338 else if (parser->tok != ';')
2340 initexpr = parse_expression_leave(parser, false);
2345 /* move on to condition */
2346 if (parser->tok != ';') {
2347 parseerror(parser, "expected semicolon after for-loop initializer");
2350 if (!parser_next(parser)) {
2351 parseerror(parser, "expected for-loop condition");
2355 /* parse the condition */
2356 if (parser->tok != ';') {
2357 cond = parse_expression_leave(parser, false);
2362 /* move on to incrementor */
2363 if (parser->tok != ';') {
2364 parseerror(parser, "expected semicolon after for-loop initializer");
2367 if (!parser_next(parser)) {
2368 parseerror(parser, "expected for-loop condition");
2372 /* parse the incrementor */
2373 if (parser->tok != ')') {
2374 increment = parse_expression_leave(parser, false);
2377 if (!ast_side_effects(increment)) {
2378 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2384 if (parser->tok != ')') {
2385 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2388 /* parse into the 'then' branch */
2389 if (!parser_next(parser)) {
2390 parseerror(parser, "expected for-loop body");
2393 if (!parse_statement_or_block(parser, &ontrue))
2397 cond = process_condition(parser, cond, &ifnot);
2401 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2402 *out = (ast_expression*)aloop;
2404 if (!parser_leaveblock(parser))
2408 if (initexpr) ast_delete(initexpr);
2409 if (cond) ast_delete(cond);
2410 if (increment) ast_delete(increment);
2411 (void)!parser_leaveblock(parser);
2415 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2417 ast_expression *exp = NULL;
2418 ast_return *ret = NULL;
2419 ast_value *expected = parser->function->vtype;
2421 lex_ctx ctx = parser_ctx(parser);
2423 (void)block; /* not touching */
2425 if (!parser_next(parser)) {
2426 parseerror(parser, "expected return expression");
2430 if (parser->tok != ';') {
2431 exp = parse_expression(parser, false);
2435 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2436 parseerror(parser, "return with invalid expression");
2439 ret = ast_return_new(ctx, exp);
2445 if (!parser_next(parser))
2446 parseerror(parser, "parse error");
2447 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2448 if (opts.standard != COMPILER_GMQCC)
2449 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2451 parseerror(parser, "return without value");
2453 ret = ast_return_new(ctx, NULL);
2455 *out = (ast_expression*)ret;
2459 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2462 unsigned int levels = 0;
2463 lex_ctx ctx = parser_ctx(parser);
2464 const char **loops = (is_continue ? parser->continues : parser->breaks);
2466 (void)block; /* not touching */
2467 if (!parser_next(parser)) {
2468 parseerror(parser, "expected semicolon or loop label");
2472 if (parser->tok == TOKEN_IDENT) {
2473 if (!OPTS_FLAG(LOOP_LABELS))
2474 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2475 i = vec_size(loops);
2477 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2480 parseerror(parser, "no such loop to %s: `%s`",
2481 (is_continue ? "continue" : "break out of"),
2482 parser_tokval(parser));
2487 if (!parser_next(parser)) {
2488 parseerror(parser, "expected semicolon");
2493 if (parser->tok != ';') {
2494 parseerror(parser, "expected semicolon");
2498 if (!parser_next(parser))
2499 parseerror(parser, "parse error");
2501 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2505 /* returns true when it was a variable qualifier, false otherwise!
2506 * on error, cvq is set to CV_WRONG
2508 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn, bool *is_static)
2510 bool had_const = false;
2511 bool had_var = false;
2512 bool had_noref = false;
2513 bool had_noreturn = false;
2514 bool had_attrib = false;
2515 bool had_static = false;
2519 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2521 /* parse an attribute */
2522 if (!parser_next(parser)) {
2523 parseerror(parser, "expected attribute after `[[`");
2527 if (!strcmp(parser_tokval(parser), "noreturn")) {
2528 had_noreturn = true;
2529 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2530 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2535 else if (!strcmp(parser_tokval(parser), "noref")) {
2537 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2538 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2545 /* Skip tokens until we hit a ]] */
2546 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2547 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2548 if (!parser_next(parser)) {
2549 parseerror(parser, "error inside attribute");
2556 else if (!strcmp(parser_tokval(parser), "static"))
2558 else if (!strcmp(parser_tokval(parser), "const"))
2560 else if (!strcmp(parser_tokval(parser), "var"))
2562 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2564 else if (!strcmp(parser_tokval(parser), "noref"))
2566 else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2571 if (!parser_next(parser))
2581 *noreturn = had_noreturn;
2582 *is_static = had_static;
2585 parseerror(parser, "parse error after variable qualifier");
2590 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2591 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2596 /* skip the 'while' and get the body */
2597 if (!parser_next(parser)) {
2598 if (OPTS_FLAG(LOOP_LABELS))
2599 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2601 parseerror(parser, "expected 'switch' operand in parenthesis");
2605 if (parser->tok == ':') {
2606 if (!OPTS_FLAG(LOOP_LABELS))
2607 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2608 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2609 parseerror(parser, "expected loop label");
2612 label = util_strdup(parser_tokval(parser));
2613 if (!parser_next(parser)) {
2615 parseerror(parser, "expected 'switch' operand in parenthesis");
2620 if (parser->tok != '(') {
2621 parseerror(parser, "expected 'switch' operand in parenthesis");
2625 vec_push(parser->breaks, label);
2627 rv = parse_switch_go(parser, block, out);
2630 if (vec_last(parser->breaks) != label) {
2631 parseerror(parser, "internal error: label stack corrupted");
2637 vec_pop(parser->breaks);
2642 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2644 ast_expression *operand;
2647 ast_switch *switchnode;
2648 ast_switch_case swcase;
2651 bool noref, noreturn, is_static;
2653 lex_ctx ctx = parser_ctx(parser);
2655 (void)block; /* not touching */
2658 /* parse into the expression */
2659 if (!parser_next(parser)) {
2660 parseerror(parser, "expected switch operand");
2663 /* parse the operand */
2664 operand = parse_expression_leave(parser, false);
2668 switchnode = ast_switch_new(ctx, operand);
2671 if (parser->tok != ')') {
2672 ast_delete(switchnode);
2673 parseerror(parser, "expected closing paren after 'switch' operand");
2677 /* parse over the opening paren */
2678 if (!parser_next(parser) || parser->tok != '{') {
2679 ast_delete(switchnode);
2680 parseerror(parser, "expected list of cases");
2684 if (!parser_next(parser)) {
2685 ast_delete(switchnode);
2686 parseerror(parser, "expected 'case' or 'default'");
2690 /* new block; allow some variables to be declared here */
2691 parser_enterblock(parser);
2694 if (parser->tok == TOKEN_IDENT)
2695 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2696 if (typevar || parser->tok == TOKEN_TYPENAME) {
2697 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2698 ast_delete(switchnode);
2703 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2705 if (cvq == CV_WRONG) {
2706 ast_delete(switchnode);
2709 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2710 ast_delete(switchnode);
2719 while (parser->tok != '}') {
2720 ast_block *caseblock;
2722 if (!strcmp(parser_tokval(parser), "case")) {
2723 if (!parser_next(parser)) {
2724 ast_delete(switchnode);
2725 parseerror(parser, "expected expression for case");
2728 swcase.value = parse_expression_leave(parser, false);
2729 if (!swcase.value) {
2730 ast_delete(switchnode);
2731 parseerror(parser, "expected expression for case");
2734 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2735 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2736 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2742 else if (!strcmp(parser_tokval(parser), "default")) {
2743 swcase.value = NULL;
2744 if (!parser_next(parser)) {
2745 ast_delete(switchnode);
2746 parseerror(parser, "expected colon");
2751 ast_delete(switchnode);
2752 parseerror(parser, "expected 'case' or 'default'");
2756 /* Now the colon and body */
2757 if (parser->tok != ':') {
2758 if (swcase.value) ast_unref(swcase.value);
2759 ast_delete(switchnode);
2760 parseerror(parser, "expected colon");
2764 if (!parser_next(parser)) {
2765 if (swcase.value) ast_unref(swcase.value);
2766 ast_delete(switchnode);
2767 parseerror(parser, "expected statements or case");
2770 caseblock = ast_block_new(parser_ctx(parser));
2772 if (swcase.value) ast_unref(swcase.value);
2773 ast_delete(switchnode);
2776 swcase.code = (ast_expression*)caseblock;
2777 vec_push(switchnode->cases, swcase);
2779 ast_expression *expr;
2780 if (parser->tok == '}')
2782 if (parser->tok == TOKEN_KEYWORD) {
2783 if (!strcmp(parser_tokval(parser), "case") ||
2784 !strcmp(parser_tokval(parser), "default"))
2789 if (!parse_statement(parser, caseblock, &expr, true)) {
2790 ast_delete(switchnode);
2795 if (!ast_block_add_expr(caseblock, expr)) {
2796 ast_delete(switchnode);
2802 parser_leaveblock(parser);
2805 if (parser->tok != '}') {
2806 ast_delete(switchnode);
2807 parseerror(parser, "expected closing paren of case list");
2810 if (!parser_next(parser)) {
2811 ast_delete(switchnode);
2812 parseerror(parser, "parse error after switch");
2815 *out = (ast_expression*)switchnode;
2819 static bool parse_goto(parser_t *parser, ast_expression **out)
2824 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2825 parseerror(parser, "expected label name after `goto`");
2829 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2831 for (i = 0; i < vec_size(parser->labels); ++i) {
2832 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2833 ast_goto_set_label(gt, parser->labels[i]);
2837 if (i == vec_size(parser->labels))
2838 vec_push(parser->gotos, gt);
2840 if (!parser_next(parser) || parser->tok != ';') {
2841 parseerror(parser, "semicolon expected after goto label");
2844 if (!parser_next(parser)) {
2845 parseerror(parser, "parse error after goto");
2849 *out = (ast_expression*)gt;
2853 static bool parse_skipwhite(parser_t *parser)
2856 if (!parser_next(parser))
2858 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2859 return parser->tok < TOKEN_ERROR;
2862 static bool parse_eol(parser_t *parser)
2864 if (!parse_skipwhite(parser))
2866 return parser->tok == TOKEN_EOL;
2869 static bool parse_pragma_do(parser_t *parser)
2871 if (!parser_next(parser) ||
2872 parser->tok != TOKEN_IDENT ||
2873 strcmp(parser_tokval(parser), "pragma"))
2875 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2878 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2879 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2883 if (!strcmp(parser_tokval(parser), "noref")) {
2884 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2885 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2888 parser->noref = !!parser_token(parser)->constval.i;
2889 if (!parse_eol(parser)) {
2890 parseerror(parser, "parse error after `noref` pragma");
2896 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2903 static bool parse_pragma(parser_t *parser)
2906 parser->lex->flags.preprocessing = true;
2907 parser->lex->flags.mergelines = true;
2908 rv = parse_pragma_do(parser);
2909 if (parser->tok != TOKEN_EOL) {
2910 parseerror(parser, "junk after pragma");
2913 parser->lex->flags.preprocessing = false;
2914 parser->lex->flags.mergelines = false;
2915 if (!parser_next(parser)) {
2916 parseerror(parser, "parse error after pragma");
2922 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2924 bool noref, noreturn, is_static;
2926 ast_value *typevar = NULL;
2930 if (parser->tok == TOKEN_IDENT)
2931 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2933 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2935 /* local variable */
2937 parseerror(parser, "cannot declare a variable from here");
2940 if (opts.standard == COMPILER_QCC) {
2941 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2944 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2948 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2950 if (cvq == CV_WRONG)
2952 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2954 else if (parser->tok == TOKEN_KEYWORD)
2956 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2961 if (!parser_next(parser)) {
2962 parseerror(parser, "parse error after __builtin_debug_printtype");
2966 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2968 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2969 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2970 if (!parser_next(parser)) {
2971 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2977 if (!parse_statement(parser, block, out, allow_cases))
2980 con_out("__builtin_debug_printtype: got no output node\n");
2983 ast_type_to_string(*out, ty, sizeof(ty));
2984 con_out("__builtin_debug_printtype: `%s`\n", ty);
2989 else if (!strcmp(parser_tokval(parser), "return"))
2991 return parse_return(parser, block, out);
2993 else if (!strcmp(parser_tokval(parser), "if"))
2995 return parse_if(parser, block, out);
2997 else if (!strcmp(parser_tokval(parser), "while"))
2999 return parse_while(parser, block, out);
3001 else if (!strcmp(parser_tokval(parser), "do"))
3003 return parse_dowhile(parser, block, out);
3005 else if (!strcmp(parser_tokval(parser), "for"))
3007 if (opts.standard == COMPILER_QCC) {
3008 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3011 return parse_for(parser, block, out);
3013 else if (!strcmp(parser_tokval(parser), "break"))
3015 return parse_break_continue(parser, block, out, false);
3017 else if (!strcmp(parser_tokval(parser), "continue"))
3019 return parse_break_continue(parser, block, out, true);
3021 else if (!strcmp(parser_tokval(parser), "switch"))
3023 return parse_switch(parser, block, out);
3025 else if (!strcmp(parser_tokval(parser), "case") ||
3026 !strcmp(parser_tokval(parser), "default"))
3029 parseerror(parser, "unexpected 'case' label");
3034 else if (!strcmp(parser_tokval(parser), "goto"))
3036 return parse_goto(parser, out);
3038 else if (!strcmp(parser_tokval(parser), "typedef"))
3040 if (!parser_next(parser)) {
3041 parseerror(parser, "expected type definition after 'typedef'");
3044 return parse_typedef(parser);
3046 parseerror(parser, "Unexpected keyword");
3049 else if (parser->tok == '{')
3052 inner = parse_block(parser);
3055 *out = (ast_expression*)inner;
3058 else if (parser->tok == ':')
3062 if (!parser_next(parser)) {
3063 parseerror(parser, "expected label name");
3066 if (parser->tok != TOKEN_IDENT) {
3067 parseerror(parser, "label must be an identifier");
3070 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3073 vec_push(parser->labels, label);
3074 *out = (ast_expression*)label;
3075 if (!parser_next(parser)) {
3076 parseerror(parser, "parse error after label");
3079 for (i = 0; i < vec_size(parser->gotos); ++i) {
3080 if (!strcmp(parser->gotos[i]->name, label->name)) {
3081 ast_goto_set_label(parser->gotos[i], label);
3082 vec_remove(parser->gotos, i, 1);
3088 else if (parser->tok == ';')
3090 if (!parser_next(parser)) {
3091 parseerror(parser, "parse error after empty statement");
3098 ast_expression *exp = parse_expression(parser, false);
3102 if (!ast_side_effects(exp)) {
3103 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3110 static bool parse_block_into(parser_t *parser, ast_block *block)
3114 parser_enterblock(parser);
3116 if (!parser_next(parser)) { /* skip the '{' */
3117 parseerror(parser, "expected function body");
3121 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3123 ast_expression *expr = NULL;
3124 if (parser->tok == '}')
3127 if (!parse_statement(parser, block, &expr, false)) {
3128 /* parseerror(parser, "parse error"); */
3134 if (!ast_block_add_expr(block, expr)) {
3141 if (parser->tok != '}') {
3144 (void)parser_next(parser);
3148 if (!parser_leaveblock(parser))
3150 return retval && !!block;
3153 static ast_block* parse_block(parser_t *parser)
3156 block = ast_block_new(parser_ctx(parser));
3159 if (!parse_block_into(parser, block)) {
3160 ast_block_delete(block);
3166 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3168 if (parser->tok == '{') {
3169 *out = (ast_expression*)parse_block(parser);
3172 return parse_statement(parser, NULL, out, false);
3175 static bool create_vector_members(ast_value *var, ast_member **me)
3178 size_t len = strlen(var->name);
3180 for (i = 0; i < 3; ++i) {
3181 char *name = (char*)mem_a(len+3);
3182 memcpy(name, var->name, len);
3184 name[len+1] = 'x'+i;
3186 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3195 do { ast_member_delete(me[--i]); } while(i);
3199 static bool parse_function_body(parser_t *parser, ast_value *var)
3201 ast_block *block = NULL;
3206 ast_expression *framenum = NULL;
3207 ast_expression *nextthink = NULL;
3208 /* None of the following have to be deleted */
3209 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3210 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3211 bool has_frame_think;
3215 has_frame_think = false;
3216 old = parser->function;
3218 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3219 parseerror(parser, "gotos/labels leaking");
3223 if (var->expression.flags & AST_FLAG_VARIADIC) {
3224 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3225 "variadic function with implementation will not be able to access additional parameters"))
3231 if (parser->tok == '[') {
3232 /* got a frame definition: [ framenum, nextthink ]
3233 * this translates to:
3234 * self.frame = framenum;
3235 * self.nextthink = time + 0.1;
3236 * self.think = nextthink;
3240 fld_think = parser_find_field(parser, "think");
3241 fld_nextthink = parser_find_field(parser, "nextthink");
3242 fld_frame = parser_find_field(parser, "frame");
3243 if (!fld_think || !fld_nextthink || !fld_frame) {
3244 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3245 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3248 gbl_time = parser_find_global(parser, "time");
3249 gbl_self = parser_find_global(parser, "self");
3250 if (!gbl_time || !gbl_self) {
3251 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3252 parseerror(parser, "please declare the following globals: `time`, `self`");
3256 if (!parser_next(parser))
3259 framenum = parse_expression_leave(parser, true);
3261 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3264 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3265 ast_unref(framenum);
3266 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3270 if (parser->tok != ',') {
3271 ast_unref(framenum);
3272 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3273 parseerror(parser, "Got a %i\n", parser->tok);
3277 if (!parser_next(parser)) {
3278 ast_unref(framenum);
3282 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3284 /* qc allows the use of not-yet-declared functions here
3285 * - this automatically creates a prototype */
3286 ast_value *thinkfunc;
3287 ast_expression *functype = fld_think->expression.next;
3289 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3290 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3291 ast_unref(framenum);
3292 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3296 if (!parser_next(parser)) {
3297 ast_unref(framenum);
3298 ast_delete(thinkfunc);
3302 vec_push(parser->globals, (ast_expression*)thinkfunc);
3303 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3304 nextthink = (ast_expression*)thinkfunc;
3307 nextthink = parse_expression_leave(parser, true);
3309 ast_unref(framenum);
3310 parseerror(parser, "expected a think-function in [frame,think] notation");
3315 if (!ast_istype(nextthink, ast_value)) {
3316 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3320 if (retval && parser->tok != ']') {
3321 parseerror(parser, "expected closing `]` for [frame,think] notation");
3325 if (retval && !parser_next(parser)) {
3329 if (retval && parser->tok != '{') {
3330 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3335 ast_unref(nextthink);
3336 ast_unref(framenum);
3340 has_frame_think = true;
3343 block = ast_block_new(parser_ctx(parser));
3345 parseerror(parser, "failed to allocate block");
3346 if (has_frame_think) {
3347 ast_unref(nextthink);
3348 ast_unref(framenum);
3353 if (has_frame_think) {
3355 ast_expression *self_frame;
3356 ast_expression *self_nextthink;
3357 ast_expression *self_think;
3358 ast_expression *time_plus_1;
3359 ast_store *store_frame;
3360 ast_store *store_nextthink;
3361 ast_store *store_think;
3363 ctx = parser_ctx(parser);
3364 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3365 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3366 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3368 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3369 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3371 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3372 if (self_frame) ast_delete(self_frame);
3373 if (self_nextthink) ast_delete(self_nextthink);
3374 if (self_think) ast_delete(self_think);
3375 if (time_plus_1) ast_delete(time_plus_1);
3381 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3382 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3383 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3386 ast_delete(self_frame);
3389 if (!store_nextthink) {
3390 ast_delete(self_nextthink);
3394 ast_delete(self_think);
3398 if (store_frame) ast_delete(store_frame);
3399 if (store_nextthink) ast_delete(store_nextthink);
3400 if (store_think) ast_delete(store_think);
3403 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3404 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3405 !ast_block_add_expr(block, (ast_expression*)store_think))
3412 parseerror(parser, "failed to generate code for [frame,think]");
3413 ast_unref(nextthink);
3414 ast_unref(framenum);
3420 parser_enterblock(parser);
3422 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3424 ast_value *param = var->expression.params[parami];
3427 if (param->expression.vtype != TYPE_VECTOR &&
3428 (param->expression.vtype != TYPE_FIELD ||
3429 param->expression.next->expression.vtype != TYPE_VECTOR))
3434 if (!create_vector_members(param, me)) {
3435 ast_block_delete(block);
3439 for (e = 0; e < 3; ++e) {
3440 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3441 ast_block_collect(block, (ast_expression*)me[e]);
3445 func = ast_function_new(ast_ctx(var), var->name, var);
3447 parseerror(parser, "failed to allocate function for `%s`", var->name);
3448 ast_block_delete(block);
3451 vec_push(parser->functions, func);
3453 parser->function = func;
3454 if (!parse_block_into(parser, block)) {
3455 ast_block_delete(block);
3459 vec_push(func->blocks, block);
3461 parser->function = old;
3462 if (!parser_leaveblock(parser))
3464 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3465 parseerror(parser, "internal error: local scopes left");
3469 if (parser->tok == ';')
3470 return parser_next(parser);
3471 else if (opts.standard == COMPILER_QCC)
3472 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3476 vec_pop(parser->functions);
3477 ast_function_delete(func);
3478 var->constval.vfunc = NULL;
3481 (void)!parser_leaveblock(parser);
3482 parser->function = old;
3486 static ast_expression *array_accessor_split(
3491 ast_expression *left,
3492 ast_expression *right
3498 lex_ctx ctx = ast_ctx(array);
3500 if (!left || !right) {
3501 if (left) ast_delete(left);
3502 if (right) ast_delete(right);
3506 cmp = ast_binary_new(ctx, INSTR_LT,
3507 (ast_expression*)index,
3508 (ast_expression*)parser_const_float(parser, middle));
3512 parseerror(parser, "internal error: failed to create comparison for array setter");
3516 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3518 ast_delete(cmp); /* will delete left and right */
3519 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3523 return (ast_expression*)ifthen;
3526 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3528 lex_ctx ctx = ast_ctx(array);
3530 if (from+1 == afterend) {
3531 /* set this value */
3534 ast_array_index *subscript;
3536 int assignop = type_store_instr[value->expression.vtype];
3538 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3539 assignop = INSTR_STORE_V;
3541 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3545 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3547 ast_delete(subscript);
3551 block = ast_block_new(ctx);
3557 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3562 ret = ast_return_new(ctx, NULL);
3568 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3573 return (ast_expression*)block;
3575 ast_expression *left, *right;
3576 size_t diff = afterend - from;
3577 size_t middle = from + diff/2;
3578 left = array_setter_node(parser, array, index, value, from, middle);
3579 right = array_setter_node(parser, array, index, value, middle, afterend);
3580 return array_accessor_split(parser, array, index, middle, left, right);
3584 static ast_expression *array_field_setter_node(
3593 lex_ctx ctx = ast_ctx(array);
3595 if (from+1 == afterend) {
3596 /* set this value */
3599 ast_entfield *entfield;
3600 ast_array_index *subscript;
3602 int assignop = type_storep_instr[value->expression.vtype];
3604 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3605 assignop = INSTR_STOREP_V;
3607 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3611 entfield = ast_entfield_new_force(ctx,
3612 (ast_expression*)entity,
3613 (ast_expression*)subscript,
3614 (ast_expression*)subscript);
3616 ast_delete(subscript);
3620 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3622 ast_delete(entfield);
3626 block = ast_block_new(ctx);
3632 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3637 ret = ast_return_new(ctx, NULL);
3643 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3648 return (ast_expression*)block;
3650 ast_expression *left, *right;
3651 size_t diff = afterend - from;
3652 size_t middle = from + diff/2;
3653 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3654 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3655 return array_accessor_split(parser, array, index, middle, left, right);
3659 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3661 lex_ctx ctx = ast_ctx(array);
3663 if (from+1 == afterend) {
3665 ast_array_index *subscript;
3667 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3671 ret = ast_return_new(ctx, (ast_expression*)subscript);
3673 ast_delete(subscript);
3677 return (ast_expression*)ret;
3679 ast_expression *left, *right;
3680 size_t diff = afterend - from;
3681 size_t middle = from + diff/2;
3682 left = array_getter_node(parser, array, index, from, middle);
3683 right = array_getter_node(parser, array, index, middle, afterend);
3684 return array_accessor_split(parser, array, index, middle, left, right);
3688 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3690 ast_function *func = NULL;
3691 ast_value *fval = NULL;
3692 ast_block *body = NULL;
3694 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3696 parseerror(parser, "failed to create accessor function value");
3700 func = ast_function_new(ast_ctx(array), funcname, fval);
3703 parseerror(parser, "failed to create accessor function node");
3707 body = ast_block_new(ast_ctx(array));
3709 parseerror(parser, "failed to create block for array accessor");
3715 vec_push(func->blocks, body);
3718 vec_push(parser->accessors, fval);
3723 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3725 ast_expression *root = NULL;
3726 ast_value *index = NULL;
3727 ast_value *value = NULL;
3731 if (!ast_istype(array->expression.next, ast_value)) {
3732 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3736 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3738 func = fval->constval.vfunc;
3739 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3741 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3742 value = ast_value_copy((ast_value*)array->expression.next);
3744 if (!index || !value) {
3745 parseerror(parser, "failed to create locals for array accessor");
3748 (void)!ast_value_set_name(value, "value"); /* not important */
3749 vec_push(fval->expression.params, index);
3750 vec_push(fval->expression.params, value);
3752 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3754 parseerror(parser, "failed to build accessor search tree");
3758 array->setter = fval;
3759 return ast_block_add_expr(func->blocks[0], root);
3761 if (index) ast_delete(index);
3762 if (value) ast_delete(value);
3763 if (root) ast_delete(root);
3769 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3771 ast_expression *root = NULL;
3772 ast_value *entity = NULL;
3773 ast_value *index = NULL;
3774 ast_value *value = NULL;
3778 if (!ast_istype(array->expression.next, ast_value)) {
3779 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3783 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3785 func = fval->constval.vfunc;
3786 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3788 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3789 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3790 value = ast_value_copy((ast_value*)array->expression.next);
3791 if (!entity || !index || !value) {
3792 parseerror(parser, "failed to create locals for array accessor");
3795 (void)!ast_value_set_name(value, "value"); /* not important */
3796 vec_push(fval->expression.params, entity);
3797 vec_push(fval->expression.params, index);
3798 vec_push(fval->expression.params, value);
3800 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3802 parseerror(parser, "failed to build accessor search tree");
3806 array->setter = fval;
3807 return ast_block_add_expr(func->blocks[0], root);
3809 if (entity) ast_delete(entity);
3810 if (index) ast_delete(index);
3811 if (value) ast_delete(value);
3812 if (root) ast_delete(root);
3818 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3820 ast_expression *root = NULL;
3821 ast_value *index = NULL;
3825 /* NOTE: checking array->expression.next rather than elemtype since
3826 * for fields elemtype is a temporary fieldtype.
3828 if (!ast_istype(array->expression.next, ast_value)) {
3829 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3833 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3835 func = fval->constval.vfunc;
3836 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3838 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3841 parseerror(parser, "failed to create locals for array accessor");
3844 vec_push(fval->expression.params, index);
3846 root = array_getter_node(parser, array, index, 0, array->expression.count);
3848 parseerror(parser, "failed to build accessor search tree");
3852 array->getter = fval;
3853 return ast_block_add_expr(func->blocks[0], root);
3855 if (index) ast_delete(index);
3856 if (root) ast_delete(root);
3862 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3863 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3871 bool variadic = false;
3873 ctx = parser_ctx(parser);
3875 /* for the sake of less code we parse-in in this function */
3876 if (!parser_next(parser)) {
3877 parseerror(parser, "expected parameter list");
3883 /* parse variables until we hit a closing paren */
3884 while (parser->tok != ')') {
3886 /* there must be commas between them */
3887 if (parser->tok != ',') {
3888 parseerror(parser, "expected comma or end of parameter list");
3891 if (!parser_next(parser)) {
3892 parseerror(parser, "expected parameter");
3898 if (parser->tok == TOKEN_DOTS) {
3899 /* '...' indicates a varargs function */
3901 if (!parser_next(parser)) {
3902 parseerror(parser, "expected parameter");
3905 if (parser->tok != ')') {
3906 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3912 /* for anything else just parse a typename */
3913 param = parse_typename(parser, NULL, NULL);
3916 vec_push(params, param);
3917 if (param->expression.vtype >= TYPE_VARIANT) {
3918 char tname[1024]; /* typename is reserved in C++ */
3919 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3920 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3926 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3930 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3931 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3934 if (!parser_next(parser)) {
3935 parseerror(parser, "parse error after typename");
3939 /* now turn 'var' into a function type */
3940 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3941 fval->expression.next = (ast_expression*)var;
3943 fval->expression.flags |= AST_FLAG_VARIADIC;
3946 var->expression.params = params;
3953 for (i = 0; i < vec_size(params); ++i)
3954 ast_delete(params[i]);
3959 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3961 ast_expression *cexp;
3962 ast_value *cval, *tmp;
3965 ctx = parser_ctx(parser);
3967 if (!parser_next(parser)) {
3969 parseerror(parser, "expected array-size");
3973 cexp = parse_expression_leave(parser, true);
3975 if (!cexp || !ast_istype(cexp, ast_value)) {
3979 parseerror(parser, "expected array-size as constant positive integer");
3982 cval = (ast_value*)cexp;
3984 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3985 tmp->expression.next = (ast_expression*)var;
3988 if (cval->expression.vtype == TYPE_INTEGER)
3989 tmp->expression.count = cval->constval.vint;
3990 else if (cval->expression.vtype == TYPE_FLOAT)
3991 tmp->expression.count = cval->constval.vfloat;
3995 parseerror(parser, "array-size must be a positive integer constant");
4000 if (parser->tok != ']') {
4002 parseerror(parser, "expected ']' after array-size");
4005 if (!parser_next(parser)) {
4007 parseerror(parser, "error after parsing array size");
4013 /* Parse a complete typename.
4014 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4015 * but when parsing variables separated by comma
4016 * 'storebase' should point to where the base-type should be kept.
4017 * The base type makes up every bit of type information which comes *before* the
4020 * The following will be parsed in its entirety:
4022 * The 'basetype' in this case is 'void()'
4023 * and if there's a comma after it, say:
4025 * then the type-information 'void()' can be stored in 'storebase'
4027 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4029 ast_value *var, *tmp;
4032 const char *name = NULL;
4033 bool isfield = false;
4034 bool wasarray = false;
4035 size_t morefields = 0;
4037 ctx = parser_ctx(parser);
4039 /* types may start with a dot */
4040 if (parser->tok == '.') {
4042 /* if we parsed a dot we need a typename now */
4043 if (!parser_next(parser)) {
4044 parseerror(parser, "expected typename for field definition");
4048 /* Further dots are handled seperately because they won't be part of the
4051 while (parser->tok == '.') {
4053 if (!parser_next(parser)) {
4054 parseerror(parser, "expected typename for field definition");
4059 if (parser->tok == TOKEN_IDENT)
4060 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4061 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4062 parseerror(parser, "expected typename");
4066 /* generate the basic type value */
4067 if (cached_typedef) {
4068 var = ast_value_copy(cached_typedef);
4069 ast_value_set_name(var, "<type(from_def)>");
4071 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4073 for (; morefields; --morefields) {
4074 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4075 tmp->expression.next = (ast_expression*)var;
4079 /* do not yet turn into a field - remember:
4080 * .void() foo; is a field too
4081 * .void()() foo; is a function
4085 if (!parser_next(parser)) {
4087 parseerror(parser, "parse error after typename");
4091 /* an opening paren now starts the parameter-list of a function
4092 * this is where original-QC has parameter lists.
4093 * We allow a single parameter list here.
4094 * Much like fteqcc we don't allow `float()() x`
4096 if (parser->tok == '(') {
4097 var = parse_parameter_list(parser, var);
4102 /* store the base if requested */
4104 *storebase = ast_value_copy(var);
4106 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4107 tmp->expression.next = (ast_expression*)*storebase;
4112 /* there may be a name now */
4113 if (parser->tok == TOKEN_IDENT) {
4114 name = util_strdup(parser_tokval(parser));
4116 if (!parser_next(parser)) {
4118 parseerror(parser, "error after variable or field declaration");
4123 /* now this may be an array */
4124 if (parser->tok == '[') {
4126 var = parse_arraysize(parser, var);
4131 /* This is the point where we can turn it into a field */
4133 /* turn it into a field if desired */
4134 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4135 tmp->expression.next = (ast_expression*)var;
4139 /* now there may be function parens again */
4140 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4141 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4142 if (parser->tok == '(' && wasarray)
4143 parseerror(parser, "arrays as part of a return type is not supported");
4144 while (parser->tok == '(') {
4145 var = parse_parameter_list(parser, var);
4154 /* finally name it */
4156 if (!ast_value_set_name(var, name)) {
4158 parseerror(parser, "internal error: failed to set name");
4161 /* free the name, ast_value_set_name duplicates */
4168 static bool parse_typedef(parser_t *parser)
4170 ast_value *typevar, *oldtype;
4171 ast_expression *old;
4173 typevar = parse_typename(parser, NULL, NULL);
4178 if ( (old = parser_find_var(parser, typevar->name)) ) {
4179 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4180 " -> `%s` has been declared here: %s:%i",
4181 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4182 ast_delete(typevar);
4186 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4187 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4188 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4189 ast_delete(typevar);
4193 vec_push(parser->_typedefs, typevar);
4194 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4196 if (parser->tok != ';') {
4197 parseerror(parser, "expected semicolon after typedef");
4200 if (!parser_next(parser)) {
4201 parseerror(parser, "parse error after typedef");
4208 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static)
4212 ast_expression *old;
4216 ast_value *basetype = NULL;
4218 bool isparam = false;
4219 bool isvector = false;
4220 bool cleanvar = true;
4221 bool wasarray = false;
4225 if (!localblock && is_static)
4226 parseerror(parser, "`static` qualifier is not supported in global scope");
4228 /* get the first complete variable */
4229 var = parse_typename(parser, &basetype, cached_typedef);
4232 ast_delete(basetype);
4240 /* Part 0: finish the type */
4241 if (parser->tok == '(') {
4242 if (opts.standard == COMPILER_QCC)
4243 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4244 var = parse_parameter_list(parser, var);
4250 /* we only allow 1-dimensional arrays */
4251 if (parser->tok == '[') {
4253 var = parse_arraysize(parser, var);
4259 if (parser->tok == '(' && wasarray) {
4260 parseerror(parser, "arrays as part of a return type is not supported");
4261 /* we'll still parse the type completely for now */
4263 /* for functions returning functions */
4264 while (parser->tok == '(') {
4265 if (opts.standard == COMPILER_QCC)
4266 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4267 var = parse_parameter_list(parser, var);
4274 var->cvq = qualifier;
4275 /* in a noref section we simply bump the usecount */
4276 if (noref || parser->noref)
4279 var->expression.flags |= AST_FLAG_NORETURN;
4282 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4283 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4284 * is then filled with the previous definition and the parameter-names replaced.
4286 if (!strcmp(var->name, "nil")) {
4287 if (OPTS_FLAG(UNTYPED_NIL)) {
4288 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4289 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4291 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4294 /* Deal with end_sys_ vars */
4296 if (!strcmp(var->name, "end_sys_globals")) {
4298 parser->crc_globals = vec_size(parser->globals);
4301 else if (!strcmp(var->name, "end_sys_fields")) {
4303 parser->crc_fields = vec_size(parser->fields);
4306 if (was_end && var->expression.vtype == TYPE_FIELD) {
4307 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4308 "global '%s' hint should not be a field",
4309 parser_tokval(parser)))
4316 if (!nofields && var->expression.vtype == TYPE_FIELD)
4318 /* deal with field declarations */
4319 old = parser_find_field(parser, var->name);
4321 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4322 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4331 parseerror(parser, "field `%s` already declared here: %s:%i",
4332 var->name, ast_ctx(old).file, ast_ctx(old).line);
4337 if (opts.standard == COMPILER_QCC &&
4338 (old = parser_find_global(parser, var->name)))
4340 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4341 parseerror(parser, "field `%s` already declared here: %s:%i",
4342 var->name, ast_ctx(old).file, ast_ctx(old).line);
4349 /* deal with other globals */
4350 old = parser_find_global(parser, var->name);
4351 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4353 /* This is a function which had a prototype */
4354 if (!ast_istype(old, ast_value)) {
4355 parseerror(parser, "internal error: prototype is not an ast_value");
4359 proto = (ast_value*)old;
4360 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4361 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4363 ast_ctx(proto).file, ast_ctx(proto).line);
4367 /* we need the new parameter-names */
4368 for (i = 0; i < vec_size(proto->expression.params); ++i)
4369 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4377 if (opts.standard == COMPILER_GMQCC) {
4378 parseerror(parser, "global `%s` already declared here: %s:%i",
4379 var->name, ast_ctx(old).file, ast_ctx(old).line);
4383 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4384 "global `%s` already declared here: %s:%i",
4385 var->name, ast_ctx(old).file, ast_ctx(old).line))
4390 proto = (ast_value*)old;
4391 if (!ast_istype(old, ast_value)) {
4392 parseerror(parser, "internal error: not an ast_value");
4401 if (opts.standard == COMPILER_QCC &&
4402 (old = parser_find_field(parser, var->name)))
4404 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4405 parseerror(parser, "global `%s` already declared here: %s:%i",
4406 var->name, ast_ctx(old).file, ast_ctx(old).line);
4413 else /* it's not a global */
4415 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4416 if (old && !isparam) {
4417 parseerror(parser, "local `%s` already declared here: %s:%i",
4418 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4422 old = parser_find_local(parser, var->name, 0, &isparam);
4423 if (old && isparam) {
4424 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4425 "local `%s` is shadowing a parameter", var->name))
4427 parseerror(parser, "local `%s` already declared here: %s:%i",
4428 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4432 if (opts.standard != COMPILER_GMQCC) {
4441 * Create the global/local, and deal with vector types.
4444 if (var->expression.vtype == TYPE_VECTOR)
4446 else if (var->expression.vtype == TYPE_FIELD &&
4447 var->expression.next->expression.vtype == TYPE_VECTOR)
4451 if (!create_vector_members(var, me)) {
4458 /* deal with global variables, fields, functions */
4459 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4460 var->isfield = true;
4461 vec_push(parser->fields, (ast_expression*)var);
4462 util_htset(parser->htfields, var->name, var);
4464 for (i = 0; i < 3; ++i) {
4465 vec_push(parser->fields, (ast_expression*)me[i]);
4466 util_htset(parser->htfields, me[i]->name, me[i]);
4471 vec_push(parser->globals, (ast_expression*)var);
4472 util_htset(parser->htglobals, var->name, var);
4474 for (i = 0; i < 3; ++i) {
4475 vec_push(parser->globals, (ast_expression*)me[i]);
4476 util_htset(parser->htglobals, me[i]->name, me[i]);
4482 /* a static adds itself to be generated like any other global
4483 * but is added to the local namespace instead
4485 char *defname = NULL;
4486 size_t prefix_len, ln;
4488 ln = strlen(parser->function->name);
4489 vec_append(defname, ln, parser->function->name);
4491 vec_append(defname, 2, "::");
4492 /* remember the length up to here */
4493 prefix_len = vec_size(defname);
4495 /* Add it to the local scope */
4496 util_htset(vec_last(parser->variables), var->name, (void*)var);
4497 /* now rename the global */
4498 ln = strlen(var->name);
4499 vec_append(defname, ln, var->name);
4500 ast_value_set_name(var, defname);
4502 /* push it to the to-be-generated globals */
4503 vec_push(parser->globals, (ast_expression*)var);
4505 /* same game for the vector members */
4507 for (i = 0; i < 3; ++i) {
4508 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4510 vec_shrinkto(defname, prefix_len);
4511 ln = strlen(me[i]->name);
4512 vec_append(defname, ln, me[i]->name);
4513 ast_member_set_name(me[i], defname);
4515 vec_push(parser->globals, (ast_expression*)me[i]);
4520 vec_push(localblock->locals, var);
4521 parser_addlocal(parser, var->name, (ast_expression*)var);
4523 for (i = 0; i < 3; ++i) {
4524 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4525 ast_block_collect(localblock, (ast_expression*)me[i]);
4531 me[0] = me[1] = me[2] = NULL;
4536 if (var->expression.vtype == TYPE_ARRAY) {
4538 snprintf(name, sizeof(name), "%s##SET", var->name);
4539 if (!parser_create_array_setter(parser, var, name))
4541 snprintf(name, sizeof(name), "%s##GET", var->name);
4542 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4545 else if (!localblock && !nofields &&
4546 var->expression.vtype == TYPE_FIELD &&
4547 var->expression.next->expression.vtype == TYPE_ARRAY)
4550 ast_expression *telem;
4552 ast_value *array = (ast_value*)var->expression.next;
4554 if (!ast_istype(var->expression.next, ast_value)) {
4555 parseerror(parser, "internal error: field element type must be an ast_value");
4559 snprintf(name, sizeof(name), "%s##SETF", var->name);
4560 if (!parser_create_array_field_setter(parser, array, name))
4563 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4564 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4565 tfield->expression.next = telem;
4566 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4567 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4575 if (parser->tok == ';') {
4576 ast_delete(basetype);
4577 if (!parser_next(parser)) {
4578 parseerror(parser, "error after variable declaration");
4584 if (parser->tok == ',')
4588 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4591 parseerror(parser, "missing comma or semicolon while parsing variables");
4595 if (localblock && opts.standard == COMPILER_QCC) {
4596 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4597 "initializing expression turns variable `%s` into a constant in this standard",
4604 if (parser->tok != '{') {
4605 if (parser->tok != '=') {
4606 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4610 if (!parser_next(parser)) {
4611 parseerror(parser, "error parsing initializer");
4615 else if (opts.standard == COMPILER_QCC) {
4616 parseerror(parser, "expected '=' before function body in this standard");
4619 if (parser->tok == '#') {
4620 ast_function *func = NULL;
4623 parseerror(parser, "cannot declare builtins within functions");
4626 if (var->expression.vtype != TYPE_FUNCTION) {
4627 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4630 if (!parser_next(parser)) {
4631 parseerror(parser, "expected builtin number");
4634 if (parser->tok != TOKEN_INTCONST) {
4635 parseerror(parser, "builtin number must be an integer constant");
4638 if (parser_token(parser)->constval.i < 0) {
4639 parseerror(parser, "builtin number must be an integer greater than zero");
4643 if (var->hasvalue) {
4644 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4645 "builtin `%s` has already been defined\n"
4646 " -> previous declaration here: %s:%i",
4647 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4651 func = ast_function_new(ast_ctx(var), var->name, var);
4653 parseerror(parser, "failed to allocate function for `%s`", var->name);
4656 vec_push(parser->functions, func);
4658 func->builtin = -parser_token(parser)->constval.i-1;
4661 if (!parser_next(parser)) {
4662 parseerror(parser, "expected comma or semicolon");
4664 ast_function_delete(func);
4665 var->constval.vfunc = NULL;
4669 else if (parser->tok == '{' || parser->tok == '[')
4672 parseerror(parser, "cannot declare functions within functions");
4677 ast_ctx(proto) = parser_ctx(parser);
4679 if (!parse_function_body(parser, var))
4681 ast_delete(basetype);
4682 for (i = 0; i < vec_size(parser->gotos); ++i)
4683 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4684 vec_free(parser->gotos);
4685 vec_free(parser->labels);
4688 ast_expression *cexp;
4691 cexp = parse_expression_leave(parser, true);
4696 cval = (ast_value*)cexp;
4697 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4698 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4701 if (opts.standard != COMPILER_GMQCC &&
4702 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4703 qualifier != CV_VAR)
4705 var->cvq = CV_CONST;
4707 var->hasvalue = true;
4708 if (cval->expression.vtype == TYPE_STRING)
4709 var->constval.vstring = parser_strdup(cval->constval.vstring);
4710 else if (cval->expression.vtype == TYPE_FIELD)
4711 var->constval.vfield = cval;
4713 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4718 shunt sy = { NULL, NULL };
4721 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4722 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4723 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4724 if (!parser_sy_apply_operator(parser, &sy))
4727 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4728 parseerror(parser, "internal error: leaked operands");
4729 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4739 if (parser->tok == ',') {
4740 if (!parser_next(parser)) {
4741 parseerror(parser, "expected another variable");
4745 if (parser->tok != TOKEN_IDENT) {
4746 parseerror(parser, "expected another variable");
4749 var = ast_value_copy(basetype);
4751 ast_value_set_name(var, parser_tokval(parser));
4752 if (!parser_next(parser)) {
4753 parseerror(parser, "error parsing variable declaration");
4759 if (parser->tok != ';') {
4760 parseerror(parser, "missing semicolon after variables");
4764 if (!parser_next(parser)) {
4765 parseerror(parser, "parse error after variable declaration");
4769 ast_delete(basetype);
4773 if (cleanvar && var)
4775 ast_delete(basetype);
4779 ast_delete(basetype);
4780 if (cleanvar && var)
4782 if (me[0]) ast_member_delete(me[0]);
4783 if (me[1]) ast_member_delete(me[1]);
4784 if (me[2]) ast_member_delete(me[2]);
4788 static bool parser_global_statement(parser_t *parser)
4792 bool noreturn = false;
4793 bool is_static = false;
4794 ast_value *istype = NULL;
4796 if (parser->tok == TOKEN_IDENT)
4797 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4799 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4801 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4803 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4805 if (cvq == CV_WRONG)
4807 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4809 else if (parser->tok == TOKEN_KEYWORD)
4811 if (!strcmp(parser_tokval(parser), "typedef")) {
4812 if (!parser_next(parser)) {
4813 parseerror(parser, "expected type definition after 'typedef'");
4816 return parse_typedef(parser);
4818 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4821 else if (parser->tok == '#')
4823 return parse_pragma(parser);
4825 else if (parser->tok == '$')
4827 if (!parser_next(parser)) {
4828 parseerror(parser, "parse error");
4834 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4840 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4842 return util_crc16(old, str, strlen(str));
4845 static void progdefs_crc_file(const char *str)
4847 /* write to progdefs.h here */
4851 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4853 old = progdefs_crc_sum(old, str);
4854 progdefs_crc_file(str);
4858 static void generate_checksum(parser_t *parser)
4860 uint16_t crc = 0xFFFF;
4864 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4865 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4867 progdefs_crc_file("\tint\tpad;\n");
4868 progdefs_crc_file("\tint\tofs_return[3];\n");
4869 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4870 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4871 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4872 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4873 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4874 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4875 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4876 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4878 for (i = 0; i < parser->crc_globals; ++i) {
4879 if (!ast_istype(parser->globals[i], ast_value))
4881 value = (ast_value*)(parser->globals[i]);
4882 switch (value->expression.vtype) {
4883 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4884 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4885 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4886 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4888 crc = progdefs_crc_both(crc, "\tint\t");
4891 crc = progdefs_crc_both(crc, value->name);
4892 crc = progdefs_crc_both(crc, ";\n");
4894 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4895 for (i = 0; i < parser->crc_fields; ++i) {
4896 if (!ast_istype(parser->fields[i], ast_value))
4898 value = (ast_value*)(parser->fields[i]);
4899 switch (value->expression.next->expression.vtype) {
4900 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4901 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4902 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4903 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4905 crc = progdefs_crc_both(crc, "\tint\t");
4908 crc = progdefs_crc_both(crc, value->name);
4909 crc = progdefs_crc_both(crc, ";\n");
4911 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4916 static parser_t *parser;
4923 parser = (parser_t*)mem_a(sizeof(parser_t));
4927 memset(parser, 0, sizeof(*parser));
4929 for (i = 0; i < operator_count; ++i) {
4930 if (operators[i].id == opid1('=')) {
4931 parser->assign_op = operators+i;
4935 if (!parser->assign_op) {
4936 printf("internal error: initializing parser: failed to find assign operator\n");
4941 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4942 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4943 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4944 vec_push(parser->_blocktypedefs, 0);
4946 empty_ctx.file = "<internal>";
4948 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
4949 if (OPTS_FLAG(UNTYPED_NIL))
4950 util_htset(parser->htglobals, "nil", (void*)parser->nil);
4954 bool parser_compile()
4956 /* initial lexer/parser state */
4957 parser->lex->flags.noops = true;
4959 if (parser_next(parser))
4961 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4963 if (!parser_global_statement(parser)) {
4964 if (parser->tok == TOKEN_EOF)
4965 parseerror(parser, "unexpected eof");
4966 else if (compile_errors)
4967 parseerror(parser, "there have been errors, bailing out");
4968 lex_close(parser->lex);
4974 parseerror(parser, "parse error");
4975 lex_close(parser->lex);
4980 lex_close(parser->lex);
4983 return !compile_errors;
4986 bool parser_compile_file(const char *filename)
4988 parser->lex = lex_open(filename);
4990 con_err("failed to open file \"%s\"\n", filename);
4993 return parser_compile();
4996 bool parser_compile_string(const char *name, const char *str, size_t len)
4998 parser->lex = lex_open_string(str, len, name);
5000 con_err("failed to create lexer for string \"%s\"\n", name);
5003 return parser_compile();
5006 void parser_cleanup()
5009 for (i = 0; i < vec_size(parser->accessors); ++i) {
5010 ast_delete(parser->accessors[i]->constval.vfunc);
5011 parser->accessors[i]->constval.vfunc = NULL;
5012 ast_delete(parser->accessors[i]);
5014 for (i = 0; i < vec_size(parser->functions); ++i) {
5015 ast_delete(parser->functions[i]);
5017 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5018 ast_delete(parser->imm_vector[i]);
5020 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5021 ast_delete(parser->imm_string[i]);
5023 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5024 ast_delete(parser->imm_float[i]);
5026 for (i = 0; i < vec_size(parser->fields); ++i) {
5027 ast_delete(parser->fields[i]);
5029 for (i = 0; i < vec_size(parser->globals); ++i) {
5030 ast_delete(parser->globals[i]);
5032 vec_free(parser->accessors);
5033 vec_free(parser->functions);
5034 vec_free(parser->imm_vector);
5035 vec_free(parser->imm_string);
5036 vec_free(parser->imm_float);
5037 vec_free(parser->globals);
5038 vec_free(parser->fields);
5040 for (i = 0; i < vec_size(parser->variables); ++i)
5041 util_htdel(parser->variables[i]);
5042 vec_free(parser->variables);
5043 vec_free(parser->_blocklocals);
5044 vec_free(parser->_locals);
5046 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5047 ast_delete(parser->_typedefs[i]);
5048 vec_free(parser->_typedefs);
5049 for (i = 0; i < vec_size(parser->typedefs); ++i)
5050 util_htdel(parser->typedefs[i]);
5051 vec_free(parser->typedefs);
5052 vec_free(parser->_blocktypedefs);
5054 vec_free(parser->_block_ctx);
5056 vec_free(parser->labels);
5057 vec_free(parser->gotos);
5058 vec_free(parser->breaks);
5059 vec_free(parser->continues);
5064 bool parser_finish(const char *output)
5070 if (compile_errors) {
5071 con_out("*** there were compile errors\n");
5075 ir = ir_builder_new("gmqcc_out");
5077 con_out("failed to allocate builder\n");
5081 for (i = 0; i < vec_size(parser->fields); ++i) {
5084 if (!ast_istype(parser->fields[i], ast_value))
5086 field = (ast_value*)parser->fields[i];
5087 hasvalue = field->hasvalue;
5088 field->hasvalue = false;
5089 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5090 con_out("failed to generate field %s\n", field->name);
5091 ir_builder_delete(ir);
5096 ast_expression *subtype;
5097 field->hasvalue = true;
5098 subtype = field->expression.next;
5099 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5100 if (subtype->expression.vtype == TYPE_FIELD)
5101 ifld->fieldtype = subtype->expression.next->expression.vtype;
5102 else if (subtype->expression.vtype == TYPE_FUNCTION)
5103 ifld->outtype = subtype->expression.next->expression.vtype;
5104 (void)!ir_value_set_field(field->ir_v, ifld);
5107 for (i = 0; i < vec_size(parser->globals); ++i) {
5109 if (!ast_istype(parser->globals[i], ast_value))
5111 asvalue = (ast_value*)(parser->globals[i]);
5112 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5113 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5114 "unused global: `%s`", asvalue->name);
5116 if (!ast_global_codegen(asvalue, ir, false)) {
5117 con_out("failed to generate global %s\n", asvalue->name);
5118 ir_builder_delete(ir);
5122 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5123 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5124 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5125 ir_builder_delete(ir);
5129 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5130 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5131 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5132 ir_builder_delete(ir);
5136 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5137 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5138 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5139 ir_builder_delete(ir);
5143 for (i = 0; i < vec_size(parser->globals); ++i) {
5145 if (!ast_istype(parser->globals[i], ast_value))
5147 asvalue = (ast_value*)(parser->globals[i]);
5148 if (!ast_generate_accessors(asvalue, ir)) {
5149 ir_builder_delete(ir);
5153 for (i = 0; i < vec_size(parser->fields); ++i) {
5155 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5157 if (!ast_istype((ast_expression*)asvalue, ast_value))
5159 if (asvalue->expression.vtype != TYPE_ARRAY)
5161 if (!ast_generate_accessors(asvalue, ir)) {
5162 ir_builder_delete(ir);
5166 for (i = 0; i < vec_size(parser->functions); ++i) {
5167 if (!ast_function_codegen(parser->functions[i], ir)) {
5168 con_out("failed to generate function %s\n", parser->functions[i]->name);
5169 ir_builder_delete(ir);
5174 ir_builder_dump(ir, con_out);
5175 for (i = 0; i < vec_size(parser->functions); ++i) {
5176 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5177 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5178 ir_builder_delete(ir);
5183 if (compile_Werrors) {
5184 con_out("*** there were warnings treated as errors\n");
5185 compile_show_werrors();
5191 ir_builder_dump(ir, con_out);
5193 generate_checksum(parser);
5195 if (!ir_builder_generate(ir, output)) {
5196 con_out("*** failed to generate output file\n");
5197 ir_builder_delete(ir);
5202 ir_builder_delete(ir);