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;
81 /* we store the '=' operator info */
82 const oper_info *assign_op;
84 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
85 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
86 * anything else: type error
90 /* Keep track of our ternary vs parenthesis nesting state.
91 * If we reach a 'comma' operator in a ternary without a paren,
92 * we shall trigger -Wternary-precedence.
100 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
102 static void parser_enterblock(parser_t *parser);
103 static bool parser_leaveblock(parser_t *parser);
104 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
105 static bool parse_typedef(parser_t *parser);
106 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn);
107 static ast_block* parse_block(parser_t *parser);
108 static bool parse_block_into(parser_t *parser, ast_block *block);
109 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
110 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
111 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
112 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
114 static void parseerror(parser_t *parser, const char *fmt, ...)
121 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
125 /* returns true if it counts as an error */
126 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
131 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
136 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
141 r = vcompile_warning(ctx, warntype, fmt, ap);
146 /**********************************************************************
147 * some maths used for constant folding
150 vector vec3_add(vector a, vector b)
159 vector vec3_sub(vector a, vector b)
168 qcfloat vec3_mulvv(vector a, vector b)
170 return (a.x * b.x + a.y * b.y + a.z * b.z);
173 vector vec3_mulvf(vector a, float b)
182 /**********************************************************************
186 bool parser_next(parser_t *parser)
188 /* lex_do kills the previous token */
189 parser->tok = lex_do(parser->lex);
190 if (parser->tok == TOKEN_EOF)
192 if (parser->tok >= TOKEN_ERROR) {
193 parseerror(parser, "lex error");
199 #define parser_tokval(p) ((p)->lex->tok.value)
200 #define parser_token(p) (&((p)->lex->tok))
201 #define parser_ctx(p) ((p)->lex->tok.ctx)
203 static ast_value* parser_const_float(parser_t *parser, double d)
207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
208 const double compare = parser->imm_float[i]->constval.vfloat;
209 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
210 return parser->imm_float[i];
212 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
214 out->hasvalue = true;
215 out->constval.vfloat = d;
216 vec_push(parser->imm_float, out);
220 static ast_value* parser_const_float_0(parser_t *parser)
222 if (!parser->imm_float_zero)
223 parser->imm_float_zero = parser_const_float(parser, 0);
224 return parser->imm_float_zero;
227 static ast_value* parser_const_float_1(parser_t *parser)
229 if (!parser->imm_float_one)
230 parser->imm_float_one = parser_const_float(parser, 1);
231 return parser->imm_float_one;
234 static char *parser_strdup(const char *str)
237 /* actually dup empty strings */
238 char *out = (char*)mem_a(1);
242 return util_strdup(str);
245 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
249 for (i = 0; i < vec_size(parser->imm_string); ++i) {
250 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
251 return parser->imm_string[i];
255 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
256 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
258 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
260 out->hasvalue = true;
261 out->constval.vstring = parser_strdup(str);
262 vec_push(parser->imm_string, out);
266 static ast_value* parser_const_vector(parser_t *parser, vector v)
270 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
271 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
272 return parser->imm_vector[i];
274 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
276 out->hasvalue = true;
277 out->constval.vvec = v;
278 vec_push(parser->imm_vector, out);
282 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
288 return parser_const_vector(parser, v);
291 static ast_value* parser_const_vector_0(parser_t *parser)
293 if (!parser->imm_vector_zero)
294 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
295 return parser->imm_vector_zero;
298 static ast_expression* parser_find_field(parser_t *parser, const char *name)
300 return ( ast_expression*)util_htget(parser->htfields, name);
303 static ast_expression* parser_find_global(parser_t *parser, const char *name)
305 return (ast_expression*)util_htget(parser->htglobals, name);
308 static ast_expression* parser_find_param(parser_t *parser, const char *name)
312 if (!parser->function)
314 fun = parser->function->vtype;
315 for (i = 0; i < vec_size(fun->expression.params); ++i) {
316 if (!strcmp(fun->expression.params[i]->name, name))
317 return (ast_expression*)(fun->expression.params[i]);
322 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
327 hash = util_hthash(parser->htglobals, name);
330 for (i = vec_size(parser->variables); i > upto;) {
332 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
336 return parser_find_param(parser, name);
339 static ast_expression* parser_find_var(parser_t *parser, const char *name)
343 v = parser_find_local(parser, name, 0, &dummy);
344 if (!v) v = parser_find_global(parser, name);
348 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
352 hash = util_hthash(parser->typedefs[0], name);
354 for (i = vec_size(parser->typedefs); i > upto;) {
356 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
364 size_t etype; /* 0 = expression, others are operators */
368 ast_block *block; /* for commas and function calls */
377 #define SY_PAREN_EXPR '('
378 #define SY_PAREN_FUNC 'f'
379 #define SY_PAREN_INDEX '['
380 #define SY_PAREN_TERNARY '?'
382 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
393 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
397 e.out = (ast_expression*)v;
404 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
406 e.etype = 1 + (op - operators);
415 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
427 # define DEBUGSHUNTDO(x) x
429 # define DEBUGSHUNTDO(x)
432 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
433 * so we need to rotate it to become ent.(foo[n]).
435 static bool rotate_entfield_array_index_nodes(ast_expression **out)
437 ast_array_index *index;
438 ast_entfield *entfield;
442 ast_expression *entity;
444 lex_ctx ctx = ast_ctx(*out);
446 if (!ast_istype(*out, ast_array_index))
448 index = (ast_array_index*)*out;
450 if (!ast_istype(index->array, ast_entfield))
452 entfield = (ast_entfield*)index->array;
454 if (!ast_istype(entfield->field, ast_value))
456 field = (ast_value*)entfield->field;
459 entity = entfield->entity;
463 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
464 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
465 *out = (ast_expression*)entfield;
470 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
472 switch (v->expression.vtype) {
474 return !!v->constval.vfloat;
476 return !!v->constval.vint;
478 if (OPTS_FLAG(CORRECT_LOGIC))
479 return v->constval.vvec.x &&
480 v->constval.vvec.y &&
483 return !!(v->constval.vvec.x);
485 if (!v->constval.vstring)
487 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
489 return !!v->constval.vstring[0];
491 compile_error(ctx, "internal error: immediate_is_true on invalid type");
492 return !!v->constval.vfunc;
496 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
500 ast_expression *out = NULL;
501 ast_expression *exprs[3];
502 ast_block *blocks[3];
503 ast_value *asvalue[3];
504 ast_binstore *asbinstore;
505 size_t i, assignop, addop, subop;
506 qcint generated_op = 0;
511 if (!vec_size(sy->ops)) {
512 parseerror(parser, "internal error: missing operator");
516 if (vec_last(sy->ops).paren) {
517 parseerror(parser, "unmatched parenthesis");
521 op = &operators[vec_last(sy->ops).etype - 1];
522 ctx = vec_last(sy->ops).ctx;
524 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
526 if (vec_size(sy->out) < op->operands) {
527 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
528 op->op, (int)op->id);
532 vec_shrinkby(sy->ops, 1);
534 /* op(:?) has no input and no output */
538 vec_shrinkby(sy->out, op->operands);
539 for (i = 0; i < op->operands; ++i) {
540 exprs[i] = sy->out[vec_size(sy->out)+i].out;
541 blocks[i] = sy->out[vec_size(sy->out)+i].block;
542 asvalue[i] = (ast_value*)exprs[i];
545 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
546 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
550 #define NotSameType(T) \
551 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
552 exprs[0]->expression.vtype != T)
553 #define CanConstFold1(A) \
554 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
555 (A)->expression.vtype != TYPE_FUNCTION)
556 #define CanConstFold(A, B) \
557 (CanConstFold1(A) && CanConstFold1(B))
558 #define ConstV(i) (asvalue[(i)]->constval.vvec)
559 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
560 #define ConstS(i) (asvalue[(i)]->constval.vstring)
564 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
568 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
569 if (exprs[1]->expression.vtype != TYPE_FIELD) {
570 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
573 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
575 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
576 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
580 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
586 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
587 !(exprs[0]->expression.vtype == TYPE_FIELD &&
588 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
590 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
591 parseerror(parser, "cannot index value of type %s", ty1);
594 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
595 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
596 parseerror(parser, "index must be of type float, not %s", ty1);
599 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
600 if (rotate_entfield_array_index_nodes(&out))
603 /* This is not broken in fteqcc anymore */
604 if (opts.standard != COMPILER_GMQCC) {
605 /* this error doesn't need to make us bail out */
606 (void)!parsewarning(parser, WARN_EXTENSIONS,
607 "accessing array-field members of an entity without parenthesis\n"
608 " -> this is an extension from -std=gmqcc");
616 if (!ast_block_add_expr(blocks[0], exprs[1]))
619 blocks[0] = ast_block_new(ctx);
620 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
621 !ast_block_add_expr(blocks[0], exprs[1]))
626 if (!ast_block_set_type(blocks[0], exprs[1]))
629 vec_push(sy->out, syblock(ctx, blocks[0]));
636 switch (exprs[0]->expression.vtype) {
638 if (CanConstFold1(exprs[0]))
639 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
641 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
642 (ast_expression*)parser_const_float_0(parser),
646 if (CanConstFold1(exprs[0]))
647 out = (ast_expression*)parser_const_vector_f(parser,
648 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
650 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
651 (ast_expression*)parser_const_vector_0(parser),
655 parseerror(parser, "invalid types used in expression: cannot negate type %s",
656 type_name[exprs[0]->expression.vtype]);
662 switch (exprs[0]->expression.vtype) {
664 if (CanConstFold1(exprs[0]))
665 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
667 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
670 if (CanConstFold1(exprs[0]))
671 out = (ast_expression*)parser_const_float(parser,
672 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
674 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
677 if (CanConstFold1(exprs[0])) {
678 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
679 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
681 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
683 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
684 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
686 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
689 /* we don't constant-fold NOT for these types */
691 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
694 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
697 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
698 type_name[exprs[0]->expression.vtype]);
704 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
705 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
707 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
708 type_name[exprs[0]->expression.vtype],
709 type_name[exprs[1]->expression.vtype]);
712 switch (exprs[0]->expression.vtype) {
714 if (CanConstFold(exprs[0], exprs[1]))
716 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
719 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
722 if (CanConstFold(exprs[0], exprs[1]))
723 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
725 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
728 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
729 type_name[exprs[0]->expression.vtype],
730 type_name[exprs[1]->expression.vtype]);
735 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
736 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
738 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
739 type_name[exprs[1]->expression.vtype],
740 type_name[exprs[0]->expression.vtype]);
743 switch (exprs[0]->expression.vtype) {
745 if (CanConstFold(exprs[0], exprs[1]))
746 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
748 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
751 if (CanConstFold(exprs[0], exprs[1]))
752 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
754 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
757 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
758 type_name[exprs[1]->expression.vtype],
759 type_name[exprs[0]->expression.vtype]);
764 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
765 exprs[0]->expression.vtype != TYPE_VECTOR &&
766 exprs[0]->expression.vtype != TYPE_FLOAT &&
767 exprs[1]->expression.vtype != TYPE_VECTOR &&
768 exprs[1]->expression.vtype != TYPE_FLOAT)
770 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
771 type_name[exprs[1]->expression.vtype],
772 type_name[exprs[0]->expression.vtype]);
775 switch (exprs[0]->expression.vtype) {
777 if (exprs[1]->expression.vtype == TYPE_VECTOR)
779 if (CanConstFold(exprs[0], exprs[1]))
780 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
782 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
786 if (CanConstFold(exprs[0], exprs[1]))
787 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
789 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
793 if (exprs[1]->expression.vtype == TYPE_FLOAT)
795 if (CanConstFold(exprs[0], exprs[1]))
796 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
798 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
802 if (CanConstFold(exprs[0], exprs[1]))
803 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
805 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
809 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
810 type_name[exprs[1]->expression.vtype],
811 type_name[exprs[0]->expression.vtype]);
816 if (NotSameType(TYPE_FLOAT)) {
817 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
818 type_name[exprs[0]->expression.vtype],
819 type_name[exprs[1]->expression.vtype]);
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
825 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
829 parseerror(parser, "qc does not have a modulo operator");
833 if (NotSameType(TYPE_FLOAT)) {
834 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
835 type_name[exprs[0]->expression.vtype],
836 type_name[exprs[1]->expression.vtype]);
839 if (CanConstFold(exprs[0], exprs[1]))
840 out = (ast_expression*)parser_const_float(parser,
841 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
842 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
844 out = (ast_expression*)ast_binary_new(ctx,
845 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
849 parseerror(parser, "TODO: bitxor");
854 case opid3('<','<','='):
855 case opid3('>','>','='):
856 parseerror(parser, "TODO: shifts");
860 generated_op += 1; /* INSTR_OR */
862 generated_op += INSTR_AND;
864 if (NotSameType(TYPE_FLOAT)) {
865 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
866 type_name[exprs[0]->expression.vtype],
867 type_name[exprs[1]->expression.vtype]);
868 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
869 parseerror(parser, "TODO: optional early out");
873 if (CanConstFold(exprs[0], exprs[1]))
875 if (OPTS_FLAG(PERL_LOGIC)) {
876 if (immediate_is_true(ctx, asvalue[0]))
880 out = (ast_expression*)parser_const_float(parser,
881 ( (generated_op == INSTR_OR)
882 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
883 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
888 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
889 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
890 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
891 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
894 for (i = 0; i < 2; ++i) {
895 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
896 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
898 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
900 exprs[i] = out; out = NULL;
901 if (OPTS_FLAG(PERL_LOGIC)) {
902 /* here we want to keep the right expressions' type */
906 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
907 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
909 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
911 exprs[i] = out; out = NULL;
912 if (OPTS_FLAG(PERL_LOGIC)) {
913 /* here we want to keep the right expressions' type */
918 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
923 if (vec_last(parser->pot) != POT_TERNARY2) {
924 parseerror(parser, "mismatched parenthesis/ternary");
927 vec_pop(parser->pot);
928 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
929 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
930 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
931 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
934 if (CanConstFold1(exprs[0]))
935 out = (ConstF(0) ? exprs[1] : exprs[2]);
937 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
941 generated_op += 1; /* INSTR_GT */
943 generated_op += 1; /* INSTR_LT */
944 case opid2('>', '='):
945 generated_op += 1; /* INSTR_GE */
946 case opid2('<', '='):
947 generated_op += INSTR_LE;
948 if (NotSameType(TYPE_FLOAT)) {
949 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
950 type_name[exprs[0]->expression.vtype],
951 type_name[exprs[1]->expression.vtype]);
954 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
956 case opid2('!', '='):
957 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
958 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
959 type_name[exprs[0]->expression.vtype],
960 type_name[exprs[1]->expression.vtype]);
963 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
965 case opid2('=', '='):
966 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
967 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
968 type_name[exprs[0]->expression.vtype],
969 type_name[exprs[1]->expression.vtype]);
972 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
976 if (ast_istype(exprs[0], ast_entfield)) {
977 ast_expression *field = ((ast_entfield*)exprs[0])->field;
978 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
979 exprs[0]->expression.vtype == TYPE_FIELD &&
980 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
982 assignop = type_storep_instr[TYPE_VECTOR];
985 assignop = type_storep_instr[exprs[0]->expression.vtype];
986 if (assignop == AINSTR_END ||
987 !ast_compare_type(field->expression.next, exprs[1]))
989 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
990 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
991 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
992 field->expression.next->expression.vtype == TYPE_FUNCTION &&
993 exprs[1]->expression.vtype == TYPE_FUNCTION)
995 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
996 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
1002 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1007 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1008 exprs[0]->expression.vtype == TYPE_FIELD &&
1009 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1011 assignop = type_store_instr[TYPE_VECTOR];
1014 assignop = type_store_instr[exprs[0]->expression.vtype];
1017 if (assignop == AINSTR_END) {
1018 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1019 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1020 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1022 else if (!ast_compare_type(exprs[0], exprs[1])) {
1023 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1024 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1025 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1026 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1027 exprs[1]->expression.vtype == TYPE_FUNCTION)
1029 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1030 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
1036 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1039 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1040 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1042 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1044 case opid3('+','+','P'):
1045 case opid3('-','-','P'):
1047 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1048 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1049 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1052 if (op->id == opid3('+','+','P'))
1053 addop = INSTR_ADD_F;
1055 addop = INSTR_SUB_F;
1056 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1057 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1059 if (ast_istype(exprs[0], ast_entfield)) {
1060 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1062 (ast_expression*)parser_const_float_1(parser));
1064 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1066 (ast_expression*)parser_const_float_1(parser));
1069 case opid3('S','+','+'):
1070 case opid3('S','-','-'):
1072 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1073 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1077 if (op->id == opid3('S','+','+')) {
1078 addop = INSTR_ADD_F;
1079 subop = INSTR_SUB_F;
1081 addop = INSTR_SUB_F;
1082 subop = INSTR_ADD_F;
1084 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1085 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1087 if (ast_istype(exprs[0], ast_entfield)) {
1088 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1090 (ast_expression*)parser_const_float_1(parser));
1092 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1094 (ast_expression*)parser_const_float_1(parser));
1098 out = (ast_expression*)ast_binary_new(ctx, subop,
1100 (ast_expression*)parser_const_float_1(parser));
1102 case opid2('+','='):
1103 case opid2('-','='):
1104 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1105 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1107 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1108 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1109 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1113 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1114 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1116 if (ast_istype(exprs[0], ast_entfield))
1117 assignop = type_storep_instr[exprs[0]->expression.vtype];
1119 assignop = type_store_instr[exprs[0]->expression.vtype];
1120 switch (exprs[0]->expression.vtype) {
1122 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1123 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1124 exprs[0], exprs[1]);
1127 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1128 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1129 exprs[0], exprs[1]);
1132 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1133 type_name[exprs[0]->expression.vtype],
1134 type_name[exprs[1]->expression.vtype]);
1138 case opid2('*','='):
1139 case opid2('/','='):
1140 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1141 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1142 exprs[0]->expression.vtype == TYPE_VECTOR))
1144 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1145 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1146 parseerror(parser, "invalid types used in expression: %s and %s",
1150 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1151 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1153 if (ast_istype(exprs[0], ast_entfield))
1154 assignop = type_storep_instr[exprs[0]->expression.vtype];
1156 assignop = type_store_instr[exprs[0]->expression.vtype];
1157 switch (exprs[0]->expression.vtype) {
1159 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1160 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1161 exprs[0], exprs[1]);
1164 if (op->id == opid2('*','=')) {
1165 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1166 exprs[0], exprs[1]);
1168 /* there's no DIV_VF */
1169 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1170 (ast_expression*)parser_const_float_1(parser),
1174 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1179 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1180 type_name[exprs[0]->expression.vtype],
1181 type_name[exprs[1]->expression.vtype]);
1185 case opid2('&','='):
1186 case opid2('|','='):
1187 if (NotSameType(TYPE_FLOAT)) {
1188 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1189 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1190 parseerror(parser, "invalid types used in expression: %s and %s",
1194 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1195 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1197 if (ast_istype(exprs[0], ast_entfield))
1198 assignop = type_storep_instr[exprs[0]->expression.vtype];
1200 assignop = type_store_instr[exprs[0]->expression.vtype];
1201 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1202 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1203 exprs[0], exprs[1]);
1205 case opid3('&','~','='):
1206 /* This is like: a &= ~(b);
1207 * But QC has no bitwise-not, so we implement it as
1210 if (NotSameType(TYPE_FLOAT)) {
1211 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1212 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1213 parseerror(parser, "invalid types used in expression: %s and %s",
1217 if (ast_istype(exprs[0], ast_entfield))
1218 assignop = type_storep_instr[exprs[0]->expression.vtype];
1220 assignop = type_store_instr[exprs[0]->expression.vtype];
1221 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1224 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1225 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1227 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1228 asbinstore->keep_dest = true;
1229 out = (ast_expression*)asbinstore;
1235 parseerror(parser, "failed to apply operand %s", op->op);
1239 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1240 vec_push(sy->out, syexp(ctx, out));
1244 static bool parser_close_call(parser_t *parser, shunt *sy)
1246 /* was a function call */
1247 ast_expression *fun;
1253 vec_shrinkby(sy->ops, 1);
1254 fid = sy->ops[vec_size(sy->ops)].off;
1256 /* out[fid] is the function
1257 * everything above is parameters...
1258 * 0 params = nothing
1259 * 1 params = ast_expression
1263 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1264 parseerror(parser, "internal error: function call needs function and parameter list...");
1268 fun = sy->out[fid].out;
1270 if (fun == intrinsic_debug_typestring) {
1272 if (fid+2 != vec_size(sy->out) ||
1273 vec_last(sy->out).block)
1275 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1278 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1279 ast_unref(vec_last(sy->out).out);
1280 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1281 (ast_expression*)parser_const_string(parser, ty, false));
1282 vec_shrinkby(sy->out, 1);
1286 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1288 parseerror(parser, "internal error: failed to create ast_call node");
1292 if (fid+1 == vec_size(sy->out)) {
1295 } else if (fid+2 == vec_size(sy->out)) {
1297 vec_shrinkby(sy->out, 1);
1298 params = sy->out[vec_size(sy->out)].block;
1302 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1304 paramcount = vec_size(params->exprs);
1305 call->params = params->exprs;
1306 params->exprs = NULL;
1309 if (!ast_call_check_types(call))
1312 parseerror(parser, "invalid function call");
1316 /* overwrite fid, the function, with a call */
1317 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1319 if (fun->expression.vtype != TYPE_FUNCTION) {
1320 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1324 if (!fun->expression.next) {
1325 parseerror(parser, "could not determine function return type");
1328 if (vec_size(fun->expression.params) != paramcount &&
1329 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1330 vec_size(fun->expression.params) < paramcount))
1333 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1335 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1336 if (opts.standard == COMPILER_GMQCC)
1339 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1340 " -> `%s` has been declared here: %s:%i",
1341 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1342 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1344 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1345 " -> it has been declared here: %s:%i",
1346 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1347 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1353 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1354 "too %s parameters for call to %s: expected %i, got %i\n"
1355 " -> `%s` has been declared here: %s:%i",
1356 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1357 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1359 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1360 "too %s parameters for function call: expected %i, got %i\n"
1361 " -> it has been declared here: %s:%i",
1362 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1363 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1371 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1373 if (!vec_size(sy->ops)) {
1374 parseerror(parser, "unmatched closing paren");
1377 /* this would for bit a + (x) because there are no operators inside (x)
1378 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1379 parseerror(parser, "empty parenthesis expression");
1383 while (vec_size(sy->ops)) {
1384 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1385 if (!parser_close_call(parser, sy))
1389 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1390 vec_shrinkby(sy->ops, 1);
1391 return !functions_only;
1393 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1396 /* pop off the parenthesis */
1397 vec_shrinkby(sy->ops, 1);
1398 /* then apply the index operator */
1399 if (!parser_sy_apply_operator(parser, sy))
1403 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1406 if (vec_last(parser->pot) != POT_TERNARY1) {
1407 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1410 vec_last(parser->pot) = POT_TERNARY2;
1411 /* pop off the parenthesis */
1412 vec_shrinkby(sy->ops, 1);
1415 if (!parser_sy_apply_operator(parser, sy))
1421 static void parser_reclassify_token(parser_t *parser)
1424 for (i = 0; i < operator_count; ++i) {
1425 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1426 parser->tok = TOKEN_OPERATOR;
1432 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1434 ast_expression *expr = NULL;
1436 bool wantop = false;
1437 bool gotmemberof = false;
1439 /* count the parens because an if starts with one, so the
1440 * end of a condition is an unmatched closing paren
1448 parser->lex->flags.noops = false;
1450 parser_reclassify_token(parser);
1455 gotmemberof = false;
1457 parser->memberof = 0;
1459 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1460 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1462 /* a translatable string */
1466 parseerror(parser, "expected operator or end of statement, got constant");
1470 parser->lex->flags.noops = true;
1471 if (!parser_next(parser) || parser->tok != '(') {
1472 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1475 parser->lex->flags.noops = false;
1476 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1477 parseerror(parser, "expected a constant string in translatable-string extension");
1480 val = parser_const_string(parser, parser_tokval(parser), true);
1484 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1485 DEBUGSHUNTDO(con_out("push string\n"));
1487 if (!parser_next(parser) || parser->tok != ')') {
1488 parseerror(parser, "expected closing paren after translatable string");
1492 else if (parser->tok == TOKEN_IDENT)
1494 ast_expression *var;
1496 parseerror(parser, "expected operator or end of statement");
1501 if (opts.standard == COMPILER_GMQCC)
1503 if (parser->memberof == TYPE_ENTITY) {
1504 /* still get vars first since there could be a fieldpointer */
1505 var = parser_find_var(parser, parser_tokval(parser));
1507 var = parser_find_field(parser, parser_tokval(parser));
1509 else if (parser->memberof == TYPE_VECTOR)
1511 parseerror(parser, "TODO: implement effective vector member access");
1514 else if (parser->memberof) {
1515 parseerror(parser, "namespace for member not found");
1519 var = parser_find_var(parser, parser_tokval(parser));
1521 var = parser_find_var(parser, parser_tokval(parser));
1523 var = parser_find_field(parser, parser_tokval(parser));
1527 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1528 var = (ast_expression*)intrinsic_debug_typestring;
1533 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1539 if (ast_istype(var, ast_value)) {
1540 ((ast_value*)var)->uses++;
1542 else if (ast_istype(var, ast_member)) {
1543 ast_member *mem = (ast_member*)var;
1544 if (ast_istype(mem->owner, ast_value))
1545 ((ast_value*)(mem->owner))->uses++;
1548 vec_push(sy.out, syexp(parser_ctx(parser), var));
1549 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1551 else if (parser->tok == TOKEN_FLOATCONST) {
1554 parseerror(parser, "expected operator or end of statement, got constant");
1558 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1561 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1562 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1564 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1567 parseerror(parser, "expected operator or end of statement, got constant");
1571 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1574 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1575 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1577 else if (parser->tok == TOKEN_STRINGCONST) {
1580 parseerror(parser, "expected operator or end of statement, got constant");
1584 val = parser_const_string(parser, parser_tokval(parser), false);
1587 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1588 DEBUGSHUNTDO(con_out("push string\n"));
1590 else if (parser->tok == TOKEN_VECTORCONST) {
1593 parseerror(parser, "expected operator or end of statement, got constant");
1597 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1600 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1601 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1602 parser_token(parser)->constval.v.x,
1603 parser_token(parser)->constval.v.y,
1604 parser_token(parser)->constval.v.z));
1606 else if (parser->tok == '(') {
1607 parseerror(parser, "internal error: '(' should be classified as operator");
1610 else if (parser->tok == '[') {
1611 parseerror(parser, "internal error: '[' should be classified as operator");
1614 else if (parser->tok == ')') {
1616 DEBUGSHUNTDO(con_out("do[op] )\n"));
1620 /* we do expect an operator next */
1621 /* closing an opening paren */
1622 if (!parser_close_paren(parser, &sy, false))
1624 if (vec_last(parser->pot) != POT_PAREN) {
1625 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1628 vec_pop(parser->pot);
1630 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1634 /* allowed for function calls */
1635 if (!parser_close_paren(parser, &sy, true))
1637 if (vec_last(parser->pot) != POT_PAREN) {
1638 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1641 vec_pop(parser->pot);
1645 else if (parser->tok == ']') {
1647 parseerror(parser, "operand expected");
1651 if (!parser_close_paren(parser, &sy, false))
1653 if (vec_last(parser->pot) != POT_PAREN) {
1654 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1657 vec_pop(parser->pot);
1660 else if (parser->tok == TOKEN_TYPENAME) {
1661 parseerror(parser, "unexpected typename");
1664 else if (parser->tok != TOKEN_OPERATOR) {
1666 parseerror(parser, "expected operator or end of statement");
1673 /* classify the operator */
1674 const oper_info *op;
1675 const oper_info *olast = NULL;
1677 for (o = 0; o < operator_count; ++o) {
1678 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1679 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1680 !strcmp(parser_tokval(parser), operators[o].op))
1685 if (o == operator_count) {
1686 /* no operator found... must be the end of the statement */
1689 /* found an operator */
1692 /* when declaring variables, a comma starts a new variable */
1693 if (op->id == opid1(',') && !parens && stopatcomma) {
1694 /* fixup the token */
1699 /* a colon without a pervious question mark cannot be a ternary */
1700 if (!ternaries && op->id == opid2(':','?')) {
1705 if (op->id == opid1(',')) {
1706 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1707 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1711 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1712 olast = &operators[vec_last(sy.ops).etype-1];
1715 (op->prec < olast->prec) ||
1716 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1718 if (!parser_sy_apply_operator(parser, &sy))
1720 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1721 olast = &operators[vec_last(sy.ops).etype-1];
1726 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1727 /* for gmqcc standard: open up the namespace of the previous type */
1728 ast_expression *prevex = vec_last(sy.out).out;
1730 parseerror(parser, "unexpected member operator");
1733 if (prevex->expression.vtype == TYPE_ENTITY)
1734 parser->memberof = TYPE_ENTITY;
1735 else if (prevex->expression.vtype == TYPE_VECTOR)
1736 parser->memberof = TYPE_VECTOR;
1738 parseerror(parser, "type error: type has no members");
1744 if (op->id == opid1('(')) {
1746 size_t sycount = vec_size(sy.out);
1747 DEBUGSHUNTDO(con_out("push [op] (\n"));
1748 ++parens; vec_push(parser->pot, POT_PAREN);
1749 /* we expected an operator, this is the function-call operator */
1750 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1752 ++parens; vec_push(parser->pot, POT_PAREN);
1753 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1754 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1757 } else if (op->id == opid1('[')) {
1759 parseerror(parser, "unexpected array subscript");
1762 ++parens; vec_push(parser->pot, POT_PAREN);
1763 /* push both the operator and the paren, this makes life easier */
1764 vec_push(sy.ops, syop(parser_ctx(parser), op));
1765 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1767 } else if (op->id == opid2('?',':')) {
1768 vec_push(sy.ops, syop(parser_ctx(parser), op));
1769 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1772 vec_push(parser->pot, POT_TERNARY1);
1773 } else if (op->id == opid2(':','?')) {
1774 if (!vec_size(parser->pot)) {
1775 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1778 if (vec_last(parser->pot) != POT_TERNARY1) {
1779 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1782 if (!parser_close_paren(parser, &sy, false))
1784 vec_push(sy.ops, syop(parser_ctx(parser), op));
1788 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1789 vec_push(sy.ops, syop(parser_ctx(parser), op));
1790 wantop = !!(op->flags & OP_SUFFIX);
1793 if (!parser_next(parser)) {
1796 if (parser->tok == ';' ||
1797 (!parens && parser->tok == ']'))
1803 while (vec_size(sy.ops)) {
1804 if (!parser_sy_apply_operator(parser, &sy))
1808 parser->lex->flags.noops = true;
1809 if (!vec_size(sy.out)) {
1810 parseerror(parser, "empty expression");
1813 expr = sy.out[0].out;
1816 DEBUGSHUNTDO(con_out("shunt done\n"));
1817 if (vec_size(parser->pot)) {
1818 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1821 vec_free(parser->pot);
1825 parser->lex->flags.noops = true;
1831 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1833 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1836 if (!parser_next(parser)) {
1843 static void parser_enterblock(parser_t *parser)
1845 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1846 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1847 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1848 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1849 vec_push(parser->_block_ctx, parser_ctx(parser));
1852 static bool parser_leaveblock(parser_t *parser)
1855 size_t locals, typedefs;
1857 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1858 parseerror(parser, "internal error: parser_leaveblock with no block");
1862 util_htdel(vec_last(parser->variables));
1863 vec_pop(parser->variables);
1864 if (!vec_size(parser->_blocklocals)) {
1865 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1869 locals = vec_last(parser->_blocklocals);
1870 vec_pop(parser->_blocklocals);
1871 while (vec_size(parser->_locals) != locals) {
1872 ast_expression *e = vec_last(parser->_locals);
1873 ast_value *v = (ast_value*)e;
1874 vec_pop(parser->_locals);
1875 if (ast_istype(e, ast_value) && !v->uses) {
1876 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1883 typedefs = vec_last(parser->_blocktypedefs);
1884 while (vec_size(parser->_typedefs) != typedefs) {
1885 ast_delete(vec_last(parser->_typedefs));
1886 vec_pop(parser->_typedefs);
1888 util_htdel(vec_last(parser->typedefs));
1889 vec_pop(parser->typedefs);
1891 vec_pop(parser->_block_ctx);
1895 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1897 vec_push(parser->_locals, e);
1898 util_htset(vec_last(parser->variables), name, (void*)e);
1901 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1905 ast_expression *prev;
1907 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1910 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1913 parseerror(parser, "internal error: failed to process condition");
1918 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1920 /* vector types need to be cast to true booleans */
1921 ast_binary *bin = (ast_binary*)cond;
1922 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1924 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1926 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1929 parseerror(parser, "internal error: failed to process condition");
1936 unary = (ast_unary*)cond;
1937 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1939 cond = unary->operand;
1940 unary->operand = NULL;
1943 unary = (ast_unary*)cond;
1947 parseerror(parser, "internal error: failed to process condition");
1949 if (ifnot) *_ifnot = !*_ifnot;
1953 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1956 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1959 lex_ctx ctx = parser_ctx(parser);
1961 (void)block; /* not touching */
1963 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1964 if (!parser_next(parser)) {
1965 parseerror(parser, "expected condition or 'not'");
1968 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1970 if (!parser_next(parser)) {
1971 parseerror(parser, "expected condition in parenthesis");
1975 if (parser->tok != '(') {
1976 parseerror(parser, "expected 'if' condition in parenthesis");
1979 /* parse into the expression */
1980 if (!parser_next(parser)) {
1981 parseerror(parser, "expected 'if' condition after opening paren");
1984 /* parse the condition */
1985 cond = parse_expression_leave(parser, false);
1989 if (parser->tok != ')') {
1990 parseerror(parser, "expected closing paren after 'if' condition");
1994 /* parse into the 'then' branch */
1995 if (!parser_next(parser)) {
1996 parseerror(parser, "expected statement for on-true branch of 'if'");
2000 if (!parse_statement_or_block(parser, &ontrue)) {
2004 /* check for an else */
2005 if (!strcmp(parser_tokval(parser), "else")) {
2006 /* parse into the 'else' branch */
2007 if (!parser_next(parser)) {
2008 parseerror(parser, "expected on-false branch after 'else'");
2013 if (!parse_statement_or_block(parser, &onfalse)) {
2020 cond = process_condition(parser, cond, &ifnot);
2022 if (ontrue) ast_delete(ontrue);
2023 if (onfalse) ast_delete(onfalse);
2028 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2030 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2031 *out = (ast_expression*)ifthen;
2035 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2038 ast_expression *cond, *ontrue;
2042 lex_ctx ctx = parser_ctx(parser);
2044 (void)block; /* not touching */
2046 /* skip the 'while' and check for opening paren */
2047 if (!parser_next(parser) || parser->tok != '(') {
2048 parseerror(parser, "expected 'while' condition in parenthesis");
2051 /* parse into the expression */
2052 if (!parser_next(parser)) {
2053 parseerror(parser, "expected 'while' condition after opening paren");
2056 /* parse the condition */
2057 cond = parse_expression_leave(parser, false);
2061 if (parser->tok != ')') {
2062 parseerror(parser, "expected closing paren after 'while' condition");
2066 /* parse into the 'then' branch */
2067 if (!parser_next(parser)) {
2068 parseerror(parser, "expected while-loop body");
2072 if (!parse_statement_or_block(parser, &ontrue)) {
2077 cond = process_condition(parser, cond, &ifnot);
2082 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2083 *out = (ast_expression*)aloop;
2087 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2090 ast_expression *cond, *ontrue;
2094 lex_ctx ctx = parser_ctx(parser);
2096 (void)block; /* not touching */
2098 /* skip the 'do' and get the body */
2099 if (!parser_next(parser)) {
2100 parseerror(parser, "expected loop body");
2103 if (!parse_statement_or_block(parser, &ontrue))
2106 /* expect the "while" */
2107 if (parser->tok != TOKEN_KEYWORD ||
2108 strcmp(parser_tokval(parser), "while"))
2110 parseerror(parser, "expected 'while' and condition");
2115 /* skip the 'while' and check for opening paren */
2116 if (!parser_next(parser) || parser->tok != '(') {
2117 parseerror(parser, "expected 'while' condition in parenthesis");
2121 /* parse into the expression */
2122 if (!parser_next(parser)) {
2123 parseerror(parser, "expected 'while' condition after opening paren");
2127 /* parse the condition */
2128 cond = parse_expression_leave(parser, false);
2132 if (parser->tok != ')') {
2133 parseerror(parser, "expected closing paren after 'while' condition");
2139 if (!parser_next(parser) || parser->tok != ';') {
2140 parseerror(parser, "expected semicolon after condition");
2146 if (!parser_next(parser)) {
2147 parseerror(parser, "parse error");
2153 cond = process_condition(parser, cond, &ifnot);
2158 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2159 *out = (ast_expression*)aloop;
2163 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2166 ast_expression *initexpr, *cond, *increment, *ontrue;
2172 lex_ctx ctx = parser_ctx(parser);
2174 parser_enterblock(parser);
2181 /* skip the 'while' and check for opening paren */
2182 if (!parser_next(parser) || parser->tok != '(') {
2183 parseerror(parser, "expected 'for' expressions in parenthesis");
2186 /* parse into the expression */
2187 if (!parser_next(parser)) {
2188 parseerror(parser, "expected 'for' initializer after opening paren");
2193 if (parser->tok == TOKEN_IDENT)
2194 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2196 if (typevar || parser->tok == TOKEN_TYPENAME) {
2197 if (opts.standard != COMPILER_GMQCC) {
2198 if (parsewarning(parser, WARN_EXTENSIONS,
2199 "current standard does not allow variable declarations in for-loop initializers"))
2202 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false))
2205 else if (parser->tok != ';')
2207 initexpr = parse_expression_leave(parser, false);
2212 /* move on to condition */
2213 if (parser->tok != ';') {
2214 parseerror(parser, "expected semicolon after for-loop initializer");
2217 if (!parser_next(parser)) {
2218 parseerror(parser, "expected for-loop condition");
2222 /* parse the condition */
2223 if (parser->tok != ';') {
2224 cond = parse_expression_leave(parser, false);
2229 /* move on to incrementor */
2230 if (parser->tok != ';') {
2231 parseerror(parser, "expected semicolon after for-loop initializer");
2234 if (!parser_next(parser)) {
2235 parseerror(parser, "expected for-loop condition");
2239 /* parse the incrementor */
2240 if (parser->tok != ')') {
2241 increment = parse_expression_leave(parser, false);
2244 if (!ast_side_effects(increment)) {
2245 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2251 if (parser->tok != ')') {
2252 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2255 /* parse into the 'then' branch */
2256 if (!parser_next(parser)) {
2257 parseerror(parser, "expected for-loop body");
2260 if (!parse_statement_or_block(parser, &ontrue))
2264 cond = process_condition(parser, cond, &ifnot);
2268 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2269 *out = (ast_expression*)aloop;
2271 if (!parser_leaveblock(parser))
2275 if (initexpr) ast_delete(initexpr);
2276 if (cond) ast_delete(cond);
2277 if (increment) ast_delete(increment);
2278 (void)!parser_leaveblock(parser);
2282 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2284 ast_expression *exp = NULL;
2285 ast_return *ret = NULL;
2286 ast_value *expected = parser->function->vtype;
2288 lex_ctx ctx = parser_ctx(parser);
2290 (void)block; /* not touching */
2292 if (!parser_next(parser)) {
2293 parseerror(parser, "expected return expression");
2297 if (parser->tok != ';') {
2298 exp = parse_expression(parser, false);
2302 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2303 parseerror(parser, "return with invalid expression");
2306 ret = ast_return_new(ctx, exp);
2312 if (!parser_next(parser))
2313 parseerror(parser, "parse error");
2314 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2315 if (opts.standard != COMPILER_GMQCC)
2316 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2318 parseerror(parser, "return without value");
2320 ret = ast_return_new(ctx, NULL);
2322 *out = (ast_expression*)ret;
2326 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2328 lex_ctx ctx = parser_ctx(parser);
2330 (void)block; /* not touching */
2332 if (!parser_next(parser) || parser->tok != ';') {
2333 parseerror(parser, "expected semicolon");
2337 if (!parser_next(parser))
2338 parseerror(parser, "parse error");
2340 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2344 /* returns true when it was a variable qualifier, false otherwise!
2345 * on error, cvq is set to CV_WRONG
2347 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn)
2349 bool had_const = false;
2350 bool had_var = false;
2351 bool had_noref = false;
2352 bool had_noreturn = false;
2353 bool had_attrib = false;
2357 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2359 /* parse an attribute */
2360 if (!parser_next(parser)) {
2361 parseerror(parser, "expected attribute after `[[`");
2365 if (!strcmp(parser_tokval(parser), "noreturn")) {
2366 had_noreturn = true;
2367 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2368 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2373 else if (!strcmp(parser_tokval(parser), "noref")) {
2375 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2376 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2383 /* Skip tokens until we hit a ]] */
2384 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2385 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2386 if (!parser_next(parser)) {
2387 parseerror(parser, "error inside attribute");
2394 else if (!strcmp(parser_tokval(parser), "const"))
2396 else if (!strcmp(parser_tokval(parser), "var"))
2398 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2400 else if (!strcmp(parser_tokval(parser), "noref"))
2402 else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib) {
2407 if (!parser_next(parser))
2417 *noreturn = had_noreturn;
2420 parseerror(parser, "parse error after variable qualifier");
2425 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2427 ast_expression *operand;
2430 ast_switch *switchnode;
2431 ast_switch_case swcase;
2434 bool noref, noreturn;
2436 lex_ctx ctx = parser_ctx(parser);
2438 (void)block; /* not touching */
2441 /* parse over the opening paren */
2442 if (!parser_next(parser) || parser->tok != '(') {
2443 parseerror(parser, "expected switch operand in parenthesis");
2447 /* parse into the expression */
2448 if (!parser_next(parser)) {
2449 parseerror(parser, "expected switch operand");
2452 /* parse the operand */
2453 operand = parse_expression_leave(parser, false);
2457 switchnode = ast_switch_new(ctx, operand);
2460 if (parser->tok != ')') {
2461 ast_delete(switchnode);
2462 parseerror(parser, "expected closing paren after 'switch' operand");
2466 /* parse over the opening paren */
2467 if (!parser_next(parser) || parser->tok != '{') {
2468 ast_delete(switchnode);
2469 parseerror(parser, "expected list of cases");
2473 if (!parser_next(parser)) {
2474 ast_delete(switchnode);
2475 parseerror(parser, "expected 'case' or 'default'");
2479 /* new block; allow some variables to be declared here */
2480 parser_enterblock(parser);
2483 if (parser->tok == TOKEN_IDENT)
2484 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2485 if (typevar || parser->tok == TOKEN_TYPENAME) {
2486 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false)) {
2487 ast_delete(switchnode);
2492 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn))
2494 if (cvq == CV_WRONG) {
2495 ast_delete(switchnode);
2498 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn)) {
2499 ast_delete(switchnode);
2508 while (parser->tok != '}') {
2509 ast_block *caseblock;
2511 if (parser->tok != TOKEN_KEYWORD) {
2512 ast_delete(switchnode);
2513 parseerror(parser, "expected 'case' or 'default'");
2516 if (!strcmp(parser_tokval(parser), "case")) {
2517 if (!parser_next(parser)) {
2518 ast_delete(switchnode);
2519 parseerror(parser, "expected expression for case");
2522 swcase.value = parse_expression_leave(parser, false);
2523 if (!swcase.value) {
2524 ast_delete(switchnode);
2525 parseerror(parser, "expected expression for case");
2528 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2529 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2530 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2536 else if (!strcmp(parser_tokval(parser), "default")) {
2537 swcase.value = NULL;
2538 if (!parser_next(parser)) {
2539 ast_delete(switchnode);
2540 parseerror(parser, "expected colon");
2545 /* Now the colon and body */
2546 if (parser->tok != ':') {
2547 if (swcase.value) ast_unref(swcase.value);
2548 ast_delete(switchnode);
2549 parseerror(parser, "expected colon");
2553 if (!parser_next(parser)) {
2554 if (swcase.value) ast_unref(swcase.value);
2555 ast_delete(switchnode);
2556 parseerror(parser, "expected statements or case");
2559 caseblock = ast_block_new(parser_ctx(parser));
2561 if (swcase.value) ast_unref(swcase.value);
2562 ast_delete(switchnode);
2565 swcase.code = (ast_expression*)caseblock;
2566 vec_push(switchnode->cases, swcase);
2568 ast_expression *expr;
2569 if (parser->tok == '}')
2571 if (parser->tok == TOKEN_KEYWORD) {
2572 if (!strcmp(parser_tokval(parser), "case") ||
2573 !strcmp(parser_tokval(parser), "default"))
2578 if (!parse_statement(parser, caseblock, &expr, true)) {
2579 ast_delete(switchnode);
2584 if (!ast_block_add_expr(caseblock, expr)) {
2585 ast_delete(switchnode);
2591 parser_leaveblock(parser);
2594 if (parser->tok != '}') {
2595 ast_delete(switchnode);
2596 parseerror(parser, "expected closing paren of case list");
2599 if (!parser_next(parser)) {
2600 ast_delete(switchnode);
2601 parseerror(parser, "parse error after switch");
2604 *out = (ast_expression*)switchnode;
2608 static bool parse_goto(parser_t *parser, ast_expression **out)
2613 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2614 parseerror(parser, "expected label name after `goto`");
2618 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2620 for (i = 0; i < vec_size(parser->labels); ++i) {
2621 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2622 ast_goto_set_label(gt, parser->labels[i]);
2626 if (i == vec_size(parser->labels))
2627 vec_push(parser->gotos, gt);
2629 if (!parser_next(parser) || parser->tok != ';') {
2630 parseerror(parser, "semicolon expected after goto label");
2633 if (!parser_next(parser)) {
2634 parseerror(parser, "parse error after goto");
2638 *out = (ast_expression*)gt;
2642 static bool parse_skipwhite(parser_t *parser)
2645 if (!parser_next(parser))
2647 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2648 return parser->tok < TOKEN_ERROR;
2651 static bool parse_eol(parser_t *parser)
2653 if (!parse_skipwhite(parser))
2655 return parser->tok == TOKEN_EOL;
2658 static bool parse_pragma_do(parser_t *parser)
2660 if (!parser_next(parser) ||
2661 parser->tok != TOKEN_IDENT ||
2662 strcmp(parser_tokval(parser), "pragma"))
2664 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2667 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2668 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2672 if (!strcmp(parser_tokval(parser), "noref")) {
2673 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2674 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2677 parser->noref = !!parser_token(parser)->constval.i;
2678 if (!parse_eol(parser)) {
2679 parseerror(parser, "parse error after `noref` pragma");
2685 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2692 static bool parse_pragma(parser_t *parser)
2695 parser->lex->flags.preprocessing = true;
2696 parser->lex->flags.mergelines = true;
2697 rv = parse_pragma_do(parser);
2698 if (parser->tok != TOKEN_EOL) {
2699 parseerror(parser, "junk after pragma");
2702 parser->lex->flags.preprocessing = false;
2703 parser->lex->flags.mergelines = false;
2704 if (!parser_next(parser)) {
2705 parseerror(parser, "parse error after pragma");
2711 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2713 bool noref, noreturn;
2715 ast_value *typevar = NULL;
2719 if (parser->tok == TOKEN_IDENT)
2720 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2722 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2724 /* local variable */
2726 parseerror(parser, "cannot declare a variable from here");
2729 if (opts.standard == COMPILER_QCC) {
2730 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2733 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false))
2737 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn))
2739 if (cvq == CV_WRONG)
2741 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn);
2743 else if (parser->tok == TOKEN_KEYWORD)
2745 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2750 if (!parser_next(parser)) {
2751 parseerror(parser, "parse error after __builtin_debug_printtype");
2755 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2757 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2758 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2759 if (!parser_next(parser)) {
2760 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2766 if (!parse_statement(parser, block, out, allow_cases))
2769 con_out("__builtin_debug_printtype: got no output node\n");
2772 ast_type_to_string(*out, ty, sizeof(ty));
2773 con_out("__builtin_debug_printtype: `%s`\n", ty);
2778 else if (!strcmp(parser_tokval(parser), "return"))
2780 return parse_return(parser, block, out);
2782 else if (!strcmp(parser_tokval(parser), "if"))
2784 return parse_if(parser, block, out);
2786 else if (!strcmp(parser_tokval(parser), "while"))
2788 return parse_while(parser, block, out);
2790 else if (!strcmp(parser_tokval(parser), "do"))
2792 return parse_dowhile(parser, block, out);
2794 else if (!strcmp(parser_tokval(parser), "for"))
2796 if (opts.standard == COMPILER_QCC) {
2797 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2800 return parse_for(parser, block, out);
2802 else if (!strcmp(parser_tokval(parser), "break"))
2804 return parse_break_continue(parser, block, out, false);
2806 else if (!strcmp(parser_tokval(parser), "continue"))
2808 return parse_break_continue(parser, block, out, true);
2810 else if (!strcmp(parser_tokval(parser), "switch"))
2812 return parse_switch(parser, block, out);
2814 else if (!strcmp(parser_tokval(parser), "case") ||
2815 !strcmp(parser_tokval(parser), "default"))
2818 parseerror(parser, "unexpected 'case' label");
2823 else if (!strcmp(parser_tokval(parser), "goto"))
2825 return parse_goto(parser, out);
2827 else if (!strcmp(parser_tokval(parser), "typedef"))
2829 if (!parser_next(parser)) {
2830 parseerror(parser, "expected type definition after 'typedef'");
2833 return parse_typedef(parser);
2835 parseerror(parser, "Unexpected keyword");
2838 else if (parser->tok == '{')
2841 inner = parse_block(parser);
2844 *out = (ast_expression*)inner;
2847 else if (parser->tok == ':')
2851 if (!parser_next(parser)) {
2852 parseerror(parser, "expected label name");
2855 if (parser->tok != TOKEN_IDENT) {
2856 parseerror(parser, "label must be an identifier");
2859 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2862 vec_push(parser->labels, label);
2863 *out = (ast_expression*)label;
2864 if (!parser_next(parser)) {
2865 parseerror(parser, "parse error after label");
2868 for (i = 0; i < vec_size(parser->gotos); ++i) {
2869 if (!strcmp(parser->gotos[i]->name, label->name)) {
2870 ast_goto_set_label(parser->gotos[i], label);
2871 vec_remove(parser->gotos, i, 1);
2877 else if (parser->tok == ';')
2879 if (!parser_next(parser)) {
2880 parseerror(parser, "parse error after empty statement");
2887 ast_expression *exp = parse_expression(parser, false);
2891 if (!ast_side_effects(exp)) {
2892 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2899 static bool parse_block_into(parser_t *parser, ast_block *block)
2903 parser_enterblock(parser);
2905 if (!parser_next(parser)) { /* skip the '{' */
2906 parseerror(parser, "expected function body");
2910 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2912 ast_expression *expr = NULL;
2913 if (parser->tok == '}')
2916 if (!parse_statement(parser, block, &expr, false)) {
2917 /* parseerror(parser, "parse error"); */
2923 if (!ast_block_add_expr(block, expr)) {
2930 if (parser->tok != '}') {
2933 (void)parser_next(parser);
2937 if (!parser_leaveblock(parser))
2939 return retval && !!block;
2942 static ast_block* parse_block(parser_t *parser)
2945 block = ast_block_new(parser_ctx(parser));
2948 if (!parse_block_into(parser, block)) {
2949 ast_block_delete(block);
2955 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2957 if (parser->tok == '{') {
2958 *out = (ast_expression*)parse_block(parser);
2961 return parse_statement(parser, NULL, out, false);
2964 static bool create_vector_members(ast_value *var, ast_member **me)
2967 size_t len = strlen(var->name);
2969 for (i = 0; i < 3; ++i) {
2970 char *name = (char*)mem_a(len+3);
2971 memcpy(name, var->name, len);
2973 name[len+1] = 'x'+i;
2975 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2984 do { ast_member_delete(me[--i]); } while(i);
2988 static bool parse_function_body(parser_t *parser, ast_value *var)
2990 ast_block *block = NULL;
2995 ast_expression *framenum = NULL;
2996 ast_expression *nextthink = NULL;
2997 /* None of the following have to be deleted */
2998 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2999 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3000 bool has_frame_think;
3004 has_frame_think = false;
3005 old = parser->function;
3007 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3008 parseerror(parser, "gotos/labels leaking");
3012 if (var->expression.flags & AST_FLAG_VARIADIC) {
3013 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3014 "variadic function with implementation will not be able to access additional parameters"))
3020 if (parser->tok == '[') {
3021 /* got a frame definition: [ framenum, nextthink ]
3022 * this translates to:
3023 * self.frame = framenum;
3024 * self.nextthink = time + 0.1;
3025 * self.think = nextthink;
3029 fld_think = parser_find_field(parser, "think");
3030 fld_nextthink = parser_find_field(parser, "nextthink");
3031 fld_frame = parser_find_field(parser, "frame");
3032 if (!fld_think || !fld_nextthink || !fld_frame) {
3033 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3034 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3037 gbl_time = parser_find_global(parser, "time");
3038 gbl_self = parser_find_global(parser, "self");
3039 if (!gbl_time || !gbl_self) {
3040 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3041 parseerror(parser, "please declare the following globals: `time`, `self`");
3045 if (!parser_next(parser))
3048 framenum = parse_expression_leave(parser, true);
3050 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3053 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3054 ast_unref(framenum);
3055 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3059 if (parser->tok != ',') {
3060 ast_unref(framenum);
3061 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3062 parseerror(parser, "Got a %i\n", parser->tok);
3066 if (!parser_next(parser)) {
3067 ast_unref(framenum);
3071 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3073 /* qc allows the use of not-yet-declared functions here
3074 * - this automatically creates a prototype */
3075 ast_value *thinkfunc;
3076 ast_expression *functype = fld_think->expression.next;
3078 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3079 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3080 ast_unref(framenum);
3081 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3085 if (!parser_next(parser)) {
3086 ast_unref(framenum);
3087 ast_delete(thinkfunc);
3091 vec_push(parser->globals, (ast_expression*)thinkfunc);
3092 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3093 nextthink = (ast_expression*)thinkfunc;
3096 nextthink = parse_expression_leave(parser, true);
3098 ast_unref(framenum);
3099 parseerror(parser, "expected a think-function in [frame,think] notation");
3104 if (!ast_istype(nextthink, ast_value)) {
3105 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3109 if (retval && parser->tok != ']') {
3110 parseerror(parser, "expected closing `]` for [frame,think] notation");
3114 if (retval && !parser_next(parser)) {
3118 if (retval && parser->tok != '{') {
3119 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3124 ast_unref(nextthink);
3125 ast_unref(framenum);
3129 has_frame_think = true;
3132 block = ast_block_new(parser_ctx(parser));
3134 parseerror(parser, "failed to allocate block");
3135 if (has_frame_think) {
3136 ast_unref(nextthink);
3137 ast_unref(framenum);
3142 if (has_frame_think) {
3144 ast_expression *self_frame;
3145 ast_expression *self_nextthink;
3146 ast_expression *self_think;
3147 ast_expression *time_plus_1;
3148 ast_store *store_frame;
3149 ast_store *store_nextthink;
3150 ast_store *store_think;
3152 ctx = parser_ctx(parser);
3153 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3154 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3155 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3157 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3158 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3160 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3161 if (self_frame) ast_delete(self_frame);
3162 if (self_nextthink) ast_delete(self_nextthink);
3163 if (self_think) ast_delete(self_think);
3164 if (time_plus_1) ast_delete(time_plus_1);
3170 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3171 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3172 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3175 ast_delete(self_frame);
3178 if (!store_nextthink) {
3179 ast_delete(self_nextthink);
3183 ast_delete(self_think);
3187 if (store_frame) ast_delete(store_frame);
3188 if (store_nextthink) ast_delete(store_nextthink);
3189 if (store_think) ast_delete(store_think);
3192 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3193 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3194 !ast_block_add_expr(block, (ast_expression*)store_think))
3201 parseerror(parser, "failed to generate code for [frame,think]");
3202 ast_unref(nextthink);
3203 ast_unref(framenum);
3209 parser_enterblock(parser);
3211 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3213 ast_value *param = var->expression.params[parami];
3216 if (param->expression.vtype != TYPE_VECTOR &&
3217 (param->expression.vtype != TYPE_FIELD ||
3218 param->expression.next->expression.vtype != TYPE_VECTOR))
3223 if (!create_vector_members(param, me)) {
3224 ast_block_delete(block);
3228 for (e = 0; e < 3; ++e) {
3229 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3230 ast_block_collect(block, (ast_expression*)me[e]);
3234 func = ast_function_new(ast_ctx(var), var->name, var);
3236 parseerror(parser, "failed to allocate function for `%s`", var->name);
3237 ast_block_delete(block);
3240 vec_push(parser->functions, func);
3242 parser->function = func;
3243 if (!parse_block_into(parser, block)) {
3244 ast_block_delete(block);
3248 vec_push(func->blocks, block);
3250 parser->function = old;
3251 if (!parser_leaveblock(parser))
3253 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3254 parseerror(parser, "internal error: local scopes left");
3258 if (parser->tok == ';')
3259 return parser_next(parser);
3260 else if (opts.standard == COMPILER_QCC)
3261 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3265 vec_pop(parser->functions);
3266 ast_function_delete(func);
3267 var->constval.vfunc = NULL;
3270 (void)!parser_leaveblock(parser);
3271 parser->function = old;
3275 static ast_expression *array_accessor_split(
3280 ast_expression *left,
3281 ast_expression *right
3287 lex_ctx ctx = ast_ctx(array);
3289 if (!left || !right) {
3290 if (left) ast_delete(left);
3291 if (right) ast_delete(right);
3295 cmp = ast_binary_new(ctx, INSTR_LT,
3296 (ast_expression*)index,
3297 (ast_expression*)parser_const_float(parser, middle));
3301 parseerror(parser, "internal error: failed to create comparison for array setter");
3305 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3307 ast_delete(cmp); /* will delete left and right */
3308 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3312 return (ast_expression*)ifthen;
3315 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3317 lex_ctx ctx = ast_ctx(array);
3319 if (from+1 == afterend) {
3320 /* set this value */
3323 ast_array_index *subscript;
3325 int assignop = type_store_instr[value->expression.vtype];
3327 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3328 assignop = INSTR_STORE_V;
3330 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3334 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3336 ast_delete(subscript);
3340 block = ast_block_new(ctx);
3346 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3351 ret = ast_return_new(ctx, NULL);
3357 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3362 return (ast_expression*)block;
3364 ast_expression *left, *right;
3365 size_t diff = afterend - from;
3366 size_t middle = from + diff/2;
3367 left = array_setter_node(parser, array, index, value, from, middle);
3368 right = array_setter_node(parser, array, index, value, middle, afterend);
3369 return array_accessor_split(parser, array, index, middle, left, right);
3373 static ast_expression *array_field_setter_node(
3382 lex_ctx ctx = ast_ctx(array);
3384 if (from+1 == afterend) {
3385 /* set this value */
3388 ast_entfield *entfield;
3389 ast_array_index *subscript;
3391 int assignop = type_storep_instr[value->expression.vtype];
3393 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3394 assignop = INSTR_STOREP_V;
3396 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3400 entfield = ast_entfield_new_force(ctx,
3401 (ast_expression*)entity,
3402 (ast_expression*)subscript,
3403 (ast_expression*)subscript);
3405 ast_delete(subscript);
3409 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3411 ast_delete(entfield);
3415 block = ast_block_new(ctx);
3421 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3426 ret = ast_return_new(ctx, NULL);
3432 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3437 return (ast_expression*)block;
3439 ast_expression *left, *right;
3440 size_t diff = afterend - from;
3441 size_t middle = from + diff/2;
3442 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3443 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3444 return array_accessor_split(parser, array, index, middle, left, right);
3448 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3450 lex_ctx ctx = ast_ctx(array);
3452 if (from+1 == afterend) {
3454 ast_array_index *subscript;
3456 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3460 ret = ast_return_new(ctx, (ast_expression*)subscript);
3462 ast_delete(subscript);
3466 return (ast_expression*)ret;
3468 ast_expression *left, *right;
3469 size_t diff = afterend - from;
3470 size_t middle = from + diff/2;
3471 left = array_getter_node(parser, array, index, from, middle);
3472 right = array_getter_node(parser, array, index, middle, afterend);
3473 return array_accessor_split(parser, array, index, middle, left, right);
3477 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3479 ast_function *func = NULL;
3480 ast_value *fval = NULL;
3481 ast_block *body = NULL;
3483 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3485 parseerror(parser, "failed to create accessor function value");
3489 func = ast_function_new(ast_ctx(array), funcname, fval);
3492 parseerror(parser, "failed to create accessor function node");
3496 body = ast_block_new(ast_ctx(array));
3498 parseerror(parser, "failed to create block for array accessor");
3504 vec_push(func->blocks, body);
3507 vec_push(parser->accessors, fval);
3512 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3514 ast_expression *root = NULL;
3515 ast_value *index = NULL;
3516 ast_value *value = NULL;
3520 if (!ast_istype(array->expression.next, ast_value)) {
3521 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3525 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3527 func = fval->constval.vfunc;
3528 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3530 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3531 value = ast_value_copy((ast_value*)array->expression.next);
3533 if (!index || !value) {
3534 parseerror(parser, "failed to create locals for array accessor");
3537 (void)!ast_value_set_name(value, "value"); /* not important */
3538 vec_push(fval->expression.params, index);
3539 vec_push(fval->expression.params, value);
3541 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3543 parseerror(parser, "failed to build accessor search tree");
3547 array->setter = fval;
3548 return ast_block_add_expr(func->blocks[0], root);
3550 if (index) ast_delete(index);
3551 if (value) ast_delete(value);
3552 if (root) ast_delete(root);
3558 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3560 ast_expression *root = NULL;
3561 ast_value *entity = NULL;
3562 ast_value *index = NULL;
3563 ast_value *value = NULL;
3567 if (!ast_istype(array->expression.next, ast_value)) {
3568 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3572 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3574 func = fval->constval.vfunc;
3575 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3577 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3578 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3579 value = ast_value_copy((ast_value*)array->expression.next);
3580 if (!entity || !index || !value) {
3581 parseerror(parser, "failed to create locals for array accessor");
3584 (void)!ast_value_set_name(value, "value"); /* not important */
3585 vec_push(fval->expression.params, entity);
3586 vec_push(fval->expression.params, index);
3587 vec_push(fval->expression.params, value);
3589 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3591 parseerror(parser, "failed to build accessor search tree");
3595 array->setter = fval;
3596 return ast_block_add_expr(func->blocks[0], root);
3598 if (entity) ast_delete(entity);
3599 if (index) ast_delete(index);
3600 if (value) ast_delete(value);
3601 if (root) ast_delete(root);
3607 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3609 ast_expression *root = NULL;
3610 ast_value *index = NULL;
3614 /* NOTE: checking array->expression.next rather than elemtype since
3615 * for fields elemtype is a temporary fieldtype.
3617 if (!ast_istype(array->expression.next, ast_value)) {
3618 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3622 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3624 func = fval->constval.vfunc;
3625 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3627 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3630 parseerror(parser, "failed to create locals for array accessor");
3633 vec_push(fval->expression.params, index);
3635 root = array_getter_node(parser, array, index, 0, array->expression.count);
3637 parseerror(parser, "failed to build accessor search tree");
3641 array->getter = fval;
3642 return ast_block_add_expr(func->blocks[0], root);
3644 if (index) ast_delete(index);
3645 if (root) ast_delete(root);
3651 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3652 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3660 bool variadic = false;
3662 ctx = parser_ctx(parser);
3664 /* for the sake of less code we parse-in in this function */
3665 if (!parser_next(parser)) {
3666 parseerror(parser, "expected parameter list");
3672 /* parse variables until we hit a closing paren */
3673 while (parser->tok != ')') {
3675 /* there must be commas between them */
3676 if (parser->tok != ',') {
3677 parseerror(parser, "expected comma or end of parameter list");
3680 if (!parser_next(parser)) {
3681 parseerror(parser, "expected parameter");
3687 if (parser->tok == TOKEN_DOTS) {
3688 /* '...' indicates a varargs function */
3690 if (!parser_next(parser)) {
3691 parseerror(parser, "expected parameter");
3694 if (parser->tok != ')') {
3695 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3701 /* for anything else just parse a typename */
3702 param = parse_typename(parser, NULL, NULL);
3705 vec_push(params, param);
3706 if (param->expression.vtype >= TYPE_VARIANT) {
3707 char tname[1024]; /* typename is reserved in C++ */
3708 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3709 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3715 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3719 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3720 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3723 if (!parser_next(parser)) {
3724 parseerror(parser, "parse error after typename");
3728 /* now turn 'var' into a function type */
3729 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3730 fval->expression.next = (ast_expression*)var;
3732 fval->expression.flags |= AST_FLAG_VARIADIC;
3735 var->expression.params = params;
3742 for (i = 0; i < vec_size(params); ++i)
3743 ast_delete(params[i]);
3748 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3750 ast_expression *cexp;
3751 ast_value *cval, *tmp;
3754 ctx = parser_ctx(parser);
3756 if (!parser_next(parser)) {
3758 parseerror(parser, "expected array-size");
3762 cexp = parse_expression_leave(parser, true);
3764 if (!cexp || !ast_istype(cexp, ast_value)) {
3768 parseerror(parser, "expected array-size as constant positive integer");
3771 cval = (ast_value*)cexp;
3773 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3774 tmp->expression.next = (ast_expression*)var;
3777 if (cval->expression.vtype == TYPE_INTEGER)
3778 tmp->expression.count = cval->constval.vint;
3779 else if (cval->expression.vtype == TYPE_FLOAT)
3780 tmp->expression.count = cval->constval.vfloat;
3784 parseerror(parser, "array-size must be a positive integer constant");
3789 if (parser->tok != ']') {
3791 parseerror(parser, "expected ']' after array-size");
3794 if (!parser_next(parser)) {
3796 parseerror(parser, "error after parsing array size");
3802 /* Parse a complete typename.
3803 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3804 * but when parsing variables separated by comma
3805 * 'storebase' should point to where the base-type should be kept.
3806 * The base type makes up every bit of type information which comes *before* the
3809 * The following will be parsed in its entirety:
3811 * The 'basetype' in this case is 'void()'
3812 * and if there's a comma after it, say:
3814 * then the type-information 'void()' can be stored in 'storebase'
3816 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3818 ast_value *var, *tmp;
3821 const char *name = NULL;
3822 bool isfield = false;
3823 bool wasarray = false;
3824 size_t morefields = 0;
3826 ctx = parser_ctx(parser);
3828 /* types may start with a dot */
3829 if (parser->tok == '.') {
3831 /* if we parsed a dot we need a typename now */
3832 if (!parser_next(parser)) {
3833 parseerror(parser, "expected typename for field definition");
3837 /* Further dots are handled seperately because they won't be part of the
3840 while (parser->tok == '.') {
3842 if (!parser_next(parser)) {
3843 parseerror(parser, "expected typename for field definition");
3848 if (parser->tok == TOKEN_IDENT)
3849 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3850 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3851 parseerror(parser, "expected typename");
3855 /* generate the basic type value */
3856 if (cached_typedef) {
3857 var = ast_value_copy(cached_typedef);
3858 ast_value_set_name(var, "<type(from_def)>");
3860 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3862 for (; morefields; --morefields) {
3863 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3864 tmp->expression.next = (ast_expression*)var;
3868 /* do not yet turn into a field - remember:
3869 * .void() foo; is a field too
3870 * .void()() foo; is a function
3874 if (!parser_next(parser)) {
3876 parseerror(parser, "parse error after typename");
3880 /* an opening paren now starts the parameter-list of a function
3881 * this is where original-QC has parameter lists.
3882 * We allow a single parameter list here.
3883 * Much like fteqcc we don't allow `float()() x`
3885 if (parser->tok == '(') {
3886 var = parse_parameter_list(parser, var);
3891 /* store the base if requested */
3893 *storebase = ast_value_copy(var);
3895 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3896 tmp->expression.next = (ast_expression*)*storebase;
3901 /* there may be a name now */
3902 if (parser->tok == TOKEN_IDENT) {
3903 name = util_strdup(parser_tokval(parser));
3905 if (!parser_next(parser)) {
3907 parseerror(parser, "error after variable or field declaration");
3912 /* now this may be an array */
3913 if (parser->tok == '[') {
3915 var = parse_arraysize(parser, var);
3920 /* This is the point where we can turn it into a field */
3922 /* turn it into a field if desired */
3923 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3924 tmp->expression.next = (ast_expression*)var;
3928 /* now there may be function parens again */
3929 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3930 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3931 if (parser->tok == '(' && wasarray)
3932 parseerror(parser, "arrays as part of a return type is not supported");
3933 while (parser->tok == '(') {
3934 var = parse_parameter_list(parser, var);
3943 /* finally name it */
3945 if (!ast_value_set_name(var, name)) {
3947 parseerror(parser, "internal error: failed to set name");
3950 /* free the name, ast_value_set_name duplicates */
3957 static bool parse_typedef(parser_t *parser)
3959 ast_value *typevar, *oldtype;
3960 ast_expression *old;
3962 typevar = parse_typename(parser, NULL, NULL);
3967 if ( (old = parser_find_var(parser, typevar->name)) ) {
3968 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3969 " -> `%s` has been declared here: %s:%i",
3970 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3971 ast_delete(typevar);
3975 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3976 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3977 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3978 ast_delete(typevar);
3982 vec_push(parser->_typedefs, typevar);
3983 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3985 if (parser->tok != ';') {
3986 parseerror(parser, "expected semicolon after typedef");
3989 if (!parser_next(parser)) {
3990 parseerror(parser, "parse error after typedef");
3997 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn)
4001 ast_expression *old;
4005 ast_value *basetype = NULL;
4007 bool isparam = false;
4008 bool isvector = false;
4009 bool cleanvar = true;
4010 bool wasarray = false;
4014 /* get the first complete variable */
4015 var = parse_typename(parser, &basetype, cached_typedef);
4018 ast_delete(basetype);
4026 /* Part 0: finish the type */
4027 if (parser->tok == '(') {
4028 if (opts.standard == COMPILER_QCC)
4029 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4030 var = parse_parameter_list(parser, var);
4036 /* we only allow 1-dimensional arrays */
4037 if (parser->tok == '[') {
4039 var = parse_arraysize(parser, var);
4045 if (parser->tok == '(' && wasarray) {
4046 parseerror(parser, "arrays as part of a return type is not supported");
4047 /* we'll still parse the type completely for now */
4049 /* for functions returning functions */
4050 while (parser->tok == '(') {
4051 if (opts.standard == COMPILER_QCC)
4052 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4053 var = parse_parameter_list(parser, var);
4060 var->cvq = qualifier;
4061 /* in a noref section we simply bump the usecount */
4062 if (noref || parser->noref)
4065 var->expression.flags |= AST_FLAG_NORETURN;
4068 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4069 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4070 * is then filled with the previous definition and the parameter-names replaced.
4073 /* Deal with end_sys_ vars */
4075 if (!strcmp(var->name, "end_sys_globals")) {
4077 parser->crc_globals = vec_size(parser->globals);
4080 else if (!strcmp(var->name, "end_sys_fields")) {
4082 parser->crc_fields = vec_size(parser->fields);
4085 if (was_end && var->expression.vtype == TYPE_FIELD) {
4086 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4087 "global '%s' hint should not be a field",
4088 parser_tokval(parser)))
4095 if (!nofields && var->expression.vtype == TYPE_FIELD)
4097 /* deal with field declarations */
4098 old = parser_find_field(parser, var->name);
4100 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4101 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4110 parseerror(parser, "field `%s` already declared here: %s:%i",
4111 var->name, ast_ctx(old).file, ast_ctx(old).line);
4116 if (opts.standard == COMPILER_QCC &&
4117 (old = parser_find_global(parser, var->name)))
4119 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4120 parseerror(parser, "field `%s` already declared here: %s:%i",
4121 var->name, ast_ctx(old).file, ast_ctx(old).line);
4128 /* deal with other globals */
4129 old = parser_find_global(parser, var->name);
4130 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4132 /* This is a function which had a prototype */
4133 if (!ast_istype(old, ast_value)) {
4134 parseerror(parser, "internal error: prototype is not an ast_value");
4138 proto = (ast_value*)old;
4139 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4140 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4142 ast_ctx(proto).file, ast_ctx(proto).line);
4146 /* we need the new parameter-names */
4147 for (i = 0; i < vec_size(proto->expression.params); ++i)
4148 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4156 if (opts.standard == COMPILER_GMQCC) {
4157 parseerror(parser, "global `%s` already declared here: %s:%i",
4158 var->name, ast_ctx(old).file, ast_ctx(old).line);
4162 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4163 "global `%s` already declared here: %s:%i",
4164 var->name, ast_ctx(old).file, ast_ctx(old).line))
4169 proto = (ast_value*)old;
4170 if (!ast_istype(old, ast_value)) {
4171 parseerror(parser, "internal error: not an ast_value");
4180 if (opts.standard == COMPILER_QCC &&
4181 (old = parser_find_field(parser, var->name)))
4183 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4184 parseerror(parser, "global `%s` already declared here: %s:%i",
4185 var->name, ast_ctx(old).file, ast_ctx(old).line);
4192 else /* it's not a global */
4194 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4195 if (old && !isparam) {
4196 parseerror(parser, "local `%s` already declared here: %s:%i",
4197 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4201 old = parser_find_local(parser, var->name, 0, &isparam);
4202 if (old && isparam) {
4203 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4204 "local `%s` is shadowing a parameter", var->name))
4206 parseerror(parser, "local `%s` already declared here: %s:%i",
4207 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4211 if (opts.standard != COMPILER_GMQCC) {
4220 * Create the global/local, and deal with vector types.
4223 if (var->expression.vtype == TYPE_VECTOR)
4225 else if (var->expression.vtype == TYPE_FIELD &&
4226 var->expression.next->expression.vtype == TYPE_VECTOR)
4230 if (!create_vector_members(var, me)) {
4237 /* deal with global variables, fields, functions */
4238 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4239 var->isfield = true;
4240 vec_push(parser->fields, (ast_expression*)var);
4241 util_htset(parser->htfields, var->name, var);
4243 for (i = 0; i < 3; ++i) {
4244 vec_push(parser->fields, (ast_expression*)me[i]);
4245 util_htset(parser->htfields, me[i]->name, me[i]);
4250 vec_push(parser->globals, (ast_expression*)var);
4251 util_htset(parser->htglobals, var->name, var);
4253 for (i = 0; i < 3; ++i) {
4254 vec_push(parser->globals, (ast_expression*)me[i]);
4255 util_htset(parser->htglobals, me[i]->name, me[i]);
4260 vec_push(localblock->locals, var);
4261 parser_addlocal(parser, var->name, (ast_expression*)var);
4263 for (i = 0; i < 3; ++i) {
4264 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4265 ast_block_collect(localblock, (ast_expression*)me[i]);
4271 me[0] = me[1] = me[2] = NULL;
4276 if (var->expression.vtype == TYPE_ARRAY) {
4278 snprintf(name, sizeof(name), "%s##SET", var->name);
4279 if (!parser_create_array_setter(parser, var, name))
4281 snprintf(name, sizeof(name), "%s##GET", var->name);
4282 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4285 else if (!localblock && !nofields &&
4286 var->expression.vtype == TYPE_FIELD &&
4287 var->expression.next->expression.vtype == TYPE_ARRAY)
4290 ast_expression *telem;
4292 ast_value *array = (ast_value*)var->expression.next;
4294 if (!ast_istype(var->expression.next, ast_value)) {
4295 parseerror(parser, "internal error: field element type must be an ast_value");
4299 snprintf(name, sizeof(name), "%s##SETF", var->name);
4300 if (!parser_create_array_field_setter(parser, array, name))
4303 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4304 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4305 tfield->expression.next = telem;
4306 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4307 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4315 if (parser->tok == ';') {
4316 ast_delete(basetype);
4317 if (!parser_next(parser)) {
4318 parseerror(parser, "error after variable declaration");
4324 if (parser->tok == ',')
4328 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4331 parseerror(parser, "missing comma or semicolon while parsing variables");
4335 if (localblock && opts.standard == COMPILER_QCC) {
4336 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4337 "initializing expression turns variable `%s` into a constant in this standard",
4344 if (parser->tok != '{') {
4345 if (parser->tok != '=') {
4346 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4350 if (!parser_next(parser)) {
4351 parseerror(parser, "error parsing initializer");
4355 else if (opts.standard == COMPILER_QCC) {
4356 parseerror(parser, "expected '=' before function body in this standard");
4359 if (parser->tok == '#') {
4360 ast_function *func = NULL;
4363 parseerror(parser, "cannot declare builtins within functions");
4366 if (var->expression.vtype != TYPE_FUNCTION) {
4367 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4370 if (!parser_next(parser)) {
4371 parseerror(parser, "expected builtin number");
4374 if (parser->tok != TOKEN_INTCONST) {
4375 parseerror(parser, "builtin number must be an integer constant");
4378 if (parser_token(parser)->constval.i < 0) {
4379 parseerror(parser, "builtin number must be an integer greater than zero");
4383 if (var->hasvalue) {
4384 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4385 "builtin `%s` has already been defined\n"
4386 " -> previous declaration here: %s:%i",
4387 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4391 func = ast_function_new(ast_ctx(var), var->name, var);
4393 parseerror(parser, "failed to allocate function for `%s`", var->name);
4396 vec_push(parser->functions, func);
4398 func->builtin = -parser_token(parser)->constval.i-1;
4401 if (!parser_next(parser)) {
4402 parseerror(parser, "expected comma or semicolon");
4404 ast_function_delete(func);
4405 var->constval.vfunc = NULL;
4409 else if (parser->tok == '{' || parser->tok == '[')
4412 parseerror(parser, "cannot declare functions within functions");
4417 ast_ctx(proto) = parser_ctx(parser);
4419 if (!parse_function_body(parser, var))
4421 ast_delete(basetype);
4422 for (i = 0; i < vec_size(parser->gotos); ++i)
4423 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4424 vec_free(parser->gotos);
4425 vec_free(parser->labels);
4428 ast_expression *cexp;
4431 cexp = parse_expression_leave(parser, true);
4436 cval = (ast_value*)cexp;
4437 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4438 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4441 if (opts.standard != COMPILER_GMQCC &&
4442 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4443 qualifier != CV_VAR)
4445 var->cvq = CV_CONST;
4447 var->hasvalue = true;
4448 if (cval->expression.vtype == TYPE_STRING)
4449 var->constval.vstring = parser_strdup(cval->constval.vstring);
4450 else if (cval->expression.vtype == TYPE_FIELD)
4451 var->constval.vfield = cval;
4453 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4458 shunt sy = { NULL, NULL };
4461 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4462 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4463 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4464 if (!parser_sy_apply_operator(parser, &sy))
4467 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4468 parseerror(parser, "internal error: leaked operands");
4469 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4479 if (parser->tok == ',') {
4480 if (!parser_next(parser)) {
4481 parseerror(parser, "expected another variable");
4485 if (parser->tok != TOKEN_IDENT) {
4486 parseerror(parser, "expected another variable");
4489 var = ast_value_copy(basetype);
4491 ast_value_set_name(var, parser_tokval(parser));
4492 if (!parser_next(parser)) {
4493 parseerror(parser, "error parsing variable declaration");
4499 if (parser->tok != ';') {
4500 parseerror(parser, "missing semicolon after variables");
4504 if (!parser_next(parser)) {
4505 parseerror(parser, "parse error after variable declaration");
4509 ast_delete(basetype);
4513 if (cleanvar && var)
4515 ast_delete(basetype);
4519 ast_delete(basetype);
4520 if (cleanvar && var)
4522 if (me[0]) ast_member_delete(me[0]);
4523 if (me[1]) ast_member_delete(me[1]);
4524 if (me[2]) ast_member_delete(me[2]);
4528 static bool parser_global_statement(parser_t *parser)
4532 bool noreturn = false;
4533 ast_value *istype = NULL;
4535 if (parser->tok == TOKEN_IDENT)
4536 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4538 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4540 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false);
4542 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn))
4544 if (cvq == CV_WRONG)
4546 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn);
4548 else if (parser->tok == TOKEN_KEYWORD)
4550 if (!strcmp(parser_tokval(parser), "typedef")) {
4551 if (!parser_next(parser)) {
4552 parseerror(parser, "expected type definition after 'typedef'");
4555 return parse_typedef(parser);
4557 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4560 else if (parser->tok == '#')
4562 return parse_pragma(parser);
4564 else if (parser->tok == '$')
4566 if (!parser_next(parser)) {
4567 parseerror(parser, "parse error");
4573 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4579 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4581 return util_crc16(old, str, strlen(str));
4584 static void progdefs_crc_file(const char *str)
4586 /* write to progdefs.h here */
4590 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4592 old = progdefs_crc_sum(old, str);
4593 progdefs_crc_file(str);
4597 static void generate_checksum(parser_t *parser)
4599 uint16_t crc = 0xFFFF;
4603 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4604 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4606 progdefs_crc_file("\tint\tpad;\n");
4607 progdefs_crc_file("\tint\tofs_return[3];\n");
4608 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4609 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4610 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4611 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4612 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4613 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4614 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4615 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4617 for (i = 0; i < parser->crc_globals; ++i) {
4618 if (!ast_istype(parser->globals[i], ast_value))
4620 value = (ast_value*)(parser->globals[i]);
4621 switch (value->expression.vtype) {
4622 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4623 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4624 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4625 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4627 crc = progdefs_crc_both(crc, "\tint\t");
4630 crc = progdefs_crc_both(crc, value->name);
4631 crc = progdefs_crc_both(crc, ";\n");
4633 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4634 for (i = 0; i < parser->crc_fields; ++i) {
4635 if (!ast_istype(parser->fields[i], ast_value))
4637 value = (ast_value*)(parser->fields[i]);
4638 switch (value->expression.next->expression.vtype) {
4639 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4640 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4641 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4642 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4644 crc = progdefs_crc_both(crc, "\tint\t");
4647 crc = progdefs_crc_both(crc, value->name);
4648 crc = progdefs_crc_both(crc, ";\n");
4650 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4655 static parser_t *parser;
4661 parser = (parser_t*)mem_a(sizeof(parser_t));
4665 memset(parser, 0, sizeof(*parser));
4667 for (i = 0; i < operator_count; ++i) {
4668 if (operators[i].id == opid1('=')) {
4669 parser->assign_op = operators+i;
4673 if (!parser->assign_op) {
4674 printf("internal error: initializing parser: failed to find assign operator\n");
4679 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4680 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4681 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4682 vec_push(parser->_blocktypedefs, 0);
4686 bool parser_compile()
4688 /* initial lexer/parser state */
4689 parser->lex->flags.noops = true;
4691 if (parser_next(parser))
4693 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4695 if (!parser_global_statement(parser)) {
4696 if (parser->tok == TOKEN_EOF)
4697 parseerror(parser, "unexpected eof");
4698 else if (!parser->errors)
4699 parseerror(parser, "there have been errors, bailing out");
4700 lex_close(parser->lex);
4706 parseerror(parser, "parse error");
4707 lex_close(parser->lex);
4712 lex_close(parser->lex);
4715 return !parser->errors;
4718 bool parser_compile_file(const char *filename)
4720 parser->lex = lex_open(filename);
4722 con_err("failed to open file \"%s\"\n", filename);
4725 return parser_compile();
4728 bool parser_compile_string(const char *name, const char *str, size_t len)
4730 parser->lex = lex_open_string(str, len, name);
4732 con_err("failed to create lexer for string \"%s\"\n", name);
4735 return parser_compile();
4738 void parser_cleanup()
4741 for (i = 0; i < vec_size(parser->accessors); ++i) {
4742 ast_delete(parser->accessors[i]->constval.vfunc);
4743 parser->accessors[i]->constval.vfunc = NULL;
4744 ast_delete(parser->accessors[i]);
4746 for (i = 0; i < vec_size(parser->functions); ++i) {
4747 ast_delete(parser->functions[i]);
4749 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4750 ast_delete(parser->imm_vector[i]);
4752 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4753 ast_delete(parser->imm_string[i]);
4755 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4756 ast_delete(parser->imm_float[i]);
4758 for (i = 0; i < vec_size(parser->fields); ++i) {
4759 ast_delete(parser->fields[i]);
4761 for (i = 0; i < vec_size(parser->globals); ++i) {
4762 ast_delete(parser->globals[i]);
4764 vec_free(parser->accessors);
4765 vec_free(parser->functions);
4766 vec_free(parser->imm_vector);
4767 vec_free(parser->imm_string);
4768 vec_free(parser->imm_float);
4769 vec_free(parser->globals);
4770 vec_free(parser->fields);
4772 for (i = 0; i < vec_size(parser->variables); ++i)
4773 util_htdel(parser->variables[i]);
4774 vec_free(parser->variables);
4775 vec_free(parser->_blocklocals);
4776 vec_free(parser->_locals);
4778 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4779 ast_delete(parser->_typedefs[i]);
4780 vec_free(parser->_typedefs);
4781 for (i = 0; i < vec_size(parser->typedefs); ++i)
4782 util_htdel(parser->typedefs[i]);
4783 vec_free(parser->typedefs);
4784 vec_free(parser->_blocktypedefs);
4786 vec_free(parser->_block_ctx);
4788 vec_free(parser->labels);
4789 vec_free(parser->gotos);
4794 bool parser_finish(const char *output)
4800 if (!parser->errors)
4802 ir = ir_builder_new("gmqcc_out");
4804 con_out("failed to allocate builder\n");
4808 for (i = 0; i < vec_size(parser->fields); ++i) {
4811 if (!ast_istype(parser->fields[i], ast_value))
4813 field = (ast_value*)parser->fields[i];
4814 hasvalue = field->hasvalue;
4815 field->hasvalue = false;
4816 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4817 con_out("failed to generate field %s\n", field->name);
4818 ir_builder_delete(ir);
4823 ast_expression *subtype;
4824 field->hasvalue = true;
4825 subtype = field->expression.next;
4826 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4827 if (subtype->expression.vtype == TYPE_FIELD)
4828 ifld->fieldtype = subtype->expression.next->expression.vtype;
4829 else if (subtype->expression.vtype == TYPE_FUNCTION)
4830 ifld->outtype = subtype->expression.next->expression.vtype;
4831 (void)!ir_value_set_field(field->ir_v, ifld);
4834 for (i = 0; i < vec_size(parser->globals); ++i) {
4836 if (!ast_istype(parser->globals[i], ast_value))
4838 asvalue = (ast_value*)(parser->globals[i]);
4839 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4840 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4841 "unused global: `%s`", asvalue->name);
4843 if (!ast_global_codegen(asvalue, ir, false)) {
4844 con_out("failed to generate global %s\n", asvalue->name);
4845 ir_builder_delete(ir);
4849 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4850 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4851 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4852 ir_builder_delete(ir);
4856 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4857 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4858 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4859 ir_builder_delete(ir);
4863 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4864 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4865 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4866 ir_builder_delete(ir);
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 (!ast_generate_accessors(asvalue, ir)) {
4876 ir_builder_delete(ir);
4880 for (i = 0; i < vec_size(parser->fields); ++i) {
4882 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4884 if (!ast_istype((ast_expression*)asvalue, ast_value))
4886 if (asvalue->expression.vtype != TYPE_ARRAY)
4888 if (!ast_generate_accessors(asvalue, ir)) {
4889 ir_builder_delete(ir);
4893 for (i = 0; i < vec_size(parser->functions); ++i) {
4894 if (!ast_function_codegen(parser->functions[i], ir)) {
4895 con_out("failed to generate function %s\n", parser->functions[i]->name);
4896 ir_builder_delete(ir);
4901 ir_builder_dump(ir, con_out);
4902 for (i = 0; i < vec_size(parser->functions); ++i) {
4903 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4904 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4905 ir_builder_delete(ir);
4912 ir_builder_dump(ir, con_out);
4914 generate_checksum(parser);
4916 if (!ir_builder_generate(ir, output)) {
4917 con_out("*** failed to generate output file\n");
4918 ir_builder_delete(ir);
4923 ir_builder_delete(ir);
4927 con_out("*** there were compile errors\n");