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);
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 (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
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 = (ConstF(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 ||
1045 !ast_compare_type(field->expression.next, exprs[1]))
1047 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1048 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1049 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1050 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1051 exprs[1]->expression.vtype == TYPE_FUNCTION)
1053 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1054 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1057 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1062 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1063 exprs[0]->expression.vtype == TYPE_FIELD &&
1064 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1066 assignop = type_store_instr[TYPE_VECTOR];
1069 assignop = type_store_instr[exprs[0]->expression.vtype];
1072 if (assignop == AINSTR_END) {
1073 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1075 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1077 else if (exprs[1]->expression.vtype != TYPE_NIL &&
1078 !ast_compare_type(exprs[0], exprs[1]))
1080 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1081 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1082 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1083 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1084 exprs[1]->expression.vtype == TYPE_FUNCTION)
1086 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1087 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1090 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1093 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1094 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1096 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1098 case opid3('+','+','P'):
1099 case opid3('-','-','P'):
1101 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1102 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1103 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1106 if (op->id == opid3('+','+','P'))
1107 addop = INSTR_ADD_F;
1109 addop = INSTR_SUB_F;
1110 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1111 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1113 if (ast_istype(exprs[0], ast_entfield)) {
1114 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1116 (ast_expression*)parser_const_float_1(parser));
1118 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1120 (ast_expression*)parser_const_float_1(parser));
1123 case opid3('S','+','+'):
1124 case opid3('S','-','-'):
1126 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1127 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1128 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1131 if (op->id == opid3('S','+','+')) {
1132 addop = INSTR_ADD_F;
1133 subop = INSTR_SUB_F;
1135 addop = INSTR_SUB_F;
1136 subop = INSTR_ADD_F;
1138 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1139 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1141 if (ast_istype(exprs[0], ast_entfield)) {
1142 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1144 (ast_expression*)parser_const_float_1(parser));
1146 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1148 (ast_expression*)parser_const_float_1(parser));
1152 out = (ast_expression*)ast_binary_new(ctx, subop,
1154 (ast_expression*)parser_const_float_1(parser));
1156 case opid2('+','='):
1157 case opid2('-','='):
1158 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1159 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1161 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1162 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1163 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1167 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1168 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1170 if (ast_istype(exprs[0], ast_entfield))
1171 assignop = type_storep_instr[exprs[0]->expression.vtype];
1173 assignop = type_store_instr[exprs[0]->expression.vtype];
1174 switch (exprs[0]->expression.vtype) {
1176 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1177 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1178 exprs[0], exprs[1]);
1181 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1182 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1183 exprs[0], exprs[1]);
1186 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1187 type_name[exprs[0]->expression.vtype],
1188 type_name[exprs[1]->expression.vtype]);
1192 case opid2('*','='):
1193 case opid2('/','='):
1194 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1195 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1196 exprs[0]->expression.vtype == TYPE_VECTOR))
1198 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1199 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1200 parseerror(parser, "invalid types used in expression: %s and %s",
1204 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1205 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1207 if (ast_istype(exprs[0], ast_entfield))
1208 assignop = type_storep_instr[exprs[0]->expression.vtype];
1210 assignop = type_store_instr[exprs[0]->expression.vtype];
1211 switch (exprs[0]->expression.vtype) {
1213 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1214 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1215 exprs[0], exprs[1]);
1218 if (op->id == opid2('*','=')) {
1219 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1220 exprs[0], exprs[1]);
1222 /* there's no DIV_VF */
1223 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1224 (ast_expression*)parser_const_float_1(parser),
1228 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1233 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1234 type_name[exprs[0]->expression.vtype],
1235 type_name[exprs[1]->expression.vtype]);
1239 case opid2('&','='):
1240 case opid2('|','='):
1241 if (NotSameType(TYPE_FLOAT)) {
1242 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1243 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1244 parseerror(parser, "invalid types used in expression: %s and %s",
1248 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1249 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1251 if (ast_istype(exprs[0], ast_entfield))
1252 assignop = type_storep_instr[exprs[0]->expression.vtype];
1254 assignop = type_store_instr[exprs[0]->expression.vtype];
1255 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1256 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1257 exprs[0], exprs[1]);
1259 case opid3('&','~','='):
1260 /* This is like: a &= ~(b);
1261 * But QC has no bitwise-not, so we implement it as
1264 if (NotSameType(TYPE_FLOAT)) {
1265 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1266 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1267 parseerror(parser, "invalid types used in expression: %s and %s",
1271 if (ast_istype(exprs[0], ast_entfield))
1272 assignop = type_storep_instr[exprs[0]->expression.vtype];
1274 assignop = type_store_instr[exprs[0]->expression.vtype];
1275 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1278 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1279 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1281 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1282 asbinstore->keep_dest = true;
1283 out = (ast_expression*)asbinstore;
1289 parseerror(parser, "failed to apply operand %s", op->op);
1293 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1294 vec_push(sy->out, syexp(ctx, out));
1298 static bool parser_close_call(parser_t *parser, shunt *sy)
1300 /* was a function call */
1301 ast_expression *fun;
1307 vec_shrinkby(sy->ops, 1);
1308 fid = sy->ops[vec_size(sy->ops)].off;
1310 /* out[fid] is the function
1311 * everything above is parameters...
1312 * 0 params = nothing
1313 * 1 params = ast_expression
1317 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1318 parseerror(parser, "internal error: function call needs function and parameter list...");
1322 fun = sy->out[fid].out;
1324 if (fun == intrinsic_debug_typestring) {
1326 if (fid+2 != vec_size(sy->out) ||
1327 vec_last(sy->out).block)
1329 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1332 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1333 ast_unref(vec_last(sy->out).out);
1334 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1335 (ast_expression*)parser_const_string(parser, ty, false));
1336 vec_shrinkby(sy->out, 1);
1340 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1342 parseerror(parser, "internal error: failed to create ast_call node");
1346 if (fid+1 == vec_size(sy->out)) {
1349 } else if (fid+2 == vec_size(sy->out)) {
1351 vec_shrinkby(sy->out, 1);
1352 params = sy->out[vec_size(sy->out)].block;
1356 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1358 paramcount = vec_size(params->exprs);
1359 call->params = params->exprs;
1360 params->exprs = NULL;
1363 (void)!ast_call_check_types(call);
1365 parseerror(parser, "invalid function call");
1369 /* overwrite fid, the function, with a call */
1370 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1372 if (fun->expression.vtype != TYPE_FUNCTION) {
1373 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1377 if (!fun->expression.next) {
1378 parseerror(parser, "could not determine function return type");
1381 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1383 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1385 return !parsewarning(parser, WARN_DEPRECATED,
1386 "call to function (which is marked deprecated)\n",
1387 "-> it has been declared here: %s:%i",
1388 ast_ctx(fun).file, ast_ctx(fun).line);
1391 return !parsewarning(parser, WARN_DEPRECATED,
1392 "call to `%s` (which is marked deprecated)\n"
1393 "-> `%s` declared here: %s:%i",
1394 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1396 return !parsewarning(parser, WARN_DEPRECATED,
1397 "call to `%s` (deprecated: %s)\n"
1398 "-> `%s` declared here: %s:%i",
1399 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1403 if (vec_size(fun->expression.params) != paramcount &&
1404 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1405 vec_size(fun->expression.params) < paramcount))
1407 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1408 if (opts.standard == COMPILER_GMQCC)
1411 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1412 " -> `%s` has been declared here: %s:%i",
1413 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1414 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1416 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1417 " -> it has been declared here: %s:%i",
1418 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1419 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1425 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1426 "too %s parameters for call to %s: expected %i, got %i\n"
1427 " -> `%s` has been declared here: %s:%i",
1428 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1429 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1431 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1432 "too %s parameters for function call: expected %i, got %i\n"
1433 " -> it has been declared here: %s:%i",
1434 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1435 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1443 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1445 if (!vec_size(sy->ops)) {
1446 parseerror(parser, "unmatched closing paren");
1449 /* this would for bit a + (x) because there are no operators inside (x)
1450 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1451 parseerror(parser, "empty parenthesis expression");
1455 while (vec_size(sy->ops)) {
1456 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1457 if (!parser_close_call(parser, sy))
1461 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1462 vec_shrinkby(sy->ops, 1);
1463 return !functions_only;
1465 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1468 /* pop off the parenthesis */
1469 vec_shrinkby(sy->ops, 1);
1470 /* then apply the index operator */
1471 if (!parser_sy_apply_operator(parser, sy))
1475 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1478 if (vec_last(parser->pot) != POT_TERNARY1) {
1479 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1482 vec_last(parser->pot) = POT_TERNARY2;
1483 /* pop off the parenthesis */
1484 vec_shrinkby(sy->ops, 1);
1487 if (!parser_sy_apply_operator(parser, sy))
1493 static void parser_reclassify_token(parser_t *parser)
1496 for (i = 0; i < operator_count; ++i) {
1497 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1498 parser->tok = TOKEN_OPERATOR;
1504 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1506 ast_expression *expr = NULL;
1508 bool wantop = false;
1509 bool gotmemberof = false;
1511 /* count the parens because an if starts with one, so the
1512 * end of a condition is an unmatched closing paren
1520 parser->lex->flags.noops = false;
1522 parser_reclassify_token(parser);
1527 gotmemberof = false;
1529 parser->memberof = 0;
1531 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1532 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1534 /* a translatable string */
1538 parseerror(parser, "expected operator or end of statement, got constant");
1542 parser->lex->flags.noops = true;
1543 if (!parser_next(parser) || parser->tok != '(') {
1544 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1547 parser->lex->flags.noops = false;
1548 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1549 parseerror(parser, "expected a constant string in translatable-string extension");
1552 val = parser_const_string(parser, parser_tokval(parser), true);
1556 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1557 DEBUGSHUNTDO(con_out("push string\n"));
1559 if (!parser_next(parser) || parser->tok != ')') {
1560 parseerror(parser, "expected closing paren after translatable string");
1564 else if (parser->tok == TOKEN_IDENT)
1566 ast_expression *var;
1568 parseerror(parser, "expected operator or end of statement");
1573 if (opts.standard == COMPILER_GMQCC)
1575 if (parser->memberof == TYPE_ENTITY) {
1576 /* still get vars first since there could be a fieldpointer */
1577 var = parser_find_var(parser, parser_tokval(parser));
1579 var = parser_find_field(parser, parser_tokval(parser));
1581 else if (parser->memberof == TYPE_VECTOR)
1583 parseerror(parser, "TODO: implement effective vector member access");
1586 else if (parser->memberof) {
1587 parseerror(parser, "namespace for member not found");
1591 var = parser_find_var(parser, parser_tokval(parser));
1593 var = parser_find_var(parser, parser_tokval(parser));
1595 var = parser_find_field(parser, parser_tokval(parser));
1599 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1600 var = (ast_expression*)intrinsic_debug_typestring;
1605 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1611 if (ast_istype(var, ast_value)) {
1612 ((ast_value*)var)->uses++;
1614 else if (ast_istype(var, ast_member)) {
1615 ast_member *mem = (ast_member*)var;
1616 if (ast_istype(mem->owner, ast_value))
1617 ((ast_value*)(mem->owner))->uses++;
1620 vec_push(sy.out, syexp(parser_ctx(parser), var));
1621 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1623 else if (parser->tok == TOKEN_FLOATCONST) {
1626 parseerror(parser, "expected operator or end of statement, got constant");
1630 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1633 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1634 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1636 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1639 parseerror(parser, "expected operator or end of statement, got constant");
1643 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1646 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1647 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1649 else if (parser->tok == TOKEN_STRINGCONST) {
1652 parseerror(parser, "expected operator or end of statement, got constant");
1656 val = parser_const_string(parser, parser_tokval(parser), false);
1659 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1660 DEBUGSHUNTDO(con_out("push string\n"));
1662 else if (parser->tok == TOKEN_VECTORCONST) {
1665 parseerror(parser, "expected operator or end of statement, got constant");
1669 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1672 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1673 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1674 parser_token(parser)->constval.v.x,
1675 parser_token(parser)->constval.v.y,
1676 parser_token(parser)->constval.v.z));
1678 else if (parser->tok == '(') {
1679 parseerror(parser, "internal error: '(' should be classified as operator");
1682 else if (parser->tok == '[') {
1683 parseerror(parser, "internal error: '[' should be classified as operator");
1686 else if (parser->tok == ')') {
1688 DEBUGSHUNTDO(con_out("do[op] )\n"));
1692 /* we do expect an operator next */
1693 /* closing an opening paren */
1694 if (!parser_close_paren(parser, &sy, false))
1696 if (vec_last(parser->pot) != POT_PAREN) {
1697 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1700 vec_pop(parser->pot);
1702 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1706 /* allowed for function calls */
1707 if (!parser_close_paren(parser, &sy, true))
1709 if (vec_last(parser->pot) != POT_PAREN) {
1710 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1713 vec_pop(parser->pot);
1717 else if (parser->tok == ']') {
1719 parseerror(parser, "operand expected");
1723 if (!parser_close_paren(parser, &sy, false))
1725 if (vec_last(parser->pot) != POT_PAREN) {
1726 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1729 vec_pop(parser->pot);
1732 else if (parser->tok == TOKEN_TYPENAME) {
1733 parseerror(parser, "unexpected typename");
1736 else if (parser->tok != TOKEN_OPERATOR) {
1738 parseerror(parser, "expected operator or end of statement");
1745 /* classify the operator */
1746 const oper_info *op;
1747 const oper_info *olast = NULL;
1749 for (o = 0; o < operator_count; ++o) {
1750 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1751 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1752 !strcmp(parser_tokval(parser), operators[o].op))
1757 if (o == operator_count) {
1758 /* no operator found... must be the end of the statement */
1761 /* found an operator */
1764 /* when declaring variables, a comma starts a new variable */
1765 if (op->id == opid1(',') && !parens && stopatcomma) {
1766 /* fixup the token */
1771 /* a colon without a pervious question mark cannot be a ternary */
1772 if (!ternaries && op->id == opid2(':','?')) {
1777 if (op->id == opid1(',')) {
1778 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1779 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1783 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1784 olast = &operators[vec_last(sy.ops).etype-1];
1787 (op->prec < olast->prec) ||
1788 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1790 if (!parser_sy_apply_operator(parser, &sy))
1792 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1793 olast = &operators[vec_last(sy.ops).etype-1];
1798 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1799 /* for gmqcc standard: open up the namespace of the previous type */
1800 ast_expression *prevex = vec_last(sy.out).out;
1802 parseerror(parser, "unexpected member operator");
1805 if (prevex->expression.vtype == TYPE_ENTITY)
1806 parser->memberof = TYPE_ENTITY;
1807 else if (prevex->expression.vtype == TYPE_VECTOR)
1808 parser->memberof = TYPE_VECTOR;
1810 parseerror(parser, "type error: type has no members");
1816 if (op->id == opid1('(')) {
1818 size_t sycount = vec_size(sy.out);
1819 DEBUGSHUNTDO(con_out("push [op] (\n"));
1820 ++parens; vec_push(parser->pot, POT_PAREN);
1821 /* we expected an operator, this is the function-call operator */
1822 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1824 ++parens; vec_push(parser->pot, POT_PAREN);
1825 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1826 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1829 } else if (op->id == opid1('[')) {
1831 parseerror(parser, "unexpected array subscript");
1834 ++parens; vec_push(parser->pot, POT_PAREN);
1835 /* push both the operator and the paren, this makes life easier */
1836 vec_push(sy.ops, syop(parser_ctx(parser), op));
1837 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1839 } else if (op->id == opid2('?',':')) {
1840 vec_push(sy.ops, syop(parser_ctx(parser), op));
1841 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1844 vec_push(parser->pot, POT_TERNARY1);
1845 } else if (op->id == opid2(':','?')) {
1846 if (!vec_size(parser->pot)) {
1847 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1850 if (vec_last(parser->pot) != POT_TERNARY1) {
1851 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1854 if (!parser_close_paren(parser, &sy, false))
1856 vec_push(sy.ops, syop(parser_ctx(parser), op));
1860 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1861 vec_push(sy.ops, syop(parser_ctx(parser), op));
1862 wantop = !!(op->flags & OP_SUFFIX);
1865 if (!parser_next(parser)) {
1868 if (parser->tok == ';' ||
1869 (!parens && parser->tok == ']'))
1875 while (vec_size(sy.ops)) {
1876 if (!parser_sy_apply_operator(parser, &sy))
1880 parser->lex->flags.noops = true;
1881 if (!vec_size(sy.out)) {
1882 parseerror(parser, "empty expression");
1885 expr = sy.out[0].out;
1888 DEBUGSHUNTDO(con_out("shunt done\n"));
1889 if (vec_size(parser->pot)) {
1890 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1893 vec_free(parser->pot);
1897 parser->lex->flags.noops = true;
1903 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1905 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1908 if (!parser_next(parser)) {
1915 static void parser_enterblock(parser_t *parser)
1917 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1918 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1919 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1920 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1921 vec_push(parser->_block_ctx, parser_ctx(parser));
1924 static bool parser_leaveblock(parser_t *parser)
1927 size_t locals, typedefs;
1929 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1930 parseerror(parser, "internal error: parser_leaveblock with no block");
1934 util_htdel(vec_last(parser->variables));
1935 vec_pop(parser->variables);
1936 if (!vec_size(parser->_blocklocals)) {
1937 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1941 locals = vec_last(parser->_blocklocals);
1942 vec_pop(parser->_blocklocals);
1943 while (vec_size(parser->_locals) != locals) {
1944 ast_expression *e = vec_last(parser->_locals);
1945 ast_value *v = (ast_value*)e;
1946 vec_pop(parser->_locals);
1947 if (ast_istype(e, ast_value) && !v->uses) {
1948 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1953 typedefs = vec_last(parser->_blocktypedefs);
1954 while (vec_size(parser->_typedefs) != typedefs) {
1955 ast_delete(vec_last(parser->_typedefs));
1956 vec_pop(parser->_typedefs);
1958 util_htdel(vec_last(parser->typedefs));
1959 vec_pop(parser->typedefs);
1961 vec_pop(parser->_block_ctx);
1965 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1967 vec_push(parser->_locals, e);
1968 util_htset(vec_last(parser->variables), name, (void*)e);
1971 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1975 ast_expression *prev;
1977 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1980 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1983 parseerror(parser, "internal error: failed to process condition");
1988 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1990 /* vector types need to be cast to true booleans */
1991 ast_binary *bin = (ast_binary*)cond;
1992 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1994 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1996 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1999 parseerror(parser, "internal error: failed to process condition");
2006 unary = (ast_unary*)cond;
2007 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2009 cond = unary->operand;
2010 unary->operand = NULL;
2013 unary = (ast_unary*)cond;
2017 parseerror(parser, "internal error: failed to process condition");
2019 if (ifnot) *_ifnot = !*_ifnot;
2023 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2026 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2029 lex_ctx ctx = parser_ctx(parser);
2031 (void)block; /* not touching */
2033 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2034 if (!parser_next(parser)) {
2035 parseerror(parser, "expected condition or 'not'");
2038 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2040 if (!parser_next(parser)) {
2041 parseerror(parser, "expected condition in parenthesis");
2045 if (parser->tok != '(') {
2046 parseerror(parser, "expected 'if' condition in parenthesis");
2049 /* parse into the expression */
2050 if (!parser_next(parser)) {
2051 parseerror(parser, "expected 'if' condition after opening paren");
2054 /* parse the condition */
2055 cond = parse_expression_leave(parser, false);
2059 if (parser->tok != ')') {
2060 parseerror(parser, "expected closing paren after 'if' condition");
2064 /* parse into the 'then' branch */
2065 if (!parser_next(parser)) {
2066 parseerror(parser, "expected statement for on-true branch of 'if'");
2070 if (!parse_statement_or_block(parser, &ontrue)) {
2074 /* check for an else */
2075 if (!strcmp(parser_tokval(parser), "else")) {
2076 /* parse into the 'else' branch */
2077 if (!parser_next(parser)) {
2078 parseerror(parser, "expected on-false branch after 'else'");
2083 if (!parse_statement_or_block(parser, &onfalse)) {
2090 cond = process_condition(parser, cond, &ifnot);
2092 if (ontrue) ast_delete(ontrue);
2093 if (onfalse) ast_delete(onfalse);
2098 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2100 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2101 *out = (ast_expression*)ifthen;
2105 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2106 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2111 /* skip the 'while' and get the body */
2112 if (!parser_next(parser)) {
2113 if (OPTS_FLAG(LOOP_LABELS))
2114 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2116 parseerror(parser, "expected 'while' condition in parenthesis");
2120 if (parser->tok == ':') {
2121 if (!OPTS_FLAG(LOOP_LABELS))
2122 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2123 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2124 parseerror(parser, "expected loop label");
2127 label = util_strdup(parser_tokval(parser));
2128 if (!parser_next(parser)) {
2130 parseerror(parser, "expected 'while' condition in parenthesis");
2135 if (parser->tok != '(') {
2136 parseerror(parser, "expected 'while' condition in parenthesis");
2140 vec_push(parser->breaks, label);
2141 vec_push(parser->continues, label);
2143 rv = parse_while_go(parser, block, out);
2146 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2147 parseerror(parser, "internal error: label stack corrupted");
2153 vec_pop(parser->breaks);
2154 vec_pop(parser->continues);
2159 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2162 ast_expression *cond, *ontrue;
2166 lex_ctx ctx = parser_ctx(parser);
2168 (void)block; /* not touching */
2170 /* parse into the expression */
2171 if (!parser_next(parser)) {
2172 parseerror(parser, "expected 'while' condition after opening paren");
2175 /* parse the condition */
2176 cond = parse_expression_leave(parser, false);
2180 if (parser->tok != ')') {
2181 parseerror(parser, "expected closing paren after 'while' condition");
2185 /* parse into the 'then' branch */
2186 if (!parser_next(parser)) {
2187 parseerror(parser, "expected while-loop body");
2191 if (!parse_statement_or_block(parser, &ontrue)) {
2196 cond = process_condition(parser, cond, &ifnot);
2201 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2202 *out = (ast_expression*)aloop;
2206 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2207 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2212 /* skip the 'do' and get the body */
2213 if (!parser_next(parser)) {
2214 if (OPTS_FLAG(LOOP_LABELS))
2215 parseerror(parser, "expected loop label or body");
2217 parseerror(parser, "expected loop body");
2221 if (parser->tok == ':') {
2222 if (!OPTS_FLAG(LOOP_LABELS))
2223 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2224 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2225 parseerror(parser, "expected loop label");
2228 label = util_strdup(parser_tokval(parser));
2229 if (!parser_next(parser)) {
2231 parseerror(parser, "expected loop body");
2236 vec_push(parser->breaks, label);
2237 vec_push(parser->continues, label);
2239 rv = parse_dowhile_go(parser, block, out);
2242 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2243 parseerror(parser, "internal error: label stack corrupted");
2249 vec_pop(parser->breaks);
2250 vec_pop(parser->continues);
2255 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2258 ast_expression *cond, *ontrue;
2262 lex_ctx ctx = parser_ctx(parser);
2264 (void)block; /* not touching */
2266 if (!parse_statement_or_block(parser, &ontrue))
2269 /* expect the "while" */
2270 if (parser->tok != TOKEN_KEYWORD ||
2271 strcmp(parser_tokval(parser), "while"))
2273 parseerror(parser, "expected 'while' and condition");
2278 /* skip the 'while' and check for opening paren */
2279 if (!parser_next(parser) || parser->tok != '(') {
2280 parseerror(parser, "expected 'while' condition in parenthesis");
2284 /* parse into the expression */
2285 if (!parser_next(parser)) {
2286 parseerror(parser, "expected 'while' condition after opening paren");
2290 /* parse the condition */
2291 cond = parse_expression_leave(parser, false);
2295 if (parser->tok != ')') {
2296 parseerror(parser, "expected closing paren after 'while' condition");
2302 if (!parser_next(parser) || parser->tok != ';') {
2303 parseerror(parser, "expected semicolon after condition");
2309 if (!parser_next(parser)) {
2310 parseerror(parser, "parse error");
2316 cond = process_condition(parser, cond, &ifnot);
2321 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2322 *out = (ast_expression*)aloop;
2326 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2327 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2332 /* skip the 'for' and check for opening paren */
2333 if (!parser_next(parser)) {
2334 if (OPTS_FLAG(LOOP_LABELS))
2335 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2337 parseerror(parser, "expected 'for' expressions in parenthesis");
2341 if (parser->tok == ':') {
2342 if (!OPTS_FLAG(LOOP_LABELS))
2343 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2344 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2345 parseerror(parser, "expected loop label");
2348 label = util_strdup(parser_tokval(parser));
2349 if (!parser_next(parser)) {
2351 parseerror(parser, "expected 'for' expressions in parenthesis");
2356 if (parser->tok != '(') {
2357 parseerror(parser, "expected 'for' expressions in parenthesis");
2361 vec_push(parser->breaks, label);
2362 vec_push(parser->continues, label);
2364 rv = parse_for_go(parser, block, out);
2367 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2368 parseerror(parser, "internal error: label stack corrupted");
2374 vec_pop(parser->breaks);
2375 vec_pop(parser->continues);
2379 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2382 ast_expression *initexpr, *cond, *increment, *ontrue;
2388 lex_ctx ctx = parser_ctx(parser);
2390 parser_enterblock(parser);
2397 /* parse into the expression */
2398 if (!parser_next(parser)) {
2399 parseerror(parser, "expected 'for' initializer after opening paren");
2404 if (parser->tok == TOKEN_IDENT)
2405 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2407 if (typevar || parser->tok == TOKEN_TYPENAME) {
2408 if (opts.standard != COMPILER_GMQCC) {
2409 if (parsewarning(parser, WARN_EXTENSIONS,
2410 "current standard does not allow variable declarations in for-loop initializers"))
2413 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2416 else if (parser->tok != ';')
2418 initexpr = parse_expression_leave(parser, false);
2423 /* move on to condition */
2424 if (parser->tok != ';') {
2425 parseerror(parser, "expected semicolon after for-loop initializer");
2428 if (!parser_next(parser)) {
2429 parseerror(parser, "expected for-loop condition");
2433 /* parse the condition */
2434 if (parser->tok != ';') {
2435 cond = parse_expression_leave(parser, false);
2440 /* move on to incrementor */
2441 if (parser->tok != ';') {
2442 parseerror(parser, "expected semicolon after for-loop initializer");
2445 if (!parser_next(parser)) {
2446 parseerror(parser, "expected for-loop condition");
2450 /* parse the incrementor */
2451 if (parser->tok != ')') {
2452 increment = parse_expression_leave(parser, false);
2455 if (!ast_side_effects(increment)) {
2456 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2462 if (parser->tok != ')') {
2463 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2466 /* parse into the 'then' branch */
2467 if (!parser_next(parser)) {
2468 parseerror(parser, "expected for-loop body");
2471 if (!parse_statement_or_block(parser, &ontrue))
2475 cond = process_condition(parser, cond, &ifnot);
2479 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2480 *out = (ast_expression*)aloop;
2482 if (!parser_leaveblock(parser))
2486 if (initexpr) ast_delete(initexpr);
2487 if (cond) ast_delete(cond);
2488 if (increment) ast_delete(increment);
2489 (void)!parser_leaveblock(parser);
2493 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2495 ast_expression *exp = NULL;
2496 ast_return *ret = NULL;
2497 ast_value *expected = parser->function->vtype;
2499 lex_ctx ctx = parser_ctx(parser);
2501 (void)block; /* not touching */
2503 if (!parser_next(parser)) {
2504 parseerror(parser, "expected return expression");
2508 if (parser->tok != ';') {
2509 exp = parse_expression(parser, false);
2513 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2514 parseerror(parser, "return with invalid expression");
2517 ret = ast_return_new(ctx, exp);
2523 if (!parser_next(parser))
2524 parseerror(parser, "parse error");
2525 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2526 if (opts.standard != COMPILER_GMQCC)
2527 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2529 parseerror(parser, "return without value");
2531 ret = ast_return_new(ctx, NULL);
2533 *out = (ast_expression*)ret;
2537 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2540 unsigned int levels = 0;
2541 lex_ctx ctx = parser_ctx(parser);
2542 const char **loops = (is_continue ? parser->continues : parser->breaks);
2544 (void)block; /* not touching */
2545 if (!parser_next(parser)) {
2546 parseerror(parser, "expected semicolon or loop label");
2550 if (parser->tok == TOKEN_IDENT) {
2551 if (!OPTS_FLAG(LOOP_LABELS))
2552 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2553 i = vec_size(loops);
2555 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2558 parseerror(parser, "no such loop to %s: `%s`",
2559 (is_continue ? "continue" : "break out of"),
2560 parser_tokval(parser));
2565 if (!parser_next(parser)) {
2566 parseerror(parser, "expected semicolon");
2571 if (parser->tok != ';') {
2572 parseerror(parser, "expected semicolon");
2576 if (!parser_next(parser))
2577 parseerror(parser, "parse error");
2579 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2583 /* returns true when it was a variable qualifier, false otherwise!
2584 * on error, cvq is set to CV_WRONG
2586 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2588 bool had_const = false;
2589 bool had_var = false;
2590 bool had_noref = false;
2591 bool had_attrib = false;
2592 bool had_static = false;
2597 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2599 /* parse an attribute */
2600 if (!parser_next(parser)) {
2601 parseerror(parser, "expected attribute after `[[`");
2605 if (!strcmp(parser_tokval(parser), "noreturn")) {
2606 flags |= AST_FLAG_NORETURN;
2607 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2608 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2613 else if (!strcmp(parser_tokval(parser), "noref")) {
2615 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2616 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2621 else if (!strcmp(parser_tokval(parser), "inline")) {
2622 flags |= AST_FLAG_INLINE;
2623 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2624 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2631 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2632 flags |= AST_FLAG_DEPRECATED;
2635 if (!parser_next(parser)) {
2636 parseerror(parser, "parse error in attribute");
2640 if (parser->tok == '(') {
2641 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2642 parseerror(parser, "`deprecated` attribute missing parameter");
2646 *message = util_strdup(parser_tokval(parser));
2648 if (!parser_next(parser)) {
2649 parseerror(parser, "parse error in attribute");
2653 if(parser->tok != ')') {
2654 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2658 if (!parser_next(parser)) {
2659 parseerror(parser, "parse error in attribute");
2664 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2665 parseerror(parser, "`deprecated` attribute expected `]]`");
2668 if (*message) mem_d(*message);
2676 /* Skip tokens until we hit a ]] */
2677 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2678 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2679 if (!parser_next(parser)) {
2680 parseerror(parser, "error inside attribute");
2687 else if (!strcmp(parser_tokval(parser), "static"))
2689 else if (!strcmp(parser_tokval(parser), "const"))
2691 else if (!strcmp(parser_tokval(parser), "var"))
2693 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2695 else if (!strcmp(parser_tokval(parser), "noref"))
2697 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2702 if (!parser_next(parser))
2712 *is_static = had_static;
2716 parseerror(parser, "parse error after variable qualifier");
2721 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2722 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2727 /* skip the 'while' and get the body */
2728 if (!parser_next(parser)) {
2729 if (OPTS_FLAG(LOOP_LABELS))
2730 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2732 parseerror(parser, "expected 'switch' operand in parenthesis");
2736 if (parser->tok == ':') {
2737 if (!OPTS_FLAG(LOOP_LABELS))
2738 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2739 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2740 parseerror(parser, "expected loop label");
2743 label = util_strdup(parser_tokval(parser));
2744 if (!parser_next(parser)) {
2746 parseerror(parser, "expected 'switch' operand in parenthesis");
2751 if (parser->tok != '(') {
2752 parseerror(parser, "expected 'switch' operand in parenthesis");
2756 vec_push(parser->breaks, label);
2758 rv = parse_switch_go(parser, block, out);
2761 if (vec_last(parser->breaks) != label) {
2762 parseerror(parser, "internal error: label stack corrupted");
2768 vec_pop(parser->breaks);
2773 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2775 ast_expression *operand;
2778 ast_switch *switchnode;
2779 ast_switch_case swcase;
2782 bool noref, is_static;
2783 uint32_t qflags = 0;
2785 lex_ctx ctx = parser_ctx(parser);
2787 (void)block; /* not touching */
2790 /* parse into the expression */
2791 if (!parser_next(parser)) {
2792 parseerror(parser, "expected switch operand");
2795 /* parse the operand */
2796 operand = parse_expression_leave(parser, false);
2800 switchnode = ast_switch_new(ctx, operand);
2803 if (parser->tok != ')') {
2804 ast_delete(switchnode);
2805 parseerror(parser, "expected closing paren after 'switch' operand");
2809 /* parse over the opening paren */
2810 if (!parser_next(parser) || parser->tok != '{') {
2811 ast_delete(switchnode);
2812 parseerror(parser, "expected list of cases");
2816 if (!parser_next(parser)) {
2817 ast_delete(switchnode);
2818 parseerror(parser, "expected 'case' or 'default'");
2822 /* new block; allow some variables to be declared here */
2823 parser_enterblock(parser);
2826 if (parser->tok == TOKEN_IDENT)
2827 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2828 if (typevar || parser->tok == TOKEN_TYPENAME) {
2829 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2830 ast_delete(switchnode);
2835 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2837 if (cvq == CV_WRONG) {
2838 ast_delete(switchnode);
2841 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2842 ast_delete(switchnode);
2851 while (parser->tok != '}') {
2852 ast_block *caseblock;
2854 if (!strcmp(parser_tokval(parser), "case")) {
2855 if (!parser_next(parser)) {
2856 ast_delete(switchnode);
2857 parseerror(parser, "expected expression for case");
2860 swcase.value = parse_expression_leave(parser, false);
2861 if (!swcase.value) {
2862 ast_delete(switchnode);
2863 parseerror(parser, "expected expression for case");
2866 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2867 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2868 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2874 else if (!strcmp(parser_tokval(parser), "default")) {
2875 swcase.value = NULL;
2876 if (!parser_next(parser)) {
2877 ast_delete(switchnode);
2878 parseerror(parser, "expected colon");
2883 ast_delete(switchnode);
2884 parseerror(parser, "expected 'case' or 'default'");
2888 /* Now the colon and body */
2889 if (parser->tok != ':') {
2890 if (swcase.value) ast_unref(swcase.value);
2891 ast_delete(switchnode);
2892 parseerror(parser, "expected colon");
2896 if (!parser_next(parser)) {
2897 if (swcase.value) ast_unref(swcase.value);
2898 ast_delete(switchnode);
2899 parseerror(parser, "expected statements or case");
2902 caseblock = ast_block_new(parser_ctx(parser));
2904 if (swcase.value) ast_unref(swcase.value);
2905 ast_delete(switchnode);
2908 swcase.code = (ast_expression*)caseblock;
2909 vec_push(switchnode->cases, swcase);
2911 ast_expression *expr;
2912 if (parser->tok == '}')
2914 if (parser->tok == TOKEN_KEYWORD) {
2915 if (!strcmp(parser_tokval(parser), "case") ||
2916 !strcmp(parser_tokval(parser), "default"))
2921 if (!parse_statement(parser, caseblock, &expr, true)) {
2922 ast_delete(switchnode);
2927 if (!ast_block_add_expr(caseblock, expr)) {
2928 ast_delete(switchnode);
2934 parser_leaveblock(parser);
2937 if (parser->tok != '}') {
2938 ast_delete(switchnode);
2939 parseerror(parser, "expected closing paren of case list");
2942 if (!parser_next(parser)) {
2943 ast_delete(switchnode);
2944 parseerror(parser, "parse error after switch");
2947 *out = (ast_expression*)switchnode;
2951 static bool parse_goto(parser_t *parser, ast_expression **out)
2956 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2957 parseerror(parser, "expected label name after `goto`");
2961 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2963 for (i = 0; i < vec_size(parser->labels); ++i) {
2964 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2965 ast_goto_set_label(gt, parser->labels[i]);
2969 if (i == vec_size(parser->labels))
2970 vec_push(parser->gotos, gt);
2972 if (!parser_next(parser) || parser->tok != ';') {
2973 parseerror(parser, "semicolon expected after goto label");
2976 if (!parser_next(parser)) {
2977 parseerror(parser, "parse error after goto");
2981 *out = (ast_expression*)gt;
2985 static bool parse_skipwhite(parser_t *parser)
2988 if (!parser_next(parser))
2990 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2991 return parser->tok < TOKEN_ERROR;
2994 static bool parse_eol(parser_t *parser)
2996 if (!parse_skipwhite(parser))
2998 return parser->tok == TOKEN_EOL;
3001 static bool parse_pragma_do(parser_t *parser)
3003 if (!parser_next(parser) ||
3004 parser->tok != TOKEN_IDENT ||
3005 strcmp(parser_tokval(parser), "pragma"))
3007 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3010 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3011 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3015 if (!strcmp(parser_tokval(parser), "noref")) {
3016 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3017 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3020 parser->noref = !!parser_token(parser)->constval.i;
3021 if (!parse_eol(parser)) {
3022 parseerror(parser, "parse error after `noref` pragma");
3028 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3035 static bool parse_pragma(parser_t *parser)
3038 parser->lex->flags.preprocessing = true;
3039 parser->lex->flags.mergelines = true;
3040 rv = parse_pragma_do(parser);
3041 if (parser->tok != TOKEN_EOL) {
3042 parseerror(parser, "junk after pragma");
3045 parser->lex->flags.preprocessing = false;
3046 parser->lex->flags.mergelines = false;
3047 if (!parser_next(parser)) {
3048 parseerror(parser, "parse error after pragma");
3054 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3056 bool noref, is_static;
3058 uint32_t qflags = 0;
3059 ast_value *typevar = NULL;
3060 char *vstring = NULL;
3064 if (parser->tok == TOKEN_IDENT)
3065 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3067 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3069 /* local variable */
3071 parseerror(parser, "cannot declare a variable from here");
3074 if (opts.standard == COMPILER_QCC) {
3075 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3078 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3082 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3084 if (cvq == CV_WRONG)
3086 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3088 else if (parser->tok == TOKEN_KEYWORD)
3090 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3095 if (!parser_next(parser)) {
3096 parseerror(parser, "parse error after __builtin_debug_printtype");
3100 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3102 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3103 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3104 if (!parser_next(parser)) {
3105 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3111 if (!parse_statement(parser, block, out, allow_cases))
3114 con_out("__builtin_debug_printtype: got no output node\n");
3117 ast_type_to_string(*out, ty, sizeof(ty));
3118 con_out("__builtin_debug_printtype: `%s`\n", ty);
3123 else if (!strcmp(parser_tokval(parser), "return"))
3125 return parse_return(parser, block, out);
3127 else if (!strcmp(parser_tokval(parser), "if"))
3129 return parse_if(parser, block, out);
3131 else if (!strcmp(parser_tokval(parser), "while"))
3133 return parse_while(parser, block, out);
3135 else if (!strcmp(parser_tokval(parser), "do"))
3137 return parse_dowhile(parser, block, out);
3139 else if (!strcmp(parser_tokval(parser), "for"))
3141 if (opts.standard == COMPILER_QCC) {
3142 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3145 return parse_for(parser, block, out);
3147 else if (!strcmp(parser_tokval(parser), "break"))
3149 return parse_break_continue(parser, block, out, false);
3151 else if (!strcmp(parser_tokval(parser), "continue"))
3153 return parse_break_continue(parser, block, out, true);
3155 else if (!strcmp(parser_tokval(parser), "switch"))
3157 return parse_switch(parser, block, out);
3159 else if (!strcmp(parser_tokval(parser), "case") ||
3160 !strcmp(parser_tokval(parser), "default"))
3163 parseerror(parser, "unexpected 'case' label");
3168 else if (!strcmp(parser_tokval(parser), "goto"))
3170 return parse_goto(parser, out);
3172 else if (!strcmp(parser_tokval(parser), "typedef"))
3174 if (!parser_next(parser)) {
3175 parseerror(parser, "expected type definition after 'typedef'");
3178 return parse_typedef(parser);
3180 parseerror(parser, "Unexpected keyword");
3183 else if (parser->tok == '{')
3186 inner = parse_block(parser);
3189 *out = (ast_expression*)inner;
3192 else if (parser->tok == ':')
3196 if (!parser_next(parser)) {
3197 parseerror(parser, "expected label name");
3200 if (parser->tok != TOKEN_IDENT) {
3201 parseerror(parser, "label must be an identifier");
3204 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3207 vec_push(parser->labels, label);
3208 *out = (ast_expression*)label;
3209 if (!parser_next(parser)) {
3210 parseerror(parser, "parse error after label");
3213 for (i = 0; i < vec_size(parser->gotos); ++i) {
3214 if (!strcmp(parser->gotos[i]->name, label->name)) {
3215 ast_goto_set_label(parser->gotos[i], label);
3216 vec_remove(parser->gotos, i, 1);
3222 else if (parser->tok == ';')
3224 if (!parser_next(parser)) {
3225 parseerror(parser, "parse error after empty statement");
3232 ast_expression *exp = parse_expression(parser, false);
3236 if (!ast_side_effects(exp)) {
3237 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3244 static bool parse_block_into(parser_t *parser, ast_block *block)
3248 parser_enterblock(parser);
3250 if (!parser_next(parser)) { /* skip the '{' */
3251 parseerror(parser, "expected function body");
3255 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3257 ast_expression *expr = NULL;
3258 if (parser->tok == '}')
3261 if (!parse_statement(parser, block, &expr, false)) {
3262 /* parseerror(parser, "parse error"); */
3268 if (!ast_block_add_expr(block, expr)) {
3275 if (parser->tok != '}') {
3278 (void)parser_next(parser);
3282 if (!parser_leaveblock(parser))
3284 return retval && !!block;
3287 static ast_block* parse_block(parser_t *parser)
3290 block = ast_block_new(parser_ctx(parser));
3293 if (!parse_block_into(parser, block)) {
3294 ast_block_delete(block);
3300 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3302 if (parser->tok == '{') {
3303 *out = (ast_expression*)parse_block(parser);
3306 return parse_statement(parser, NULL, out, false);
3309 static bool create_vector_members(ast_value *var, ast_member **me)
3312 size_t len = strlen(var->name);
3314 for (i = 0; i < 3; ++i) {
3315 char *name = (char*)mem_a(len+3);
3316 memcpy(name, var->name, len);
3318 name[len+1] = 'x'+i;
3320 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3329 do { ast_member_delete(me[--i]); } while(i);
3333 static bool parse_function_body(parser_t *parser, ast_value *var)
3335 ast_block *block = NULL;
3340 ast_expression *framenum = NULL;
3341 ast_expression *nextthink = NULL;
3342 /* None of the following have to be deleted */
3343 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3344 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3345 bool has_frame_think;
3349 has_frame_think = false;
3350 old = parser->function;
3352 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3353 parseerror(parser, "gotos/labels leaking");
3357 if (var->expression.flags & AST_FLAG_VARIADIC) {
3358 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3359 "variadic function with implementation will not be able to access additional parameters"))
3365 if (parser->tok == '[') {
3366 /* got a frame definition: [ framenum, nextthink ]
3367 * this translates to:
3368 * self.frame = framenum;
3369 * self.nextthink = time + 0.1;
3370 * self.think = nextthink;
3374 fld_think = parser_find_field(parser, "think");
3375 fld_nextthink = parser_find_field(parser, "nextthink");
3376 fld_frame = parser_find_field(parser, "frame");
3377 if (!fld_think || !fld_nextthink || !fld_frame) {
3378 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3379 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3382 gbl_time = parser_find_global(parser, "time");
3383 gbl_self = parser_find_global(parser, "self");
3384 if (!gbl_time || !gbl_self) {
3385 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3386 parseerror(parser, "please declare the following globals: `time`, `self`");
3390 if (!parser_next(parser))
3393 framenum = parse_expression_leave(parser, true);
3395 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3398 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3399 ast_unref(framenum);
3400 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3404 if (parser->tok != ',') {
3405 ast_unref(framenum);
3406 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3407 parseerror(parser, "Got a %i\n", parser->tok);
3411 if (!parser_next(parser)) {
3412 ast_unref(framenum);
3416 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3418 /* qc allows the use of not-yet-declared functions here
3419 * - this automatically creates a prototype */
3420 ast_value *thinkfunc;
3421 ast_expression *functype = fld_think->expression.next;
3423 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3424 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3425 ast_unref(framenum);
3426 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3430 if (!parser_next(parser)) {
3431 ast_unref(framenum);
3432 ast_delete(thinkfunc);
3436 vec_push(parser->globals, (ast_expression*)thinkfunc);
3437 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3438 nextthink = (ast_expression*)thinkfunc;
3441 nextthink = parse_expression_leave(parser, true);
3443 ast_unref(framenum);
3444 parseerror(parser, "expected a think-function in [frame,think] notation");
3449 if (!ast_istype(nextthink, ast_value)) {
3450 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3454 if (retval && parser->tok != ']') {
3455 parseerror(parser, "expected closing `]` for [frame,think] notation");
3459 if (retval && !parser_next(parser)) {
3463 if (retval && parser->tok != '{') {
3464 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3469 ast_unref(nextthink);
3470 ast_unref(framenum);
3474 has_frame_think = true;
3477 block = ast_block_new(parser_ctx(parser));
3479 parseerror(parser, "failed to allocate block");
3480 if (has_frame_think) {
3481 ast_unref(nextthink);
3482 ast_unref(framenum);
3487 if (has_frame_think) {
3489 ast_expression *self_frame;
3490 ast_expression *self_nextthink;
3491 ast_expression *self_think;
3492 ast_expression *time_plus_1;
3493 ast_store *store_frame;
3494 ast_store *store_nextthink;
3495 ast_store *store_think;
3497 ctx = parser_ctx(parser);
3498 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3499 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3500 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3502 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3503 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3505 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3506 if (self_frame) ast_delete(self_frame);
3507 if (self_nextthink) ast_delete(self_nextthink);
3508 if (self_think) ast_delete(self_think);
3509 if (time_plus_1) ast_delete(time_plus_1);
3515 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3516 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3517 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3520 ast_delete(self_frame);
3523 if (!store_nextthink) {
3524 ast_delete(self_nextthink);
3528 ast_delete(self_think);
3532 if (store_frame) ast_delete(store_frame);
3533 if (store_nextthink) ast_delete(store_nextthink);
3534 if (store_think) ast_delete(store_think);
3537 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3538 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3539 !ast_block_add_expr(block, (ast_expression*)store_think))
3546 parseerror(parser, "failed to generate code for [frame,think]");
3547 ast_unref(nextthink);
3548 ast_unref(framenum);
3554 parser_enterblock(parser);
3556 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3558 ast_value *param = var->expression.params[parami];
3561 if (param->expression.vtype != TYPE_VECTOR &&
3562 (param->expression.vtype != TYPE_FIELD ||
3563 param->expression.next->expression.vtype != TYPE_VECTOR))
3568 if (!create_vector_members(param, me)) {
3569 ast_block_delete(block);
3573 for (e = 0; e < 3; ++e) {
3574 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3575 ast_block_collect(block, (ast_expression*)me[e]);
3579 func = ast_function_new(ast_ctx(var), var->name, var);
3581 parseerror(parser, "failed to allocate function for `%s`", var->name);
3582 ast_block_delete(block);
3585 vec_push(parser->functions, func);
3587 parser->function = func;
3588 if (!parse_block_into(parser, block)) {
3589 ast_block_delete(block);
3593 vec_push(func->blocks, block);
3595 parser->function = old;
3596 if (!parser_leaveblock(parser))
3598 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3599 parseerror(parser, "internal error: local scopes left");
3603 if (parser->tok == ';')
3604 return parser_next(parser);
3605 else if (opts.standard == COMPILER_QCC)
3606 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3610 vec_pop(parser->functions);
3611 ast_function_delete(func);
3612 var->constval.vfunc = NULL;
3615 (void)!parser_leaveblock(parser);
3616 parser->function = old;
3620 static ast_expression *array_accessor_split(
3625 ast_expression *left,
3626 ast_expression *right
3632 lex_ctx ctx = ast_ctx(array);
3634 if (!left || !right) {
3635 if (left) ast_delete(left);
3636 if (right) ast_delete(right);
3640 cmp = ast_binary_new(ctx, INSTR_LT,
3641 (ast_expression*)index,
3642 (ast_expression*)parser_const_float(parser, middle));
3646 parseerror(parser, "internal error: failed to create comparison for array setter");
3650 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3652 ast_delete(cmp); /* will delete left and right */
3653 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3657 return (ast_expression*)ifthen;
3660 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3662 lex_ctx ctx = ast_ctx(array);
3664 if (from+1 == afterend) {
3665 /* set this value */
3668 ast_array_index *subscript;
3670 int assignop = type_store_instr[value->expression.vtype];
3672 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3673 assignop = INSTR_STORE_V;
3675 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3679 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3681 ast_delete(subscript);
3685 block = ast_block_new(ctx);
3691 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3696 ret = ast_return_new(ctx, NULL);
3702 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3707 return (ast_expression*)block;
3709 ast_expression *left, *right;
3710 size_t diff = afterend - from;
3711 size_t middle = from + diff/2;
3712 left = array_setter_node(parser, array, index, value, from, middle);
3713 right = array_setter_node(parser, array, index, value, middle, afterend);
3714 return array_accessor_split(parser, array, index, middle, left, right);
3718 static ast_expression *array_field_setter_node(
3727 lex_ctx ctx = ast_ctx(array);
3729 if (from+1 == afterend) {
3730 /* set this value */
3733 ast_entfield *entfield;
3734 ast_array_index *subscript;
3736 int assignop = type_storep_instr[value->expression.vtype];
3738 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3739 assignop = INSTR_STOREP_V;
3741 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3745 entfield = ast_entfield_new_force(ctx,
3746 (ast_expression*)entity,
3747 (ast_expression*)subscript,
3748 (ast_expression*)subscript);
3750 ast_delete(subscript);
3754 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3756 ast_delete(entfield);
3760 block = ast_block_new(ctx);
3766 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3771 ret = ast_return_new(ctx, NULL);
3777 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3782 return (ast_expression*)block;
3784 ast_expression *left, *right;
3785 size_t diff = afterend - from;
3786 size_t middle = from + diff/2;
3787 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3788 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3789 return array_accessor_split(parser, array, index, middle, left, right);
3793 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3795 lex_ctx ctx = ast_ctx(array);
3797 if (from+1 == afterend) {
3799 ast_array_index *subscript;
3801 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3805 ret = ast_return_new(ctx, (ast_expression*)subscript);
3807 ast_delete(subscript);
3811 return (ast_expression*)ret;
3813 ast_expression *left, *right;
3814 size_t diff = afterend - from;
3815 size_t middle = from + diff/2;
3816 left = array_getter_node(parser, array, index, from, middle);
3817 right = array_getter_node(parser, array, index, middle, afterend);
3818 return array_accessor_split(parser, array, index, middle, left, right);
3822 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3824 ast_function *func = NULL;
3825 ast_value *fval = NULL;
3826 ast_block *body = NULL;
3828 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3830 parseerror(parser, "failed to create accessor function value");
3834 func = ast_function_new(ast_ctx(array), funcname, fval);
3837 parseerror(parser, "failed to create accessor function node");
3841 body = ast_block_new(ast_ctx(array));
3843 parseerror(parser, "failed to create block for array accessor");
3849 vec_push(func->blocks, body);
3852 vec_push(parser->accessors, fval);
3857 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3859 ast_expression *root = NULL;
3860 ast_value *index = NULL;
3861 ast_value *value = NULL;
3865 if (!ast_istype(array->expression.next, ast_value)) {
3866 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3870 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3872 func = fval->constval.vfunc;
3873 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3875 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3876 value = ast_value_copy((ast_value*)array->expression.next);
3878 if (!index || !value) {
3879 parseerror(parser, "failed to create locals for array accessor");
3882 (void)!ast_value_set_name(value, "value"); /* not important */
3883 vec_push(fval->expression.params, index);
3884 vec_push(fval->expression.params, value);
3886 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3888 parseerror(parser, "failed to build accessor search tree");
3892 array->setter = fval;
3893 return ast_block_add_expr(func->blocks[0], root);
3895 if (index) ast_delete(index);
3896 if (value) ast_delete(value);
3897 if (root) ast_delete(root);
3903 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3905 ast_expression *root = NULL;
3906 ast_value *entity = NULL;
3907 ast_value *index = NULL;
3908 ast_value *value = NULL;
3912 if (!ast_istype(array->expression.next, ast_value)) {
3913 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3917 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3919 func = fval->constval.vfunc;
3920 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3922 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3923 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3924 value = ast_value_copy((ast_value*)array->expression.next);
3925 if (!entity || !index || !value) {
3926 parseerror(parser, "failed to create locals for array accessor");
3929 (void)!ast_value_set_name(value, "value"); /* not important */
3930 vec_push(fval->expression.params, entity);
3931 vec_push(fval->expression.params, index);
3932 vec_push(fval->expression.params, value);
3934 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3936 parseerror(parser, "failed to build accessor search tree");
3940 array->setter = fval;
3941 return ast_block_add_expr(func->blocks[0], root);
3943 if (entity) ast_delete(entity);
3944 if (index) ast_delete(index);
3945 if (value) ast_delete(value);
3946 if (root) ast_delete(root);
3952 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3954 ast_expression *root = NULL;
3955 ast_value *index = NULL;
3959 /* NOTE: checking array->expression.next rather than elemtype since
3960 * for fields elemtype is a temporary fieldtype.
3962 if (!ast_istype(array->expression.next, ast_value)) {
3963 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3967 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3969 func = fval->constval.vfunc;
3970 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3972 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3975 parseerror(parser, "failed to create locals for array accessor");
3978 vec_push(fval->expression.params, index);
3980 root = array_getter_node(parser, array, index, 0, array->expression.count);
3982 parseerror(parser, "failed to build accessor search tree");
3986 array->getter = fval;
3987 return ast_block_add_expr(func->blocks[0], root);
3989 if (index) ast_delete(index);
3990 if (root) ast_delete(root);
3996 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3997 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4005 bool variadic = false;
4007 ctx = parser_ctx(parser);
4009 /* for the sake of less code we parse-in in this function */
4010 if (!parser_next(parser)) {
4011 parseerror(parser, "expected parameter list");
4017 /* parse variables until we hit a closing paren */
4018 while (parser->tok != ')') {
4020 /* there must be commas between them */
4021 if (parser->tok != ',') {
4022 parseerror(parser, "expected comma or end of parameter list");
4025 if (!parser_next(parser)) {
4026 parseerror(parser, "expected parameter");
4032 if (parser->tok == TOKEN_DOTS) {
4033 /* '...' indicates a varargs function */
4035 if (!parser_next(parser)) {
4036 parseerror(parser, "expected parameter");
4039 if (parser->tok != ')') {
4040 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4046 /* for anything else just parse a typename */
4047 param = parse_typename(parser, NULL, NULL);
4050 vec_push(params, param);
4051 if (param->expression.vtype >= TYPE_VARIANT) {
4052 char tname[1024]; /* typename is reserved in C++ */
4053 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4054 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4060 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4064 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4065 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4068 if (!parser_next(parser)) {
4069 parseerror(parser, "parse error after typename");
4073 /* now turn 'var' into a function type */
4074 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4075 fval->expression.next = (ast_expression*)var;
4077 fval->expression.flags |= AST_FLAG_VARIADIC;
4080 var->expression.params = params;
4087 for (i = 0; i < vec_size(params); ++i)
4088 ast_delete(params[i]);
4093 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4095 ast_expression *cexp;
4096 ast_value *cval, *tmp;
4099 ctx = parser_ctx(parser);
4101 if (!parser_next(parser)) {
4103 parseerror(parser, "expected array-size");
4107 cexp = parse_expression_leave(parser, true);
4109 if (!cexp || !ast_istype(cexp, ast_value)) {
4113 parseerror(parser, "expected array-size as constant positive integer");
4116 cval = (ast_value*)cexp;
4118 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4119 tmp->expression.next = (ast_expression*)var;
4122 if (cval->expression.vtype == TYPE_INTEGER)
4123 tmp->expression.count = cval->constval.vint;
4124 else if (cval->expression.vtype == TYPE_FLOAT)
4125 tmp->expression.count = cval->constval.vfloat;
4129 parseerror(parser, "array-size must be a positive integer constant");
4134 if (parser->tok != ']') {
4136 parseerror(parser, "expected ']' after array-size");
4139 if (!parser_next(parser)) {
4141 parseerror(parser, "error after parsing array size");
4147 /* Parse a complete typename.
4148 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4149 * but when parsing variables separated by comma
4150 * 'storebase' should point to where the base-type should be kept.
4151 * The base type makes up every bit of type information which comes *before* the
4154 * The following will be parsed in its entirety:
4156 * The 'basetype' in this case is 'void()'
4157 * and if there's a comma after it, say:
4159 * then the type-information 'void()' can be stored in 'storebase'
4161 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4163 ast_value *var, *tmp;
4166 const char *name = NULL;
4167 bool isfield = false;
4168 bool wasarray = false;
4169 size_t morefields = 0;
4171 ctx = parser_ctx(parser);
4173 /* types may start with a dot */
4174 if (parser->tok == '.') {
4176 /* if we parsed a dot we need a typename now */
4177 if (!parser_next(parser)) {
4178 parseerror(parser, "expected typename for field definition");
4182 /* Further dots are handled seperately because they won't be part of the
4185 while (parser->tok == '.') {
4187 if (!parser_next(parser)) {
4188 parseerror(parser, "expected typename for field definition");
4193 if (parser->tok == TOKEN_IDENT)
4194 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4195 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4196 parseerror(parser, "expected typename");
4200 /* generate the basic type value */
4201 if (cached_typedef) {
4202 var = ast_value_copy(cached_typedef);
4203 ast_value_set_name(var, "<type(from_def)>");
4205 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4207 for (; morefields; --morefields) {
4208 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4209 tmp->expression.next = (ast_expression*)var;
4213 /* do not yet turn into a field - remember:
4214 * .void() foo; is a field too
4215 * .void()() foo; is a function
4219 if (!parser_next(parser)) {
4221 parseerror(parser, "parse error after typename");
4225 /* an opening paren now starts the parameter-list of a function
4226 * this is where original-QC has parameter lists.
4227 * We allow a single parameter list here.
4228 * Much like fteqcc we don't allow `float()() x`
4230 if (parser->tok == '(') {
4231 var = parse_parameter_list(parser, var);
4236 /* store the base if requested */
4238 *storebase = ast_value_copy(var);
4240 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4241 tmp->expression.next = (ast_expression*)*storebase;
4246 /* there may be a name now */
4247 if (parser->tok == TOKEN_IDENT) {
4248 name = util_strdup(parser_tokval(parser));
4250 if (!parser_next(parser)) {
4252 parseerror(parser, "error after variable or field declaration");
4257 /* now this may be an array */
4258 if (parser->tok == '[') {
4260 var = parse_arraysize(parser, var);
4265 /* This is the point where we can turn it into a field */
4267 /* turn it into a field if desired */
4268 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4269 tmp->expression.next = (ast_expression*)var;
4273 /* now there may be function parens again */
4274 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4275 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4276 if (parser->tok == '(' && wasarray)
4277 parseerror(parser, "arrays as part of a return type is not supported");
4278 while (parser->tok == '(') {
4279 var = parse_parameter_list(parser, var);
4288 /* finally name it */
4290 if (!ast_value_set_name(var, name)) {
4292 parseerror(parser, "internal error: failed to set name");
4295 /* free the name, ast_value_set_name duplicates */
4302 static bool parse_typedef(parser_t *parser)
4304 ast_value *typevar, *oldtype;
4305 ast_expression *old;
4307 typevar = parse_typename(parser, NULL, NULL);
4312 if ( (old = parser_find_var(parser, typevar->name)) ) {
4313 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4314 " -> `%s` has been declared here: %s:%i",
4315 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4316 ast_delete(typevar);
4320 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4321 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4322 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4323 ast_delete(typevar);
4327 vec_push(parser->_typedefs, typevar);
4328 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4330 if (parser->tok != ';') {
4331 parseerror(parser, "expected semicolon after typedef");
4334 if (!parser_next(parser)) {
4335 parseerror(parser, "parse error after typedef");
4342 static const char *cvq_to_str(int cvq) {
4344 case CV_NONE: return "none";
4345 case CV_VAR: return "`var`";
4346 case CV_CONST: return "`const`";
4347 default: return "<INVALID>";
4351 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4354 if (proto->cvq != var->cvq) {
4355 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4356 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4357 parser->tok == '='))
4359 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4360 "`%s` declared with different qualifiers: %s\n"
4361 " -> previous declaration here: %s:%i uses %s",
4362 var->name, cvq_to_str(var->cvq),
4363 ast_ctx(proto).file, ast_ctx(proto).line,
4364 cvq_to_str(proto->cvq));
4367 av = (var ->expression.flags & AST_FLAG_NORETURN);
4368 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4370 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4371 "`%s` declared with different attributes%s\n"
4372 " -> previous declaration here: %s:%i",
4373 var->name, (av ? ": noreturn" : ""),
4374 ast_ctx(proto).file, ast_ctx(proto).line,
4375 (ao ? ": noreturn" : ""));
4380 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)
4384 ast_expression *old;
4388 ast_value *basetype = NULL;
4390 bool isparam = false;
4391 bool isvector = false;
4392 bool cleanvar = true;
4393 bool wasarray = false;
4397 if (!localblock && is_static)
4398 parseerror(parser, "`static` qualifier is not supported in global scope");
4400 /* get the first complete variable */
4401 var = parse_typename(parser, &basetype, cached_typedef);
4404 ast_delete(basetype);
4412 /* Part 0: finish the type */
4413 if (parser->tok == '(') {
4414 if (opts.standard == COMPILER_QCC)
4415 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4416 var = parse_parameter_list(parser, var);
4422 /* we only allow 1-dimensional arrays */
4423 if (parser->tok == '[') {
4425 var = parse_arraysize(parser, var);
4431 if (parser->tok == '(' && wasarray) {
4432 parseerror(parser, "arrays as part of a return type is not supported");
4433 /* we'll still parse the type completely for now */
4435 /* for functions returning functions */
4436 while (parser->tok == '(') {
4437 if (opts.standard == COMPILER_QCC)
4438 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4439 var = parse_parameter_list(parser, var);
4446 var->cvq = qualifier;
4447 var->expression.flags |= qflags;
4448 if (var->expression.flags & AST_FLAG_DEPRECATED)
4449 var->desc = vstring;
4452 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4453 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4454 * is then filled with the previous definition and the parameter-names replaced.
4456 if (!strcmp(var->name, "nil")) {
4457 if (OPTS_FLAG(UNTYPED_NIL)) {
4458 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4459 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4461 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4464 /* Deal with end_sys_ vars */
4466 if (!strcmp(var->name, "end_sys_globals")) {
4468 parser->crc_globals = vec_size(parser->globals);
4471 else if (!strcmp(var->name, "end_sys_fields")) {
4473 parser->crc_fields = vec_size(parser->fields);
4476 if (was_end && var->expression.vtype == TYPE_FIELD) {
4477 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4478 "global '%s' hint should not be a field",
4479 parser_tokval(parser)))
4486 if (!nofields && var->expression.vtype == TYPE_FIELD)
4488 /* deal with field declarations */
4489 old = parser_find_field(parser, var->name);
4491 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4492 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4501 parseerror(parser, "field `%s` already declared here: %s:%i",
4502 var->name, ast_ctx(old).file, ast_ctx(old).line);
4507 if (opts.standard == COMPILER_QCC &&
4508 (old = parser_find_global(parser, var->name)))
4510 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4511 parseerror(parser, "field `%s` already declared here: %s:%i",
4512 var->name, ast_ctx(old).file, ast_ctx(old).line);
4519 /* deal with other globals */
4520 old = parser_find_global(parser, var->name);
4521 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4523 /* This is a function which had a prototype */
4524 if (!ast_istype(old, ast_value)) {
4525 parseerror(parser, "internal error: prototype is not an ast_value");
4529 proto = (ast_value*)old;
4530 proto->desc = var->desc;
4531 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4532 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4534 ast_ctx(proto).file, ast_ctx(proto).line);
4538 /* we need the new parameter-names */
4539 for (i = 0; i < vec_size(proto->expression.params); ++i)
4540 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4541 if (!parser_check_qualifiers(parser, var, proto)) {
4548 proto->expression.flags |= var->expression.flags;
4556 if (opts.standard == COMPILER_GMQCC) {
4557 parseerror(parser, "global `%s` already declared here: %s:%i",
4558 var->name, ast_ctx(old).file, ast_ctx(old).line);
4562 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4563 "global `%s` already declared here: %s:%i",
4564 var->name, ast_ctx(old).file, ast_ctx(old).line))
4569 proto = (ast_value*)old;
4570 if (!ast_istype(old, ast_value)) {
4571 parseerror(parser, "internal error: not an ast_value");
4576 if (!parser_check_qualifiers(parser, var, proto)) {
4581 proto->expression.flags |= var->expression.flags;
4586 if (opts.standard == COMPILER_QCC &&
4587 (old = parser_find_field(parser, var->name)))
4589 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4590 parseerror(parser, "global `%s` already declared here: %s:%i",
4591 var->name, ast_ctx(old).file, ast_ctx(old).line);
4598 else /* it's not a global */
4600 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4601 if (old && !isparam) {
4602 parseerror(parser, "local `%s` already declared here: %s:%i",
4603 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4607 old = parser_find_local(parser, var->name, 0, &isparam);
4608 if (old && isparam) {
4609 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4610 "local `%s` is shadowing a parameter", var->name))
4612 parseerror(parser, "local `%s` already declared here: %s:%i",
4613 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4617 if (opts.standard != COMPILER_GMQCC) {
4625 /* in a noref section we simply bump the usecount */
4626 if (noref || parser->noref)
4630 * Create the global/local, and deal with vector types.
4633 if (var->expression.vtype == TYPE_VECTOR)
4635 else if (var->expression.vtype == TYPE_FIELD &&
4636 var->expression.next->expression.vtype == TYPE_VECTOR)
4640 if (!create_vector_members(var, me)) {
4647 /* deal with global variables, fields, functions */
4648 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4649 var->isfield = true;
4650 vec_push(parser->fields, (ast_expression*)var);
4651 util_htset(parser->htfields, var->name, var);
4653 for (i = 0; i < 3; ++i) {
4654 vec_push(parser->fields, (ast_expression*)me[i]);
4655 util_htset(parser->htfields, me[i]->name, me[i]);
4660 vec_push(parser->globals, (ast_expression*)var);
4661 util_htset(parser->htglobals, var->name, var);
4663 for (i = 0; i < 3; ++i) {
4664 vec_push(parser->globals, (ast_expression*)me[i]);
4665 util_htset(parser->htglobals, me[i]->name, me[i]);
4671 /* a static adds itself to be generated like any other global
4672 * but is added to the local namespace instead
4674 char *defname = NULL;
4675 size_t prefix_len, ln;
4677 ln = strlen(parser->function->name);
4678 vec_append(defname, ln, parser->function->name);
4680 vec_append(defname, 2, "::");
4681 /* remember the length up to here */
4682 prefix_len = vec_size(defname);
4684 /* Add it to the local scope */
4685 util_htset(vec_last(parser->variables), var->name, (void*)var);
4686 /* now rename the global */
4687 ln = strlen(var->name);
4688 vec_append(defname, ln, var->name);
4689 ast_value_set_name(var, defname);
4691 /* push it to the to-be-generated globals */
4692 vec_push(parser->globals, (ast_expression*)var);
4694 /* same game for the vector members */
4696 for (i = 0; i < 3; ++i) {
4697 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4699 vec_shrinkto(defname, prefix_len);
4700 ln = strlen(me[i]->name);
4701 vec_append(defname, ln, me[i]->name);
4702 ast_member_set_name(me[i], defname);
4704 vec_push(parser->globals, (ast_expression*)me[i]);
4709 vec_push(localblock->locals, var);
4710 parser_addlocal(parser, var->name, (ast_expression*)var);
4712 for (i = 0; i < 3; ++i) {
4713 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4714 ast_block_collect(localblock, (ast_expression*)me[i]);
4720 me[0] = me[1] = me[2] = NULL;
4725 if (var->expression.vtype == TYPE_ARRAY) {
4727 snprintf(name, sizeof(name), "%s##SET", var->name);
4728 if (!parser_create_array_setter(parser, var, name))
4730 snprintf(name, sizeof(name), "%s##GET", var->name);
4731 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4734 else if (!localblock && !nofields &&
4735 var->expression.vtype == TYPE_FIELD &&
4736 var->expression.next->expression.vtype == TYPE_ARRAY)
4739 ast_expression *telem;
4741 ast_value *array = (ast_value*)var->expression.next;
4743 if (!ast_istype(var->expression.next, ast_value)) {
4744 parseerror(parser, "internal error: field element type must be an ast_value");
4748 snprintf(name, sizeof(name), "%s##SETF", var->name);
4749 if (!parser_create_array_field_setter(parser, array, name))
4752 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4753 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4754 tfield->expression.next = telem;
4755 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4756 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4764 if (parser->tok == ';') {
4765 ast_delete(basetype);
4766 if (!parser_next(parser)) {
4767 parseerror(parser, "error after variable declaration");
4773 if (parser->tok == ',')
4777 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4780 parseerror(parser, "missing comma or semicolon while parsing variables");
4784 if (localblock && opts.standard == COMPILER_QCC) {
4785 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4786 "initializing expression turns variable `%s` into a constant in this standard",
4793 if (parser->tok != '{') {
4794 if (parser->tok != '=') {
4795 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4799 if (!parser_next(parser)) {
4800 parseerror(parser, "error parsing initializer");
4804 else if (opts.standard == COMPILER_QCC) {
4805 parseerror(parser, "expected '=' before function body in this standard");
4808 if (parser->tok == '#') {
4809 ast_function *func = NULL;
4812 parseerror(parser, "cannot declare builtins within functions");
4815 if (var->expression.vtype != TYPE_FUNCTION) {
4816 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4819 if (!parser_next(parser)) {
4820 parseerror(parser, "expected builtin number");
4823 if (parser->tok != TOKEN_INTCONST) {
4824 parseerror(parser, "builtin number must be an integer constant");
4827 if (parser_token(parser)->constval.i < 0) {
4828 parseerror(parser, "builtin number must be an integer greater than zero");
4832 if (var->hasvalue) {
4833 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4834 "builtin `%s` has already been defined\n"
4835 " -> previous declaration here: %s:%i",
4836 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4840 func = ast_function_new(ast_ctx(var), var->name, var);
4842 parseerror(parser, "failed to allocate function for `%s`", var->name);
4845 vec_push(parser->functions, func);
4847 func->builtin = -parser_token(parser)->constval.i-1;
4850 if (!parser_next(parser)) {
4851 parseerror(parser, "expected comma or semicolon");
4853 ast_function_delete(func);
4854 var->constval.vfunc = NULL;
4858 else if (parser->tok == '{' || parser->tok == '[')
4861 parseerror(parser, "cannot declare functions within functions");
4866 ast_ctx(proto) = parser_ctx(parser);
4868 if (!parse_function_body(parser, var))
4870 ast_delete(basetype);
4871 for (i = 0; i < vec_size(parser->gotos); ++i)
4872 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4873 vec_free(parser->gotos);
4874 vec_free(parser->labels);
4877 ast_expression *cexp;
4880 cexp = parse_expression_leave(parser, true);
4885 cval = (ast_value*)cexp;
4886 if (cval != parser->nil &&
4887 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4890 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4894 if (opts.standard != COMPILER_GMQCC &&
4895 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4896 qualifier != CV_VAR)
4898 var->cvq = CV_CONST;
4900 if (cval == parser->nil)
4901 var->expression.flags |= AST_FLAG_INITIALIZED;
4904 var->hasvalue = true;
4905 if (cval->expression.vtype == TYPE_STRING)
4906 var->constval.vstring = parser_strdup(cval->constval.vstring);
4907 else if (cval->expression.vtype == TYPE_FIELD)
4908 var->constval.vfield = cval;
4910 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4916 shunt sy = { NULL, NULL };
4919 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4920 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4921 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4922 if (!parser_sy_apply_operator(parser, &sy))
4925 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4926 parseerror(parser, "internal error: leaked operands");
4927 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4937 if (parser->tok == ',') {
4938 if (!parser_next(parser)) {
4939 parseerror(parser, "expected another variable");
4943 if (parser->tok != TOKEN_IDENT) {
4944 parseerror(parser, "expected another variable");
4947 var = ast_value_copy(basetype);
4949 ast_value_set_name(var, parser_tokval(parser));
4950 if (!parser_next(parser)) {
4951 parseerror(parser, "error parsing variable declaration");
4957 if (parser->tok != ';') {
4958 parseerror(parser, "missing semicolon after variables");
4962 if (!parser_next(parser)) {
4963 parseerror(parser, "parse error after variable declaration");
4967 ast_delete(basetype);
4971 if (cleanvar && var)
4973 ast_delete(basetype);
4977 ast_delete(basetype);
4978 if (cleanvar && var)
4980 if (me[0]) ast_member_delete(me[0]);
4981 if (me[1]) ast_member_delete(me[1]);
4982 if (me[2]) ast_member_delete(me[2]);
4986 static bool parser_global_statement(parser_t *parser)
4990 bool is_static = false;
4991 uint32_t qflags = 0;
4992 ast_value *istype = NULL;
4993 char *vstring = NULL;
4995 if (parser->tok == TOKEN_IDENT)
4996 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4998 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5000 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5002 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5004 if (cvq == CV_WRONG)
5006 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5008 else if (parser->tok == TOKEN_KEYWORD)
5010 if (!strcmp(parser_tokval(parser), "typedef")) {
5011 if (!parser_next(parser)) {
5012 parseerror(parser, "expected type definition after 'typedef'");
5015 return parse_typedef(parser);
5017 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5020 else if (parser->tok == '#')
5022 return parse_pragma(parser);
5024 else if (parser->tok == '$')
5026 if (!parser_next(parser)) {
5027 parseerror(parser, "parse error");
5033 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5039 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5041 return util_crc16(old, str, strlen(str));
5044 static void progdefs_crc_file(const char *str)
5046 /* write to progdefs.h here */
5050 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5052 old = progdefs_crc_sum(old, str);
5053 progdefs_crc_file(str);
5057 static void generate_checksum(parser_t *parser)
5059 uint16_t crc = 0xFFFF;
5063 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5064 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5066 progdefs_crc_file("\tint\tpad;\n");
5067 progdefs_crc_file("\tint\tofs_return[3];\n");
5068 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5069 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5070 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5071 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5072 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5073 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5074 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5075 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5077 for (i = 0; i < parser->crc_globals; ++i) {
5078 if (!ast_istype(parser->globals[i], ast_value))
5080 value = (ast_value*)(parser->globals[i]);
5081 switch (value->expression.vtype) {
5082 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5083 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5084 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5085 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5087 crc = progdefs_crc_both(crc, "\tint\t");
5090 crc = progdefs_crc_both(crc, value->name);
5091 crc = progdefs_crc_both(crc, ";\n");
5093 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5094 for (i = 0; i < parser->crc_fields; ++i) {
5095 if (!ast_istype(parser->fields[i], ast_value))
5097 value = (ast_value*)(parser->fields[i]);
5098 switch (value->expression.next->expression.vtype) {
5099 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5100 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5101 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5102 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5104 crc = progdefs_crc_both(crc, "\tint\t");
5107 crc = progdefs_crc_both(crc, value->name);
5108 crc = progdefs_crc_both(crc, ";\n");
5110 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5115 static parser_t *parser;
5122 parser = (parser_t*)mem_a(sizeof(parser_t));
5126 memset(parser, 0, sizeof(*parser));
5128 for (i = 0; i < operator_count; ++i) {
5129 if (operators[i].id == opid1('=')) {
5130 parser->assign_op = operators+i;
5134 if (!parser->assign_op) {
5135 printf("internal error: initializing parser: failed to find assign operator\n");
5140 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5141 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5142 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5143 vec_push(parser->_blocktypedefs, 0);
5145 empty_ctx.file = "<internal>";
5147 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5148 parser->nil->cvq = CV_CONST;
5149 if (OPTS_FLAG(UNTYPED_NIL))
5150 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5154 bool parser_compile()
5156 /* initial lexer/parser state */
5157 parser->lex->flags.noops = true;
5159 if (parser_next(parser))
5161 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5163 if (!parser_global_statement(parser)) {
5164 if (parser->tok == TOKEN_EOF)
5165 parseerror(parser, "unexpected eof");
5166 else if (compile_errors)
5167 parseerror(parser, "there have been errors, bailing out");
5168 lex_close(parser->lex);
5174 parseerror(parser, "parse error");
5175 lex_close(parser->lex);
5180 lex_close(parser->lex);
5183 return !compile_errors;
5186 bool parser_compile_file(const char *filename)
5188 parser->lex = lex_open(filename);
5190 con_err("failed to open file \"%s\"\n", filename);
5193 return parser_compile();
5196 bool parser_compile_string(const char *name, const char *str, size_t len)
5198 parser->lex = lex_open_string(str, len, name);
5200 con_err("failed to create lexer for string \"%s\"\n", name);
5203 return parser_compile();
5206 void parser_cleanup()
5209 for (i = 0; i < vec_size(parser->accessors); ++i) {
5210 ast_delete(parser->accessors[i]->constval.vfunc);
5211 parser->accessors[i]->constval.vfunc = NULL;
5212 ast_delete(parser->accessors[i]);
5214 for (i = 0; i < vec_size(parser->functions); ++i) {
5215 ast_delete(parser->functions[i]);
5217 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5218 ast_delete(parser->imm_vector[i]);
5220 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5221 ast_delete(parser->imm_string[i]);
5223 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5224 ast_delete(parser->imm_float[i]);
5226 for (i = 0; i < vec_size(parser->fields); ++i) {
5227 ast_delete(parser->fields[i]);
5229 for (i = 0; i < vec_size(parser->globals); ++i) {
5230 ast_delete(parser->globals[i]);
5232 vec_free(parser->accessors);
5233 vec_free(parser->functions);
5234 vec_free(parser->imm_vector);
5235 vec_free(parser->imm_string);
5236 vec_free(parser->imm_float);
5237 vec_free(parser->globals);
5238 vec_free(parser->fields);
5240 for (i = 0; i < vec_size(parser->variables); ++i)
5241 util_htdel(parser->variables[i]);
5242 vec_free(parser->variables);
5243 vec_free(parser->_blocklocals);
5244 vec_free(parser->_locals);
5246 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5247 ast_delete(parser->_typedefs[i]);
5248 vec_free(parser->_typedefs);
5249 for (i = 0; i < vec_size(parser->typedefs); ++i)
5250 util_htdel(parser->typedefs[i]);
5251 vec_free(parser->typedefs);
5252 vec_free(parser->_blocktypedefs);
5254 vec_free(parser->_block_ctx);
5256 vec_free(parser->labels);
5257 vec_free(parser->gotos);
5258 vec_free(parser->breaks);
5259 vec_free(parser->continues);
5261 ast_value_delete(parser->nil);
5266 bool parser_finish(const char *output)
5272 if (compile_errors) {
5273 con_out("*** there were compile errors\n");
5277 ir = ir_builder_new("gmqcc_out");
5279 con_out("failed to allocate builder\n");
5283 for (i = 0; i < vec_size(parser->fields); ++i) {
5286 if (!ast_istype(parser->fields[i], ast_value))
5288 field = (ast_value*)parser->fields[i];
5289 hasvalue = field->hasvalue;
5290 field->hasvalue = false;
5291 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5292 con_out("failed to generate field %s\n", field->name);
5293 ir_builder_delete(ir);
5298 ast_expression *subtype;
5299 field->hasvalue = true;
5300 subtype = field->expression.next;
5301 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5302 if (subtype->expression.vtype == TYPE_FIELD)
5303 ifld->fieldtype = subtype->expression.next->expression.vtype;
5304 else if (subtype->expression.vtype == TYPE_FUNCTION)
5305 ifld->outtype = subtype->expression.next->expression.vtype;
5306 (void)!ir_value_set_field(field->ir_v, ifld);
5309 for (i = 0; i < vec_size(parser->globals); ++i) {
5311 if (!ast_istype(parser->globals[i], ast_value))
5313 asvalue = (ast_value*)(parser->globals[i]);
5314 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5315 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5316 "unused global: `%s`", asvalue->name);
5318 if (!ast_global_codegen(asvalue, ir, false)) {
5319 con_out("failed to generate global %s\n", asvalue->name);
5320 ir_builder_delete(ir);
5324 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5325 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5326 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5327 ir_builder_delete(ir);
5331 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5332 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5333 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5334 ir_builder_delete(ir);
5338 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5339 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5340 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5341 ir_builder_delete(ir);
5345 for (i = 0; i < vec_size(parser->globals); ++i) {
5347 if (!ast_istype(parser->globals[i], ast_value))
5349 asvalue = (ast_value*)(parser->globals[i]);
5350 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5352 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5353 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5354 "uninitialized constant: `%s`",
5356 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5357 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5358 "uninitialized global: `%s`",
5361 if (!ast_generate_accessors(asvalue, ir)) {
5362 ir_builder_delete(ir);
5366 for (i = 0; i < vec_size(parser->fields); ++i) {
5368 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5370 if (!ast_istype((ast_expression*)asvalue, ast_value))
5372 if (asvalue->expression.vtype != TYPE_ARRAY)
5374 if (!ast_generate_accessors(asvalue, ir)) {
5375 ir_builder_delete(ir);
5379 for (i = 0; i < vec_size(parser->functions); ++i) {
5380 if (!ast_function_codegen(parser->functions[i], ir)) {
5381 con_out("failed to generate function %s\n", parser->functions[i]->name);
5382 ir_builder_delete(ir);
5387 ir_builder_dump(ir, con_out);
5388 for (i = 0; i < vec_size(parser->functions); ++i) {
5389 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5390 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5391 ir_builder_delete(ir);
5396 if (compile_Werrors) {
5397 con_out("*** there were warnings treated as errors\n");
5398 compile_show_werrors();
5404 ir_builder_dump(ir, con_out);
5406 generate_checksum(parser);
5408 if (!ir_builder_generate(ir, output)) {
5409 con_out("*** failed to generate output file\n");
5410 ir_builder_delete(ir);
5415 ir_builder_delete(ir);