5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define PARSER_HT_FIELDS 0
30 #define PARSER_HT_GLOBALS 1
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
59 ast_function *function;
61 /* All the labels the function defined...
62 * Should they be in ast_function instead?
67 /* A list of hashtables for each scope */
73 /* not to be used directly, we use the hash table */
74 ast_expression **_locals;
76 ast_value **_typedefs;
77 size_t *_blocktypedefs;
82 /* we store the '=' operator info */
83 const oper_info *assign_op;
85 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
86 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
87 * anything else: type error
91 /* Keep track of our ternary vs parenthesis nesting state.
92 * If we reach a 'comma' operator in a ternary without a paren,
93 * we shall trigger -Wternary-precedence.
95 enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
101 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
103 static void parser_enterblock(parser_t *parser);
104 static bool parser_leaveblock(parser_t *parser);
105 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
106 static bool parse_typedef(parser_t *parser);
107 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn);
108 static ast_block* parse_block(parser_t *parser);
109 static bool parse_block_into(parser_t *parser, ast_block *block);
110 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
111 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
112 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
113 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
115 static void parseerror(parser_t *parser, const char *fmt, ...)
122 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
126 /* returns true if it counts as an error */
127 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
132 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
137 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
142 r = vcompile_warning(ctx, warntype, fmt, ap);
147 /**********************************************************************
148 * some maths used for constant folding
151 vector vec3_add(vector a, vector b)
160 vector vec3_sub(vector a, vector b)
169 qcfloat vec3_mulvv(vector a, vector b)
171 return (a.x * b.x + a.y * b.y + a.z * b.z);
174 vector vec3_mulvf(vector a, float b)
183 /**********************************************************************
187 bool parser_next(parser_t *parser)
189 /* lex_do kills the previous token */
190 parser->tok = lex_do(parser->lex);
191 if (parser->tok == TOKEN_EOF)
193 if (parser->tok >= TOKEN_ERROR) {
194 parseerror(parser, "lex error");
200 #define parser_tokval(p) ((p)->lex->tok.value)
201 #define parser_token(p) (&((p)->lex->tok))
202 #define parser_ctx(p) ((p)->lex->tok.ctx)
204 static ast_value* parser_const_float(parser_t *parser, double d)
208 for (i = 0; i < vec_size(parser->imm_float); ++i) {
209 const double compare = parser->imm_float[i]->constval.vfloat;
210 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
211 return parser->imm_float[i];
213 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
215 out->hasvalue = true;
216 out->constval.vfloat = d;
217 vec_push(parser->imm_float, out);
221 static ast_value* parser_const_float_0(parser_t *parser)
223 if (!parser->imm_float_zero)
224 parser->imm_float_zero = parser_const_float(parser, 0);
225 return parser->imm_float_zero;
228 static ast_value* parser_const_float_1(parser_t *parser)
230 if (!parser->imm_float_one)
231 parser->imm_float_one = parser_const_float(parser, 1);
232 return parser->imm_float_one;
235 static char *parser_strdup(const char *str)
238 /* actually dup empty strings */
239 char *out = mem_a(1);
243 return util_strdup(str);
246 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
250 for (i = 0; i < vec_size(parser->imm_string); ++i) {
251 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
252 return parser->imm_string[i];
256 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
257 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
259 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
261 out->hasvalue = true;
262 out->constval.vstring = parser_strdup(str);
263 vec_push(parser->imm_string, out);
267 static ast_value* parser_const_vector(parser_t *parser, vector v)
271 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
272 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
273 return parser->imm_vector[i];
275 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
277 out->hasvalue = true;
278 out->constval.vvec = v;
279 vec_push(parser->imm_vector, out);
283 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
289 return parser_const_vector(parser, v);
292 static ast_value* parser_const_vector_0(parser_t *parser)
294 if (!parser->imm_vector_zero)
295 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
296 return parser->imm_vector_zero;
299 static ast_expression* parser_find_field(parser_t *parser, const char *name)
301 return util_htget(parser->htfields, name);
304 static ast_expression* parser_find_global(parser_t *parser, const char *name)
306 return util_htget(parser->htglobals, name);
309 static ast_expression* parser_find_param(parser_t *parser, const char *name)
313 if (!parser->function)
315 fun = parser->function->vtype;
316 for (i = 0; i < vec_size(fun->expression.params); ++i) {
317 if (!strcmp(fun->expression.params[i]->name, name))
318 return (ast_expression*)(fun->expression.params[i]);
323 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
328 hash = util_hthash(parser->htglobals, name);
331 for (i = vec_size(parser->variables); i > upto;) {
333 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
337 return parser_find_param(parser, name);
340 static ast_expression* parser_find_var(parser_t *parser, const char *name)
344 v = parser_find_local(parser, name, 0, &dummy);
345 if (!v) v = parser_find_global(parser, name);
349 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
353 hash = util_hthash(parser->typedefs[0], name);
355 for (i = vec_size(parser->typedefs); i > upto;) {
357 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
365 size_t etype; /* 0 = expression, others are operators */
369 ast_block *block; /* for commas and function calls */
378 #define SY_PAREN_EXPR '('
379 #define SY_PAREN_FUNC 'f'
380 #define SY_PAREN_INDEX '['
381 #define SY_PAREN_TERNARY '?'
383 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
394 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
398 e.out = (ast_expression*)v;
405 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
407 e.etype = 1 + (op - operators);
416 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
428 # define DEBUGSHUNTDO(x) x
430 # define DEBUGSHUNTDO(x)
433 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
434 * so we need to rotate it to become ent.(foo[n]).
436 static bool rotate_entfield_array_index_nodes(ast_expression **out)
438 ast_array_index *index;
439 ast_entfield *entfield;
443 ast_expression *entity;
445 lex_ctx ctx = ast_ctx(*out);
447 if (!ast_istype(*out, ast_array_index))
449 index = (ast_array_index*)*out;
451 if (!ast_istype(index->array, ast_entfield))
453 entfield = (ast_entfield*)index->array;
455 if (!ast_istype(entfield->field, ast_value))
457 field = (ast_value*)entfield->field;
460 entity = entfield->entity;
464 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
465 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
466 *out = (ast_expression*)entfield;
471 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
473 switch (v->expression.vtype) {
475 return !!v->constval.vfloat;
477 return !!v->constval.vint;
479 if (OPTS_FLAG(CORRECT_LOGIC))
480 return v->constval.vvec.x &&
481 v->constval.vvec.y &&
484 return !!(v->constval.vvec.x);
486 if (!v->constval.vstring)
488 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
490 return !!v->constval.vstring[0];
492 compile_error(ctx, "internal error: immediate_is_true on invalid type");
493 return !!v->constval.vfunc;
497 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
501 ast_expression *out = NULL;
502 ast_expression *exprs[3];
503 ast_block *blocks[3];
504 ast_value *asvalue[3];
505 ast_binstore *asbinstore;
506 size_t i, assignop, addop, subop;
507 qcint generated_op = 0;
512 if (!vec_size(sy->ops)) {
513 parseerror(parser, "internal error: missing operator");
517 if (vec_last(sy->ops).paren) {
518 parseerror(parser, "unmatched parenthesis");
522 op = &operators[vec_last(sy->ops).etype - 1];
523 ctx = vec_last(sy->ops).ctx;
525 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
527 if (vec_size(sy->out) < op->operands) {
528 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
529 op->op, (int)op->id);
533 vec_shrinkby(sy->ops, 1);
535 /* op(:?) has no input and no output */
539 vec_shrinkby(sy->out, op->operands);
540 for (i = 0; i < op->operands; ++i) {
541 exprs[i] = sy->out[vec_size(sy->out)+i].out;
542 blocks[i] = sy->out[vec_size(sy->out)+i].block;
543 asvalue[i] = (ast_value*)exprs[i];
546 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
547 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
551 #define NotSameType(T) \
552 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
553 exprs[0]->expression.vtype != T)
554 #define CanConstFold1(A) \
555 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
556 (A)->expression.vtype != TYPE_FUNCTION)
557 #define CanConstFold(A, B) \
558 (CanConstFold1(A) && CanConstFold1(B))
559 #define ConstV(i) (asvalue[(i)]->constval.vvec)
560 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
561 #define ConstS(i) (asvalue[(i)]->constval.vstring)
565 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
569 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
570 if (exprs[1]->expression.vtype != TYPE_FIELD) {
571 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
574 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
576 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
577 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
581 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
587 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
588 !(exprs[0]->expression.vtype == TYPE_FIELD &&
589 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
591 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
592 parseerror(parser, "cannot index value of type %s", ty1);
595 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
596 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
597 parseerror(parser, "index must be of type float, not %s", ty1);
600 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
601 if (rotate_entfield_array_index_nodes(&out))
604 /* This is not broken in fteqcc anymore */
605 if (opts.standard != COMPILER_GMQCC) {
606 /* this error doesn't need to make us bail out */
607 (void)!parsewarning(parser, WARN_EXTENSIONS,
608 "accessing array-field members of an entity without parenthesis\n"
609 " -> this is an extension from -std=gmqcc");
617 if (!ast_block_add_expr(blocks[0], exprs[1]))
620 blocks[0] = ast_block_new(ctx);
621 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
622 !ast_block_add_expr(blocks[0], exprs[1]))
627 if (!ast_block_set_type(blocks[0], exprs[1]))
630 vec_push(sy->out, syblock(ctx, blocks[0]));
637 switch (exprs[0]->expression.vtype) {
639 if (CanConstFold1(exprs[0]))
640 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
642 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
643 (ast_expression*)parser_const_float_0(parser),
647 if (CanConstFold1(exprs[0]))
648 out = (ast_expression*)parser_const_vector_f(parser,
649 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
651 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
652 (ast_expression*)parser_const_vector_0(parser),
656 parseerror(parser, "invalid types used in expression: cannot negate type %s",
657 type_name[exprs[0]->expression.vtype]);
663 switch (exprs[0]->expression.vtype) {
665 if (CanConstFold1(exprs[0]))
666 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
668 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
671 if (CanConstFold1(exprs[0]))
672 out = (ast_expression*)parser_const_float(parser,
673 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
675 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
678 if (CanConstFold1(exprs[0])) {
679 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
680 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
682 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
684 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
685 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
687 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
690 /* we don't constant-fold NOT for these types */
692 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
695 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
698 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
699 type_name[exprs[0]->expression.vtype]);
705 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
706 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
708 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
709 type_name[exprs[0]->expression.vtype],
710 type_name[exprs[1]->expression.vtype]);
713 switch (exprs[0]->expression.vtype) {
715 if (CanConstFold(exprs[0], exprs[1]))
717 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
720 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
723 if (CanConstFold(exprs[0], exprs[1]))
724 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
726 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
729 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
730 type_name[exprs[0]->expression.vtype],
731 type_name[exprs[1]->expression.vtype]);
736 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
737 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
739 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
740 type_name[exprs[1]->expression.vtype],
741 type_name[exprs[0]->expression.vtype]);
744 switch (exprs[0]->expression.vtype) {
746 if (CanConstFold(exprs[0], exprs[1]))
747 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
749 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
752 if (CanConstFold(exprs[0], exprs[1]))
753 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
755 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
758 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
759 type_name[exprs[1]->expression.vtype],
760 type_name[exprs[0]->expression.vtype]);
765 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
766 exprs[0]->expression.vtype != TYPE_VECTOR &&
767 exprs[0]->expression.vtype != TYPE_FLOAT &&
768 exprs[1]->expression.vtype != TYPE_VECTOR &&
769 exprs[1]->expression.vtype != TYPE_FLOAT)
771 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
772 type_name[exprs[1]->expression.vtype],
773 type_name[exprs[0]->expression.vtype]);
776 switch (exprs[0]->expression.vtype) {
778 if (exprs[1]->expression.vtype == TYPE_VECTOR)
780 if (CanConstFold(exprs[0], exprs[1]))
781 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
783 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
787 if (CanConstFold(exprs[0], exprs[1]))
788 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
790 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
794 if (exprs[1]->expression.vtype == TYPE_FLOAT)
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
799 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
803 if (CanConstFold(exprs[0], exprs[1]))
804 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
806 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
810 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
811 type_name[exprs[1]->expression.vtype],
812 type_name[exprs[0]->expression.vtype]);
817 if (NotSameType(TYPE_FLOAT)) {
818 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
819 type_name[exprs[0]->expression.vtype],
820 type_name[exprs[1]->expression.vtype]);
823 if (CanConstFold(exprs[0], exprs[1]))
824 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
826 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
830 parseerror(parser, "qc does not have a modulo operator");
834 if (NotSameType(TYPE_FLOAT)) {
835 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
836 type_name[exprs[0]->expression.vtype],
837 type_name[exprs[1]->expression.vtype]);
840 if (CanConstFold(exprs[0], exprs[1]))
841 out = (ast_expression*)parser_const_float(parser,
842 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
843 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
845 out = (ast_expression*)ast_binary_new(ctx,
846 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
850 parseerror(parser, "TODO: bitxor");
855 case opid3('<','<','='):
856 case opid3('>','>','='):
857 parseerror(parser, "TODO: shifts");
861 generated_op += 1; /* INSTR_OR */
863 generated_op += INSTR_AND;
865 if (NotSameType(TYPE_FLOAT)) {
866 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
867 type_name[exprs[0]->expression.vtype],
868 type_name[exprs[1]->expression.vtype]);
869 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
870 parseerror(parser, "TODO: optional early out");
874 if (CanConstFold(exprs[0], exprs[1]))
876 if (OPTS_FLAG(PERL_LOGIC)) {
877 if (immediate_is_true(ctx, asvalue[0]))
881 out = (ast_expression*)parser_const_float(parser,
882 ( (generated_op == INSTR_OR)
883 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
884 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
889 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
890 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
891 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
892 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
895 if (OPTS_FLAG(CORRECT_LOGIC)) {
896 /* non-floats need to be NOTed */
897 for (i = 0; i < 2; ++i) {
898 if (exprs[i]->expression.vtype != TYPE_FLOAT) {
899 if (type_not_instr[exprs[i]->expression.vtype] == AINSTR_END) {
900 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
901 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
902 parseerror(parser, "invalid types for logical operation with -fcorrect-logic: %s and %s", ty1, ty2);
905 out = (ast_expression*)ast_unary_new(ctx, type_not_instr[exprs[i]->expression.vtype], exprs[i]);
908 exprs[i] = out; out = NULL;
910 if (OPTS_FLAG(PERL_LOGIC))
914 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
919 if (vec_last(parser->pot) != POT_TERNARY2) {
920 parseerror(parser, "mismatched parenthesis/ternary");
923 vec_pop(parser->pot);
924 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
925 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
926 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
927 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
930 if (CanConstFold1(exprs[0]))
931 out = (ConstF(0) ? exprs[1] : exprs[2]);
933 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
937 generated_op += 1; /* INSTR_GT */
939 generated_op += 1; /* INSTR_LT */
940 case opid2('>', '='):
941 generated_op += 1; /* INSTR_GE */
942 case opid2('<', '='):
943 generated_op += INSTR_LE;
944 if (NotSameType(TYPE_FLOAT)) {
945 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
946 type_name[exprs[0]->expression.vtype],
947 type_name[exprs[1]->expression.vtype]);
950 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
952 case opid2('!', '='):
953 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
954 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
955 type_name[exprs[0]->expression.vtype],
956 type_name[exprs[1]->expression.vtype]);
959 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
961 case opid2('=', '='):
962 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
963 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
964 type_name[exprs[0]->expression.vtype],
965 type_name[exprs[1]->expression.vtype]);
968 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
972 if (ast_istype(exprs[0], ast_entfield)) {
973 ast_expression *field = ((ast_entfield*)exprs[0])->field;
974 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
975 exprs[0]->expression.vtype == TYPE_FIELD &&
976 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
978 assignop = type_storep_instr[TYPE_VECTOR];
981 assignop = type_storep_instr[exprs[0]->expression.vtype];
982 if (assignop == AINSTR_END ||
983 !ast_compare_type(field->expression.next, exprs[1]))
985 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
986 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
987 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
988 field->expression.next->expression.vtype == TYPE_FUNCTION &&
989 exprs[1]->expression.vtype == TYPE_FUNCTION)
991 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
992 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
998 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1003 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1004 exprs[0]->expression.vtype == TYPE_FIELD &&
1005 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1007 assignop = type_store_instr[TYPE_VECTOR];
1010 assignop = type_store_instr[exprs[0]->expression.vtype];
1013 if (assignop == AINSTR_END) {
1014 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1015 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1016 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1018 else if (!ast_compare_type(exprs[0], exprs[1])) {
1019 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1020 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1021 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1022 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1023 exprs[1]->expression.vtype == TYPE_FUNCTION)
1025 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1026 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
1032 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1035 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1036 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1038 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1040 case opid3('+','+','P'):
1041 case opid3('-','-','P'):
1043 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1044 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1045 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1048 if (op->id == opid3('+','+','P'))
1049 addop = INSTR_ADD_F;
1051 addop = INSTR_SUB_F;
1052 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1053 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1055 if (ast_istype(exprs[0], ast_entfield)) {
1056 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1058 (ast_expression*)parser_const_float_1(parser));
1060 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1062 (ast_expression*)parser_const_float_1(parser));
1065 case opid3('S','+','+'):
1066 case opid3('S','-','-'):
1068 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1069 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1070 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1073 if (op->id == opid3('S','+','+')) {
1074 addop = INSTR_ADD_F;
1075 subop = INSTR_SUB_F;
1077 addop = INSTR_SUB_F;
1078 subop = INSTR_ADD_F;
1080 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1081 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1083 if (ast_istype(exprs[0], ast_entfield)) {
1084 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1086 (ast_expression*)parser_const_float_1(parser));
1088 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1090 (ast_expression*)parser_const_float_1(parser));
1094 out = (ast_expression*)ast_binary_new(ctx, subop,
1096 (ast_expression*)parser_const_float_1(parser));
1098 case opid2('+','='):
1099 case opid2('-','='):
1100 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1101 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1103 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1104 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1105 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1109 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1110 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1112 if (ast_istype(exprs[0], ast_entfield))
1113 assignop = type_storep_instr[exprs[0]->expression.vtype];
1115 assignop = type_store_instr[exprs[0]->expression.vtype];
1116 switch (exprs[0]->expression.vtype) {
1118 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1119 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1120 exprs[0], exprs[1]);
1123 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1124 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1125 exprs[0], exprs[1]);
1128 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1129 type_name[exprs[0]->expression.vtype],
1130 type_name[exprs[1]->expression.vtype]);
1134 case opid2('*','='):
1135 case opid2('/','='):
1136 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1137 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1138 exprs[0]->expression.vtype == TYPE_VECTOR))
1140 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1141 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1142 parseerror(parser, "invalid types used in expression: %s and %s",
1146 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1147 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1149 if (ast_istype(exprs[0], ast_entfield))
1150 assignop = type_storep_instr[exprs[0]->expression.vtype];
1152 assignop = type_store_instr[exprs[0]->expression.vtype];
1153 switch (exprs[0]->expression.vtype) {
1155 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1156 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1157 exprs[0], exprs[1]);
1160 if (op->id == opid2('*','=')) {
1161 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1162 exprs[0], exprs[1]);
1164 /* there's no DIV_VF */
1165 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1166 (ast_expression*)parser_const_float_1(parser),
1170 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1175 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1176 type_name[exprs[0]->expression.vtype],
1177 type_name[exprs[1]->expression.vtype]);
1181 case opid2('&','='):
1182 case opid2('|','='):
1183 if (NotSameType(TYPE_FLOAT)) {
1184 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1185 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1186 parseerror(parser, "invalid types used in expression: %s and %s",
1190 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1191 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1193 if (ast_istype(exprs[0], ast_entfield))
1194 assignop = type_storep_instr[exprs[0]->expression.vtype];
1196 assignop = type_store_instr[exprs[0]->expression.vtype];
1197 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1198 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1199 exprs[0], exprs[1]);
1201 case opid3('&','~','='):
1202 /* This is like: a &= ~(b);
1203 * But QC has no bitwise-not, so we implement it as
1206 if (NotSameType(TYPE_FLOAT)) {
1207 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1208 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1209 parseerror(parser, "invalid types used in expression: %s and %s",
1213 if (ast_istype(exprs[0], ast_entfield))
1214 assignop = type_storep_instr[exprs[0]->expression.vtype];
1216 assignop = type_store_instr[exprs[0]->expression.vtype];
1217 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1220 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1221 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1223 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1224 asbinstore->keep_dest = true;
1225 out = (ast_expression*)asbinstore;
1231 parseerror(parser, "failed to apply operand %s", op->op);
1235 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1236 vec_push(sy->out, syexp(ctx, out));
1240 static bool parser_close_call(parser_t *parser, shunt *sy)
1242 /* was a function call */
1243 ast_expression *fun;
1249 vec_shrinkby(sy->ops, 1);
1250 fid = sy->ops[vec_size(sy->ops)].off;
1252 /* out[fid] is the function
1253 * everything above is parameters...
1254 * 0 params = nothing
1255 * 1 params = ast_expression
1259 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1260 parseerror(parser, "internal error: function call needs function and parameter list...");
1264 fun = sy->out[fid].out;
1266 if (fun == intrinsic_debug_typestring) {
1268 if (fid+2 != vec_size(sy->out) ||
1269 vec_last(sy->out).block)
1271 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1274 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1275 ast_unref(vec_last(sy->out).out);
1276 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1277 (ast_expression*)parser_const_string(parser, ty, false));
1278 vec_shrinkby(sy->out, 1);
1282 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1284 parseerror(parser, "internal error: failed to create ast_call node");
1288 if (fid+1 == vec_size(sy->out)) {
1291 } else if (fid+2 == vec_size(sy->out)) {
1293 vec_shrinkby(sy->out, 1);
1294 params = sy->out[vec_size(sy->out)].block;
1298 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1300 paramcount = vec_size(params->exprs);
1301 call->params = params->exprs;
1302 params->exprs = NULL;
1305 if (!ast_call_check_types(call))
1308 parseerror(parser, "invalid function call");
1312 /* overwrite fid, the function, with a call */
1313 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1315 if (fun->expression.vtype != TYPE_FUNCTION) {
1316 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1320 if (!fun->expression.next) {
1321 parseerror(parser, "could not determine function return type");
1324 if (vec_size(fun->expression.params) != paramcount &&
1325 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1326 vec_size(fun->expression.params) < paramcount))
1329 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1331 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1332 if (opts.standard == COMPILER_GMQCC)
1335 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1336 " -> `%s` has been declared here: %s:%i",
1337 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1338 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1340 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1341 " -> it has been declared here: %s:%i",
1342 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1343 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1349 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1350 "too %s parameters for call to %s: expected %i, got %i\n"
1351 " -> `%s` has been declared here: %s:%i",
1352 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1353 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1355 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1356 "too %s parameters for function call: expected %i, got %i\n"
1357 " -> it has been declared here: %s:%i",
1358 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1359 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1367 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1369 if (!vec_size(sy->ops)) {
1370 parseerror(parser, "unmatched closing paren");
1373 /* this would for bit a + (x) because there are no operators inside (x)
1374 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1375 parseerror(parser, "empty parenthesis expression");
1379 while (vec_size(sy->ops)) {
1380 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1381 if (!parser_close_call(parser, sy))
1385 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1386 vec_shrinkby(sy->ops, 1);
1387 return !functions_only;
1389 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1392 /* pop off the parenthesis */
1393 vec_shrinkby(sy->ops, 1);
1394 /* then apply the index operator */
1395 if (!parser_sy_apply_operator(parser, sy))
1399 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1402 if (vec_last(parser->pot) != POT_TERNARY1) {
1403 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1406 vec_last(parser->pot) = POT_TERNARY2;
1407 /* pop off the parenthesis */
1408 vec_shrinkby(sy->ops, 1);
1411 if (!parser_sy_apply_operator(parser, sy))
1417 static void parser_reclassify_token(parser_t *parser)
1420 for (i = 0; i < operator_count; ++i) {
1421 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1422 parser->tok = TOKEN_OPERATOR;
1428 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1430 ast_expression *expr = NULL;
1432 bool wantop = false;
1433 bool gotmemberof = false;
1435 /* count the parens because an if starts with one, so the
1436 * end of a condition is an unmatched closing paren
1444 parser->lex->flags.noops = false;
1446 parser_reclassify_token(parser);
1451 gotmemberof = false;
1453 parser->memberof = 0;
1455 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1456 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1458 /* a translatable string */
1462 parseerror(parser, "expected operator or end of statement, got constant");
1466 parser->lex->flags.noops = true;
1467 if (!parser_next(parser) || parser->tok != '(') {
1468 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1471 parser->lex->flags.noops = false;
1472 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1473 parseerror(parser, "expected a constant string in translatable-string extension");
1476 val = parser_const_string(parser, parser_tokval(parser), true);
1480 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1481 DEBUGSHUNTDO(con_out("push string\n"));
1483 if (!parser_next(parser) || parser->tok != ')') {
1484 parseerror(parser, "expected closing paren after translatable string");
1488 else if (parser->tok == TOKEN_IDENT)
1490 ast_expression *var;
1492 parseerror(parser, "expected operator or end of statement");
1497 if (opts.standard == COMPILER_GMQCC)
1499 if (parser->memberof == TYPE_ENTITY) {
1500 /* still get vars first since there could be a fieldpointer */
1501 var = parser_find_var(parser, parser_tokval(parser));
1503 var = parser_find_field(parser, parser_tokval(parser));
1505 else if (parser->memberof == TYPE_VECTOR)
1507 parseerror(parser, "TODO: implement effective vector member access");
1510 else if (parser->memberof) {
1511 parseerror(parser, "namespace for member not found");
1515 var = parser_find_var(parser, parser_tokval(parser));
1517 var = parser_find_var(parser, parser_tokval(parser));
1519 var = parser_find_field(parser, parser_tokval(parser));
1523 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1524 var = (ast_expression*)intrinsic_debug_typestring;
1529 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1535 if (ast_istype(var, ast_value)) {
1536 ((ast_value*)var)->uses++;
1538 else if (ast_istype(var, ast_member)) {
1539 ast_member *mem = (ast_member*)var;
1540 if (ast_istype(mem->owner, ast_value))
1541 ((ast_value*)(mem->owner))->uses++;
1544 vec_push(sy.out, syexp(parser_ctx(parser), var));
1545 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1547 else if (parser->tok == TOKEN_FLOATCONST) {
1550 parseerror(parser, "expected operator or end of statement, got constant");
1554 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1557 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1558 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1560 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1563 parseerror(parser, "expected operator or end of statement, got constant");
1567 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1570 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1571 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1573 else if (parser->tok == TOKEN_STRINGCONST) {
1576 parseerror(parser, "expected operator or end of statement, got constant");
1580 val = parser_const_string(parser, parser_tokval(parser), false);
1583 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1584 DEBUGSHUNTDO(con_out("push string\n"));
1586 else if (parser->tok == TOKEN_VECTORCONST) {
1589 parseerror(parser, "expected operator or end of statement, got constant");
1593 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1596 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1597 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1598 parser_token(parser)->constval.v.x,
1599 parser_token(parser)->constval.v.y,
1600 parser_token(parser)->constval.v.z));
1602 else if (parser->tok == '(') {
1603 parseerror(parser, "internal error: '(' should be classified as operator");
1606 else if (parser->tok == '[') {
1607 parseerror(parser, "internal error: '[' should be classified as operator");
1610 else if (parser->tok == ')') {
1612 DEBUGSHUNTDO(con_out("do[op] )\n"));
1616 /* we do expect an operator next */
1617 /* closing an opening paren */
1618 if (!parser_close_paren(parser, &sy, false))
1620 if (vec_last(parser->pot) != POT_PAREN) {
1621 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1624 vec_pop(parser->pot);
1626 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1630 /* allowed for function calls */
1631 if (!parser_close_paren(parser, &sy, true))
1633 if (vec_last(parser->pot) != POT_PAREN) {
1634 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1637 vec_pop(parser->pot);
1641 else if (parser->tok == ']') {
1643 parseerror(parser, "operand expected");
1647 if (!parser_close_paren(parser, &sy, false))
1649 if (vec_last(parser->pot) != POT_PAREN) {
1650 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1653 vec_pop(parser->pot);
1656 else if (parser->tok == TOKEN_TYPENAME) {
1657 parseerror(parser, "unexpected typename");
1660 else if (parser->tok != TOKEN_OPERATOR) {
1662 parseerror(parser, "expected operator or end of statement");
1669 /* classify the operator */
1670 const oper_info *op;
1671 const oper_info *olast = NULL;
1673 for (o = 0; o < operator_count; ++o) {
1674 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1675 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1676 !strcmp(parser_tokval(parser), operators[o].op))
1681 if (o == operator_count) {
1682 /* no operator found... must be the end of the statement */
1685 /* found an operator */
1688 /* when declaring variables, a comma starts a new variable */
1689 if (op->id == opid1(',') && !parens && stopatcomma) {
1690 /* fixup the token */
1695 /* a colon without a pervious question mark cannot be a ternary */
1696 if (!ternaries && op->id == opid2(':','?')) {
1701 if (op->id == opid1(',')) {
1702 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1703 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1707 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1708 olast = &operators[vec_last(sy.ops).etype-1];
1711 (op->prec < olast->prec) ||
1712 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1714 if (!parser_sy_apply_operator(parser, &sy))
1716 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1717 olast = &operators[vec_last(sy.ops).etype-1];
1722 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1723 /* for gmqcc standard: open up the namespace of the previous type */
1724 ast_expression *prevex = vec_last(sy.out).out;
1726 parseerror(parser, "unexpected member operator");
1729 if (prevex->expression.vtype == TYPE_ENTITY)
1730 parser->memberof = TYPE_ENTITY;
1731 else if (prevex->expression.vtype == TYPE_VECTOR)
1732 parser->memberof = TYPE_VECTOR;
1734 parseerror(parser, "type error: type has no members");
1740 if (op->id == opid1('(')) {
1742 size_t sycount = vec_size(sy.out);
1743 DEBUGSHUNTDO(con_out("push [op] (\n"));
1744 ++parens; vec_push(parser->pot, POT_PAREN);
1745 /* we expected an operator, this is the function-call operator */
1746 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1748 ++parens; vec_push(parser->pot, POT_PAREN);
1749 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1750 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1753 } else if (op->id == opid1('[')) {
1755 parseerror(parser, "unexpected array subscript");
1758 ++parens; vec_push(parser->pot, POT_PAREN);
1759 /* push both the operator and the paren, this makes life easier */
1760 vec_push(sy.ops, syop(parser_ctx(parser), op));
1761 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1763 } else if (op->id == opid2('?',':')) {
1764 vec_push(sy.ops, syop(parser_ctx(parser), op));
1765 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1768 vec_push(parser->pot, POT_TERNARY1);
1769 } else if (op->id == opid2(':','?')) {
1770 if (!vec_size(parser->pot)) {
1771 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1774 if (vec_last(parser->pot) != POT_TERNARY1) {
1775 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1778 if (!parser_close_paren(parser, &sy, false))
1780 vec_push(sy.ops, syop(parser_ctx(parser), op));
1784 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1785 vec_push(sy.ops, syop(parser_ctx(parser), op));
1786 wantop = !!(op->flags & OP_SUFFIX);
1789 if (!parser_next(parser)) {
1792 if (parser->tok == ';' ||
1793 (!parens && parser->tok == ']'))
1799 while (vec_size(sy.ops)) {
1800 if (!parser_sy_apply_operator(parser, &sy))
1804 parser->lex->flags.noops = true;
1805 if (!vec_size(sy.out)) {
1806 parseerror(parser, "empty expression");
1809 expr = sy.out[0].out;
1812 DEBUGSHUNTDO(con_out("shunt done\n"));
1813 if (vec_size(parser->pot)) {
1814 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1817 vec_free(parser->pot);
1821 parser->lex->flags.noops = true;
1827 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1829 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1832 if (!parser_next(parser)) {
1839 static void parser_enterblock(parser_t *parser)
1841 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1842 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1843 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1844 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1845 vec_push(parser->_block_ctx, parser_ctx(parser));
1848 static bool parser_leaveblock(parser_t *parser)
1851 size_t locals, typedefs;
1853 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1854 parseerror(parser, "internal error: parser_leaveblock with no block");
1858 util_htdel(vec_last(parser->variables));
1859 vec_pop(parser->variables);
1860 if (!vec_size(parser->_blocklocals)) {
1861 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1865 locals = vec_last(parser->_blocklocals);
1866 vec_pop(parser->_blocklocals);
1867 while (vec_size(parser->_locals) != locals) {
1868 ast_expression *e = vec_last(parser->_locals);
1869 ast_value *v = (ast_value*)e;
1870 vec_pop(parser->_locals);
1871 if (ast_istype(e, ast_value) && !v->uses) {
1872 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1879 typedefs = vec_last(parser->_blocktypedefs);
1880 while (vec_size(parser->_typedefs) != typedefs) {
1881 ast_delete(vec_last(parser->_typedefs));
1882 vec_pop(parser->_typedefs);
1884 util_htdel(vec_last(parser->typedefs));
1885 vec_pop(parser->typedefs);
1887 vec_pop(parser->_block_ctx);
1891 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1893 vec_push(parser->_locals, e);
1894 util_htset(vec_last(parser->variables), name, (void*)e);
1897 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1901 ast_expression *prev;
1903 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING) {
1905 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1908 parseerror(parser, "internal error: failed to process condition");
1913 if (OPTS_FLAG(CORRECT_LOGIC) &&
1914 !(cond->expression.vtype == TYPE_STRING && OPTS_FLAG(TRUE_EMPTY_STRINGS)))
1916 /* non-floats need to use NOT; except for strings on -ftrue-empty-strings */
1917 unary = (ast_unary*)cond;
1918 if (!ast_istype(cond, ast_unary) || unary->op < INSTR_NOT_F || unary->op > INSTR_NOT_FNC)
1920 /* use the right NOT_ */
1922 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), type_not_instr[cond->expression.vtype], cond);
1925 parseerror(parser, "internal error: failed to process condition");
1932 unary = (ast_unary*)cond;
1933 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1934 /*&& unary->operand->expression.vtype != TYPE_STRING) */
1936 cond = unary->operand;
1937 unary->operand = NULL;
1940 unary = (ast_unary*)cond;
1944 parseerror(parser, "internal error: failed to process condition");
1946 if (ifnot) *_ifnot = !*_ifnot;
1950 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1953 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1956 lex_ctx ctx = parser_ctx(parser);
1958 (void)block; /* not touching */
1960 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1961 if (!parser_next(parser)) {
1962 parseerror(parser, "expected condition or 'not'");
1965 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1967 if (!parser_next(parser)) {
1968 parseerror(parser, "expected condition in parenthesis");
1972 if (parser->tok != '(') {
1973 parseerror(parser, "expected 'if' condition in parenthesis");
1976 /* parse into the expression */
1977 if (!parser_next(parser)) {
1978 parseerror(parser, "expected 'if' condition after opening paren");
1981 /* parse the condition */
1982 cond = parse_expression_leave(parser, false);
1986 if (parser->tok != ')') {
1987 parseerror(parser, "expected closing paren after 'if' condition");
1991 /* parse into the 'then' branch */
1992 if (!parser_next(parser)) {
1993 parseerror(parser, "expected statement for on-true branch of 'if'");
1997 if (!parse_statement_or_block(parser, &ontrue)) {
2001 /* check for an else */
2002 if (!strcmp(parser_tokval(parser), "else")) {
2003 /* parse into the 'else' branch */
2004 if (!parser_next(parser)) {
2005 parseerror(parser, "expected on-false branch after 'else'");
2010 if (!parse_statement_or_block(parser, &onfalse)) {
2017 cond = process_condition(parser, cond, &ifnot);
2019 if (ontrue) ast_delete(ontrue);
2020 if (onfalse) ast_delete(onfalse);
2025 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2027 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2028 *out = (ast_expression*)ifthen;
2032 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2035 ast_expression *cond, *ontrue;
2039 lex_ctx ctx = parser_ctx(parser);
2041 (void)block; /* not touching */
2043 /* skip the 'while' and check for opening paren */
2044 if (!parser_next(parser) || parser->tok != '(') {
2045 parseerror(parser, "expected 'while' condition in parenthesis");
2048 /* parse into the expression */
2049 if (!parser_next(parser)) {
2050 parseerror(parser, "expected 'while' condition after opening paren");
2053 /* parse the condition */
2054 cond = parse_expression_leave(parser, false);
2058 if (parser->tok != ')') {
2059 parseerror(parser, "expected closing paren after 'while' condition");
2063 /* parse into the 'then' branch */
2064 if (!parser_next(parser)) {
2065 parseerror(parser, "expected while-loop body");
2069 if (!parse_statement_or_block(parser, &ontrue)) {
2074 cond = process_condition(parser, cond, &ifnot);
2079 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2080 *out = (ast_expression*)aloop;
2084 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2087 ast_expression *cond, *ontrue;
2091 lex_ctx ctx = parser_ctx(parser);
2093 (void)block; /* not touching */
2095 /* skip the 'do' and get the body */
2096 if (!parser_next(parser)) {
2097 parseerror(parser, "expected loop body");
2100 if (!parse_statement_or_block(parser, &ontrue))
2103 /* expect the "while" */
2104 if (parser->tok != TOKEN_KEYWORD ||
2105 strcmp(parser_tokval(parser), "while"))
2107 parseerror(parser, "expected 'while' and condition");
2112 /* skip the 'while' and check for opening paren */
2113 if (!parser_next(parser) || parser->tok != '(') {
2114 parseerror(parser, "expected 'while' condition in parenthesis");
2118 /* parse into the expression */
2119 if (!parser_next(parser)) {
2120 parseerror(parser, "expected 'while' condition after opening paren");
2124 /* parse the condition */
2125 cond = parse_expression_leave(parser, false);
2129 if (parser->tok != ')') {
2130 parseerror(parser, "expected closing paren after 'while' condition");
2136 if (!parser_next(parser) || parser->tok != ';') {
2137 parseerror(parser, "expected semicolon after condition");
2143 if (!parser_next(parser)) {
2144 parseerror(parser, "parse error");
2150 cond = process_condition(parser, cond, &ifnot);
2155 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2156 *out = (ast_expression*)aloop;
2160 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2163 ast_expression *initexpr, *cond, *increment, *ontrue;
2169 lex_ctx ctx = parser_ctx(parser);
2171 parser_enterblock(parser);
2178 /* skip the 'while' and check for opening paren */
2179 if (!parser_next(parser) || parser->tok != '(') {
2180 parseerror(parser, "expected 'for' expressions in parenthesis");
2183 /* parse into the expression */
2184 if (!parser_next(parser)) {
2185 parseerror(parser, "expected 'for' initializer after opening paren");
2190 if (parser->tok == TOKEN_IDENT)
2191 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2193 if (typevar || parser->tok == TOKEN_TYPENAME) {
2194 if (opts.standard != COMPILER_GMQCC) {
2195 if (parsewarning(parser, WARN_EXTENSIONS,
2196 "current standard does not allow variable declarations in for-loop initializers"))
2199 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false))
2202 else if (parser->tok != ';')
2204 initexpr = parse_expression_leave(parser, false);
2209 /* move on to condition */
2210 if (parser->tok != ';') {
2211 parseerror(parser, "expected semicolon after for-loop initializer");
2214 if (!parser_next(parser)) {
2215 parseerror(parser, "expected for-loop condition");
2219 /* parse the condition */
2220 if (parser->tok != ';') {
2221 cond = parse_expression_leave(parser, false);
2226 /* move on to incrementor */
2227 if (parser->tok != ';') {
2228 parseerror(parser, "expected semicolon after for-loop initializer");
2231 if (!parser_next(parser)) {
2232 parseerror(parser, "expected for-loop condition");
2236 /* parse the incrementor */
2237 if (parser->tok != ')') {
2238 increment = parse_expression_leave(parser, false);
2241 if (!ast_side_effects(increment)) {
2242 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2248 if (parser->tok != ')') {
2249 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2252 /* parse into the 'then' branch */
2253 if (!parser_next(parser)) {
2254 parseerror(parser, "expected for-loop body");
2257 if (!parse_statement_or_block(parser, &ontrue))
2261 cond = process_condition(parser, cond, &ifnot);
2265 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2266 *out = (ast_expression*)aloop;
2268 if (!parser_leaveblock(parser))
2272 if (initexpr) ast_delete(initexpr);
2273 if (cond) ast_delete(cond);
2274 if (increment) ast_delete(increment);
2275 (void)!parser_leaveblock(parser);
2279 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2281 ast_expression *exp = NULL;
2282 ast_return *ret = NULL;
2283 ast_value *expected = parser->function->vtype;
2285 lex_ctx ctx = parser_ctx(parser);
2287 (void)block; /* not touching */
2289 if (!parser_next(parser)) {
2290 parseerror(parser, "expected return expression");
2294 if (parser->tok != ';') {
2295 exp = parse_expression(parser, false);
2299 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2300 parseerror(parser, "return with invalid expression");
2303 ret = ast_return_new(ctx, exp);
2309 if (!parser_next(parser))
2310 parseerror(parser, "parse error");
2311 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2312 if (opts.standard != COMPILER_GMQCC)
2313 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2315 parseerror(parser, "return without value");
2317 ret = ast_return_new(ctx, NULL);
2319 *out = (ast_expression*)ret;
2323 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2325 lex_ctx ctx = parser_ctx(parser);
2327 (void)block; /* not touching */
2329 if (!parser_next(parser) || parser->tok != ';') {
2330 parseerror(parser, "expected semicolon");
2334 if (!parser_next(parser))
2335 parseerror(parser, "parse error");
2337 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2341 /* returns true when it was a variable qualifier, false otherwise!
2342 * on error, cvq is set to CV_WRONG
2344 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn)
2346 bool had_const = false;
2347 bool had_var = false;
2348 bool had_noref = false;
2349 bool had_noreturn = false;
2352 if (!strcmp(parser_tokval(parser), "const"))
2354 else if (!strcmp(parser_tokval(parser), "var"))
2356 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2358 else if (!strcmp(parser_tokval(parser), "noref"))
2360 else if (!strcmp(parser_tokval(parser), "noreturn"))
2361 had_noreturn = true;
2362 else if (!had_const && !had_var && !had_noref && !had_noreturn) {
2367 if (!parser_next(parser))
2377 *noreturn = had_noreturn;
2380 parseerror(parser, "parse error after variable qualifier");
2385 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2387 ast_expression *operand;
2390 ast_switch *switchnode;
2391 ast_switch_case swcase;
2394 bool noref, noreturn;
2396 lex_ctx ctx = parser_ctx(parser);
2398 (void)block; /* not touching */
2401 /* parse over the opening paren */
2402 if (!parser_next(parser) || parser->tok != '(') {
2403 parseerror(parser, "expected switch operand in parenthesis");
2407 /* parse into the expression */
2408 if (!parser_next(parser)) {
2409 parseerror(parser, "expected switch operand");
2412 /* parse the operand */
2413 operand = parse_expression_leave(parser, false);
2417 switchnode = ast_switch_new(ctx, operand);
2420 if (parser->tok != ')') {
2421 ast_delete(switchnode);
2422 parseerror(parser, "expected closing paren after 'switch' operand");
2426 /* parse over the opening paren */
2427 if (!parser_next(parser) || parser->tok != '{') {
2428 ast_delete(switchnode);
2429 parseerror(parser, "expected list of cases");
2433 if (!parser_next(parser)) {
2434 ast_delete(switchnode);
2435 parseerror(parser, "expected 'case' or 'default'");
2439 /* new block; allow some variables to be declared here */
2440 parser_enterblock(parser);
2443 if (parser->tok == TOKEN_IDENT)
2444 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2445 if (typevar || parser->tok == TOKEN_TYPENAME) {
2446 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false)) {
2447 ast_delete(switchnode);
2452 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn))
2454 if (cvq == CV_WRONG) {
2455 ast_delete(switchnode);
2458 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn)) {
2459 ast_delete(switchnode);
2468 while (parser->tok != '}') {
2469 ast_block *caseblock;
2471 if (parser->tok != TOKEN_KEYWORD) {
2472 ast_delete(switchnode);
2473 parseerror(parser, "expected 'case' or 'default'");
2476 if (!strcmp(parser_tokval(parser), "case")) {
2477 if (!parser_next(parser)) {
2478 ast_delete(switchnode);
2479 parseerror(parser, "expected expression for case");
2482 swcase.value = parse_expression_leave(parser, false);
2483 if (!swcase.value) {
2484 ast_delete(switchnode);
2485 parseerror(parser, "expected expression for case");
2488 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2489 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2490 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2496 else if (!strcmp(parser_tokval(parser), "default")) {
2497 swcase.value = NULL;
2498 if (!parser_next(parser)) {
2499 ast_delete(switchnode);
2500 parseerror(parser, "expected colon");
2505 /* Now the colon and body */
2506 if (parser->tok != ':') {
2507 if (swcase.value) ast_unref(swcase.value);
2508 ast_delete(switchnode);
2509 parseerror(parser, "expected colon");
2513 if (!parser_next(parser)) {
2514 if (swcase.value) ast_unref(swcase.value);
2515 ast_delete(switchnode);
2516 parseerror(parser, "expected statements or case");
2519 caseblock = ast_block_new(parser_ctx(parser));
2521 if (swcase.value) ast_unref(swcase.value);
2522 ast_delete(switchnode);
2525 swcase.code = (ast_expression*)caseblock;
2526 vec_push(switchnode->cases, swcase);
2528 ast_expression *expr;
2529 if (parser->tok == '}')
2531 if (parser->tok == TOKEN_KEYWORD) {
2532 if (!strcmp(parser_tokval(parser), "case") ||
2533 !strcmp(parser_tokval(parser), "default"))
2538 if (!parse_statement(parser, caseblock, &expr, true)) {
2539 ast_delete(switchnode);
2544 if (!ast_block_add_expr(caseblock, expr)) {
2545 ast_delete(switchnode);
2551 parser_leaveblock(parser);
2554 if (parser->tok != '}') {
2555 ast_delete(switchnode);
2556 parseerror(parser, "expected closing paren of case list");
2559 if (!parser_next(parser)) {
2560 ast_delete(switchnode);
2561 parseerror(parser, "parse error after switch");
2564 *out = (ast_expression*)switchnode;
2568 static bool parse_goto(parser_t *parser, ast_expression **out)
2573 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2574 parseerror(parser, "expected label name after `goto`");
2578 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2580 for (i = 0; i < vec_size(parser->labels); ++i) {
2581 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2582 ast_goto_set_label(gt, parser->labels[i]);
2586 if (i == vec_size(parser->labels))
2587 vec_push(parser->gotos, gt);
2589 if (!parser_next(parser) || parser->tok != ';') {
2590 parseerror(parser, "semicolon expected after goto label");
2593 if (!parser_next(parser)) {
2594 parseerror(parser, "parse error after goto");
2598 *out = (ast_expression*)gt;
2602 static bool parse_skipwhite(parser_t *parser)
2605 if (!parser_next(parser))
2607 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2608 return parser->tok < TOKEN_ERROR;
2611 static bool parse_eol(parser_t *parser)
2613 if (!parse_skipwhite(parser))
2615 return parser->tok == TOKEN_EOL;
2618 static bool parse_pragma_do(parser_t *parser)
2620 if (!parser_next(parser) ||
2621 parser->tok != TOKEN_IDENT ||
2622 strcmp(parser_tokval(parser), "pragma"))
2624 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2627 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2628 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2632 if (!strcmp(parser_tokval(parser), "noref")) {
2633 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2634 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2637 parser->noref = !!parser_token(parser)->constval.i;
2638 if (!parse_eol(parser)) {
2639 parseerror(parser, "parse error after `noref` pragma");
2645 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2652 static bool parse_pragma(parser_t *parser)
2655 parser->lex->flags.preprocessing = true;
2656 parser->lex->flags.mergelines = true;
2657 rv = parse_pragma_do(parser);
2658 if (parser->tok != TOKEN_EOL) {
2659 parseerror(parser, "junk after pragma");
2662 parser->lex->flags.preprocessing = false;
2663 parser->lex->flags.mergelines = false;
2664 if (!parser_next(parser)) {
2665 parseerror(parser, "parse error after pragma");
2671 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2673 bool noref, noreturn;
2675 ast_value *typevar = NULL;
2679 if (parser->tok == TOKEN_IDENT)
2680 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2682 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2684 /* local variable */
2686 parseerror(parser, "cannot declare a variable from here");
2689 if (opts.standard == COMPILER_QCC) {
2690 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2693 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false))
2697 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn))
2699 if (cvq == CV_WRONG)
2701 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn);
2703 else if (parser->tok == TOKEN_KEYWORD)
2705 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2710 if (!parser_next(parser)) {
2711 parseerror(parser, "parse error after __builtin_debug_printtype");
2715 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2717 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2718 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2719 if (!parser_next(parser)) {
2720 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2726 if (!parse_statement(parser, block, out, allow_cases))
2729 con_out("__builtin_debug_printtype: got no output node\n");
2732 ast_type_to_string(*out, ty, sizeof(ty));
2733 con_out("__builtin_debug_printtype: `%s`\n", ty);
2738 else if (!strcmp(parser_tokval(parser), "return"))
2740 return parse_return(parser, block, out);
2742 else if (!strcmp(parser_tokval(parser), "if"))
2744 return parse_if(parser, block, out);
2746 else if (!strcmp(parser_tokval(parser), "while"))
2748 return parse_while(parser, block, out);
2750 else if (!strcmp(parser_tokval(parser), "do"))
2752 return parse_dowhile(parser, block, out);
2754 else if (!strcmp(parser_tokval(parser), "for"))
2756 if (opts.standard == COMPILER_QCC) {
2757 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2760 return parse_for(parser, block, out);
2762 else if (!strcmp(parser_tokval(parser), "break"))
2764 return parse_break_continue(parser, block, out, false);
2766 else if (!strcmp(parser_tokval(parser), "continue"))
2768 return parse_break_continue(parser, block, out, true);
2770 else if (!strcmp(parser_tokval(parser), "switch"))
2772 return parse_switch(parser, block, out);
2774 else if (!strcmp(parser_tokval(parser), "case") ||
2775 !strcmp(parser_tokval(parser), "default"))
2778 parseerror(parser, "unexpected 'case' label");
2783 else if (!strcmp(parser_tokval(parser), "goto"))
2785 return parse_goto(parser, out);
2787 else if (!strcmp(parser_tokval(parser), "typedef"))
2789 if (!parser_next(parser)) {
2790 parseerror(parser, "expected type definition after 'typedef'");
2793 return parse_typedef(parser);
2795 parseerror(parser, "Unexpected keyword");
2798 else if (parser->tok == '{')
2801 inner = parse_block(parser);
2804 *out = (ast_expression*)inner;
2807 else if (parser->tok == ':')
2811 if (!parser_next(parser)) {
2812 parseerror(parser, "expected label name");
2815 if (parser->tok != TOKEN_IDENT) {
2816 parseerror(parser, "label must be an identifier");
2819 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2822 vec_push(parser->labels, label);
2823 *out = (ast_expression*)label;
2824 if (!parser_next(parser)) {
2825 parseerror(parser, "parse error after label");
2828 for (i = 0; i < vec_size(parser->gotos); ++i) {
2829 if (!strcmp(parser->gotos[i]->name, label->name)) {
2830 ast_goto_set_label(parser->gotos[i], label);
2831 vec_remove(parser->gotos, i, 1);
2837 else if (parser->tok == ';')
2839 if (!parser_next(parser)) {
2840 parseerror(parser, "parse error after empty statement");
2847 ast_expression *exp = parse_expression(parser, false);
2851 if (!ast_side_effects(exp)) {
2852 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2859 static bool parse_block_into(parser_t *parser, ast_block *block)
2863 parser_enterblock(parser);
2865 if (!parser_next(parser)) { /* skip the '{' */
2866 parseerror(parser, "expected function body");
2870 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2872 ast_expression *expr = NULL;
2873 if (parser->tok == '}')
2876 if (!parse_statement(parser, block, &expr, false)) {
2877 /* parseerror(parser, "parse error"); */
2883 if (!ast_block_add_expr(block, expr)) {
2890 if (parser->tok != '}') {
2893 (void)parser_next(parser);
2897 if (!parser_leaveblock(parser))
2899 return retval && !!block;
2902 static ast_block* parse_block(parser_t *parser)
2905 block = ast_block_new(parser_ctx(parser));
2908 if (!parse_block_into(parser, block)) {
2909 ast_block_delete(block);
2915 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2917 if (parser->tok == '{') {
2918 *out = (ast_expression*)parse_block(parser);
2921 return parse_statement(parser, NULL, out, false);
2924 static bool create_vector_members(ast_value *var, ast_member **me)
2927 size_t len = strlen(var->name);
2929 for (i = 0; i < 3; ++i) {
2930 char *name = mem_a(len+3);
2931 memcpy(name, var->name, len);
2933 name[len+1] = 'x'+i;
2935 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2944 do { ast_member_delete(me[--i]); } while(i);
2948 static bool parse_function_body(parser_t *parser, ast_value *var)
2950 ast_block *block = NULL;
2955 ast_expression *framenum = NULL;
2956 ast_expression *nextthink = NULL;
2957 /* None of the following have to be deleted */
2958 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2959 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2960 bool has_frame_think;
2964 has_frame_think = false;
2965 old = parser->function;
2967 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2968 parseerror(parser, "gotos/labels leaking");
2972 if (var->expression.flags & AST_FLAG_VARIADIC) {
2973 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2974 "variadic function with implementation will not be able to access additional parameters"))
2980 if (parser->tok == '[') {
2981 /* got a frame definition: [ framenum, nextthink ]
2982 * this translates to:
2983 * self.frame = framenum;
2984 * self.nextthink = time + 0.1;
2985 * self.think = nextthink;
2989 fld_think = parser_find_field(parser, "think");
2990 fld_nextthink = parser_find_field(parser, "nextthink");
2991 fld_frame = parser_find_field(parser, "frame");
2992 if (!fld_think || !fld_nextthink || !fld_frame) {
2993 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2994 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2997 gbl_time = parser_find_global(parser, "time");
2998 gbl_self = parser_find_global(parser, "self");
2999 if (!gbl_time || !gbl_self) {
3000 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3001 parseerror(parser, "please declare the following globals: `time`, `self`");
3005 if (!parser_next(parser))
3008 framenum = parse_expression_leave(parser, true);
3010 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3013 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3014 ast_unref(framenum);
3015 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3019 if (parser->tok != ',') {
3020 ast_unref(framenum);
3021 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3022 parseerror(parser, "Got a %i\n", parser->tok);
3026 if (!parser_next(parser)) {
3027 ast_unref(framenum);
3031 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3033 /* qc allows the use of not-yet-declared functions here
3034 * - this automatically creates a prototype */
3035 ast_value *thinkfunc;
3036 ast_expression *functype = fld_think->expression.next;
3038 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3039 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3040 ast_unref(framenum);
3041 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3045 if (!parser_next(parser)) {
3046 ast_unref(framenum);
3047 ast_delete(thinkfunc);
3051 vec_push(parser->globals, (ast_expression*)thinkfunc);
3052 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3053 nextthink = (ast_expression*)thinkfunc;
3056 nextthink = parse_expression_leave(parser, true);
3058 ast_unref(framenum);
3059 parseerror(parser, "expected a think-function in [frame,think] notation");
3064 if (!ast_istype(nextthink, ast_value)) {
3065 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3069 if (retval && parser->tok != ']') {
3070 parseerror(parser, "expected closing `]` for [frame,think] notation");
3074 if (retval && !parser_next(parser)) {
3078 if (retval && parser->tok != '{') {
3079 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3084 ast_unref(nextthink);
3085 ast_unref(framenum);
3089 has_frame_think = true;
3092 block = ast_block_new(parser_ctx(parser));
3094 parseerror(parser, "failed to allocate block");
3095 if (has_frame_think) {
3096 ast_unref(nextthink);
3097 ast_unref(framenum);
3102 if (has_frame_think) {
3104 ast_expression *self_frame;
3105 ast_expression *self_nextthink;
3106 ast_expression *self_think;
3107 ast_expression *time_plus_1;
3108 ast_store *store_frame;
3109 ast_store *store_nextthink;
3110 ast_store *store_think;
3112 ctx = parser_ctx(parser);
3113 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3114 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3115 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3117 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3118 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3120 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3121 if (self_frame) ast_delete(self_frame);
3122 if (self_nextthink) ast_delete(self_nextthink);
3123 if (self_think) ast_delete(self_think);
3124 if (time_plus_1) ast_delete(time_plus_1);
3130 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3131 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3132 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3135 ast_delete(self_frame);
3138 if (!store_nextthink) {
3139 ast_delete(self_nextthink);
3143 ast_delete(self_think);
3147 if (store_frame) ast_delete(store_frame);
3148 if (store_nextthink) ast_delete(store_nextthink);
3149 if (store_think) ast_delete(store_think);
3152 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3153 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3154 !ast_block_add_expr(block, (ast_expression*)store_think))
3161 parseerror(parser, "failed to generate code for [frame,think]");
3162 ast_unref(nextthink);
3163 ast_unref(framenum);
3169 parser_enterblock(parser);
3171 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3173 ast_value *param = var->expression.params[parami];
3176 if (param->expression.vtype != TYPE_VECTOR &&
3177 (param->expression.vtype != TYPE_FIELD ||
3178 param->expression.next->expression.vtype != TYPE_VECTOR))
3183 if (!create_vector_members(param, me)) {
3184 ast_block_delete(block);
3188 for (e = 0; e < 3; ++e) {
3189 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3190 ast_block_collect(block, (ast_expression*)me[e]);
3194 func = ast_function_new(ast_ctx(var), var->name, var);
3196 parseerror(parser, "failed to allocate function for `%s`", var->name);
3197 ast_block_delete(block);
3200 vec_push(parser->functions, func);
3202 parser->function = func;
3203 if (!parse_block_into(parser, block)) {
3204 ast_block_delete(block);
3208 vec_push(func->blocks, block);
3210 parser->function = old;
3211 if (!parser_leaveblock(parser))
3213 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3214 parseerror(parser, "internal error: local scopes left");
3218 if (parser->tok == ';')
3219 return parser_next(parser);
3220 else if (opts.standard == COMPILER_QCC)
3221 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3225 vec_pop(parser->functions);
3226 ast_function_delete(func);
3227 var->constval.vfunc = NULL;
3230 (void)!parser_leaveblock(parser);
3231 parser->function = old;
3235 static ast_expression *array_accessor_split(
3240 ast_expression *left,
3241 ast_expression *right
3247 lex_ctx ctx = ast_ctx(array);
3249 if (!left || !right) {
3250 if (left) ast_delete(left);
3251 if (right) ast_delete(right);
3255 cmp = ast_binary_new(ctx, INSTR_LT,
3256 (ast_expression*)index,
3257 (ast_expression*)parser_const_float(parser, middle));
3261 parseerror(parser, "internal error: failed to create comparison for array setter");
3265 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3267 ast_delete(cmp); /* will delete left and right */
3268 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3272 return (ast_expression*)ifthen;
3275 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3277 lex_ctx ctx = ast_ctx(array);
3279 if (from+1 == afterend) {
3280 /* set this value */
3283 ast_array_index *subscript;
3285 int assignop = type_store_instr[value->expression.vtype];
3287 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3288 assignop = INSTR_STORE_V;
3290 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3294 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3296 ast_delete(subscript);
3300 block = ast_block_new(ctx);
3306 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3311 ret = ast_return_new(ctx, NULL);
3317 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3322 return (ast_expression*)block;
3324 ast_expression *left, *right;
3325 size_t diff = afterend - from;
3326 size_t middle = from + diff/2;
3327 left = array_setter_node(parser, array, index, value, from, middle);
3328 right = array_setter_node(parser, array, index, value, middle, afterend);
3329 return array_accessor_split(parser, array, index, middle, left, right);
3333 static ast_expression *array_field_setter_node(
3342 lex_ctx ctx = ast_ctx(array);
3344 if (from+1 == afterend) {
3345 /* set this value */
3348 ast_entfield *entfield;
3349 ast_array_index *subscript;
3351 int assignop = type_storep_instr[value->expression.vtype];
3353 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3354 assignop = INSTR_STOREP_V;
3356 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3360 entfield = ast_entfield_new_force(ctx,
3361 (ast_expression*)entity,
3362 (ast_expression*)subscript,
3363 (ast_expression*)subscript);
3365 ast_delete(subscript);
3369 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3371 ast_delete(entfield);
3375 block = ast_block_new(ctx);
3381 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3386 ret = ast_return_new(ctx, NULL);
3392 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3397 return (ast_expression*)block;
3399 ast_expression *left, *right;
3400 size_t diff = afterend - from;
3401 size_t middle = from + diff/2;
3402 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3403 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3404 return array_accessor_split(parser, array, index, middle, left, right);
3408 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3410 lex_ctx ctx = ast_ctx(array);
3412 if (from+1 == afterend) {
3414 ast_array_index *subscript;
3416 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3420 ret = ast_return_new(ctx, (ast_expression*)subscript);
3422 ast_delete(subscript);
3426 return (ast_expression*)ret;
3428 ast_expression *left, *right;
3429 size_t diff = afterend - from;
3430 size_t middle = from + diff/2;
3431 left = array_getter_node(parser, array, index, from, middle);
3432 right = array_getter_node(parser, array, index, middle, afterend);
3433 return array_accessor_split(parser, array, index, middle, left, right);
3437 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3439 ast_function *func = NULL;
3440 ast_value *fval = NULL;
3441 ast_block *body = NULL;
3443 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3445 parseerror(parser, "failed to create accessor function value");
3449 func = ast_function_new(ast_ctx(array), funcname, fval);
3452 parseerror(parser, "failed to create accessor function node");
3456 body = ast_block_new(ast_ctx(array));
3458 parseerror(parser, "failed to create block for array accessor");
3464 vec_push(func->blocks, body);
3467 vec_push(parser->accessors, fval);
3472 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3474 ast_expression *root = NULL;
3475 ast_value *index = NULL;
3476 ast_value *value = NULL;
3480 if (!ast_istype(array->expression.next, ast_value)) {
3481 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3485 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3487 func = fval->constval.vfunc;
3488 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3490 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3491 value = ast_value_copy((ast_value*)array->expression.next);
3493 if (!index || !value) {
3494 parseerror(parser, "failed to create locals for array accessor");
3497 (void)!ast_value_set_name(value, "value"); /* not important */
3498 vec_push(fval->expression.params, index);
3499 vec_push(fval->expression.params, value);
3501 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3503 parseerror(parser, "failed to build accessor search tree");
3507 array->setter = fval;
3508 return ast_block_add_expr(func->blocks[0], root);
3510 if (index) ast_delete(index);
3511 if (value) ast_delete(value);
3512 if (root) ast_delete(root);
3518 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3520 ast_expression *root = NULL;
3521 ast_value *entity = NULL;
3522 ast_value *index = NULL;
3523 ast_value *value = NULL;
3527 if (!ast_istype(array->expression.next, ast_value)) {
3528 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3532 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3534 func = fval->constval.vfunc;
3535 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3537 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3538 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3539 value = ast_value_copy((ast_value*)array->expression.next);
3540 if (!entity || !index || !value) {
3541 parseerror(parser, "failed to create locals for array accessor");
3544 (void)!ast_value_set_name(value, "value"); /* not important */
3545 vec_push(fval->expression.params, entity);
3546 vec_push(fval->expression.params, index);
3547 vec_push(fval->expression.params, value);
3549 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3551 parseerror(parser, "failed to build accessor search tree");
3555 array->setter = fval;
3556 return ast_block_add_expr(func->blocks[0], root);
3558 if (entity) ast_delete(entity);
3559 if (index) ast_delete(index);
3560 if (value) ast_delete(value);
3561 if (root) ast_delete(root);
3567 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3569 ast_expression *root = NULL;
3570 ast_value *index = NULL;
3574 /* NOTE: checking array->expression.next rather than elemtype since
3575 * for fields elemtype is a temporary fieldtype.
3577 if (!ast_istype(array->expression.next, ast_value)) {
3578 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3582 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3584 func = fval->constval.vfunc;
3585 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3587 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3590 parseerror(parser, "failed to create locals for array accessor");
3593 vec_push(fval->expression.params, index);
3595 root = array_getter_node(parser, array, index, 0, array->expression.count);
3597 parseerror(parser, "failed to build accessor search tree");
3601 array->getter = fval;
3602 return ast_block_add_expr(func->blocks[0], root);
3604 if (index) ast_delete(index);
3605 if (root) ast_delete(root);
3611 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3612 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3620 bool variadic = false;
3622 ctx = parser_ctx(parser);
3624 /* for the sake of less code we parse-in in this function */
3625 if (!parser_next(parser)) {
3626 parseerror(parser, "expected parameter list");
3632 /* parse variables until we hit a closing paren */
3633 while (parser->tok != ')') {
3635 /* there must be commas between them */
3636 if (parser->tok != ',') {
3637 parseerror(parser, "expected comma or end of parameter list");
3640 if (!parser_next(parser)) {
3641 parseerror(parser, "expected parameter");
3647 if (parser->tok == TOKEN_DOTS) {
3648 /* '...' indicates a varargs function */
3650 if (!parser_next(parser)) {
3651 parseerror(parser, "expected parameter");
3654 if (parser->tok != ')') {
3655 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3661 /* for anything else just parse a typename */
3662 param = parse_typename(parser, NULL, NULL);
3665 vec_push(params, param);
3666 if (param->expression.vtype >= TYPE_VARIANT) {
3667 char typename[1024];
3668 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3669 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3675 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3679 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3680 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3683 if (!parser_next(parser)) {
3684 parseerror(parser, "parse error after typename");
3688 /* now turn 'var' into a function type */
3689 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3690 fval->expression.next = (ast_expression*)var;
3692 fval->expression.flags |= AST_FLAG_VARIADIC;
3695 var->expression.params = params;
3702 for (i = 0; i < vec_size(params); ++i)
3703 ast_delete(params[i]);
3708 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3710 ast_expression *cexp;
3711 ast_value *cval, *tmp;
3714 ctx = parser_ctx(parser);
3716 if (!parser_next(parser)) {
3718 parseerror(parser, "expected array-size");
3722 cexp = parse_expression_leave(parser, true);
3724 if (!cexp || !ast_istype(cexp, ast_value)) {
3728 parseerror(parser, "expected array-size as constant positive integer");
3731 cval = (ast_value*)cexp;
3733 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3734 tmp->expression.next = (ast_expression*)var;
3737 if (cval->expression.vtype == TYPE_INTEGER)
3738 tmp->expression.count = cval->constval.vint;
3739 else if (cval->expression.vtype == TYPE_FLOAT)
3740 tmp->expression.count = cval->constval.vfloat;
3744 parseerror(parser, "array-size must be a positive integer constant");
3749 if (parser->tok != ']') {
3751 parseerror(parser, "expected ']' after array-size");
3754 if (!parser_next(parser)) {
3756 parseerror(parser, "error after parsing array size");
3762 /* Parse a complete typename.
3763 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3764 * but when parsing variables separated by comma
3765 * 'storebase' should point to where the base-type should be kept.
3766 * The base type makes up every bit of type information which comes *before* the
3769 * The following will be parsed in its entirety:
3771 * The 'basetype' in this case is 'void()'
3772 * and if there's a comma after it, say:
3774 * then the type-information 'void()' can be stored in 'storebase'
3776 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3778 ast_value *var, *tmp;
3781 const char *name = NULL;
3782 bool isfield = false;
3783 bool wasarray = false;
3784 size_t morefields = 0;
3786 ctx = parser_ctx(parser);
3788 /* types may start with a dot */
3789 if (parser->tok == '.') {
3791 /* if we parsed a dot we need a typename now */
3792 if (!parser_next(parser)) {
3793 parseerror(parser, "expected typename for field definition");
3797 /* Further dots are handled seperately because they won't be part of the
3800 while (parser->tok == '.') {
3802 if (!parser_next(parser)) {
3803 parseerror(parser, "expected typename for field definition");
3808 if (parser->tok == TOKEN_IDENT)
3809 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3810 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3811 parseerror(parser, "expected typename");
3815 /* generate the basic type value */
3816 if (cached_typedef) {
3817 var = ast_value_copy(cached_typedef);
3818 ast_value_set_name(var, "<type(from_def)>");
3820 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3822 for (; morefields; --morefields) {
3823 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3824 tmp->expression.next = (ast_expression*)var;
3828 /* do not yet turn into a field - remember:
3829 * .void() foo; is a field too
3830 * .void()() foo; is a function
3834 if (!parser_next(parser)) {
3836 parseerror(parser, "parse error after typename");
3840 /* an opening paren now starts the parameter-list of a function
3841 * this is where original-QC has parameter lists.
3842 * We allow a single parameter list here.
3843 * Much like fteqcc we don't allow `float()() x`
3845 if (parser->tok == '(') {
3846 var = parse_parameter_list(parser, var);
3851 /* store the base if requested */
3853 *storebase = ast_value_copy(var);
3855 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3856 tmp->expression.next = (ast_expression*)*storebase;
3861 /* there may be a name now */
3862 if (parser->tok == TOKEN_IDENT) {
3863 name = util_strdup(parser_tokval(parser));
3865 if (!parser_next(parser)) {
3867 parseerror(parser, "error after variable or field declaration");
3872 /* now this may be an array */
3873 if (parser->tok == '[') {
3875 var = parse_arraysize(parser, var);
3880 /* This is the point where we can turn it into a field */
3882 /* turn it into a field if desired */
3883 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3884 tmp->expression.next = (ast_expression*)var;
3888 /* now there may be function parens again */
3889 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3890 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3891 if (parser->tok == '(' && wasarray)
3892 parseerror(parser, "arrays as part of a return type is not supported");
3893 while (parser->tok == '(') {
3894 var = parse_parameter_list(parser, var);
3903 /* finally name it */
3905 if (!ast_value_set_name(var, name)) {
3907 parseerror(parser, "internal error: failed to set name");
3910 /* free the name, ast_value_set_name duplicates */
3917 static bool parse_typedef(parser_t *parser)
3919 ast_value *typevar, *oldtype;
3920 ast_expression *old;
3922 typevar = parse_typename(parser, NULL, NULL);
3927 if ( (old = parser_find_var(parser, typevar->name)) ) {
3928 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3929 " -> `%s` has been declared here: %s:%i",
3930 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3931 ast_delete(typevar);
3935 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3936 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3937 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3938 ast_delete(typevar);
3942 vec_push(parser->_typedefs, typevar);
3943 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3945 if (parser->tok != ';') {
3946 parseerror(parser, "expected semicolon after typedef");
3949 if (!parser_next(parser)) {
3950 parseerror(parser, "parse error after typedef");
3957 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn)
3961 ast_expression *old;
3965 ast_value *basetype = NULL;
3967 bool isparam = false;
3968 bool isvector = false;
3969 bool cleanvar = true;
3970 bool wasarray = false;
3974 /* get the first complete variable */
3975 var = parse_typename(parser, &basetype, cached_typedef);
3978 ast_delete(basetype);
3986 /* Part 0: finish the type */
3987 if (parser->tok == '(') {
3988 if (opts.standard == COMPILER_QCC)
3989 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3990 var = parse_parameter_list(parser, var);
3996 /* we only allow 1-dimensional arrays */
3997 if (parser->tok == '[') {
3999 var = parse_arraysize(parser, var);
4005 if (parser->tok == '(' && wasarray) {
4006 parseerror(parser, "arrays as part of a return type is not supported");
4007 /* we'll still parse the type completely for now */
4009 /* for functions returning functions */
4010 while (parser->tok == '(') {
4011 if (opts.standard == COMPILER_QCC)
4012 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4013 var = parse_parameter_list(parser, var);
4020 var->cvq = qualifier;
4021 /* in a noref section we simply bump the usecount */
4022 if (noref || parser->noref)
4025 var->expression.flags |= AST_FLAG_NORETURN;
4028 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4029 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4030 * is then filled with the previous definition and the parameter-names replaced.
4033 /* Deal with end_sys_ vars */
4035 if (!strcmp(var->name, "end_sys_globals")) {
4037 parser->crc_globals = vec_size(parser->globals);
4040 else if (!strcmp(var->name, "end_sys_fields")) {
4042 parser->crc_fields = vec_size(parser->fields);
4045 if (was_end && var->expression.vtype == TYPE_FIELD) {
4046 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4047 "global '%s' hint should not be a field",
4048 parser_tokval(parser)))
4055 if (!nofields && var->expression.vtype == TYPE_FIELD)
4057 /* deal with field declarations */
4058 old = parser_find_field(parser, var->name);
4060 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4061 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4070 parseerror(parser, "field `%s` already declared here: %s:%i",
4071 var->name, ast_ctx(old).file, ast_ctx(old).line);
4076 if (opts.standard == COMPILER_QCC &&
4077 (old = parser_find_global(parser, var->name)))
4079 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4080 parseerror(parser, "field `%s` already declared here: %s:%i",
4081 var->name, ast_ctx(old).file, ast_ctx(old).line);
4088 /* deal with other globals */
4089 old = parser_find_global(parser, var->name);
4090 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4092 /* This is a function which had a prototype */
4093 if (!ast_istype(old, ast_value)) {
4094 parseerror(parser, "internal error: prototype is not an ast_value");
4098 proto = (ast_value*)old;
4099 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4100 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4102 ast_ctx(proto).file, ast_ctx(proto).line);
4106 /* we need the new parameter-names */
4107 for (i = 0; i < vec_size(proto->expression.params); ++i)
4108 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4116 if (opts.standard == COMPILER_GMQCC) {
4117 parseerror(parser, "global `%s` already declared here: %s:%i",
4118 var->name, ast_ctx(old).file, ast_ctx(old).line);
4122 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4123 "global `%s` already declared here: %s:%i",
4124 var->name, ast_ctx(old).file, ast_ctx(old).line))
4129 proto = (ast_value*)old;
4130 if (!ast_istype(old, ast_value)) {
4131 parseerror(parser, "internal error: not an ast_value");
4140 if (opts.standard == COMPILER_QCC &&
4141 (old = parser_find_field(parser, var->name)))
4143 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4144 parseerror(parser, "global `%s` already declared here: %s:%i",
4145 var->name, ast_ctx(old).file, ast_ctx(old).line);
4152 else /* it's not a global */
4154 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4155 if (old && !isparam) {
4156 parseerror(parser, "local `%s` already declared here: %s:%i",
4157 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4161 old = parser_find_local(parser, var->name, 0, &isparam);
4162 if (old && isparam) {
4163 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4164 "local `%s` is shadowing a parameter", var->name))
4166 parseerror(parser, "local `%s` already declared here: %s:%i",
4167 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4171 if (opts.standard != COMPILER_GMQCC) {
4180 * Create the global/local, and deal with vector types.
4183 if (var->expression.vtype == TYPE_VECTOR)
4185 else if (var->expression.vtype == TYPE_FIELD &&
4186 var->expression.next->expression.vtype == TYPE_VECTOR)
4190 if (!create_vector_members(var, me)) {
4197 /* deal with global variables, fields, functions */
4198 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4199 var->isfield = true;
4200 vec_push(parser->fields, (ast_expression*)var);
4201 util_htset(parser->htfields, var->name, var);
4203 for (i = 0; i < 3; ++i) {
4204 vec_push(parser->fields, (ast_expression*)me[i]);
4205 util_htset(parser->htfields, me[i]->name, me[i]);
4210 vec_push(parser->globals, (ast_expression*)var);
4211 util_htset(parser->htglobals, var->name, var);
4213 for (i = 0; i < 3; ++i) {
4214 vec_push(parser->globals, (ast_expression*)me[i]);
4215 util_htset(parser->htglobals, me[i]->name, me[i]);
4220 vec_push(localblock->locals, var);
4221 parser_addlocal(parser, var->name, (ast_expression*)var);
4223 for (i = 0; i < 3; ++i) {
4224 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4225 ast_block_collect(localblock, (ast_expression*)me[i]);
4231 me[0] = me[1] = me[2] = NULL;
4236 if (var->expression.vtype == TYPE_ARRAY) {
4238 snprintf(name, sizeof(name), "%s##SET", var->name);
4239 if (!parser_create_array_setter(parser, var, name))
4241 snprintf(name, sizeof(name), "%s##GET", var->name);
4242 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4245 else if (!localblock && !nofields &&
4246 var->expression.vtype == TYPE_FIELD &&
4247 var->expression.next->expression.vtype == TYPE_ARRAY)
4250 ast_expression *telem;
4252 ast_value *array = (ast_value*)var->expression.next;
4254 if (!ast_istype(var->expression.next, ast_value)) {
4255 parseerror(parser, "internal error: field element type must be an ast_value");
4259 snprintf(name, sizeof(name), "%s##SETF", var->name);
4260 if (!parser_create_array_field_setter(parser, array, name))
4263 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4264 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4265 tfield->expression.next = telem;
4266 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4267 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4275 if (parser->tok == ';') {
4276 ast_delete(basetype);
4277 if (!parser_next(parser)) {
4278 parseerror(parser, "error after variable declaration");
4284 if (parser->tok == ',')
4288 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4291 parseerror(parser, "missing comma or semicolon while parsing variables");
4295 if (localblock && opts.standard == COMPILER_QCC) {
4296 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4297 "initializing expression turns variable `%s` into a constant in this standard",
4304 if (parser->tok != '{') {
4305 if (parser->tok != '=') {
4306 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4310 if (!parser_next(parser)) {
4311 parseerror(parser, "error parsing initializer");
4315 else if (opts.standard == COMPILER_QCC) {
4316 parseerror(parser, "expected '=' before function body in this standard");
4319 if (parser->tok == '#') {
4320 ast_function *func = NULL;
4323 parseerror(parser, "cannot declare builtins within functions");
4326 if (var->expression.vtype != TYPE_FUNCTION) {
4327 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4330 if (!parser_next(parser)) {
4331 parseerror(parser, "expected builtin number");
4334 if (parser->tok != TOKEN_INTCONST) {
4335 parseerror(parser, "builtin number must be an integer constant");
4338 if (parser_token(parser)->constval.i < 0) {
4339 parseerror(parser, "builtin number must be an integer greater than zero");
4343 if (var->hasvalue) {
4344 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4345 "builtin `%s` has already been defined\n"
4346 " -> previous declaration here: %s:%i",
4347 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4351 func = ast_function_new(ast_ctx(var), var->name, var);
4353 parseerror(parser, "failed to allocate function for `%s`", var->name);
4356 vec_push(parser->functions, func);
4358 func->builtin = -parser_token(parser)->constval.i-1;
4361 if (!parser_next(parser)) {
4362 parseerror(parser, "expected comma or semicolon");
4364 ast_function_delete(func);
4365 var->constval.vfunc = NULL;
4369 else if (parser->tok == '{' || parser->tok == '[')
4373 parseerror(parser, "cannot declare functions within functions");
4378 ast_ctx(proto) = parser_ctx(parser);
4380 if (!parse_function_body(parser, var))
4382 ast_delete(basetype);
4383 for (i = 0; i < vec_size(parser->gotos); ++i)
4384 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4385 vec_free(parser->gotos);
4386 vec_free(parser->labels);
4389 ast_expression *cexp;
4392 cexp = parse_expression_leave(parser, true);
4397 cval = (ast_value*)cexp;
4398 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4399 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4402 if (opts.standard != COMPILER_GMQCC &&
4403 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4404 qualifier != CV_VAR)
4406 var->cvq = CV_CONST;
4408 var->hasvalue = true;
4409 if (cval->expression.vtype == TYPE_STRING)
4410 var->constval.vstring = parser_strdup(cval->constval.vstring);
4411 else if (cval->expression.vtype == TYPE_FIELD)
4412 var->constval.vfield = cval;
4414 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4419 shunt sy = { NULL, NULL };
4422 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4423 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4424 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4425 if (!parser_sy_apply_operator(parser, &sy))
4428 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4429 parseerror(parser, "internal error: leaked operands");
4430 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4440 if (parser->tok == ',') {
4441 if (!parser_next(parser)) {
4442 parseerror(parser, "expected another variable");
4446 if (parser->tok != TOKEN_IDENT) {
4447 parseerror(parser, "expected another variable");
4450 var = ast_value_copy(basetype);
4452 ast_value_set_name(var, parser_tokval(parser));
4453 if (!parser_next(parser)) {
4454 parseerror(parser, "error parsing variable declaration");
4460 if (parser->tok != ';') {
4461 parseerror(parser, "missing semicolon after variables");
4465 if (!parser_next(parser)) {
4466 parseerror(parser, "parse error after variable declaration");
4470 ast_delete(basetype);
4474 if (cleanvar && var)
4476 ast_delete(basetype);
4480 ast_delete(basetype);
4481 if (cleanvar && var)
4483 if (me[0]) ast_member_delete(me[0]);
4484 if (me[1]) ast_member_delete(me[1]);
4485 if (me[2]) ast_member_delete(me[2]);
4489 static bool parser_global_statement(parser_t *parser)
4493 bool noreturn = false;
4494 ast_value *istype = NULL;
4496 if (parser->tok == TOKEN_IDENT)
4497 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4499 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4501 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false);
4503 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn))
4505 if (cvq == CV_WRONG)
4507 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn);
4509 else if (parser->tok == TOKEN_KEYWORD)
4511 if (!strcmp(parser_tokval(parser), "typedef")) {
4512 if (!parser_next(parser)) {
4513 parseerror(parser, "expected type definition after 'typedef'");
4516 return parse_typedef(parser);
4518 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4521 else if (parser->tok == '#')
4523 return parse_pragma(parser);
4525 else if (parser->tok == '$')
4527 if (!parser_next(parser)) {
4528 parseerror(parser, "parse error");
4534 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4540 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4542 return util_crc16(old, str, strlen(str));
4545 static void progdefs_crc_file(const char *str)
4547 /* write to progdefs.h here */
4551 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4553 old = progdefs_crc_sum(old, str);
4554 progdefs_crc_file(str);
4558 static void generate_checksum(parser_t *parser)
4560 uint16_t crc = 0xFFFF;
4564 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4565 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4567 progdefs_crc_file("\tint\tpad;\n");
4568 progdefs_crc_file("\tint\tofs_return[3];\n");
4569 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4570 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4571 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4572 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4573 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4574 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4575 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4576 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4578 for (i = 0; i < parser->crc_globals; ++i) {
4579 if (!ast_istype(parser->globals[i], ast_value))
4581 value = (ast_value*)(parser->globals[i]);
4582 switch (value->expression.vtype) {
4583 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4584 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4585 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4586 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4588 crc = progdefs_crc_both(crc, "\tint\t");
4591 crc = progdefs_crc_both(crc, value->name);
4592 crc = progdefs_crc_both(crc, ";\n");
4594 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4595 for (i = 0; i < parser->crc_fields; ++i) {
4596 if (!ast_istype(parser->fields[i], ast_value))
4598 value = (ast_value*)(parser->fields[i]);
4599 switch (value->expression.next->expression.vtype) {
4600 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4601 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4602 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4603 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4605 crc = progdefs_crc_both(crc, "\tint\t");
4608 crc = progdefs_crc_both(crc, value->name);
4609 crc = progdefs_crc_both(crc, ";\n");
4611 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4616 static parser_t *parser;
4622 parser = (parser_t*)mem_a(sizeof(parser_t));
4626 memset(parser, 0, sizeof(*parser));
4628 for (i = 0; i < operator_count; ++i) {
4629 if (operators[i].id == opid1('=')) {
4630 parser->assign_op = operators+i;
4634 if (!parser->assign_op) {
4635 printf("internal error: initializing parser: failed to find assign operator\n");
4640 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4641 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4642 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4643 vec_push(parser->_blocktypedefs, 0);
4647 bool parser_compile()
4649 /* initial lexer/parser state */
4650 parser->lex->flags.noops = true;
4652 if (parser_next(parser))
4654 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4656 if (!parser_global_statement(parser)) {
4657 if (parser->tok == TOKEN_EOF)
4658 parseerror(parser, "unexpected eof");
4659 else if (!parser->errors)
4660 parseerror(parser, "there have been errors, bailing out");
4661 lex_close(parser->lex);
4667 parseerror(parser, "parse error");
4668 lex_close(parser->lex);
4673 lex_close(parser->lex);
4676 return !parser->errors;
4679 bool parser_compile_file(const char *filename)
4681 parser->lex = lex_open(filename);
4683 con_err("failed to open file \"%s\"\n", filename);
4686 return parser_compile();
4689 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4691 parser->lex = lex_open_string(str, len, name);
4693 con_err("failed to create lexer for string \"%s\"\n", name);
4696 return parser_compile();
4699 bool parser_compile_string(const char *name, const char *str)
4701 parser->lex = lex_open_string(str, strlen(str), name);
4703 con_err("failed to create lexer for string \"%s\"\n", name);
4706 return parser_compile();
4709 void parser_cleanup()
4712 for (i = 0; i < vec_size(parser->accessors); ++i) {
4713 ast_delete(parser->accessors[i]->constval.vfunc);
4714 parser->accessors[i]->constval.vfunc = NULL;
4715 ast_delete(parser->accessors[i]);
4717 for (i = 0; i < vec_size(parser->functions); ++i) {
4718 ast_delete(parser->functions[i]);
4720 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4721 ast_delete(parser->imm_vector[i]);
4723 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4724 ast_delete(parser->imm_string[i]);
4726 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4727 ast_delete(parser->imm_float[i]);
4729 for (i = 0; i < vec_size(parser->fields); ++i) {
4730 ast_delete(parser->fields[i]);
4732 for (i = 0; i < vec_size(parser->globals); ++i) {
4733 ast_delete(parser->globals[i]);
4735 vec_free(parser->accessors);
4736 vec_free(parser->functions);
4737 vec_free(parser->imm_vector);
4738 vec_free(parser->imm_string);
4739 vec_free(parser->imm_float);
4740 vec_free(parser->globals);
4741 vec_free(parser->fields);
4743 for (i = 0; i < vec_size(parser->variables); ++i)
4744 util_htdel(parser->variables[i]);
4745 vec_free(parser->variables);
4746 vec_free(parser->_blocklocals);
4747 vec_free(parser->_locals);
4749 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4750 ast_delete(parser->_typedefs[i]);
4751 vec_free(parser->_typedefs);
4752 for (i = 0; i < vec_size(parser->typedefs); ++i)
4753 util_htdel(parser->typedefs[i]);
4754 vec_free(parser->typedefs);
4755 vec_free(parser->_blocktypedefs);
4757 vec_free(parser->_block_ctx);
4759 vec_free(parser->labels);
4760 vec_free(parser->gotos);
4765 bool parser_finish(const char *output)
4771 if (!parser->errors)
4773 ir = ir_builder_new("gmqcc_out");
4775 con_out("failed to allocate builder\n");
4779 for (i = 0; i < vec_size(parser->fields); ++i) {
4782 if (!ast_istype(parser->fields[i], ast_value))
4784 field = (ast_value*)parser->fields[i];
4785 hasvalue = field->hasvalue;
4786 field->hasvalue = false;
4787 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4788 con_out("failed to generate field %s\n", field->name);
4789 ir_builder_delete(ir);
4794 ast_expression *subtype;
4795 field->hasvalue = true;
4796 subtype = field->expression.next;
4797 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4798 if (subtype->expression.vtype == TYPE_FIELD)
4799 ifld->fieldtype = subtype->expression.next->expression.vtype;
4800 else if (subtype->expression.vtype == TYPE_FUNCTION)
4801 ifld->outtype = subtype->expression.next->expression.vtype;
4802 (void)!ir_value_set_field(field->ir_v, ifld);
4805 for (i = 0; i < vec_size(parser->globals); ++i) {
4807 if (!ast_istype(parser->globals[i], ast_value))
4809 asvalue = (ast_value*)(parser->globals[i]);
4810 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4811 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4812 "unused global: `%s`", asvalue->name);
4814 if (!ast_global_codegen(asvalue, ir, false)) {
4815 con_out("failed to generate global %s\n", asvalue->name);
4816 ir_builder_delete(ir);
4820 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4821 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4822 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4823 ir_builder_delete(ir);
4827 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4828 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4829 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4830 ir_builder_delete(ir);
4834 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4835 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4836 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4837 ir_builder_delete(ir);
4841 for (i = 0; i < vec_size(parser->globals); ++i) {
4843 if (!ast_istype(parser->globals[i], ast_value))
4845 asvalue = (ast_value*)(parser->globals[i]);
4846 if (!ast_generate_accessors(asvalue, ir)) {
4847 ir_builder_delete(ir);
4851 for (i = 0; i < vec_size(parser->fields); ++i) {
4853 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4855 if (!ast_istype((ast_expression*)asvalue, ast_value))
4857 if (asvalue->expression.vtype != TYPE_ARRAY)
4859 if (!ast_generate_accessors(asvalue, ir)) {
4860 ir_builder_delete(ir);
4864 for (i = 0; i < vec_size(parser->functions); ++i) {
4865 if (!ast_function_codegen(parser->functions[i], ir)) {
4866 con_out("failed to generate function %s\n", parser->functions[i]->name);
4867 ir_builder_delete(ir);
4872 ir_builder_dump(ir, con_out);
4873 for (i = 0; i < vec_size(parser->functions); ++i) {
4874 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4875 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4876 ir_builder_delete(ir);
4883 ir_builder_dump(ir, con_out);
4885 generate_checksum(parser);
4887 if (!ir_builder_generate(ir, output)) {
4888 con_out("*** failed to generate output file\n");
4889 ir_builder_delete(ir);
4894 ir_builder_delete(ir);
4898 con_out("*** there were compile errors\n");