2 * Copyright (C) 2012, 2013
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
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
37 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_vector_zero;
61 ast_function *function;
63 /* All the labels the function defined...
64 * Should they be in ast_function instead?
69 const char **continues;
71 /* A list of hashtables for each scope */
77 /* not to be used directly, we use the hash table */
78 ast_expression **_locals;
80 ast_value **_typedefs;
81 size_t *_blocktypedefs;
84 /* we store the '=' operator info */
85 const oper_info *assign_op;
87 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
88 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
89 * anything else: type error
93 /* Keep track of our ternary vs parenthesis nesting state.
94 * If we reach a 'comma' operator in a ternary without a paren,
95 * we shall trigger -Wternary-precedence.
103 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
105 static void parser_enterblock(parser_t *parser);
106 static bool parser_leaveblock(parser_t *parser);
107 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
108 static bool parse_typedef(parser_t *parser);
109 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);
110 static ast_block* parse_block(parser_t *parser);
111 static bool parse_block_into(parser_t *parser, ast_block *block);
112 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
113 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
114 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
115 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
117 static void parseerror(parser_t *parser, const char *fmt, ...)
121 vcompile_error(parser->lex->tok.ctx, fmt, ap);
125 /* returns true if it counts as an error */
126 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
131 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
136 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
141 r = vcompile_warning(ctx, warntype, fmt, ap);
146 /**********************************************************************
147 * some maths used for constant folding
150 vector vec3_add(vector a, vector b)
159 vector vec3_sub(vector a, vector b)
168 qcfloat vec3_mulvv(vector a, vector b)
170 return (a.x * b.x + a.y * b.y + a.z * b.z);
173 vector vec3_mulvf(vector a, float b)
182 /**********************************************************************
186 bool parser_next(parser_t *parser)
188 /* lex_do kills the previous token */
189 parser->tok = lex_do(parser->lex);
190 if (parser->tok == TOKEN_EOF)
192 if (parser->tok >= TOKEN_ERROR) {
193 parseerror(parser, "lex error");
199 #define parser_tokval(p) ((p)->lex->tok.value)
200 #define parser_token(p) (&((p)->lex->tok))
201 #define parser_ctx(p) ((p)->lex->tok.ctx)
203 static ast_value* parser_const_float(parser_t *parser, double d)
207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
208 const double compare = parser->imm_float[i]->constval.vfloat;
209 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
210 return parser->imm_float[i];
212 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
214 out->hasvalue = true;
215 out->constval.vfloat = d;
216 vec_push(parser->imm_float, out);
220 static ast_value* parser_const_float_0(parser_t *parser)
222 if (!parser->imm_float_zero)
223 parser->imm_float_zero = parser_const_float(parser, 0);
224 return parser->imm_float_zero;
227 static ast_value* parser_const_float_1(parser_t *parser)
229 if (!parser->imm_float_one)
230 parser->imm_float_one = parser_const_float(parser, 1);
231 return parser->imm_float_one;
234 static char *parser_strdup(const char *str)
237 /* actually dup empty strings */
238 char *out = (char*)mem_a(1);
242 return util_strdup(str);
245 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
249 for (i = 0; i < vec_size(parser->imm_string); ++i) {
250 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
251 return parser->imm_string[i];
255 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
256 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
258 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
260 out->hasvalue = true;
261 out->constval.vstring = parser_strdup(str);
262 vec_push(parser->imm_string, out);
266 static ast_value* parser_const_vector(parser_t *parser, vector v)
270 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
271 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
272 return parser->imm_vector[i];
274 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
276 out->hasvalue = true;
277 out->constval.vvec = v;
278 vec_push(parser->imm_vector, out);
282 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
288 return parser_const_vector(parser, v);
291 static ast_value* parser_const_vector_0(parser_t *parser)
293 if (!parser->imm_vector_zero)
294 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
295 return parser->imm_vector_zero;
298 static ast_expression* parser_find_field(parser_t *parser, const char *name)
300 return ( ast_expression*)util_htget(parser->htfields, name);
303 static ast_expression* parser_find_label(parser_t *parser, const char *name)
306 for(i = 0; i < vec_size(parser->labels); i++)
307 if (!strcmp(parser->labels[i]->name, name))
308 return (ast_expression*)parser->labels[i];
312 static ast_expression* parser_find_global(parser_t *parser, const char *name)
314 return (ast_expression*)util_htget(parser->htglobals, name);
317 static ast_expression* parser_find_param(parser_t *parser, const char *name)
321 if (!parser->function)
323 fun = parser->function->vtype;
324 for (i = 0; i < vec_size(fun->expression.params); ++i) {
325 if (!strcmp(fun->expression.params[i]->name, name))
326 return (ast_expression*)(fun->expression.params[i]);
331 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
336 hash = util_hthash(parser->htglobals, name);
339 for (i = vec_size(parser->variables); i > upto;) {
341 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
345 return parser_find_param(parser, name);
348 static ast_expression* parser_find_var(parser_t *parser, const char *name)
352 v = parser_find_local(parser, name, 0, &dummy);
353 if (!v) v = parser_find_global(parser, name);
357 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
361 hash = util_hthash(parser->typedefs[0], name);
363 for (i = vec_size(parser->typedefs); i > upto;) {
365 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
373 size_t etype; /* 0 = expression, others are operators */
377 ast_block *block; /* for commas and function calls */
386 #define SY_PAREN_EXPR '('
387 #define SY_PAREN_FUNC 'f'
388 #define SY_PAREN_INDEX '['
389 #define SY_PAREN_TERNARY '?'
391 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
402 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
406 e.out = (ast_expression*)v;
413 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
415 e.etype = 1 + (op - operators);
424 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
436 # define DEBUGSHUNTDO(x) x
438 # define DEBUGSHUNTDO(x)
441 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
442 * so we need to rotate it to become ent.(foo[n]).
444 static bool rotate_entfield_array_index_nodes(ast_expression **out)
446 ast_array_index *index;
447 ast_entfield *entfield;
451 ast_expression *entity;
453 lex_ctx ctx = ast_ctx(*out);
455 if (!ast_istype(*out, ast_array_index))
457 index = (ast_array_index*)*out;
459 if (!ast_istype(index->array, ast_entfield))
461 entfield = (ast_entfield*)index->array;
463 if (!ast_istype(entfield->field, ast_value))
465 field = (ast_value*)entfield->field;
468 entity = entfield->entity;
472 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
473 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
474 *out = (ast_expression*)entfield;
479 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
481 switch (v->expression.vtype) {
483 return !!v->constval.vfloat;
485 return !!v->constval.vint;
487 if (OPTS_FLAG(CORRECT_LOGIC))
488 return v->constval.vvec.x &&
489 v->constval.vvec.y &&
492 return !!(v->constval.vvec.x);
494 if (!v->constval.vstring)
496 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
498 return !!v->constval.vstring[0];
500 compile_error(ctx, "internal error: immediate_is_true on invalid type");
501 return !!v->constval.vfunc;
505 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
509 ast_expression *out = NULL;
510 ast_expression *exprs[3];
511 ast_block *blocks[3];
512 ast_value *asvalue[3];
513 ast_binstore *asbinstore;
514 size_t i, assignop, addop, subop;
515 qcint generated_op = 0;
520 if (!vec_size(sy->ops)) {
521 parseerror(parser, "internal error: missing operator");
525 if (vec_last(sy->ops).paren) {
526 parseerror(parser, "unmatched parenthesis");
530 op = &operators[vec_last(sy->ops).etype - 1];
531 ctx = vec_last(sy->ops).ctx;
533 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
535 if (vec_size(sy->out) < op->operands) {
536 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
537 op->op, (int)op->id);
541 vec_shrinkby(sy->ops, 1);
543 /* op(:?) has no input and no output */
547 vec_shrinkby(sy->out, op->operands);
548 for (i = 0; i < op->operands; ++i) {
549 exprs[i] = sy->out[vec_size(sy->out)+i].out;
550 blocks[i] = sy->out[vec_size(sy->out)+i].block;
551 asvalue[i] = (ast_value*)exprs[i];
554 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
555 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
559 #define NotSameType(T) \
560 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
561 exprs[0]->expression.vtype != T)
562 #define CanConstFold1(A) \
563 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
564 (A)->expression.vtype != TYPE_FUNCTION)
565 #define CanConstFold(A, B) \
566 (CanConstFold1(A) && CanConstFold1(B))
567 #define ConstV(i) (asvalue[(i)]->constval.vvec)
568 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
569 #define ConstS(i) (asvalue[(i)]->constval.vstring)
573 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
577 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
578 if (exprs[1]->expression.vtype != TYPE_FIELD) {
579 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
582 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
584 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
585 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
589 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
595 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
596 !(exprs[0]->expression.vtype == TYPE_FIELD &&
597 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
599 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
600 parseerror(parser, "cannot index value of type %s", ty1);
603 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
604 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
605 parseerror(parser, "index must be of type float, not %s", ty1);
608 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
609 if (rotate_entfield_array_index_nodes(&out))
612 /* This is not broken in fteqcc anymore */
613 if (opts.standard != COMPILER_GMQCC) {
614 /* this error doesn't need to make us bail out */
615 (void)!parsewarning(parser, WARN_EXTENSIONS,
616 "accessing array-field members of an entity without parenthesis\n"
617 " -> this is an extension from -std=gmqcc");
625 if (!ast_block_add_expr(blocks[0], exprs[1]))
628 blocks[0] = ast_block_new(ctx);
629 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
630 !ast_block_add_expr(blocks[0], exprs[1]))
635 if (!ast_block_set_type(blocks[0], exprs[1]))
638 vec_push(sy->out, syblock(ctx, blocks[0]));
645 switch (exprs[0]->expression.vtype) {
647 if (CanConstFold1(exprs[0]))
648 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
650 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
651 (ast_expression*)parser_const_float_0(parser),
655 if (CanConstFold1(exprs[0]))
656 out = (ast_expression*)parser_const_vector_f(parser,
657 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
659 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
660 (ast_expression*)parser_const_vector_0(parser),
664 parseerror(parser, "invalid types used in expression: cannot negate type %s",
665 type_name[exprs[0]->expression.vtype]);
671 switch (exprs[0]->expression.vtype) {
673 if (CanConstFold1(exprs[0]))
674 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
676 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
679 if (CanConstFold1(exprs[0]))
680 out = (ast_expression*)parser_const_float(parser,
681 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
683 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
686 if (CanConstFold1(exprs[0])) {
687 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
688 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
690 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
692 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
693 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
695 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
698 /* we don't constant-fold NOT for these types */
700 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
703 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
706 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
707 type_name[exprs[0]->expression.vtype]);
713 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
714 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
716 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
717 type_name[exprs[0]->expression.vtype],
718 type_name[exprs[1]->expression.vtype]);
721 switch (exprs[0]->expression.vtype) {
723 if (CanConstFold(exprs[0], exprs[1]))
725 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
728 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
731 if (CanConstFold(exprs[0], exprs[1]))
732 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
734 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
737 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
738 type_name[exprs[0]->expression.vtype],
739 type_name[exprs[1]->expression.vtype]);
744 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
745 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
747 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
748 type_name[exprs[1]->expression.vtype],
749 type_name[exprs[0]->expression.vtype]);
752 switch (exprs[0]->expression.vtype) {
754 if (CanConstFold(exprs[0], exprs[1]))
755 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
757 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
760 if (CanConstFold(exprs[0], exprs[1]))
761 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
763 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
766 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
767 type_name[exprs[1]->expression.vtype],
768 type_name[exprs[0]->expression.vtype]);
773 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
774 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
775 exprs[1]->expression.vtype == TYPE_FLOAT) &&
776 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
777 exprs[0]->expression.vtype == TYPE_FLOAT)
780 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
781 type_name[exprs[1]->expression.vtype],
782 type_name[exprs[0]->expression.vtype]);
785 switch (exprs[0]->expression.vtype) {
787 if (exprs[1]->expression.vtype == TYPE_VECTOR)
789 if (CanConstFold(exprs[0], exprs[1]))
790 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
792 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
799 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
803 if (exprs[1]->expression.vtype == TYPE_FLOAT)
805 if (CanConstFold(exprs[0], exprs[1]))
806 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
808 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
812 if (CanConstFold(exprs[0], exprs[1]))
813 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
814 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
815 vector vec = ConstV(0);
816 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
817 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
818 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
819 out->expression.node.keep = false;
820 ((ast_member*)out)->rvalue = true;
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
824 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
825 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
826 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
827 out->expression.node.keep = false;
828 ((ast_member*)out)->rvalue = true;
830 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
832 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
833 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
834 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
835 out->expression.node.keep = false;
836 ((ast_member*)out)->rvalue = true;
838 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
841 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
843 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
844 vector vec = ConstV(1);
845 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
846 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
847 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
848 out->expression.node.keep = false;
849 ((ast_member*)out)->rvalue = true;
851 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
853 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
854 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
855 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
856 out->expression.node.keep = false;
857 ((ast_member*)out)->rvalue = true;
859 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
861 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
862 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
863 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
864 out->expression.node.keep = false;
865 ((ast_member*)out)->rvalue = true;
867 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
870 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
873 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
877 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
878 type_name[exprs[1]->expression.vtype],
879 type_name[exprs[0]->expression.vtype]);
884 if (NotSameType(TYPE_FLOAT)) {
885 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
886 type_name[exprs[0]->expression.vtype],
887 type_name[exprs[1]->expression.vtype]);
890 if (CanConstFold(exprs[0], exprs[1]))
891 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
893 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
897 parseerror(parser, "qc does not have a modulo operator");
901 if (NotSameType(TYPE_FLOAT)) {
902 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
903 type_name[exprs[0]->expression.vtype],
904 type_name[exprs[1]->expression.vtype]);
907 if (CanConstFold(exprs[0], exprs[1]))
908 out = (ast_expression*)parser_const_float(parser,
909 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
910 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
912 out = (ast_expression*)ast_binary_new(ctx,
913 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
917 parseerror(parser, "TODO: bitxor");
922 case opid3('<','<','='):
923 case opid3('>','>','='):
924 parseerror(parser, "TODO: shifts");
928 generated_op += 1; /* INSTR_OR */
930 generated_op += INSTR_AND;
932 if (NotSameType(TYPE_FLOAT)) {
933 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
934 type_name[exprs[0]->expression.vtype],
935 type_name[exprs[1]->expression.vtype]);
936 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
937 parseerror(parser, "TODO: optional early out");
941 if (CanConstFold(exprs[0], exprs[1]))
943 if (OPTS_FLAG(PERL_LOGIC)) {
944 if (immediate_is_true(ctx, asvalue[0]))
948 out = (ast_expression*)parser_const_float(parser,
949 ( (generated_op == INSTR_OR)
950 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
951 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
956 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
957 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
958 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
959 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
962 for (i = 0; i < 2; ++i) {
963 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
964 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
966 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
968 exprs[i] = out; out = NULL;
969 if (OPTS_FLAG(PERL_LOGIC)) {
970 /* here we want to keep the right expressions' type */
974 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
975 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
977 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
979 exprs[i] = out; out = NULL;
980 if (OPTS_FLAG(PERL_LOGIC)) {
981 /* here we want to keep the right expressions' type */
986 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
991 if (vec_last(parser->pot) != POT_TERNARY2) {
992 parseerror(parser, "mismatched parenthesis/ternary");
995 vec_pop(parser->pot);
996 if (!ast_compare_type(exprs[1], exprs[2])) {
997 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
998 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
999 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1002 if (CanConstFold1(exprs[0]))
1003 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1005 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1009 generated_op += 1; /* INSTR_GT */
1011 generated_op += 1; /* INSTR_LT */
1012 case opid2('>', '='):
1013 generated_op += 1; /* INSTR_GE */
1014 case opid2('<', '='):
1015 generated_op += INSTR_LE;
1016 if (NotSameType(TYPE_FLOAT)) {
1017 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1018 type_name[exprs[0]->expression.vtype],
1019 type_name[exprs[1]->expression.vtype]);
1022 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1024 case opid2('!', '='):
1025 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1026 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1027 type_name[exprs[0]->expression.vtype],
1028 type_name[exprs[1]->expression.vtype]);
1031 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1033 case opid2('=', '='):
1034 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1035 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1036 type_name[exprs[0]->expression.vtype],
1037 type_name[exprs[1]->expression.vtype]);
1040 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1044 if (ast_istype(exprs[0], ast_entfield)) {
1045 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1046 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1047 exprs[0]->expression.vtype == TYPE_FIELD &&
1048 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1050 assignop = type_storep_instr[TYPE_VECTOR];
1053 assignop = type_storep_instr[exprs[0]->expression.vtype];
1054 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1056 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1057 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1058 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1059 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1060 exprs[1]->expression.vtype == TYPE_FUNCTION)
1062 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1063 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1066 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1071 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1072 exprs[0]->expression.vtype == TYPE_FIELD &&
1073 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1075 assignop = type_store_instr[TYPE_VECTOR];
1078 assignop = type_store_instr[exprs[0]->expression.vtype];
1081 if (assignop == AINSTR_END) {
1082 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1083 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1084 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1086 else if (!ast_compare_type(exprs[0], exprs[1]))
1088 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1089 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1090 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1091 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1092 exprs[1]->expression.vtype == TYPE_FUNCTION)
1094 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1095 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1098 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1101 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1102 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1104 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1106 case opid3('+','+','P'):
1107 case opid3('-','-','P'):
1109 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1110 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1111 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1114 if (op->id == opid3('+','+','P'))
1115 addop = INSTR_ADD_F;
1117 addop = INSTR_SUB_F;
1118 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1119 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1121 if (ast_istype(exprs[0], ast_entfield)) {
1122 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1124 (ast_expression*)parser_const_float_1(parser));
1126 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1128 (ast_expression*)parser_const_float_1(parser));
1131 case opid3('S','+','+'):
1132 case opid3('S','-','-'):
1134 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1139 if (op->id == opid3('S','+','+')) {
1140 addop = INSTR_ADD_F;
1141 subop = INSTR_SUB_F;
1143 addop = INSTR_SUB_F;
1144 subop = INSTR_ADD_F;
1146 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1147 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1149 if (ast_istype(exprs[0], ast_entfield)) {
1150 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1152 (ast_expression*)parser_const_float_1(parser));
1154 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1156 (ast_expression*)parser_const_float_1(parser));
1160 out = (ast_expression*)ast_binary_new(ctx, subop,
1162 (ast_expression*)parser_const_float_1(parser));
1164 case opid2('+','='):
1165 case opid2('-','='):
1166 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1167 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1169 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1170 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1171 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1175 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1176 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1178 if (ast_istype(exprs[0], ast_entfield))
1179 assignop = type_storep_instr[exprs[0]->expression.vtype];
1181 assignop = type_store_instr[exprs[0]->expression.vtype];
1182 switch (exprs[0]->expression.vtype) {
1184 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1185 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1186 exprs[0], exprs[1]);
1189 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1190 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1191 exprs[0], exprs[1]);
1194 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1195 type_name[exprs[0]->expression.vtype],
1196 type_name[exprs[1]->expression.vtype]);
1200 case opid2('*','='):
1201 case opid2('/','='):
1202 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1203 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1204 exprs[0]->expression.vtype == TYPE_VECTOR))
1206 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1207 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1208 parseerror(parser, "invalid types used in expression: %s and %s",
1212 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1213 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1215 if (ast_istype(exprs[0], ast_entfield))
1216 assignop = type_storep_instr[exprs[0]->expression.vtype];
1218 assignop = type_store_instr[exprs[0]->expression.vtype];
1219 switch (exprs[0]->expression.vtype) {
1221 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1222 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1223 exprs[0], exprs[1]);
1226 if (op->id == opid2('*','=')) {
1227 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1228 exprs[0], exprs[1]);
1230 /* there's no DIV_VF */
1231 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1232 (ast_expression*)parser_const_float_1(parser),
1236 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1241 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1242 type_name[exprs[0]->expression.vtype],
1243 type_name[exprs[1]->expression.vtype]);
1247 case opid2('&','='):
1248 case opid2('|','='):
1249 if (NotSameType(TYPE_FLOAT)) {
1250 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1251 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1252 parseerror(parser, "invalid types used in expression: %s and %s",
1256 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1257 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1259 if (ast_istype(exprs[0], ast_entfield))
1260 assignop = type_storep_instr[exprs[0]->expression.vtype];
1262 assignop = type_store_instr[exprs[0]->expression.vtype];
1263 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1264 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1265 exprs[0], exprs[1]);
1267 case opid3('&','~','='):
1268 /* This is like: a &= ~(b);
1269 * But QC has no bitwise-not, so we implement it as
1272 if (NotSameType(TYPE_FLOAT)) {
1273 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1274 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1275 parseerror(parser, "invalid types used in expression: %s and %s",
1279 if (ast_istype(exprs[0], ast_entfield))
1280 assignop = type_storep_instr[exprs[0]->expression.vtype];
1282 assignop = type_store_instr[exprs[0]->expression.vtype];
1283 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1286 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1287 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1289 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1290 asbinstore->keep_dest = true;
1291 out = (ast_expression*)asbinstore;
1297 parseerror(parser, "failed to apply operand %s", op->op);
1301 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1302 vec_push(sy->out, syexp(ctx, out));
1306 static bool parser_close_call(parser_t *parser, shunt *sy)
1308 /* was a function call */
1309 ast_expression *fun;
1315 vec_shrinkby(sy->ops, 1);
1316 fid = sy->ops[vec_size(sy->ops)].off;
1318 /* out[fid] is the function
1319 * everything above is parameters...
1320 * 0 params = nothing
1321 * 1 params = ast_expression
1325 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1326 parseerror(parser, "internal error: function call needs function and parameter list...");
1330 fun = sy->out[fid].out;
1332 if (fun == intrinsic_debug_typestring) {
1334 if (fid+2 != vec_size(sy->out) ||
1335 vec_last(sy->out).block)
1337 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1340 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1341 ast_unref(vec_last(sy->out).out);
1342 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1343 (ast_expression*)parser_const_string(parser, ty, false));
1344 vec_shrinkby(sy->out, 1);
1348 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1350 parseerror(parser, "internal error: failed to create ast_call node");
1354 if (fid+1 == vec_size(sy->out)) {
1357 } else if (fid+2 == vec_size(sy->out)) {
1359 vec_shrinkby(sy->out, 1);
1360 params = sy->out[vec_size(sy->out)].block;
1364 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1366 paramcount = vec_size(params->exprs);
1367 call->params = params->exprs;
1368 params->exprs = NULL;
1371 (void)!ast_call_check_types(call);
1373 parseerror(parser, "invalid function call");
1377 /* overwrite fid, the function, with a call */
1378 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1380 if (fun->expression.vtype != TYPE_FUNCTION) {
1381 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1385 if (!fun->expression.next) {
1386 parseerror(parser, "could not determine function return type");
1389 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1391 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1393 return !parsewarning(parser, WARN_DEPRECATED,
1394 "call to function (which is marked deprecated)\n",
1395 "-> it has been declared here: %s:%i",
1396 ast_ctx(fun).file, ast_ctx(fun).line);
1399 return !parsewarning(parser, WARN_DEPRECATED,
1400 "call to `%s` (which is marked deprecated)\n"
1401 "-> `%s` declared here: %s:%i",
1402 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1404 return !parsewarning(parser, WARN_DEPRECATED,
1405 "call to `%s` (deprecated: %s)\n"
1406 "-> `%s` declared here: %s:%i",
1407 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1411 if (vec_size(fun->expression.params) != paramcount &&
1412 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1413 vec_size(fun->expression.params) < paramcount))
1415 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1417 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1418 "too %s parameters for call to %s: expected %i, got %i\n"
1419 " -> `%s` has been declared here: %s:%i",
1420 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1421 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1423 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1424 "too %s parameters for function call: expected %i, got %i\n"
1425 " -> it has been declared here: %s:%i",
1426 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1427 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1434 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1436 if (!vec_size(sy->ops)) {
1437 parseerror(parser, "unmatched closing paren");
1440 /* this would for bit a + (x) because there are no operators inside (x)
1441 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1442 parseerror(parser, "empty parenthesis expression");
1446 while (vec_size(sy->ops)) {
1447 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1448 if (!parser_close_call(parser, sy))
1452 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1453 vec_shrinkby(sy->ops, 1);
1454 return !functions_only;
1456 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1459 /* pop off the parenthesis */
1460 vec_shrinkby(sy->ops, 1);
1461 /* then apply the index operator */
1462 if (!parser_sy_apply_operator(parser, sy))
1466 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1469 if (vec_last(parser->pot) != POT_TERNARY1) {
1470 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1473 vec_last(parser->pot) = POT_TERNARY2;
1474 /* pop off the parenthesis */
1475 vec_shrinkby(sy->ops, 1);
1478 if (!parser_sy_apply_operator(parser, sy))
1484 static void parser_reclassify_token(parser_t *parser)
1487 for (i = 0; i < operator_count; ++i) {
1488 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1489 parser->tok = TOKEN_OPERATOR;
1495 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1497 ast_expression *expr = NULL;
1499 bool wantop = false;
1500 bool gotmemberof = false;
1501 /* only warn once about an assignment in a truth value because the current code
1502 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1504 bool warn_truthvalue = true;
1506 /* count the parens because an if starts with one, so the
1507 * end of a condition is an unmatched closing paren
1515 parser->lex->flags.noops = false;
1517 parser_reclassify_token(parser);
1522 gotmemberof = false;
1524 parser->memberof = 0;
1526 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1527 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1529 /* a translatable string */
1533 parseerror(parser, "expected operator or end of statement, got constant");
1537 parser->lex->flags.noops = true;
1538 if (!parser_next(parser) || parser->tok != '(') {
1539 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1542 parser->lex->flags.noops = false;
1543 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1544 parseerror(parser, "expected a constant string in translatable-string extension");
1547 val = parser_const_string(parser, parser_tokval(parser), true);
1551 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1552 DEBUGSHUNTDO(con_out("push string\n"));
1554 if (!parser_next(parser) || parser->tok != ')') {
1555 parseerror(parser, "expected closing paren after translatable string");
1559 else if (parser->tok == TOKEN_IDENT)
1561 ast_expression *var;
1563 parseerror(parser, "expected operator or end of statement");
1568 if (opts.standard == COMPILER_GMQCC)
1570 if (parser->memberof == TYPE_ENTITY) {
1571 /* still get vars first since there could be a fieldpointer */
1572 var = parser_find_var(parser, parser_tokval(parser));
1574 var = parser_find_field(parser, parser_tokval(parser));
1576 else if (parser->memberof == TYPE_VECTOR)
1578 parseerror(parser, "TODO: implement effective vector member access");
1581 else if (parser->memberof) {
1582 parseerror(parser, "namespace for member not found");
1586 var = parser_find_var(parser, parser_tokval(parser));
1588 var = parser_find_var(parser, parser_tokval(parser));
1590 var = parser_find_field(parser, parser_tokval(parser));
1592 if (!var && with_labels) {
1593 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1595 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1596 var = (ast_expression*)lbl;
1597 vec_push(parser->labels, lbl);
1602 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1603 var = (ast_expression*)intrinsic_debug_typestring;
1608 * sometimes people use preprocessing predefs without enabling them
1609 * i've done this thousands of times already myself. Lets check for
1610 * it in the predef table. And diagnose it better :)
1612 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1614 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1615 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1616 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1622 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1628 if (ast_istype(var, ast_value)) {
1629 ((ast_value*)var)->uses++;
1631 else if (ast_istype(var, ast_member)) {
1632 ast_member *mem = (ast_member*)var;
1633 if (ast_istype(mem->owner, ast_value))
1634 ((ast_value*)(mem->owner))->uses++;
1637 vec_push(sy.out, syexp(parser_ctx(parser), var));
1638 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1640 else if (parser->tok == TOKEN_FLOATCONST) {
1643 parseerror(parser, "expected operator or end of statement, got constant");
1647 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1650 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1651 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1653 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1656 parseerror(parser, "expected operator or end of statement, got constant");
1660 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1663 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1664 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1666 else if (parser->tok == TOKEN_STRINGCONST) {
1669 parseerror(parser, "expected operator or end of statement, got constant");
1673 val = parser_const_string(parser, parser_tokval(parser), false);
1676 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1677 DEBUGSHUNTDO(con_out("push string\n"));
1679 else if (parser->tok == TOKEN_VECTORCONST) {
1682 parseerror(parser, "expected operator or end of statement, got constant");
1686 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1689 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1690 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1691 parser_token(parser)->constval.v.x,
1692 parser_token(parser)->constval.v.y,
1693 parser_token(parser)->constval.v.z));
1695 else if (parser->tok == '(') {
1696 parseerror(parser, "internal error: '(' should be classified as operator");
1699 else if (parser->tok == '[') {
1700 parseerror(parser, "internal error: '[' should be classified as operator");
1703 else if (parser->tok == ')') {
1705 DEBUGSHUNTDO(con_out("do[op] )\n"));
1709 /* we do expect an operator next */
1710 /* closing an opening paren */
1711 if (!parser_close_paren(parser, &sy, false))
1713 if (vec_last(parser->pot) != POT_PAREN) {
1714 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1717 vec_pop(parser->pot);
1719 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1723 /* allowed for function calls */
1724 if (!parser_close_paren(parser, &sy, true))
1726 if (vec_last(parser->pot) != POT_PAREN) {
1727 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1730 vec_pop(parser->pot);
1734 else if (parser->tok == ']') {
1736 parseerror(parser, "operand expected");
1740 if (!parser_close_paren(parser, &sy, false))
1742 if (vec_last(parser->pot) != POT_PAREN) {
1743 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1746 vec_pop(parser->pot);
1749 else if (parser->tok == TOKEN_TYPENAME) {
1750 parseerror(parser, "unexpected typename");
1753 else if (parser->tok != TOKEN_OPERATOR) {
1755 parseerror(parser, "expected operator or end of statement");
1762 /* classify the operator */
1763 const oper_info *op;
1764 const oper_info *olast = NULL;
1766 for (o = 0; o < operator_count; ++o) {
1767 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1768 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1769 !strcmp(parser_tokval(parser), operators[o].op))
1774 if (o == operator_count) {
1775 /* no operator found... must be the end of the statement */
1778 /* found an operator */
1781 /* when declaring variables, a comma starts a new variable */
1782 if (op->id == opid1(',') && !parens && stopatcomma) {
1783 /* fixup the token */
1788 /* a colon without a pervious question mark cannot be a ternary */
1789 if (!ternaries && op->id == opid2(':','?')) {
1794 if (op->id == opid1(',')) {
1795 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1796 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1800 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1801 olast = &operators[vec_last(sy.ops).etype-1];
1803 #define IsAssignOp(x) (\
1804 (x) == opid1('=') || \
1805 (x) == opid2('+','=') || \
1806 (x) == opid2('-','=') || \
1807 (x) == opid2('*','=') || \
1808 (x) == opid2('/','=') || \
1809 (x) == opid2('%','=') || \
1810 (x) == opid2('&','=') || \
1811 (x) == opid2('|','=') || \
1812 (x) == opid3('&','~','=') \
1814 if (warn_truthvalue) {
1815 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1816 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1817 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1820 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1821 warn_truthvalue = false;
1826 (op->prec < olast->prec) ||
1827 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1829 if (!parser_sy_apply_operator(parser, &sy))
1831 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1832 olast = &operators[vec_last(sy.ops).etype-1];
1837 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1838 /* for gmqcc standard: open up the namespace of the previous type */
1839 ast_expression *prevex = vec_last(sy.out).out;
1841 parseerror(parser, "unexpected member operator");
1844 if (prevex->expression.vtype == TYPE_ENTITY)
1845 parser->memberof = TYPE_ENTITY;
1846 else if (prevex->expression.vtype == TYPE_VECTOR)
1847 parser->memberof = TYPE_VECTOR;
1849 parseerror(parser, "type error: type has no members");
1855 if (op->id == opid1('(')) {
1857 size_t sycount = vec_size(sy.out);
1858 DEBUGSHUNTDO(con_out("push [op] (\n"));
1859 ++parens; vec_push(parser->pot, POT_PAREN);
1860 /* we expected an operator, this is the function-call operator */
1861 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1863 ++parens; vec_push(parser->pot, POT_PAREN);
1864 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1865 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1868 } else if (op->id == opid1('[')) {
1870 parseerror(parser, "unexpected array subscript");
1873 ++parens; vec_push(parser->pot, POT_PAREN);
1874 /* push both the operator and the paren, this makes life easier */
1875 vec_push(sy.ops, syop(parser_ctx(parser), op));
1876 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1878 } else if (op->id == opid2('?',':')) {
1879 vec_push(sy.ops, syop(parser_ctx(parser), op));
1880 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1883 vec_push(parser->pot, POT_TERNARY1);
1884 } else if (op->id == opid2(':','?')) {
1885 if (!vec_size(parser->pot)) {
1886 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1889 if (vec_last(parser->pot) != POT_TERNARY1) {
1890 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1893 if (!parser_close_paren(parser, &sy, false))
1895 vec_push(sy.ops, syop(parser_ctx(parser), op));
1899 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1900 vec_push(sy.ops, syop(parser_ctx(parser), op));
1901 wantop = !!(op->flags & OP_SUFFIX);
1904 if (!parser_next(parser)) {
1907 if (parser->tok == ';' ||
1908 (!parens && parser->tok == ']'))
1914 while (vec_size(sy.ops)) {
1915 if (!parser_sy_apply_operator(parser, &sy))
1919 parser->lex->flags.noops = true;
1920 if (!vec_size(sy.out)) {
1921 parseerror(parser, "empty expression");
1924 expr = sy.out[0].out;
1927 DEBUGSHUNTDO(con_out("shunt done\n"));
1928 if (vec_size(parser->pot)) {
1929 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1932 vec_free(parser->pot);
1936 parser->lex->flags.noops = true;
1942 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1944 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1947 if (!parser_next(parser)) {
1954 static void parser_enterblock(parser_t *parser)
1956 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1957 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1958 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1959 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1960 vec_push(parser->_block_ctx, parser_ctx(parser));
1963 static bool parser_leaveblock(parser_t *parser)
1966 size_t locals, typedefs;
1968 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1969 parseerror(parser, "internal error: parser_leaveblock with no block");
1973 util_htdel(vec_last(parser->variables));
1974 vec_pop(parser->variables);
1975 if (!vec_size(parser->_blocklocals)) {
1976 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1980 locals = vec_last(parser->_blocklocals);
1981 vec_pop(parser->_blocklocals);
1982 while (vec_size(parser->_locals) != locals) {
1983 ast_expression *e = vec_last(parser->_locals);
1984 ast_value *v = (ast_value*)e;
1985 vec_pop(parser->_locals);
1986 if (ast_istype(e, ast_value) && !v->uses) {
1987 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1992 typedefs = vec_last(parser->_blocktypedefs);
1993 while (vec_size(parser->_typedefs) != typedefs) {
1994 ast_delete(vec_last(parser->_typedefs));
1995 vec_pop(parser->_typedefs);
1997 util_htdel(vec_last(parser->typedefs));
1998 vec_pop(parser->typedefs);
2000 vec_pop(parser->_block_ctx);
2004 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2006 vec_push(parser->_locals, e);
2007 util_htset(vec_last(parser->variables), name, (void*)e);
2010 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2014 ast_expression *prev;
2016 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2019 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2022 parseerror(parser, "internal error: failed to process condition");
2027 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2029 /* vector types need to be cast to true booleans */
2030 ast_binary *bin = (ast_binary*)cond;
2031 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2033 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2035 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2038 parseerror(parser, "internal error: failed to process condition");
2045 unary = (ast_unary*)cond;
2046 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2048 cond = unary->operand;
2049 unary->operand = NULL;
2052 unary = (ast_unary*)cond;
2056 parseerror(parser, "internal error: failed to process condition");
2058 if (ifnot) *_ifnot = !*_ifnot;
2062 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2065 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2068 lex_ctx ctx = parser_ctx(parser);
2070 (void)block; /* not touching */
2072 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2073 if (!parser_next(parser)) {
2074 parseerror(parser, "expected condition or 'not'");
2077 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2079 if (!parser_next(parser)) {
2080 parseerror(parser, "expected condition in parenthesis");
2084 if (parser->tok != '(') {
2085 parseerror(parser, "expected 'if' condition in parenthesis");
2088 /* parse into the expression */
2089 if (!parser_next(parser)) {
2090 parseerror(parser, "expected 'if' condition after opening paren");
2093 /* parse the condition */
2094 cond = parse_expression_leave(parser, false, true, false);
2098 if (parser->tok != ')') {
2099 parseerror(parser, "expected closing paren after 'if' condition");
2103 /* parse into the 'then' branch */
2104 if (!parser_next(parser)) {
2105 parseerror(parser, "expected statement for on-true branch of 'if'");
2109 if (!parse_statement_or_block(parser, &ontrue)) {
2113 /* check for an else */
2114 if (!strcmp(parser_tokval(parser), "else")) {
2115 /* parse into the 'else' branch */
2116 if (!parser_next(parser)) {
2117 parseerror(parser, "expected on-false branch after 'else'");
2122 if (!parse_statement_or_block(parser, &onfalse)) {
2129 cond = process_condition(parser, cond, &ifnot);
2131 if (ontrue) ast_delete(ontrue);
2132 if (onfalse) ast_delete(onfalse);
2137 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2139 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2140 *out = (ast_expression*)ifthen;
2144 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2145 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2150 /* skip the 'while' and get the body */
2151 if (!parser_next(parser)) {
2152 if (OPTS_FLAG(LOOP_LABELS))
2153 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2155 parseerror(parser, "expected 'while' condition in parenthesis");
2159 if (parser->tok == ':') {
2160 if (!OPTS_FLAG(LOOP_LABELS))
2161 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2162 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2163 parseerror(parser, "expected loop label");
2166 label = util_strdup(parser_tokval(parser));
2167 if (!parser_next(parser)) {
2169 parseerror(parser, "expected 'while' condition in parenthesis");
2174 if (parser->tok != '(') {
2175 parseerror(parser, "expected 'while' condition in parenthesis");
2179 vec_push(parser->breaks, label);
2180 vec_push(parser->continues, label);
2182 rv = parse_while_go(parser, block, out);
2185 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2186 parseerror(parser, "internal error: label stack corrupted");
2192 vec_pop(parser->breaks);
2193 vec_pop(parser->continues);
2198 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2201 ast_expression *cond, *ontrue;
2205 lex_ctx ctx = parser_ctx(parser);
2207 (void)block; /* not touching */
2209 /* parse into the expression */
2210 if (!parser_next(parser)) {
2211 parseerror(parser, "expected 'while' condition after opening paren");
2214 /* parse the condition */
2215 cond = parse_expression_leave(parser, false, true, false);
2219 if (parser->tok != ')') {
2220 parseerror(parser, "expected closing paren after 'while' condition");
2224 /* parse into the 'then' branch */
2225 if (!parser_next(parser)) {
2226 parseerror(parser, "expected while-loop body");
2230 if (!parse_statement_or_block(parser, &ontrue)) {
2235 cond = process_condition(parser, cond, &ifnot);
2240 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2241 *out = (ast_expression*)aloop;
2245 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2246 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2251 /* skip the 'do' and get the body */
2252 if (!parser_next(parser)) {
2253 if (OPTS_FLAG(LOOP_LABELS))
2254 parseerror(parser, "expected loop label or body");
2256 parseerror(parser, "expected loop body");
2260 if (parser->tok == ':') {
2261 if (!OPTS_FLAG(LOOP_LABELS))
2262 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2263 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2264 parseerror(parser, "expected loop label");
2267 label = util_strdup(parser_tokval(parser));
2268 if (!parser_next(parser)) {
2270 parseerror(parser, "expected loop body");
2275 vec_push(parser->breaks, label);
2276 vec_push(parser->continues, label);
2278 rv = parse_dowhile_go(parser, block, out);
2281 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2282 parseerror(parser, "internal error: label stack corrupted");
2288 vec_pop(parser->breaks);
2289 vec_pop(parser->continues);
2294 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2297 ast_expression *cond, *ontrue;
2301 lex_ctx ctx = parser_ctx(parser);
2303 (void)block; /* not touching */
2305 if (!parse_statement_or_block(parser, &ontrue))
2308 /* expect the "while" */
2309 if (parser->tok != TOKEN_KEYWORD ||
2310 strcmp(parser_tokval(parser), "while"))
2312 parseerror(parser, "expected 'while' and condition");
2317 /* skip the 'while' and check for opening paren */
2318 if (!parser_next(parser) || parser->tok != '(') {
2319 parseerror(parser, "expected 'while' condition in parenthesis");
2323 /* parse into the expression */
2324 if (!parser_next(parser)) {
2325 parseerror(parser, "expected 'while' condition after opening paren");
2329 /* parse the condition */
2330 cond = parse_expression_leave(parser, false, true, false);
2334 if (parser->tok != ')') {
2335 parseerror(parser, "expected closing paren after 'while' condition");
2341 if (!parser_next(parser) || parser->tok != ';') {
2342 parseerror(parser, "expected semicolon after condition");
2348 if (!parser_next(parser)) {
2349 parseerror(parser, "parse error");
2355 cond = process_condition(parser, cond, &ifnot);
2360 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2361 *out = (ast_expression*)aloop;
2365 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2366 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2371 /* skip the 'for' and check for opening paren */
2372 if (!parser_next(parser)) {
2373 if (OPTS_FLAG(LOOP_LABELS))
2374 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2376 parseerror(parser, "expected 'for' expressions in parenthesis");
2380 if (parser->tok == ':') {
2381 if (!OPTS_FLAG(LOOP_LABELS))
2382 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2383 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2384 parseerror(parser, "expected loop label");
2387 label = util_strdup(parser_tokval(parser));
2388 if (!parser_next(parser)) {
2390 parseerror(parser, "expected 'for' expressions in parenthesis");
2395 if (parser->tok != '(') {
2396 parseerror(parser, "expected 'for' expressions in parenthesis");
2400 vec_push(parser->breaks, label);
2401 vec_push(parser->continues, label);
2403 rv = parse_for_go(parser, block, out);
2406 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2407 parseerror(parser, "internal error: label stack corrupted");
2413 vec_pop(parser->breaks);
2414 vec_pop(parser->continues);
2418 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2421 ast_expression *initexpr, *cond, *increment, *ontrue;
2427 lex_ctx ctx = parser_ctx(parser);
2429 parser_enterblock(parser);
2436 /* parse into the expression */
2437 if (!parser_next(parser)) {
2438 parseerror(parser, "expected 'for' initializer after opening paren");
2443 if (parser->tok == TOKEN_IDENT)
2444 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2446 if (typevar || parser->tok == TOKEN_TYPENAME) {
2448 if (opts.standard != COMPILER_GMQCC) {
2449 if (parsewarning(parser, WARN_EXTENSIONS,
2450 "current standard does not allow variable declarations in for-loop initializers"))
2454 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2457 else if (parser->tok != ';')
2459 initexpr = parse_expression_leave(parser, false, false, false);
2464 /* move on to condition */
2465 if (parser->tok != ';') {
2466 parseerror(parser, "expected semicolon after for-loop initializer");
2469 if (!parser_next(parser)) {
2470 parseerror(parser, "expected for-loop condition");
2474 /* parse the condition */
2475 if (parser->tok != ';') {
2476 cond = parse_expression_leave(parser, false, true, false);
2481 /* move on to incrementor */
2482 if (parser->tok != ';') {
2483 parseerror(parser, "expected semicolon after for-loop initializer");
2486 if (!parser_next(parser)) {
2487 parseerror(parser, "expected for-loop condition");
2491 /* parse the incrementor */
2492 if (parser->tok != ')') {
2493 increment = parse_expression_leave(parser, false, false, false);
2496 if (!ast_side_effects(increment)) {
2497 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2503 if (parser->tok != ')') {
2504 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2507 /* parse into the 'then' branch */
2508 if (!parser_next(parser)) {
2509 parseerror(parser, "expected for-loop body");
2512 if (!parse_statement_or_block(parser, &ontrue))
2516 cond = process_condition(parser, cond, &ifnot);
2520 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2521 *out = (ast_expression*)aloop;
2523 if (!parser_leaveblock(parser))
2527 if (initexpr) ast_delete(initexpr);
2528 if (cond) ast_delete(cond);
2529 if (increment) ast_delete(increment);
2530 (void)!parser_leaveblock(parser);
2534 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2536 ast_expression *exp = NULL;
2537 ast_return *ret = NULL;
2538 ast_value *expected = parser->function->vtype;
2540 lex_ctx ctx = parser_ctx(parser);
2542 (void)block; /* not touching */
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected return expression");
2549 if (parser->tok != ';') {
2550 exp = parse_expression(parser, false, false);
2554 if (exp->expression.vtype != TYPE_NIL &&
2555 exp->expression.vtype != expected->expression.next->expression.vtype)
2557 parseerror(parser, "return with invalid expression");
2560 ret = ast_return_new(ctx, exp);
2566 if (!parser_next(parser))
2567 parseerror(parser, "parse error");
2568 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2569 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2571 ret = ast_return_new(ctx, NULL);
2573 *out = (ast_expression*)ret;
2577 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2580 unsigned int levels = 0;
2581 lex_ctx ctx = parser_ctx(parser);
2582 const char **loops = (is_continue ? parser->continues : parser->breaks);
2584 (void)block; /* not touching */
2585 if (!parser_next(parser)) {
2586 parseerror(parser, "expected semicolon or loop label");
2590 if (parser->tok == TOKEN_IDENT) {
2591 if (!OPTS_FLAG(LOOP_LABELS))
2592 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2593 i = vec_size(loops);
2595 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2598 parseerror(parser, "no such loop to %s: `%s`",
2599 (is_continue ? "continue" : "break out of"),
2600 parser_tokval(parser));
2605 if (!parser_next(parser)) {
2606 parseerror(parser, "expected semicolon");
2611 if (parser->tok != ';') {
2612 parseerror(parser, "expected semicolon");
2616 if (!parser_next(parser))
2617 parseerror(parser, "parse error");
2619 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2623 /* returns true when it was a variable qualifier, false otherwise!
2624 * on error, cvq is set to CV_WRONG
2626 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2628 bool had_const = false;
2629 bool had_var = false;
2630 bool had_noref = false;
2631 bool had_attrib = false;
2632 bool had_static = false;
2637 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2639 /* parse an attribute */
2640 if (!parser_next(parser)) {
2641 parseerror(parser, "expected attribute after `[[`");
2645 if (!strcmp(parser_tokval(parser), "noreturn")) {
2646 flags |= AST_FLAG_NORETURN;
2647 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2648 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2653 else if (!strcmp(parser_tokval(parser), "noref")) {
2655 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2656 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2661 else if (!strcmp(parser_tokval(parser), "inline")) {
2662 flags |= AST_FLAG_INLINE;
2663 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2664 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2671 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2672 flags |= AST_FLAG_DEPRECATED;
2675 if (!parser_next(parser)) {
2676 parseerror(parser, "parse error in attribute");
2680 if (parser->tok == '(') {
2681 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2682 parseerror(parser, "`deprecated` attribute missing parameter");
2686 *message = util_strdup(parser_tokval(parser));
2688 if (!parser_next(parser)) {
2689 parseerror(parser, "parse error in attribute");
2693 if(parser->tok != ')') {
2694 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2698 if (!parser_next(parser)) {
2699 parseerror(parser, "parse error in attribute");
2704 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2705 parseerror(parser, "`deprecated` attribute expected `]]`");
2708 if (*message) mem_d(*message);
2716 /* Skip tokens until we hit a ]] */
2717 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2718 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2719 if (!parser_next(parser)) {
2720 parseerror(parser, "error inside attribute");
2727 else if (!strcmp(parser_tokval(parser), "static"))
2729 else if (!strcmp(parser_tokval(parser), "const"))
2731 else if (!strcmp(parser_tokval(parser), "var"))
2733 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2735 else if (!strcmp(parser_tokval(parser), "noref"))
2737 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2742 if (!parser_next(parser))
2752 *is_static = had_static;
2756 parseerror(parser, "parse error after variable qualifier");
2761 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2762 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2767 /* skip the 'while' and get the body */
2768 if (!parser_next(parser)) {
2769 if (OPTS_FLAG(LOOP_LABELS))
2770 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2772 parseerror(parser, "expected 'switch' operand in parenthesis");
2776 if (parser->tok == ':') {
2777 if (!OPTS_FLAG(LOOP_LABELS))
2778 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2779 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2780 parseerror(parser, "expected loop label");
2783 label = util_strdup(parser_tokval(parser));
2784 if (!parser_next(parser)) {
2786 parseerror(parser, "expected 'switch' operand in parenthesis");
2791 if (parser->tok != '(') {
2792 parseerror(parser, "expected 'switch' operand in parenthesis");
2796 vec_push(parser->breaks, label);
2798 rv = parse_switch_go(parser, block, out);
2801 if (vec_last(parser->breaks) != label) {
2802 parseerror(parser, "internal error: label stack corrupted");
2808 vec_pop(parser->breaks);
2813 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2815 ast_expression *operand;
2818 ast_switch *switchnode;
2819 ast_switch_case swcase;
2822 bool noref, is_static;
2823 uint32_t qflags = 0;
2825 lex_ctx ctx = parser_ctx(parser);
2827 (void)block; /* not touching */
2830 /* parse into the expression */
2831 if (!parser_next(parser)) {
2832 parseerror(parser, "expected switch operand");
2835 /* parse the operand */
2836 operand = parse_expression_leave(parser, false, false, false);
2840 switchnode = ast_switch_new(ctx, operand);
2843 if (parser->tok != ')') {
2844 ast_delete(switchnode);
2845 parseerror(parser, "expected closing paren after 'switch' operand");
2849 /* parse over the opening paren */
2850 if (!parser_next(parser) || parser->tok != '{') {
2851 ast_delete(switchnode);
2852 parseerror(parser, "expected list of cases");
2856 if (!parser_next(parser)) {
2857 ast_delete(switchnode);
2858 parseerror(parser, "expected 'case' or 'default'");
2862 /* new block; allow some variables to be declared here */
2863 parser_enterblock(parser);
2866 if (parser->tok == TOKEN_IDENT)
2867 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2868 if (typevar || parser->tok == TOKEN_TYPENAME) {
2869 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2870 ast_delete(switchnode);
2875 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2877 if (cvq == CV_WRONG) {
2878 ast_delete(switchnode);
2881 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2882 ast_delete(switchnode);
2891 while (parser->tok != '}') {
2892 ast_block *caseblock;
2894 if (!strcmp(parser_tokval(parser), "case")) {
2895 if (!parser_next(parser)) {
2896 ast_delete(switchnode);
2897 parseerror(parser, "expected expression for case");
2900 swcase.value = parse_expression_leave(parser, false, false, false);
2901 if (!swcase.value) {
2902 ast_delete(switchnode);
2903 parseerror(parser, "expected expression for case");
2906 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2907 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2908 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2914 else if (!strcmp(parser_tokval(parser), "default")) {
2915 swcase.value = NULL;
2916 if (!parser_next(parser)) {
2917 ast_delete(switchnode);
2918 parseerror(parser, "expected colon");
2923 ast_delete(switchnode);
2924 parseerror(parser, "expected 'case' or 'default'");
2928 /* Now the colon and body */
2929 if (parser->tok != ':') {
2930 if (swcase.value) ast_unref(swcase.value);
2931 ast_delete(switchnode);
2932 parseerror(parser, "expected colon");
2936 if (!parser_next(parser)) {
2937 if (swcase.value) ast_unref(swcase.value);
2938 ast_delete(switchnode);
2939 parseerror(parser, "expected statements or case");
2942 caseblock = ast_block_new(parser_ctx(parser));
2944 if (swcase.value) ast_unref(swcase.value);
2945 ast_delete(switchnode);
2948 swcase.code = (ast_expression*)caseblock;
2949 vec_push(switchnode->cases, swcase);
2951 ast_expression *expr;
2952 if (parser->tok == '}')
2954 if (parser->tok == TOKEN_KEYWORD) {
2955 if (!strcmp(parser_tokval(parser), "case") ||
2956 !strcmp(parser_tokval(parser), "default"))
2961 if (!parse_statement(parser, caseblock, &expr, true)) {
2962 ast_delete(switchnode);
2967 if (!ast_block_add_expr(caseblock, expr)) {
2968 ast_delete(switchnode);
2974 parser_leaveblock(parser);
2977 if (parser->tok != '}') {
2978 ast_delete(switchnode);
2979 parseerror(parser, "expected closing paren of case list");
2982 if (!parser_next(parser)) {
2983 ast_delete(switchnode);
2984 parseerror(parser, "parse error after switch");
2987 *out = (ast_expression*)switchnode;
2991 /* parse computed goto sides */
2992 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression *side) {
2993 ast_expression *on_true;
2994 ast_expression *on_false;
2999 if (ast_istype(side, ast_ternary)) {
3000 on_true = parse_goto_computed(parser, ((ast_ternary*)side)->on_true);
3001 on_false = parse_goto_computed(parser, ((ast_ternary*)side)->on_false);
3003 if (!on_true || !on_false) {
3004 parseerror(parser, "expected label or expression in ternary");
3005 if (((ast_ternary*)side)->on_false) ast_unref(((ast_ternary*)side)->on_false);
3006 if (((ast_ternary*)side)->on_true) ast_unref(((ast_ternary*)side)->on_true);
3010 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), ((ast_ternary*)side)->cond, on_true, on_false);
3011 } else if (ast_istype(side, ast_label)) {
3012 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)side)->name);
3013 ast_goto_set_label(gt, ((ast_label*)side));
3014 return (ast_expression*)gt;
3019 static bool parse_goto(parser_t *parser, ast_expression **out)
3021 ast_goto *gt = NULL;
3022 ast_expression *lbl;
3024 if (!parser_next(parser))
3027 if (parser->tok != TOKEN_IDENT) {
3028 ast_expression *expression;
3030 /* could be an expression i.e computed goto :-) */
3031 if (parser->tok != '(') {
3032 parseerror(parser, "expected label name after `goto`");
3036 /* failed to parse expression for goto */
3037 if (!(expression = parse_expression(parser, false, true)) ||
3038 !(*out = parse_goto_computed(parser, expression))) {
3039 parseerror(parser, "invalid goto expression");
3040 ast_unref(expression);
3047 /* not computed goto */
3048 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3049 lbl = parser_find_label(parser, gt->name);
3051 if (!ast_istype(lbl, ast_label)) {
3052 parseerror(parser, "internal error: label is not an ast_label");
3056 ast_goto_set_label(gt, (ast_label*)lbl);
3059 vec_push(parser->gotos, gt);
3061 if (!parser_next(parser) || parser->tok != ';') {
3062 parseerror(parser, "semicolon expected after goto label");
3065 if (!parser_next(parser)) {
3066 parseerror(parser, "parse error after goto");
3070 *out = (ast_expression*)gt;
3074 static bool parse_skipwhite(parser_t *parser)
3077 if (!parser_next(parser))
3079 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3080 return parser->tok < TOKEN_ERROR;
3083 static bool parse_eol(parser_t *parser)
3085 if (!parse_skipwhite(parser))
3087 return parser->tok == TOKEN_EOL;
3090 static bool parse_pragma_do(parser_t *parser)
3092 if (!parser_next(parser) ||
3093 parser->tok != TOKEN_IDENT ||
3094 strcmp(parser_tokval(parser), "pragma"))
3096 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3099 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3100 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3104 if (!strcmp(parser_tokval(parser), "noref")) {
3105 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3106 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3109 parser->noref = !!parser_token(parser)->constval.i;
3110 if (!parse_eol(parser)) {
3111 parseerror(parser, "parse error after `noref` pragma");
3117 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3124 static bool parse_pragma(parser_t *parser)
3127 parser->lex->flags.preprocessing = true;
3128 parser->lex->flags.mergelines = true;
3129 rv = parse_pragma_do(parser);
3130 if (parser->tok != TOKEN_EOL) {
3131 parseerror(parser, "junk after pragma");
3134 parser->lex->flags.preprocessing = false;
3135 parser->lex->flags.mergelines = false;
3136 if (!parser_next(parser)) {
3137 parseerror(parser, "parse error after pragma");
3143 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3145 bool noref, is_static;
3147 uint32_t qflags = 0;
3148 ast_value *typevar = NULL;
3149 char *vstring = NULL;
3153 if (parser->tok == TOKEN_IDENT)
3154 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3156 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3158 /* local variable */
3160 parseerror(parser, "cannot declare a variable from here");
3163 if (opts.standard == COMPILER_QCC) {
3164 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3167 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3171 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3173 if (cvq == CV_WRONG)
3175 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3177 else if (parser->tok == TOKEN_KEYWORD)
3179 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3184 if (!parser_next(parser)) {
3185 parseerror(parser, "parse error after __builtin_debug_printtype");
3189 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3191 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3192 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3193 if (!parser_next(parser)) {
3194 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3200 if (!parse_statement(parser, block, out, allow_cases))
3203 con_out("__builtin_debug_printtype: got no output node\n");
3206 ast_type_to_string(*out, ty, sizeof(ty));
3207 con_out("__builtin_debug_printtype: `%s`\n", ty);
3212 else if (!strcmp(parser_tokval(parser), "return"))
3214 return parse_return(parser, block, out);
3216 else if (!strcmp(parser_tokval(parser), "if"))
3218 return parse_if(parser, block, out);
3220 else if (!strcmp(parser_tokval(parser), "while"))
3222 return parse_while(parser, block, out);
3224 else if (!strcmp(parser_tokval(parser), "do"))
3226 return parse_dowhile(parser, block, out);
3228 else if (!strcmp(parser_tokval(parser), "for"))
3230 if (opts.standard == COMPILER_QCC) {
3231 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3234 return parse_for(parser, block, out);
3236 else if (!strcmp(parser_tokval(parser), "break"))
3238 return parse_break_continue(parser, block, out, false);
3240 else if (!strcmp(parser_tokval(parser), "continue"))
3242 return parse_break_continue(parser, block, out, true);
3244 else if (!strcmp(parser_tokval(parser), "switch"))
3246 return parse_switch(parser, block, out);
3248 else if (!strcmp(parser_tokval(parser), "case") ||
3249 !strcmp(parser_tokval(parser), "default"))
3252 parseerror(parser, "unexpected 'case' label");
3257 else if (!strcmp(parser_tokval(parser), "goto"))
3259 return parse_goto(parser, out);
3261 else if (!strcmp(parser_tokval(parser), "typedef"))
3263 if (!parser_next(parser)) {
3264 parseerror(parser, "expected type definition after 'typedef'");
3267 return parse_typedef(parser);
3269 parseerror(parser, "Unexpected keyword");
3272 else if (parser->tok == '{')
3275 inner = parse_block(parser);
3278 *out = (ast_expression*)inner;
3281 else if (parser->tok == ':')
3285 if (!parser_next(parser)) {
3286 parseerror(parser, "expected label name");
3289 if (parser->tok != TOKEN_IDENT) {
3290 parseerror(parser, "label must be an identifier");
3293 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3295 if (!label->undefined) {
3296 parseerror(parser, "label `%s` already defined", label->name);
3299 label->undefined = false;
3302 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3303 vec_push(parser->labels, label);
3305 *out = (ast_expression*)label;
3306 if (!parser_next(parser)) {
3307 parseerror(parser, "parse error after label");
3310 for (i = 0; i < vec_size(parser->gotos); ++i) {
3311 if (!strcmp(parser->gotos[i]->name, label->name)) {
3312 ast_goto_set_label(parser->gotos[i], label);
3313 vec_remove(parser->gotos, i, 1);
3319 else if (parser->tok == ';')
3321 if (!parser_next(parser)) {
3322 parseerror(parser, "parse error after empty statement");
3329 ast_expression *exp = parse_expression(parser, false, false);
3333 if (!ast_side_effects(exp)) {
3334 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3341 static bool parse_block_into(parser_t *parser, ast_block *block)
3345 parser_enterblock(parser);
3347 if (!parser_next(parser)) { /* skip the '{' */
3348 parseerror(parser, "expected function body");
3352 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3354 ast_expression *expr = NULL;
3355 if (parser->tok == '}')
3358 if (!parse_statement(parser, block, &expr, false)) {
3359 /* parseerror(parser, "parse error"); */
3365 if (!ast_block_add_expr(block, expr)) {
3372 if (parser->tok != '}') {
3375 (void)parser_next(parser);
3379 if (!parser_leaveblock(parser))
3381 return retval && !!block;
3384 static ast_block* parse_block(parser_t *parser)
3387 block = ast_block_new(parser_ctx(parser));
3390 if (!parse_block_into(parser, block)) {
3391 ast_block_delete(block);
3397 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3399 if (parser->tok == '{') {
3400 *out = (ast_expression*)parse_block(parser);
3403 return parse_statement(parser, NULL, out, false);
3406 static bool create_vector_members(ast_value *var, ast_member **me)
3409 size_t len = strlen(var->name);
3411 for (i = 0; i < 3; ++i) {
3412 char *name = (char*)mem_a(len+3);
3413 memcpy(name, var->name, len);
3415 name[len+1] = 'x'+i;
3417 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3426 do { ast_member_delete(me[--i]); } while(i);
3430 static bool parse_function_body(parser_t *parser, ast_value *var)
3432 ast_block *block = NULL;
3437 ast_expression *framenum = NULL;
3438 ast_expression *nextthink = NULL;
3439 /* None of the following have to be deleted */
3440 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3441 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3442 bool has_frame_think;
3446 has_frame_think = false;
3447 old = parser->function;
3449 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3450 parseerror(parser, "gotos/labels leaking");
3454 if (var->expression.flags & AST_FLAG_VARIADIC) {
3455 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3456 "variadic function with implementation will not be able to access additional parameters"))
3462 if (parser->tok == '[') {
3463 /* got a frame definition: [ framenum, nextthink ]
3464 * this translates to:
3465 * self.frame = framenum;
3466 * self.nextthink = time + 0.1;
3467 * self.think = nextthink;
3471 fld_think = parser_find_field(parser, "think");
3472 fld_nextthink = parser_find_field(parser, "nextthink");
3473 fld_frame = parser_find_field(parser, "frame");
3474 if (!fld_think || !fld_nextthink || !fld_frame) {
3475 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3476 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3479 gbl_time = parser_find_global(parser, "time");
3480 gbl_self = parser_find_global(parser, "self");
3481 if (!gbl_time || !gbl_self) {
3482 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3483 parseerror(parser, "please declare the following globals: `time`, `self`");
3487 if (!parser_next(parser))
3490 framenum = parse_expression_leave(parser, true, false, false);
3492 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3495 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3496 ast_unref(framenum);
3497 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3501 if (parser->tok != ',') {
3502 ast_unref(framenum);
3503 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3504 parseerror(parser, "Got a %i\n", parser->tok);
3508 if (!parser_next(parser)) {
3509 ast_unref(framenum);
3513 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3515 /* qc allows the use of not-yet-declared functions here
3516 * - this automatically creates a prototype */
3517 ast_value *thinkfunc;
3518 ast_expression *functype = fld_think->expression.next;
3520 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3521 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3522 ast_unref(framenum);
3523 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3527 if (!parser_next(parser)) {
3528 ast_unref(framenum);
3529 ast_delete(thinkfunc);
3533 vec_push(parser->globals, (ast_expression*)thinkfunc);
3534 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3535 nextthink = (ast_expression*)thinkfunc;
3538 nextthink = parse_expression_leave(parser, true, false, false);
3540 ast_unref(framenum);
3541 parseerror(parser, "expected a think-function in [frame,think] notation");
3546 if (!ast_istype(nextthink, ast_value)) {
3547 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3551 if (retval && parser->tok != ']') {
3552 parseerror(parser, "expected closing `]` for [frame,think] notation");
3556 if (retval && !parser_next(parser)) {
3560 if (retval && parser->tok != '{') {
3561 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3566 ast_unref(nextthink);
3567 ast_unref(framenum);
3571 has_frame_think = true;
3574 block = ast_block_new(parser_ctx(parser));
3576 parseerror(parser, "failed to allocate block");
3577 if (has_frame_think) {
3578 ast_unref(nextthink);
3579 ast_unref(framenum);
3584 if (has_frame_think) {
3586 ast_expression *self_frame;
3587 ast_expression *self_nextthink;
3588 ast_expression *self_think;
3589 ast_expression *time_plus_1;
3590 ast_store *store_frame;
3591 ast_store *store_nextthink;
3592 ast_store *store_think;
3594 ctx = parser_ctx(parser);
3595 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3596 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3597 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3599 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3600 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3602 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3603 if (self_frame) ast_delete(self_frame);
3604 if (self_nextthink) ast_delete(self_nextthink);
3605 if (self_think) ast_delete(self_think);
3606 if (time_plus_1) ast_delete(time_plus_1);
3612 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3613 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3614 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3617 ast_delete(self_frame);
3620 if (!store_nextthink) {
3621 ast_delete(self_nextthink);
3625 ast_delete(self_think);
3629 if (store_frame) ast_delete(store_frame);
3630 if (store_nextthink) ast_delete(store_nextthink);
3631 if (store_think) ast_delete(store_think);
3634 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3635 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3636 !ast_block_add_expr(block, (ast_expression*)store_think))
3643 parseerror(parser, "failed to generate code for [frame,think]");
3644 ast_unref(nextthink);
3645 ast_unref(framenum);
3651 parser_enterblock(parser);
3653 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3655 ast_value *param = var->expression.params[parami];
3658 if (param->expression.vtype != TYPE_VECTOR &&
3659 (param->expression.vtype != TYPE_FIELD ||
3660 param->expression.next->expression.vtype != TYPE_VECTOR))
3665 if (!create_vector_members(param, me)) {
3666 ast_block_delete(block);
3670 for (e = 0; e < 3; ++e) {
3671 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3672 ast_block_collect(block, (ast_expression*)me[e]);
3676 func = ast_function_new(ast_ctx(var), var->name, var);
3678 parseerror(parser, "failed to allocate function for `%s`", var->name);
3679 ast_block_delete(block);
3682 vec_push(parser->functions, func);
3684 parser->function = func;
3685 if (!parse_block_into(parser, block)) {
3686 ast_block_delete(block);
3690 vec_push(func->blocks, block);
3692 parser->function = old;
3693 if (!parser_leaveblock(parser))
3695 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3696 parseerror(parser, "internal error: local scopes left");
3700 if (parser->tok == ';')
3701 return parser_next(parser);
3702 else if (opts.standard == COMPILER_QCC)
3703 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3707 vec_pop(parser->functions);
3708 ast_function_delete(func);
3709 var->constval.vfunc = NULL;
3712 (void)!parser_leaveblock(parser);
3713 parser->function = old;
3717 static ast_expression *array_accessor_split(
3722 ast_expression *left,
3723 ast_expression *right
3729 lex_ctx ctx = ast_ctx(array);
3731 if (!left || !right) {
3732 if (left) ast_delete(left);
3733 if (right) ast_delete(right);
3737 cmp = ast_binary_new(ctx, INSTR_LT,
3738 (ast_expression*)index,
3739 (ast_expression*)parser_const_float(parser, middle));
3743 parseerror(parser, "internal error: failed to create comparison for array setter");
3747 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3749 ast_delete(cmp); /* will delete left and right */
3750 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3754 return (ast_expression*)ifthen;
3757 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3759 lex_ctx ctx = ast_ctx(array);
3761 if (from+1 == afterend) {
3762 /* set this value */
3765 ast_array_index *subscript;
3767 int assignop = type_store_instr[value->expression.vtype];
3769 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3770 assignop = INSTR_STORE_V;
3772 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3776 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3778 ast_delete(subscript);
3782 block = ast_block_new(ctx);
3788 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3793 ret = ast_return_new(ctx, NULL);
3799 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3804 return (ast_expression*)block;
3806 ast_expression *left, *right;
3807 size_t diff = afterend - from;
3808 size_t middle = from + diff/2;
3809 left = array_setter_node(parser, array, index, value, from, middle);
3810 right = array_setter_node(parser, array, index, value, middle, afterend);
3811 return array_accessor_split(parser, array, index, middle, left, right);
3815 static ast_expression *array_field_setter_node(
3824 lex_ctx ctx = ast_ctx(array);
3826 if (from+1 == afterend) {
3827 /* set this value */
3830 ast_entfield *entfield;
3831 ast_array_index *subscript;
3833 int assignop = type_storep_instr[value->expression.vtype];
3835 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3836 assignop = INSTR_STOREP_V;
3838 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3842 entfield = ast_entfield_new_force(ctx,
3843 (ast_expression*)entity,
3844 (ast_expression*)subscript,
3845 (ast_expression*)subscript);
3847 ast_delete(subscript);
3851 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3853 ast_delete(entfield);
3857 block = ast_block_new(ctx);
3863 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3868 ret = ast_return_new(ctx, NULL);
3874 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3879 return (ast_expression*)block;
3881 ast_expression *left, *right;
3882 size_t diff = afterend - from;
3883 size_t middle = from + diff/2;
3884 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3885 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3886 return array_accessor_split(parser, array, index, middle, left, right);
3890 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3892 lex_ctx ctx = ast_ctx(array);
3894 if (from+1 == afterend) {
3896 ast_array_index *subscript;
3898 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3902 ret = ast_return_new(ctx, (ast_expression*)subscript);
3904 ast_delete(subscript);
3908 return (ast_expression*)ret;
3910 ast_expression *left, *right;
3911 size_t diff = afterend - from;
3912 size_t middle = from + diff/2;
3913 left = array_getter_node(parser, array, index, from, middle);
3914 right = array_getter_node(parser, array, index, middle, afterend);
3915 return array_accessor_split(parser, array, index, middle, left, right);
3919 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3921 ast_function *func = NULL;
3922 ast_value *fval = NULL;
3923 ast_block *body = NULL;
3925 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3927 parseerror(parser, "failed to create accessor function value");
3931 func = ast_function_new(ast_ctx(array), funcname, fval);
3934 parseerror(parser, "failed to create accessor function node");
3938 body = ast_block_new(ast_ctx(array));
3940 parseerror(parser, "failed to create block for array accessor");
3946 vec_push(func->blocks, body);
3949 vec_push(parser->accessors, fval);
3954 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3956 ast_expression *root = NULL;
3957 ast_value *index = NULL;
3958 ast_value *value = NULL;
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_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3972 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3973 value = ast_value_copy((ast_value*)array->expression.next);
3975 if (!index || !value) {
3976 parseerror(parser, "failed to create locals for array accessor");
3979 (void)!ast_value_set_name(value, "value"); /* not important */
3980 vec_push(fval->expression.params, index);
3981 vec_push(fval->expression.params, value);
3983 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3985 parseerror(parser, "failed to build accessor search tree");
3989 array->setter = fval;
3990 return ast_block_add_expr(func->blocks[0], root);
3992 if (index) ast_delete(index);
3993 if (value) ast_delete(value);
3994 if (root) ast_delete(root);
4000 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4002 ast_expression *root = NULL;
4003 ast_value *entity = NULL;
4004 ast_value *index = NULL;
4005 ast_value *value = NULL;
4009 if (!ast_istype(array->expression.next, ast_value)) {
4010 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4014 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4016 func = fval->constval.vfunc;
4017 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4019 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4020 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4021 value = ast_value_copy((ast_value*)array->expression.next);
4022 if (!entity || !index || !value) {
4023 parseerror(parser, "failed to create locals for array accessor");
4026 (void)!ast_value_set_name(value, "value"); /* not important */
4027 vec_push(fval->expression.params, entity);
4028 vec_push(fval->expression.params, index);
4029 vec_push(fval->expression.params, value);
4031 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4033 parseerror(parser, "failed to build accessor search tree");
4037 array->setter = fval;
4038 return ast_block_add_expr(func->blocks[0], root);
4040 if (entity) ast_delete(entity);
4041 if (index) ast_delete(index);
4042 if (value) ast_delete(value);
4043 if (root) ast_delete(root);
4049 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4051 ast_expression *root = NULL;
4052 ast_value *index = NULL;
4056 /* NOTE: checking array->expression.next rather than elemtype since
4057 * for fields elemtype is a temporary fieldtype.
4059 if (!ast_istype(array->expression.next, ast_value)) {
4060 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4064 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4066 func = fval->constval.vfunc;
4067 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4069 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4072 parseerror(parser, "failed to create locals for array accessor");
4075 vec_push(fval->expression.params, index);
4077 root = array_getter_node(parser, array, index, 0, array->expression.count);
4079 parseerror(parser, "failed to build accessor search tree");
4083 array->getter = fval;
4084 return ast_block_add_expr(func->blocks[0], root);
4086 if (index) ast_delete(index);
4087 if (root) ast_delete(root);
4093 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4094 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4102 bool variadic = false;
4104 ctx = parser_ctx(parser);
4106 /* for the sake of less code we parse-in in this function */
4107 if (!parser_next(parser)) {
4108 parseerror(parser, "expected parameter list");
4114 /* parse variables until we hit a closing paren */
4115 while (parser->tok != ')') {
4117 /* there must be commas between them */
4118 if (parser->tok != ',') {
4119 parseerror(parser, "expected comma or end of parameter list");
4122 if (!parser_next(parser)) {
4123 parseerror(parser, "expected parameter");
4129 if (parser->tok == TOKEN_DOTS) {
4130 /* '...' indicates a varargs function */
4132 if (!parser_next(parser)) {
4133 parseerror(parser, "expected parameter");
4136 if (parser->tok != ')') {
4137 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4143 /* for anything else just parse a typename */
4144 param = parse_typename(parser, NULL, NULL);
4147 vec_push(params, param);
4148 if (param->expression.vtype >= TYPE_VARIANT) {
4149 char tname[1024]; /* typename is reserved in C++ */
4150 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4151 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4157 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4161 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4162 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4165 if (!parser_next(parser)) {
4166 parseerror(parser, "parse error after typename");
4170 /* now turn 'var' into a function type */
4171 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4172 fval->expression.next = (ast_expression*)var;
4174 fval->expression.flags |= AST_FLAG_VARIADIC;
4177 var->expression.params = params;
4184 for (i = 0; i < vec_size(params); ++i)
4185 ast_delete(params[i]);
4190 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4192 ast_expression *cexp;
4193 ast_value *cval, *tmp;
4196 ctx = parser_ctx(parser);
4198 if (!parser_next(parser)) {
4200 parseerror(parser, "expected array-size");
4204 cexp = parse_expression_leave(parser, true, false, false);
4206 if (!cexp || !ast_istype(cexp, ast_value)) {
4210 parseerror(parser, "expected array-size as constant positive integer");
4213 cval = (ast_value*)cexp;
4215 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4216 tmp->expression.next = (ast_expression*)var;
4219 if (cval->expression.vtype == TYPE_INTEGER)
4220 tmp->expression.count = cval->constval.vint;
4221 else if (cval->expression.vtype == TYPE_FLOAT)
4222 tmp->expression.count = cval->constval.vfloat;
4226 parseerror(parser, "array-size must be a positive integer constant");
4231 if (parser->tok != ']') {
4233 parseerror(parser, "expected ']' after array-size");
4236 if (!parser_next(parser)) {
4238 parseerror(parser, "error after parsing array size");
4244 /* Parse a complete typename.
4245 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4246 * but when parsing variables separated by comma
4247 * 'storebase' should point to where the base-type should be kept.
4248 * The base type makes up every bit of type information which comes *before* the
4251 * The following will be parsed in its entirety:
4253 * The 'basetype' in this case is 'void()'
4254 * and if there's a comma after it, say:
4256 * then the type-information 'void()' can be stored in 'storebase'
4258 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4260 ast_value *var, *tmp;
4263 const char *name = NULL;
4264 bool isfield = false;
4265 bool wasarray = false;
4266 size_t morefields = 0;
4268 ctx = parser_ctx(parser);
4270 /* types may start with a dot */
4271 if (parser->tok == '.') {
4273 /* if we parsed a dot we need a typename now */
4274 if (!parser_next(parser)) {
4275 parseerror(parser, "expected typename for field definition");
4279 /* Further dots are handled seperately because they won't be part of the
4282 while (parser->tok == '.') {
4284 if (!parser_next(parser)) {
4285 parseerror(parser, "expected typename for field definition");
4290 if (parser->tok == TOKEN_IDENT)
4291 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4292 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4293 parseerror(parser, "expected typename");
4297 /* generate the basic type value */
4298 if (cached_typedef) {
4299 var = ast_value_copy(cached_typedef);
4300 ast_value_set_name(var, "<type(from_def)>");
4302 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4304 for (; morefields; --morefields) {
4305 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4306 tmp->expression.next = (ast_expression*)var;
4310 /* do not yet turn into a field - remember:
4311 * .void() foo; is a field too
4312 * .void()() foo; is a function
4316 if (!parser_next(parser)) {
4318 parseerror(parser, "parse error after typename");
4322 /* an opening paren now starts the parameter-list of a function
4323 * this is where original-QC has parameter lists.
4324 * We allow a single parameter list here.
4325 * Much like fteqcc we don't allow `float()() x`
4327 if (parser->tok == '(') {
4328 var = parse_parameter_list(parser, var);
4333 /* store the base if requested */
4335 *storebase = ast_value_copy(var);
4337 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4338 tmp->expression.next = (ast_expression*)*storebase;
4343 /* there may be a name now */
4344 if (parser->tok == TOKEN_IDENT) {
4345 name = util_strdup(parser_tokval(parser));
4347 if (!parser_next(parser)) {
4349 parseerror(parser, "error after variable or field declaration");
4354 /* now this may be an array */
4355 if (parser->tok == '[') {
4357 var = parse_arraysize(parser, var);
4362 /* This is the point where we can turn it into a field */
4364 /* turn it into a field if desired */
4365 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4366 tmp->expression.next = (ast_expression*)var;
4370 /* now there may be function parens again */
4371 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4372 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4373 if (parser->tok == '(' && wasarray)
4374 parseerror(parser, "arrays as part of a return type is not supported");
4375 while (parser->tok == '(') {
4376 var = parse_parameter_list(parser, var);
4385 /* finally name it */
4387 if (!ast_value_set_name(var, name)) {
4389 parseerror(parser, "internal error: failed to set name");
4392 /* free the name, ast_value_set_name duplicates */
4399 static bool parse_typedef(parser_t *parser)
4401 ast_value *typevar, *oldtype;
4402 ast_expression *old;
4404 typevar = parse_typename(parser, NULL, NULL);
4409 if ( (old = parser_find_var(parser, typevar->name)) ) {
4410 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4411 " -> `%s` has been declared here: %s:%i",
4412 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4413 ast_delete(typevar);
4417 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4418 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4419 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4420 ast_delete(typevar);
4424 vec_push(parser->_typedefs, typevar);
4425 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4427 if (parser->tok != ';') {
4428 parseerror(parser, "expected semicolon after typedef");
4431 if (!parser_next(parser)) {
4432 parseerror(parser, "parse error after typedef");
4439 static const char *cvq_to_str(int cvq) {
4441 case CV_NONE: return "none";
4442 case CV_VAR: return "`var`";
4443 case CV_CONST: return "`const`";
4444 default: return "<INVALID>";
4448 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4451 if (proto->cvq != var->cvq) {
4452 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4453 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4454 parser->tok == '='))
4456 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4457 "`%s` declared with different qualifiers: %s\n"
4458 " -> previous declaration here: %s:%i uses %s",
4459 var->name, cvq_to_str(var->cvq),
4460 ast_ctx(proto).file, ast_ctx(proto).line,
4461 cvq_to_str(proto->cvq));
4464 av = (var ->expression.flags & AST_FLAG_NORETURN);
4465 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4467 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4468 "`%s` declared with different attributes%s\n"
4469 " -> previous declaration here: %s:%i",
4470 var->name, (av ? ": noreturn" : ""),
4471 ast_ctx(proto).file, ast_ctx(proto).line,
4472 (ao ? ": noreturn" : ""));
4477 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)
4481 ast_expression *old;
4485 ast_value *basetype = NULL;
4487 bool isparam = false;
4488 bool isvector = false;
4489 bool cleanvar = true;
4490 bool wasarray = false;
4494 if (!localblock && is_static)
4495 parseerror(parser, "`static` qualifier is not supported in global scope");
4497 /* get the first complete variable */
4498 var = parse_typename(parser, &basetype, cached_typedef);
4501 ast_delete(basetype);
4509 /* Part 0: finish the type */
4510 if (parser->tok == '(') {
4511 if (opts.standard == COMPILER_QCC)
4512 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4513 var = parse_parameter_list(parser, var);
4519 /* we only allow 1-dimensional arrays */
4520 if (parser->tok == '[') {
4522 var = parse_arraysize(parser, var);
4528 if (parser->tok == '(' && wasarray) {
4529 parseerror(parser, "arrays as part of a return type is not supported");
4530 /* we'll still parse the type completely for now */
4532 /* for functions returning functions */
4533 while (parser->tok == '(') {
4534 if (opts.standard == COMPILER_QCC)
4535 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4536 var = parse_parameter_list(parser, var);
4543 var->cvq = qualifier;
4544 var->expression.flags |= qflags;
4545 if (var->expression.flags & AST_FLAG_DEPRECATED)
4546 var->desc = vstring;
4549 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4550 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4551 * is then filled with the previous definition and the parameter-names replaced.
4553 if (!strcmp(var->name, "nil")) {
4554 if (OPTS_FLAG(UNTYPED_NIL)) {
4555 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4556 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4558 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4561 /* Deal with end_sys_ vars */
4563 if (!strcmp(var->name, "end_sys_globals")) {
4565 parser->crc_globals = vec_size(parser->globals);
4568 else if (!strcmp(var->name, "end_sys_fields")) {
4570 parser->crc_fields = vec_size(parser->fields);
4573 if (was_end && var->expression.vtype == TYPE_FIELD) {
4574 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4575 "global '%s' hint should not be a field",
4576 parser_tokval(parser)))
4583 if (!nofields && var->expression.vtype == TYPE_FIELD)
4585 /* deal with field declarations */
4586 old = parser_find_field(parser, var->name);
4588 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4589 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4598 parseerror(parser, "field `%s` already declared here: %s:%i",
4599 var->name, ast_ctx(old).file, ast_ctx(old).line);
4604 if (opts.standard == COMPILER_QCC &&
4605 (old = parser_find_global(parser, var->name)))
4607 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4608 parseerror(parser, "field `%s` already declared here: %s:%i",
4609 var->name, ast_ctx(old).file, ast_ctx(old).line);
4616 /* deal with other globals */
4617 old = parser_find_global(parser, var->name);
4618 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4620 /* This is a function which had a prototype */
4621 if (!ast_istype(old, ast_value)) {
4622 parseerror(parser, "internal error: prototype is not an ast_value");
4626 proto = (ast_value*)old;
4627 proto->desc = var->desc;
4628 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4629 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4631 ast_ctx(proto).file, ast_ctx(proto).line);
4635 /* we need the new parameter-names */
4636 for (i = 0; i < vec_size(proto->expression.params); ++i)
4637 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4638 if (!parser_check_qualifiers(parser, var, proto)) {
4645 proto->expression.flags |= var->expression.flags;
4653 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4654 "global `%s` already declared here: %s:%i",
4655 var->name, ast_ctx(old).file, ast_ctx(old).line))
4660 proto = (ast_value*)old;
4661 if (!ast_istype(old, ast_value)) {
4662 parseerror(parser, "internal error: not an ast_value");
4667 if (!parser_check_qualifiers(parser, var, proto)) {
4672 proto->expression.flags |= var->expression.flags;
4676 if (opts.standard == COMPILER_QCC &&
4677 (old = parser_find_field(parser, var->name)))
4679 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4680 parseerror(parser, "global `%s` already declared here: %s:%i",
4681 var->name, ast_ctx(old).file, ast_ctx(old).line);
4688 else /* it's not a global */
4690 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4691 if (old && !isparam) {
4692 parseerror(parser, "local `%s` already declared here: %s:%i",
4693 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4697 old = parser_find_local(parser, var->name, 0, &isparam);
4698 if (old && isparam) {
4699 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4700 "local `%s` is shadowing a parameter", var->name))
4702 parseerror(parser, "local `%s` already declared here: %s:%i",
4703 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4707 if (opts.standard != COMPILER_GMQCC) {
4715 /* in a noref section we simply bump the usecount */
4716 if (noref || parser->noref)
4720 * Create the global/local, and deal with vector types.
4723 if (var->expression.vtype == TYPE_VECTOR)
4725 else if (var->expression.vtype == TYPE_FIELD &&
4726 var->expression.next->expression.vtype == TYPE_VECTOR)
4730 if (!create_vector_members(var, me)) {
4737 /* deal with global variables, fields, functions */
4738 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4739 var->isfield = true;
4740 vec_push(parser->fields, (ast_expression*)var);
4741 util_htset(parser->htfields, var->name, var);
4743 for (i = 0; i < 3; ++i) {
4744 vec_push(parser->fields, (ast_expression*)me[i]);
4745 util_htset(parser->htfields, me[i]->name, me[i]);
4750 vec_push(parser->globals, (ast_expression*)var);
4751 util_htset(parser->htglobals, var->name, var);
4753 for (i = 0; i < 3; ++i) {
4754 vec_push(parser->globals, (ast_expression*)me[i]);
4755 util_htset(parser->htglobals, me[i]->name, me[i]);
4761 /* a static adds itself to be generated like any other global
4762 * but is added to the local namespace instead
4764 char *defname = NULL;
4765 size_t prefix_len, ln;
4767 ln = strlen(parser->function->name);
4768 vec_append(defname, ln, parser->function->name);
4770 vec_append(defname, 2, "::");
4771 /* remember the length up to here */
4772 prefix_len = vec_size(defname);
4774 /* Add it to the local scope */
4775 util_htset(vec_last(parser->variables), var->name, (void*)var);
4776 /* now rename the global */
4777 ln = strlen(var->name);
4778 vec_append(defname, ln, var->name);
4779 ast_value_set_name(var, defname);
4781 /* push it to the to-be-generated globals */
4782 vec_push(parser->globals, (ast_expression*)var);
4784 /* same game for the vector members */
4786 for (i = 0; i < 3; ++i) {
4787 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4789 vec_shrinkto(defname, prefix_len);
4790 ln = strlen(me[i]->name);
4791 vec_append(defname, ln, me[i]->name);
4792 ast_member_set_name(me[i], defname);
4794 vec_push(parser->globals, (ast_expression*)me[i]);
4799 vec_push(localblock->locals, var);
4800 parser_addlocal(parser, var->name, (ast_expression*)var);
4802 for (i = 0; i < 3; ++i) {
4803 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4804 ast_block_collect(localblock, (ast_expression*)me[i]);
4810 me[0] = me[1] = me[2] = NULL;
4815 if (var->expression.vtype == TYPE_ARRAY) {
4817 snprintf(name, sizeof(name), "%s##SET", var->name);
4818 if (!parser_create_array_setter(parser, var, name))
4820 snprintf(name, sizeof(name), "%s##GET", var->name);
4821 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4824 else if (!localblock && !nofields &&
4825 var->expression.vtype == TYPE_FIELD &&
4826 var->expression.next->expression.vtype == TYPE_ARRAY)
4829 ast_expression *telem;
4831 ast_value *array = (ast_value*)var->expression.next;
4833 if (!ast_istype(var->expression.next, ast_value)) {
4834 parseerror(parser, "internal error: field element type must be an ast_value");
4838 snprintf(name, sizeof(name), "%s##SETF", var->name);
4839 if (!parser_create_array_field_setter(parser, array, name))
4842 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4843 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4844 tfield->expression.next = telem;
4845 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4846 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4854 if (parser->tok == ';') {
4855 ast_delete(basetype);
4856 if (!parser_next(parser)) {
4857 parseerror(parser, "error after variable declaration");
4863 if (parser->tok == ',')
4867 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4870 parseerror(parser, "missing comma or semicolon while parsing variables");
4874 if (localblock && opts.standard == COMPILER_QCC) {
4875 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4876 "initializing expression turns variable `%s` into a constant in this standard",
4883 if (parser->tok != '{') {
4884 if (parser->tok != '=') {
4885 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4889 if (!parser_next(parser)) {
4890 parseerror(parser, "error parsing initializer");
4894 else if (opts.standard == COMPILER_QCC) {
4895 parseerror(parser, "expected '=' before function body in this standard");
4898 if (parser->tok == '#') {
4899 ast_function *func = NULL;
4902 parseerror(parser, "cannot declare builtins within functions");
4905 if (var->expression.vtype != TYPE_FUNCTION) {
4906 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4909 if (!parser_next(parser)) {
4910 parseerror(parser, "expected builtin number");
4913 if (parser->tok != TOKEN_INTCONST) {
4914 parseerror(parser, "builtin number must be an integer constant");
4917 if (parser_token(parser)->constval.i < 0) {
4918 parseerror(parser, "builtin number must be an integer greater than zero");
4922 if (var->hasvalue) {
4923 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4924 "builtin `%s` has already been defined\n"
4925 " -> previous declaration here: %s:%i",
4926 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4930 func = ast_function_new(ast_ctx(var), var->name, var);
4932 parseerror(parser, "failed to allocate function for `%s`", var->name);
4935 vec_push(parser->functions, func);
4937 func->builtin = -parser_token(parser)->constval.i-1;
4940 if (!parser_next(parser)) {
4941 parseerror(parser, "expected comma or semicolon");
4943 ast_function_delete(func);
4944 var->constval.vfunc = NULL;
4948 else if (parser->tok == '{' || parser->tok == '[')
4951 parseerror(parser, "cannot declare functions within functions");
4956 ast_ctx(proto) = parser_ctx(parser);
4958 if (!parse_function_body(parser, var))
4960 ast_delete(basetype);
4961 for (i = 0; i < vec_size(parser->gotos); ++i)
4962 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4963 vec_free(parser->gotos);
4964 vec_free(parser->labels);
4967 ast_expression *cexp;
4970 cexp = parse_expression_leave(parser, true, false, false);
4975 cval = (ast_value*)cexp;
4976 if (cval != parser->nil &&
4977 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4980 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4984 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4985 qualifier != CV_VAR)
4987 var->cvq = CV_CONST;
4989 if (cval == parser->nil)
4990 var->expression.flags |= AST_FLAG_INITIALIZED;
4993 var->hasvalue = true;
4994 if (cval->expression.vtype == TYPE_STRING)
4995 var->constval.vstring = parser_strdup(cval->constval.vstring);
4996 else if (cval->expression.vtype == TYPE_FIELD)
4997 var->constval.vfield = cval;
4999 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5005 shunt sy = { NULL, NULL };
5008 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5009 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5010 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5011 if (!parser_sy_apply_operator(parser, &sy))
5014 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5015 parseerror(parser, "internal error: leaked operands");
5016 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5026 if (parser->tok == ',') {
5027 if (!parser_next(parser)) {
5028 parseerror(parser, "expected another variable");
5032 if (parser->tok != TOKEN_IDENT) {
5033 parseerror(parser, "expected another variable");
5036 var = ast_value_copy(basetype);
5038 ast_value_set_name(var, parser_tokval(parser));
5039 if (!parser_next(parser)) {
5040 parseerror(parser, "error parsing variable declaration");
5046 if (parser->tok != ';') {
5047 parseerror(parser, "missing semicolon after variables");
5051 if (!parser_next(parser)) {
5052 parseerror(parser, "parse error after variable declaration");
5056 ast_delete(basetype);
5060 if (cleanvar && var)
5062 ast_delete(basetype);
5066 ast_delete(basetype);
5067 if (cleanvar && var)
5069 if (me[0]) ast_member_delete(me[0]);
5070 if (me[1]) ast_member_delete(me[1]);
5071 if (me[2]) ast_member_delete(me[2]);
5075 static bool parser_global_statement(parser_t *parser)
5079 bool is_static = false;
5080 uint32_t qflags = 0;
5081 ast_value *istype = NULL;
5082 char *vstring = NULL;
5084 if (parser->tok == TOKEN_IDENT)
5085 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5087 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5089 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5091 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5093 if (cvq == CV_WRONG)
5095 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5097 else if (parser->tok == TOKEN_KEYWORD)
5099 if (!strcmp(parser_tokval(parser), "typedef")) {
5100 if (!parser_next(parser)) {
5101 parseerror(parser, "expected type definition after 'typedef'");
5104 return parse_typedef(parser);
5106 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5109 else if (parser->tok == '#')
5111 return parse_pragma(parser);
5113 else if (parser->tok == '$')
5115 if (!parser_next(parser)) {
5116 parseerror(parser, "parse error");
5122 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5128 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5130 return util_crc16(old, str, strlen(str));
5133 static void progdefs_crc_file(const char *str)
5135 /* write to progdefs.h here */
5139 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5141 old = progdefs_crc_sum(old, str);
5142 progdefs_crc_file(str);
5146 static void generate_checksum(parser_t *parser)
5148 uint16_t crc = 0xFFFF;
5152 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5153 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5155 progdefs_crc_file("\tint\tpad;\n");
5156 progdefs_crc_file("\tint\tofs_return[3];\n");
5157 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5158 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5159 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5160 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5161 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5162 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5163 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5164 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5166 for (i = 0; i < parser->crc_globals; ++i) {
5167 if (!ast_istype(parser->globals[i], ast_value))
5169 value = (ast_value*)(parser->globals[i]);
5170 switch (value->expression.vtype) {
5171 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5172 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5173 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5174 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5176 crc = progdefs_crc_both(crc, "\tint\t");
5179 crc = progdefs_crc_both(crc, value->name);
5180 crc = progdefs_crc_both(crc, ";\n");
5182 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5183 for (i = 0; i < parser->crc_fields; ++i) {
5184 if (!ast_istype(parser->fields[i], ast_value))
5186 value = (ast_value*)(parser->fields[i]);
5187 switch (value->expression.next->expression.vtype) {
5188 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5189 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5190 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5191 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5193 crc = progdefs_crc_both(crc, "\tint\t");
5196 crc = progdefs_crc_both(crc, value->name);
5197 crc = progdefs_crc_both(crc, ";\n");
5199 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5204 static parser_t *parser;
5211 parser = (parser_t*)mem_a(sizeof(parser_t));
5215 memset(parser, 0, sizeof(*parser));
5217 for (i = 0; i < operator_count; ++i) {
5218 if (operators[i].id == opid1('=')) {
5219 parser->assign_op = operators+i;
5223 if (!parser->assign_op) {
5224 printf("internal error: initializing parser: failed to find assign operator\n");
5229 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5230 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5231 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5232 vec_push(parser->_blocktypedefs, 0);
5234 empty_ctx.file = "<internal>";
5236 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5237 parser->nil->cvq = CV_CONST;
5238 if (OPTS_FLAG(UNTYPED_NIL))
5239 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5243 bool parser_compile()
5245 /* initial lexer/parser state */
5246 parser->lex->flags.noops = true;
5248 if (parser_next(parser))
5250 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5252 if (!parser_global_statement(parser)) {
5253 if (parser->tok == TOKEN_EOF)
5254 parseerror(parser, "unexpected eof");
5255 else if (compile_errors)
5256 parseerror(parser, "there have been errors, bailing out");
5257 lex_close(parser->lex);
5263 parseerror(parser, "parse error");
5264 lex_close(parser->lex);
5269 lex_close(parser->lex);
5272 return !compile_errors;
5275 bool parser_compile_file(const char *filename)
5277 parser->lex = lex_open(filename);
5279 con_err("failed to open file \"%s\"\n", filename);
5282 return parser_compile();
5285 bool parser_compile_string(const char *name, const char *str, size_t len)
5287 parser->lex = lex_open_string(str, len, name);
5289 con_err("failed to create lexer for string \"%s\"\n", name);
5292 return parser_compile();
5295 void parser_cleanup()
5298 for (i = 0; i < vec_size(parser->accessors); ++i) {
5299 ast_delete(parser->accessors[i]->constval.vfunc);
5300 parser->accessors[i]->constval.vfunc = NULL;
5301 ast_delete(parser->accessors[i]);
5303 for (i = 0; i < vec_size(parser->functions); ++i) {
5304 ast_delete(parser->functions[i]);
5306 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5307 ast_delete(parser->imm_vector[i]);
5309 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5310 ast_delete(parser->imm_string[i]);
5312 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5313 ast_delete(parser->imm_float[i]);
5315 for (i = 0; i < vec_size(parser->fields); ++i) {
5316 ast_delete(parser->fields[i]);
5318 for (i = 0; i < vec_size(parser->globals); ++i) {
5319 ast_delete(parser->globals[i]);
5321 vec_free(parser->accessors);
5322 vec_free(parser->functions);
5323 vec_free(parser->imm_vector);
5324 vec_free(parser->imm_string);
5325 vec_free(parser->imm_float);
5326 vec_free(parser->globals);
5327 vec_free(parser->fields);
5329 for (i = 0; i < vec_size(parser->variables); ++i)
5330 util_htdel(parser->variables[i]);
5331 vec_free(parser->variables);
5332 vec_free(parser->_blocklocals);
5333 vec_free(parser->_locals);
5335 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5336 ast_delete(parser->_typedefs[i]);
5337 vec_free(parser->_typedefs);
5338 for (i = 0; i < vec_size(parser->typedefs); ++i)
5339 util_htdel(parser->typedefs[i]);
5340 vec_free(parser->typedefs);
5341 vec_free(parser->_blocktypedefs);
5343 vec_free(parser->_block_ctx);
5345 vec_free(parser->labels);
5346 vec_free(parser->gotos);
5347 vec_free(parser->breaks);
5348 vec_free(parser->continues);
5350 ast_value_delete(parser->nil);
5355 bool parser_finish(const char *output)
5361 if (compile_errors) {
5362 con_out("*** there were compile errors\n");
5366 ir = ir_builder_new("gmqcc_out");
5368 con_out("failed to allocate builder\n");
5372 for (i = 0; i < vec_size(parser->fields); ++i) {
5375 if (!ast_istype(parser->fields[i], ast_value))
5377 field = (ast_value*)parser->fields[i];
5378 hasvalue = field->hasvalue;
5379 field->hasvalue = false;
5380 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5381 con_out("failed to generate field %s\n", field->name);
5382 ir_builder_delete(ir);
5387 ast_expression *subtype;
5388 field->hasvalue = true;
5389 subtype = field->expression.next;
5390 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5391 if (subtype->expression.vtype == TYPE_FIELD)
5392 ifld->fieldtype = subtype->expression.next->expression.vtype;
5393 else if (subtype->expression.vtype == TYPE_FUNCTION)
5394 ifld->outtype = subtype->expression.next->expression.vtype;
5395 (void)!ir_value_set_field(field->ir_v, ifld);
5398 for (i = 0; i < vec_size(parser->globals); ++i) {
5400 if (!ast_istype(parser->globals[i], ast_value))
5402 asvalue = (ast_value*)(parser->globals[i]);
5403 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5404 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5405 "unused global: `%s`", asvalue->name);
5407 if (!ast_global_codegen(asvalue, ir, false)) {
5408 con_out("failed to generate global %s\n", asvalue->name);
5409 ir_builder_delete(ir);
5413 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5414 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5415 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5416 ir_builder_delete(ir);
5420 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5421 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5422 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5423 ir_builder_delete(ir);
5427 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5428 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5429 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5430 ir_builder_delete(ir);
5434 for (i = 0; i < vec_size(parser->globals); ++i) {
5436 if (!ast_istype(parser->globals[i], ast_value))
5438 asvalue = (ast_value*)(parser->globals[i]);
5439 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5441 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5442 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5443 "uninitialized constant: `%s`",
5445 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5446 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5447 "uninitialized global: `%s`",
5450 if (!ast_generate_accessors(asvalue, ir)) {
5451 ir_builder_delete(ir);
5455 for (i = 0; i < vec_size(parser->fields); ++i) {
5457 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5459 if (!ast_istype((ast_expression*)asvalue, ast_value))
5461 if (asvalue->expression.vtype != TYPE_ARRAY)
5463 if (!ast_generate_accessors(asvalue, ir)) {
5464 ir_builder_delete(ir);
5468 for (i = 0; i < vec_size(parser->functions); ++i) {
5469 if (!ast_function_codegen(parser->functions[i], ir)) {
5470 con_out("failed to generate function %s\n", parser->functions[i]->name);
5471 ir_builder_delete(ir);
5476 ir_builder_dump(ir, con_out);
5477 for (i = 0; i < vec_size(parser->functions); ++i) {
5478 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5479 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5480 ir_builder_delete(ir);
5485 if (compile_Werrors) {
5486 con_out("*** there were warnings treated as errors\n");
5487 compile_show_werrors();
5493 ir_builder_dump(ir, con_out);
5495 generate_checksum(parser);
5497 if (!ir_builder_generate(ir, output)) {
5498 con_out("*** failed to generate output file\n");
5499 ir_builder_delete(ir);
5504 ir_builder_delete(ir);