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;
58 ast_function *function;
60 /* All the labels the function defined...
61 * Should they be in ast_function instead?
66 /* A list of hashtables for each scope */
72 /* not to be used directly, we use the hash table */
73 ast_expression **_locals;
75 ast_value **_typedefs;
76 size_t *_blocktypedefs;
79 /* we store the '=' operator info */
80 const oper_info *assign_op;
82 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
83 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
84 * anything else: type error
88 /* Keep track of our ternary vs parenthesis nesting state.
89 * If we reach a 'comma' operator in a ternary without a paren,
90 * we shall trigger -Wternary-precedence.
98 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
100 static void parser_enterblock(parser_t *parser);
101 static bool parser_leaveblock(parser_t *parser);
102 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
103 static bool parse_typedef(parser_t *parser);
104 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);
105 static ast_block* parse_block(parser_t *parser);
106 static bool parse_block_into(parser_t *parser, ast_block *block);
107 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
108 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
109 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
110 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
112 static void parseerror(parser_t *parser, const char *fmt, ...)
116 vcompile_error(parser->lex->tok.ctx, fmt, ap);
120 /* returns true if it counts as an error */
121 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
126 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
131 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
136 r = vcompile_warning(ctx, warntype, fmt, ap);
141 /**********************************************************************
142 * some maths used for constant folding
145 vector vec3_add(vector a, vector b)
154 vector vec3_sub(vector a, vector b)
163 qcfloat vec3_mulvv(vector a, vector b)
165 return (a.x * b.x + a.y * b.y + a.z * b.z);
168 vector vec3_mulvf(vector a, float b)
177 /**********************************************************************
181 bool parser_next(parser_t *parser)
183 /* lex_do kills the previous token */
184 parser->tok = lex_do(parser->lex);
185 if (parser->tok == TOKEN_EOF)
187 if (parser->tok >= TOKEN_ERROR) {
188 parseerror(parser, "lex error");
194 #define parser_tokval(p) ((p)->lex->tok.value)
195 #define parser_token(p) (&((p)->lex->tok))
196 #define parser_ctx(p) ((p)->lex->tok.ctx)
198 static ast_value* parser_const_float(parser_t *parser, double d)
202 for (i = 0; i < vec_size(parser->imm_float); ++i) {
203 const double compare = parser->imm_float[i]->constval.vfloat;
204 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
205 return parser->imm_float[i];
207 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
209 out->hasvalue = true;
210 out->constval.vfloat = d;
211 vec_push(parser->imm_float, out);
215 static ast_value* parser_const_float_0(parser_t *parser)
217 if (!parser->imm_float_zero)
218 parser->imm_float_zero = parser_const_float(parser, 0);
219 return parser->imm_float_zero;
222 static ast_value* parser_const_float_1(parser_t *parser)
224 if (!parser->imm_float_one)
225 parser->imm_float_one = parser_const_float(parser, 1);
226 return parser->imm_float_one;
229 static char *parser_strdup(const char *str)
232 /* actually dup empty strings */
233 char *out = (char*)mem_a(1);
237 return util_strdup(str);
240 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
244 for (i = 0; i < vec_size(parser->imm_string); ++i) {
245 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
246 return parser->imm_string[i];
250 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
251 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
253 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
255 out->hasvalue = true;
256 out->constval.vstring = parser_strdup(str);
257 vec_push(parser->imm_string, out);
261 static ast_value* parser_const_vector(parser_t *parser, vector v)
265 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
266 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
267 return parser->imm_vector[i];
269 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
271 out->hasvalue = true;
272 out->constval.vvec = v;
273 vec_push(parser->imm_vector, out);
277 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
283 return parser_const_vector(parser, v);
286 static ast_value* parser_const_vector_0(parser_t *parser)
288 if (!parser->imm_vector_zero)
289 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
290 return parser->imm_vector_zero;
293 static ast_expression* parser_find_field(parser_t *parser, const char *name)
295 return ( ast_expression*)util_htget(parser->htfields, name);
298 static ast_expression* parser_find_global(parser_t *parser, const char *name)
300 return (ast_expression*)util_htget(parser->htglobals, name);
303 static ast_expression* parser_find_param(parser_t *parser, const char *name)
307 if (!parser->function)
309 fun = parser->function->vtype;
310 for (i = 0; i < vec_size(fun->expression.params); ++i) {
311 if (!strcmp(fun->expression.params[i]->name, name))
312 return (ast_expression*)(fun->expression.params[i]);
317 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
322 hash = util_hthash(parser->htglobals, name);
325 for (i = vec_size(parser->variables); i > upto;) {
327 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
331 return parser_find_param(parser, name);
334 static ast_expression* parser_find_var(parser_t *parser, const char *name)
338 v = parser_find_local(parser, name, 0, &dummy);
339 if (!v) v = parser_find_global(parser, name);
343 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
347 hash = util_hthash(parser->typedefs[0], name);
349 for (i = vec_size(parser->typedefs); i > upto;) {
351 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
359 size_t etype; /* 0 = expression, others are operators */
363 ast_block *block; /* for commas and function calls */
372 #define SY_PAREN_EXPR '('
373 #define SY_PAREN_FUNC 'f'
374 #define SY_PAREN_INDEX '['
375 #define SY_PAREN_TERNARY '?'
377 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
388 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
392 e.out = (ast_expression*)v;
399 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
401 e.etype = 1 + (op - operators);
410 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
422 # define DEBUGSHUNTDO(x) x
424 # define DEBUGSHUNTDO(x)
427 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
428 * so we need to rotate it to become ent.(foo[n]).
430 static bool rotate_entfield_array_index_nodes(ast_expression **out)
432 ast_array_index *index;
433 ast_entfield *entfield;
437 ast_expression *entity;
439 lex_ctx ctx = ast_ctx(*out);
441 if (!ast_istype(*out, ast_array_index))
443 index = (ast_array_index*)*out;
445 if (!ast_istype(index->array, ast_entfield))
447 entfield = (ast_entfield*)index->array;
449 if (!ast_istype(entfield->field, ast_value))
451 field = (ast_value*)entfield->field;
454 entity = entfield->entity;
458 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
459 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
460 *out = (ast_expression*)entfield;
465 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
467 switch (v->expression.vtype) {
469 return !!v->constval.vfloat;
471 return !!v->constval.vint;
473 if (OPTS_FLAG(CORRECT_LOGIC))
474 return v->constval.vvec.x &&
475 v->constval.vvec.y &&
478 return !!(v->constval.vvec.x);
480 if (!v->constval.vstring)
482 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
484 return !!v->constval.vstring[0];
486 compile_error(ctx, "internal error: immediate_is_true on invalid type");
487 return !!v->constval.vfunc;
491 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
495 ast_expression *out = NULL;
496 ast_expression *exprs[3];
497 ast_block *blocks[3];
498 ast_value *asvalue[3];
499 ast_binstore *asbinstore;
500 size_t i, assignop, addop, subop;
501 qcint generated_op = 0;
506 if (!vec_size(sy->ops)) {
507 parseerror(parser, "internal error: missing operator");
511 if (vec_last(sy->ops).paren) {
512 parseerror(parser, "unmatched parenthesis");
516 op = &operators[vec_last(sy->ops).etype - 1];
517 ctx = vec_last(sy->ops).ctx;
519 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
521 if (vec_size(sy->out) < op->operands) {
522 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
523 op->op, (int)op->id);
527 vec_shrinkby(sy->ops, 1);
529 /* op(:?) has no input and no output */
533 vec_shrinkby(sy->out, op->operands);
534 for (i = 0; i < op->operands; ++i) {
535 exprs[i] = sy->out[vec_size(sy->out)+i].out;
536 blocks[i] = sy->out[vec_size(sy->out)+i].block;
537 asvalue[i] = (ast_value*)exprs[i];
540 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
541 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
545 #define NotSameType(T) \
546 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
547 exprs[0]->expression.vtype != T)
548 #define CanConstFold1(A) \
549 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
550 (A)->expression.vtype != TYPE_FUNCTION)
551 #define CanConstFold(A, B) \
552 (CanConstFold1(A) && CanConstFold1(B))
553 #define ConstV(i) (asvalue[(i)]->constval.vvec)
554 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
555 #define ConstS(i) (asvalue[(i)]->constval.vstring)
559 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
563 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
564 if (exprs[1]->expression.vtype != TYPE_FIELD) {
565 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
568 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
570 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
571 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
575 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
581 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
582 !(exprs[0]->expression.vtype == TYPE_FIELD &&
583 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
585 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
586 parseerror(parser, "cannot index value of type %s", ty1);
589 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
590 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
591 parseerror(parser, "index must be of type float, not %s", ty1);
594 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
595 if (rotate_entfield_array_index_nodes(&out))
598 /* This is not broken in fteqcc anymore */
599 if (opts.standard != COMPILER_GMQCC) {
600 /* this error doesn't need to make us bail out */
601 (void)!parsewarning(parser, WARN_EXTENSIONS,
602 "accessing array-field members of an entity without parenthesis\n"
603 " -> this is an extension from -std=gmqcc");
611 if (!ast_block_add_expr(blocks[0], exprs[1]))
614 blocks[0] = ast_block_new(ctx);
615 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
616 !ast_block_add_expr(blocks[0], exprs[1]))
621 if (!ast_block_set_type(blocks[0], exprs[1]))
624 vec_push(sy->out, syblock(ctx, blocks[0]));
631 switch (exprs[0]->expression.vtype) {
633 if (CanConstFold1(exprs[0]))
634 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
636 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
637 (ast_expression*)parser_const_float_0(parser),
641 if (CanConstFold1(exprs[0]))
642 out = (ast_expression*)parser_const_vector_f(parser,
643 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
645 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
646 (ast_expression*)parser_const_vector_0(parser),
650 parseerror(parser, "invalid types used in expression: cannot negate type %s",
651 type_name[exprs[0]->expression.vtype]);
657 switch (exprs[0]->expression.vtype) {
659 if (CanConstFold1(exprs[0]))
660 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
662 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
665 if (CanConstFold1(exprs[0]))
666 out = (ast_expression*)parser_const_float(parser,
667 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
669 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
672 if (CanConstFold1(exprs[0])) {
673 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
674 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
676 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
678 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
679 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
681 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
684 /* we don't constant-fold NOT for these types */
686 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
689 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
692 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
693 type_name[exprs[0]->expression.vtype]);
699 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
700 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
702 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
703 type_name[exprs[0]->expression.vtype],
704 type_name[exprs[1]->expression.vtype]);
707 switch (exprs[0]->expression.vtype) {
709 if (CanConstFold(exprs[0], exprs[1]))
711 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
714 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
717 if (CanConstFold(exprs[0], exprs[1]))
718 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
720 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
723 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
724 type_name[exprs[0]->expression.vtype],
725 type_name[exprs[1]->expression.vtype]);
730 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
731 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
733 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
734 type_name[exprs[1]->expression.vtype],
735 type_name[exprs[0]->expression.vtype]);
738 switch (exprs[0]->expression.vtype) {
740 if (CanConstFold(exprs[0], exprs[1]))
741 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
743 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
746 if (CanConstFold(exprs[0], exprs[1]))
747 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
749 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
752 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
753 type_name[exprs[1]->expression.vtype],
754 type_name[exprs[0]->expression.vtype]);
759 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
760 exprs[0]->expression.vtype != TYPE_VECTOR &&
761 exprs[0]->expression.vtype != TYPE_FLOAT &&
762 exprs[1]->expression.vtype != TYPE_VECTOR &&
763 exprs[1]->expression.vtype != TYPE_FLOAT)
765 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
766 type_name[exprs[1]->expression.vtype],
767 type_name[exprs[0]->expression.vtype]);
770 switch (exprs[0]->expression.vtype) {
772 if (exprs[1]->expression.vtype == TYPE_VECTOR)
774 if (CanConstFold(exprs[0], exprs[1]))
775 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
777 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
781 if (CanConstFold(exprs[0], exprs[1]))
782 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
784 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
788 if (exprs[1]->expression.vtype == TYPE_FLOAT)
790 if (CanConstFold(exprs[0], exprs[1]))
791 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
793 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
797 if (CanConstFold(exprs[0], exprs[1]))
798 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
800 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
804 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
805 type_name[exprs[1]->expression.vtype],
806 type_name[exprs[0]->expression.vtype]);
811 if (NotSameType(TYPE_FLOAT)) {
812 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
813 type_name[exprs[0]->expression.vtype],
814 type_name[exprs[1]->expression.vtype]);
817 if (CanConstFold(exprs[0], exprs[1]))
818 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
820 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
824 parseerror(parser, "qc does not have a modulo operator");
828 if (NotSameType(TYPE_FLOAT)) {
829 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
830 type_name[exprs[0]->expression.vtype],
831 type_name[exprs[1]->expression.vtype]);
834 if (CanConstFold(exprs[0], exprs[1]))
835 out = (ast_expression*)parser_const_float(parser,
836 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
837 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
839 out = (ast_expression*)ast_binary_new(ctx,
840 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
844 parseerror(parser, "TODO: bitxor");
849 case opid3('<','<','='):
850 case opid3('>','>','='):
851 parseerror(parser, "TODO: shifts");
855 generated_op += 1; /* INSTR_OR */
857 generated_op += INSTR_AND;
859 if (NotSameType(TYPE_FLOAT)) {
860 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
861 type_name[exprs[0]->expression.vtype],
862 type_name[exprs[1]->expression.vtype]);
863 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
864 parseerror(parser, "TODO: optional early out");
868 if (CanConstFold(exprs[0], exprs[1]))
870 if (OPTS_FLAG(PERL_LOGIC)) {
871 if (immediate_is_true(ctx, asvalue[0]))
875 out = (ast_expression*)parser_const_float(parser,
876 ( (generated_op == INSTR_OR)
877 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
878 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
883 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
884 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
885 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
886 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
889 for (i = 0; i < 2; ++i) {
890 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
891 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
893 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
895 exprs[i] = out; out = NULL;
896 if (OPTS_FLAG(PERL_LOGIC)) {
897 /* here we want to keep the right expressions' type */
901 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
902 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
904 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
906 exprs[i] = out; out = NULL;
907 if (OPTS_FLAG(PERL_LOGIC)) {
908 /* here we want to keep the right expressions' type */
913 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
918 if (vec_last(parser->pot) != POT_TERNARY2) {
919 parseerror(parser, "mismatched parenthesis/ternary");
922 vec_pop(parser->pot);
923 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
924 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
925 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
926 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
929 if (CanConstFold1(exprs[0]))
930 out = (ConstF(0) ? exprs[1] : exprs[2]);
932 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
936 generated_op += 1; /* INSTR_GT */
938 generated_op += 1; /* INSTR_LT */
939 case opid2('>', '='):
940 generated_op += 1; /* INSTR_GE */
941 case opid2('<', '='):
942 generated_op += INSTR_LE;
943 if (NotSameType(TYPE_FLOAT)) {
944 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
945 type_name[exprs[0]->expression.vtype],
946 type_name[exprs[1]->expression.vtype]);
949 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
951 case opid2('!', '='):
952 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
953 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
954 type_name[exprs[0]->expression.vtype],
955 type_name[exprs[1]->expression.vtype]);
958 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
960 case opid2('=', '='):
961 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
962 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
963 type_name[exprs[0]->expression.vtype],
964 type_name[exprs[1]->expression.vtype]);
967 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
971 if (ast_istype(exprs[0], ast_entfield)) {
972 ast_expression *field = ((ast_entfield*)exprs[0])->field;
973 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
974 exprs[0]->expression.vtype == TYPE_FIELD &&
975 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
977 assignop = type_storep_instr[TYPE_VECTOR];
980 assignop = type_storep_instr[exprs[0]->expression.vtype];
981 if (assignop == AINSTR_END ||
982 !ast_compare_type(field->expression.next, exprs[1]))
984 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
985 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
986 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
987 field->expression.next->expression.vtype == TYPE_FUNCTION &&
988 exprs[1]->expression.vtype == TYPE_FUNCTION)
990 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
991 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
994 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
999 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1000 exprs[0]->expression.vtype == TYPE_FIELD &&
1001 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1003 assignop = type_store_instr[TYPE_VECTOR];
1006 assignop = type_store_instr[exprs[0]->expression.vtype];
1009 if (assignop == AINSTR_END) {
1010 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1011 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1012 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1014 else if (!ast_compare_type(exprs[0], exprs[1])) {
1015 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1016 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1017 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1018 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1019 exprs[1]->expression.vtype == TYPE_FUNCTION)
1021 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1022 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1025 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1028 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1029 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1031 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1033 case opid3('+','+','P'):
1034 case opid3('-','-','P'):
1036 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1037 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1038 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1041 if (op->id == opid3('+','+','P'))
1042 addop = INSTR_ADD_F;
1044 addop = INSTR_SUB_F;
1045 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1046 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1048 if (ast_istype(exprs[0], ast_entfield)) {
1049 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1051 (ast_expression*)parser_const_float_1(parser));
1053 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1055 (ast_expression*)parser_const_float_1(parser));
1058 case opid3('S','+','+'):
1059 case opid3('S','-','-'):
1061 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1062 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1063 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1066 if (op->id == opid3('S','+','+')) {
1067 addop = INSTR_ADD_F;
1068 subop = INSTR_SUB_F;
1070 addop = INSTR_SUB_F;
1071 subop = INSTR_ADD_F;
1073 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1074 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1076 if (ast_istype(exprs[0], ast_entfield)) {
1077 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1079 (ast_expression*)parser_const_float_1(parser));
1081 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1083 (ast_expression*)parser_const_float_1(parser));
1087 out = (ast_expression*)ast_binary_new(ctx, subop,
1089 (ast_expression*)parser_const_float_1(parser));
1091 case opid2('+','='):
1092 case opid2('-','='):
1093 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1094 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1096 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1097 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1098 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1102 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1103 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1105 if (ast_istype(exprs[0], ast_entfield))
1106 assignop = type_storep_instr[exprs[0]->expression.vtype];
1108 assignop = type_store_instr[exprs[0]->expression.vtype];
1109 switch (exprs[0]->expression.vtype) {
1111 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1112 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1113 exprs[0], exprs[1]);
1116 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1117 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1118 exprs[0], exprs[1]);
1121 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1122 type_name[exprs[0]->expression.vtype],
1123 type_name[exprs[1]->expression.vtype]);
1127 case opid2('*','='):
1128 case opid2('/','='):
1129 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1130 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1131 exprs[0]->expression.vtype == TYPE_VECTOR))
1133 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1134 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1135 parseerror(parser, "invalid types used in expression: %s and %s",
1139 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1140 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1142 if (ast_istype(exprs[0], ast_entfield))
1143 assignop = type_storep_instr[exprs[0]->expression.vtype];
1145 assignop = type_store_instr[exprs[0]->expression.vtype];
1146 switch (exprs[0]->expression.vtype) {
1148 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1149 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1150 exprs[0], exprs[1]);
1153 if (op->id == opid2('*','=')) {
1154 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1155 exprs[0], exprs[1]);
1157 /* there's no DIV_VF */
1158 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1159 (ast_expression*)parser_const_float_1(parser),
1163 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1168 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1169 type_name[exprs[0]->expression.vtype],
1170 type_name[exprs[1]->expression.vtype]);
1174 case opid2('&','='):
1175 case opid2('|','='):
1176 if (NotSameType(TYPE_FLOAT)) {
1177 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1178 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1179 parseerror(parser, "invalid types used in expression: %s and %s",
1183 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1184 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1186 if (ast_istype(exprs[0], ast_entfield))
1187 assignop = type_storep_instr[exprs[0]->expression.vtype];
1189 assignop = type_store_instr[exprs[0]->expression.vtype];
1190 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1191 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1192 exprs[0], exprs[1]);
1194 case opid3('&','~','='):
1195 /* This is like: a &= ~(b);
1196 * But QC has no bitwise-not, so we implement it as
1199 if (NotSameType(TYPE_FLOAT)) {
1200 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1201 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1202 parseerror(parser, "invalid types used in expression: %s and %s",
1206 if (ast_istype(exprs[0], ast_entfield))
1207 assignop = type_storep_instr[exprs[0]->expression.vtype];
1209 assignop = type_store_instr[exprs[0]->expression.vtype];
1210 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1213 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1214 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1216 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1217 asbinstore->keep_dest = true;
1218 out = (ast_expression*)asbinstore;
1224 parseerror(parser, "failed to apply operand %s", op->op);
1228 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1229 vec_push(sy->out, syexp(ctx, out));
1233 static bool parser_close_call(parser_t *parser, shunt *sy)
1235 /* was a function call */
1236 ast_expression *fun;
1242 vec_shrinkby(sy->ops, 1);
1243 fid = sy->ops[vec_size(sy->ops)].off;
1245 /* out[fid] is the function
1246 * everything above is parameters...
1247 * 0 params = nothing
1248 * 1 params = ast_expression
1252 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1253 parseerror(parser, "internal error: function call needs function and parameter list...");
1257 fun = sy->out[fid].out;
1259 if (fun == intrinsic_debug_typestring) {
1261 if (fid+2 != vec_size(sy->out) ||
1262 vec_last(sy->out).block)
1264 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1267 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1268 ast_unref(vec_last(sy->out).out);
1269 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1270 (ast_expression*)parser_const_string(parser, ty, false));
1271 vec_shrinkby(sy->out, 1);
1275 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1277 parseerror(parser, "internal error: failed to create ast_call node");
1281 if (fid+1 == vec_size(sy->out)) {
1284 } else if (fid+2 == vec_size(sy->out)) {
1286 vec_shrinkby(sy->out, 1);
1287 params = sy->out[vec_size(sy->out)].block;
1291 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1293 paramcount = vec_size(params->exprs);
1294 call->params = params->exprs;
1295 params->exprs = NULL;
1298 (void)!ast_call_check_types(call);
1300 parseerror(parser, "invalid function call");
1304 /* overwrite fid, the function, with a call */
1305 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1307 if (fun->expression.vtype != TYPE_FUNCTION) {
1308 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1312 if (!fun->expression.next) {
1313 parseerror(parser, "could not determine function return type");
1316 if (vec_size(fun->expression.params) != paramcount &&
1317 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1318 vec_size(fun->expression.params) < paramcount))
1321 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1323 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1324 if (opts.standard == COMPILER_GMQCC)
1327 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1328 " -> `%s` has been declared here: %s:%i",
1329 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1330 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1332 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1333 " -> it has been declared here: %s:%i",
1334 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1335 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1341 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1342 "too %s parameters for call to %s: expected %i, got %i\n"
1343 " -> `%s` has been declared here: %s:%i",
1344 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1345 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1347 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1348 "too %s parameters for function call: expected %i, got %i\n"
1349 " -> it has been declared here: %s:%i",
1350 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1351 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1359 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1361 if (!vec_size(sy->ops)) {
1362 parseerror(parser, "unmatched closing paren");
1365 /* this would for bit a + (x) because there are no operators inside (x)
1366 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1367 parseerror(parser, "empty parenthesis expression");
1371 while (vec_size(sy->ops)) {
1372 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1373 if (!parser_close_call(parser, sy))
1377 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1378 vec_shrinkby(sy->ops, 1);
1379 return !functions_only;
1381 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1384 /* pop off the parenthesis */
1385 vec_shrinkby(sy->ops, 1);
1386 /* then apply the index operator */
1387 if (!parser_sy_apply_operator(parser, sy))
1391 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1394 if (vec_last(parser->pot) != POT_TERNARY1) {
1395 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1398 vec_last(parser->pot) = POT_TERNARY2;
1399 /* pop off the parenthesis */
1400 vec_shrinkby(sy->ops, 1);
1403 if (!parser_sy_apply_operator(parser, sy))
1409 static void parser_reclassify_token(parser_t *parser)
1412 for (i = 0; i < operator_count; ++i) {
1413 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1414 parser->tok = TOKEN_OPERATOR;
1420 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1422 ast_expression *expr = NULL;
1424 bool wantop = false;
1425 bool gotmemberof = false;
1427 /* count the parens because an if starts with one, so the
1428 * end of a condition is an unmatched closing paren
1436 parser->lex->flags.noops = false;
1438 parser_reclassify_token(parser);
1443 gotmemberof = false;
1445 parser->memberof = 0;
1447 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1448 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1450 /* a translatable string */
1454 parseerror(parser, "expected operator or end of statement, got constant");
1458 parser->lex->flags.noops = true;
1459 if (!parser_next(parser) || parser->tok != '(') {
1460 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1463 parser->lex->flags.noops = false;
1464 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1465 parseerror(parser, "expected a constant string in translatable-string extension");
1468 val = parser_const_string(parser, parser_tokval(parser), true);
1472 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1473 DEBUGSHUNTDO(con_out("push string\n"));
1475 if (!parser_next(parser) || parser->tok != ')') {
1476 parseerror(parser, "expected closing paren after translatable string");
1480 else if (parser->tok == TOKEN_IDENT)
1482 ast_expression *var;
1484 parseerror(parser, "expected operator or end of statement");
1489 if (opts.standard == COMPILER_GMQCC)
1491 if (parser->memberof == TYPE_ENTITY) {
1492 /* still get vars first since there could be a fieldpointer */
1493 var = parser_find_var(parser, parser_tokval(parser));
1495 var = parser_find_field(parser, parser_tokval(parser));
1497 else if (parser->memberof == TYPE_VECTOR)
1499 parseerror(parser, "TODO: implement effective vector member access");
1502 else if (parser->memberof) {
1503 parseerror(parser, "namespace for member not found");
1507 var = parser_find_var(parser, parser_tokval(parser));
1509 var = parser_find_var(parser, parser_tokval(parser));
1511 var = parser_find_field(parser, parser_tokval(parser));
1515 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1516 var = (ast_expression*)intrinsic_debug_typestring;
1521 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1527 if (ast_istype(var, ast_value)) {
1528 ((ast_value*)var)->uses++;
1530 else if (ast_istype(var, ast_member)) {
1531 ast_member *mem = (ast_member*)var;
1532 if (ast_istype(mem->owner, ast_value))
1533 ((ast_value*)(mem->owner))->uses++;
1536 vec_push(sy.out, syexp(parser_ctx(parser), var));
1537 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1539 else if (parser->tok == TOKEN_FLOATCONST) {
1542 parseerror(parser, "expected operator or end of statement, got constant");
1546 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1549 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1550 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1552 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1555 parseerror(parser, "expected operator or end of statement, got constant");
1559 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1562 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1563 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1565 else if (parser->tok == TOKEN_STRINGCONST) {
1568 parseerror(parser, "expected operator or end of statement, got constant");
1572 val = parser_const_string(parser, parser_tokval(parser), false);
1575 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1576 DEBUGSHUNTDO(con_out("push string\n"));
1578 else if (parser->tok == TOKEN_VECTORCONST) {
1581 parseerror(parser, "expected operator or end of statement, got constant");
1585 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1588 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1589 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1590 parser_token(parser)->constval.v.x,
1591 parser_token(parser)->constval.v.y,
1592 parser_token(parser)->constval.v.z));
1594 else if (parser->tok == '(') {
1595 parseerror(parser, "internal error: '(' should be classified as operator");
1598 else if (parser->tok == '[') {
1599 parseerror(parser, "internal error: '[' should be classified as operator");
1602 else if (parser->tok == ')') {
1604 DEBUGSHUNTDO(con_out("do[op] )\n"));
1608 /* we do expect an operator next */
1609 /* closing an opening paren */
1610 if (!parser_close_paren(parser, &sy, false))
1612 if (vec_last(parser->pot) != POT_PAREN) {
1613 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1616 vec_pop(parser->pot);
1618 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1622 /* allowed for function calls */
1623 if (!parser_close_paren(parser, &sy, true))
1625 if (vec_last(parser->pot) != POT_PAREN) {
1626 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1629 vec_pop(parser->pot);
1633 else if (parser->tok == ']') {
1635 parseerror(parser, "operand expected");
1639 if (!parser_close_paren(parser, &sy, false))
1641 if (vec_last(parser->pot) != POT_PAREN) {
1642 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1645 vec_pop(parser->pot);
1648 else if (parser->tok == TOKEN_TYPENAME) {
1649 parseerror(parser, "unexpected typename");
1652 else if (parser->tok != TOKEN_OPERATOR) {
1654 parseerror(parser, "expected operator or end of statement");
1661 /* classify the operator */
1662 const oper_info *op;
1663 const oper_info *olast = NULL;
1665 for (o = 0; o < operator_count; ++o) {
1666 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1667 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1668 !strcmp(parser_tokval(parser), operators[o].op))
1673 if (o == operator_count) {
1674 /* no operator found... must be the end of the statement */
1677 /* found an operator */
1680 /* when declaring variables, a comma starts a new variable */
1681 if (op->id == opid1(',') && !parens && stopatcomma) {
1682 /* fixup the token */
1687 /* a colon without a pervious question mark cannot be a ternary */
1688 if (!ternaries && op->id == opid2(':','?')) {
1693 if (op->id == opid1(',')) {
1694 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1695 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1699 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1700 olast = &operators[vec_last(sy.ops).etype-1];
1703 (op->prec < olast->prec) ||
1704 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1706 if (!parser_sy_apply_operator(parser, &sy))
1708 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1709 olast = &operators[vec_last(sy.ops).etype-1];
1714 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1715 /* for gmqcc standard: open up the namespace of the previous type */
1716 ast_expression *prevex = vec_last(sy.out).out;
1718 parseerror(parser, "unexpected member operator");
1721 if (prevex->expression.vtype == TYPE_ENTITY)
1722 parser->memberof = TYPE_ENTITY;
1723 else if (prevex->expression.vtype == TYPE_VECTOR)
1724 parser->memberof = TYPE_VECTOR;
1726 parseerror(parser, "type error: type has no members");
1732 if (op->id == opid1('(')) {
1734 size_t sycount = vec_size(sy.out);
1735 DEBUGSHUNTDO(con_out("push [op] (\n"));
1736 ++parens; vec_push(parser->pot, POT_PAREN);
1737 /* we expected an operator, this is the function-call operator */
1738 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1740 ++parens; vec_push(parser->pot, POT_PAREN);
1741 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1742 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1745 } else if (op->id == opid1('[')) {
1747 parseerror(parser, "unexpected array subscript");
1750 ++parens; vec_push(parser->pot, POT_PAREN);
1751 /* push both the operator and the paren, this makes life easier */
1752 vec_push(sy.ops, syop(parser_ctx(parser), op));
1753 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1755 } else if (op->id == opid2('?',':')) {
1756 vec_push(sy.ops, syop(parser_ctx(parser), op));
1757 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1760 vec_push(parser->pot, POT_TERNARY1);
1761 } else if (op->id == opid2(':','?')) {
1762 if (!vec_size(parser->pot)) {
1763 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1766 if (vec_last(parser->pot) != POT_TERNARY1) {
1767 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1770 if (!parser_close_paren(parser, &sy, false))
1772 vec_push(sy.ops, syop(parser_ctx(parser), op));
1776 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1777 vec_push(sy.ops, syop(parser_ctx(parser), op));
1778 wantop = !!(op->flags & OP_SUFFIX);
1781 if (!parser_next(parser)) {
1784 if (parser->tok == ';' ||
1785 (!parens && parser->tok == ']'))
1791 while (vec_size(sy.ops)) {
1792 if (!parser_sy_apply_operator(parser, &sy))
1796 parser->lex->flags.noops = true;
1797 if (!vec_size(sy.out)) {
1798 parseerror(parser, "empty expression");
1801 expr = sy.out[0].out;
1804 DEBUGSHUNTDO(con_out("shunt done\n"));
1805 if (vec_size(parser->pot)) {
1806 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1809 vec_free(parser->pot);
1813 parser->lex->flags.noops = true;
1819 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1821 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1824 if (!parser_next(parser)) {
1831 static void parser_enterblock(parser_t *parser)
1833 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1834 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1835 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1836 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1837 vec_push(parser->_block_ctx, parser_ctx(parser));
1840 static bool parser_leaveblock(parser_t *parser)
1843 size_t locals, typedefs;
1845 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1846 parseerror(parser, "internal error: parser_leaveblock with no block");
1850 util_htdel(vec_last(parser->variables));
1851 vec_pop(parser->variables);
1852 if (!vec_size(parser->_blocklocals)) {
1853 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1857 locals = vec_last(parser->_blocklocals);
1858 vec_pop(parser->_blocklocals);
1859 while (vec_size(parser->_locals) != locals) {
1860 ast_expression *e = vec_last(parser->_locals);
1861 ast_value *v = (ast_value*)e;
1862 vec_pop(parser->_locals);
1863 if (ast_istype(e, ast_value) && !v->uses) {
1864 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1869 typedefs = vec_last(parser->_blocktypedefs);
1870 while (vec_size(parser->_typedefs) != typedefs) {
1871 ast_delete(vec_last(parser->_typedefs));
1872 vec_pop(parser->_typedefs);
1874 util_htdel(vec_last(parser->typedefs));
1875 vec_pop(parser->typedefs);
1877 vec_pop(parser->_block_ctx);
1881 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1883 vec_push(parser->_locals, e);
1884 util_htset(vec_last(parser->variables), name, (void*)e);
1887 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1891 ast_expression *prev;
1893 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1896 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1899 parseerror(parser, "internal error: failed to process condition");
1904 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1906 /* vector types need to be cast to true booleans */
1907 ast_binary *bin = (ast_binary*)cond;
1908 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1910 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1912 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1915 parseerror(parser, "internal error: failed to process condition");
1922 unary = (ast_unary*)cond;
1923 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1925 cond = unary->operand;
1926 unary->operand = NULL;
1929 unary = (ast_unary*)cond;
1933 parseerror(parser, "internal error: failed to process condition");
1935 if (ifnot) *_ifnot = !*_ifnot;
1939 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1942 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1945 lex_ctx ctx = parser_ctx(parser);
1947 (void)block; /* not touching */
1949 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1950 if (!parser_next(parser)) {
1951 parseerror(parser, "expected condition or 'not'");
1954 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1956 if (!parser_next(parser)) {
1957 parseerror(parser, "expected condition in parenthesis");
1961 if (parser->tok != '(') {
1962 parseerror(parser, "expected 'if' condition in parenthesis");
1965 /* parse into the expression */
1966 if (!parser_next(parser)) {
1967 parseerror(parser, "expected 'if' condition after opening paren");
1970 /* parse the condition */
1971 cond = parse_expression_leave(parser, false);
1975 if (parser->tok != ')') {
1976 parseerror(parser, "expected closing paren after 'if' condition");
1980 /* parse into the 'then' branch */
1981 if (!parser_next(parser)) {
1982 parseerror(parser, "expected statement for on-true branch of 'if'");
1986 if (!parse_statement_or_block(parser, &ontrue)) {
1990 /* check for an else */
1991 if (!strcmp(parser_tokval(parser), "else")) {
1992 /* parse into the 'else' branch */
1993 if (!parser_next(parser)) {
1994 parseerror(parser, "expected on-false branch after 'else'");
1999 if (!parse_statement_or_block(parser, &onfalse)) {
2006 cond = process_condition(parser, cond, &ifnot);
2008 if (ontrue) ast_delete(ontrue);
2009 if (onfalse) ast_delete(onfalse);
2014 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2016 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2017 *out = (ast_expression*)ifthen;
2021 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2024 ast_expression *cond, *ontrue;
2028 lex_ctx ctx = parser_ctx(parser);
2030 (void)block; /* not touching */
2032 /* skip the 'while' and check for opening paren */
2033 if (!parser_next(parser) || parser->tok != '(') {
2034 parseerror(parser, "expected 'while' condition in parenthesis");
2037 /* parse into the expression */
2038 if (!parser_next(parser)) {
2039 parseerror(parser, "expected 'while' condition after opening paren");
2042 /* parse the condition */
2043 cond = parse_expression_leave(parser, false);
2047 if (parser->tok != ')') {
2048 parseerror(parser, "expected closing paren after 'while' condition");
2052 /* parse into the 'then' branch */
2053 if (!parser_next(parser)) {
2054 parseerror(parser, "expected while-loop body");
2058 if (!parse_statement_or_block(parser, &ontrue)) {
2063 cond = process_condition(parser, cond, &ifnot);
2068 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2069 *out = (ast_expression*)aloop;
2073 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2076 ast_expression *cond, *ontrue;
2080 lex_ctx ctx = parser_ctx(parser);
2082 (void)block; /* not touching */
2084 /* skip the 'do' and get the body */
2085 if (!parser_next(parser)) {
2086 parseerror(parser, "expected loop body");
2089 if (!parse_statement_or_block(parser, &ontrue))
2092 /* expect the "while" */
2093 if (parser->tok != TOKEN_KEYWORD ||
2094 strcmp(parser_tokval(parser), "while"))
2096 parseerror(parser, "expected 'while' and condition");
2101 /* skip the 'while' and check for opening paren */
2102 if (!parser_next(parser) || parser->tok != '(') {
2103 parseerror(parser, "expected 'while' condition in parenthesis");
2107 /* parse into the expression */
2108 if (!parser_next(parser)) {
2109 parseerror(parser, "expected 'while' condition after opening paren");
2113 /* parse the condition */
2114 cond = parse_expression_leave(parser, false);
2118 if (parser->tok != ')') {
2119 parseerror(parser, "expected closing paren after 'while' condition");
2125 if (!parser_next(parser) || parser->tok != ';') {
2126 parseerror(parser, "expected semicolon after condition");
2132 if (!parser_next(parser)) {
2133 parseerror(parser, "parse error");
2139 cond = process_condition(parser, cond, &ifnot);
2144 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2145 *out = (ast_expression*)aloop;
2149 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2152 ast_expression *initexpr, *cond, *increment, *ontrue;
2158 lex_ctx ctx = parser_ctx(parser);
2160 parser_enterblock(parser);
2167 /* skip the 'while' and check for opening paren */
2168 if (!parser_next(parser) || parser->tok != '(') {
2169 parseerror(parser, "expected 'for' expressions in parenthesis");
2172 /* parse into the expression */
2173 if (!parser_next(parser)) {
2174 parseerror(parser, "expected 'for' initializer after opening paren");
2179 if (parser->tok == TOKEN_IDENT)
2180 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2182 if (typevar || parser->tok == TOKEN_TYPENAME) {
2183 if (opts.standard != COMPILER_GMQCC) {
2184 if (parsewarning(parser, WARN_EXTENSIONS,
2185 "current standard does not allow variable declarations in for-loop initializers"))
2188 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, false))
2191 else if (parser->tok != ';')
2193 initexpr = parse_expression_leave(parser, false);
2198 /* move on to condition */
2199 if (parser->tok != ';') {
2200 parseerror(parser, "expected semicolon after for-loop initializer");
2203 if (!parser_next(parser)) {
2204 parseerror(parser, "expected for-loop condition");
2208 /* parse the condition */
2209 if (parser->tok != ';') {
2210 cond = parse_expression_leave(parser, false);
2215 /* move on to incrementor */
2216 if (parser->tok != ';') {
2217 parseerror(parser, "expected semicolon after for-loop initializer");
2220 if (!parser_next(parser)) {
2221 parseerror(parser, "expected for-loop condition");
2225 /* parse the incrementor */
2226 if (parser->tok != ')') {
2227 increment = parse_expression_leave(parser, false);
2230 if (!ast_side_effects(increment)) {
2231 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2237 if (parser->tok != ')') {
2238 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2241 /* parse into the 'then' branch */
2242 if (!parser_next(parser)) {
2243 parseerror(parser, "expected for-loop body");
2246 if (!parse_statement_or_block(parser, &ontrue))
2250 cond = process_condition(parser, cond, &ifnot);
2254 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2255 *out = (ast_expression*)aloop;
2257 if (!parser_leaveblock(parser))
2261 if (initexpr) ast_delete(initexpr);
2262 if (cond) ast_delete(cond);
2263 if (increment) ast_delete(increment);
2264 (void)!parser_leaveblock(parser);
2268 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2270 ast_expression *exp = NULL;
2271 ast_return *ret = NULL;
2272 ast_value *expected = parser->function->vtype;
2274 lex_ctx ctx = parser_ctx(parser);
2276 (void)block; /* not touching */
2278 if (!parser_next(parser)) {
2279 parseerror(parser, "expected return expression");
2283 if (parser->tok != ';') {
2284 exp = parse_expression(parser, false);
2288 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2289 parseerror(parser, "return with invalid expression");
2292 ret = ast_return_new(ctx, exp);
2298 if (!parser_next(parser))
2299 parseerror(parser, "parse error");
2300 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2301 if (opts.standard != COMPILER_GMQCC)
2302 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2304 parseerror(parser, "return without value");
2306 ret = ast_return_new(ctx, NULL);
2308 *out = (ast_expression*)ret;
2312 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2314 lex_ctx ctx = parser_ctx(parser);
2316 (void)block; /* not touching */
2318 if (!parser_next(parser) || parser->tok != ';') {
2319 parseerror(parser, "expected semicolon");
2323 if (!parser_next(parser))
2324 parseerror(parser, "parse error");
2326 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2330 /* returns true when it was a variable qualifier, false otherwise!
2331 * on error, cvq is set to CV_WRONG
2333 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn, bool *is_static)
2335 bool had_const = false;
2336 bool had_var = false;
2337 bool had_noref = false;
2338 bool had_noreturn = false;
2339 bool had_attrib = false;
2340 bool had_static = false;
2344 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2346 /* parse an attribute */
2347 if (!parser_next(parser)) {
2348 parseerror(parser, "expected attribute after `[[`");
2352 if (!strcmp(parser_tokval(parser), "noreturn")) {
2353 had_noreturn = true;
2354 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2355 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2360 else if (!strcmp(parser_tokval(parser), "noref")) {
2362 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2363 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2370 /* Skip tokens until we hit a ]] */
2371 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2372 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2373 if (!parser_next(parser)) {
2374 parseerror(parser, "error inside attribute");
2381 else if (!strcmp(parser_tokval(parser), "static"))
2383 else if (!strcmp(parser_tokval(parser), "const"))
2385 else if (!strcmp(parser_tokval(parser), "var"))
2387 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2389 else if (!strcmp(parser_tokval(parser), "noref"))
2391 else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2396 if (!parser_next(parser))
2406 *noreturn = had_noreturn;
2407 *is_static = had_static;
2410 parseerror(parser, "parse error after variable qualifier");
2415 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2417 ast_expression *operand;
2420 ast_switch *switchnode;
2421 ast_switch_case swcase;
2424 bool noref, noreturn, is_static;
2426 lex_ctx ctx = parser_ctx(parser);
2428 (void)block; /* not touching */
2431 /* parse over the opening paren */
2432 if (!parser_next(parser) || parser->tok != '(') {
2433 parseerror(parser, "expected switch operand in parenthesis");
2437 /* parse into the expression */
2438 if (!parser_next(parser)) {
2439 parseerror(parser, "expected switch operand");
2442 /* parse the operand */
2443 operand = parse_expression_leave(parser, false);
2447 switchnode = ast_switch_new(ctx, operand);
2450 if (parser->tok != ')') {
2451 ast_delete(switchnode);
2452 parseerror(parser, "expected closing paren after 'switch' operand");
2456 /* parse over the opening paren */
2457 if (!parser_next(parser) || parser->tok != '{') {
2458 ast_delete(switchnode);
2459 parseerror(parser, "expected list of cases");
2463 if (!parser_next(parser)) {
2464 ast_delete(switchnode);
2465 parseerror(parser, "expected 'case' or 'default'");
2469 /* new block; allow some variables to be declared here */
2470 parser_enterblock(parser);
2473 if (parser->tok == TOKEN_IDENT)
2474 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2475 if (typevar || parser->tok == TOKEN_TYPENAME) {
2476 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2477 ast_delete(switchnode);
2482 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2484 if (cvq == CV_WRONG) {
2485 ast_delete(switchnode);
2488 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2489 ast_delete(switchnode);
2498 while (parser->tok != '}') {
2499 ast_block *caseblock;
2501 if (!strcmp(parser_tokval(parser), "case")) {
2502 if (!parser_next(parser)) {
2503 ast_delete(switchnode);
2504 parseerror(parser, "expected expression for case");
2507 swcase.value = parse_expression_leave(parser, false);
2508 if (!swcase.value) {
2509 ast_delete(switchnode);
2510 parseerror(parser, "expected expression for case");
2513 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2514 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2515 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2521 else if (!strcmp(parser_tokval(parser), "default")) {
2522 swcase.value = NULL;
2523 if (!parser_next(parser)) {
2524 ast_delete(switchnode);
2525 parseerror(parser, "expected colon");
2530 ast_delete(switchnode);
2531 parseerror(parser, "expected 'case' or 'default'");
2535 /* Now the colon and body */
2536 if (parser->tok != ':') {
2537 if (swcase.value) ast_unref(swcase.value);
2538 ast_delete(switchnode);
2539 parseerror(parser, "expected colon");
2543 if (!parser_next(parser)) {
2544 if (swcase.value) ast_unref(swcase.value);
2545 ast_delete(switchnode);
2546 parseerror(parser, "expected statements or case");
2549 caseblock = ast_block_new(parser_ctx(parser));
2551 if (swcase.value) ast_unref(swcase.value);
2552 ast_delete(switchnode);
2555 swcase.code = (ast_expression*)caseblock;
2556 vec_push(switchnode->cases, swcase);
2558 ast_expression *expr;
2559 if (parser->tok == '}')
2561 if (parser->tok == TOKEN_KEYWORD) {
2562 if (!strcmp(parser_tokval(parser), "case") ||
2563 !strcmp(parser_tokval(parser), "default"))
2568 if (!parse_statement(parser, caseblock, &expr, true)) {
2569 ast_delete(switchnode);
2574 if (!ast_block_add_expr(caseblock, expr)) {
2575 ast_delete(switchnode);
2581 parser_leaveblock(parser);
2584 if (parser->tok != '}') {
2585 ast_delete(switchnode);
2586 parseerror(parser, "expected closing paren of case list");
2589 if (!parser_next(parser)) {
2590 ast_delete(switchnode);
2591 parseerror(parser, "parse error after switch");
2594 *out = (ast_expression*)switchnode;
2598 static bool parse_goto(parser_t *parser, ast_expression **out)
2603 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2604 parseerror(parser, "expected label name after `goto`");
2608 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2610 for (i = 0; i < vec_size(parser->labels); ++i) {
2611 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2612 ast_goto_set_label(gt, parser->labels[i]);
2616 if (i == vec_size(parser->labels))
2617 vec_push(parser->gotos, gt);
2619 if (!parser_next(parser) || parser->tok != ';') {
2620 parseerror(parser, "semicolon expected after goto label");
2623 if (!parser_next(parser)) {
2624 parseerror(parser, "parse error after goto");
2628 *out = (ast_expression*)gt;
2632 static bool parse_skipwhite(parser_t *parser)
2635 if (!parser_next(parser))
2637 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2638 return parser->tok < TOKEN_ERROR;
2641 static bool parse_eol(parser_t *parser)
2643 if (!parse_skipwhite(parser))
2645 return parser->tok == TOKEN_EOL;
2648 static bool parse_pragma_do(parser_t *parser)
2650 if (!parser_next(parser) ||
2651 parser->tok != TOKEN_IDENT ||
2652 strcmp(parser_tokval(parser), "pragma"))
2654 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2657 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2658 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2662 if (!strcmp(parser_tokval(parser), "noref")) {
2663 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2664 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2667 parser->noref = !!parser_token(parser)->constval.i;
2668 if (!parse_eol(parser)) {
2669 parseerror(parser, "parse error after `noref` pragma");
2675 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2682 static bool parse_pragma(parser_t *parser)
2685 parser->lex->flags.preprocessing = true;
2686 parser->lex->flags.mergelines = true;
2687 rv = parse_pragma_do(parser);
2688 if (parser->tok != TOKEN_EOL) {
2689 parseerror(parser, "junk after pragma");
2692 parser->lex->flags.preprocessing = false;
2693 parser->lex->flags.mergelines = false;
2694 if (!parser_next(parser)) {
2695 parseerror(parser, "parse error after pragma");
2701 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2703 bool noref, noreturn, is_static;
2705 ast_value *typevar = NULL;
2709 if (parser->tok == TOKEN_IDENT)
2710 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2712 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2714 /* local variable */
2716 parseerror(parser, "cannot declare a variable from here");
2719 if (opts.standard == COMPILER_QCC) {
2720 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2723 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2727 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2729 if (cvq == CV_WRONG)
2731 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2733 else if (parser->tok == TOKEN_KEYWORD)
2735 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2740 if (!parser_next(parser)) {
2741 parseerror(parser, "parse error after __builtin_debug_printtype");
2745 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2747 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2748 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2749 if (!parser_next(parser)) {
2750 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2756 if (!parse_statement(parser, block, out, allow_cases))
2759 con_out("__builtin_debug_printtype: got no output node\n");
2762 ast_type_to_string(*out, ty, sizeof(ty));
2763 con_out("__builtin_debug_printtype: `%s`\n", ty);
2768 else if (!strcmp(parser_tokval(parser), "return"))
2770 return parse_return(parser, block, out);
2772 else if (!strcmp(parser_tokval(parser), "if"))
2774 return parse_if(parser, block, out);
2776 else if (!strcmp(parser_tokval(parser), "while"))
2778 return parse_while(parser, block, out);
2780 else if (!strcmp(parser_tokval(parser), "do"))
2782 return parse_dowhile(parser, block, out);
2784 else if (!strcmp(parser_tokval(parser), "for"))
2786 if (opts.standard == COMPILER_QCC) {
2787 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2790 return parse_for(parser, block, out);
2792 else if (!strcmp(parser_tokval(parser), "break"))
2794 return parse_break_continue(parser, block, out, false);
2796 else if (!strcmp(parser_tokval(parser), "continue"))
2798 return parse_break_continue(parser, block, out, true);
2800 else if (!strcmp(parser_tokval(parser), "switch"))
2802 return parse_switch(parser, block, out);
2804 else if (!strcmp(parser_tokval(parser), "case") ||
2805 !strcmp(parser_tokval(parser), "default"))
2808 parseerror(parser, "unexpected 'case' label");
2813 else if (!strcmp(parser_tokval(parser), "goto"))
2815 return parse_goto(parser, out);
2817 else if (!strcmp(parser_tokval(parser), "typedef"))
2819 if (!parser_next(parser)) {
2820 parseerror(parser, "expected type definition after 'typedef'");
2823 return parse_typedef(parser);
2825 parseerror(parser, "Unexpected keyword");
2828 else if (parser->tok == '{')
2831 inner = parse_block(parser);
2834 *out = (ast_expression*)inner;
2837 else if (parser->tok == ':')
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "expected label name");
2845 if (parser->tok != TOKEN_IDENT) {
2846 parseerror(parser, "label must be an identifier");
2849 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2852 vec_push(parser->labels, label);
2853 *out = (ast_expression*)label;
2854 if (!parser_next(parser)) {
2855 parseerror(parser, "parse error after label");
2858 for (i = 0; i < vec_size(parser->gotos); ++i) {
2859 if (!strcmp(parser->gotos[i]->name, label->name)) {
2860 ast_goto_set_label(parser->gotos[i], label);
2861 vec_remove(parser->gotos, i, 1);
2867 else if (parser->tok == ';')
2869 if (!parser_next(parser)) {
2870 parseerror(parser, "parse error after empty statement");
2877 ast_expression *exp = parse_expression(parser, false);
2881 if (!ast_side_effects(exp)) {
2882 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2889 static bool parse_block_into(parser_t *parser, ast_block *block)
2893 parser_enterblock(parser);
2895 if (!parser_next(parser)) { /* skip the '{' */
2896 parseerror(parser, "expected function body");
2900 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2902 ast_expression *expr = NULL;
2903 if (parser->tok == '}')
2906 if (!parse_statement(parser, block, &expr, false)) {
2907 /* parseerror(parser, "parse error"); */
2913 if (!ast_block_add_expr(block, expr)) {
2920 if (parser->tok != '}') {
2923 (void)parser_next(parser);
2927 if (!parser_leaveblock(parser))
2929 return retval && !!block;
2932 static ast_block* parse_block(parser_t *parser)
2935 block = ast_block_new(parser_ctx(parser));
2938 if (!parse_block_into(parser, block)) {
2939 ast_block_delete(block);
2945 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2947 if (parser->tok == '{') {
2948 *out = (ast_expression*)parse_block(parser);
2951 return parse_statement(parser, NULL, out, false);
2954 static bool create_vector_members(ast_value *var, ast_member **me)
2957 size_t len = strlen(var->name);
2959 for (i = 0; i < 3; ++i) {
2960 char *name = (char*)mem_a(len+3);
2961 memcpy(name, var->name, len);
2963 name[len+1] = 'x'+i;
2965 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2974 do { ast_member_delete(me[--i]); } while(i);
2978 static bool parse_function_body(parser_t *parser, ast_value *var)
2980 ast_block *block = NULL;
2985 ast_expression *framenum = NULL;
2986 ast_expression *nextthink = NULL;
2987 /* None of the following have to be deleted */
2988 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2989 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2990 bool has_frame_think;
2994 has_frame_think = false;
2995 old = parser->function;
2997 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2998 parseerror(parser, "gotos/labels leaking");
3002 if (var->expression.flags & AST_FLAG_VARIADIC) {
3003 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3004 "variadic function with implementation will not be able to access additional parameters"))
3010 if (parser->tok == '[') {
3011 /* got a frame definition: [ framenum, nextthink ]
3012 * this translates to:
3013 * self.frame = framenum;
3014 * self.nextthink = time + 0.1;
3015 * self.think = nextthink;
3019 fld_think = parser_find_field(parser, "think");
3020 fld_nextthink = parser_find_field(parser, "nextthink");
3021 fld_frame = parser_find_field(parser, "frame");
3022 if (!fld_think || !fld_nextthink || !fld_frame) {
3023 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3024 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3027 gbl_time = parser_find_global(parser, "time");
3028 gbl_self = parser_find_global(parser, "self");
3029 if (!gbl_time || !gbl_self) {
3030 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3031 parseerror(parser, "please declare the following globals: `time`, `self`");
3035 if (!parser_next(parser))
3038 framenum = parse_expression_leave(parser, true);
3040 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3043 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3044 ast_unref(framenum);
3045 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3049 if (parser->tok != ',') {
3050 ast_unref(framenum);
3051 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3052 parseerror(parser, "Got a %i\n", parser->tok);
3056 if (!parser_next(parser)) {
3057 ast_unref(framenum);
3061 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3063 /* qc allows the use of not-yet-declared functions here
3064 * - this automatically creates a prototype */
3065 ast_value *thinkfunc;
3066 ast_expression *functype = fld_think->expression.next;
3068 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3069 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3070 ast_unref(framenum);
3071 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3075 if (!parser_next(parser)) {
3076 ast_unref(framenum);
3077 ast_delete(thinkfunc);
3081 vec_push(parser->globals, (ast_expression*)thinkfunc);
3082 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3083 nextthink = (ast_expression*)thinkfunc;
3086 nextthink = parse_expression_leave(parser, true);
3088 ast_unref(framenum);
3089 parseerror(parser, "expected a think-function in [frame,think] notation");
3094 if (!ast_istype(nextthink, ast_value)) {
3095 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3099 if (retval && parser->tok != ']') {
3100 parseerror(parser, "expected closing `]` for [frame,think] notation");
3104 if (retval && !parser_next(parser)) {
3108 if (retval && parser->tok != '{') {
3109 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3114 ast_unref(nextthink);
3115 ast_unref(framenum);
3119 has_frame_think = true;
3122 block = ast_block_new(parser_ctx(parser));
3124 parseerror(parser, "failed to allocate block");
3125 if (has_frame_think) {
3126 ast_unref(nextthink);
3127 ast_unref(framenum);
3132 if (has_frame_think) {
3134 ast_expression *self_frame;
3135 ast_expression *self_nextthink;
3136 ast_expression *self_think;
3137 ast_expression *time_plus_1;
3138 ast_store *store_frame;
3139 ast_store *store_nextthink;
3140 ast_store *store_think;
3142 ctx = parser_ctx(parser);
3143 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3144 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3145 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3147 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3148 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3150 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3151 if (self_frame) ast_delete(self_frame);
3152 if (self_nextthink) ast_delete(self_nextthink);
3153 if (self_think) ast_delete(self_think);
3154 if (time_plus_1) ast_delete(time_plus_1);
3160 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3161 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3162 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3165 ast_delete(self_frame);
3168 if (!store_nextthink) {
3169 ast_delete(self_nextthink);
3173 ast_delete(self_think);
3177 if (store_frame) ast_delete(store_frame);
3178 if (store_nextthink) ast_delete(store_nextthink);
3179 if (store_think) ast_delete(store_think);
3182 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3183 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3184 !ast_block_add_expr(block, (ast_expression*)store_think))
3191 parseerror(parser, "failed to generate code for [frame,think]");
3192 ast_unref(nextthink);
3193 ast_unref(framenum);
3199 parser_enterblock(parser);
3201 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3203 ast_value *param = var->expression.params[parami];
3206 if (param->expression.vtype != TYPE_VECTOR &&
3207 (param->expression.vtype != TYPE_FIELD ||
3208 param->expression.next->expression.vtype != TYPE_VECTOR))
3213 if (!create_vector_members(param, me)) {
3214 ast_block_delete(block);
3218 for (e = 0; e < 3; ++e) {
3219 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3220 ast_block_collect(block, (ast_expression*)me[e]);
3224 func = ast_function_new(ast_ctx(var), var->name, var);
3226 parseerror(parser, "failed to allocate function for `%s`", var->name);
3227 ast_block_delete(block);
3230 vec_push(parser->functions, func);
3232 parser->function = func;
3233 if (!parse_block_into(parser, block)) {
3234 ast_block_delete(block);
3238 vec_push(func->blocks, block);
3240 parser->function = old;
3241 if (!parser_leaveblock(parser))
3243 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3244 parseerror(parser, "internal error: local scopes left");
3248 if (parser->tok == ';')
3249 return parser_next(parser);
3250 else if (opts.standard == COMPILER_QCC)
3251 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3255 vec_pop(parser->functions);
3256 ast_function_delete(func);
3257 var->constval.vfunc = NULL;
3260 (void)!parser_leaveblock(parser);
3261 parser->function = old;
3265 static ast_expression *array_accessor_split(
3270 ast_expression *left,
3271 ast_expression *right
3277 lex_ctx ctx = ast_ctx(array);
3279 if (!left || !right) {
3280 if (left) ast_delete(left);
3281 if (right) ast_delete(right);
3285 cmp = ast_binary_new(ctx, INSTR_LT,
3286 (ast_expression*)index,
3287 (ast_expression*)parser_const_float(parser, middle));
3291 parseerror(parser, "internal error: failed to create comparison for array setter");
3295 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3297 ast_delete(cmp); /* will delete left and right */
3298 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3302 return (ast_expression*)ifthen;
3305 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3307 lex_ctx ctx = ast_ctx(array);
3309 if (from+1 == afterend) {
3310 /* set this value */
3313 ast_array_index *subscript;
3315 int assignop = type_store_instr[value->expression.vtype];
3317 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3318 assignop = INSTR_STORE_V;
3320 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3324 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3326 ast_delete(subscript);
3330 block = ast_block_new(ctx);
3336 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3341 ret = ast_return_new(ctx, NULL);
3347 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3352 return (ast_expression*)block;
3354 ast_expression *left, *right;
3355 size_t diff = afterend - from;
3356 size_t middle = from + diff/2;
3357 left = array_setter_node(parser, array, index, value, from, middle);
3358 right = array_setter_node(parser, array, index, value, middle, afterend);
3359 return array_accessor_split(parser, array, index, middle, left, right);
3363 static ast_expression *array_field_setter_node(
3372 lex_ctx ctx = ast_ctx(array);
3374 if (from+1 == afterend) {
3375 /* set this value */
3378 ast_entfield *entfield;
3379 ast_array_index *subscript;
3381 int assignop = type_storep_instr[value->expression.vtype];
3383 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3384 assignop = INSTR_STOREP_V;
3386 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3390 entfield = ast_entfield_new_force(ctx,
3391 (ast_expression*)entity,
3392 (ast_expression*)subscript,
3393 (ast_expression*)subscript);
3395 ast_delete(subscript);
3399 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3401 ast_delete(entfield);
3405 block = ast_block_new(ctx);
3411 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3416 ret = ast_return_new(ctx, NULL);
3422 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3427 return (ast_expression*)block;
3429 ast_expression *left, *right;
3430 size_t diff = afterend - from;
3431 size_t middle = from + diff/2;
3432 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3433 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3434 return array_accessor_split(parser, array, index, middle, left, right);
3438 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3440 lex_ctx ctx = ast_ctx(array);
3442 if (from+1 == afterend) {
3444 ast_array_index *subscript;
3446 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3450 ret = ast_return_new(ctx, (ast_expression*)subscript);
3452 ast_delete(subscript);
3456 return (ast_expression*)ret;
3458 ast_expression *left, *right;
3459 size_t diff = afterend - from;
3460 size_t middle = from + diff/2;
3461 left = array_getter_node(parser, array, index, from, middle);
3462 right = array_getter_node(parser, array, index, middle, afterend);
3463 return array_accessor_split(parser, array, index, middle, left, right);
3467 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3469 ast_function *func = NULL;
3470 ast_value *fval = NULL;
3471 ast_block *body = NULL;
3473 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3475 parseerror(parser, "failed to create accessor function value");
3479 func = ast_function_new(ast_ctx(array), funcname, fval);
3482 parseerror(parser, "failed to create accessor function node");
3486 body = ast_block_new(ast_ctx(array));
3488 parseerror(parser, "failed to create block for array accessor");
3494 vec_push(func->blocks, body);
3497 vec_push(parser->accessors, fval);
3502 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3504 ast_expression *root = NULL;
3505 ast_value *index = NULL;
3506 ast_value *value = NULL;
3510 if (!ast_istype(array->expression.next, ast_value)) {
3511 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3515 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3517 func = fval->constval.vfunc;
3518 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3520 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3521 value = ast_value_copy((ast_value*)array->expression.next);
3523 if (!index || !value) {
3524 parseerror(parser, "failed to create locals for array accessor");
3527 (void)!ast_value_set_name(value, "value"); /* not important */
3528 vec_push(fval->expression.params, index);
3529 vec_push(fval->expression.params, value);
3531 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3533 parseerror(parser, "failed to build accessor search tree");
3537 array->setter = fval;
3538 return ast_block_add_expr(func->blocks[0], root);
3540 if (index) ast_delete(index);
3541 if (value) ast_delete(value);
3542 if (root) ast_delete(root);
3548 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3550 ast_expression *root = NULL;
3551 ast_value *entity = NULL;
3552 ast_value *index = NULL;
3553 ast_value *value = NULL;
3557 if (!ast_istype(array->expression.next, ast_value)) {
3558 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3562 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3564 func = fval->constval.vfunc;
3565 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3567 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3568 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3569 value = ast_value_copy((ast_value*)array->expression.next);
3570 if (!entity || !index || !value) {
3571 parseerror(parser, "failed to create locals for array accessor");
3574 (void)!ast_value_set_name(value, "value"); /* not important */
3575 vec_push(fval->expression.params, entity);
3576 vec_push(fval->expression.params, index);
3577 vec_push(fval->expression.params, value);
3579 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3581 parseerror(parser, "failed to build accessor search tree");
3585 array->setter = fval;
3586 return ast_block_add_expr(func->blocks[0], root);
3588 if (entity) ast_delete(entity);
3589 if (index) ast_delete(index);
3590 if (value) ast_delete(value);
3591 if (root) ast_delete(root);
3597 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3599 ast_expression *root = NULL;
3600 ast_value *index = NULL;
3604 /* NOTE: checking array->expression.next rather than elemtype since
3605 * for fields elemtype is a temporary fieldtype.
3607 if (!ast_istype(array->expression.next, ast_value)) {
3608 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3612 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3614 func = fval->constval.vfunc;
3615 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3617 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3620 parseerror(parser, "failed to create locals for array accessor");
3623 vec_push(fval->expression.params, index);
3625 root = array_getter_node(parser, array, index, 0, array->expression.count);
3627 parseerror(parser, "failed to build accessor search tree");
3631 array->getter = fval;
3632 return ast_block_add_expr(func->blocks[0], root);
3634 if (index) ast_delete(index);
3635 if (root) ast_delete(root);
3641 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3642 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3650 bool variadic = false;
3652 ctx = parser_ctx(parser);
3654 /* for the sake of less code we parse-in in this function */
3655 if (!parser_next(parser)) {
3656 parseerror(parser, "expected parameter list");
3662 /* parse variables until we hit a closing paren */
3663 while (parser->tok != ')') {
3665 /* there must be commas between them */
3666 if (parser->tok != ',') {
3667 parseerror(parser, "expected comma or end of parameter list");
3670 if (!parser_next(parser)) {
3671 parseerror(parser, "expected parameter");
3677 if (parser->tok == TOKEN_DOTS) {
3678 /* '...' indicates a varargs function */
3680 if (!parser_next(parser)) {
3681 parseerror(parser, "expected parameter");
3684 if (parser->tok != ')') {
3685 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3691 /* for anything else just parse a typename */
3692 param = parse_typename(parser, NULL, NULL);
3695 vec_push(params, param);
3696 if (param->expression.vtype >= TYPE_VARIANT) {
3697 char tname[1024]; /* typename is reserved in C++ */
3698 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3699 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3705 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3709 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3710 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3713 if (!parser_next(parser)) {
3714 parseerror(parser, "parse error after typename");
3718 /* now turn 'var' into a function type */
3719 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3720 fval->expression.next = (ast_expression*)var;
3722 fval->expression.flags |= AST_FLAG_VARIADIC;
3725 var->expression.params = params;
3732 for (i = 0; i < vec_size(params); ++i)
3733 ast_delete(params[i]);
3738 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3740 ast_expression *cexp;
3741 ast_value *cval, *tmp;
3744 ctx = parser_ctx(parser);
3746 if (!parser_next(parser)) {
3748 parseerror(parser, "expected array-size");
3752 cexp = parse_expression_leave(parser, true);
3754 if (!cexp || !ast_istype(cexp, ast_value)) {
3758 parseerror(parser, "expected array-size as constant positive integer");
3761 cval = (ast_value*)cexp;
3763 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3764 tmp->expression.next = (ast_expression*)var;
3767 if (cval->expression.vtype == TYPE_INTEGER)
3768 tmp->expression.count = cval->constval.vint;
3769 else if (cval->expression.vtype == TYPE_FLOAT)
3770 tmp->expression.count = cval->constval.vfloat;
3774 parseerror(parser, "array-size must be a positive integer constant");
3779 if (parser->tok != ']') {
3781 parseerror(parser, "expected ']' after array-size");
3784 if (!parser_next(parser)) {
3786 parseerror(parser, "error after parsing array size");
3792 /* Parse a complete typename.
3793 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3794 * but when parsing variables separated by comma
3795 * 'storebase' should point to where the base-type should be kept.
3796 * The base type makes up every bit of type information which comes *before* the
3799 * The following will be parsed in its entirety:
3801 * The 'basetype' in this case is 'void()'
3802 * and if there's a comma after it, say:
3804 * then the type-information 'void()' can be stored in 'storebase'
3806 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3808 ast_value *var, *tmp;
3811 const char *name = NULL;
3812 bool isfield = false;
3813 bool wasarray = false;
3814 size_t morefields = 0;
3816 ctx = parser_ctx(parser);
3818 /* types may start with a dot */
3819 if (parser->tok == '.') {
3821 /* if we parsed a dot we need a typename now */
3822 if (!parser_next(parser)) {
3823 parseerror(parser, "expected typename for field definition");
3827 /* Further dots are handled seperately because they won't be part of the
3830 while (parser->tok == '.') {
3832 if (!parser_next(parser)) {
3833 parseerror(parser, "expected typename for field definition");
3838 if (parser->tok == TOKEN_IDENT)
3839 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3840 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3841 parseerror(parser, "expected typename");
3845 /* generate the basic type value */
3846 if (cached_typedef) {
3847 var = ast_value_copy(cached_typedef);
3848 ast_value_set_name(var, "<type(from_def)>");
3850 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3852 for (; morefields; --morefields) {
3853 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3854 tmp->expression.next = (ast_expression*)var;
3858 /* do not yet turn into a field - remember:
3859 * .void() foo; is a field too
3860 * .void()() foo; is a function
3864 if (!parser_next(parser)) {
3866 parseerror(parser, "parse error after typename");
3870 /* an opening paren now starts the parameter-list of a function
3871 * this is where original-QC has parameter lists.
3872 * We allow a single parameter list here.
3873 * Much like fteqcc we don't allow `float()() x`
3875 if (parser->tok == '(') {
3876 var = parse_parameter_list(parser, var);
3881 /* store the base if requested */
3883 *storebase = ast_value_copy(var);
3885 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3886 tmp->expression.next = (ast_expression*)*storebase;
3891 /* there may be a name now */
3892 if (parser->tok == TOKEN_IDENT) {
3893 name = util_strdup(parser_tokval(parser));
3895 if (!parser_next(parser)) {
3897 parseerror(parser, "error after variable or field declaration");
3902 /* now this may be an array */
3903 if (parser->tok == '[') {
3905 var = parse_arraysize(parser, var);
3910 /* This is the point where we can turn it into a field */
3912 /* turn it into a field if desired */
3913 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3914 tmp->expression.next = (ast_expression*)var;
3918 /* now there may be function parens again */
3919 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3920 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3921 if (parser->tok == '(' && wasarray)
3922 parseerror(parser, "arrays as part of a return type is not supported");
3923 while (parser->tok == '(') {
3924 var = parse_parameter_list(parser, var);
3933 /* finally name it */
3935 if (!ast_value_set_name(var, name)) {
3937 parseerror(parser, "internal error: failed to set name");
3940 /* free the name, ast_value_set_name duplicates */
3947 static bool parse_typedef(parser_t *parser)
3949 ast_value *typevar, *oldtype;
3950 ast_expression *old;
3952 typevar = parse_typename(parser, NULL, NULL);
3957 if ( (old = parser_find_var(parser, typevar->name)) ) {
3958 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3959 " -> `%s` has been declared here: %s:%i",
3960 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3961 ast_delete(typevar);
3965 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3966 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3967 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3968 ast_delete(typevar);
3972 vec_push(parser->_typedefs, typevar);
3973 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3975 if (parser->tok != ';') {
3976 parseerror(parser, "expected semicolon after typedef");
3979 if (!parser_next(parser)) {
3980 parseerror(parser, "parse error after typedef");
3987 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)
3991 ast_expression *old;
3995 ast_value *basetype = NULL;
3997 bool isparam = false;
3998 bool isvector = false;
3999 bool cleanvar = true;
4000 bool wasarray = false;
4004 if (!localblock && is_static)
4005 parseerror(parser, "`static` qualifier is not supported in global scope");
4007 /* get the first complete variable */
4008 var = parse_typename(parser, &basetype, cached_typedef);
4011 ast_delete(basetype);
4019 /* Part 0: finish the type */
4020 if (parser->tok == '(') {
4021 if (opts.standard == COMPILER_QCC)
4022 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4023 var = parse_parameter_list(parser, var);
4029 /* we only allow 1-dimensional arrays */
4030 if (parser->tok == '[') {
4032 var = parse_arraysize(parser, var);
4038 if (parser->tok == '(' && wasarray) {
4039 parseerror(parser, "arrays as part of a return type is not supported");
4040 /* we'll still parse the type completely for now */
4042 /* for functions returning functions */
4043 while (parser->tok == '(') {
4044 if (opts.standard == COMPILER_QCC)
4045 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4046 var = parse_parameter_list(parser, var);
4053 var->cvq = qualifier;
4054 /* in a noref section we simply bump the usecount */
4055 if (noref || parser->noref)
4058 var->expression.flags |= AST_FLAG_NORETURN;
4061 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4062 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4063 * is then filled with the previous definition and the parameter-names replaced.
4066 /* Deal with end_sys_ vars */
4068 if (!strcmp(var->name, "end_sys_globals")) {
4070 parser->crc_globals = vec_size(parser->globals);
4073 else if (!strcmp(var->name, "end_sys_fields")) {
4075 parser->crc_fields = vec_size(parser->fields);
4078 if (was_end && var->expression.vtype == TYPE_FIELD) {
4079 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4080 "global '%s' hint should not be a field",
4081 parser_tokval(parser)))
4088 if (!nofields && var->expression.vtype == TYPE_FIELD)
4090 /* deal with field declarations */
4091 old = parser_find_field(parser, var->name);
4093 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4094 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4103 parseerror(parser, "field `%s` already declared here: %s:%i",
4104 var->name, ast_ctx(old).file, ast_ctx(old).line);
4109 if (opts.standard == COMPILER_QCC &&
4110 (old = parser_find_global(parser, var->name)))
4112 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4113 parseerror(parser, "field `%s` already declared here: %s:%i",
4114 var->name, ast_ctx(old).file, ast_ctx(old).line);
4121 /* deal with other globals */
4122 old = parser_find_global(parser, var->name);
4123 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4125 /* This is a function which had a prototype */
4126 if (!ast_istype(old, ast_value)) {
4127 parseerror(parser, "internal error: prototype is not an ast_value");
4131 proto = (ast_value*)old;
4132 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4133 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4135 ast_ctx(proto).file, ast_ctx(proto).line);
4139 /* we need the new parameter-names */
4140 for (i = 0; i < vec_size(proto->expression.params); ++i)
4141 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4149 if (opts.standard == COMPILER_GMQCC) {
4150 parseerror(parser, "global `%s` already declared here: %s:%i",
4151 var->name, ast_ctx(old).file, ast_ctx(old).line);
4155 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4156 "global `%s` already declared here: %s:%i",
4157 var->name, ast_ctx(old).file, ast_ctx(old).line))
4162 proto = (ast_value*)old;
4163 if (!ast_istype(old, ast_value)) {
4164 parseerror(parser, "internal error: not an ast_value");
4173 if (opts.standard == COMPILER_QCC &&
4174 (old = parser_find_field(parser, var->name)))
4176 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4177 parseerror(parser, "global `%s` already declared here: %s:%i",
4178 var->name, ast_ctx(old).file, ast_ctx(old).line);
4185 else /* it's not a global */
4187 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4188 if (old && !isparam) {
4189 parseerror(parser, "local `%s` already declared here: %s:%i",
4190 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4194 old = parser_find_local(parser, var->name, 0, &isparam);
4195 if (old && isparam) {
4196 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4197 "local `%s` is shadowing a parameter", var->name))
4199 parseerror(parser, "local `%s` already declared here: %s:%i",
4200 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4204 if (opts.standard != COMPILER_GMQCC) {
4213 * Create the global/local, and deal with vector types.
4216 if (var->expression.vtype == TYPE_VECTOR)
4218 else if (var->expression.vtype == TYPE_FIELD &&
4219 var->expression.next->expression.vtype == TYPE_VECTOR)
4223 if (!create_vector_members(var, me)) {
4230 /* deal with global variables, fields, functions */
4231 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4232 var->isfield = true;
4233 vec_push(parser->fields, (ast_expression*)var);
4234 util_htset(parser->htfields, var->name, var);
4236 for (i = 0; i < 3; ++i) {
4237 vec_push(parser->fields, (ast_expression*)me[i]);
4238 util_htset(parser->htfields, me[i]->name, me[i]);
4243 vec_push(parser->globals, (ast_expression*)var);
4244 util_htset(parser->htglobals, var->name, var);
4246 for (i = 0; i < 3; ++i) {
4247 vec_push(parser->globals, (ast_expression*)me[i]);
4248 util_htset(parser->htglobals, me[i]->name, me[i]);
4254 /* a static adds itself to be generated like any other global
4255 * but is added to the local namespace instead
4257 char *defname = NULL;
4258 size_t prefix_len, ln;
4260 ln = strlen(parser->function->name);
4261 vec_append(defname, ln, parser->function->name);
4263 vec_append(defname, 2, "::");
4264 /* remember the length up to here */
4265 prefix_len = vec_size(defname);
4267 /* Add it to the local scope */
4268 util_htset(vec_last(parser->variables), var->name, (void*)var);
4269 /* now rename the global */
4270 ln = strlen(var->name);
4271 vec_append(defname, ln, var->name);
4272 ast_value_set_name(var, defname);
4274 /* push it to the to-be-generated globals */
4275 vec_push(parser->globals, (ast_expression*)var);
4277 /* same game for the vector members */
4279 for (i = 0; i < 3; ++i) {
4280 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4282 vec_shrinkto(defname, prefix_len);
4283 ln = strlen(me[i]->name);
4284 vec_append(defname, ln, me[i]->name);
4285 ast_member_set_name(me[i], defname);
4287 vec_push(parser->globals, (ast_expression*)me[i]);
4292 vec_push(localblock->locals, var);
4293 parser_addlocal(parser, var->name, (ast_expression*)var);
4295 for (i = 0; i < 3; ++i) {
4296 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4297 ast_block_collect(localblock, (ast_expression*)me[i]);
4303 me[0] = me[1] = me[2] = NULL;
4308 if (var->expression.vtype == TYPE_ARRAY) {
4310 snprintf(name, sizeof(name), "%s##SET", var->name);
4311 if (!parser_create_array_setter(parser, var, name))
4313 snprintf(name, sizeof(name), "%s##GET", var->name);
4314 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4317 else if (!localblock && !nofields &&
4318 var->expression.vtype == TYPE_FIELD &&
4319 var->expression.next->expression.vtype == TYPE_ARRAY)
4322 ast_expression *telem;
4324 ast_value *array = (ast_value*)var->expression.next;
4326 if (!ast_istype(var->expression.next, ast_value)) {
4327 parseerror(parser, "internal error: field element type must be an ast_value");
4331 snprintf(name, sizeof(name), "%s##SETF", var->name);
4332 if (!parser_create_array_field_setter(parser, array, name))
4335 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4336 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4337 tfield->expression.next = telem;
4338 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4339 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4347 if (parser->tok == ';') {
4348 ast_delete(basetype);
4349 if (!parser_next(parser)) {
4350 parseerror(parser, "error after variable declaration");
4356 if (parser->tok == ',')
4360 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4363 parseerror(parser, "missing comma or semicolon while parsing variables");
4367 if (localblock && opts.standard == COMPILER_QCC) {
4368 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4369 "initializing expression turns variable `%s` into a constant in this standard",
4376 if (parser->tok != '{') {
4377 if (parser->tok != '=') {
4378 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4382 if (!parser_next(parser)) {
4383 parseerror(parser, "error parsing initializer");
4387 else if (opts.standard == COMPILER_QCC) {
4388 parseerror(parser, "expected '=' before function body in this standard");
4391 if (parser->tok == '#') {
4392 ast_function *func = NULL;
4395 parseerror(parser, "cannot declare builtins within functions");
4398 if (var->expression.vtype != TYPE_FUNCTION) {
4399 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4402 if (!parser_next(parser)) {
4403 parseerror(parser, "expected builtin number");
4406 if (parser->tok != TOKEN_INTCONST) {
4407 parseerror(parser, "builtin number must be an integer constant");
4410 if (parser_token(parser)->constval.i < 0) {
4411 parseerror(parser, "builtin number must be an integer greater than zero");
4415 if (var->hasvalue) {
4416 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4417 "builtin `%s` has already been defined\n"
4418 " -> previous declaration here: %s:%i",
4419 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4423 func = ast_function_new(ast_ctx(var), var->name, var);
4425 parseerror(parser, "failed to allocate function for `%s`", var->name);
4428 vec_push(parser->functions, func);
4430 func->builtin = -parser_token(parser)->constval.i-1;
4433 if (!parser_next(parser)) {
4434 parseerror(parser, "expected comma or semicolon");
4436 ast_function_delete(func);
4437 var->constval.vfunc = NULL;
4441 else if (parser->tok == '{' || parser->tok == '[')
4444 parseerror(parser, "cannot declare functions within functions");
4449 ast_ctx(proto) = parser_ctx(parser);
4451 if (!parse_function_body(parser, var))
4453 ast_delete(basetype);
4454 for (i = 0; i < vec_size(parser->gotos); ++i)
4455 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4456 vec_free(parser->gotos);
4457 vec_free(parser->labels);
4460 ast_expression *cexp;
4463 cexp = parse_expression_leave(parser, true);
4468 cval = (ast_value*)cexp;
4469 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4470 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4473 if (opts.standard != COMPILER_GMQCC &&
4474 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4475 qualifier != CV_VAR)
4477 var->cvq = CV_CONST;
4479 var->hasvalue = true;
4480 if (cval->expression.vtype == TYPE_STRING)
4481 var->constval.vstring = parser_strdup(cval->constval.vstring);
4482 else if (cval->expression.vtype == TYPE_FIELD)
4483 var->constval.vfield = cval;
4485 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4490 shunt sy = { NULL, NULL };
4493 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4494 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4495 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4496 if (!parser_sy_apply_operator(parser, &sy))
4499 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4500 parseerror(parser, "internal error: leaked operands");
4501 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4511 if (parser->tok == ',') {
4512 if (!parser_next(parser)) {
4513 parseerror(parser, "expected another variable");
4517 if (parser->tok != TOKEN_IDENT) {
4518 parseerror(parser, "expected another variable");
4521 var = ast_value_copy(basetype);
4523 ast_value_set_name(var, parser_tokval(parser));
4524 if (!parser_next(parser)) {
4525 parseerror(parser, "error parsing variable declaration");
4531 if (parser->tok != ';') {
4532 parseerror(parser, "missing semicolon after variables");
4536 if (!parser_next(parser)) {
4537 parseerror(parser, "parse error after variable declaration");
4541 ast_delete(basetype);
4545 if (cleanvar && var)
4547 ast_delete(basetype);
4551 ast_delete(basetype);
4552 if (cleanvar && var)
4554 if (me[0]) ast_member_delete(me[0]);
4555 if (me[1]) ast_member_delete(me[1]);
4556 if (me[2]) ast_member_delete(me[2]);
4560 static bool parser_global_statement(parser_t *parser)
4564 bool noreturn = false;
4565 bool is_static = false;
4566 ast_value *istype = NULL;
4568 if (parser->tok == TOKEN_IDENT)
4569 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4571 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4573 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4575 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4577 if (cvq == CV_WRONG)
4579 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4581 else if (parser->tok == TOKEN_KEYWORD)
4583 if (!strcmp(parser_tokval(parser), "typedef")) {
4584 if (!parser_next(parser)) {
4585 parseerror(parser, "expected type definition after 'typedef'");
4588 return parse_typedef(parser);
4590 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4593 else if (parser->tok == '#')
4595 return parse_pragma(parser);
4597 else if (parser->tok == '$')
4599 if (!parser_next(parser)) {
4600 parseerror(parser, "parse error");
4606 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4612 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4614 return util_crc16(old, str, strlen(str));
4617 static void progdefs_crc_file(const char *str)
4619 /* write to progdefs.h here */
4623 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4625 old = progdefs_crc_sum(old, str);
4626 progdefs_crc_file(str);
4630 static void generate_checksum(parser_t *parser)
4632 uint16_t crc = 0xFFFF;
4636 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4637 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4639 progdefs_crc_file("\tint\tpad;\n");
4640 progdefs_crc_file("\tint\tofs_return[3];\n");
4641 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4642 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4643 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4644 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4645 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4646 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4647 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4648 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4650 for (i = 0; i < parser->crc_globals; ++i) {
4651 if (!ast_istype(parser->globals[i], ast_value))
4653 value = (ast_value*)(parser->globals[i]);
4654 switch (value->expression.vtype) {
4655 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4656 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4657 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4658 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4660 crc = progdefs_crc_both(crc, "\tint\t");
4663 crc = progdefs_crc_both(crc, value->name);
4664 crc = progdefs_crc_both(crc, ";\n");
4666 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4667 for (i = 0; i < parser->crc_fields; ++i) {
4668 if (!ast_istype(parser->fields[i], ast_value))
4670 value = (ast_value*)(parser->fields[i]);
4671 switch (value->expression.next->expression.vtype) {
4672 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4673 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4674 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4675 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4677 crc = progdefs_crc_both(crc, "\tint\t");
4680 crc = progdefs_crc_both(crc, value->name);
4681 crc = progdefs_crc_both(crc, ";\n");
4683 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4688 static parser_t *parser;
4694 parser = (parser_t*)mem_a(sizeof(parser_t));
4698 memset(parser, 0, sizeof(*parser));
4700 for (i = 0; i < operator_count; ++i) {
4701 if (operators[i].id == opid1('=')) {
4702 parser->assign_op = operators+i;
4706 if (!parser->assign_op) {
4707 printf("internal error: initializing parser: failed to find assign operator\n");
4712 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4713 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4714 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4715 vec_push(parser->_blocktypedefs, 0);
4719 bool parser_compile()
4721 /* initial lexer/parser state */
4722 parser->lex->flags.noops = true;
4724 if (parser_next(parser))
4726 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4728 if (!parser_global_statement(parser)) {
4729 if (parser->tok == TOKEN_EOF)
4730 parseerror(parser, "unexpected eof");
4731 else if (compile_errors)
4732 parseerror(parser, "there have been errors, bailing out");
4733 lex_close(parser->lex);
4739 parseerror(parser, "parse error");
4740 lex_close(parser->lex);
4745 lex_close(parser->lex);
4748 return !compile_errors;
4751 bool parser_compile_file(const char *filename)
4753 parser->lex = lex_open(filename);
4755 con_err("failed to open file \"%s\"\n", filename);
4758 return parser_compile();
4761 bool parser_compile_string(const char *name, const char *str, size_t len)
4763 parser->lex = lex_open_string(str, len, name);
4765 con_err("failed to create lexer for string \"%s\"\n", name);
4768 return parser_compile();
4771 void parser_cleanup()
4774 for (i = 0; i < vec_size(parser->accessors); ++i) {
4775 ast_delete(parser->accessors[i]->constval.vfunc);
4776 parser->accessors[i]->constval.vfunc = NULL;
4777 ast_delete(parser->accessors[i]);
4779 for (i = 0; i < vec_size(parser->functions); ++i) {
4780 ast_delete(parser->functions[i]);
4782 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4783 ast_delete(parser->imm_vector[i]);
4785 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4786 ast_delete(parser->imm_string[i]);
4788 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4789 ast_delete(parser->imm_float[i]);
4791 for (i = 0; i < vec_size(parser->fields); ++i) {
4792 ast_delete(parser->fields[i]);
4794 for (i = 0; i < vec_size(parser->globals); ++i) {
4795 ast_delete(parser->globals[i]);
4797 vec_free(parser->accessors);
4798 vec_free(parser->functions);
4799 vec_free(parser->imm_vector);
4800 vec_free(parser->imm_string);
4801 vec_free(parser->imm_float);
4802 vec_free(parser->globals);
4803 vec_free(parser->fields);
4805 for (i = 0; i < vec_size(parser->variables); ++i)
4806 util_htdel(parser->variables[i]);
4807 vec_free(parser->variables);
4808 vec_free(parser->_blocklocals);
4809 vec_free(parser->_locals);
4811 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4812 ast_delete(parser->_typedefs[i]);
4813 vec_free(parser->_typedefs);
4814 for (i = 0; i < vec_size(parser->typedefs); ++i)
4815 util_htdel(parser->typedefs[i]);
4816 vec_free(parser->typedefs);
4817 vec_free(parser->_blocktypedefs);
4819 vec_free(parser->_block_ctx);
4821 vec_free(parser->labels);
4822 vec_free(parser->gotos);
4827 bool parser_finish(const char *output)
4833 if (compile_errors) {
4834 con_out("*** there were compile errors\n");
4838 ir = ir_builder_new("gmqcc_out");
4840 con_out("failed to allocate builder\n");
4844 for (i = 0; i < vec_size(parser->fields); ++i) {
4847 if (!ast_istype(parser->fields[i], ast_value))
4849 field = (ast_value*)parser->fields[i];
4850 hasvalue = field->hasvalue;
4851 field->hasvalue = false;
4852 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4853 con_out("failed to generate field %s\n", field->name);
4854 ir_builder_delete(ir);
4859 ast_expression *subtype;
4860 field->hasvalue = true;
4861 subtype = field->expression.next;
4862 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4863 if (subtype->expression.vtype == TYPE_FIELD)
4864 ifld->fieldtype = subtype->expression.next->expression.vtype;
4865 else if (subtype->expression.vtype == TYPE_FUNCTION)
4866 ifld->outtype = subtype->expression.next->expression.vtype;
4867 (void)!ir_value_set_field(field->ir_v, ifld);
4870 for (i = 0; i < vec_size(parser->globals); ++i) {
4872 if (!ast_istype(parser->globals[i], ast_value))
4874 asvalue = (ast_value*)(parser->globals[i]);
4875 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4876 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4877 "unused global: `%s`", asvalue->name);
4879 if (!ast_global_codegen(asvalue, ir, false)) {
4880 con_out("failed to generate global %s\n", asvalue->name);
4881 ir_builder_delete(ir);
4885 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4886 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4887 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4888 ir_builder_delete(ir);
4892 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4893 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4894 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4895 ir_builder_delete(ir);
4899 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4900 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4901 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4902 ir_builder_delete(ir);
4906 for (i = 0; i < vec_size(parser->globals); ++i) {
4908 if (!ast_istype(parser->globals[i], ast_value))
4910 asvalue = (ast_value*)(parser->globals[i]);
4911 if (!ast_generate_accessors(asvalue, ir)) {
4912 ir_builder_delete(ir);
4916 for (i = 0; i < vec_size(parser->fields); ++i) {
4918 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4920 if (!ast_istype((ast_expression*)asvalue, ast_value))
4922 if (asvalue->expression.vtype != TYPE_ARRAY)
4924 if (!ast_generate_accessors(asvalue, ir)) {
4925 ir_builder_delete(ir);
4929 for (i = 0; i < vec_size(parser->functions); ++i) {
4930 if (!ast_function_codegen(parser->functions[i], ir)) {
4931 con_out("failed to generate function %s\n", parser->functions[i]->name);
4932 ir_builder_delete(ir);
4937 ir_builder_dump(ir, con_out);
4938 for (i = 0; i < vec_size(parser->functions); ++i) {
4939 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4940 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4941 ir_builder_delete(ir);
4946 if (compile_Werrors) {
4947 con_out("*** there were warnings treated as errors\n");
4948 compile_show_werrors();
4954 ir_builder_dump(ir, con_out);
4956 generate_checksum(parser);
4958 if (!ir_builder_generate(ir, output)) {
4959 con_out("*** failed to generate output file\n");
4960 ir_builder_delete(ir);
4965 ir_builder_delete(ir);