6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 /* beginning of locals */
31 #define PARSER_HT_LOCALS 2
33 #define PARSER_HT_SIZE 1024
34 #define TYPEDEF_HT_SIZE 16
36 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
60 ast_function *function;
62 /* All the labels the function defined...
63 * Should they be in ast_function instead?
68 const char **continues;
70 /* A list of hashtables for each scope */
76 /* not to be used directly, we use the hash table */
77 ast_expression **_locals;
79 ast_value **_typedefs;
80 size_t *_blocktypedefs;
83 /* we store the '=' operator info */
84 const oper_info *assign_op;
86 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
87 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
88 * anything else: type error
92 /* Keep track of our ternary vs parenthesis nesting state.
93 * If we reach a 'comma' operator in a ternary without a paren,
94 * we shall trigger -Wternary-precedence.
102 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
104 static void parser_enterblock(parser_t *parser);
105 static bool parser_leaveblock(parser_t *parser);
106 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
107 static bool parse_typedef(parser_t *parser);
108 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
109 static ast_block* parse_block(parser_t *parser);
110 static bool parse_block_into(parser_t *parser, ast_block *block);
111 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
112 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
113 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue);
114 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
116 static void parseerror(parser_t *parser, const char *fmt, ...)
120 vcompile_error(parser->lex->tok.ctx, 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 = (char*)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 ( ast_expression*)util_htget(parser->htfields, name);
302 static ast_expression* parser_find_global(parser_t *parser, const char *name)
304 return (ast_expression*)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 = (ast_expression*)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[1]->expression.vtype == TYPE_FLOAT) &&
766 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
767 exprs[0]->expression.vtype == TYPE_FLOAT)
770 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
771 type_name[exprs[1]->expression.vtype],
772 type_name[exprs[0]->expression.vtype]);
775 switch (exprs[0]->expression.vtype) {
777 if (exprs[1]->expression.vtype == TYPE_VECTOR)
779 if (CanConstFold(exprs[0], exprs[1]))
780 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
782 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
786 if (CanConstFold(exprs[0], exprs[1]))
787 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
789 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
793 if (exprs[1]->expression.vtype == TYPE_FLOAT)
795 if (CanConstFold(exprs[0], exprs[1]))
796 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
798 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
802 if (CanConstFold(exprs[0], exprs[1]))
803 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
804 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
805 vector vec = ConstV(0);
806 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
807 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
808 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
809 out->expression.node.keep = false;
810 ((ast_member*)out)->rvalue = true;
812 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
814 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
815 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
816 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
817 out->expression.node.keep = false;
818 ((ast_member*)out)->rvalue = true;
820 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
822 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
823 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
824 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
825 out->expression.node.keep = false;
826 ((ast_member*)out)->rvalue = true;
828 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
831 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
833 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
834 vector vec = ConstV(1);
835 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
836 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
837 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
838 out->expression.node.keep = false;
839 ((ast_member*)out)->rvalue = true;
841 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
843 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
844 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
845 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
846 out->expression.node.keep = false;
847 ((ast_member*)out)->rvalue = true;
849 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
851 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
852 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
853 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
854 out->expression.node.keep = false;
855 ((ast_member*)out)->rvalue = true;
857 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
860 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
863 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
867 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
868 type_name[exprs[1]->expression.vtype],
869 type_name[exprs[0]->expression.vtype]);
874 if (NotSameType(TYPE_FLOAT)) {
875 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
876 type_name[exprs[0]->expression.vtype],
877 type_name[exprs[1]->expression.vtype]);
880 if (CanConstFold(exprs[0], exprs[1]))
881 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
883 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
887 parseerror(parser, "qc does not have a modulo operator");
891 if (NotSameType(TYPE_FLOAT)) {
892 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
893 type_name[exprs[0]->expression.vtype],
894 type_name[exprs[1]->expression.vtype]);
897 if (CanConstFold(exprs[0], exprs[1]))
898 out = (ast_expression*)parser_const_float(parser,
899 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
900 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
902 out = (ast_expression*)ast_binary_new(ctx,
903 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
907 parseerror(parser, "TODO: bitxor");
912 case opid3('<','<','='):
913 case opid3('>','>','='):
914 parseerror(parser, "TODO: shifts");
918 generated_op += 1; /* INSTR_OR */
920 generated_op += INSTR_AND;
922 if (NotSameType(TYPE_FLOAT)) {
923 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
924 type_name[exprs[0]->expression.vtype],
925 type_name[exprs[1]->expression.vtype]);
926 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
927 parseerror(parser, "TODO: optional early out");
931 if (CanConstFold(exprs[0], exprs[1]))
933 if (OPTS_FLAG(PERL_LOGIC)) {
934 if (immediate_is_true(ctx, asvalue[0]))
938 out = (ast_expression*)parser_const_float(parser,
939 ( (generated_op == INSTR_OR)
940 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
941 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
946 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
947 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
948 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
949 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
952 for (i = 0; i < 2; ++i) {
953 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
954 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
956 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
958 exprs[i] = out; out = NULL;
959 if (OPTS_FLAG(PERL_LOGIC)) {
960 /* here we want to keep the right expressions' type */
964 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
965 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
967 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
969 exprs[i] = out; out = NULL;
970 if (OPTS_FLAG(PERL_LOGIC)) {
971 /* here we want to keep the right expressions' type */
976 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
981 if (vec_last(parser->pot) != POT_TERNARY2) {
982 parseerror(parser, "mismatched parenthesis/ternary");
985 vec_pop(parser->pot);
986 if (!ast_compare_type(exprs[1], exprs[2])) {
987 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
988 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
989 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
992 if (CanConstFold1(exprs[0]))
993 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
995 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
999 generated_op += 1; /* INSTR_GT */
1001 generated_op += 1; /* INSTR_LT */
1002 case opid2('>', '='):
1003 generated_op += 1; /* INSTR_GE */
1004 case opid2('<', '='):
1005 generated_op += INSTR_LE;
1006 if (NotSameType(TYPE_FLOAT)) {
1007 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1008 type_name[exprs[0]->expression.vtype],
1009 type_name[exprs[1]->expression.vtype]);
1012 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1014 case opid2('!', '='):
1015 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1016 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1017 type_name[exprs[0]->expression.vtype],
1018 type_name[exprs[1]->expression.vtype]);
1021 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1023 case opid2('=', '='):
1024 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1025 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1026 type_name[exprs[0]->expression.vtype],
1027 type_name[exprs[1]->expression.vtype]);
1030 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1034 if (ast_istype(exprs[0], ast_entfield)) {
1035 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1036 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1037 exprs[0]->expression.vtype == TYPE_FIELD &&
1038 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1040 assignop = type_storep_instr[TYPE_VECTOR];
1043 assignop = type_storep_instr[exprs[0]->expression.vtype];
1044 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1046 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1047 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1048 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1049 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1050 exprs[1]->expression.vtype == TYPE_FUNCTION)
1052 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1053 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1056 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1061 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1062 exprs[0]->expression.vtype == TYPE_FIELD &&
1063 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1065 assignop = type_store_instr[TYPE_VECTOR];
1068 assignop = type_store_instr[exprs[0]->expression.vtype];
1071 if (assignop == AINSTR_END) {
1072 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1073 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1074 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1076 else if (!ast_compare_type(exprs[0], exprs[1]))
1078 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1079 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1081 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1082 exprs[1]->expression.vtype == TYPE_FUNCTION)
1084 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1085 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1088 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1091 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1092 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1094 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1096 case opid3('+','+','P'):
1097 case opid3('-','-','P'):
1099 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1100 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1101 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1104 if (op->id == opid3('+','+','P'))
1105 addop = INSTR_ADD_F;
1107 addop = INSTR_SUB_F;
1108 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1109 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1111 if (ast_istype(exprs[0], ast_entfield)) {
1112 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1114 (ast_expression*)parser_const_float_1(parser));
1116 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1118 (ast_expression*)parser_const_float_1(parser));
1121 case opid3('S','+','+'):
1122 case opid3('S','-','-'):
1124 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1125 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1126 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1129 if (op->id == opid3('S','+','+')) {
1130 addop = INSTR_ADD_F;
1131 subop = INSTR_SUB_F;
1133 addop = INSTR_SUB_F;
1134 subop = INSTR_ADD_F;
1136 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1137 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1139 if (ast_istype(exprs[0], ast_entfield)) {
1140 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1142 (ast_expression*)parser_const_float_1(parser));
1144 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1146 (ast_expression*)parser_const_float_1(parser));
1150 out = (ast_expression*)ast_binary_new(ctx, subop,
1152 (ast_expression*)parser_const_float_1(parser));
1154 case opid2('+','='):
1155 case opid2('-','='):
1156 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1157 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1159 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1160 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1161 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1165 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1166 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1168 if (ast_istype(exprs[0], ast_entfield))
1169 assignop = type_storep_instr[exprs[0]->expression.vtype];
1171 assignop = type_store_instr[exprs[0]->expression.vtype];
1172 switch (exprs[0]->expression.vtype) {
1174 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1175 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1176 exprs[0], exprs[1]);
1179 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1180 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1181 exprs[0], exprs[1]);
1184 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1185 type_name[exprs[0]->expression.vtype],
1186 type_name[exprs[1]->expression.vtype]);
1190 case opid2('*','='):
1191 case opid2('/','='):
1192 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1193 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1194 exprs[0]->expression.vtype == TYPE_VECTOR))
1196 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1197 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1198 parseerror(parser, "invalid types used in expression: %s and %s",
1202 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1203 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1205 if (ast_istype(exprs[0], ast_entfield))
1206 assignop = type_storep_instr[exprs[0]->expression.vtype];
1208 assignop = type_store_instr[exprs[0]->expression.vtype];
1209 switch (exprs[0]->expression.vtype) {
1211 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1212 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1213 exprs[0], exprs[1]);
1216 if (op->id == opid2('*','=')) {
1217 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1218 exprs[0], exprs[1]);
1220 /* there's no DIV_VF */
1221 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1222 (ast_expression*)parser_const_float_1(parser),
1226 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1231 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1232 type_name[exprs[0]->expression.vtype],
1233 type_name[exprs[1]->expression.vtype]);
1237 case opid2('&','='):
1238 case opid2('|','='):
1239 if (NotSameType(TYPE_FLOAT)) {
1240 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1241 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1242 parseerror(parser, "invalid types used in expression: %s and %s",
1246 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1247 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1249 if (ast_istype(exprs[0], ast_entfield))
1250 assignop = type_storep_instr[exprs[0]->expression.vtype];
1252 assignop = type_store_instr[exprs[0]->expression.vtype];
1253 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1254 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1255 exprs[0], exprs[1]);
1257 case opid3('&','~','='):
1258 /* This is like: a &= ~(b);
1259 * But QC has no bitwise-not, so we implement it as
1262 if (NotSameType(TYPE_FLOAT)) {
1263 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1264 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1265 parseerror(parser, "invalid types used in expression: %s and %s",
1269 if (ast_istype(exprs[0], ast_entfield))
1270 assignop = type_storep_instr[exprs[0]->expression.vtype];
1272 assignop = type_store_instr[exprs[0]->expression.vtype];
1273 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1276 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1277 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1279 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1280 asbinstore->keep_dest = true;
1281 out = (ast_expression*)asbinstore;
1287 parseerror(parser, "failed to apply operand %s", op->op);
1291 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1292 vec_push(sy->out, syexp(ctx, out));
1296 static bool parser_close_call(parser_t *parser, shunt *sy)
1298 /* was a function call */
1299 ast_expression *fun;
1305 vec_shrinkby(sy->ops, 1);
1306 fid = sy->ops[vec_size(sy->ops)].off;
1308 /* out[fid] is the function
1309 * everything above is parameters...
1310 * 0 params = nothing
1311 * 1 params = ast_expression
1315 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1316 parseerror(parser, "internal error: function call needs function and parameter list...");
1320 fun = sy->out[fid].out;
1322 if (fun == intrinsic_debug_typestring) {
1324 if (fid+2 != vec_size(sy->out) ||
1325 vec_last(sy->out).block)
1327 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1330 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1331 ast_unref(vec_last(sy->out).out);
1332 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1333 (ast_expression*)parser_const_string(parser, ty, false));
1334 vec_shrinkby(sy->out, 1);
1338 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1340 parseerror(parser, "internal error: failed to create ast_call node");
1344 if (fid+1 == vec_size(sy->out)) {
1347 } else if (fid+2 == vec_size(sy->out)) {
1349 vec_shrinkby(sy->out, 1);
1350 params = sy->out[vec_size(sy->out)].block;
1354 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1356 paramcount = vec_size(params->exprs);
1357 call->params = params->exprs;
1358 params->exprs = NULL;
1361 (void)!ast_call_check_types(call);
1363 parseerror(parser, "invalid function call");
1367 /* overwrite fid, the function, with a call */
1368 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1370 if (fun->expression.vtype != TYPE_FUNCTION) {
1371 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1375 if (!fun->expression.next) {
1376 parseerror(parser, "could not determine function return type");
1379 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1381 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1383 return !parsewarning(parser, WARN_DEPRECATED,
1384 "call to function (which is marked deprecated)\n",
1385 "-> it has been declared here: %s:%i",
1386 ast_ctx(fun).file, ast_ctx(fun).line);
1389 return !parsewarning(parser, WARN_DEPRECATED,
1390 "call to `%s` (which is marked deprecated)\n"
1391 "-> `%s` declared here: %s:%i",
1392 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1394 return !parsewarning(parser, WARN_DEPRECATED,
1395 "call to `%s` (deprecated: %s)\n"
1396 "-> `%s` declared here: %s:%i",
1397 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1401 if (vec_size(fun->expression.params) != paramcount &&
1402 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1403 vec_size(fun->expression.params) < paramcount))
1405 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1407 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1408 "too %s parameters for call to %s: expected %i, got %i\n"
1409 " -> `%s` has been declared here: %s:%i",
1410 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1411 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1413 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1414 "too %s parameters for function call: expected %i, got %i\n"
1415 " -> it has been declared here: %s:%i",
1416 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1417 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1424 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1426 if (!vec_size(sy->ops)) {
1427 parseerror(parser, "unmatched closing paren");
1430 /* this would for bit a + (x) because there are no operators inside (x)
1431 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1432 parseerror(parser, "empty parenthesis expression");
1436 while (vec_size(sy->ops)) {
1437 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1438 if (!parser_close_call(parser, sy))
1442 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1443 vec_shrinkby(sy->ops, 1);
1444 return !functions_only;
1446 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1449 /* pop off the parenthesis */
1450 vec_shrinkby(sy->ops, 1);
1451 /* then apply the index operator */
1452 if (!parser_sy_apply_operator(parser, sy))
1456 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1459 if (vec_last(parser->pot) != POT_TERNARY1) {
1460 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1463 vec_last(parser->pot) = POT_TERNARY2;
1464 /* pop off the parenthesis */
1465 vec_shrinkby(sy->ops, 1);
1468 if (!parser_sy_apply_operator(parser, sy))
1474 static void parser_reclassify_token(parser_t *parser)
1477 for (i = 0; i < operator_count; ++i) {
1478 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1479 parser->tok = TOKEN_OPERATOR;
1485 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue)
1487 ast_expression *expr = NULL;
1489 bool wantop = false;
1490 bool gotmemberof = false;
1491 /* only warn once about an assignment in a truth value because the current code
1492 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1494 bool warn_truthvalue = true;
1496 /* count the parens because an if starts with one, so the
1497 * end of a condition is an unmatched closing paren
1505 parser->lex->flags.noops = false;
1507 parser_reclassify_token(parser);
1512 gotmemberof = false;
1514 parser->memberof = 0;
1516 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1517 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1519 /* a translatable string */
1523 parseerror(parser, "expected operator or end of statement, got constant");
1527 parser->lex->flags.noops = true;
1528 if (!parser_next(parser) || parser->tok != '(') {
1529 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1532 parser->lex->flags.noops = false;
1533 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1534 parseerror(parser, "expected a constant string in translatable-string extension");
1537 val = parser_const_string(parser, parser_tokval(parser), true);
1541 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1542 DEBUGSHUNTDO(con_out("push string\n"));
1544 if (!parser_next(parser) || parser->tok != ')') {
1545 parseerror(parser, "expected closing paren after translatable string");
1549 else if (parser->tok == TOKEN_IDENT)
1551 ast_expression *var;
1553 parseerror(parser, "expected operator or end of statement");
1558 if (opts.standard == COMPILER_GMQCC)
1560 if (parser->memberof == TYPE_ENTITY) {
1561 /* still get vars first since there could be a fieldpointer */
1562 var = parser_find_var(parser, parser_tokval(parser));
1564 var = parser_find_field(parser, parser_tokval(parser));
1566 else if (parser->memberof == TYPE_VECTOR)
1568 parseerror(parser, "TODO: implement effective vector member access");
1571 else if (parser->memberof) {
1572 parseerror(parser, "namespace for member not found");
1576 var = parser_find_var(parser, parser_tokval(parser));
1578 var = parser_find_var(parser, parser_tokval(parser));
1580 var = parser_find_field(parser, parser_tokval(parser));
1584 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1585 var = (ast_expression*)intrinsic_debug_typestring;
1590 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1596 if (ast_istype(var, ast_value)) {
1597 ((ast_value*)var)->uses++;
1599 else if (ast_istype(var, ast_member)) {
1600 ast_member *mem = (ast_member*)var;
1601 if (ast_istype(mem->owner, ast_value))
1602 ((ast_value*)(mem->owner))->uses++;
1605 vec_push(sy.out, syexp(parser_ctx(parser), var));
1606 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1608 else if (parser->tok == TOKEN_FLOATCONST) {
1611 parseerror(parser, "expected operator or end of statement, got constant");
1615 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1618 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1619 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1621 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1624 parseerror(parser, "expected operator or end of statement, got constant");
1628 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1631 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1632 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1634 else if (parser->tok == TOKEN_STRINGCONST) {
1637 parseerror(parser, "expected operator or end of statement, got constant");
1641 val = parser_const_string(parser, parser_tokval(parser), false);
1644 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1645 DEBUGSHUNTDO(con_out("push string\n"));
1647 else if (parser->tok == TOKEN_VECTORCONST) {
1650 parseerror(parser, "expected operator or end of statement, got constant");
1654 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1657 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1658 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1659 parser_token(parser)->constval.v.x,
1660 parser_token(parser)->constval.v.y,
1661 parser_token(parser)->constval.v.z));
1663 else if (parser->tok == '(') {
1664 parseerror(parser, "internal error: '(' should be classified as operator");
1667 else if (parser->tok == '[') {
1668 parseerror(parser, "internal error: '[' should be classified as operator");
1671 else if (parser->tok == ')') {
1673 DEBUGSHUNTDO(con_out("do[op] )\n"));
1677 /* we do expect an operator next */
1678 /* closing an opening paren */
1679 if (!parser_close_paren(parser, &sy, false))
1681 if (vec_last(parser->pot) != POT_PAREN) {
1682 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1685 vec_pop(parser->pot);
1687 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1691 /* allowed for function calls */
1692 if (!parser_close_paren(parser, &sy, true))
1694 if (vec_last(parser->pot) != POT_PAREN) {
1695 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1698 vec_pop(parser->pot);
1702 else if (parser->tok == ']') {
1704 parseerror(parser, "operand expected");
1708 if (!parser_close_paren(parser, &sy, false))
1710 if (vec_last(parser->pot) != POT_PAREN) {
1711 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1714 vec_pop(parser->pot);
1717 else if (parser->tok == TOKEN_TYPENAME) {
1718 parseerror(parser, "unexpected typename");
1721 else if (parser->tok != TOKEN_OPERATOR) {
1723 parseerror(parser, "expected operator or end of statement");
1730 /* classify the operator */
1731 const oper_info *op;
1732 const oper_info *olast = NULL;
1734 for (o = 0; o < operator_count; ++o) {
1735 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1736 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1737 !strcmp(parser_tokval(parser), operators[o].op))
1742 if (o == operator_count) {
1743 /* no operator found... must be the end of the statement */
1746 /* found an operator */
1749 /* when declaring variables, a comma starts a new variable */
1750 if (op->id == opid1(',') && !parens && stopatcomma) {
1751 /* fixup the token */
1756 /* a colon without a pervious question mark cannot be a ternary */
1757 if (!ternaries && op->id == opid2(':','?')) {
1762 if (op->id == opid1(',')) {
1763 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1764 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1768 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1769 olast = &operators[vec_last(sy.ops).etype-1];
1771 #define IsAssignOp(x) (\
1772 (x) == opid1('=') || \
1773 (x) == opid2('+','=') || \
1774 (x) == opid2('-','=') || \
1775 (x) == opid2('*','=') || \
1776 (x) == opid2('/','=') || \
1777 (x) == opid2('%','=') || \
1778 (x) == opid2('&','=') || \
1779 (x) == opid2('|','=') || \
1780 (x) == opid3('&','~','=') \
1782 if (warn_truthvalue) {
1783 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1784 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1785 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1788 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1789 warn_truthvalue = false;
1794 (op->prec < olast->prec) ||
1795 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1797 if (!parser_sy_apply_operator(parser, &sy))
1799 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1800 olast = &operators[vec_last(sy.ops).etype-1];
1805 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1806 /* for gmqcc standard: open up the namespace of the previous type */
1807 ast_expression *prevex = vec_last(sy.out).out;
1809 parseerror(parser, "unexpected member operator");
1812 if (prevex->expression.vtype == TYPE_ENTITY)
1813 parser->memberof = TYPE_ENTITY;
1814 else if (prevex->expression.vtype == TYPE_VECTOR)
1815 parser->memberof = TYPE_VECTOR;
1817 parseerror(parser, "type error: type has no members");
1823 if (op->id == opid1('(')) {
1825 size_t sycount = vec_size(sy.out);
1826 DEBUGSHUNTDO(con_out("push [op] (\n"));
1827 ++parens; vec_push(parser->pot, POT_PAREN);
1828 /* we expected an operator, this is the function-call operator */
1829 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1831 ++parens; vec_push(parser->pot, POT_PAREN);
1832 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1833 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1836 } else if (op->id == opid1('[')) {
1838 parseerror(parser, "unexpected array subscript");
1841 ++parens; vec_push(parser->pot, POT_PAREN);
1842 /* push both the operator and the paren, this makes life easier */
1843 vec_push(sy.ops, syop(parser_ctx(parser), op));
1844 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1846 } else if (op->id == opid2('?',':')) {
1847 vec_push(sy.ops, syop(parser_ctx(parser), op));
1848 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1851 vec_push(parser->pot, POT_TERNARY1);
1852 } else if (op->id == opid2(':','?')) {
1853 if (!vec_size(parser->pot)) {
1854 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1857 if (vec_last(parser->pot) != POT_TERNARY1) {
1858 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1861 if (!parser_close_paren(parser, &sy, false))
1863 vec_push(sy.ops, syop(parser_ctx(parser), op));
1867 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1868 vec_push(sy.ops, syop(parser_ctx(parser), op));
1869 wantop = !!(op->flags & OP_SUFFIX);
1872 if (!parser_next(parser)) {
1875 if (parser->tok == ';' ||
1876 (!parens && parser->tok == ']'))
1882 while (vec_size(sy.ops)) {
1883 if (!parser_sy_apply_operator(parser, &sy))
1887 parser->lex->flags.noops = true;
1888 if (!vec_size(sy.out)) {
1889 parseerror(parser, "empty expression");
1892 expr = sy.out[0].out;
1895 DEBUGSHUNTDO(con_out("shunt done\n"));
1896 if (vec_size(parser->pot)) {
1897 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1900 vec_free(parser->pot);
1904 parser->lex->flags.noops = true;
1910 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1912 ast_expression *e = parse_expression_leave(parser, stopatcomma, false);
1915 if (!parser_next(parser)) {
1922 static void parser_enterblock(parser_t *parser)
1924 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1925 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1926 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1927 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1928 vec_push(parser->_block_ctx, parser_ctx(parser));
1931 static bool parser_leaveblock(parser_t *parser)
1934 size_t locals, typedefs;
1936 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1937 parseerror(parser, "internal error: parser_leaveblock with no block");
1941 util_htdel(vec_last(parser->variables));
1942 vec_pop(parser->variables);
1943 if (!vec_size(parser->_blocklocals)) {
1944 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1948 locals = vec_last(parser->_blocklocals);
1949 vec_pop(parser->_blocklocals);
1950 while (vec_size(parser->_locals) != locals) {
1951 ast_expression *e = vec_last(parser->_locals);
1952 ast_value *v = (ast_value*)e;
1953 vec_pop(parser->_locals);
1954 if (ast_istype(e, ast_value) && !v->uses) {
1955 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1960 typedefs = vec_last(parser->_blocktypedefs);
1961 while (vec_size(parser->_typedefs) != typedefs) {
1962 ast_delete(vec_last(parser->_typedefs));
1963 vec_pop(parser->_typedefs);
1965 util_htdel(vec_last(parser->typedefs));
1966 vec_pop(parser->typedefs);
1968 vec_pop(parser->_block_ctx);
1972 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1974 vec_push(parser->_locals, e);
1975 util_htset(vec_last(parser->variables), name, (void*)e);
1978 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1982 ast_expression *prev;
1984 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1987 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1990 parseerror(parser, "internal error: failed to process condition");
1995 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1997 /* vector types need to be cast to true booleans */
1998 ast_binary *bin = (ast_binary*)cond;
1999 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2001 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2003 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2006 parseerror(parser, "internal error: failed to process condition");
2013 unary = (ast_unary*)cond;
2014 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2016 cond = unary->operand;
2017 unary->operand = NULL;
2020 unary = (ast_unary*)cond;
2024 parseerror(parser, "internal error: failed to process condition");
2026 if (ifnot) *_ifnot = !*_ifnot;
2030 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2033 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2036 lex_ctx ctx = parser_ctx(parser);
2038 (void)block; /* not touching */
2040 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2041 if (!parser_next(parser)) {
2042 parseerror(parser, "expected condition or 'not'");
2045 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2047 if (!parser_next(parser)) {
2048 parseerror(parser, "expected condition in parenthesis");
2052 if (parser->tok != '(') {
2053 parseerror(parser, "expected 'if' condition in parenthesis");
2056 /* parse into the expression */
2057 if (!parser_next(parser)) {
2058 parseerror(parser, "expected 'if' condition after opening paren");
2061 /* parse the condition */
2062 cond = parse_expression_leave(parser, false, true);
2066 if (parser->tok != ')') {
2067 parseerror(parser, "expected closing paren after 'if' condition");
2071 /* parse into the 'then' branch */
2072 if (!parser_next(parser)) {
2073 parseerror(parser, "expected statement for on-true branch of 'if'");
2077 if (!parse_statement_or_block(parser, &ontrue)) {
2081 /* check for an else */
2082 if (!strcmp(parser_tokval(parser), "else")) {
2083 /* parse into the 'else' branch */
2084 if (!parser_next(parser)) {
2085 parseerror(parser, "expected on-false branch after 'else'");
2090 if (!parse_statement_or_block(parser, &onfalse)) {
2097 cond = process_condition(parser, cond, &ifnot);
2099 if (ontrue) ast_delete(ontrue);
2100 if (onfalse) ast_delete(onfalse);
2105 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2107 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2108 *out = (ast_expression*)ifthen;
2112 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2113 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2118 /* skip the 'while' and get the body */
2119 if (!parser_next(parser)) {
2120 if (OPTS_FLAG(LOOP_LABELS))
2121 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2123 parseerror(parser, "expected 'while' condition in parenthesis");
2127 if (parser->tok == ':') {
2128 if (!OPTS_FLAG(LOOP_LABELS))
2129 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2130 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2131 parseerror(parser, "expected loop label");
2134 label = util_strdup(parser_tokval(parser));
2135 if (!parser_next(parser)) {
2137 parseerror(parser, "expected 'while' condition in parenthesis");
2142 if (parser->tok != '(') {
2143 parseerror(parser, "expected 'while' condition in parenthesis");
2147 vec_push(parser->breaks, label);
2148 vec_push(parser->continues, label);
2150 rv = parse_while_go(parser, block, out);
2153 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2154 parseerror(parser, "internal error: label stack corrupted");
2160 vec_pop(parser->breaks);
2161 vec_pop(parser->continues);
2166 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2169 ast_expression *cond, *ontrue;
2173 lex_ctx ctx = parser_ctx(parser);
2175 (void)block; /* not touching */
2177 /* parse into the expression */
2178 if (!parser_next(parser)) {
2179 parseerror(parser, "expected 'while' condition after opening paren");
2182 /* parse the condition */
2183 cond = parse_expression_leave(parser, false, true);
2187 if (parser->tok != ')') {
2188 parseerror(parser, "expected closing paren after 'while' condition");
2192 /* parse into the 'then' branch */
2193 if (!parser_next(parser)) {
2194 parseerror(parser, "expected while-loop body");
2198 if (!parse_statement_or_block(parser, &ontrue)) {
2203 cond = process_condition(parser, cond, &ifnot);
2208 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2209 *out = (ast_expression*)aloop;
2213 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2214 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2219 /* skip the 'do' and get the body */
2220 if (!parser_next(parser)) {
2221 if (OPTS_FLAG(LOOP_LABELS))
2222 parseerror(parser, "expected loop label or body");
2224 parseerror(parser, "expected loop body");
2228 if (parser->tok == ':') {
2229 if (!OPTS_FLAG(LOOP_LABELS))
2230 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2231 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2232 parseerror(parser, "expected loop label");
2235 label = util_strdup(parser_tokval(parser));
2236 if (!parser_next(parser)) {
2238 parseerror(parser, "expected loop body");
2243 vec_push(parser->breaks, label);
2244 vec_push(parser->continues, label);
2246 rv = parse_dowhile_go(parser, block, out);
2249 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2250 parseerror(parser, "internal error: label stack corrupted");
2256 vec_pop(parser->breaks);
2257 vec_pop(parser->continues);
2262 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2265 ast_expression *cond, *ontrue;
2269 lex_ctx ctx = parser_ctx(parser);
2271 (void)block; /* not touching */
2273 if (!parse_statement_or_block(parser, &ontrue))
2276 /* expect the "while" */
2277 if (parser->tok != TOKEN_KEYWORD ||
2278 strcmp(parser_tokval(parser), "while"))
2280 parseerror(parser, "expected 'while' and condition");
2285 /* skip the 'while' and check for opening paren */
2286 if (!parser_next(parser) || parser->tok != '(') {
2287 parseerror(parser, "expected 'while' condition in parenthesis");
2291 /* parse into the expression */
2292 if (!parser_next(parser)) {
2293 parseerror(parser, "expected 'while' condition after opening paren");
2297 /* parse the condition */
2298 cond = parse_expression_leave(parser, false, true);
2302 if (parser->tok != ')') {
2303 parseerror(parser, "expected closing paren after 'while' condition");
2309 if (!parser_next(parser) || parser->tok != ';') {
2310 parseerror(parser, "expected semicolon after condition");
2316 if (!parser_next(parser)) {
2317 parseerror(parser, "parse error");
2323 cond = process_condition(parser, cond, &ifnot);
2328 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2329 *out = (ast_expression*)aloop;
2333 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2334 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2339 /* skip the 'for' and check for opening paren */
2340 if (!parser_next(parser)) {
2341 if (OPTS_FLAG(LOOP_LABELS))
2342 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2344 parseerror(parser, "expected 'for' expressions in parenthesis");
2348 if (parser->tok == ':') {
2349 if (!OPTS_FLAG(LOOP_LABELS))
2350 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2351 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2352 parseerror(parser, "expected loop label");
2355 label = util_strdup(parser_tokval(parser));
2356 if (!parser_next(parser)) {
2358 parseerror(parser, "expected 'for' expressions in parenthesis");
2363 if (parser->tok != '(') {
2364 parseerror(parser, "expected 'for' expressions in parenthesis");
2368 vec_push(parser->breaks, label);
2369 vec_push(parser->continues, label);
2371 rv = parse_for_go(parser, block, out);
2374 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2375 parseerror(parser, "internal error: label stack corrupted");
2381 vec_pop(parser->breaks);
2382 vec_pop(parser->continues);
2386 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2389 ast_expression *initexpr, *cond, *increment, *ontrue;
2395 lex_ctx ctx = parser_ctx(parser);
2397 parser_enterblock(parser);
2404 /* parse into the expression */
2405 if (!parser_next(parser)) {
2406 parseerror(parser, "expected 'for' initializer after opening paren");
2411 if (parser->tok == TOKEN_IDENT)
2412 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2414 if (typevar || parser->tok == TOKEN_TYPENAME) {
2416 if (opts.standard != COMPILER_GMQCC) {
2417 if (parsewarning(parser, WARN_EXTENSIONS,
2418 "current standard does not allow variable declarations in for-loop initializers"))
2422 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2425 else if (parser->tok != ';')
2427 initexpr = parse_expression_leave(parser, false, false);
2432 /* move on to condition */
2433 if (parser->tok != ';') {
2434 parseerror(parser, "expected semicolon after for-loop initializer");
2437 if (!parser_next(parser)) {
2438 parseerror(parser, "expected for-loop condition");
2442 /* parse the condition */
2443 if (parser->tok != ';') {
2444 cond = parse_expression_leave(parser, false, true);
2449 /* move on to incrementor */
2450 if (parser->tok != ';') {
2451 parseerror(parser, "expected semicolon after for-loop initializer");
2454 if (!parser_next(parser)) {
2455 parseerror(parser, "expected for-loop condition");
2459 /* parse the incrementor */
2460 if (parser->tok != ')') {
2461 increment = parse_expression_leave(parser, false, false);
2464 if (!ast_side_effects(increment)) {
2465 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2471 if (parser->tok != ')') {
2472 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2475 /* parse into the 'then' branch */
2476 if (!parser_next(parser)) {
2477 parseerror(parser, "expected for-loop body");
2480 if (!parse_statement_or_block(parser, &ontrue))
2484 cond = process_condition(parser, cond, &ifnot);
2488 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2489 *out = (ast_expression*)aloop;
2491 if (!parser_leaveblock(parser))
2495 if (initexpr) ast_delete(initexpr);
2496 if (cond) ast_delete(cond);
2497 if (increment) ast_delete(increment);
2498 (void)!parser_leaveblock(parser);
2502 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2504 ast_expression *exp = NULL;
2505 ast_return *ret = NULL;
2506 ast_value *expected = parser->function->vtype;
2508 lex_ctx ctx = parser_ctx(parser);
2510 (void)block; /* not touching */
2512 if (!parser_next(parser)) {
2513 parseerror(parser, "expected return expression");
2517 if (parser->tok != ';') {
2518 exp = parse_expression(parser, false);
2522 if (exp->expression.vtype != TYPE_NIL &&
2523 exp->expression.vtype != expected->expression.next->expression.vtype)
2525 parseerror(parser, "return with invalid expression");
2528 ret = ast_return_new(ctx, exp);
2534 if (!parser_next(parser))
2535 parseerror(parser, "parse error");
2536 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2537 if (opts.standard != COMPILER_GMQCC)
2538 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2540 parseerror(parser, "return without value");
2542 ret = ast_return_new(ctx, NULL);
2544 *out = (ast_expression*)ret;
2548 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2551 unsigned int levels = 0;
2552 lex_ctx ctx = parser_ctx(parser);
2553 const char **loops = (is_continue ? parser->continues : parser->breaks);
2555 (void)block; /* not touching */
2556 if (!parser_next(parser)) {
2557 parseerror(parser, "expected semicolon or loop label");
2561 if (parser->tok == TOKEN_IDENT) {
2562 if (!OPTS_FLAG(LOOP_LABELS))
2563 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2564 i = vec_size(loops);
2566 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2569 parseerror(parser, "no such loop to %s: `%s`",
2570 (is_continue ? "continue" : "break out of"),
2571 parser_tokval(parser));
2576 if (!parser_next(parser)) {
2577 parseerror(parser, "expected semicolon");
2582 if (parser->tok != ';') {
2583 parseerror(parser, "expected semicolon");
2587 if (!parser_next(parser))
2588 parseerror(parser, "parse error");
2590 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2594 /* returns true when it was a variable qualifier, false otherwise!
2595 * on error, cvq is set to CV_WRONG
2597 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2599 bool had_const = false;
2600 bool had_var = false;
2601 bool had_noref = false;
2602 bool had_attrib = false;
2603 bool had_static = false;
2608 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2610 /* parse an attribute */
2611 if (!parser_next(parser)) {
2612 parseerror(parser, "expected attribute after `[[`");
2616 if (!strcmp(parser_tokval(parser), "noreturn")) {
2617 flags |= AST_FLAG_NORETURN;
2618 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2619 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2624 else if (!strcmp(parser_tokval(parser), "noref")) {
2626 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2627 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2632 else if (!strcmp(parser_tokval(parser), "inline")) {
2633 flags |= AST_FLAG_INLINE;
2634 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2635 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2642 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2643 flags |= AST_FLAG_DEPRECATED;
2646 if (!parser_next(parser)) {
2647 parseerror(parser, "parse error in attribute");
2651 if (parser->tok == '(') {
2652 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2653 parseerror(parser, "`deprecated` attribute missing parameter");
2657 *message = util_strdup(parser_tokval(parser));
2659 if (!parser_next(parser)) {
2660 parseerror(parser, "parse error in attribute");
2664 if(parser->tok != ')') {
2665 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2669 if (!parser_next(parser)) {
2670 parseerror(parser, "parse error in attribute");
2675 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2676 parseerror(parser, "`deprecated` attribute expected `]]`");
2679 if (*message) mem_d(*message);
2687 /* Skip tokens until we hit a ]] */
2688 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2689 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2690 if (!parser_next(parser)) {
2691 parseerror(parser, "error inside attribute");
2698 else if (!strcmp(parser_tokval(parser), "static"))
2700 else if (!strcmp(parser_tokval(parser), "const"))
2702 else if (!strcmp(parser_tokval(parser), "var"))
2704 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2706 else if (!strcmp(parser_tokval(parser), "noref"))
2708 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2713 if (!parser_next(parser))
2723 *is_static = had_static;
2727 parseerror(parser, "parse error after variable qualifier");
2732 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2733 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2738 /* skip the 'while' and get the body */
2739 if (!parser_next(parser)) {
2740 if (OPTS_FLAG(LOOP_LABELS))
2741 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2743 parseerror(parser, "expected 'switch' operand in parenthesis");
2747 if (parser->tok == ':') {
2748 if (!OPTS_FLAG(LOOP_LABELS))
2749 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2750 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2751 parseerror(parser, "expected loop label");
2754 label = util_strdup(parser_tokval(parser));
2755 if (!parser_next(parser)) {
2757 parseerror(parser, "expected 'switch' operand in parenthesis");
2762 if (parser->tok != '(') {
2763 parseerror(parser, "expected 'switch' operand in parenthesis");
2767 vec_push(parser->breaks, label);
2769 rv = parse_switch_go(parser, block, out);
2772 if (vec_last(parser->breaks) != label) {
2773 parseerror(parser, "internal error: label stack corrupted");
2779 vec_pop(parser->breaks);
2784 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2786 ast_expression *operand;
2789 ast_switch *switchnode;
2790 ast_switch_case swcase;
2793 bool noref, is_static;
2794 uint32_t qflags = 0;
2796 lex_ctx ctx = parser_ctx(parser);
2798 (void)block; /* not touching */
2801 /* parse into the expression */
2802 if (!parser_next(parser)) {
2803 parseerror(parser, "expected switch operand");
2806 /* parse the operand */
2807 operand = parse_expression_leave(parser, false, false);
2811 switchnode = ast_switch_new(ctx, operand);
2814 if (parser->tok != ')') {
2815 ast_delete(switchnode);
2816 parseerror(parser, "expected closing paren after 'switch' operand");
2820 /* parse over the opening paren */
2821 if (!parser_next(parser) || parser->tok != '{') {
2822 ast_delete(switchnode);
2823 parseerror(parser, "expected list of cases");
2827 if (!parser_next(parser)) {
2828 ast_delete(switchnode);
2829 parseerror(parser, "expected 'case' or 'default'");
2833 /* new block; allow some variables to be declared here */
2834 parser_enterblock(parser);
2837 if (parser->tok == TOKEN_IDENT)
2838 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2839 if (typevar || parser->tok == TOKEN_TYPENAME) {
2840 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2841 ast_delete(switchnode);
2846 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2848 if (cvq == CV_WRONG) {
2849 ast_delete(switchnode);
2852 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2853 ast_delete(switchnode);
2862 while (parser->tok != '}') {
2863 ast_block *caseblock;
2865 if (!strcmp(parser_tokval(parser), "case")) {
2866 if (!parser_next(parser)) {
2867 ast_delete(switchnode);
2868 parseerror(parser, "expected expression for case");
2871 swcase.value = parse_expression_leave(parser, false, false);
2872 if (!swcase.value) {
2873 ast_delete(switchnode);
2874 parseerror(parser, "expected expression for case");
2877 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2878 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2879 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2885 else if (!strcmp(parser_tokval(parser), "default")) {
2886 swcase.value = NULL;
2887 if (!parser_next(parser)) {
2888 ast_delete(switchnode);
2889 parseerror(parser, "expected colon");
2894 ast_delete(switchnode);
2895 parseerror(parser, "expected 'case' or 'default'");
2899 /* Now the colon and body */
2900 if (parser->tok != ':') {
2901 if (swcase.value) ast_unref(swcase.value);
2902 ast_delete(switchnode);
2903 parseerror(parser, "expected colon");
2907 if (!parser_next(parser)) {
2908 if (swcase.value) ast_unref(swcase.value);
2909 ast_delete(switchnode);
2910 parseerror(parser, "expected statements or case");
2913 caseblock = ast_block_new(parser_ctx(parser));
2915 if (swcase.value) ast_unref(swcase.value);
2916 ast_delete(switchnode);
2919 swcase.code = (ast_expression*)caseblock;
2920 vec_push(switchnode->cases, swcase);
2922 ast_expression *expr;
2923 if (parser->tok == '}')
2925 if (parser->tok == TOKEN_KEYWORD) {
2926 if (!strcmp(parser_tokval(parser), "case") ||
2927 !strcmp(parser_tokval(parser), "default"))
2932 if (!parse_statement(parser, caseblock, &expr, true)) {
2933 ast_delete(switchnode);
2938 if (!ast_block_add_expr(caseblock, expr)) {
2939 ast_delete(switchnode);
2945 parser_leaveblock(parser);
2948 if (parser->tok != '}') {
2949 ast_delete(switchnode);
2950 parseerror(parser, "expected closing paren of case list");
2953 if (!parser_next(parser)) {
2954 ast_delete(switchnode);
2955 parseerror(parser, "parse error after switch");
2958 *out = (ast_expression*)switchnode;
2962 static bool parse_goto(parser_t *parser, ast_expression **out)
2967 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2968 parseerror(parser, "expected label name after `goto`");
2972 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2974 for (i = 0; i < vec_size(parser->labels); ++i) {
2975 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2976 ast_goto_set_label(gt, parser->labels[i]);
2980 if (i == vec_size(parser->labels))
2981 vec_push(parser->gotos, gt);
2983 if (!parser_next(parser) || parser->tok != ';') {
2984 parseerror(parser, "semicolon expected after goto label");
2987 if (!parser_next(parser)) {
2988 parseerror(parser, "parse error after goto");
2992 *out = (ast_expression*)gt;
2996 static bool parse_skipwhite(parser_t *parser)
2999 if (!parser_next(parser))
3001 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3002 return parser->tok < TOKEN_ERROR;
3005 static bool parse_eol(parser_t *parser)
3007 if (!parse_skipwhite(parser))
3009 return parser->tok == TOKEN_EOL;
3012 static bool parse_pragma_do(parser_t *parser)
3014 if (!parser_next(parser) ||
3015 parser->tok != TOKEN_IDENT ||
3016 strcmp(parser_tokval(parser), "pragma"))
3018 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3021 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3022 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3026 if (!strcmp(parser_tokval(parser), "noref")) {
3027 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3028 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3031 parser->noref = !!parser_token(parser)->constval.i;
3032 if (!parse_eol(parser)) {
3033 parseerror(parser, "parse error after `noref` pragma");
3039 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3046 static bool parse_pragma(parser_t *parser)
3049 parser->lex->flags.preprocessing = true;
3050 parser->lex->flags.mergelines = true;
3051 rv = parse_pragma_do(parser);
3052 if (parser->tok != TOKEN_EOL) {
3053 parseerror(parser, "junk after pragma");
3056 parser->lex->flags.preprocessing = false;
3057 parser->lex->flags.mergelines = false;
3058 if (!parser_next(parser)) {
3059 parseerror(parser, "parse error after pragma");
3065 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3067 bool noref, is_static;
3069 uint32_t qflags = 0;
3070 ast_value *typevar = NULL;
3071 char *vstring = NULL;
3075 if (parser->tok == TOKEN_IDENT)
3076 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3078 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3080 /* local variable */
3082 parseerror(parser, "cannot declare a variable from here");
3085 if (opts.standard == COMPILER_QCC) {
3086 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3089 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3093 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3095 if (cvq == CV_WRONG)
3097 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3099 else if (parser->tok == TOKEN_KEYWORD)
3101 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3106 if (!parser_next(parser)) {
3107 parseerror(parser, "parse error after __builtin_debug_printtype");
3111 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3113 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3114 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3115 if (!parser_next(parser)) {
3116 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3122 if (!parse_statement(parser, block, out, allow_cases))
3125 con_out("__builtin_debug_printtype: got no output node\n");
3128 ast_type_to_string(*out, ty, sizeof(ty));
3129 con_out("__builtin_debug_printtype: `%s`\n", ty);
3134 else if (!strcmp(parser_tokval(parser), "return"))
3136 return parse_return(parser, block, out);
3138 else if (!strcmp(parser_tokval(parser), "if"))
3140 return parse_if(parser, block, out);
3142 else if (!strcmp(parser_tokval(parser), "while"))
3144 return parse_while(parser, block, out);
3146 else if (!strcmp(parser_tokval(parser), "do"))
3148 return parse_dowhile(parser, block, out);
3150 else if (!strcmp(parser_tokval(parser), "for"))
3152 if (opts.standard == COMPILER_QCC) {
3153 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3156 return parse_for(parser, block, out);
3158 else if (!strcmp(parser_tokval(parser), "break"))
3160 return parse_break_continue(parser, block, out, false);
3162 else if (!strcmp(parser_tokval(parser), "continue"))
3164 return parse_break_continue(parser, block, out, true);
3166 else if (!strcmp(parser_tokval(parser), "switch"))
3168 return parse_switch(parser, block, out);
3170 else if (!strcmp(parser_tokval(parser), "case") ||
3171 !strcmp(parser_tokval(parser), "default"))
3174 parseerror(parser, "unexpected 'case' label");
3179 else if (!strcmp(parser_tokval(parser), "goto"))
3181 return parse_goto(parser, out);
3183 else if (!strcmp(parser_tokval(parser), "typedef"))
3185 if (!parser_next(parser)) {
3186 parseerror(parser, "expected type definition after 'typedef'");
3189 return parse_typedef(parser);
3191 parseerror(parser, "Unexpected keyword");
3194 else if (parser->tok == '{')
3197 inner = parse_block(parser);
3200 *out = (ast_expression*)inner;
3203 else if (parser->tok == ':')
3207 if (!parser_next(parser)) {
3208 parseerror(parser, "expected label name");
3211 if (parser->tok != TOKEN_IDENT) {
3212 parseerror(parser, "label must be an identifier");
3215 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3218 vec_push(parser->labels, label);
3219 *out = (ast_expression*)label;
3220 if (!parser_next(parser)) {
3221 parseerror(parser, "parse error after label");
3224 for (i = 0; i < vec_size(parser->gotos); ++i) {
3225 if (!strcmp(parser->gotos[i]->name, label->name)) {
3226 ast_goto_set_label(parser->gotos[i], label);
3227 vec_remove(parser->gotos, i, 1);
3233 else if (parser->tok == ';')
3235 if (!parser_next(parser)) {
3236 parseerror(parser, "parse error after empty statement");
3243 ast_expression *exp = parse_expression(parser, false);
3247 if (!ast_side_effects(exp)) {
3248 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3255 static bool parse_block_into(parser_t *parser, ast_block *block)
3259 parser_enterblock(parser);
3261 if (!parser_next(parser)) { /* skip the '{' */
3262 parseerror(parser, "expected function body");
3266 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3268 ast_expression *expr = NULL;
3269 if (parser->tok == '}')
3272 if (!parse_statement(parser, block, &expr, false)) {
3273 /* parseerror(parser, "parse error"); */
3279 if (!ast_block_add_expr(block, expr)) {
3286 if (parser->tok != '}') {
3289 (void)parser_next(parser);
3293 if (!parser_leaveblock(parser))
3295 return retval && !!block;
3298 static ast_block* parse_block(parser_t *parser)
3301 block = ast_block_new(parser_ctx(parser));
3304 if (!parse_block_into(parser, block)) {
3305 ast_block_delete(block);
3311 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3313 if (parser->tok == '{') {
3314 *out = (ast_expression*)parse_block(parser);
3317 return parse_statement(parser, NULL, out, false);
3320 static bool create_vector_members(ast_value *var, ast_member **me)
3323 size_t len = strlen(var->name);
3325 for (i = 0; i < 3; ++i) {
3326 char *name = (char*)mem_a(len+3);
3327 memcpy(name, var->name, len);
3329 name[len+1] = 'x'+i;
3331 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3340 do { ast_member_delete(me[--i]); } while(i);
3344 static bool parse_function_body(parser_t *parser, ast_value *var)
3346 ast_block *block = NULL;
3351 ast_expression *framenum = NULL;
3352 ast_expression *nextthink = NULL;
3353 /* None of the following have to be deleted */
3354 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3355 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3356 bool has_frame_think;
3360 has_frame_think = false;
3361 old = parser->function;
3363 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3364 parseerror(parser, "gotos/labels leaking");
3368 if (var->expression.flags & AST_FLAG_VARIADIC) {
3369 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3370 "variadic function with implementation will not be able to access additional parameters"))
3376 if (parser->tok == '[') {
3377 /* got a frame definition: [ framenum, nextthink ]
3378 * this translates to:
3379 * self.frame = framenum;
3380 * self.nextthink = time + 0.1;
3381 * self.think = nextthink;
3385 fld_think = parser_find_field(parser, "think");
3386 fld_nextthink = parser_find_field(parser, "nextthink");
3387 fld_frame = parser_find_field(parser, "frame");
3388 if (!fld_think || !fld_nextthink || !fld_frame) {
3389 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3390 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3393 gbl_time = parser_find_global(parser, "time");
3394 gbl_self = parser_find_global(parser, "self");
3395 if (!gbl_time || !gbl_self) {
3396 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3397 parseerror(parser, "please declare the following globals: `time`, `self`");
3401 if (!parser_next(parser))
3404 framenum = parse_expression_leave(parser, true, false);
3406 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3409 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3410 ast_unref(framenum);
3411 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3415 if (parser->tok != ',') {
3416 ast_unref(framenum);
3417 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3418 parseerror(parser, "Got a %i\n", parser->tok);
3422 if (!parser_next(parser)) {
3423 ast_unref(framenum);
3427 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3429 /* qc allows the use of not-yet-declared functions here
3430 * - this automatically creates a prototype */
3431 ast_value *thinkfunc;
3432 ast_expression *functype = fld_think->expression.next;
3434 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3435 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3436 ast_unref(framenum);
3437 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3441 if (!parser_next(parser)) {
3442 ast_unref(framenum);
3443 ast_delete(thinkfunc);
3447 vec_push(parser->globals, (ast_expression*)thinkfunc);
3448 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3449 nextthink = (ast_expression*)thinkfunc;
3452 nextthink = parse_expression_leave(parser, true, false);
3454 ast_unref(framenum);
3455 parseerror(parser, "expected a think-function in [frame,think] notation");
3460 if (!ast_istype(nextthink, ast_value)) {
3461 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3465 if (retval && parser->tok != ']') {
3466 parseerror(parser, "expected closing `]` for [frame,think] notation");
3470 if (retval && !parser_next(parser)) {
3474 if (retval && parser->tok != '{') {
3475 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3480 ast_unref(nextthink);
3481 ast_unref(framenum);
3485 has_frame_think = true;
3488 block = ast_block_new(parser_ctx(parser));
3490 parseerror(parser, "failed to allocate block");
3491 if (has_frame_think) {
3492 ast_unref(nextthink);
3493 ast_unref(framenum);
3498 if (has_frame_think) {
3500 ast_expression *self_frame;
3501 ast_expression *self_nextthink;
3502 ast_expression *self_think;
3503 ast_expression *time_plus_1;
3504 ast_store *store_frame;
3505 ast_store *store_nextthink;
3506 ast_store *store_think;
3508 ctx = parser_ctx(parser);
3509 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3510 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3511 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3513 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3514 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3516 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3517 if (self_frame) ast_delete(self_frame);
3518 if (self_nextthink) ast_delete(self_nextthink);
3519 if (self_think) ast_delete(self_think);
3520 if (time_plus_1) ast_delete(time_plus_1);
3526 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3527 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3528 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3531 ast_delete(self_frame);
3534 if (!store_nextthink) {
3535 ast_delete(self_nextthink);
3539 ast_delete(self_think);
3543 if (store_frame) ast_delete(store_frame);
3544 if (store_nextthink) ast_delete(store_nextthink);
3545 if (store_think) ast_delete(store_think);
3548 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3549 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3550 !ast_block_add_expr(block, (ast_expression*)store_think))
3557 parseerror(parser, "failed to generate code for [frame,think]");
3558 ast_unref(nextthink);
3559 ast_unref(framenum);
3565 parser_enterblock(parser);
3567 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3569 ast_value *param = var->expression.params[parami];
3572 if (param->expression.vtype != TYPE_VECTOR &&
3573 (param->expression.vtype != TYPE_FIELD ||
3574 param->expression.next->expression.vtype != TYPE_VECTOR))
3579 if (!create_vector_members(param, me)) {
3580 ast_block_delete(block);
3584 for (e = 0; e < 3; ++e) {
3585 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3586 ast_block_collect(block, (ast_expression*)me[e]);
3590 func = ast_function_new(ast_ctx(var), var->name, var);
3592 parseerror(parser, "failed to allocate function for `%s`", var->name);
3593 ast_block_delete(block);
3596 vec_push(parser->functions, func);
3598 parser->function = func;
3599 if (!parse_block_into(parser, block)) {
3600 ast_block_delete(block);
3604 vec_push(func->blocks, block);
3606 parser->function = old;
3607 if (!parser_leaveblock(parser))
3609 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3610 parseerror(parser, "internal error: local scopes left");
3614 if (parser->tok == ';')
3615 return parser_next(parser);
3616 else if (opts.standard == COMPILER_QCC)
3617 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3621 vec_pop(parser->functions);
3622 ast_function_delete(func);
3623 var->constval.vfunc = NULL;
3626 (void)!parser_leaveblock(parser);
3627 parser->function = old;
3631 static ast_expression *array_accessor_split(
3636 ast_expression *left,
3637 ast_expression *right
3643 lex_ctx ctx = ast_ctx(array);
3645 if (!left || !right) {
3646 if (left) ast_delete(left);
3647 if (right) ast_delete(right);
3651 cmp = ast_binary_new(ctx, INSTR_LT,
3652 (ast_expression*)index,
3653 (ast_expression*)parser_const_float(parser, middle));
3657 parseerror(parser, "internal error: failed to create comparison for array setter");
3661 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3663 ast_delete(cmp); /* will delete left and right */
3664 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3668 return (ast_expression*)ifthen;
3671 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3673 lex_ctx ctx = ast_ctx(array);
3675 if (from+1 == afterend) {
3676 /* set this value */
3679 ast_array_index *subscript;
3681 int assignop = type_store_instr[value->expression.vtype];
3683 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3684 assignop = INSTR_STORE_V;
3686 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3690 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3692 ast_delete(subscript);
3696 block = ast_block_new(ctx);
3702 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3707 ret = ast_return_new(ctx, NULL);
3713 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3718 return (ast_expression*)block;
3720 ast_expression *left, *right;
3721 size_t diff = afterend - from;
3722 size_t middle = from + diff/2;
3723 left = array_setter_node(parser, array, index, value, from, middle);
3724 right = array_setter_node(parser, array, index, value, middle, afterend);
3725 return array_accessor_split(parser, array, index, middle, left, right);
3729 static ast_expression *array_field_setter_node(
3738 lex_ctx ctx = ast_ctx(array);
3740 if (from+1 == afterend) {
3741 /* set this value */
3744 ast_entfield *entfield;
3745 ast_array_index *subscript;
3747 int assignop = type_storep_instr[value->expression.vtype];
3749 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3750 assignop = INSTR_STOREP_V;
3752 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3756 entfield = ast_entfield_new_force(ctx,
3757 (ast_expression*)entity,
3758 (ast_expression*)subscript,
3759 (ast_expression*)subscript);
3761 ast_delete(subscript);
3765 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3767 ast_delete(entfield);
3771 block = ast_block_new(ctx);
3777 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3782 ret = ast_return_new(ctx, NULL);
3788 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3793 return (ast_expression*)block;
3795 ast_expression *left, *right;
3796 size_t diff = afterend - from;
3797 size_t middle = from + diff/2;
3798 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3799 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3800 return array_accessor_split(parser, array, index, middle, left, right);
3804 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3806 lex_ctx ctx = ast_ctx(array);
3808 if (from+1 == afterend) {
3810 ast_array_index *subscript;
3812 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3816 ret = ast_return_new(ctx, (ast_expression*)subscript);
3818 ast_delete(subscript);
3822 return (ast_expression*)ret;
3824 ast_expression *left, *right;
3825 size_t diff = afterend - from;
3826 size_t middle = from + diff/2;
3827 left = array_getter_node(parser, array, index, from, middle);
3828 right = array_getter_node(parser, array, index, middle, afterend);
3829 return array_accessor_split(parser, array, index, middle, left, right);
3833 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3835 ast_function *func = NULL;
3836 ast_value *fval = NULL;
3837 ast_block *body = NULL;
3839 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3841 parseerror(parser, "failed to create accessor function value");
3845 func = ast_function_new(ast_ctx(array), funcname, fval);
3848 parseerror(parser, "failed to create accessor function node");
3852 body = ast_block_new(ast_ctx(array));
3854 parseerror(parser, "failed to create block for array accessor");
3860 vec_push(func->blocks, body);
3863 vec_push(parser->accessors, fval);
3868 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3870 ast_expression *root = NULL;
3871 ast_value *index = NULL;
3872 ast_value *value = NULL;
3876 if (!ast_istype(array->expression.next, ast_value)) {
3877 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3881 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3883 func = fval->constval.vfunc;
3884 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3886 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3887 value = ast_value_copy((ast_value*)array->expression.next);
3889 if (!index || !value) {
3890 parseerror(parser, "failed to create locals for array accessor");
3893 (void)!ast_value_set_name(value, "value"); /* not important */
3894 vec_push(fval->expression.params, index);
3895 vec_push(fval->expression.params, value);
3897 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3899 parseerror(parser, "failed to build accessor search tree");
3903 array->setter = fval;
3904 return ast_block_add_expr(func->blocks[0], root);
3906 if (index) ast_delete(index);
3907 if (value) ast_delete(value);
3908 if (root) ast_delete(root);
3914 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3916 ast_expression *root = NULL;
3917 ast_value *entity = NULL;
3918 ast_value *index = NULL;
3919 ast_value *value = NULL;
3923 if (!ast_istype(array->expression.next, ast_value)) {
3924 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3928 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3930 func = fval->constval.vfunc;
3931 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3933 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3934 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3935 value = ast_value_copy((ast_value*)array->expression.next);
3936 if (!entity || !index || !value) {
3937 parseerror(parser, "failed to create locals for array accessor");
3940 (void)!ast_value_set_name(value, "value"); /* not important */
3941 vec_push(fval->expression.params, entity);
3942 vec_push(fval->expression.params, index);
3943 vec_push(fval->expression.params, value);
3945 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3947 parseerror(parser, "failed to build accessor search tree");
3951 array->setter = fval;
3952 return ast_block_add_expr(func->blocks[0], root);
3954 if (entity) ast_delete(entity);
3955 if (index) ast_delete(index);
3956 if (value) ast_delete(value);
3957 if (root) ast_delete(root);
3963 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3965 ast_expression *root = NULL;
3966 ast_value *index = NULL;
3970 /* NOTE: checking array->expression.next rather than elemtype since
3971 * for fields elemtype is a temporary fieldtype.
3973 if (!ast_istype(array->expression.next, ast_value)) {
3974 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3978 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3980 func = fval->constval.vfunc;
3981 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3983 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3986 parseerror(parser, "failed to create locals for array accessor");
3989 vec_push(fval->expression.params, index);
3991 root = array_getter_node(parser, array, index, 0, array->expression.count);
3993 parseerror(parser, "failed to build accessor search tree");
3997 array->getter = fval;
3998 return ast_block_add_expr(func->blocks[0], root);
4000 if (index) ast_delete(index);
4001 if (root) ast_delete(root);
4007 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4008 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4016 bool variadic = false;
4018 ctx = parser_ctx(parser);
4020 /* for the sake of less code we parse-in in this function */
4021 if (!parser_next(parser)) {
4022 parseerror(parser, "expected parameter list");
4028 /* parse variables until we hit a closing paren */
4029 while (parser->tok != ')') {
4031 /* there must be commas between them */
4032 if (parser->tok != ',') {
4033 parseerror(parser, "expected comma or end of parameter list");
4036 if (!parser_next(parser)) {
4037 parseerror(parser, "expected parameter");
4043 if (parser->tok == TOKEN_DOTS) {
4044 /* '...' indicates a varargs function */
4046 if (!parser_next(parser)) {
4047 parseerror(parser, "expected parameter");
4050 if (parser->tok != ')') {
4051 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4057 /* for anything else just parse a typename */
4058 param = parse_typename(parser, NULL, NULL);
4061 vec_push(params, param);
4062 if (param->expression.vtype >= TYPE_VARIANT) {
4063 char tname[1024]; /* typename is reserved in C++ */
4064 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4065 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4071 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4075 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4076 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4079 if (!parser_next(parser)) {
4080 parseerror(parser, "parse error after typename");
4084 /* now turn 'var' into a function type */
4085 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4086 fval->expression.next = (ast_expression*)var;
4088 fval->expression.flags |= AST_FLAG_VARIADIC;
4091 var->expression.params = params;
4098 for (i = 0; i < vec_size(params); ++i)
4099 ast_delete(params[i]);
4104 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4106 ast_expression *cexp;
4107 ast_value *cval, *tmp;
4110 ctx = parser_ctx(parser);
4112 if (!parser_next(parser)) {
4114 parseerror(parser, "expected array-size");
4118 cexp = parse_expression_leave(parser, true, false);
4120 if (!cexp || !ast_istype(cexp, ast_value)) {
4124 parseerror(parser, "expected array-size as constant positive integer");
4127 cval = (ast_value*)cexp;
4129 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4130 tmp->expression.next = (ast_expression*)var;
4133 if (cval->expression.vtype == TYPE_INTEGER)
4134 tmp->expression.count = cval->constval.vint;
4135 else if (cval->expression.vtype == TYPE_FLOAT)
4136 tmp->expression.count = cval->constval.vfloat;
4140 parseerror(parser, "array-size must be a positive integer constant");
4145 if (parser->tok != ']') {
4147 parseerror(parser, "expected ']' after array-size");
4150 if (!parser_next(parser)) {
4152 parseerror(parser, "error after parsing array size");
4158 /* Parse a complete typename.
4159 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4160 * but when parsing variables separated by comma
4161 * 'storebase' should point to where the base-type should be kept.
4162 * The base type makes up every bit of type information which comes *before* the
4165 * The following will be parsed in its entirety:
4167 * The 'basetype' in this case is 'void()'
4168 * and if there's a comma after it, say:
4170 * then the type-information 'void()' can be stored in 'storebase'
4172 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4174 ast_value *var, *tmp;
4177 const char *name = NULL;
4178 bool isfield = false;
4179 bool wasarray = false;
4180 size_t morefields = 0;
4182 ctx = parser_ctx(parser);
4184 /* types may start with a dot */
4185 if (parser->tok == '.') {
4187 /* if we parsed a dot we need a typename now */
4188 if (!parser_next(parser)) {
4189 parseerror(parser, "expected typename for field definition");
4193 /* Further dots are handled seperately because they won't be part of the
4196 while (parser->tok == '.') {
4198 if (!parser_next(parser)) {
4199 parseerror(parser, "expected typename for field definition");
4204 if (parser->tok == TOKEN_IDENT)
4205 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4206 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4207 parseerror(parser, "expected typename");
4211 /* generate the basic type value */
4212 if (cached_typedef) {
4213 var = ast_value_copy(cached_typedef);
4214 ast_value_set_name(var, "<type(from_def)>");
4216 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4218 for (; morefields; --morefields) {
4219 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4220 tmp->expression.next = (ast_expression*)var;
4224 /* do not yet turn into a field - remember:
4225 * .void() foo; is a field too
4226 * .void()() foo; is a function
4230 if (!parser_next(parser)) {
4232 parseerror(parser, "parse error after typename");
4236 /* an opening paren now starts the parameter-list of a function
4237 * this is where original-QC has parameter lists.
4238 * We allow a single parameter list here.
4239 * Much like fteqcc we don't allow `float()() x`
4241 if (parser->tok == '(') {
4242 var = parse_parameter_list(parser, var);
4247 /* store the base if requested */
4249 *storebase = ast_value_copy(var);
4251 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4252 tmp->expression.next = (ast_expression*)*storebase;
4257 /* there may be a name now */
4258 if (parser->tok == TOKEN_IDENT) {
4259 name = util_strdup(parser_tokval(parser));
4261 if (!parser_next(parser)) {
4263 parseerror(parser, "error after variable or field declaration");
4268 /* now this may be an array */
4269 if (parser->tok == '[') {
4271 var = parse_arraysize(parser, var);
4276 /* This is the point where we can turn it into a field */
4278 /* turn it into a field if desired */
4279 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4280 tmp->expression.next = (ast_expression*)var;
4284 /* now there may be function parens again */
4285 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4286 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4287 if (parser->tok == '(' && wasarray)
4288 parseerror(parser, "arrays as part of a return type is not supported");
4289 while (parser->tok == '(') {
4290 var = parse_parameter_list(parser, var);
4299 /* finally name it */
4301 if (!ast_value_set_name(var, name)) {
4303 parseerror(parser, "internal error: failed to set name");
4306 /* free the name, ast_value_set_name duplicates */
4313 static bool parse_typedef(parser_t *parser)
4315 ast_value *typevar, *oldtype;
4316 ast_expression *old;
4318 typevar = parse_typename(parser, NULL, NULL);
4323 if ( (old = parser_find_var(parser, typevar->name)) ) {
4324 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4325 " -> `%s` has been declared here: %s:%i",
4326 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4327 ast_delete(typevar);
4331 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4332 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4333 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4334 ast_delete(typevar);
4338 vec_push(parser->_typedefs, typevar);
4339 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4341 if (parser->tok != ';') {
4342 parseerror(parser, "expected semicolon after typedef");
4345 if (!parser_next(parser)) {
4346 parseerror(parser, "parse error after typedef");
4353 static const char *cvq_to_str(int cvq) {
4355 case CV_NONE: return "none";
4356 case CV_VAR: return "`var`";
4357 case CV_CONST: return "`const`";
4358 default: return "<INVALID>";
4362 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4365 if (proto->cvq != var->cvq) {
4366 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4367 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4368 parser->tok == '='))
4370 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4371 "`%s` declared with different qualifiers: %s\n"
4372 " -> previous declaration here: %s:%i uses %s",
4373 var->name, cvq_to_str(var->cvq),
4374 ast_ctx(proto).file, ast_ctx(proto).line,
4375 cvq_to_str(proto->cvq));
4378 av = (var ->expression.flags & AST_FLAG_NORETURN);
4379 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4381 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4382 "`%s` declared with different attributes%s\n"
4383 " -> previous declaration here: %s:%i",
4384 var->name, (av ? ": noreturn" : ""),
4385 ast_ctx(proto).file, ast_ctx(proto).line,
4386 (ao ? ": noreturn" : ""));
4391 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring)
4395 ast_expression *old;
4399 ast_value *basetype = NULL;
4401 bool isparam = false;
4402 bool isvector = false;
4403 bool cleanvar = true;
4404 bool wasarray = false;
4408 if (!localblock && is_static)
4409 parseerror(parser, "`static` qualifier is not supported in global scope");
4411 /* get the first complete variable */
4412 var = parse_typename(parser, &basetype, cached_typedef);
4415 ast_delete(basetype);
4423 /* Part 0: finish the type */
4424 if (parser->tok == '(') {
4425 if (opts.standard == COMPILER_QCC)
4426 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4427 var = parse_parameter_list(parser, var);
4433 /* we only allow 1-dimensional arrays */
4434 if (parser->tok == '[') {
4436 var = parse_arraysize(parser, var);
4442 if (parser->tok == '(' && wasarray) {
4443 parseerror(parser, "arrays as part of a return type is not supported");
4444 /* we'll still parse the type completely for now */
4446 /* for functions returning functions */
4447 while (parser->tok == '(') {
4448 if (opts.standard == COMPILER_QCC)
4449 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4450 var = parse_parameter_list(parser, var);
4457 var->cvq = qualifier;
4458 var->expression.flags |= qflags;
4459 if (var->expression.flags & AST_FLAG_DEPRECATED)
4460 var->desc = vstring;
4463 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4464 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4465 * is then filled with the previous definition and the parameter-names replaced.
4467 if (!strcmp(var->name, "nil")) {
4468 if (OPTS_FLAG(UNTYPED_NIL)) {
4469 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4470 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4472 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4475 /* Deal with end_sys_ vars */
4477 if (!strcmp(var->name, "end_sys_globals")) {
4479 parser->crc_globals = vec_size(parser->globals);
4482 else if (!strcmp(var->name, "end_sys_fields")) {
4484 parser->crc_fields = vec_size(parser->fields);
4487 if (was_end && var->expression.vtype == TYPE_FIELD) {
4488 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4489 "global '%s' hint should not be a field",
4490 parser_tokval(parser)))
4497 if (!nofields && var->expression.vtype == TYPE_FIELD)
4499 /* deal with field declarations */
4500 old = parser_find_field(parser, var->name);
4502 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4503 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4512 parseerror(parser, "field `%s` already declared here: %s:%i",
4513 var->name, ast_ctx(old).file, ast_ctx(old).line);
4518 if (opts.standard == COMPILER_QCC &&
4519 (old = parser_find_global(parser, var->name)))
4521 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4522 parseerror(parser, "field `%s` already declared here: %s:%i",
4523 var->name, ast_ctx(old).file, ast_ctx(old).line);
4530 /* deal with other globals */
4531 old = parser_find_global(parser, var->name);
4532 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4534 /* This is a function which had a prototype */
4535 if (!ast_istype(old, ast_value)) {
4536 parseerror(parser, "internal error: prototype is not an ast_value");
4540 proto = (ast_value*)old;
4541 proto->desc = var->desc;
4542 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4543 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4545 ast_ctx(proto).file, ast_ctx(proto).line);
4549 /* we need the new parameter-names */
4550 for (i = 0; i < vec_size(proto->expression.params); ++i)
4551 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4552 if (!parser_check_qualifiers(parser, var, proto)) {
4559 proto->expression.flags |= var->expression.flags;
4567 if (opts.standard == COMPILER_GMQCC) {
4568 parseerror(parser, "global `%s` already declared here: %s:%i",
4569 var->name, ast_ctx(old).file, ast_ctx(old).line);
4573 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4574 "global `%s` already declared here: %s:%i",
4575 var->name, ast_ctx(old).file, ast_ctx(old).line))
4580 proto = (ast_value*)old;
4581 if (!ast_istype(old, ast_value)) {
4582 parseerror(parser, "internal error: not an ast_value");
4587 if (!parser_check_qualifiers(parser, var, proto)) {
4592 proto->expression.flags |= var->expression.flags;
4597 if (opts.standard == COMPILER_QCC &&
4598 (old = parser_find_field(parser, var->name)))
4600 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4601 parseerror(parser, "global `%s` already declared here: %s:%i",
4602 var->name, ast_ctx(old).file, ast_ctx(old).line);
4609 else /* it's not a global */
4611 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4612 if (old && !isparam) {
4613 parseerror(parser, "local `%s` already declared here: %s:%i",
4614 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4618 old = parser_find_local(parser, var->name, 0, &isparam);
4619 if (old && isparam) {
4620 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4621 "local `%s` is shadowing a parameter", var->name))
4623 parseerror(parser, "local `%s` already declared here: %s:%i",
4624 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4628 if (opts.standard != COMPILER_GMQCC) {
4636 /* in a noref section we simply bump the usecount */
4637 if (noref || parser->noref)
4641 * Create the global/local, and deal with vector types.
4644 if (var->expression.vtype == TYPE_VECTOR)
4646 else if (var->expression.vtype == TYPE_FIELD &&
4647 var->expression.next->expression.vtype == TYPE_VECTOR)
4651 if (!create_vector_members(var, me)) {
4658 /* deal with global variables, fields, functions */
4659 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4660 var->isfield = true;
4661 vec_push(parser->fields, (ast_expression*)var);
4662 util_htset(parser->htfields, var->name, var);
4664 for (i = 0; i < 3; ++i) {
4665 vec_push(parser->fields, (ast_expression*)me[i]);
4666 util_htset(parser->htfields, me[i]->name, me[i]);
4671 vec_push(parser->globals, (ast_expression*)var);
4672 util_htset(parser->htglobals, var->name, var);
4674 for (i = 0; i < 3; ++i) {
4675 vec_push(parser->globals, (ast_expression*)me[i]);
4676 util_htset(parser->htglobals, me[i]->name, me[i]);
4682 /* a static adds itself to be generated like any other global
4683 * but is added to the local namespace instead
4685 char *defname = NULL;
4686 size_t prefix_len, ln;
4688 ln = strlen(parser->function->name);
4689 vec_append(defname, ln, parser->function->name);
4691 vec_append(defname, 2, "::");
4692 /* remember the length up to here */
4693 prefix_len = vec_size(defname);
4695 /* Add it to the local scope */
4696 util_htset(vec_last(parser->variables), var->name, (void*)var);
4697 /* now rename the global */
4698 ln = strlen(var->name);
4699 vec_append(defname, ln, var->name);
4700 ast_value_set_name(var, defname);
4702 /* push it to the to-be-generated globals */
4703 vec_push(parser->globals, (ast_expression*)var);
4705 /* same game for the vector members */
4707 for (i = 0; i < 3; ++i) {
4708 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4710 vec_shrinkto(defname, prefix_len);
4711 ln = strlen(me[i]->name);
4712 vec_append(defname, ln, me[i]->name);
4713 ast_member_set_name(me[i], defname);
4715 vec_push(parser->globals, (ast_expression*)me[i]);
4720 vec_push(localblock->locals, var);
4721 parser_addlocal(parser, var->name, (ast_expression*)var);
4723 for (i = 0; i < 3; ++i) {
4724 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4725 ast_block_collect(localblock, (ast_expression*)me[i]);
4731 me[0] = me[1] = me[2] = NULL;
4736 if (var->expression.vtype == TYPE_ARRAY) {
4738 snprintf(name, sizeof(name), "%s##SET", var->name);
4739 if (!parser_create_array_setter(parser, var, name))
4741 snprintf(name, sizeof(name), "%s##GET", var->name);
4742 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4745 else if (!localblock && !nofields &&
4746 var->expression.vtype == TYPE_FIELD &&
4747 var->expression.next->expression.vtype == TYPE_ARRAY)
4750 ast_expression *telem;
4752 ast_value *array = (ast_value*)var->expression.next;
4754 if (!ast_istype(var->expression.next, ast_value)) {
4755 parseerror(parser, "internal error: field element type must be an ast_value");
4759 snprintf(name, sizeof(name), "%s##SETF", var->name);
4760 if (!parser_create_array_field_setter(parser, array, name))
4763 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4764 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4765 tfield->expression.next = telem;
4766 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4767 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4775 if (parser->tok == ';') {
4776 ast_delete(basetype);
4777 if (!parser_next(parser)) {
4778 parseerror(parser, "error after variable declaration");
4784 if (parser->tok == ',')
4788 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4791 parseerror(parser, "missing comma or semicolon while parsing variables");
4795 if (localblock && opts.standard == COMPILER_QCC) {
4796 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4797 "initializing expression turns variable `%s` into a constant in this standard",
4804 if (parser->tok != '{') {
4805 if (parser->tok != '=') {
4806 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4810 if (!parser_next(parser)) {
4811 parseerror(parser, "error parsing initializer");
4815 else if (opts.standard == COMPILER_QCC) {
4816 parseerror(parser, "expected '=' before function body in this standard");
4819 if (parser->tok == '#') {
4820 ast_function *func = NULL;
4823 parseerror(parser, "cannot declare builtins within functions");
4826 if (var->expression.vtype != TYPE_FUNCTION) {
4827 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4830 if (!parser_next(parser)) {
4831 parseerror(parser, "expected builtin number");
4834 if (parser->tok != TOKEN_INTCONST) {
4835 parseerror(parser, "builtin number must be an integer constant");
4838 if (parser_token(parser)->constval.i < 0) {
4839 parseerror(parser, "builtin number must be an integer greater than zero");
4843 if (var->hasvalue) {
4844 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4845 "builtin `%s` has already been defined\n"
4846 " -> previous declaration here: %s:%i",
4847 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4851 func = ast_function_new(ast_ctx(var), var->name, var);
4853 parseerror(parser, "failed to allocate function for `%s`", var->name);
4856 vec_push(parser->functions, func);
4858 func->builtin = -parser_token(parser)->constval.i-1;
4861 if (!parser_next(parser)) {
4862 parseerror(parser, "expected comma or semicolon");
4864 ast_function_delete(func);
4865 var->constval.vfunc = NULL;
4869 else if (parser->tok == '{' || parser->tok == '[')
4872 parseerror(parser, "cannot declare functions within functions");
4877 ast_ctx(proto) = parser_ctx(parser);
4879 if (!parse_function_body(parser, var))
4881 ast_delete(basetype);
4882 for (i = 0; i < vec_size(parser->gotos); ++i)
4883 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4884 vec_free(parser->gotos);
4885 vec_free(parser->labels);
4888 ast_expression *cexp;
4891 cexp = parse_expression_leave(parser, true, false);
4896 cval = (ast_value*)cexp;
4897 if (cval != parser->nil &&
4898 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4901 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4905 if (opts.standard != COMPILER_GMQCC &&
4906 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4907 qualifier != CV_VAR)
4909 var->cvq = CV_CONST;
4911 if (cval == parser->nil)
4912 var->expression.flags |= AST_FLAG_INITIALIZED;
4915 var->hasvalue = true;
4916 if (cval->expression.vtype == TYPE_STRING)
4917 var->constval.vstring = parser_strdup(cval->constval.vstring);
4918 else if (cval->expression.vtype == TYPE_FIELD)
4919 var->constval.vfield = cval;
4921 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4927 shunt sy = { NULL, NULL };
4930 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4931 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4932 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4933 if (!parser_sy_apply_operator(parser, &sy))
4936 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4937 parseerror(parser, "internal error: leaked operands");
4938 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4948 if (parser->tok == ',') {
4949 if (!parser_next(parser)) {
4950 parseerror(parser, "expected another variable");
4954 if (parser->tok != TOKEN_IDENT) {
4955 parseerror(parser, "expected another variable");
4958 var = ast_value_copy(basetype);
4960 ast_value_set_name(var, parser_tokval(parser));
4961 if (!parser_next(parser)) {
4962 parseerror(parser, "error parsing variable declaration");
4968 if (parser->tok != ';') {
4969 parseerror(parser, "missing semicolon after variables");
4973 if (!parser_next(parser)) {
4974 parseerror(parser, "parse error after variable declaration");
4978 ast_delete(basetype);
4982 if (cleanvar && var)
4984 ast_delete(basetype);
4988 ast_delete(basetype);
4989 if (cleanvar && var)
4991 if (me[0]) ast_member_delete(me[0]);
4992 if (me[1]) ast_member_delete(me[1]);
4993 if (me[2]) ast_member_delete(me[2]);
4997 static bool parser_global_statement(parser_t *parser)
5001 bool is_static = false;
5002 uint32_t qflags = 0;
5003 ast_value *istype = NULL;
5004 char *vstring = NULL;
5006 if (parser->tok == TOKEN_IDENT)
5007 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5009 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5011 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5013 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5015 if (cvq == CV_WRONG)
5017 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5019 else if (parser->tok == TOKEN_KEYWORD)
5021 if (!strcmp(parser_tokval(parser), "typedef")) {
5022 if (!parser_next(parser)) {
5023 parseerror(parser, "expected type definition after 'typedef'");
5026 return parse_typedef(parser);
5028 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5031 else if (parser->tok == '#')
5033 return parse_pragma(parser);
5035 else if (parser->tok == '$')
5037 if (!parser_next(parser)) {
5038 parseerror(parser, "parse error");
5044 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5050 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5052 return util_crc16(old, str, strlen(str));
5055 static void progdefs_crc_file(const char *str)
5057 /* write to progdefs.h here */
5061 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5063 old = progdefs_crc_sum(old, str);
5064 progdefs_crc_file(str);
5068 static void generate_checksum(parser_t *parser)
5070 uint16_t crc = 0xFFFF;
5074 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5075 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5077 progdefs_crc_file("\tint\tpad;\n");
5078 progdefs_crc_file("\tint\tofs_return[3];\n");
5079 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5080 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5081 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5082 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5083 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5084 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5085 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5086 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5088 for (i = 0; i < parser->crc_globals; ++i) {
5089 if (!ast_istype(parser->globals[i], ast_value))
5091 value = (ast_value*)(parser->globals[i]);
5092 switch (value->expression.vtype) {
5093 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5094 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5095 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5096 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5098 crc = progdefs_crc_both(crc, "\tint\t");
5101 crc = progdefs_crc_both(crc, value->name);
5102 crc = progdefs_crc_both(crc, ";\n");
5104 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5105 for (i = 0; i < parser->crc_fields; ++i) {
5106 if (!ast_istype(parser->fields[i], ast_value))
5108 value = (ast_value*)(parser->fields[i]);
5109 switch (value->expression.next->expression.vtype) {
5110 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5111 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5112 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5113 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5115 crc = progdefs_crc_both(crc, "\tint\t");
5118 crc = progdefs_crc_both(crc, value->name);
5119 crc = progdefs_crc_both(crc, ";\n");
5121 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5126 static parser_t *parser;
5133 parser = (parser_t*)mem_a(sizeof(parser_t));
5137 memset(parser, 0, sizeof(*parser));
5139 for (i = 0; i < operator_count; ++i) {
5140 if (operators[i].id == opid1('=')) {
5141 parser->assign_op = operators+i;
5145 if (!parser->assign_op) {
5146 printf("internal error: initializing parser: failed to find assign operator\n");
5151 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5152 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5153 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5154 vec_push(parser->_blocktypedefs, 0);
5156 empty_ctx.file = "<internal>";
5158 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5159 parser->nil->cvq = CV_CONST;
5160 if (OPTS_FLAG(UNTYPED_NIL))
5161 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5165 bool parser_compile()
5167 /* initial lexer/parser state */
5168 parser->lex->flags.noops = true;
5170 if (parser_next(parser))
5172 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5174 if (!parser_global_statement(parser)) {
5175 if (parser->tok == TOKEN_EOF)
5176 parseerror(parser, "unexpected eof");
5177 else if (compile_errors)
5178 parseerror(parser, "there have been errors, bailing out");
5179 lex_close(parser->lex);
5185 parseerror(parser, "parse error");
5186 lex_close(parser->lex);
5191 lex_close(parser->lex);
5194 return !compile_errors;
5197 bool parser_compile_file(const char *filename)
5199 parser->lex = lex_open(filename);
5201 con_err("failed to open file \"%s\"\n", filename);
5204 return parser_compile();
5207 bool parser_compile_string(const char *name, const char *str, size_t len)
5209 parser->lex = lex_open_string(str, len, name);
5211 con_err("failed to create lexer for string \"%s\"\n", name);
5214 return parser_compile();
5217 void parser_cleanup()
5220 for (i = 0; i < vec_size(parser->accessors); ++i) {
5221 ast_delete(parser->accessors[i]->constval.vfunc);
5222 parser->accessors[i]->constval.vfunc = NULL;
5223 ast_delete(parser->accessors[i]);
5225 for (i = 0; i < vec_size(parser->functions); ++i) {
5226 ast_delete(parser->functions[i]);
5228 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5229 ast_delete(parser->imm_vector[i]);
5231 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5232 ast_delete(parser->imm_string[i]);
5234 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5235 ast_delete(parser->imm_float[i]);
5237 for (i = 0; i < vec_size(parser->fields); ++i) {
5238 ast_delete(parser->fields[i]);
5240 for (i = 0; i < vec_size(parser->globals); ++i) {
5241 ast_delete(parser->globals[i]);
5243 vec_free(parser->accessors);
5244 vec_free(parser->functions);
5245 vec_free(parser->imm_vector);
5246 vec_free(parser->imm_string);
5247 vec_free(parser->imm_float);
5248 vec_free(parser->globals);
5249 vec_free(parser->fields);
5251 for (i = 0; i < vec_size(parser->variables); ++i)
5252 util_htdel(parser->variables[i]);
5253 vec_free(parser->variables);
5254 vec_free(parser->_blocklocals);
5255 vec_free(parser->_locals);
5257 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5258 ast_delete(parser->_typedefs[i]);
5259 vec_free(parser->_typedefs);
5260 for (i = 0; i < vec_size(parser->typedefs); ++i)
5261 util_htdel(parser->typedefs[i]);
5262 vec_free(parser->typedefs);
5263 vec_free(parser->_blocktypedefs);
5265 vec_free(parser->_block_ctx);
5267 vec_free(parser->labels);
5268 vec_free(parser->gotos);
5269 vec_free(parser->breaks);
5270 vec_free(parser->continues);
5272 ast_value_delete(parser->nil);
5277 bool parser_finish(const char *output)
5283 if (compile_errors) {
5284 con_out("*** there were compile errors\n");
5288 ir = ir_builder_new("gmqcc_out");
5290 con_out("failed to allocate builder\n");
5294 for (i = 0; i < vec_size(parser->fields); ++i) {
5297 if (!ast_istype(parser->fields[i], ast_value))
5299 field = (ast_value*)parser->fields[i];
5300 hasvalue = field->hasvalue;
5301 field->hasvalue = false;
5302 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5303 con_out("failed to generate field %s\n", field->name);
5304 ir_builder_delete(ir);
5309 ast_expression *subtype;
5310 field->hasvalue = true;
5311 subtype = field->expression.next;
5312 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5313 if (subtype->expression.vtype == TYPE_FIELD)
5314 ifld->fieldtype = subtype->expression.next->expression.vtype;
5315 else if (subtype->expression.vtype == TYPE_FUNCTION)
5316 ifld->outtype = subtype->expression.next->expression.vtype;
5317 (void)!ir_value_set_field(field->ir_v, ifld);
5320 for (i = 0; i < vec_size(parser->globals); ++i) {
5322 if (!ast_istype(parser->globals[i], ast_value))
5324 asvalue = (ast_value*)(parser->globals[i]);
5325 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5326 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5327 "unused global: `%s`", asvalue->name);
5329 if (!ast_global_codegen(asvalue, ir, false)) {
5330 con_out("failed to generate global %s\n", asvalue->name);
5331 ir_builder_delete(ir);
5335 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5336 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5337 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5338 ir_builder_delete(ir);
5342 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5343 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5344 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5345 ir_builder_delete(ir);
5349 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5350 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5351 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5352 ir_builder_delete(ir);
5356 for (i = 0; i < vec_size(parser->globals); ++i) {
5358 if (!ast_istype(parser->globals[i], ast_value))
5360 asvalue = (ast_value*)(parser->globals[i]);
5361 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5363 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5364 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5365 "uninitialized constant: `%s`",
5367 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5368 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5369 "uninitialized global: `%s`",
5372 if (!ast_generate_accessors(asvalue, ir)) {
5373 ir_builder_delete(ir);
5377 for (i = 0; i < vec_size(parser->fields); ++i) {
5379 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5381 if (!ast_istype((ast_expression*)asvalue, ast_value))
5383 if (asvalue->expression.vtype != TYPE_ARRAY)
5385 if (!ast_generate_accessors(asvalue, ir)) {
5386 ir_builder_delete(ir);
5390 for (i = 0; i < vec_size(parser->functions); ++i) {
5391 if (!ast_function_codegen(parser->functions[i], ir)) {
5392 con_out("failed to generate function %s\n", parser->functions[i]->name);
5393 ir_builder_delete(ir);
5398 ir_builder_dump(ir, con_out);
5399 for (i = 0; i < vec_size(parser->functions); ++i) {
5400 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5401 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5402 ir_builder_delete(ir);
5407 if (compile_Werrors) {
5408 con_out("*** there were warnings treated as errors\n");
5409 compile_show_werrors();
5415 ir_builder_dump(ir, con_out);
5417 generate_checksum(parser);
5419 if (!ir_builder_generate(ir, output)) {
5420 con_out("*** failed to generate output file\n");
5421 ir_builder_delete(ir);
5426 ir_builder_delete(ir);