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, bool is_static);
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, 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, bool *is_static)
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;
2354 bool had_static = false;
2358 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2360 /* parse an attribute */
2361 if (!parser_next(parser)) {
2362 parseerror(parser, "expected attribute after `[[`");
2366 if (!strcmp(parser_tokval(parser), "noreturn")) {
2367 had_noreturn = true;
2368 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2369 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2374 else if (!strcmp(parser_tokval(parser), "noref")) {
2376 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2377 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2384 /* Skip tokens until we hit a ]] */
2385 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2386 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2387 if (!parser_next(parser)) {
2388 parseerror(parser, "error inside attribute");
2395 else if (!strcmp(parser_tokval(parser), "static"))
2397 else if (!strcmp(parser_tokval(parser), "const"))
2399 else if (!strcmp(parser_tokval(parser), "var"))
2401 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2403 else if (!strcmp(parser_tokval(parser), "noref"))
2405 else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2410 if (!parser_next(parser))
2420 *noreturn = had_noreturn;
2421 *is_static = had_static;
2424 parseerror(parser, "parse error after variable qualifier");
2429 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2431 ast_expression *operand;
2434 ast_switch *switchnode;
2435 ast_switch_case swcase;
2438 bool noref, noreturn, is_static;
2440 lex_ctx ctx = parser_ctx(parser);
2442 (void)block; /* not touching */
2445 /* parse over the opening paren */
2446 if (!parser_next(parser) || parser->tok != '(') {
2447 parseerror(parser, "expected switch operand in parenthesis");
2451 /* parse into the expression */
2452 if (!parser_next(parser)) {
2453 parseerror(parser, "expected switch operand");
2456 /* parse the operand */
2457 operand = parse_expression_leave(parser, false);
2461 switchnode = ast_switch_new(ctx, operand);
2464 if (parser->tok != ')') {
2465 ast_delete(switchnode);
2466 parseerror(parser, "expected closing paren after 'switch' operand");
2470 /* parse over the opening paren */
2471 if (!parser_next(parser) || parser->tok != '{') {
2472 ast_delete(switchnode);
2473 parseerror(parser, "expected list of cases");
2477 if (!parser_next(parser)) {
2478 ast_delete(switchnode);
2479 parseerror(parser, "expected 'case' or 'default'");
2483 /* new block; allow some variables to be declared here */
2484 parser_enterblock(parser);
2487 if (parser->tok == TOKEN_IDENT)
2488 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2489 if (typevar || parser->tok == TOKEN_TYPENAME) {
2490 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2491 ast_delete(switchnode);
2496 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2498 if (cvq == CV_WRONG) {
2499 ast_delete(switchnode);
2502 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2503 ast_delete(switchnode);
2512 while (parser->tok != '}') {
2513 ast_block *caseblock;
2515 if (parser->tok != TOKEN_KEYWORD) {
2516 ast_delete(switchnode);
2517 parseerror(parser, "expected 'case' or 'default'");
2520 if (!strcmp(parser_tokval(parser), "case")) {
2521 if (!parser_next(parser)) {
2522 ast_delete(switchnode);
2523 parseerror(parser, "expected expression for case");
2526 swcase.value = parse_expression_leave(parser, false);
2527 if (!swcase.value) {
2528 ast_delete(switchnode);
2529 parseerror(parser, "expected expression for case");
2532 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2533 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2534 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2540 else if (!strcmp(parser_tokval(parser), "default")) {
2541 swcase.value = NULL;
2542 if (!parser_next(parser)) {
2543 ast_delete(switchnode);
2544 parseerror(parser, "expected colon");
2549 /* Now the colon and body */
2550 if (parser->tok != ':') {
2551 if (swcase.value) ast_unref(swcase.value);
2552 ast_delete(switchnode);
2553 parseerror(parser, "expected colon");
2557 if (!parser_next(parser)) {
2558 if (swcase.value) ast_unref(swcase.value);
2559 ast_delete(switchnode);
2560 parseerror(parser, "expected statements or case");
2563 caseblock = ast_block_new(parser_ctx(parser));
2565 if (swcase.value) ast_unref(swcase.value);
2566 ast_delete(switchnode);
2569 swcase.code = (ast_expression*)caseblock;
2570 vec_push(switchnode->cases, swcase);
2572 ast_expression *expr;
2573 if (parser->tok == '}')
2575 if (parser->tok == TOKEN_KEYWORD) {
2576 if (!strcmp(parser_tokval(parser), "case") ||
2577 !strcmp(parser_tokval(parser), "default"))
2582 if (!parse_statement(parser, caseblock, &expr, true)) {
2583 ast_delete(switchnode);
2588 if (!ast_block_add_expr(caseblock, expr)) {
2589 ast_delete(switchnode);
2595 parser_leaveblock(parser);
2598 if (parser->tok != '}') {
2599 ast_delete(switchnode);
2600 parseerror(parser, "expected closing paren of case list");
2603 if (!parser_next(parser)) {
2604 ast_delete(switchnode);
2605 parseerror(parser, "parse error after switch");
2608 *out = (ast_expression*)switchnode;
2612 static bool parse_goto(parser_t *parser, ast_expression **out)
2617 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2618 parseerror(parser, "expected label name after `goto`");
2622 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2624 for (i = 0; i < vec_size(parser->labels); ++i) {
2625 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2626 ast_goto_set_label(gt, parser->labels[i]);
2630 if (i == vec_size(parser->labels))
2631 vec_push(parser->gotos, gt);
2633 if (!parser_next(parser) || parser->tok != ';') {
2634 parseerror(parser, "semicolon expected after goto label");
2637 if (!parser_next(parser)) {
2638 parseerror(parser, "parse error after goto");
2642 *out = (ast_expression*)gt;
2646 static bool parse_skipwhite(parser_t *parser)
2649 if (!parser_next(parser))
2651 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2652 return parser->tok < TOKEN_ERROR;
2655 static bool parse_eol(parser_t *parser)
2657 if (!parse_skipwhite(parser))
2659 return parser->tok == TOKEN_EOL;
2662 static bool parse_pragma_do(parser_t *parser)
2664 if (!parser_next(parser) ||
2665 parser->tok != TOKEN_IDENT ||
2666 strcmp(parser_tokval(parser), "pragma"))
2668 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2671 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2672 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2676 if (!strcmp(parser_tokval(parser), "noref")) {
2677 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2678 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2681 parser->noref = !!parser_token(parser)->constval.i;
2682 if (!parse_eol(parser)) {
2683 parseerror(parser, "parse error after `noref` pragma");
2689 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2696 static bool parse_pragma(parser_t *parser)
2699 parser->lex->flags.preprocessing = true;
2700 parser->lex->flags.mergelines = true;
2701 rv = parse_pragma_do(parser);
2702 if (parser->tok != TOKEN_EOL) {
2703 parseerror(parser, "junk after pragma");
2706 parser->lex->flags.preprocessing = false;
2707 parser->lex->flags.mergelines = false;
2708 if (!parser_next(parser)) {
2709 parseerror(parser, "parse error after pragma");
2715 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2717 bool noref, noreturn, is_static;
2719 ast_value *typevar = NULL;
2723 if (parser->tok == TOKEN_IDENT)
2724 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2726 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2728 /* local variable */
2730 parseerror(parser, "cannot declare a variable from here");
2733 if (opts.standard == COMPILER_QCC) {
2734 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2737 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2741 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2743 if (cvq == CV_WRONG)
2745 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2747 else if (parser->tok == TOKEN_KEYWORD)
2749 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2754 if (!parser_next(parser)) {
2755 parseerror(parser, "parse error after __builtin_debug_printtype");
2759 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2761 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2762 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2763 if (!parser_next(parser)) {
2764 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2770 if (!parse_statement(parser, block, out, allow_cases))
2773 con_out("__builtin_debug_printtype: got no output node\n");
2776 ast_type_to_string(*out, ty, sizeof(ty));
2777 con_out("__builtin_debug_printtype: `%s`\n", ty);
2782 else if (!strcmp(parser_tokval(parser), "return"))
2784 return parse_return(parser, block, out);
2786 else if (!strcmp(parser_tokval(parser), "if"))
2788 return parse_if(parser, block, out);
2790 else if (!strcmp(parser_tokval(parser), "while"))
2792 return parse_while(parser, block, out);
2794 else if (!strcmp(parser_tokval(parser), "do"))
2796 return parse_dowhile(parser, block, out);
2798 else if (!strcmp(parser_tokval(parser), "for"))
2800 if (opts.standard == COMPILER_QCC) {
2801 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2804 return parse_for(parser, block, out);
2806 else if (!strcmp(parser_tokval(parser), "break"))
2808 return parse_break_continue(parser, block, out, false);
2810 else if (!strcmp(parser_tokval(parser), "continue"))
2812 return parse_break_continue(parser, block, out, true);
2814 else if (!strcmp(parser_tokval(parser), "switch"))
2816 return parse_switch(parser, block, out);
2818 else if (!strcmp(parser_tokval(parser), "case") ||
2819 !strcmp(parser_tokval(parser), "default"))
2822 parseerror(parser, "unexpected 'case' label");
2827 else if (!strcmp(parser_tokval(parser), "goto"))
2829 return parse_goto(parser, out);
2831 else if (!strcmp(parser_tokval(parser), "typedef"))
2833 if (!parser_next(parser)) {
2834 parseerror(parser, "expected type definition after 'typedef'");
2837 return parse_typedef(parser);
2839 parseerror(parser, "Unexpected keyword");
2842 else if (parser->tok == '{')
2845 inner = parse_block(parser);
2848 *out = (ast_expression*)inner;
2851 else if (parser->tok == ':')
2855 if (!parser_next(parser)) {
2856 parseerror(parser, "expected label name");
2859 if (parser->tok != TOKEN_IDENT) {
2860 parseerror(parser, "label must be an identifier");
2863 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2866 vec_push(parser->labels, label);
2867 *out = (ast_expression*)label;
2868 if (!parser_next(parser)) {
2869 parseerror(parser, "parse error after label");
2872 for (i = 0; i < vec_size(parser->gotos); ++i) {
2873 if (!strcmp(parser->gotos[i]->name, label->name)) {
2874 ast_goto_set_label(parser->gotos[i], label);
2875 vec_remove(parser->gotos, i, 1);
2881 else if (parser->tok == ';')
2883 if (!parser_next(parser)) {
2884 parseerror(parser, "parse error after empty statement");
2891 ast_expression *exp = parse_expression(parser, false);
2895 if (!ast_side_effects(exp)) {
2896 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2903 static bool parse_block_into(parser_t *parser, ast_block *block)
2907 parser_enterblock(parser);
2909 if (!parser_next(parser)) { /* skip the '{' */
2910 parseerror(parser, "expected function body");
2914 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2916 ast_expression *expr = NULL;
2917 if (parser->tok == '}')
2920 if (!parse_statement(parser, block, &expr, false)) {
2921 /* parseerror(parser, "parse error"); */
2927 if (!ast_block_add_expr(block, expr)) {
2934 if (parser->tok != '}') {
2937 (void)parser_next(parser);
2941 if (!parser_leaveblock(parser))
2943 return retval && !!block;
2946 static ast_block* parse_block(parser_t *parser)
2949 block = ast_block_new(parser_ctx(parser));
2952 if (!parse_block_into(parser, block)) {
2953 ast_block_delete(block);
2959 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2961 if (parser->tok == '{') {
2962 *out = (ast_expression*)parse_block(parser);
2965 return parse_statement(parser, NULL, out, false);
2968 static bool create_vector_members(ast_value *var, ast_member **me)
2971 size_t len = strlen(var->name);
2973 for (i = 0; i < 3; ++i) {
2974 char *name = (char*)mem_a(len+3);
2975 memcpy(name, var->name, len);
2977 name[len+1] = 'x'+i;
2979 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2988 do { ast_member_delete(me[--i]); } while(i);
2992 static bool parse_function_body(parser_t *parser, ast_value *var)
2994 ast_block *block = NULL;
2999 ast_expression *framenum = NULL;
3000 ast_expression *nextthink = NULL;
3001 /* None of the following have to be deleted */
3002 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3003 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3004 bool has_frame_think;
3008 has_frame_think = false;
3009 old = parser->function;
3011 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3012 parseerror(parser, "gotos/labels leaking");
3016 if (var->expression.flags & AST_FLAG_VARIADIC) {
3017 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3018 "variadic function with implementation will not be able to access additional parameters"))
3024 if (parser->tok == '[') {
3025 /* got a frame definition: [ framenum, nextthink ]
3026 * this translates to:
3027 * self.frame = framenum;
3028 * self.nextthink = time + 0.1;
3029 * self.think = nextthink;
3033 fld_think = parser_find_field(parser, "think");
3034 fld_nextthink = parser_find_field(parser, "nextthink");
3035 fld_frame = parser_find_field(parser, "frame");
3036 if (!fld_think || !fld_nextthink || !fld_frame) {
3037 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3038 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3041 gbl_time = parser_find_global(parser, "time");
3042 gbl_self = parser_find_global(parser, "self");
3043 if (!gbl_time || !gbl_self) {
3044 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3045 parseerror(parser, "please declare the following globals: `time`, `self`");
3049 if (!parser_next(parser))
3052 framenum = parse_expression_leave(parser, true);
3054 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3057 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3058 ast_unref(framenum);
3059 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3063 if (parser->tok != ',') {
3064 ast_unref(framenum);
3065 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3066 parseerror(parser, "Got a %i\n", parser->tok);
3070 if (!parser_next(parser)) {
3071 ast_unref(framenum);
3075 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3077 /* qc allows the use of not-yet-declared functions here
3078 * - this automatically creates a prototype */
3079 ast_value *thinkfunc;
3080 ast_expression *functype = fld_think->expression.next;
3082 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3083 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3084 ast_unref(framenum);
3085 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3089 if (!parser_next(parser)) {
3090 ast_unref(framenum);
3091 ast_delete(thinkfunc);
3095 vec_push(parser->globals, (ast_expression*)thinkfunc);
3096 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3097 nextthink = (ast_expression*)thinkfunc;
3100 nextthink = parse_expression_leave(parser, true);
3102 ast_unref(framenum);
3103 parseerror(parser, "expected a think-function in [frame,think] notation");
3108 if (!ast_istype(nextthink, ast_value)) {
3109 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3113 if (retval && parser->tok != ']') {
3114 parseerror(parser, "expected closing `]` for [frame,think] notation");
3118 if (retval && !parser_next(parser)) {
3122 if (retval && parser->tok != '{') {
3123 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3128 ast_unref(nextthink);
3129 ast_unref(framenum);
3133 has_frame_think = true;
3136 block = ast_block_new(parser_ctx(parser));
3138 parseerror(parser, "failed to allocate block");
3139 if (has_frame_think) {
3140 ast_unref(nextthink);
3141 ast_unref(framenum);
3146 if (has_frame_think) {
3148 ast_expression *self_frame;
3149 ast_expression *self_nextthink;
3150 ast_expression *self_think;
3151 ast_expression *time_plus_1;
3152 ast_store *store_frame;
3153 ast_store *store_nextthink;
3154 ast_store *store_think;
3156 ctx = parser_ctx(parser);
3157 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3158 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3159 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3161 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3162 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3164 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3165 if (self_frame) ast_delete(self_frame);
3166 if (self_nextthink) ast_delete(self_nextthink);
3167 if (self_think) ast_delete(self_think);
3168 if (time_plus_1) ast_delete(time_plus_1);
3174 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3175 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3176 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3179 ast_delete(self_frame);
3182 if (!store_nextthink) {
3183 ast_delete(self_nextthink);
3187 ast_delete(self_think);
3191 if (store_frame) ast_delete(store_frame);
3192 if (store_nextthink) ast_delete(store_nextthink);
3193 if (store_think) ast_delete(store_think);
3196 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3197 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3198 !ast_block_add_expr(block, (ast_expression*)store_think))
3205 parseerror(parser, "failed to generate code for [frame,think]");
3206 ast_unref(nextthink);
3207 ast_unref(framenum);
3213 parser_enterblock(parser);
3215 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3217 ast_value *param = var->expression.params[parami];
3220 if (param->expression.vtype != TYPE_VECTOR &&
3221 (param->expression.vtype != TYPE_FIELD ||
3222 param->expression.next->expression.vtype != TYPE_VECTOR))
3227 if (!create_vector_members(param, me)) {
3228 ast_block_delete(block);
3232 for (e = 0; e < 3; ++e) {
3233 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3234 ast_block_collect(block, (ast_expression*)me[e]);
3238 func = ast_function_new(ast_ctx(var), var->name, var);
3240 parseerror(parser, "failed to allocate function for `%s`", var->name);
3241 ast_block_delete(block);
3244 vec_push(parser->functions, func);
3246 parser->function = func;
3247 if (!parse_block_into(parser, block)) {
3248 ast_block_delete(block);
3252 vec_push(func->blocks, block);
3254 parser->function = old;
3255 if (!parser_leaveblock(parser))
3257 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3258 parseerror(parser, "internal error: local scopes left");
3262 if (parser->tok == ';')
3263 return parser_next(parser);
3264 else if (opts.standard == COMPILER_QCC)
3265 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3269 vec_pop(parser->functions);
3270 ast_function_delete(func);
3271 var->constval.vfunc = NULL;
3274 (void)!parser_leaveblock(parser);
3275 parser->function = old;
3279 static ast_expression *array_accessor_split(
3284 ast_expression *left,
3285 ast_expression *right
3291 lex_ctx ctx = ast_ctx(array);
3293 if (!left || !right) {
3294 if (left) ast_delete(left);
3295 if (right) ast_delete(right);
3299 cmp = ast_binary_new(ctx, INSTR_LT,
3300 (ast_expression*)index,
3301 (ast_expression*)parser_const_float(parser, middle));
3305 parseerror(parser, "internal error: failed to create comparison for array setter");
3309 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3311 ast_delete(cmp); /* will delete left and right */
3312 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3316 return (ast_expression*)ifthen;
3319 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3321 lex_ctx ctx = ast_ctx(array);
3323 if (from+1 == afterend) {
3324 /* set this value */
3327 ast_array_index *subscript;
3329 int assignop = type_store_instr[value->expression.vtype];
3331 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3332 assignop = INSTR_STORE_V;
3334 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3338 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3340 ast_delete(subscript);
3344 block = ast_block_new(ctx);
3350 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3355 ret = ast_return_new(ctx, NULL);
3361 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3366 return (ast_expression*)block;
3368 ast_expression *left, *right;
3369 size_t diff = afterend - from;
3370 size_t middle = from + diff/2;
3371 left = array_setter_node(parser, array, index, value, from, middle);
3372 right = array_setter_node(parser, array, index, value, middle, afterend);
3373 return array_accessor_split(parser, array, index, middle, left, right);
3377 static ast_expression *array_field_setter_node(
3386 lex_ctx ctx = ast_ctx(array);
3388 if (from+1 == afterend) {
3389 /* set this value */
3392 ast_entfield *entfield;
3393 ast_array_index *subscript;
3395 int assignop = type_storep_instr[value->expression.vtype];
3397 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3398 assignop = INSTR_STOREP_V;
3400 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3404 entfield = ast_entfield_new_force(ctx,
3405 (ast_expression*)entity,
3406 (ast_expression*)subscript,
3407 (ast_expression*)subscript);
3409 ast_delete(subscript);
3413 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3415 ast_delete(entfield);
3419 block = ast_block_new(ctx);
3425 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3430 ret = ast_return_new(ctx, NULL);
3436 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3441 return (ast_expression*)block;
3443 ast_expression *left, *right;
3444 size_t diff = afterend - from;
3445 size_t middle = from + diff/2;
3446 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3447 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3448 return array_accessor_split(parser, array, index, middle, left, right);
3452 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3454 lex_ctx ctx = ast_ctx(array);
3456 if (from+1 == afterend) {
3458 ast_array_index *subscript;
3460 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3464 ret = ast_return_new(ctx, (ast_expression*)subscript);
3466 ast_delete(subscript);
3470 return (ast_expression*)ret;
3472 ast_expression *left, *right;
3473 size_t diff = afterend - from;
3474 size_t middle = from + diff/2;
3475 left = array_getter_node(parser, array, index, from, middle);
3476 right = array_getter_node(parser, array, index, middle, afterend);
3477 return array_accessor_split(parser, array, index, middle, left, right);
3481 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3483 ast_function *func = NULL;
3484 ast_value *fval = NULL;
3485 ast_block *body = NULL;
3487 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3489 parseerror(parser, "failed to create accessor function value");
3493 func = ast_function_new(ast_ctx(array), funcname, fval);
3496 parseerror(parser, "failed to create accessor function node");
3500 body = ast_block_new(ast_ctx(array));
3502 parseerror(parser, "failed to create block for array accessor");
3508 vec_push(func->blocks, body);
3511 vec_push(parser->accessors, fval);
3516 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3518 ast_expression *root = NULL;
3519 ast_value *index = NULL;
3520 ast_value *value = NULL;
3524 if (!ast_istype(array->expression.next, ast_value)) {
3525 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3529 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3531 func = fval->constval.vfunc;
3532 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3534 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3535 value = ast_value_copy((ast_value*)array->expression.next);
3537 if (!index || !value) {
3538 parseerror(parser, "failed to create locals for array accessor");
3541 (void)!ast_value_set_name(value, "value"); /* not important */
3542 vec_push(fval->expression.params, index);
3543 vec_push(fval->expression.params, value);
3545 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3547 parseerror(parser, "failed to build accessor search tree");
3551 array->setter = fval;
3552 return ast_block_add_expr(func->blocks[0], root);
3554 if (index) ast_delete(index);
3555 if (value) ast_delete(value);
3556 if (root) ast_delete(root);
3562 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3564 ast_expression *root = NULL;
3565 ast_value *entity = NULL;
3566 ast_value *index = NULL;
3567 ast_value *value = NULL;
3571 if (!ast_istype(array->expression.next, ast_value)) {
3572 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3576 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3578 func = fval->constval.vfunc;
3579 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3581 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3582 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3583 value = ast_value_copy((ast_value*)array->expression.next);
3584 if (!entity || !index || !value) {
3585 parseerror(parser, "failed to create locals for array accessor");
3588 (void)!ast_value_set_name(value, "value"); /* not important */
3589 vec_push(fval->expression.params, entity);
3590 vec_push(fval->expression.params, index);
3591 vec_push(fval->expression.params, value);
3593 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3595 parseerror(parser, "failed to build accessor search tree");
3599 array->setter = fval;
3600 return ast_block_add_expr(func->blocks[0], root);
3602 if (entity) ast_delete(entity);
3603 if (index) ast_delete(index);
3604 if (value) ast_delete(value);
3605 if (root) ast_delete(root);
3611 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3613 ast_expression *root = NULL;
3614 ast_value *index = NULL;
3618 /* NOTE: checking array->expression.next rather than elemtype since
3619 * for fields elemtype is a temporary fieldtype.
3621 if (!ast_istype(array->expression.next, ast_value)) {
3622 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3626 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3628 func = fval->constval.vfunc;
3629 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3631 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3634 parseerror(parser, "failed to create locals for array accessor");
3637 vec_push(fval->expression.params, index);
3639 root = array_getter_node(parser, array, index, 0, array->expression.count);
3641 parseerror(parser, "failed to build accessor search tree");
3645 array->getter = fval;
3646 return ast_block_add_expr(func->blocks[0], root);
3648 if (index) ast_delete(index);
3649 if (root) ast_delete(root);
3655 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3656 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3664 bool variadic = false;
3666 ctx = parser_ctx(parser);
3668 /* for the sake of less code we parse-in in this function */
3669 if (!parser_next(parser)) {
3670 parseerror(parser, "expected parameter list");
3676 /* parse variables until we hit a closing paren */
3677 while (parser->tok != ')') {
3679 /* there must be commas between them */
3680 if (parser->tok != ',') {
3681 parseerror(parser, "expected comma or end of parameter list");
3684 if (!parser_next(parser)) {
3685 parseerror(parser, "expected parameter");
3691 if (parser->tok == TOKEN_DOTS) {
3692 /* '...' indicates a varargs function */
3694 if (!parser_next(parser)) {
3695 parseerror(parser, "expected parameter");
3698 if (parser->tok != ')') {
3699 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3705 /* for anything else just parse a typename */
3706 param = parse_typename(parser, NULL, NULL);
3709 vec_push(params, param);
3710 if (param->expression.vtype >= TYPE_VARIANT) {
3711 char tname[1024]; /* typename is reserved in C++ */
3712 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3713 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3719 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3723 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3724 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3727 if (!parser_next(parser)) {
3728 parseerror(parser, "parse error after typename");
3732 /* now turn 'var' into a function type */
3733 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3734 fval->expression.next = (ast_expression*)var;
3736 fval->expression.flags |= AST_FLAG_VARIADIC;
3739 var->expression.params = params;
3746 for (i = 0; i < vec_size(params); ++i)
3747 ast_delete(params[i]);
3752 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3754 ast_expression *cexp;
3755 ast_value *cval, *tmp;
3758 ctx = parser_ctx(parser);
3760 if (!parser_next(parser)) {
3762 parseerror(parser, "expected array-size");
3766 cexp = parse_expression_leave(parser, true);
3768 if (!cexp || !ast_istype(cexp, ast_value)) {
3772 parseerror(parser, "expected array-size as constant positive integer");
3775 cval = (ast_value*)cexp;
3777 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3778 tmp->expression.next = (ast_expression*)var;
3781 if (cval->expression.vtype == TYPE_INTEGER)
3782 tmp->expression.count = cval->constval.vint;
3783 else if (cval->expression.vtype == TYPE_FLOAT)
3784 tmp->expression.count = cval->constval.vfloat;
3788 parseerror(parser, "array-size must be a positive integer constant");
3793 if (parser->tok != ']') {
3795 parseerror(parser, "expected ']' after array-size");
3798 if (!parser_next(parser)) {
3800 parseerror(parser, "error after parsing array size");
3806 /* Parse a complete typename.
3807 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3808 * but when parsing variables separated by comma
3809 * 'storebase' should point to where the base-type should be kept.
3810 * The base type makes up every bit of type information which comes *before* the
3813 * The following will be parsed in its entirety:
3815 * The 'basetype' in this case is 'void()'
3816 * and if there's a comma after it, say:
3818 * then the type-information 'void()' can be stored in 'storebase'
3820 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3822 ast_value *var, *tmp;
3825 const char *name = NULL;
3826 bool isfield = false;
3827 bool wasarray = false;
3828 size_t morefields = 0;
3830 ctx = parser_ctx(parser);
3832 /* types may start with a dot */
3833 if (parser->tok == '.') {
3835 /* if we parsed a dot we need a typename now */
3836 if (!parser_next(parser)) {
3837 parseerror(parser, "expected typename for field definition");
3841 /* Further dots are handled seperately because they won't be part of the
3844 while (parser->tok == '.') {
3846 if (!parser_next(parser)) {
3847 parseerror(parser, "expected typename for field definition");
3852 if (parser->tok == TOKEN_IDENT)
3853 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3854 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3855 parseerror(parser, "expected typename");
3859 /* generate the basic type value */
3860 if (cached_typedef) {
3861 var = ast_value_copy(cached_typedef);
3862 ast_value_set_name(var, "<type(from_def)>");
3864 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3866 for (; morefields; --morefields) {
3867 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3868 tmp->expression.next = (ast_expression*)var;
3872 /* do not yet turn into a field - remember:
3873 * .void() foo; is a field too
3874 * .void()() foo; is a function
3878 if (!parser_next(parser)) {
3880 parseerror(parser, "parse error after typename");
3884 /* an opening paren now starts the parameter-list of a function
3885 * this is where original-QC has parameter lists.
3886 * We allow a single parameter list here.
3887 * Much like fteqcc we don't allow `float()() x`
3889 if (parser->tok == '(') {
3890 var = parse_parameter_list(parser, var);
3895 /* store the base if requested */
3897 *storebase = ast_value_copy(var);
3899 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3900 tmp->expression.next = (ast_expression*)*storebase;
3905 /* there may be a name now */
3906 if (parser->tok == TOKEN_IDENT) {
3907 name = util_strdup(parser_tokval(parser));
3909 if (!parser_next(parser)) {
3911 parseerror(parser, "error after variable or field declaration");
3916 /* now this may be an array */
3917 if (parser->tok == '[') {
3919 var = parse_arraysize(parser, var);
3924 /* This is the point where we can turn it into a field */
3926 /* turn it into a field if desired */
3927 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3928 tmp->expression.next = (ast_expression*)var;
3932 /* now there may be function parens again */
3933 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3934 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3935 if (parser->tok == '(' && wasarray)
3936 parseerror(parser, "arrays as part of a return type is not supported");
3937 while (parser->tok == '(') {
3938 var = parse_parameter_list(parser, var);
3947 /* finally name it */
3949 if (!ast_value_set_name(var, name)) {
3951 parseerror(parser, "internal error: failed to set name");
3954 /* free the name, ast_value_set_name duplicates */
3961 static bool parse_typedef(parser_t *parser)
3963 ast_value *typevar, *oldtype;
3964 ast_expression *old;
3966 typevar = parse_typename(parser, NULL, NULL);
3971 if ( (old = parser_find_var(parser, typevar->name)) ) {
3972 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3973 " -> `%s` has been declared here: %s:%i",
3974 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3975 ast_delete(typevar);
3979 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3980 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3981 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3982 ast_delete(typevar);
3986 vec_push(parser->_typedefs, typevar);
3987 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3989 if (parser->tok != ';') {
3990 parseerror(parser, "expected semicolon after typedef");
3993 if (!parser_next(parser)) {
3994 parseerror(parser, "parse error after typedef");
4001 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static)
4005 ast_expression *old;
4009 ast_value *basetype = NULL;
4011 bool isparam = false;
4012 bool isvector = false;
4013 bool cleanvar = true;
4014 bool wasarray = false;
4018 /* get the first complete variable */
4019 var = parse_typename(parser, &basetype, cached_typedef);
4022 ast_delete(basetype);
4030 /* Part 0: finish the type */
4031 if (parser->tok == '(') {
4032 if (opts.standard == COMPILER_QCC)
4033 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4034 var = parse_parameter_list(parser, var);
4040 /* we only allow 1-dimensional arrays */
4041 if (parser->tok == '[') {
4043 var = parse_arraysize(parser, var);
4049 if (parser->tok == '(' && wasarray) {
4050 parseerror(parser, "arrays as part of a return type is not supported");
4051 /* we'll still parse the type completely for now */
4053 /* for functions returning functions */
4054 while (parser->tok == '(') {
4055 if (opts.standard == COMPILER_QCC)
4056 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4057 var = parse_parameter_list(parser, var);
4064 var->cvq = qualifier;
4065 /* in a noref section we simply bump the usecount */
4066 if (noref || parser->noref)
4069 var->expression.flags |= AST_FLAG_NORETURN;
4072 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4073 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4074 * is then filled with the previous definition and the parameter-names replaced.
4077 /* Deal with end_sys_ vars */
4079 if (!strcmp(var->name, "end_sys_globals")) {
4081 parser->crc_globals = vec_size(parser->globals);
4084 else if (!strcmp(var->name, "end_sys_fields")) {
4086 parser->crc_fields = vec_size(parser->fields);
4089 if (was_end && var->expression.vtype == TYPE_FIELD) {
4090 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4091 "global '%s' hint should not be a field",
4092 parser_tokval(parser)))
4099 if (!nofields && var->expression.vtype == TYPE_FIELD)
4101 /* deal with field declarations */
4102 old = parser_find_field(parser, var->name);
4104 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4105 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4114 parseerror(parser, "field `%s` already declared here: %s:%i",
4115 var->name, ast_ctx(old).file, ast_ctx(old).line);
4120 if (opts.standard == COMPILER_QCC &&
4121 (old = parser_find_global(parser, var->name)))
4123 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4124 parseerror(parser, "field `%s` already declared here: %s:%i",
4125 var->name, ast_ctx(old).file, ast_ctx(old).line);
4132 /* deal with other globals */
4133 old = parser_find_global(parser, var->name);
4134 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4136 /* This is a function which had a prototype */
4137 if (!ast_istype(old, ast_value)) {
4138 parseerror(parser, "internal error: prototype is not an ast_value");
4142 proto = (ast_value*)old;
4143 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4144 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4146 ast_ctx(proto).file, ast_ctx(proto).line);
4150 /* we need the new parameter-names */
4151 for (i = 0; i < vec_size(proto->expression.params); ++i)
4152 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4160 if (opts.standard == COMPILER_GMQCC) {
4161 parseerror(parser, "global `%s` already declared here: %s:%i",
4162 var->name, ast_ctx(old).file, ast_ctx(old).line);
4166 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4167 "global `%s` already declared here: %s:%i",
4168 var->name, ast_ctx(old).file, ast_ctx(old).line))
4173 proto = (ast_value*)old;
4174 if (!ast_istype(old, ast_value)) {
4175 parseerror(parser, "internal error: not an ast_value");
4184 if (opts.standard == COMPILER_QCC &&
4185 (old = parser_find_field(parser, var->name)))
4187 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4188 parseerror(parser, "global `%s` already declared here: %s:%i",
4189 var->name, ast_ctx(old).file, ast_ctx(old).line);
4196 else /* it's not a global */
4198 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4199 if (old && !isparam) {
4200 parseerror(parser, "local `%s` already declared here: %s:%i",
4201 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4205 old = parser_find_local(parser, var->name, 0, &isparam);
4206 if (old && isparam) {
4207 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4208 "local `%s` is shadowing a parameter", var->name))
4210 parseerror(parser, "local `%s` already declared here: %s:%i",
4211 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4215 if (opts.standard != COMPILER_GMQCC) {
4224 * Create the global/local, and deal with vector types.
4227 if (var->expression.vtype == TYPE_VECTOR)
4229 else if (var->expression.vtype == TYPE_FIELD &&
4230 var->expression.next->expression.vtype == TYPE_VECTOR)
4234 if (!create_vector_members(var, me)) {
4241 /* deal with global variables, fields, functions */
4242 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4243 var->isfield = true;
4244 vec_push(parser->fields, (ast_expression*)var);
4245 util_htset(parser->htfields, var->name, var);
4247 for (i = 0; i < 3; ++i) {
4248 vec_push(parser->fields, (ast_expression*)me[i]);
4249 util_htset(parser->htfields, me[i]->name, me[i]);
4254 vec_push(parser->globals, (ast_expression*)var);
4255 util_htset(parser->htglobals, var->name, var);
4257 for (i = 0; i < 3; ++i) {
4258 vec_push(parser->globals, (ast_expression*)me[i]);
4259 util_htset(parser->htglobals, me[i]->name, me[i]);
4265 /* a static adds itself to be generated like any other global
4266 * but is added to the local namespace instead
4268 char *defname = NULL;
4269 size_t prefix_len, ln;
4271 ln = strlen(parser->function->name);
4272 vec_append(defname, ln, parser->function->name);
4274 vec_append(defname, 2, "::");
4275 /* remember the length up to here */
4276 prefix_len = vec_size(defname);
4278 /* Add it to the local scope */
4279 util_htset(vec_last(parser->variables), var->name, (void*)var);
4280 /* now rename the global */
4281 ln = strlen(var->name);
4282 vec_append(defname, ln, var->name);
4283 ast_value_set_name(var, defname);
4285 /* push it to the to-be-generated globals */
4286 vec_push(parser->globals, (ast_expression*)var);
4288 /* same game for the vector members */
4290 for (i = 0; i < 3; ++i) {
4291 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4293 vec_shrinkto(defname, prefix_len);
4294 ln = strlen(me[i]->name);
4295 vec_append(defname, ln, me[i]->name);
4296 ast_member_set_name(me[i], defname);
4298 vec_push(parser->globals, (ast_expression*)me[i]);
4303 vec_push(localblock->locals, var);
4304 parser_addlocal(parser, var->name, (ast_expression*)var);
4306 for (i = 0; i < 3; ++i) {
4307 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4308 ast_block_collect(localblock, (ast_expression*)me[i]);
4314 me[0] = me[1] = me[2] = NULL;
4319 if (var->expression.vtype == TYPE_ARRAY) {
4321 snprintf(name, sizeof(name), "%s##SET", var->name);
4322 if (!parser_create_array_setter(parser, var, name))
4324 snprintf(name, sizeof(name), "%s##GET", var->name);
4325 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4328 else if (!localblock && !nofields &&
4329 var->expression.vtype == TYPE_FIELD &&
4330 var->expression.next->expression.vtype == TYPE_ARRAY)
4333 ast_expression *telem;
4335 ast_value *array = (ast_value*)var->expression.next;
4337 if (!ast_istype(var->expression.next, ast_value)) {
4338 parseerror(parser, "internal error: field element type must be an ast_value");
4342 snprintf(name, sizeof(name), "%s##SETF", var->name);
4343 if (!parser_create_array_field_setter(parser, array, name))
4346 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4347 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4348 tfield->expression.next = telem;
4349 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4350 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4358 if (parser->tok == ';') {
4359 ast_delete(basetype);
4360 if (!parser_next(parser)) {
4361 parseerror(parser, "error after variable declaration");
4367 if (parser->tok == ',')
4371 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4374 parseerror(parser, "missing comma or semicolon while parsing variables");
4378 if (localblock && opts.standard == COMPILER_QCC) {
4379 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4380 "initializing expression turns variable `%s` into a constant in this standard",
4387 if (parser->tok != '{') {
4388 if (parser->tok != '=') {
4389 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4393 if (!parser_next(parser)) {
4394 parseerror(parser, "error parsing initializer");
4398 else if (opts.standard == COMPILER_QCC) {
4399 parseerror(parser, "expected '=' before function body in this standard");
4402 if (parser->tok == '#') {
4403 ast_function *func = NULL;
4406 parseerror(parser, "cannot declare builtins within functions");
4409 if (var->expression.vtype != TYPE_FUNCTION) {
4410 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4413 if (!parser_next(parser)) {
4414 parseerror(parser, "expected builtin number");
4417 if (parser->tok != TOKEN_INTCONST) {
4418 parseerror(parser, "builtin number must be an integer constant");
4421 if (parser_token(parser)->constval.i < 0) {
4422 parseerror(parser, "builtin number must be an integer greater than zero");
4426 if (var->hasvalue) {
4427 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4428 "builtin `%s` has already been defined\n"
4429 " -> previous declaration here: %s:%i",
4430 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4434 func = ast_function_new(ast_ctx(var), var->name, var);
4436 parseerror(parser, "failed to allocate function for `%s`", var->name);
4439 vec_push(parser->functions, func);
4441 func->builtin = -parser_token(parser)->constval.i-1;
4444 if (!parser_next(parser)) {
4445 parseerror(parser, "expected comma or semicolon");
4447 ast_function_delete(func);
4448 var->constval.vfunc = NULL;
4452 else if (parser->tok == '{' || parser->tok == '[')
4455 parseerror(parser, "cannot declare functions within functions");
4460 ast_ctx(proto) = parser_ctx(parser);
4462 if (!parse_function_body(parser, var))
4464 ast_delete(basetype);
4465 for (i = 0; i < vec_size(parser->gotos); ++i)
4466 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4467 vec_free(parser->gotos);
4468 vec_free(parser->labels);
4471 ast_expression *cexp;
4474 cexp = parse_expression_leave(parser, true);
4479 cval = (ast_value*)cexp;
4480 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4481 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4484 if (opts.standard != COMPILER_GMQCC &&
4485 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4486 qualifier != CV_VAR)
4488 var->cvq = CV_CONST;
4490 var->hasvalue = true;
4491 if (cval->expression.vtype == TYPE_STRING)
4492 var->constval.vstring = parser_strdup(cval->constval.vstring);
4493 else if (cval->expression.vtype == TYPE_FIELD)
4494 var->constval.vfield = cval;
4496 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4501 shunt sy = { NULL, NULL };
4504 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4505 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4506 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4507 if (!parser_sy_apply_operator(parser, &sy))
4510 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4511 parseerror(parser, "internal error: leaked operands");
4512 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4522 if (parser->tok == ',') {
4523 if (!parser_next(parser)) {
4524 parseerror(parser, "expected another variable");
4528 if (parser->tok != TOKEN_IDENT) {
4529 parseerror(parser, "expected another variable");
4532 var = ast_value_copy(basetype);
4534 ast_value_set_name(var, parser_tokval(parser));
4535 if (!parser_next(parser)) {
4536 parseerror(parser, "error parsing variable declaration");
4542 if (parser->tok != ';') {
4543 parseerror(parser, "missing semicolon after variables");
4547 if (!parser_next(parser)) {
4548 parseerror(parser, "parse error after variable declaration");
4552 ast_delete(basetype);
4556 if (cleanvar && var)
4558 ast_delete(basetype);
4562 ast_delete(basetype);
4563 if (cleanvar && var)
4565 if (me[0]) ast_member_delete(me[0]);
4566 if (me[1]) ast_member_delete(me[1]);
4567 if (me[2]) ast_member_delete(me[2]);
4571 static bool parser_global_statement(parser_t *parser)
4575 bool noreturn = false;
4576 bool is_static = false;
4577 ast_value *istype = NULL;
4579 if (parser->tok == TOKEN_IDENT)
4580 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4582 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4584 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4586 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4588 if (cvq == CV_WRONG)
4590 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4592 else if (parser->tok == TOKEN_KEYWORD)
4594 if (!strcmp(parser_tokval(parser), "typedef")) {
4595 if (!parser_next(parser)) {
4596 parseerror(parser, "expected type definition after 'typedef'");
4599 return parse_typedef(parser);
4601 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4604 else if (parser->tok == '#')
4606 return parse_pragma(parser);
4608 else if (parser->tok == '$')
4610 if (!parser_next(parser)) {
4611 parseerror(parser, "parse error");
4617 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4623 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4625 return util_crc16(old, str, strlen(str));
4628 static void progdefs_crc_file(const char *str)
4630 /* write to progdefs.h here */
4634 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4636 old = progdefs_crc_sum(old, str);
4637 progdefs_crc_file(str);
4641 static void generate_checksum(parser_t *parser)
4643 uint16_t crc = 0xFFFF;
4647 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4648 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4650 progdefs_crc_file("\tint\tpad;\n");
4651 progdefs_crc_file("\tint\tofs_return[3];\n");
4652 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4653 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4654 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4655 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4656 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4657 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4658 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4659 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4661 for (i = 0; i < parser->crc_globals; ++i) {
4662 if (!ast_istype(parser->globals[i], ast_value))
4664 value = (ast_value*)(parser->globals[i]);
4665 switch (value->expression.vtype) {
4666 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4667 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4668 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4669 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4671 crc = progdefs_crc_both(crc, "\tint\t");
4674 crc = progdefs_crc_both(crc, value->name);
4675 crc = progdefs_crc_both(crc, ";\n");
4677 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4678 for (i = 0; i < parser->crc_fields; ++i) {
4679 if (!ast_istype(parser->fields[i], ast_value))
4681 value = (ast_value*)(parser->fields[i]);
4682 switch (value->expression.next->expression.vtype) {
4683 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4684 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4685 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4686 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4688 crc = progdefs_crc_both(crc, "\tint\t");
4691 crc = progdefs_crc_both(crc, value->name);
4692 crc = progdefs_crc_both(crc, ";\n");
4694 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4699 static parser_t *parser;
4705 parser = (parser_t*)mem_a(sizeof(parser_t));
4709 memset(parser, 0, sizeof(*parser));
4711 for (i = 0; i < operator_count; ++i) {
4712 if (operators[i].id == opid1('=')) {
4713 parser->assign_op = operators+i;
4717 if (!parser->assign_op) {
4718 printf("internal error: initializing parser: failed to find assign operator\n");
4723 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4724 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4725 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4726 vec_push(parser->_blocktypedefs, 0);
4730 bool parser_compile()
4732 /* initial lexer/parser state */
4733 parser->lex->flags.noops = true;
4735 if (parser_next(parser))
4737 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4739 if (!parser_global_statement(parser)) {
4740 if (parser->tok == TOKEN_EOF)
4741 parseerror(parser, "unexpected eof");
4742 else if (!parser->errors)
4743 parseerror(parser, "there have been errors, bailing out");
4744 lex_close(parser->lex);
4750 parseerror(parser, "parse error");
4751 lex_close(parser->lex);
4756 lex_close(parser->lex);
4759 return !parser->errors;
4762 bool parser_compile_file(const char *filename)
4764 parser->lex = lex_open(filename);
4766 con_err("failed to open file \"%s\"\n", filename);
4769 return parser_compile();
4772 bool parser_compile_string(const char *name, const char *str, size_t len)
4774 parser->lex = lex_open_string(str, len, name);
4776 con_err("failed to create lexer for string \"%s\"\n", name);
4779 return parser_compile();
4782 void parser_cleanup()
4785 for (i = 0; i < vec_size(parser->accessors); ++i) {
4786 ast_delete(parser->accessors[i]->constval.vfunc);
4787 parser->accessors[i]->constval.vfunc = NULL;
4788 ast_delete(parser->accessors[i]);
4790 for (i = 0; i < vec_size(parser->functions); ++i) {
4791 ast_delete(parser->functions[i]);
4793 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4794 ast_delete(parser->imm_vector[i]);
4796 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4797 ast_delete(parser->imm_string[i]);
4799 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4800 ast_delete(parser->imm_float[i]);
4802 for (i = 0; i < vec_size(parser->fields); ++i) {
4803 ast_delete(parser->fields[i]);
4805 for (i = 0; i < vec_size(parser->globals); ++i) {
4806 ast_delete(parser->globals[i]);
4808 vec_free(parser->accessors);
4809 vec_free(parser->functions);
4810 vec_free(parser->imm_vector);
4811 vec_free(parser->imm_string);
4812 vec_free(parser->imm_float);
4813 vec_free(parser->globals);
4814 vec_free(parser->fields);
4816 for (i = 0; i < vec_size(parser->variables); ++i)
4817 util_htdel(parser->variables[i]);
4818 vec_free(parser->variables);
4819 vec_free(parser->_blocklocals);
4820 vec_free(parser->_locals);
4822 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4823 ast_delete(parser->_typedefs[i]);
4824 vec_free(parser->_typedefs);
4825 for (i = 0; i < vec_size(parser->typedefs); ++i)
4826 util_htdel(parser->typedefs[i]);
4827 vec_free(parser->typedefs);
4828 vec_free(parser->_blocktypedefs);
4830 vec_free(parser->_block_ctx);
4832 vec_free(parser->labels);
4833 vec_free(parser->gotos);
4838 bool parser_finish(const char *output)
4844 if (!parser->errors)
4846 ir = ir_builder_new("gmqcc_out");
4848 con_out("failed to allocate builder\n");
4852 for (i = 0; i < vec_size(parser->fields); ++i) {
4855 if (!ast_istype(parser->fields[i], ast_value))
4857 field = (ast_value*)parser->fields[i];
4858 hasvalue = field->hasvalue;
4859 field->hasvalue = false;
4860 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4861 con_out("failed to generate field %s\n", field->name);
4862 ir_builder_delete(ir);
4867 ast_expression *subtype;
4868 field->hasvalue = true;
4869 subtype = field->expression.next;
4870 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4871 if (subtype->expression.vtype == TYPE_FIELD)
4872 ifld->fieldtype = subtype->expression.next->expression.vtype;
4873 else if (subtype->expression.vtype == TYPE_FUNCTION)
4874 ifld->outtype = subtype->expression.next->expression.vtype;
4875 (void)!ir_value_set_field(field->ir_v, ifld);
4878 for (i = 0; i < vec_size(parser->globals); ++i) {
4880 if (!ast_istype(parser->globals[i], ast_value))
4882 asvalue = (ast_value*)(parser->globals[i]);
4883 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4884 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4885 "unused global: `%s`", asvalue->name);
4887 if (!ast_global_codegen(asvalue, ir, false)) {
4888 con_out("failed to generate global %s\n", asvalue->name);
4889 ir_builder_delete(ir);
4893 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4894 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4895 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4896 ir_builder_delete(ir);
4900 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4901 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4902 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4903 ir_builder_delete(ir);
4907 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4908 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4909 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4910 ir_builder_delete(ir);
4914 for (i = 0; i < vec_size(parser->globals); ++i) {
4916 if (!ast_istype(parser->globals[i], ast_value))
4918 asvalue = (ast_value*)(parser->globals[i]);
4919 if (!ast_generate_accessors(asvalue, ir)) {
4920 ir_builder_delete(ir);
4924 for (i = 0; i < vec_size(parser->fields); ++i) {
4926 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4928 if (!ast_istype((ast_expression*)asvalue, ast_value))
4930 if (asvalue->expression.vtype != TYPE_ARRAY)
4932 if (!ast_generate_accessors(asvalue, ir)) {
4933 ir_builder_delete(ir);
4937 for (i = 0; i < vec_size(parser->functions); ++i) {
4938 if (!ast_function_codegen(parser->functions[i], ir)) {
4939 con_out("failed to generate function %s\n", parser->functions[i]->name);
4940 ir_builder_delete(ir);
4945 ir_builder_dump(ir, con_out);
4946 for (i = 0; i < vec_size(parser->functions); ++i) {
4947 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4948 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4949 ir_builder_delete(ir);
4956 ir_builder_dump(ir, con_out);
4958 generate_checksum(parser);
4960 if (!ir_builder_generate(ir, output)) {
4961 con_out("*** failed to generate output file\n");
4962 ir_builder_delete(ir);
4967 ir_builder_delete(ir);
4971 con_out("*** there were compile errors\n");