5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 /* beginning of locals */
30 #define PARSER_HT_LOCALS 2
32 #define PARSER_HT_SIZE 1024
33 #define TYPEDEF_HT_SIZE 16
39 ast_expression **globals;
40 ast_expression **fields;
41 ast_function **functions;
42 ast_value **imm_float;
43 ast_value **imm_string;
44 ast_value **imm_vector;
47 /* must be deleted first, they reference immediates and values */
48 ast_value **accessors;
50 ast_value *imm_float_zero;
51 ast_value *imm_float_one;
52 ast_value *imm_vector_zero;
57 ast_function *function;
59 /* All the labels the function defined...
60 * Should they be in ast_function instead?
65 /* A list of hashtables for each scope */
71 /* not to be used directly, we use the hash table */
72 ast_expression **_locals;
74 ast_value **_typedefs;
75 size_t *_blocktypedefs;
80 /* we store the '=' operator info */
81 const oper_info *assign_op;
83 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
84 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
85 * anything else: type error
89 /* Keep track of our ternary vs parenthesis nesting state.
90 * If we reach a 'comma' operator in a ternary without a paren,
91 * we shall trigger -Wternary-precedence.
93 enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
99 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
101 static void parser_enterblock(parser_t *parser);
102 static bool parser_leaveblock(parser_t *parser);
103 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
104 static bool parse_typedef(parser_t *parser);
105 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn);
106 static ast_block* parse_block(parser_t *parser);
107 static bool parse_block_into(parser_t *parser, ast_block *block);
108 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
109 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
110 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
111 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
113 static void parseerror(parser_t *parser, const char *fmt, ...)
120 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
124 /* returns true if it counts as an error */
125 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
130 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
135 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
140 r = vcompile_warning(ctx, warntype, fmt, ap);
145 /**********************************************************************
146 * some maths used for constant folding
149 vector vec3_add(vector a, vector b)
158 vector vec3_sub(vector a, vector b)
167 qcfloat vec3_mulvv(vector a, vector b)
169 return (a.x * b.x + a.y * b.y + a.z * b.z);
172 vector vec3_mulvf(vector a, float b)
181 /**********************************************************************
185 bool parser_next(parser_t *parser)
187 /* lex_do kills the previous token */
188 parser->tok = lex_do(parser->lex);
189 if (parser->tok == TOKEN_EOF)
191 if (parser->tok >= TOKEN_ERROR) {
192 parseerror(parser, "lex error");
198 #define parser_tokval(p) ((p)->lex->tok.value)
199 #define parser_token(p) (&((p)->lex->tok))
200 #define parser_ctx(p) ((p)->lex->tok.ctx)
202 static ast_value* parser_const_float(parser_t *parser, double d)
206 for (i = 0; i < vec_size(parser->imm_float); ++i) {
207 const double compare = parser->imm_float[i]->constval.vfloat;
208 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
209 return parser->imm_float[i];
211 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
213 out->hasvalue = true;
214 out->constval.vfloat = d;
215 vec_push(parser->imm_float, out);
219 static ast_value* parser_const_float_0(parser_t *parser)
221 if (!parser->imm_float_zero)
222 parser->imm_float_zero = parser_const_float(parser, 0);
223 return parser->imm_float_zero;
226 static ast_value* parser_const_float_1(parser_t *parser)
228 if (!parser->imm_float_one)
229 parser->imm_float_one = parser_const_float(parser, 1);
230 return parser->imm_float_one;
233 static char *parser_strdup(const char *str)
236 /* actually dup empty strings */
237 char *out = mem_a(1);
241 return util_strdup(str);
244 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
248 for (i = 0; i < vec_size(parser->imm_string); ++i) {
249 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
250 return parser->imm_string[i];
254 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
255 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
257 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
259 out->hasvalue = true;
260 out->constval.vstring = parser_strdup(str);
261 vec_push(parser->imm_string, out);
265 static ast_value* parser_const_vector(parser_t *parser, vector v)
269 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
270 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
271 return parser->imm_vector[i];
273 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
275 out->hasvalue = true;
276 out->constval.vvec = v;
277 vec_push(parser->imm_vector, out);
281 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
287 return parser_const_vector(parser, v);
290 static ast_value* parser_const_vector_0(parser_t *parser)
292 if (!parser->imm_vector_zero)
293 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
294 return parser->imm_vector_zero;
297 static ast_expression* parser_find_field(parser_t *parser, const char *name)
299 return util_htget(parser->htfields, name);
302 static ast_expression* parser_find_global(parser_t *parser, const char *name)
304 return util_htget(parser->htglobals, name);
307 static ast_expression* parser_find_param(parser_t *parser, const char *name)
311 if (!parser->function)
313 fun = parser->function->vtype;
314 for (i = 0; i < vec_size(fun->expression.params); ++i) {
315 if (!strcmp(fun->expression.params[i]->name, name))
316 return (ast_expression*)(fun->expression.params[i]);
321 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
326 hash = util_hthash(parser->htglobals, name);
329 for (i = vec_size(parser->variables); i > upto;) {
331 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
335 return parser_find_param(parser, name);
338 static ast_expression* parser_find_var(parser_t *parser, const char *name)
342 v = parser_find_local(parser, name, 0, &dummy);
343 if (!v) v = parser_find_global(parser, name);
347 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
351 hash = util_hthash(parser->typedefs[0], name);
353 for (i = vec_size(parser->typedefs); i > upto;) {
355 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
363 size_t etype; /* 0 = expression, others are operators */
367 ast_block *block; /* for commas and function calls */
376 #define SY_PAREN_EXPR '('
377 #define SY_PAREN_FUNC 'f'
378 #define SY_PAREN_INDEX '['
379 #define SY_PAREN_TERNARY '?'
381 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
392 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
396 e.out = (ast_expression*)v;
403 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
405 e.etype = 1 + (op - operators);
414 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
426 # define DEBUGSHUNTDO(x) x
428 # define DEBUGSHUNTDO(x)
431 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
432 * so we need to rotate it to become ent.(foo[n]).
434 static bool rotate_entfield_array_index_nodes(ast_expression **out)
436 ast_array_index *index;
437 ast_entfield *entfield;
441 ast_expression *entity;
443 lex_ctx ctx = ast_ctx(*out);
445 if (!ast_istype(*out, ast_array_index))
447 index = (ast_array_index*)*out;
449 if (!ast_istype(index->array, ast_entfield))
451 entfield = (ast_entfield*)index->array;
453 if (!ast_istype(entfield->field, ast_value))
455 field = (ast_value*)entfield->field;
458 entity = entfield->entity;
462 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
463 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
464 *out = (ast_expression*)entfield;
469 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
471 switch (v->expression.vtype) {
473 return !!v->constval.vfloat;
475 return !!v->constval.vint;
477 if (OPTS_FLAG(CORRECT_LOGIC))
478 return v->constval.vvec.x &&
479 v->constval.vvec.y &&
482 return !!(v->constval.vvec.x);
484 if (!v->constval.vstring)
486 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
488 return !!v->constval.vstring[0];
490 compile_error(ctx, "internal error: immediate_is_true on invalid type");
491 return !!v->constval.vfunc;
495 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
499 ast_expression *out = NULL;
500 ast_expression *exprs[3];
501 ast_block *blocks[3];
502 ast_value *asvalue[3];
503 ast_binstore *asbinstore;
504 size_t i, assignop, addop, subop;
505 qcint generated_op = 0;
510 if (!vec_size(sy->ops)) {
511 parseerror(parser, "internal error: missing operator");
515 if (vec_last(sy->ops).paren) {
516 parseerror(parser, "unmatched parenthesis");
520 op = &operators[vec_last(sy->ops).etype - 1];
521 ctx = vec_last(sy->ops).ctx;
523 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
525 if (vec_size(sy->out) < op->operands) {
526 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
527 op->op, (int)op->id);
531 vec_shrinkby(sy->ops, 1);
533 /* op(:?) has no input and no output */
537 vec_shrinkby(sy->out, op->operands);
538 for (i = 0; i < op->operands; ++i) {
539 exprs[i] = sy->out[vec_size(sy->out)+i].out;
540 blocks[i] = sy->out[vec_size(sy->out)+i].block;
541 asvalue[i] = (ast_value*)exprs[i];
544 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
545 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
549 #define NotSameType(T) \
550 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
551 exprs[0]->expression.vtype != T)
552 #define CanConstFold1(A) \
553 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
554 (A)->expression.vtype != TYPE_FUNCTION)
555 #define CanConstFold(A, B) \
556 (CanConstFold1(A) && CanConstFold1(B))
557 #define ConstV(i) (asvalue[(i)]->constval.vvec)
558 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
559 #define ConstS(i) (asvalue[(i)]->constval.vstring)
563 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
567 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
568 if (exprs[1]->expression.vtype != TYPE_FIELD) {
569 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
572 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
574 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
575 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
579 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
585 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
586 !(exprs[0]->expression.vtype == TYPE_FIELD &&
587 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
589 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
590 parseerror(parser, "cannot index value of type %s", ty1);
593 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
594 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
595 parseerror(parser, "index must be of type float, not %s", ty1);
598 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
599 if (rotate_entfield_array_index_nodes(&out))
602 /* This is not broken in fteqcc anymore */
603 if (opts.standard != COMPILER_GMQCC) {
604 /* this error doesn't need to make us bail out */
605 (void)!parsewarning(parser, WARN_EXTENSIONS,
606 "accessing array-field members of an entity without parenthesis\n"
607 " -> this is an extension from -std=gmqcc");
615 if (!ast_block_add_expr(blocks[0], exprs[1]))
618 blocks[0] = ast_block_new(ctx);
619 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
620 !ast_block_add_expr(blocks[0], exprs[1]))
625 if (!ast_block_set_type(blocks[0], exprs[1]))
628 vec_push(sy->out, syblock(ctx, blocks[0]));
635 switch (exprs[0]->expression.vtype) {
637 if (CanConstFold1(exprs[0]))
638 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
640 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
641 (ast_expression*)parser_const_float_0(parser),
645 if (CanConstFold1(exprs[0]))
646 out = (ast_expression*)parser_const_vector_f(parser,
647 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
649 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
650 (ast_expression*)parser_const_vector_0(parser),
654 parseerror(parser, "invalid types used in expression: cannot negate type %s",
655 type_name[exprs[0]->expression.vtype]);
661 switch (exprs[0]->expression.vtype) {
663 if (CanConstFold1(exprs[0]))
664 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
666 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
669 if (CanConstFold1(exprs[0]))
670 out = (ast_expression*)parser_const_float(parser,
671 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
673 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
676 if (CanConstFold1(exprs[0])) {
677 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
678 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
680 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
682 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
683 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
685 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
688 /* we don't constant-fold NOT for these types */
690 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
693 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
696 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
697 type_name[exprs[0]->expression.vtype]);
703 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
704 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
706 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
707 type_name[exprs[0]->expression.vtype],
708 type_name[exprs[1]->expression.vtype]);
711 switch (exprs[0]->expression.vtype) {
713 if (CanConstFold(exprs[0], exprs[1]))
715 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
718 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
721 if (CanConstFold(exprs[0], exprs[1]))
722 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
727 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
728 type_name[exprs[0]->expression.vtype],
729 type_name[exprs[1]->expression.vtype]);
734 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
735 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
737 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
738 type_name[exprs[1]->expression.vtype],
739 type_name[exprs[0]->expression.vtype]);
742 switch (exprs[0]->expression.vtype) {
744 if (CanConstFold(exprs[0], exprs[1]))
745 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
747 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
750 if (CanConstFold(exprs[0], exprs[1]))
751 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
753 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
756 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
757 type_name[exprs[1]->expression.vtype],
758 type_name[exprs[0]->expression.vtype]);
763 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
764 exprs[0]->expression.vtype != TYPE_VECTOR &&
765 exprs[0]->expression.vtype != TYPE_FLOAT &&
766 exprs[1]->expression.vtype != TYPE_VECTOR &&
767 exprs[1]->expression.vtype != TYPE_FLOAT)
769 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
770 type_name[exprs[1]->expression.vtype],
771 type_name[exprs[0]->expression.vtype]);
774 switch (exprs[0]->expression.vtype) {
776 if (exprs[1]->expression.vtype == TYPE_VECTOR)
778 if (CanConstFold(exprs[0], exprs[1]))
779 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
781 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
785 if (CanConstFold(exprs[0], exprs[1]))
786 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
788 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
792 if (exprs[1]->expression.vtype == TYPE_FLOAT)
794 if (CanConstFold(exprs[0], exprs[1]))
795 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
797 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
801 if (CanConstFold(exprs[0], exprs[1]))
802 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
804 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
808 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
809 type_name[exprs[1]->expression.vtype],
810 type_name[exprs[0]->expression.vtype]);
815 if (NotSameType(TYPE_FLOAT)) {
816 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
817 type_name[exprs[0]->expression.vtype],
818 type_name[exprs[1]->expression.vtype]);
821 if (CanConstFold(exprs[0], exprs[1]))
822 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
824 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
828 parseerror(parser, "qc does not have a modulo operator");
832 if (NotSameType(TYPE_FLOAT)) {
833 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
834 type_name[exprs[0]->expression.vtype],
835 type_name[exprs[1]->expression.vtype]);
838 if (CanConstFold(exprs[0], exprs[1]))
839 out = (ast_expression*)parser_const_float(parser,
840 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
841 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
843 out = (ast_expression*)ast_binary_new(ctx,
844 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
848 parseerror(parser, "TODO: bitxor");
853 case opid3('<','<','='):
854 case opid3('>','>','='):
855 parseerror(parser, "TODO: shifts");
859 generated_op += 1; /* INSTR_OR */
861 generated_op += INSTR_AND;
863 if (NotSameType(TYPE_FLOAT)) {
864 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
865 type_name[exprs[0]->expression.vtype],
866 type_name[exprs[1]->expression.vtype]);
867 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
868 parseerror(parser, "TODO: optional early out");
872 if (CanConstFold(exprs[0], exprs[1]))
874 if (OPTS_FLAG(PERL_LOGIC)) {
875 if (immediate_is_true(ctx, asvalue[0]))
879 out = (ast_expression*)parser_const_float(parser,
880 ( (generated_op == INSTR_OR)
881 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
882 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
887 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
888 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
889 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
890 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
893 for (i = 0; i < 2; ++i) {
894 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
895 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
897 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
899 exprs[i] = out; out = NULL;
900 if (OPTS_FLAG(PERL_LOGIC)) {
901 /* here we want to keep the right expressions' type */
905 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
906 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
908 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
910 exprs[i] = out; out = NULL;
911 if (OPTS_FLAG(PERL_LOGIC)) {
912 /* here we want to keep the right expressions' type */
917 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
922 if (vec_last(parser->pot) != POT_TERNARY2) {
923 parseerror(parser, "mismatched parenthesis/ternary");
926 vec_pop(parser->pot);
927 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
928 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
929 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
930 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
933 if (CanConstFold1(exprs[0]))
934 out = (ConstF(0) ? exprs[1] : exprs[2]);
936 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
940 generated_op += 1; /* INSTR_GT */
942 generated_op += 1; /* INSTR_LT */
943 case opid2('>', '='):
944 generated_op += 1; /* INSTR_GE */
945 case opid2('<', '='):
946 generated_op += INSTR_LE;
947 if (NotSameType(TYPE_FLOAT)) {
948 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
949 type_name[exprs[0]->expression.vtype],
950 type_name[exprs[1]->expression.vtype]);
953 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
955 case opid2('!', '='):
956 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
957 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
958 type_name[exprs[0]->expression.vtype],
959 type_name[exprs[1]->expression.vtype]);
962 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
964 case opid2('=', '='):
965 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
966 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
967 type_name[exprs[0]->expression.vtype],
968 type_name[exprs[1]->expression.vtype]);
971 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
975 if (ast_istype(exprs[0], ast_entfield)) {
976 ast_expression *field = ((ast_entfield*)exprs[0])->field;
977 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
978 exprs[0]->expression.vtype == TYPE_FIELD &&
979 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
981 assignop = type_storep_instr[TYPE_VECTOR];
984 assignop = type_storep_instr[exprs[0]->expression.vtype];
985 if (assignop == AINSTR_END ||
986 !ast_compare_type(field->expression.next, exprs[1]))
988 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
989 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
990 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
991 field->expression.next->expression.vtype == TYPE_FUNCTION &&
992 exprs[1]->expression.vtype == TYPE_FUNCTION)
994 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
995 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
1001 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1006 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1007 exprs[0]->expression.vtype == TYPE_FIELD &&
1008 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1010 assignop = type_store_instr[TYPE_VECTOR];
1013 assignop = type_store_instr[exprs[0]->expression.vtype];
1016 if (assignop == AINSTR_END) {
1017 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1018 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1019 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1021 else if (!ast_compare_type(exprs[0], exprs[1])) {
1022 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1023 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1024 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1025 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1026 exprs[1]->expression.vtype == TYPE_FUNCTION)
1028 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1029 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
1035 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1038 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1039 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1041 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1043 case opid3('+','+','P'):
1044 case opid3('-','-','P'):
1046 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1047 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1048 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1051 if (op->id == opid3('+','+','P'))
1052 addop = INSTR_ADD_F;
1054 addop = INSTR_SUB_F;
1055 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1056 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1058 if (ast_istype(exprs[0], ast_entfield)) {
1059 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1061 (ast_expression*)parser_const_float_1(parser));
1063 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1065 (ast_expression*)parser_const_float_1(parser));
1068 case opid3('S','+','+'):
1069 case opid3('S','-','-'):
1071 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1072 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1073 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1076 if (op->id == opid3('S','+','+')) {
1077 addop = INSTR_ADD_F;
1078 subop = INSTR_SUB_F;
1080 addop = INSTR_SUB_F;
1081 subop = INSTR_ADD_F;
1083 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1084 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1086 if (ast_istype(exprs[0], ast_entfield)) {
1087 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1089 (ast_expression*)parser_const_float_1(parser));
1091 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1093 (ast_expression*)parser_const_float_1(parser));
1097 out = (ast_expression*)ast_binary_new(ctx, subop,
1099 (ast_expression*)parser_const_float_1(parser));
1101 case opid2('+','='):
1102 case opid2('-','='):
1103 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1104 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1106 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1107 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1108 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1112 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1113 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1115 if (ast_istype(exprs[0], ast_entfield))
1116 assignop = type_storep_instr[exprs[0]->expression.vtype];
1118 assignop = type_store_instr[exprs[0]->expression.vtype];
1119 switch (exprs[0]->expression.vtype) {
1121 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1122 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1123 exprs[0], exprs[1]);
1126 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1127 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1128 exprs[0], exprs[1]);
1131 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1132 type_name[exprs[0]->expression.vtype],
1133 type_name[exprs[1]->expression.vtype]);
1137 case opid2('*','='):
1138 case opid2('/','='):
1139 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1140 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1141 exprs[0]->expression.vtype == TYPE_VECTOR))
1143 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1144 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1145 parseerror(parser, "invalid types used in expression: %s and %s",
1149 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1150 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1152 if (ast_istype(exprs[0], ast_entfield))
1153 assignop = type_storep_instr[exprs[0]->expression.vtype];
1155 assignop = type_store_instr[exprs[0]->expression.vtype];
1156 switch (exprs[0]->expression.vtype) {
1158 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1159 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1160 exprs[0], exprs[1]);
1163 if (op->id == opid2('*','=')) {
1164 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1165 exprs[0], exprs[1]);
1167 /* there's no DIV_VF */
1168 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1169 (ast_expression*)parser_const_float_1(parser),
1173 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1178 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1179 type_name[exprs[0]->expression.vtype],
1180 type_name[exprs[1]->expression.vtype]);
1184 case opid2('&','='):
1185 case opid2('|','='):
1186 if (NotSameType(TYPE_FLOAT)) {
1187 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1188 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1189 parseerror(parser, "invalid types used in expression: %s and %s",
1193 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1194 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1196 if (ast_istype(exprs[0], ast_entfield))
1197 assignop = type_storep_instr[exprs[0]->expression.vtype];
1199 assignop = type_store_instr[exprs[0]->expression.vtype];
1200 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1201 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1202 exprs[0], exprs[1]);
1204 case opid3('&','~','='):
1205 /* This is like: a &= ~(b);
1206 * But QC has no bitwise-not, so we implement it as
1209 if (NotSameType(TYPE_FLOAT)) {
1210 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1211 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1212 parseerror(parser, "invalid types used in expression: %s and %s",
1216 if (ast_istype(exprs[0], ast_entfield))
1217 assignop = type_storep_instr[exprs[0]->expression.vtype];
1219 assignop = type_store_instr[exprs[0]->expression.vtype];
1220 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1223 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1224 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1226 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1227 asbinstore->keep_dest = true;
1228 out = (ast_expression*)asbinstore;
1234 parseerror(parser, "failed to apply operand %s", op->op);
1238 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1239 vec_push(sy->out, syexp(ctx, out));
1243 static bool parser_close_call(parser_t *parser, shunt *sy)
1245 /* was a function call */
1246 ast_expression *fun;
1252 vec_shrinkby(sy->ops, 1);
1253 fid = sy->ops[vec_size(sy->ops)].off;
1255 /* out[fid] is the function
1256 * everything above is parameters...
1257 * 0 params = nothing
1258 * 1 params = ast_expression
1262 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1263 parseerror(parser, "internal error: function call needs function and parameter list...");
1267 fun = sy->out[fid].out;
1269 if (fun == intrinsic_debug_typestring) {
1271 if (fid+2 != vec_size(sy->out) ||
1272 vec_last(sy->out).block)
1274 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1277 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1278 ast_unref(vec_last(sy->out).out);
1279 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1280 (ast_expression*)parser_const_string(parser, ty, false));
1281 vec_shrinkby(sy->out, 1);
1285 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1287 parseerror(parser, "internal error: failed to create ast_call node");
1291 if (fid+1 == vec_size(sy->out)) {
1294 } else if (fid+2 == vec_size(sy->out)) {
1296 vec_shrinkby(sy->out, 1);
1297 params = sy->out[vec_size(sy->out)].block;
1301 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1303 paramcount = vec_size(params->exprs);
1304 call->params = params->exprs;
1305 params->exprs = NULL;
1308 if (!ast_call_check_types(call))
1311 parseerror(parser, "invalid function call");
1315 /* overwrite fid, the function, with a call */
1316 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1318 if (fun->expression.vtype != TYPE_FUNCTION) {
1319 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1323 if (!fun->expression.next) {
1324 parseerror(parser, "could not determine function return type");
1327 if (vec_size(fun->expression.params) != paramcount &&
1328 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1329 vec_size(fun->expression.params) < paramcount))
1332 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1334 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1335 if (opts.standard == COMPILER_GMQCC)
1338 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1339 " -> `%s` has been declared here: %s:%i",
1340 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1341 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1343 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1344 " -> it has been declared here: %s:%i",
1345 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1346 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1352 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1353 "too %s parameters for call to %s: expected %i, got %i\n"
1354 " -> `%s` has been declared here: %s:%i",
1355 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1356 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1358 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1359 "too %s parameters for function call: expected %i, got %i\n"
1360 " -> it has been declared here: %s:%i",
1361 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1362 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1370 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1372 if (!vec_size(sy->ops)) {
1373 parseerror(parser, "unmatched closing paren");
1376 /* this would for bit a + (x) because there are no operators inside (x)
1377 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1378 parseerror(parser, "empty parenthesis expression");
1382 while (vec_size(sy->ops)) {
1383 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1384 if (!parser_close_call(parser, sy))
1388 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1389 vec_shrinkby(sy->ops, 1);
1390 return !functions_only;
1392 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1395 /* pop off the parenthesis */
1396 vec_shrinkby(sy->ops, 1);
1397 /* then apply the index operator */
1398 if (!parser_sy_apply_operator(parser, sy))
1402 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1405 if (vec_last(parser->pot) != POT_TERNARY1) {
1406 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1409 vec_last(parser->pot) = POT_TERNARY2;
1410 /* pop off the parenthesis */
1411 vec_shrinkby(sy->ops, 1);
1414 if (!parser_sy_apply_operator(parser, sy))
1420 static void parser_reclassify_token(parser_t *parser)
1423 for (i = 0; i < operator_count; ++i) {
1424 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1425 parser->tok = TOKEN_OPERATOR;
1431 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1433 ast_expression *expr = NULL;
1435 bool wantop = false;
1436 bool gotmemberof = false;
1438 /* count the parens because an if starts with one, so the
1439 * end of a condition is an unmatched closing paren
1447 parser->lex->flags.noops = false;
1449 parser_reclassify_token(parser);
1454 gotmemberof = false;
1456 parser->memberof = 0;
1458 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1459 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1461 /* a translatable string */
1465 parseerror(parser, "expected operator or end of statement, got constant");
1469 parser->lex->flags.noops = true;
1470 if (!parser_next(parser) || parser->tok != '(') {
1471 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1474 parser->lex->flags.noops = false;
1475 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1476 parseerror(parser, "expected a constant string in translatable-string extension");
1479 val = parser_const_string(parser, parser_tokval(parser), true);
1483 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1484 DEBUGSHUNTDO(con_out("push string\n"));
1486 if (!parser_next(parser) || parser->tok != ')') {
1487 parseerror(parser, "expected closing paren after translatable string");
1491 else if (parser->tok == TOKEN_IDENT)
1493 ast_expression *var;
1495 parseerror(parser, "expected operator or end of statement");
1500 if (opts.standard == COMPILER_GMQCC)
1502 if (parser->memberof == TYPE_ENTITY) {
1503 /* still get vars first since there could be a fieldpointer */
1504 var = parser_find_var(parser, parser_tokval(parser));
1506 var = parser_find_field(parser, parser_tokval(parser));
1508 else if (parser->memberof == TYPE_VECTOR)
1510 parseerror(parser, "TODO: implement effective vector member access");
1513 else if (parser->memberof) {
1514 parseerror(parser, "namespace for member not found");
1518 var = parser_find_var(parser, parser_tokval(parser));
1520 var = parser_find_var(parser, parser_tokval(parser));
1522 var = parser_find_field(parser, parser_tokval(parser));
1526 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1527 var = (ast_expression*)intrinsic_debug_typestring;
1532 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1538 if (ast_istype(var, ast_value)) {
1539 ((ast_value*)var)->uses++;
1541 else if (ast_istype(var, ast_member)) {
1542 ast_member *mem = (ast_member*)var;
1543 if (ast_istype(mem->owner, ast_value))
1544 ((ast_value*)(mem->owner))->uses++;
1547 vec_push(sy.out, syexp(parser_ctx(parser), var));
1548 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1550 else if (parser->tok == TOKEN_FLOATCONST) {
1553 parseerror(parser, "expected operator or end of statement, got constant");
1557 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1560 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1561 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1563 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1566 parseerror(parser, "expected operator or end of statement, got constant");
1570 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1573 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1574 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1576 else if (parser->tok == TOKEN_STRINGCONST) {
1579 parseerror(parser, "expected operator or end of statement, got constant");
1583 val = parser_const_string(parser, parser_tokval(parser), false);
1586 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1587 DEBUGSHUNTDO(con_out("push string\n"));
1589 else if (parser->tok == TOKEN_VECTORCONST) {
1592 parseerror(parser, "expected operator or end of statement, got constant");
1596 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1599 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1600 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1601 parser_token(parser)->constval.v.x,
1602 parser_token(parser)->constval.v.y,
1603 parser_token(parser)->constval.v.z));
1605 else if (parser->tok == '(') {
1606 parseerror(parser, "internal error: '(' should be classified as operator");
1609 else if (parser->tok == '[') {
1610 parseerror(parser, "internal error: '[' should be classified as operator");
1613 else if (parser->tok == ')') {
1615 DEBUGSHUNTDO(con_out("do[op] )\n"));
1619 /* we do expect an operator next */
1620 /* closing an opening paren */
1621 if (!parser_close_paren(parser, &sy, false))
1623 if (vec_last(parser->pot) != POT_PAREN) {
1624 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1627 vec_pop(parser->pot);
1629 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1633 /* allowed for function calls */
1634 if (!parser_close_paren(parser, &sy, true))
1636 if (vec_last(parser->pot) != POT_PAREN) {
1637 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1640 vec_pop(parser->pot);
1644 else if (parser->tok == ']') {
1646 parseerror(parser, "operand expected");
1650 if (!parser_close_paren(parser, &sy, false))
1652 if (vec_last(parser->pot) != POT_PAREN) {
1653 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1656 vec_pop(parser->pot);
1659 else if (parser->tok == TOKEN_TYPENAME) {
1660 parseerror(parser, "unexpected typename");
1663 else if (parser->tok != TOKEN_OPERATOR) {
1665 parseerror(parser, "expected operator or end of statement");
1672 /* classify the operator */
1673 const oper_info *op;
1674 const oper_info *olast = NULL;
1676 for (o = 0; o < operator_count; ++o) {
1677 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1678 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1679 !strcmp(parser_tokval(parser), operators[o].op))
1684 if (o == operator_count) {
1685 /* no operator found... must be the end of the statement */
1688 /* found an operator */
1691 /* when declaring variables, a comma starts a new variable */
1692 if (op->id == opid1(',') && !parens && stopatcomma) {
1693 /* fixup the token */
1698 /* a colon without a pervious question mark cannot be a ternary */
1699 if (!ternaries && op->id == opid2(':','?')) {
1704 if (op->id == opid1(',')) {
1705 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1706 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1710 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1711 olast = &operators[vec_last(sy.ops).etype-1];
1714 (op->prec < olast->prec) ||
1715 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1717 if (!parser_sy_apply_operator(parser, &sy))
1719 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1720 olast = &operators[vec_last(sy.ops).etype-1];
1725 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1726 /* for gmqcc standard: open up the namespace of the previous type */
1727 ast_expression *prevex = vec_last(sy.out).out;
1729 parseerror(parser, "unexpected member operator");
1732 if (prevex->expression.vtype == TYPE_ENTITY)
1733 parser->memberof = TYPE_ENTITY;
1734 else if (prevex->expression.vtype == TYPE_VECTOR)
1735 parser->memberof = TYPE_VECTOR;
1737 parseerror(parser, "type error: type has no members");
1743 if (op->id == opid1('(')) {
1745 size_t sycount = vec_size(sy.out);
1746 DEBUGSHUNTDO(con_out("push [op] (\n"));
1747 ++parens; vec_push(parser->pot, POT_PAREN);
1748 /* we expected an operator, this is the function-call operator */
1749 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1751 ++parens; vec_push(parser->pot, POT_PAREN);
1752 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1753 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1756 } else if (op->id == opid1('[')) {
1758 parseerror(parser, "unexpected array subscript");
1761 ++parens; vec_push(parser->pot, POT_PAREN);
1762 /* push both the operator and the paren, this makes life easier */
1763 vec_push(sy.ops, syop(parser_ctx(parser), op));
1764 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1766 } else if (op->id == opid2('?',':')) {
1767 vec_push(sy.ops, syop(parser_ctx(parser), op));
1768 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1771 vec_push(parser->pot, POT_TERNARY1);
1772 } else if (op->id == opid2(':','?')) {
1773 if (!vec_size(parser->pot)) {
1774 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1777 if (vec_last(parser->pot) != POT_TERNARY1) {
1778 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1781 if (!parser_close_paren(parser, &sy, false))
1783 vec_push(sy.ops, syop(parser_ctx(parser), op));
1787 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1788 vec_push(sy.ops, syop(parser_ctx(parser), op));
1789 wantop = !!(op->flags & OP_SUFFIX);
1792 if (!parser_next(parser)) {
1795 if (parser->tok == ';' ||
1796 (!parens && parser->tok == ']'))
1802 while (vec_size(sy.ops)) {
1803 if (!parser_sy_apply_operator(parser, &sy))
1807 parser->lex->flags.noops = true;
1808 if (!vec_size(sy.out)) {
1809 parseerror(parser, "empty expression");
1812 expr = sy.out[0].out;
1815 DEBUGSHUNTDO(con_out("shunt done\n"));
1816 if (vec_size(parser->pot)) {
1817 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1820 vec_free(parser->pot);
1824 parser->lex->flags.noops = true;
1830 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1832 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1835 if (!parser_next(parser)) {
1842 static void parser_enterblock(parser_t *parser)
1844 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1845 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1846 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1847 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1848 vec_push(parser->_block_ctx, parser_ctx(parser));
1851 static bool parser_leaveblock(parser_t *parser)
1854 size_t locals, typedefs;
1856 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1857 parseerror(parser, "internal error: parser_leaveblock with no block");
1861 util_htdel(vec_last(parser->variables));
1862 vec_pop(parser->variables);
1863 if (!vec_size(parser->_blocklocals)) {
1864 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1868 locals = vec_last(parser->_blocklocals);
1869 vec_pop(parser->_blocklocals);
1870 while (vec_size(parser->_locals) != locals) {
1871 ast_expression *e = vec_last(parser->_locals);
1872 ast_value *v = (ast_value*)e;
1873 vec_pop(parser->_locals);
1874 if (ast_istype(e, ast_value) && !v->uses) {
1875 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1882 typedefs = vec_last(parser->_blocktypedefs);
1883 while (vec_size(parser->_typedefs) != typedefs) {
1884 ast_delete(vec_last(parser->_typedefs));
1885 vec_pop(parser->_typedefs);
1887 util_htdel(vec_last(parser->typedefs));
1888 vec_pop(parser->typedefs);
1890 vec_pop(parser->_block_ctx);
1894 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1896 vec_push(parser->_locals, e);
1897 util_htset(vec_last(parser->variables), name, (void*)e);
1900 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1904 ast_expression *prev;
1906 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1909 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1912 parseerror(parser, "internal error: failed to process condition");
1917 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1919 /* vector types need to be cast to true booleans */
1920 ast_binary *bin = (ast_binary*)cond;
1921 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1923 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1925 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1928 parseerror(parser, "internal error: failed to process condition");
1935 unary = (ast_unary*)cond;
1936 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1938 cond = unary->operand;
1939 unary->operand = NULL;
1942 unary = (ast_unary*)cond;
1946 parseerror(parser, "internal error: failed to process condition");
1948 if (ifnot) *_ifnot = !*_ifnot;
1952 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1955 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1958 lex_ctx ctx = parser_ctx(parser);
1960 (void)block; /* not touching */
1962 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1963 if (!parser_next(parser)) {
1964 parseerror(parser, "expected condition or 'not'");
1967 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1969 if (!parser_next(parser)) {
1970 parseerror(parser, "expected condition in parenthesis");
1974 if (parser->tok != '(') {
1975 parseerror(parser, "expected 'if' condition in parenthesis");
1978 /* parse into the expression */
1979 if (!parser_next(parser)) {
1980 parseerror(parser, "expected 'if' condition after opening paren");
1983 /* parse the condition */
1984 cond = parse_expression_leave(parser, false);
1988 if (parser->tok != ')') {
1989 parseerror(parser, "expected closing paren after 'if' condition");
1993 /* parse into the 'then' branch */
1994 if (!parser_next(parser)) {
1995 parseerror(parser, "expected statement for on-true branch of 'if'");
1999 if (!parse_statement_or_block(parser, &ontrue)) {
2003 /* check for an else */
2004 if (!strcmp(parser_tokval(parser), "else")) {
2005 /* parse into the 'else' branch */
2006 if (!parser_next(parser)) {
2007 parseerror(parser, "expected on-false branch after 'else'");
2012 if (!parse_statement_or_block(parser, &onfalse)) {
2019 cond = process_condition(parser, cond, &ifnot);
2021 if (ontrue) ast_delete(ontrue);
2022 if (onfalse) ast_delete(onfalse);
2027 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2029 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2030 *out = (ast_expression*)ifthen;
2034 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2037 ast_expression *cond, *ontrue;
2041 lex_ctx ctx = parser_ctx(parser);
2043 (void)block; /* not touching */
2045 /* skip the 'while' and check for opening paren */
2046 if (!parser_next(parser) || parser->tok != '(') {
2047 parseerror(parser, "expected 'while' condition in parenthesis");
2050 /* parse into the expression */
2051 if (!parser_next(parser)) {
2052 parseerror(parser, "expected 'while' condition after opening paren");
2055 /* parse the condition */
2056 cond = parse_expression_leave(parser, false);
2060 if (parser->tok != ')') {
2061 parseerror(parser, "expected closing paren after 'while' condition");
2065 /* parse into the 'then' branch */
2066 if (!parser_next(parser)) {
2067 parseerror(parser, "expected while-loop body");
2071 if (!parse_statement_or_block(parser, &ontrue)) {
2076 cond = process_condition(parser, cond, &ifnot);
2081 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2082 *out = (ast_expression*)aloop;
2086 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2089 ast_expression *cond, *ontrue;
2093 lex_ctx ctx = parser_ctx(parser);
2095 (void)block; /* not touching */
2097 /* skip the 'do' and get the body */
2098 if (!parser_next(parser)) {
2099 parseerror(parser, "expected loop body");
2102 if (!parse_statement_or_block(parser, &ontrue))
2105 /* expect the "while" */
2106 if (parser->tok != TOKEN_KEYWORD ||
2107 strcmp(parser_tokval(parser), "while"))
2109 parseerror(parser, "expected 'while' and condition");
2114 /* skip the 'while' and check for opening paren */
2115 if (!parser_next(parser) || parser->tok != '(') {
2116 parseerror(parser, "expected 'while' condition in parenthesis");
2120 /* parse into the expression */
2121 if (!parser_next(parser)) {
2122 parseerror(parser, "expected 'while' condition after opening paren");
2126 /* parse the condition */
2127 cond = parse_expression_leave(parser, false);
2131 if (parser->tok != ')') {
2132 parseerror(parser, "expected closing paren after 'while' condition");
2138 if (!parser_next(parser) || parser->tok != ';') {
2139 parseerror(parser, "expected semicolon after condition");
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "parse error");
2152 cond = process_condition(parser, cond, &ifnot);
2157 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2158 *out = (ast_expression*)aloop;
2162 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2165 ast_expression *initexpr, *cond, *increment, *ontrue;
2171 lex_ctx ctx = parser_ctx(parser);
2173 parser_enterblock(parser);
2180 /* skip the 'while' and check for opening paren */
2181 if (!parser_next(parser) || parser->tok != '(') {
2182 parseerror(parser, "expected 'for' expressions in parenthesis");
2185 /* parse into the expression */
2186 if (!parser_next(parser)) {
2187 parseerror(parser, "expected 'for' initializer after opening paren");
2192 if (parser->tok == TOKEN_IDENT)
2193 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2195 if (typevar || parser->tok == TOKEN_TYPENAME) {
2196 if (opts.standard != COMPILER_GMQCC) {
2197 if (parsewarning(parser, WARN_EXTENSIONS,
2198 "current standard does not allow variable declarations in for-loop initializers"))
2201 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false))
2204 else if (parser->tok != ';')
2206 initexpr = parse_expression_leave(parser, false);
2211 /* move on to condition */
2212 if (parser->tok != ';') {
2213 parseerror(parser, "expected semicolon after for-loop initializer");
2216 if (!parser_next(parser)) {
2217 parseerror(parser, "expected for-loop condition");
2221 /* parse the condition */
2222 if (parser->tok != ';') {
2223 cond = parse_expression_leave(parser, false);
2228 /* move on to incrementor */
2229 if (parser->tok != ';') {
2230 parseerror(parser, "expected semicolon after for-loop initializer");
2233 if (!parser_next(parser)) {
2234 parseerror(parser, "expected for-loop condition");
2238 /* parse the incrementor */
2239 if (parser->tok != ')') {
2240 increment = parse_expression_leave(parser, false);
2243 if (!ast_side_effects(increment)) {
2244 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2250 if (parser->tok != ')') {
2251 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2254 /* parse into the 'then' branch */
2255 if (!parser_next(parser)) {
2256 parseerror(parser, "expected for-loop body");
2259 if (!parse_statement_or_block(parser, &ontrue))
2263 cond = process_condition(parser, cond, &ifnot);
2267 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2268 *out = (ast_expression*)aloop;
2270 if (!parser_leaveblock(parser))
2274 if (initexpr) ast_delete(initexpr);
2275 if (cond) ast_delete(cond);
2276 if (increment) ast_delete(increment);
2277 (void)!parser_leaveblock(parser);
2281 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2283 ast_expression *exp = NULL;
2284 ast_return *ret = NULL;
2285 ast_value *expected = parser->function->vtype;
2287 lex_ctx ctx = parser_ctx(parser);
2289 (void)block; /* not touching */
2291 if (!parser_next(parser)) {
2292 parseerror(parser, "expected return expression");
2296 if (parser->tok != ';') {
2297 exp = parse_expression(parser, false);
2301 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2302 parseerror(parser, "return with invalid expression");
2305 ret = ast_return_new(ctx, exp);
2311 if (!parser_next(parser))
2312 parseerror(parser, "parse error");
2313 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2314 if (opts.standard != COMPILER_GMQCC)
2315 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2317 parseerror(parser, "return without value");
2319 ret = ast_return_new(ctx, NULL);
2321 *out = (ast_expression*)ret;
2325 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2327 lex_ctx ctx = parser_ctx(parser);
2329 (void)block; /* not touching */
2331 if (!parser_next(parser) || parser->tok != ';') {
2332 parseerror(parser, "expected semicolon");
2336 if (!parser_next(parser))
2337 parseerror(parser, "parse error");
2339 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2343 /* returns true when it was a variable qualifier, false otherwise!
2344 * on error, cvq is set to CV_WRONG
2346 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn)
2348 bool had_const = false;
2349 bool had_var = false;
2350 bool had_noref = false;
2351 bool had_noreturn = false;
2355 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2356 /* parse an attribute */
2357 if (!parser_next(parser)) {
2358 parseerror(parser, "expected attribute after `[[`");
2361 if (!strcmp(parser_tokval(parser), "noreturn")) {
2362 had_noreturn = true;
2363 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2364 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2368 else if (!strcmp(parser_tokval(parser), "noref")) {
2370 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2371 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2377 /* Skip tokens until we hit a ]] */
2378 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2379 if (!parser_next(parser)) {
2380 parseerror(parser, "error inside attribute");
2386 else if (!strcmp(parser_tokval(parser), "const"))
2388 else if (!strcmp(parser_tokval(parser), "var"))
2390 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2392 else if (!strcmp(parser_tokval(parser), "noref"))
2394 else if (!had_const && !had_var && !had_noref && !had_noreturn) {
2399 if (!parser_next(parser))
2409 *noreturn = had_noreturn;
2412 parseerror(parser, "parse error after variable qualifier");
2417 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2419 ast_expression *operand;
2422 ast_switch *switchnode;
2423 ast_switch_case swcase;
2426 bool noref, noreturn;
2428 lex_ctx ctx = parser_ctx(parser);
2430 (void)block; /* not touching */
2433 /* parse over the opening paren */
2434 if (!parser_next(parser) || parser->tok != '(') {
2435 parseerror(parser, "expected switch operand in parenthesis");
2439 /* parse into the expression */
2440 if (!parser_next(parser)) {
2441 parseerror(parser, "expected switch operand");
2444 /* parse the operand */
2445 operand = parse_expression_leave(parser, false);
2449 switchnode = ast_switch_new(ctx, operand);
2452 if (parser->tok != ')') {
2453 ast_delete(switchnode);
2454 parseerror(parser, "expected closing paren after 'switch' operand");
2458 /* parse over the opening paren */
2459 if (!parser_next(parser) || parser->tok != '{') {
2460 ast_delete(switchnode);
2461 parseerror(parser, "expected list of cases");
2465 if (!parser_next(parser)) {
2466 ast_delete(switchnode);
2467 parseerror(parser, "expected 'case' or 'default'");
2471 /* new block; allow some variables to be declared here */
2472 parser_enterblock(parser);
2475 if (parser->tok == TOKEN_IDENT)
2476 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2477 if (typevar || parser->tok == TOKEN_TYPENAME) {
2478 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false)) {
2479 ast_delete(switchnode);
2484 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn))
2486 if (cvq == CV_WRONG) {
2487 ast_delete(switchnode);
2490 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn)) {
2491 ast_delete(switchnode);
2500 while (parser->tok != '}') {
2501 ast_block *caseblock;
2503 if (parser->tok != TOKEN_KEYWORD) {
2504 ast_delete(switchnode);
2505 parseerror(parser, "expected 'case' or 'default'");
2508 if (!strcmp(parser_tokval(parser), "case")) {
2509 if (!parser_next(parser)) {
2510 ast_delete(switchnode);
2511 parseerror(parser, "expected expression for case");
2514 swcase.value = parse_expression_leave(parser, false);
2515 if (!swcase.value) {
2516 ast_delete(switchnode);
2517 parseerror(parser, "expected expression for case");
2520 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2521 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2522 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2528 else if (!strcmp(parser_tokval(parser), "default")) {
2529 swcase.value = NULL;
2530 if (!parser_next(parser)) {
2531 ast_delete(switchnode);
2532 parseerror(parser, "expected colon");
2537 /* Now the colon and body */
2538 if (parser->tok != ':') {
2539 if (swcase.value) ast_unref(swcase.value);
2540 ast_delete(switchnode);
2541 parseerror(parser, "expected colon");
2545 if (!parser_next(parser)) {
2546 if (swcase.value) ast_unref(swcase.value);
2547 ast_delete(switchnode);
2548 parseerror(parser, "expected statements or case");
2551 caseblock = ast_block_new(parser_ctx(parser));
2553 if (swcase.value) ast_unref(swcase.value);
2554 ast_delete(switchnode);
2557 swcase.code = (ast_expression*)caseblock;
2558 vec_push(switchnode->cases, swcase);
2560 ast_expression *expr;
2561 if (parser->tok == '}')
2563 if (parser->tok == TOKEN_KEYWORD) {
2564 if (!strcmp(parser_tokval(parser), "case") ||
2565 !strcmp(parser_tokval(parser), "default"))
2570 if (!parse_statement(parser, caseblock, &expr, true)) {
2571 ast_delete(switchnode);
2576 if (!ast_block_add_expr(caseblock, expr)) {
2577 ast_delete(switchnode);
2583 parser_leaveblock(parser);
2586 if (parser->tok != '}') {
2587 ast_delete(switchnode);
2588 parseerror(parser, "expected closing paren of case list");
2591 if (!parser_next(parser)) {
2592 ast_delete(switchnode);
2593 parseerror(parser, "parse error after switch");
2596 *out = (ast_expression*)switchnode;
2600 static bool parse_goto(parser_t *parser, ast_expression **out)
2605 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2606 parseerror(parser, "expected label name after `goto`");
2610 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2612 for (i = 0; i < vec_size(parser->labels); ++i) {
2613 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2614 ast_goto_set_label(gt, parser->labels[i]);
2618 if (i == vec_size(parser->labels))
2619 vec_push(parser->gotos, gt);
2621 if (!parser_next(parser) || parser->tok != ';') {
2622 parseerror(parser, "semicolon expected after goto label");
2625 if (!parser_next(parser)) {
2626 parseerror(parser, "parse error after goto");
2630 *out = (ast_expression*)gt;
2634 static bool parse_skipwhite(parser_t *parser)
2637 if (!parser_next(parser))
2639 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2640 return parser->tok < TOKEN_ERROR;
2643 static bool parse_eol(parser_t *parser)
2645 if (!parse_skipwhite(parser))
2647 return parser->tok == TOKEN_EOL;
2650 static bool parse_pragma_do(parser_t *parser)
2652 if (!parser_next(parser) ||
2653 parser->tok != TOKEN_IDENT ||
2654 strcmp(parser_tokval(parser), "pragma"))
2656 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2659 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2660 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2664 if (!strcmp(parser_tokval(parser), "noref")) {
2665 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2666 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2669 parser->noref = !!parser_token(parser)->constval.i;
2670 if (!parse_eol(parser)) {
2671 parseerror(parser, "parse error after `noref` pragma");
2677 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2684 static bool parse_pragma(parser_t *parser)
2687 parser->lex->flags.preprocessing = true;
2688 parser->lex->flags.mergelines = true;
2689 rv = parse_pragma_do(parser);
2690 if (parser->tok != TOKEN_EOL) {
2691 parseerror(parser, "junk after pragma");
2694 parser->lex->flags.preprocessing = false;
2695 parser->lex->flags.mergelines = false;
2696 if (!parser_next(parser)) {
2697 parseerror(parser, "parse error after pragma");
2703 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2705 bool noref, noreturn;
2707 ast_value *typevar = NULL;
2711 if (parser->tok == TOKEN_IDENT)
2712 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2714 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2716 /* local variable */
2718 parseerror(parser, "cannot declare a variable from here");
2721 if (opts.standard == COMPILER_QCC) {
2722 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2725 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false))
2729 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn))
2731 if (cvq == CV_WRONG)
2733 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn);
2735 else if (parser->tok == TOKEN_KEYWORD)
2737 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2742 if (!parser_next(parser)) {
2743 parseerror(parser, "parse error after __builtin_debug_printtype");
2747 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2749 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2750 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2751 if (!parser_next(parser)) {
2752 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2758 if (!parse_statement(parser, block, out, allow_cases))
2761 con_out("__builtin_debug_printtype: got no output node\n");
2764 ast_type_to_string(*out, ty, sizeof(ty));
2765 con_out("__builtin_debug_printtype: `%s`\n", ty);
2770 else if (!strcmp(parser_tokval(parser), "return"))
2772 return parse_return(parser, block, out);
2774 else if (!strcmp(parser_tokval(parser), "if"))
2776 return parse_if(parser, block, out);
2778 else if (!strcmp(parser_tokval(parser), "while"))
2780 return parse_while(parser, block, out);
2782 else if (!strcmp(parser_tokval(parser), "do"))
2784 return parse_dowhile(parser, block, out);
2786 else if (!strcmp(parser_tokval(parser), "for"))
2788 if (opts.standard == COMPILER_QCC) {
2789 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2792 return parse_for(parser, block, out);
2794 else if (!strcmp(parser_tokval(parser), "break"))
2796 return parse_break_continue(parser, block, out, false);
2798 else if (!strcmp(parser_tokval(parser), "continue"))
2800 return parse_break_continue(parser, block, out, true);
2802 else if (!strcmp(parser_tokval(parser), "switch"))
2804 return parse_switch(parser, block, out);
2806 else if (!strcmp(parser_tokval(parser), "case") ||
2807 !strcmp(parser_tokval(parser), "default"))
2810 parseerror(parser, "unexpected 'case' label");
2815 else if (!strcmp(parser_tokval(parser), "goto"))
2817 return parse_goto(parser, out);
2819 else if (!strcmp(parser_tokval(parser), "typedef"))
2821 if (!parser_next(parser)) {
2822 parseerror(parser, "expected type definition after 'typedef'");
2825 return parse_typedef(parser);
2827 parseerror(parser, "Unexpected keyword");
2830 else if (parser->tok == '{')
2833 inner = parse_block(parser);
2836 *out = (ast_expression*)inner;
2839 else if (parser->tok == ':')
2843 if (!parser_next(parser)) {
2844 parseerror(parser, "expected label name");
2847 if (parser->tok != TOKEN_IDENT) {
2848 parseerror(parser, "label must be an identifier");
2851 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2854 vec_push(parser->labels, label);
2855 *out = (ast_expression*)label;
2856 if (!parser_next(parser)) {
2857 parseerror(parser, "parse error after label");
2860 for (i = 0; i < vec_size(parser->gotos); ++i) {
2861 if (!strcmp(parser->gotos[i]->name, label->name)) {
2862 ast_goto_set_label(parser->gotos[i], label);
2863 vec_remove(parser->gotos, i, 1);
2869 else if (parser->tok == ';')
2871 if (!parser_next(parser)) {
2872 parseerror(parser, "parse error after empty statement");
2879 ast_expression *exp = parse_expression(parser, false);
2883 if (!ast_side_effects(exp)) {
2884 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2891 static bool parse_block_into(parser_t *parser, ast_block *block)
2895 parser_enterblock(parser);
2897 if (!parser_next(parser)) { /* skip the '{' */
2898 parseerror(parser, "expected function body");
2902 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2904 ast_expression *expr = NULL;
2905 if (parser->tok == '}')
2908 if (!parse_statement(parser, block, &expr, false)) {
2909 /* parseerror(parser, "parse error"); */
2915 if (!ast_block_add_expr(block, expr)) {
2922 if (parser->tok != '}') {
2925 (void)parser_next(parser);
2929 if (!parser_leaveblock(parser))
2931 return retval && !!block;
2934 static ast_block* parse_block(parser_t *parser)
2937 block = ast_block_new(parser_ctx(parser));
2940 if (!parse_block_into(parser, block)) {
2941 ast_block_delete(block);
2947 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2949 if (parser->tok == '{') {
2950 *out = (ast_expression*)parse_block(parser);
2953 return parse_statement(parser, NULL, out, false);
2956 static bool create_vector_members(ast_value *var, ast_member **me)
2959 size_t len = strlen(var->name);
2961 for (i = 0; i < 3; ++i) {
2962 char *name = mem_a(len+3);
2963 memcpy(name, var->name, len);
2965 name[len+1] = 'x'+i;
2967 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2976 do { ast_member_delete(me[--i]); } while(i);
2980 static bool parse_function_body(parser_t *parser, ast_value *var)
2982 ast_block *block = NULL;
2987 ast_expression *framenum = NULL;
2988 ast_expression *nextthink = NULL;
2989 /* None of the following have to be deleted */
2990 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2991 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2992 bool has_frame_think;
2996 has_frame_think = false;
2997 old = parser->function;
2999 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3000 parseerror(parser, "gotos/labels leaking");
3004 if (var->expression.flags & AST_FLAG_VARIADIC) {
3005 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3006 "variadic function with implementation will not be able to access additional parameters"))
3012 if (parser->tok == '[') {
3013 /* got a frame definition: [ framenum, nextthink ]
3014 * this translates to:
3015 * self.frame = framenum;
3016 * self.nextthink = time + 0.1;
3017 * self.think = nextthink;
3021 fld_think = parser_find_field(parser, "think");
3022 fld_nextthink = parser_find_field(parser, "nextthink");
3023 fld_frame = parser_find_field(parser, "frame");
3024 if (!fld_think || !fld_nextthink || !fld_frame) {
3025 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3026 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3029 gbl_time = parser_find_global(parser, "time");
3030 gbl_self = parser_find_global(parser, "self");
3031 if (!gbl_time || !gbl_self) {
3032 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3033 parseerror(parser, "please declare the following globals: `time`, `self`");
3037 if (!parser_next(parser))
3040 framenum = parse_expression_leave(parser, true);
3042 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3045 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3046 ast_unref(framenum);
3047 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3051 if (parser->tok != ',') {
3052 ast_unref(framenum);
3053 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3054 parseerror(parser, "Got a %i\n", parser->tok);
3058 if (!parser_next(parser)) {
3059 ast_unref(framenum);
3063 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3065 /* qc allows the use of not-yet-declared functions here
3066 * - this automatically creates a prototype */
3067 ast_value *thinkfunc;
3068 ast_expression *functype = fld_think->expression.next;
3070 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3071 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3072 ast_unref(framenum);
3073 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3077 if (!parser_next(parser)) {
3078 ast_unref(framenum);
3079 ast_delete(thinkfunc);
3083 vec_push(parser->globals, (ast_expression*)thinkfunc);
3084 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3085 nextthink = (ast_expression*)thinkfunc;
3088 nextthink = parse_expression_leave(parser, true);
3090 ast_unref(framenum);
3091 parseerror(parser, "expected a think-function in [frame,think] notation");
3096 if (!ast_istype(nextthink, ast_value)) {
3097 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3101 if (retval && parser->tok != ']') {
3102 parseerror(parser, "expected closing `]` for [frame,think] notation");
3106 if (retval && !parser_next(parser)) {
3110 if (retval && parser->tok != '{') {
3111 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3116 ast_unref(nextthink);
3117 ast_unref(framenum);
3121 has_frame_think = true;
3124 block = ast_block_new(parser_ctx(parser));
3126 parseerror(parser, "failed to allocate block");
3127 if (has_frame_think) {
3128 ast_unref(nextthink);
3129 ast_unref(framenum);
3134 if (has_frame_think) {
3136 ast_expression *self_frame;
3137 ast_expression *self_nextthink;
3138 ast_expression *self_think;
3139 ast_expression *time_plus_1;
3140 ast_store *store_frame;
3141 ast_store *store_nextthink;
3142 ast_store *store_think;
3144 ctx = parser_ctx(parser);
3145 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3146 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3147 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3149 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3150 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3152 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3153 if (self_frame) ast_delete(self_frame);
3154 if (self_nextthink) ast_delete(self_nextthink);
3155 if (self_think) ast_delete(self_think);
3156 if (time_plus_1) ast_delete(time_plus_1);
3162 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3163 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3164 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3167 ast_delete(self_frame);
3170 if (!store_nextthink) {
3171 ast_delete(self_nextthink);
3175 ast_delete(self_think);
3179 if (store_frame) ast_delete(store_frame);
3180 if (store_nextthink) ast_delete(store_nextthink);
3181 if (store_think) ast_delete(store_think);
3184 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3185 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3186 !ast_block_add_expr(block, (ast_expression*)store_think))
3193 parseerror(parser, "failed to generate code for [frame,think]");
3194 ast_unref(nextthink);
3195 ast_unref(framenum);
3201 parser_enterblock(parser);
3203 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3205 ast_value *param = var->expression.params[parami];
3208 if (param->expression.vtype != TYPE_VECTOR &&
3209 (param->expression.vtype != TYPE_FIELD ||
3210 param->expression.next->expression.vtype != TYPE_VECTOR))
3215 if (!create_vector_members(param, me)) {
3216 ast_block_delete(block);
3220 for (e = 0; e < 3; ++e) {
3221 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3222 ast_block_collect(block, (ast_expression*)me[e]);
3226 func = ast_function_new(ast_ctx(var), var->name, var);
3228 parseerror(parser, "failed to allocate function for `%s`", var->name);
3229 ast_block_delete(block);
3232 vec_push(parser->functions, func);
3234 parser->function = func;
3235 if (!parse_block_into(parser, block)) {
3236 ast_block_delete(block);
3240 vec_push(func->blocks, block);
3242 parser->function = old;
3243 if (!parser_leaveblock(parser))
3245 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3246 parseerror(parser, "internal error: local scopes left");
3250 if (parser->tok == ';')
3251 return parser_next(parser);
3252 else if (opts.standard == COMPILER_QCC)
3253 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3257 vec_pop(parser->functions);
3258 ast_function_delete(func);
3259 var->constval.vfunc = NULL;
3262 (void)!parser_leaveblock(parser);
3263 parser->function = old;
3267 static ast_expression *array_accessor_split(
3272 ast_expression *left,
3273 ast_expression *right
3279 lex_ctx ctx = ast_ctx(array);
3281 if (!left || !right) {
3282 if (left) ast_delete(left);
3283 if (right) ast_delete(right);
3287 cmp = ast_binary_new(ctx, INSTR_LT,
3288 (ast_expression*)index,
3289 (ast_expression*)parser_const_float(parser, middle));
3293 parseerror(parser, "internal error: failed to create comparison for array setter");
3297 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3299 ast_delete(cmp); /* will delete left and right */
3300 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3304 return (ast_expression*)ifthen;
3307 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3309 lex_ctx ctx = ast_ctx(array);
3311 if (from+1 == afterend) {
3312 /* set this value */
3315 ast_array_index *subscript;
3317 int assignop = type_store_instr[value->expression.vtype];
3319 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3320 assignop = INSTR_STORE_V;
3322 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3326 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3328 ast_delete(subscript);
3332 block = ast_block_new(ctx);
3338 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3343 ret = ast_return_new(ctx, NULL);
3349 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3354 return (ast_expression*)block;
3356 ast_expression *left, *right;
3357 size_t diff = afterend - from;
3358 size_t middle = from + diff/2;
3359 left = array_setter_node(parser, array, index, value, from, middle);
3360 right = array_setter_node(parser, array, index, value, middle, afterend);
3361 return array_accessor_split(parser, array, index, middle, left, right);
3365 static ast_expression *array_field_setter_node(
3374 lex_ctx ctx = ast_ctx(array);
3376 if (from+1 == afterend) {
3377 /* set this value */
3380 ast_entfield *entfield;
3381 ast_array_index *subscript;
3383 int assignop = type_storep_instr[value->expression.vtype];
3385 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3386 assignop = INSTR_STOREP_V;
3388 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3392 entfield = ast_entfield_new_force(ctx,
3393 (ast_expression*)entity,
3394 (ast_expression*)subscript,
3395 (ast_expression*)subscript);
3397 ast_delete(subscript);
3401 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3403 ast_delete(entfield);
3407 block = ast_block_new(ctx);
3413 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3418 ret = ast_return_new(ctx, NULL);
3424 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3429 return (ast_expression*)block;
3431 ast_expression *left, *right;
3432 size_t diff = afterend - from;
3433 size_t middle = from + diff/2;
3434 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3435 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3436 return array_accessor_split(parser, array, index, middle, left, right);
3440 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3442 lex_ctx ctx = ast_ctx(array);
3444 if (from+1 == afterend) {
3446 ast_array_index *subscript;
3448 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3452 ret = ast_return_new(ctx, (ast_expression*)subscript);
3454 ast_delete(subscript);
3458 return (ast_expression*)ret;
3460 ast_expression *left, *right;
3461 size_t diff = afterend - from;
3462 size_t middle = from + diff/2;
3463 left = array_getter_node(parser, array, index, from, middle);
3464 right = array_getter_node(parser, array, index, middle, afterend);
3465 return array_accessor_split(parser, array, index, middle, left, right);
3469 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3471 ast_function *func = NULL;
3472 ast_value *fval = NULL;
3473 ast_block *body = NULL;
3475 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3477 parseerror(parser, "failed to create accessor function value");
3481 func = ast_function_new(ast_ctx(array), funcname, fval);
3484 parseerror(parser, "failed to create accessor function node");
3488 body = ast_block_new(ast_ctx(array));
3490 parseerror(parser, "failed to create block for array accessor");
3496 vec_push(func->blocks, body);
3499 vec_push(parser->accessors, fval);
3504 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3506 ast_expression *root = NULL;
3507 ast_value *index = NULL;
3508 ast_value *value = NULL;
3512 if (!ast_istype(array->expression.next, ast_value)) {
3513 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3517 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3519 func = fval->constval.vfunc;
3520 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3522 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3523 value = ast_value_copy((ast_value*)array->expression.next);
3525 if (!index || !value) {
3526 parseerror(parser, "failed to create locals for array accessor");
3529 (void)!ast_value_set_name(value, "value"); /* not important */
3530 vec_push(fval->expression.params, index);
3531 vec_push(fval->expression.params, value);
3533 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3535 parseerror(parser, "failed to build accessor search tree");
3539 array->setter = fval;
3540 return ast_block_add_expr(func->blocks[0], root);
3542 if (index) ast_delete(index);
3543 if (value) ast_delete(value);
3544 if (root) ast_delete(root);
3550 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3552 ast_expression *root = NULL;
3553 ast_value *entity = NULL;
3554 ast_value *index = NULL;
3555 ast_value *value = NULL;
3559 if (!ast_istype(array->expression.next, ast_value)) {
3560 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3564 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3566 func = fval->constval.vfunc;
3567 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3569 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3570 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3571 value = ast_value_copy((ast_value*)array->expression.next);
3572 if (!entity || !index || !value) {
3573 parseerror(parser, "failed to create locals for array accessor");
3576 (void)!ast_value_set_name(value, "value"); /* not important */
3577 vec_push(fval->expression.params, entity);
3578 vec_push(fval->expression.params, index);
3579 vec_push(fval->expression.params, value);
3581 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3583 parseerror(parser, "failed to build accessor search tree");
3587 array->setter = fval;
3588 return ast_block_add_expr(func->blocks[0], root);
3590 if (entity) ast_delete(entity);
3591 if (index) ast_delete(index);
3592 if (value) ast_delete(value);
3593 if (root) ast_delete(root);
3599 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3601 ast_expression *root = NULL;
3602 ast_value *index = NULL;
3606 /* NOTE: checking array->expression.next rather than elemtype since
3607 * for fields elemtype is a temporary fieldtype.
3609 if (!ast_istype(array->expression.next, ast_value)) {
3610 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3614 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3616 func = fval->constval.vfunc;
3617 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3619 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3622 parseerror(parser, "failed to create locals for array accessor");
3625 vec_push(fval->expression.params, index);
3627 root = array_getter_node(parser, array, index, 0, array->expression.count);
3629 parseerror(parser, "failed to build accessor search tree");
3633 array->getter = fval;
3634 return ast_block_add_expr(func->blocks[0], root);
3636 if (index) ast_delete(index);
3637 if (root) ast_delete(root);
3643 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3644 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3652 bool variadic = false;
3654 ctx = parser_ctx(parser);
3656 /* for the sake of less code we parse-in in this function */
3657 if (!parser_next(parser)) {
3658 parseerror(parser, "expected parameter list");
3664 /* parse variables until we hit a closing paren */
3665 while (parser->tok != ')') {
3667 /* there must be commas between them */
3668 if (parser->tok != ',') {
3669 parseerror(parser, "expected comma or end of parameter list");
3672 if (!parser_next(parser)) {
3673 parseerror(parser, "expected parameter");
3679 if (parser->tok == TOKEN_DOTS) {
3680 /* '...' indicates a varargs function */
3682 if (!parser_next(parser)) {
3683 parseerror(parser, "expected parameter");
3686 if (parser->tok != ')') {
3687 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3693 /* for anything else just parse a typename */
3694 param = parse_typename(parser, NULL, NULL);
3697 vec_push(params, param);
3698 if (param->expression.vtype >= TYPE_VARIANT) {
3699 char typename[1024];
3700 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3701 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3707 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3711 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3712 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3715 if (!parser_next(parser)) {
3716 parseerror(parser, "parse error after typename");
3720 /* now turn 'var' into a function type */
3721 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3722 fval->expression.next = (ast_expression*)var;
3724 fval->expression.flags |= AST_FLAG_VARIADIC;
3727 var->expression.params = params;
3734 for (i = 0; i < vec_size(params); ++i)
3735 ast_delete(params[i]);
3740 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3742 ast_expression *cexp;
3743 ast_value *cval, *tmp;
3746 ctx = parser_ctx(parser);
3748 if (!parser_next(parser)) {
3750 parseerror(parser, "expected array-size");
3754 cexp = parse_expression_leave(parser, true);
3756 if (!cexp || !ast_istype(cexp, ast_value)) {
3760 parseerror(parser, "expected array-size as constant positive integer");
3763 cval = (ast_value*)cexp;
3765 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3766 tmp->expression.next = (ast_expression*)var;
3769 if (cval->expression.vtype == TYPE_INTEGER)
3770 tmp->expression.count = cval->constval.vint;
3771 else if (cval->expression.vtype == TYPE_FLOAT)
3772 tmp->expression.count = cval->constval.vfloat;
3776 parseerror(parser, "array-size must be a positive integer constant");
3781 if (parser->tok != ']') {
3783 parseerror(parser, "expected ']' after array-size");
3786 if (!parser_next(parser)) {
3788 parseerror(parser, "error after parsing array size");
3794 /* Parse a complete typename.
3795 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3796 * but when parsing variables separated by comma
3797 * 'storebase' should point to where the base-type should be kept.
3798 * The base type makes up every bit of type information which comes *before* the
3801 * The following will be parsed in its entirety:
3803 * The 'basetype' in this case is 'void()'
3804 * and if there's a comma after it, say:
3806 * then the type-information 'void()' can be stored in 'storebase'
3808 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3810 ast_value *var, *tmp;
3813 const char *name = NULL;
3814 bool isfield = false;
3815 bool wasarray = false;
3816 size_t morefields = 0;
3818 ctx = parser_ctx(parser);
3820 /* types may start with a dot */
3821 if (parser->tok == '.') {
3823 /* if we parsed a dot we need a typename now */
3824 if (!parser_next(parser)) {
3825 parseerror(parser, "expected typename for field definition");
3829 /* Further dots are handled seperately because they won't be part of the
3832 while (parser->tok == '.') {
3834 if (!parser_next(parser)) {
3835 parseerror(parser, "expected typename for field definition");
3840 if (parser->tok == TOKEN_IDENT)
3841 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3842 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3843 parseerror(parser, "expected typename");
3847 /* generate the basic type value */
3848 if (cached_typedef) {
3849 var = ast_value_copy(cached_typedef);
3850 ast_value_set_name(var, "<type(from_def)>");
3852 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3854 for (; morefields; --morefields) {
3855 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3856 tmp->expression.next = (ast_expression*)var;
3860 /* do not yet turn into a field - remember:
3861 * .void() foo; is a field too
3862 * .void()() foo; is a function
3866 if (!parser_next(parser)) {
3868 parseerror(parser, "parse error after typename");
3872 /* an opening paren now starts the parameter-list of a function
3873 * this is where original-QC has parameter lists.
3874 * We allow a single parameter list here.
3875 * Much like fteqcc we don't allow `float()() x`
3877 if (parser->tok == '(') {
3878 var = parse_parameter_list(parser, var);
3883 /* store the base if requested */
3885 *storebase = ast_value_copy(var);
3887 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3888 tmp->expression.next = (ast_expression*)*storebase;
3893 /* there may be a name now */
3894 if (parser->tok == TOKEN_IDENT) {
3895 name = util_strdup(parser_tokval(parser));
3897 if (!parser_next(parser)) {
3899 parseerror(parser, "error after variable or field declaration");
3904 /* now this may be an array */
3905 if (parser->tok == '[') {
3907 var = parse_arraysize(parser, var);
3912 /* This is the point where we can turn it into a field */
3914 /* turn it into a field if desired */
3915 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3916 tmp->expression.next = (ast_expression*)var;
3920 /* now there may be function parens again */
3921 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3922 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3923 if (parser->tok == '(' && wasarray)
3924 parseerror(parser, "arrays as part of a return type is not supported");
3925 while (parser->tok == '(') {
3926 var = parse_parameter_list(parser, var);
3935 /* finally name it */
3937 if (!ast_value_set_name(var, name)) {
3939 parseerror(parser, "internal error: failed to set name");
3942 /* free the name, ast_value_set_name duplicates */
3949 static bool parse_typedef(parser_t *parser)
3951 ast_value *typevar, *oldtype;
3952 ast_expression *old;
3954 typevar = parse_typename(parser, NULL, NULL);
3959 if ( (old = parser_find_var(parser, typevar->name)) ) {
3960 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3961 " -> `%s` has been declared here: %s:%i",
3962 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3963 ast_delete(typevar);
3967 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3968 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3969 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3970 ast_delete(typevar);
3974 vec_push(parser->_typedefs, typevar);
3975 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3977 if (parser->tok != ';') {
3978 parseerror(parser, "expected semicolon after typedef");
3981 if (!parser_next(parser)) {
3982 parseerror(parser, "parse error after typedef");
3989 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn)
3993 ast_expression *old;
3997 ast_value *basetype = NULL;
3999 bool isparam = false;
4000 bool isvector = false;
4001 bool cleanvar = true;
4002 bool wasarray = false;
4006 /* get the first complete variable */
4007 var = parse_typename(parser, &basetype, cached_typedef);
4010 ast_delete(basetype);
4018 /* Part 0: finish the type */
4019 if (parser->tok == '(') {
4020 if (opts.standard == COMPILER_QCC)
4021 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4022 var = parse_parameter_list(parser, var);
4028 /* we only allow 1-dimensional arrays */
4029 if (parser->tok == '[') {
4031 var = parse_arraysize(parser, var);
4037 if (parser->tok == '(' && wasarray) {
4038 parseerror(parser, "arrays as part of a return type is not supported");
4039 /* we'll still parse the type completely for now */
4041 /* for functions returning functions */
4042 while (parser->tok == '(') {
4043 if (opts.standard == COMPILER_QCC)
4044 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4045 var = parse_parameter_list(parser, var);
4052 var->cvq = qualifier;
4053 /* in a noref section we simply bump the usecount */
4054 if (noref || parser->noref)
4057 var->expression.flags |= AST_FLAG_NORETURN;
4060 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4061 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4062 * is then filled with the previous definition and the parameter-names replaced.
4065 /* Deal with end_sys_ vars */
4067 if (!strcmp(var->name, "end_sys_globals")) {
4069 parser->crc_globals = vec_size(parser->globals);
4072 else if (!strcmp(var->name, "end_sys_fields")) {
4074 parser->crc_fields = vec_size(parser->fields);
4077 if (was_end && var->expression.vtype == TYPE_FIELD) {
4078 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4079 "global '%s' hint should not be a field",
4080 parser_tokval(parser)))
4087 if (!nofields && var->expression.vtype == TYPE_FIELD)
4089 /* deal with field declarations */
4090 old = parser_find_field(parser, var->name);
4092 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4093 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4102 parseerror(parser, "field `%s` already declared here: %s:%i",
4103 var->name, ast_ctx(old).file, ast_ctx(old).line);
4108 if (opts.standard == COMPILER_QCC &&
4109 (old = parser_find_global(parser, var->name)))
4111 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4112 parseerror(parser, "field `%s` already declared here: %s:%i",
4113 var->name, ast_ctx(old).file, ast_ctx(old).line);
4120 /* deal with other globals */
4121 old = parser_find_global(parser, var->name);
4122 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4124 /* This is a function which had a prototype */
4125 if (!ast_istype(old, ast_value)) {
4126 parseerror(parser, "internal error: prototype is not an ast_value");
4130 proto = (ast_value*)old;
4131 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4132 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4134 ast_ctx(proto).file, ast_ctx(proto).line);
4138 /* we need the new parameter-names */
4139 for (i = 0; i < vec_size(proto->expression.params); ++i)
4140 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4148 if (opts.standard == COMPILER_GMQCC) {
4149 parseerror(parser, "global `%s` already declared here: %s:%i",
4150 var->name, ast_ctx(old).file, ast_ctx(old).line);
4154 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4155 "global `%s` already declared here: %s:%i",
4156 var->name, ast_ctx(old).file, ast_ctx(old).line))
4161 proto = (ast_value*)old;
4162 if (!ast_istype(old, ast_value)) {
4163 parseerror(parser, "internal error: not an ast_value");
4172 if (opts.standard == COMPILER_QCC &&
4173 (old = parser_find_field(parser, var->name)))
4175 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4176 parseerror(parser, "global `%s` already declared here: %s:%i",
4177 var->name, ast_ctx(old).file, ast_ctx(old).line);
4184 else /* it's not a global */
4186 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4187 if (old && !isparam) {
4188 parseerror(parser, "local `%s` already declared here: %s:%i",
4189 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4193 old = parser_find_local(parser, var->name, 0, &isparam);
4194 if (old && isparam) {
4195 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4196 "local `%s` is shadowing a parameter", var->name))
4198 parseerror(parser, "local `%s` already declared here: %s:%i",
4199 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4203 if (opts.standard != COMPILER_GMQCC) {
4212 * Create the global/local, and deal with vector types.
4215 if (var->expression.vtype == TYPE_VECTOR)
4217 else if (var->expression.vtype == TYPE_FIELD &&
4218 var->expression.next->expression.vtype == TYPE_VECTOR)
4222 if (!create_vector_members(var, me)) {
4229 /* deal with global variables, fields, functions */
4230 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4231 var->isfield = true;
4232 vec_push(parser->fields, (ast_expression*)var);
4233 util_htset(parser->htfields, var->name, var);
4235 for (i = 0; i < 3; ++i) {
4236 vec_push(parser->fields, (ast_expression*)me[i]);
4237 util_htset(parser->htfields, me[i]->name, me[i]);
4242 vec_push(parser->globals, (ast_expression*)var);
4243 util_htset(parser->htglobals, var->name, var);
4245 for (i = 0; i < 3; ++i) {
4246 vec_push(parser->globals, (ast_expression*)me[i]);
4247 util_htset(parser->htglobals, me[i]->name, me[i]);
4252 vec_push(localblock->locals, var);
4253 parser_addlocal(parser, var->name, (ast_expression*)var);
4255 for (i = 0; i < 3; ++i) {
4256 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4257 ast_block_collect(localblock, (ast_expression*)me[i]);
4263 me[0] = me[1] = me[2] = NULL;
4268 if (var->expression.vtype == TYPE_ARRAY) {
4270 snprintf(name, sizeof(name), "%s##SET", var->name);
4271 if (!parser_create_array_setter(parser, var, name))
4273 snprintf(name, sizeof(name), "%s##GET", var->name);
4274 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4277 else if (!localblock && !nofields &&
4278 var->expression.vtype == TYPE_FIELD &&
4279 var->expression.next->expression.vtype == TYPE_ARRAY)
4282 ast_expression *telem;
4284 ast_value *array = (ast_value*)var->expression.next;
4286 if (!ast_istype(var->expression.next, ast_value)) {
4287 parseerror(parser, "internal error: field element type must be an ast_value");
4291 snprintf(name, sizeof(name), "%s##SETF", var->name);
4292 if (!parser_create_array_field_setter(parser, array, name))
4295 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4296 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4297 tfield->expression.next = telem;
4298 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4299 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4307 if (parser->tok == ';') {
4308 ast_delete(basetype);
4309 if (!parser_next(parser)) {
4310 parseerror(parser, "error after variable declaration");
4316 if (parser->tok == ',')
4320 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4323 parseerror(parser, "missing comma or semicolon while parsing variables");
4327 if (localblock && opts.standard == COMPILER_QCC) {
4328 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4329 "initializing expression turns variable `%s` into a constant in this standard",
4336 if (parser->tok != '{') {
4337 if (parser->tok != '=') {
4338 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4342 if (!parser_next(parser)) {
4343 parseerror(parser, "error parsing initializer");
4347 else if (opts.standard == COMPILER_QCC) {
4348 parseerror(parser, "expected '=' before function body in this standard");
4351 if (parser->tok == '#') {
4352 ast_function *func = NULL;
4355 parseerror(parser, "cannot declare builtins within functions");
4358 if (var->expression.vtype != TYPE_FUNCTION) {
4359 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4362 if (!parser_next(parser)) {
4363 parseerror(parser, "expected builtin number");
4366 if (parser->tok != TOKEN_INTCONST) {
4367 parseerror(parser, "builtin number must be an integer constant");
4370 if (parser_token(parser)->constval.i < 0) {
4371 parseerror(parser, "builtin number must be an integer greater than zero");
4375 if (var->hasvalue) {
4376 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4377 "builtin `%s` has already been defined\n"
4378 " -> previous declaration here: %s:%i",
4379 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4383 func = ast_function_new(ast_ctx(var), var->name, var);
4385 parseerror(parser, "failed to allocate function for `%s`", var->name);
4388 vec_push(parser->functions, func);
4390 func->builtin = -parser_token(parser)->constval.i-1;
4393 if (!parser_next(parser)) {
4394 parseerror(parser, "expected comma or semicolon");
4396 ast_function_delete(func);
4397 var->constval.vfunc = NULL;
4401 else if (parser->tok == '{' || parser->tok == '[')
4404 parseerror(parser, "cannot declare functions within functions");
4409 ast_ctx(proto) = parser_ctx(parser);
4411 if (!parse_function_body(parser, var))
4413 ast_delete(basetype);
4414 for (i = 0; i < vec_size(parser->gotos); ++i)
4415 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4416 vec_free(parser->gotos);
4417 vec_free(parser->labels);
4420 ast_expression *cexp;
4423 cexp = parse_expression_leave(parser, true);
4428 cval = (ast_value*)cexp;
4429 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4430 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4433 if (opts.standard != COMPILER_GMQCC &&
4434 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4435 qualifier != CV_VAR)
4437 var->cvq = CV_CONST;
4439 var->hasvalue = true;
4440 if (cval->expression.vtype == TYPE_STRING)
4441 var->constval.vstring = parser_strdup(cval->constval.vstring);
4442 else if (cval->expression.vtype == TYPE_FIELD)
4443 var->constval.vfield = cval;
4445 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4450 shunt sy = { NULL, NULL };
4453 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4454 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4455 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4456 if (!parser_sy_apply_operator(parser, &sy))
4459 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4460 parseerror(parser, "internal error: leaked operands");
4461 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4471 if (parser->tok == ',') {
4472 if (!parser_next(parser)) {
4473 parseerror(parser, "expected another variable");
4477 if (parser->tok != TOKEN_IDENT) {
4478 parseerror(parser, "expected another variable");
4481 var = ast_value_copy(basetype);
4483 ast_value_set_name(var, parser_tokval(parser));
4484 if (!parser_next(parser)) {
4485 parseerror(parser, "error parsing variable declaration");
4491 if (parser->tok != ';') {
4492 parseerror(parser, "missing semicolon after variables");
4496 if (!parser_next(parser)) {
4497 parseerror(parser, "parse error after variable declaration");
4501 ast_delete(basetype);
4505 if (cleanvar && var)
4507 ast_delete(basetype);
4511 ast_delete(basetype);
4512 if (cleanvar && var)
4514 if (me[0]) ast_member_delete(me[0]);
4515 if (me[1]) ast_member_delete(me[1]);
4516 if (me[2]) ast_member_delete(me[2]);
4520 static bool parser_global_statement(parser_t *parser)
4524 bool noreturn = false;
4525 ast_value *istype = NULL;
4527 if (parser->tok == TOKEN_IDENT)
4528 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4530 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4532 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false);
4534 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn))
4536 if (cvq == CV_WRONG)
4538 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn);
4540 else if (parser->tok == TOKEN_KEYWORD)
4542 if (!strcmp(parser_tokval(parser), "typedef")) {
4543 if (!parser_next(parser)) {
4544 parseerror(parser, "expected type definition after 'typedef'");
4547 return parse_typedef(parser);
4549 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4552 else if (parser->tok == '#')
4554 return parse_pragma(parser);
4556 else if (parser->tok == '$')
4558 if (!parser_next(parser)) {
4559 parseerror(parser, "parse error");
4565 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4571 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4573 return util_crc16(old, str, strlen(str));
4576 static void progdefs_crc_file(const char *str)
4578 /* write to progdefs.h here */
4582 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4584 old = progdefs_crc_sum(old, str);
4585 progdefs_crc_file(str);
4589 static void generate_checksum(parser_t *parser)
4591 uint16_t crc = 0xFFFF;
4595 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4596 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4598 progdefs_crc_file("\tint\tpad;\n");
4599 progdefs_crc_file("\tint\tofs_return[3];\n");
4600 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4601 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4602 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4603 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4604 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4605 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4606 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4607 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4609 for (i = 0; i < parser->crc_globals; ++i) {
4610 if (!ast_istype(parser->globals[i], ast_value))
4612 value = (ast_value*)(parser->globals[i]);
4613 switch (value->expression.vtype) {
4614 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4615 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4616 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4617 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4619 crc = progdefs_crc_both(crc, "\tint\t");
4622 crc = progdefs_crc_both(crc, value->name);
4623 crc = progdefs_crc_both(crc, ";\n");
4625 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4626 for (i = 0; i < parser->crc_fields; ++i) {
4627 if (!ast_istype(parser->fields[i], ast_value))
4629 value = (ast_value*)(parser->fields[i]);
4630 switch (value->expression.next->expression.vtype) {
4631 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4632 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4633 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4634 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4636 crc = progdefs_crc_both(crc, "\tint\t");
4639 crc = progdefs_crc_both(crc, value->name);
4640 crc = progdefs_crc_both(crc, ";\n");
4642 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4647 static parser_t *parser;
4653 parser = (parser_t*)mem_a(sizeof(parser_t));
4657 memset(parser, 0, sizeof(*parser));
4659 for (i = 0; i < operator_count; ++i) {
4660 if (operators[i].id == opid1('=')) {
4661 parser->assign_op = operators+i;
4665 if (!parser->assign_op) {
4666 printf("internal error: initializing parser: failed to find assign operator\n");
4671 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4672 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4673 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4674 vec_push(parser->_blocktypedefs, 0);
4678 bool parser_compile()
4680 /* initial lexer/parser state */
4681 parser->lex->flags.noops = true;
4683 if (parser_next(parser))
4685 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4687 if (!parser_global_statement(parser)) {
4688 if (parser->tok == TOKEN_EOF)
4689 parseerror(parser, "unexpected eof");
4690 else if (!parser->errors)
4691 parseerror(parser, "there have been errors, bailing out");
4692 lex_close(parser->lex);
4698 parseerror(parser, "parse error");
4699 lex_close(parser->lex);
4704 lex_close(parser->lex);
4707 return !parser->errors;
4710 bool parser_compile_file(const char *filename)
4712 parser->lex = lex_open(filename);
4714 con_err("failed to open file \"%s\"\n", filename);
4717 return parser_compile();
4720 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4722 parser->lex = lex_open_string(str, len, name);
4724 con_err("failed to create lexer for string \"%s\"\n", name);
4727 return parser_compile();
4730 bool parser_compile_string(const char *name, const char *str)
4732 parser->lex = lex_open_string(str, strlen(str), name);
4734 con_err("failed to create lexer for string \"%s\"\n", name);
4737 return parser_compile();
4740 void parser_cleanup()
4743 for (i = 0; i < vec_size(parser->accessors); ++i) {
4744 ast_delete(parser->accessors[i]->constval.vfunc);
4745 parser->accessors[i]->constval.vfunc = NULL;
4746 ast_delete(parser->accessors[i]);
4748 for (i = 0; i < vec_size(parser->functions); ++i) {
4749 ast_delete(parser->functions[i]);
4751 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4752 ast_delete(parser->imm_vector[i]);
4754 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4755 ast_delete(parser->imm_string[i]);
4757 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4758 ast_delete(parser->imm_float[i]);
4760 for (i = 0; i < vec_size(parser->fields); ++i) {
4761 ast_delete(parser->fields[i]);
4763 for (i = 0; i < vec_size(parser->globals); ++i) {
4764 ast_delete(parser->globals[i]);
4766 vec_free(parser->accessors);
4767 vec_free(parser->functions);
4768 vec_free(parser->imm_vector);
4769 vec_free(parser->imm_string);
4770 vec_free(parser->imm_float);
4771 vec_free(parser->globals);
4772 vec_free(parser->fields);
4774 for (i = 0; i < vec_size(parser->variables); ++i)
4775 util_htdel(parser->variables[i]);
4776 vec_free(parser->variables);
4777 vec_free(parser->_blocklocals);
4778 vec_free(parser->_locals);
4780 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4781 ast_delete(parser->_typedefs[i]);
4782 vec_free(parser->_typedefs);
4783 for (i = 0; i < vec_size(parser->typedefs); ++i)
4784 util_htdel(parser->typedefs[i]);
4785 vec_free(parser->typedefs);
4786 vec_free(parser->_blocktypedefs);
4788 vec_free(parser->_block_ctx);
4790 vec_free(parser->labels);
4791 vec_free(parser->gotos);
4796 bool parser_finish(const char *output)
4802 if (!parser->errors)
4804 ir = ir_builder_new("gmqcc_out");
4806 con_out("failed to allocate builder\n");
4810 for (i = 0; i < vec_size(parser->fields); ++i) {
4813 if (!ast_istype(parser->fields[i], ast_value))
4815 field = (ast_value*)parser->fields[i];
4816 hasvalue = field->hasvalue;
4817 field->hasvalue = false;
4818 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4819 con_out("failed to generate field %s\n", field->name);
4820 ir_builder_delete(ir);
4825 ast_expression *subtype;
4826 field->hasvalue = true;
4827 subtype = field->expression.next;
4828 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4829 if (subtype->expression.vtype == TYPE_FIELD)
4830 ifld->fieldtype = subtype->expression.next->expression.vtype;
4831 else if (subtype->expression.vtype == TYPE_FUNCTION)
4832 ifld->outtype = subtype->expression.next->expression.vtype;
4833 (void)!ir_value_set_field(field->ir_v, ifld);
4836 for (i = 0; i < vec_size(parser->globals); ++i) {
4838 if (!ast_istype(parser->globals[i], ast_value))
4840 asvalue = (ast_value*)(parser->globals[i]);
4841 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4842 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4843 "unused global: `%s`", asvalue->name);
4845 if (!ast_global_codegen(asvalue, ir, false)) {
4846 con_out("failed to generate global %s\n", asvalue->name);
4847 ir_builder_delete(ir);
4851 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4852 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4853 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4854 ir_builder_delete(ir);
4858 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4859 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4860 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4861 ir_builder_delete(ir);
4865 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4866 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4867 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4868 ir_builder_delete(ir);
4872 for (i = 0; i < vec_size(parser->globals); ++i) {
4874 if (!ast_istype(parser->globals[i], ast_value))
4876 asvalue = (ast_value*)(parser->globals[i]);
4877 if (!ast_generate_accessors(asvalue, ir)) {
4878 ir_builder_delete(ir);
4882 for (i = 0; i < vec_size(parser->fields); ++i) {
4884 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4886 if (!ast_istype((ast_expression*)asvalue, ast_value))
4888 if (asvalue->expression.vtype != TYPE_ARRAY)
4890 if (!ast_generate_accessors(asvalue, ir)) {
4891 ir_builder_delete(ir);
4895 for (i = 0; i < vec_size(parser->functions); ++i) {
4896 if (!ast_function_codegen(parser->functions[i], ir)) {
4897 con_out("failed to generate function %s\n", parser->functions[i]->name);
4898 ir_builder_delete(ir);
4903 ir_builder_dump(ir, con_out);
4904 for (i = 0; i < vec_size(parser->functions); ++i) {
4905 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4906 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4907 ir_builder_delete(ir);
4914 ir_builder_dump(ir, con_out);
4916 generate_checksum(parser);
4918 if (!ir_builder_generate(ir, output)) {
4919 con_out("*** failed to generate output file\n");
4920 ir_builder_delete(ir);
4925 ir_builder_delete(ir);
4929 con_out("*** there were compile errors\n");