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);
115 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
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) {
308 for(i = 0; i < vec_size(parser->labels); i++)
309 if (!strcmp(parser->labels[i]->name, name))
310 return (ast_expression*)parser->labels[i];
314 static ast_expression* parser_find_global(parser_t *parser, const char *name)
316 return (ast_expression*)util_htget(parser->htglobals, name);
319 static ast_expression* parser_find_param(parser_t *parser, const char *name)
323 if (!parser->function)
325 fun = parser->function->vtype;
326 for (i = 0; i < vec_size(fun->expression.params); ++i) {
327 if (!strcmp(fun->expression.params[i]->name, name))
328 return (ast_expression*)(fun->expression.params[i]);
333 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
338 hash = util_hthash(parser->htglobals, name);
341 for (i = vec_size(parser->variables); i > upto;) {
343 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
347 return parser_find_param(parser, name);
350 static ast_expression* parser_find_var(parser_t *parser, const char *name)
354 v = parser_find_local(parser, name, 0, &dummy);
355 if (!v) v = parser_find_global(parser, name);
359 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
363 hash = util_hthash(parser->typedefs[0], name);
365 for (i = vec_size(parser->typedefs); i > upto;) {
367 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
375 size_t etype; /* 0 = expression, others are operators */
379 ast_block *block; /* for commas and function calls */
388 #define SY_PAREN_EXPR '('
389 #define SY_PAREN_FUNC 'f'
390 #define SY_PAREN_INDEX '['
391 #define SY_PAREN_TERNARY '?'
393 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
404 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
408 e.out = (ast_expression*)v;
415 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
417 e.etype = 1 + (op - operators);
426 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
438 # define DEBUGSHUNTDO(x) x
440 # define DEBUGSHUNTDO(x)
443 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
444 * so we need to rotate it to become ent.(foo[n]).
446 static bool rotate_entfield_array_index_nodes(ast_expression **out)
448 ast_array_index *index;
449 ast_entfield *entfield;
453 ast_expression *entity;
455 lex_ctx ctx = ast_ctx(*out);
457 if (!ast_istype(*out, ast_array_index))
459 index = (ast_array_index*)*out;
461 if (!ast_istype(index->array, ast_entfield))
463 entfield = (ast_entfield*)index->array;
465 if (!ast_istype(entfield->field, ast_value))
467 field = (ast_value*)entfield->field;
470 entity = entfield->entity;
474 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
475 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
476 *out = (ast_expression*)entfield;
481 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
483 switch (v->expression.vtype) {
485 return !!v->constval.vfloat;
487 return !!v->constval.vint;
489 if (OPTS_FLAG(CORRECT_LOGIC))
490 return v->constval.vvec.x &&
491 v->constval.vvec.y &&
494 return !!(v->constval.vvec.x);
496 if (!v->constval.vstring)
498 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
500 return !!v->constval.vstring[0];
502 compile_error(ctx, "internal error: immediate_is_true on invalid type");
503 return !!v->constval.vfunc;
507 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
511 ast_expression *out = NULL;
512 ast_expression *exprs[3];
513 ast_block *blocks[3];
514 ast_value *asvalue[3];
515 ast_binstore *asbinstore;
516 size_t i, assignop, addop, subop;
517 qcint generated_op = 0;
522 if (!vec_size(sy->ops)) {
523 parseerror(parser, "internal error: missing operator");
527 if (vec_last(sy->ops).paren) {
528 parseerror(parser, "unmatched parenthesis");
532 op = &operators[vec_last(sy->ops).etype - 1];
533 ctx = vec_last(sy->ops).ctx;
535 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
537 if (vec_size(sy->out) < op->operands) {
538 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
539 op->op, (int)op->id);
543 vec_shrinkby(sy->ops, 1);
545 /* op(:?) has no input and no output */
549 vec_shrinkby(sy->out, op->operands);
550 for (i = 0; i < op->operands; ++i) {
551 exprs[i] = sy->out[vec_size(sy->out)+i].out;
552 blocks[i] = sy->out[vec_size(sy->out)+i].block;
553 asvalue[i] = (ast_value*)exprs[i];
556 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
557 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
561 #define NotSameType(T) \
562 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
563 exprs[0]->expression.vtype != T)
564 #define CanConstFold1(A) \
565 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
566 (A)->expression.vtype != TYPE_FUNCTION)
567 #define CanConstFold(A, B) \
568 (CanConstFold1(A) && CanConstFold1(B))
569 #define ConstV(i) (asvalue[(i)]->constval.vvec)
570 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
571 #define ConstS(i) (asvalue[(i)]->constval.vstring)
575 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
579 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
580 if (exprs[1]->expression.vtype != TYPE_FIELD) {
581 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
584 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
586 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
587 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
591 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
597 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
598 !(exprs[0]->expression.vtype == TYPE_FIELD &&
599 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
601 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
602 parseerror(parser, "cannot index value of type %s", ty1);
605 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
606 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
607 parseerror(parser, "index must be of type float, not %s", ty1);
610 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
611 if (rotate_entfield_array_index_nodes(&out))
614 /* This is not broken in fteqcc anymore */
615 if (opts.standard != COMPILER_GMQCC) {
616 /* this error doesn't need to make us bail out */
617 (void)!parsewarning(parser, WARN_EXTENSIONS,
618 "accessing array-field members of an entity without parenthesis\n"
619 " -> this is an extension from -std=gmqcc");
627 if (!ast_block_add_expr(blocks[0], exprs[1]))
630 blocks[0] = ast_block_new(ctx);
631 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
632 !ast_block_add_expr(blocks[0], exprs[1]))
637 if (!ast_block_set_type(blocks[0], exprs[1]))
640 vec_push(sy->out, syblock(ctx, blocks[0]));
647 switch (exprs[0]->expression.vtype) {
649 if (CanConstFold1(exprs[0]))
650 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
652 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
653 (ast_expression*)parser_const_float_0(parser),
657 if (CanConstFold1(exprs[0]))
658 out = (ast_expression*)parser_const_vector_f(parser,
659 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
661 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
662 (ast_expression*)parser_const_vector_0(parser),
666 parseerror(parser, "invalid types used in expression: cannot negate type %s",
667 type_name[exprs[0]->expression.vtype]);
673 switch (exprs[0]->expression.vtype) {
675 if (CanConstFold1(exprs[0]))
676 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
678 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
681 if (CanConstFold1(exprs[0]))
682 out = (ast_expression*)parser_const_float(parser,
683 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
685 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
688 if (CanConstFold1(exprs[0])) {
689 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
690 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
692 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
694 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
695 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
697 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
700 /* we don't constant-fold NOT for these types */
702 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
705 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
708 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
709 type_name[exprs[0]->expression.vtype]);
715 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
716 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
718 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
719 type_name[exprs[0]->expression.vtype],
720 type_name[exprs[1]->expression.vtype]);
723 switch (exprs[0]->expression.vtype) {
725 if (CanConstFold(exprs[0], exprs[1]))
727 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
730 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
733 if (CanConstFold(exprs[0], exprs[1]))
734 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
736 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
739 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
740 type_name[exprs[0]->expression.vtype],
741 type_name[exprs[1]->expression.vtype]);
746 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
747 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
749 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
750 type_name[exprs[1]->expression.vtype],
751 type_name[exprs[0]->expression.vtype]);
754 switch (exprs[0]->expression.vtype) {
756 if (CanConstFold(exprs[0], exprs[1]))
757 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
759 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
762 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
765 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
768 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
769 type_name[exprs[1]->expression.vtype],
770 type_name[exprs[0]->expression.vtype]);
775 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
776 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
777 exprs[1]->expression.vtype == TYPE_FLOAT) &&
778 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
779 exprs[0]->expression.vtype == TYPE_FLOAT)
782 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
783 type_name[exprs[1]->expression.vtype],
784 type_name[exprs[0]->expression.vtype]);
787 switch (exprs[0]->expression.vtype) {
789 if (exprs[1]->expression.vtype == TYPE_VECTOR)
791 if (CanConstFold(exprs[0], exprs[1]))
792 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
794 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
798 if (CanConstFold(exprs[0], exprs[1]))
799 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
801 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
805 if (exprs[1]->expression.vtype == TYPE_FLOAT)
807 if (CanConstFold(exprs[0], exprs[1]))
808 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
810 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
814 if (CanConstFold(exprs[0], exprs[1]))
815 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
816 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
817 vector vec = ConstV(0);
818 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
819 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
820 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
821 out->expression.node.keep = false;
822 ((ast_member*)out)->rvalue = true;
824 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
826 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
827 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
828 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
829 out->expression.node.keep = false;
830 ((ast_member*)out)->rvalue = true;
832 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
834 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
835 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
836 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
837 out->expression.node.keep = false;
838 ((ast_member*)out)->rvalue = true;
840 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
843 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
845 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
846 vector vec = ConstV(1);
847 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
848 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
849 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
850 out->expression.node.keep = false;
851 ((ast_member*)out)->rvalue = true;
853 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
855 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
856 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
857 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
858 out->expression.node.keep = false;
859 ((ast_member*)out)->rvalue = true;
861 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
863 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
864 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
865 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
866 out->expression.node.keep = false;
867 ((ast_member*)out)->rvalue = true;
869 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
872 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
875 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
879 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
880 type_name[exprs[1]->expression.vtype],
881 type_name[exprs[0]->expression.vtype]);
886 if (NotSameType(TYPE_FLOAT)) {
887 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
888 type_name[exprs[0]->expression.vtype],
889 type_name[exprs[1]->expression.vtype]);
892 if (CanConstFold(exprs[0], exprs[1]))
893 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
895 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
899 parseerror(parser, "qc does not have a modulo operator");
903 if (NotSameType(TYPE_FLOAT)) {
904 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
905 type_name[exprs[0]->expression.vtype],
906 type_name[exprs[1]->expression.vtype]);
909 if (CanConstFold(exprs[0], exprs[1]))
910 out = (ast_expression*)parser_const_float(parser,
911 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
912 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
914 out = (ast_expression*)ast_binary_new(ctx,
915 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
919 parseerror(parser, "TODO: bitxor");
924 case opid3('<','<','='):
925 case opid3('>','>','='):
926 parseerror(parser, "TODO: shifts");
930 generated_op += 1; /* INSTR_OR */
932 generated_op += INSTR_AND;
934 if (NotSameType(TYPE_FLOAT)) {
935 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
936 type_name[exprs[0]->expression.vtype],
937 type_name[exprs[1]->expression.vtype]);
938 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
939 parseerror(parser, "TODO: optional early out");
943 if (CanConstFold(exprs[0], exprs[1]))
945 if (OPTS_FLAG(PERL_LOGIC)) {
946 if (immediate_is_true(ctx, asvalue[0]))
950 out = (ast_expression*)parser_const_float(parser,
951 ( (generated_op == INSTR_OR)
952 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
953 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
958 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
959 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
960 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
961 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
964 for (i = 0; i < 2; ++i) {
965 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
966 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
968 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
970 exprs[i] = out; out = NULL;
971 if (OPTS_FLAG(PERL_LOGIC)) {
972 /* here we want to keep the right expressions' type */
976 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
977 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
979 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
981 exprs[i] = out; out = NULL;
982 if (OPTS_FLAG(PERL_LOGIC)) {
983 /* here we want to keep the right expressions' type */
988 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
993 if (vec_last(parser->pot) != POT_TERNARY2) {
994 parseerror(parser, "mismatched parenthesis/ternary");
997 vec_pop(parser->pot);
998 if (!ast_compare_type(exprs[1], exprs[2])) {
999 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1000 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1001 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1004 if (CanConstFold1(exprs[0]))
1005 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1007 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1011 generated_op += 1; /* INSTR_GT */
1013 generated_op += 1; /* INSTR_LT */
1014 case opid2('>', '='):
1015 generated_op += 1; /* INSTR_GE */
1016 case opid2('<', '='):
1017 generated_op += INSTR_LE;
1018 if (NotSameType(TYPE_FLOAT)) {
1019 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1020 type_name[exprs[0]->expression.vtype],
1021 type_name[exprs[1]->expression.vtype]);
1024 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1026 case opid2('!', '='):
1027 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1028 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1029 type_name[exprs[0]->expression.vtype],
1030 type_name[exprs[1]->expression.vtype]);
1033 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1035 case opid2('=', '='):
1036 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1037 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1038 type_name[exprs[0]->expression.vtype],
1039 type_name[exprs[1]->expression.vtype]);
1042 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1046 if (ast_istype(exprs[0], ast_entfield)) {
1047 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1048 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1049 exprs[0]->expression.vtype == TYPE_FIELD &&
1050 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1052 assignop = type_storep_instr[TYPE_VECTOR];
1055 assignop = type_storep_instr[exprs[0]->expression.vtype];
1056 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1058 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1059 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1060 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1061 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1062 exprs[1]->expression.vtype == TYPE_FUNCTION)
1064 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1065 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1068 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1073 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1074 exprs[0]->expression.vtype == TYPE_FIELD &&
1075 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1077 assignop = type_store_instr[TYPE_VECTOR];
1080 assignop = type_store_instr[exprs[0]->expression.vtype];
1083 if (assignop == AINSTR_END) {
1084 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1085 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1086 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1088 else if (!ast_compare_type(exprs[0], exprs[1]))
1090 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1091 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1092 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1093 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1094 exprs[1]->expression.vtype == TYPE_FUNCTION)
1096 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1097 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1100 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1103 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1104 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1106 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1108 case opid3('+','+','P'):
1109 case opid3('-','-','P'):
1111 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1112 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1113 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1116 if (op->id == opid3('+','+','P'))
1117 addop = INSTR_ADD_F;
1119 addop = INSTR_SUB_F;
1120 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1121 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1123 if (ast_istype(exprs[0], ast_entfield)) {
1124 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1126 (ast_expression*)parser_const_float_1(parser));
1128 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1130 (ast_expression*)parser_const_float_1(parser));
1133 case opid3('S','+','+'):
1134 case opid3('S','-','-'):
1136 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1137 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1138 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1141 if (op->id == opid3('S','+','+')) {
1142 addop = INSTR_ADD_F;
1143 subop = INSTR_SUB_F;
1145 addop = INSTR_SUB_F;
1146 subop = INSTR_ADD_F;
1148 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1149 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1151 if (ast_istype(exprs[0], ast_entfield)) {
1152 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1154 (ast_expression*)parser_const_float_1(parser));
1156 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1158 (ast_expression*)parser_const_float_1(parser));
1162 out = (ast_expression*)ast_binary_new(ctx, subop,
1164 (ast_expression*)parser_const_float_1(parser));
1166 case opid2('+','='):
1167 case opid2('-','='):
1168 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1169 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1171 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1172 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1173 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1177 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1178 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1180 if (ast_istype(exprs[0], ast_entfield))
1181 assignop = type_storep_instr[exprs[0]->expression.vtype];
1183 assignop = type_store_instr[exprs[0]->expression.vtype];
1184 switch (exprs[0]->expression.vtype) {
1186 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1187 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1188 exprs[0], exprs[1]);
1191 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1192 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1193 exprs[0], exprs[1]);
1196 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1197 type_name[exprs[0]->expression.vtype],
1198 type_name[exprs[1]->expression.vtype]);
1202 case opid2('*','='):
1203 case opid2('/','='):
1204 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1205 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1206 exprs[0]->expression.vtype == TYPE_VECTOR))
1208 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1209 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1210 parseerror(parser, "invalid types used in expression: %s and %s",
1214 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1215 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1217 if (ast_istype(exprs[0], ast_entfield))
1218 assignop = type_storep_instr[exprs[0]->expression.vtype];
1220 assignop = type_store_instr[exprs[0]->expression.vtype];
1221 switch (exprs[0]->expression.vtype) {
1223 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1224 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1225 exprs[0], exprs[1]);
1228 if (op->id == opid2('*','=')) {
1229 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1230 exprs[0], exprs[1]);
1232 /* there's no DIV_VF */
1233 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1234 (ast_expression*)parser_const_float_1(parser),
1238 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1243 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1244 type_name[exprs[0]->expression.vtype],
1245 type_name[exprs[1]->expression.vtype]);
1249 case opid2('&','='):
1250 case opid2('|','='):
1251 if (NotSameType(TYPE_FLOAT)) {
1252 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1253 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1254 parseerror(parser, "invalid types used in expression: %s and %s",
1258 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1259 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1261 if (ast_istype(exprs[0], ast_entfield))
1262 assignop = type_storep_instr[exprs[0]->expression.vtype];
1264 assignop = type_store_instr[exprs[0]->expression.vtype];
1265 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1266 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1267 exprs[0], exprs[1]);
1269 case opid3('&','~','='):
1270 /* This is like: a &= ~(b);
1271 * But QC has no bitwise-not, so we implement it as
1274 if (NotSameType(TYPE_FLOAT)) {
1275 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1276 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1277 parseerror(parser, "invalid types used in expression: %s and %s",
1281 if (ast_istype(exprs[0], ast_entfield))
1282 assignop = type_storep_instr[exprs[0]->expression.vtype];
1284 assignop = type_store_instr[exprs[0]->expression.vtype];
1285 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1288 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1289 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1291 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1292 asbinstore->keep_dest = true;
1293 out = (ast_expression*)asbinstore;
1299 parseerror(parser, "failed to apply operand %s", op->op);
1303 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1304 vec_push(sy->out, syexp(ctx, out));
1308 static bool parser_close_call(parser_t *parser, shunt *sy)
1310 /* was a function call */
1311 ast_expression *fun;
1317 vec_shrinkby(sy->ops, 1);
1318 fid = sy->ops[vec_size(sy->ops)].off;
1320 /* out[fid] is the function
1321 * everything above is parameters...
1322 * 0 params = nothing
1323 * 1 params = ast_expression
1327 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1328 parseerror(parser, "internal error: function call needs function and parameter list...");
1332 fun = sy->out[fid].out;
1334 if (fun == intrinsic_debug_typestring) {
1336 if (fid+2 != vec_size(sy->out) ||
1337 vec_last(sy->out).block)
1339 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1342 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1343 ast_unref(vec_last(sy->out).out);
1344 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1345 (ast_expression*)parser_const_string(parser, ty, false));
1346 vec_shrinkby(sy->out, 1);
1350 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1352 parseerror(parser, "internal error: failed to create ast_call node");
1356 if (fid+1 == vec_size(sy->out)) {
1359 } else if (fid+2 == vec_size(sy->out)) {
1361 vec_shrinkby(sy->out, 1);
1362 params = sy->out[vec_size(sy->out)].block;
1366 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1368 paramcount = vec_size(params->exprs);
1369 call->params = params->exprs;
1370 params->exprs = NULL;
1373 (void)!ast_call_check_types(call);
1375 parseerror(parser, "invalid function call");
1379 /* overwrite fid, the function, with a call */
1380 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1382 if (fun->expression.vtype != TYPE_FUNCTION) {
1383 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1387 if (!fun->expression.next) {
1388 parseerror(parser, "could not determine function return type");
1391 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1393 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1395 return !parsewarning(parser, WARN_DEPRECATED,
1396 "call to function (which is marked deprecated)\n",
1397 "-> it has been declared here: %s:%i",
1398 ast_ctx(fun).file, ast_ctx(fun).line);
1401 return !parsewarning(parser, WARN_DEPRECATED,
1402 "call to `%s` (which is marked deprecated)\n"
1403 "-> `%s` declared here: %s:%i",
1404 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1406 return !parsewarning(parser, WARN_DEPRECATED,
1407 "call to `%s` (deprecated: %s)\n"
1408 "-> `%s` declared here: %s:%i",
1409 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1413 if (vec_size(fun->expression.params) != paramcount &&
1414 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1415 vec_size(fun->expression.params) < paramcount))
1417 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1419 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1420 "too %s parameters for call to %s: expected %i, got %i\n"
1421 " -> `%s` has been declared here: %s:%i",
1422 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1423 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1425 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1426 "too %s parameters for function call: expected %i, got %i\n"
1427 " -> it has been declared here: %s:%i",
1428 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1429 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1436 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1438 if (!vec_size(sy->ops)) {
1439 parseerror(parser, "unmatched closing paren");
1442 /* this would for bit a + (x) because there are no operators inside (x)
1443 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1444 parseerror(parser, "empty parenthesis expression");
1448 while (vec_size(sy->ops)) {
1449 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1450 if (!parser_close_call(parser, sy))
1454 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1455 vec_shrinkby(sy->ops, 1);
1456 return !functions_only;
1458 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1461 /* pop off the parenthesis */
1462 vec_shrinkby(sy->ops, 1);
1463 /* then apply the index operator */
1464 if (!parser_sy_apply_operator(parser, sy))
1468 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1471 if (vec_last(parser->pot) != POT_TERNARY1) {
1472 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1475 vec_last(parser->pot) = POT_TERNARY2;
1476 /* pop off the parenthesis */
1477 vec_shrinkby(sy->ops, 1);
1480 if (!parser_sy_apply_operator(parser, sy))
1486 static void parser_reclassify_token(parser_t *parser)
1489 for (i = 0; i < operator_count; ++i) {
1490 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1491 parser->tok = TOKEN_OPERATOR;
1497 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue)
1499 ast_expression *expr = NULL;
1501 bool wantop = false;
1502 bool gotmemberof = false;
1503 /* only warn once about an assignment in a truth value because the current code
1504 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1506 bool warn_truthvalue = true;
1508 /* count the parens because an if starts with one, so the
1509 * end of a condition is an unmatched closing paren
1517 parser->lex->flags.noops = false;
1519 parser_reclassify_token(parser);
1524 gotmemberof = false;
1526 parser->memberof = 0;
1528 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1529 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1531 /* a translatable string */
1535 parseerror(parser, "expected operator or end of statement, got constant");
1539 parser->lex->flags.noops = true;
1540 if (!parser_next(parser) || parser->tok != '(') {
1541 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1544 parser->lex->flags.noops = false;
1545 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1546 parseerror(parser, "expected a constant string in translatable-string extension");
1549 val = parser_const_string(parser, parser_tokval(parser), true);
1553 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1554 DEBUGSHUNTDO(con_out("push string\n"));
1556 if (!parser_next(parser) || parser->tok != ')') {
1557 parseerror(parser, "expected closing paren after translatable string");
1561 else if (parser->tok == TOKEN_IDENT)
1563 ast_expression *var;
1565 parseerror(parser, "expected operator or end of statement");
1570 if (opts.standard == COMPILER_GMQCC)
1572 if (parser->memberof == TYPE_ENTITY) {
1573 /* still get vars first since there could be a fieldpointer */
1574 var = parser_find_var(parser, parser_tokval(parser));
1576 var = parser_find_field(parser, parser_tokval(parser));
1578 else if (parser->memberof == TYPE_VECTOR)
1580 parseerror(parser, "TODO: implement effective vector member access");
1583 else if (parser->memberof) {
1584 parseerror(parser, "namespace for member not found");
1587 else if (!(var = parser_find_var(parser, parser_tokval(parser))))
1588 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1590 var = parser_find_var(parser, parser_tokval(parser));
1592 var = parser_find_field(parser, parser_tokval(parser));
1594 var = parser_find_label(parser, parser_tokval(parser));
1598 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1599 var = (ast_expression*)intrinsic_debug_typestring;
1603 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1609 if (ast_istype(var, ast_value)) {
1610 ((ast_value*)var)->uses++;
1612 else if (ast_istype(var, ast_member)) {
1613 ast_member *mem = (ast_member*)var;
1614 if (ast_istype(mem->owner, ast_value))
1615 ((ast_value*)(mem->owner))->uses++;
1618 vec_push(sy.out, syexp(parser_ctx(parser), var));
1619 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1621 else if (parser->tok == TOKEN_FLOATCONST) {
1624 parseerror(parser, "expected operator or end of statement, got constant");
1628 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1631 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1632 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1634 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1637 parseerror(parser, "expected operator or end of statement, got constant");
1641 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1644 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1645 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1647 else if (parser->tok == TOKEN_STRINGCONST) {
1650 parseerror(parser, "expected operator or end of statement, got constant");
1654 val = parser_const_string(parser, parser_tokval(parser), false);
1657 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1658 DEBUGSHUNTDO(con_out("push string\n"));
1660 else if (parser->tok == TOKEN_VECTORCONST) {
1663 parseerror(parser, "expected operator or end of statement, got constant");
1667 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1670 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1671 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1672 parser_token(parser)->constval.v.x,
1673 parser_token(parser)->constval.v.y,
1674 parser_token(parser)->constval.v.z));
1676 else if (parser->tok == '(') {
1677 parseerror(parser, "internal error: '(' should be classified as operator");
1680 else if (parser->tok == '[') {
1681 parseerror(parser, "internal error: '[' should be classified as operator");
1684 else if (parser->tok == ')') {
1686 DEBUGSHUNTDO(con_out("do[op] )\n"));
1690 /* we do expect an operator next */
1691 /* closing an opening paren */
1692 if (!parser_close_paren(parser, &sy, false))
1694 if (vec_last(parser->pot) != POT_PAREN) {
1695 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1698 vec_pop(parser->pot);
1700 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1704 /* allowed for function calls */
1705 if (!parser_close_paren(parser, &sy, true))
1707 if (vec_last(parser->pot) != POT_PAREN) {
1708 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1711 vec_pop(parser->pot);
1715 else if (parser->tok == ']') {
1717 parseerror(parser, "operand expected");
1721 if (!parser_close_paren(parser, &sy, false))
1723 if (vec_last(parser->pot) != POT_PAREN) {
1724 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1727 vec_pop(parser->pot);
1730 else if (parser->tok == TOKEN_TYPENAME) {
1731 parseerror(parser, "unexpected typename");
1734 else if (parser->tok != TOKEN_OPERATOR) {
1736 parseerror(parser, "expected operator or end of statement");
1743 /* classify the operator */
1744 const oper_info *op;
1745 const oper_info *olast = NULL;
1747 for (o = 0; o < operator_count; ++o) {
1748 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1749 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1750 !strcmp(parser_tokval(parser), operators[o].op))
1755 if (o == operator_count) {
1756 /* no operator found... must be the end of the statement */
1759 /* found an operator */
1762 /* when declaring variables, a comma starts a new variable */
1763 if (op->id == opid1(',') && !parens && stopatcomma) {
1764 /* fixup the token */
1769 /* a colon without a pervious question mark cannot be a ternary */
1770 if (!ternaries && op->id == opid2(':','?')) {
1775 if (op->id == opid1(',')) {
1776 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1777 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1781 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1782 olast = &operators[vec_last(sy.ops).etype-1];
1784 #define IsAssignOp(x) (\
1785 (x) == opid1('=') || \
1786 (x) == opid2('+','=') || \
1787 (x) == opid2('-','=') || \
1788 (x) == opid2('*','=') || \
1789 (x) == opid2('/','=') || \
1790 (x) == opid2('%','=') || \
1791 (x) == opid2('&','=') || \
1792 (x) == opid2('|','=') || \
1793 (x) == opid3('&','~','=') \
1795 if (warn_truthvalue) {
1796 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1797 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1798 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1801 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1802 warn_truthvalue = false;
1807 (op->prec < olast->prec) ||
1808 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1810 if (!parser_sy_apply_operator(parser, &sy))
1812 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1813 olast = &operators[vec_last(sy.ops).etype-1];
1818 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1819 /* for gmqcc standard: open up the namespace of the previous type */
1820 ast_expression *prevex = vec_last(sy.out).out;
1822 parseerror(parser, "unexpected member operator");
1825 if (prevex->expression.vtype == TYPE_ENTITY)
1826 parser->memberof = TYPE_ENTITY;
1827 else if (prevex->expression.vtype == TYPE_VECTOR)
1828 parser->memberof = TYPE_VECTOR;
1830 parseerror(parser, "type error: type has no members");
1836 if (op->id == opid1('(')) {
1838 size_t sycount = vec_size(sy.out);
1839 DEBUGSHUNTDO(con_out("push [op] (\n"));
1840 ++parens; vec_push(parser->pot, POT_PAREN);
1841 /* we expected an operator, this is the function-call operator */
1842 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1844 ++parens; vec_push(parser->pot, POT_PAREN);
1845 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1846 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1849 } else if (op->id == opid1('[')) {
1851 parseerror(parser, "unexpected array subscript");
1854 ++parens; vec_push(parser->pot, POT_PAREN);
1855 /* push both the operator and the paren, this makes life easier */
1856 vec_push(sy.ops, syop(parser_ctx(parser), op));
1857 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1859 } else if (op->id == opid2('?',':')) {
1860 vec_push(sy.ops, syop(parser_ctx(parser), op));
1861 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1864 vec_push(parser->pot, POT_TERNARY1);
1865 } else if (op->id == opid2(':','?')) {
1866 if (!vec_size(parser->pot)) {
1867 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1870 if (vec_last(parser->pot) != POT_TERNARY1) {
1871 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1874 if (!parser_close_paren(parser, &sy, false))
1876 vec_push(sy.ops, syop(parser_ctx(parser), op));
1880 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1881 vec_push(sy.ops, syop(parser_ctx(parser), op));
1882 wantop = !!(op->flags & OP_SUFFIX);
1885 if (!parser_next(parser)) {
1888 if (parser->tok == ';' ||
1889 (!parens && parser->tok == ']'))
1895 while (vec_size(sy.ops)) {
1896 if (!parser_sy_apply_operator(parser, &sy))
1900 parser->lex->flags.noops = true;
1901 if (!vec_size(sy.out)) {
1902 parseerror(parser, "empty expression");
1905 expr = sy.out[0].out;
1908 DEBUGSHUNTDO(con_out("shunt done\n"));
1909 if (vec_size(parser->pot)) {
1910 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1913 vec_free(parser->pot);
1917 parser->lex->flags.noops = true;
1923 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1925 ast_expression *e = parse_expression_leave(parser, stopatcomma, false);
1928 if (!parser_next(parser)) {
1935 static void parser_enterblock(parser_t *parser)
1937 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1938 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1939 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1940 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1941 vec_push(parser->_block_ctx, parser_ctx(parser));
1944 static bool parser_leaveblock(parser_t *parser)
1947 size_t locals, typedefs;
1949 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1950 parseerror(parser, "internal error: parser_leaveblock with no block");
1954 util_htdel(vec_last(parser->variables));
1955 vec_pop(parser->variables);
1956 if (!vec_size(parser->_blocklocals)) {
1957 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1961 locals = vec_last(parser->_blocklocals);
1962 vec_pop(parser->_blocklocals);
1963 while (vec_size(parser->_locals) != locals) {
1964 ast_expression *e = vec_last(parser->_locals);
1965 ast_value *v = (ast_value*)e;
1966 vec_pop(parser->_locals);
1967 if (ast_istype(e, ast_value) && !v->uses) {
1968 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1973 typedefs = vec_last(parser->_blocktypedefs);
1974 while (vec_size(parser->_typedefs) != typedefs) {
1975 ast_delete(vec_last(parser->_typedefs));
1976 vec_pop(parser->_typedefs);
1978 util_htdel(vec_last(parser->typedefs));
1979 vec_pop(parser->typedefs);
1981 vec_pop(parser->_block_ctx);
1985 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1987 vec_push(parser->_locals, e);
1988 util_htset(vec_last(parser->variables), name, (void*)e);
1991 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1995 ast_expression *prev;
1997 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2000 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2003 parseerror(parser, "internal error: failed to process condition");
2008 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2010 /* vector types need to be cast to true booleans */
2011 ast_binary *bin = (ast_binary*)cond;
2012 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2014 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2016 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2019 parseerror(parser, "internal error: failed to process condition");
2026 unary = (ast_unary*)cond;
2027 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2029 cond = unary->operand;
2030 unary->operand = NULL;
2033 unary = (ast_unary*)cond;
2037 parseerror(parser, "internal error: failed to process condition");
2039 if (ifnot) *_ifnot = !*_ifnot;
2043 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2046 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2049 lex_ctx ctx = parser_ctx(parser);
2051 (void)block; /* not touching */
2053 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2054 if (!parser_next(parser)) {
2055 parseerror(parser, "expected condition or 'not'");
2058 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2060 if (!parser_next(parser)) {
2061 parseerror(parser, "expected condition in parenthesis");
2065 if (parser->tok != '(') {
2066 parseerror(parser, "expected 'if' condition in parenthesis");
2069 /* parse into the expression */
2070 if (!parser_next(parser)) {
2071 parseerror(parser, "expected 'if' condition after opening paren");
2074 /* parse the condition */
2075 cond = parse_expression_leave(parser, false, true);
2079 if (parser->tok != ')') {
2080 parseerror(parser, "expected closing paren after 'if' condition");
2084 /* parse into the 'then' branch */
2085 if (!parser_next(parser)) {
2086 parseerror(parser, "expected statement for on-true branch of 'if'");
2090 if (!parse_statement_or_block(parser, &ontrue)) {
2094 /* check for an else */
2095 if (!strcmp(parser_tokval(parser), "else")) {
2096 /* parse into the 'else' branch */
2097 if (!parser_next(parser)) {
2098 parseerror(parser, "expected on-false branch after 'else'");
2103 if (!parse_statement_or_block(parser, &onfalse)) {
2110 cond = process_condition(parser, cond, &ifnot);
2112 if (ontrue) ast_delete(ontrue);
2113 if (onfalse) ast_delete(onfalse);
2118 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2120 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2121 *out = (ast_expression*)ifthen;
2125 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2126 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2131 /* skip the 'while' and get the body */
2132 if (!parser_next(parser)) {
2133 if (OPTS_FLAG(LOOP_LABELS))
2134 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2136 parseerror(parser, "expected 'while' condition in parenthesis");
2140 if (parser->tok == ':') {
2141 if (!OPTS_FLAG(LOOP_LABELS))
2142 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2143 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2144 parseerror(parser, "expected loop label");
2147 label = util_strdup(parser_tokval(parser));
2148 if (!parser_next(parser)) {
2150 parseerror(parser, "expected 'while' condition in parenthesis");
2155 if (parser->tok != '(') {
2156 parseerror(parser, "expected 'while' condition in parenthesis");
2160 vec_push(parser->breaks, label);
2161 vec_push(parser->continues, label);
2163 rv = parse_while_go(parser, block, out);
2166 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2167 parseerror(parser, "internal error: label stack corrupted");
2173 vec_pop(parser->breaks);
2174 vec_pop(parser->continues);
2179 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2182 ast_expression *cond, *ontrue;
2186 lex_ctx ctx = parser_ctx(parser);
2188 (void)block; /* not touching */
2190 /* parse into the expression */
2191 if (!parser_next(parser)) {
2192 parseerror(parser, "expected 'while' condition after opening paren");
2195 /* parse the condition */
2196 cond = parse_expression_leave(parser, false, true);
2200 if (parser->tok != ')') {
2201 parseerror(parser, "expected closing paren after 'while' condition");
2205 /* parse into the 'then' branch */
2206 if (!parser_next(parser)) {
2207 parseerror(parser, "expected while-loop body");
2211 if (!parse_statement_or_block(parser, &ontrue)) {
2216 cond = process_condition(parser, cond, &ifnot);
2221 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2222 *out = (ast_expression*)aloop;
2226 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2227 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2232 /* skip the 'do' and get the body */
2233 if (!parser_next(parser)) {
2234 if (OPTS_FLAG(LOOP_LABELS))
2235 parseerror(parser, "expected loop label or body");
2237 parseerror(parser, "expected loop body");
2241 if (parser->tok == ':') {
2242 if (!OPTS_FLAG(LOOP_LABELS))
2243 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2244 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2245 parseerror(parser, "expected loop label");
2248 label = util_strdup(parser_tokval(parser));
2249 if (!parser_next(parser)) {
2251 parseerror(parser, "expected loop body");
2256 vec_push(parser->breaks, label);
2257 vec_push(parser->continues, label);
2259 rv = parse_dowhile_go(parser, block, out);
2262 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2263 parseerror(parser, "internal error: label stack corrupted");
2269 vec_pop(parser->breaks);
2270 vec_pop(parser->continues);
2275 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2278 ast_expression *cond, *ontrue;
2282 lex_ctx ctx = parser_ctx(parser);
2284 (void)block; /* not touching */
2286 if (!parse_statement_or_block(parser, &ontrue))
2289 /* expect the "while" */
2290 if (parser->tok != TOKEN_KEYWORD ||
2291 strcmp(parser_tokval(parser), "while"))
2293 parseerror(parser, "expected 'while' and condition");
2298 /* skip the 'while' and check for opening paren */
2299 if (!parser_next(parser) || parser->tok != '(') {
2300 parseerror(parser, "expected 'while' condition in parenthesis");
2304 /* parse into the expression */
2305 if (!parser_next(parser)) {
2306 parseerror(parser, "expected 'while' condition after opening paren");
2310 /* parse the condition */
2311 cond = parse_expression_leave(parser, false, true);
2315 if (parser->tok != ')') {
2316 parseerror(parser, "expected closing paren after 'while' condition");
2322 if (!parser_next(parser) || parser->tok != ';') {
2323 parseerror(parser, "expected semicolon after condition");
2329 if (!parser_next(parser)) {
2330 parseerror(parser, "parse error");
2336 cond = process_condition(parser, cond, &ifnot);
2341 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2342 *out = (ast_expression*)aloop;
2346 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2347 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2352 /* skip the 'for' and check for opening paren */
2353 if (!parser_next(parser)) {
2354 if (OPTS_FLAG(LOOP_LABELS))
2355 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2357 parseerror(parser, "expected 'for' expressions in parenthesis");
2361 if (parser->tok == ':') {
2362 if (!OPTS_FLAG(LOOP_LABELS))
2363 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2364 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2365 parseerror(parser, "expected loop label");
2368 label = util_strdup(parser_tokval(parser));
2369 if (!parser_next(parser)) {
2371 parseerror(parser, "expected 'for' expressions in parenthesis");
2376 if (parser->tok != '(') {
2377 parseerror(parser, "expected 'for' expressions in parenthesis");
2381 vec_push(parser->breaks, label);
2382 vec_push(parser->continues, label);
2384 rv = parse_for_go(parser, block, out);
2387 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2388 parseerror(parser, "internal error: label stack corrupted");
2394 vec_pop(parser->breaks);
2395 vec_pop(parser->continues);
2399 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2402 ast_expression *initexpr, *cond, *increment, *ontrue;
2408 lex_ctx ctx = parser_ctx(parser);
2410 parser_enterblock(parser);
2417 /* parse into the expression */
2418 if (!parser_next(parser)) {
2419 parseerror(parser, "expected 'for' initializer after opening paren");
2424 if (parser->tok == TOKEN_IDENT)
2425 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2427 if (typevar || parser->tok == TOKEN_TYPENAME) {
2429 if (opts.standard != COMPILER_GMQCC) {
2430 if (parsewarning(parser, WARN_EXTENSIONS,
2431 "current standard does not allow variable declarations in for-loop initializers"))
2435 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2438 else if (parser->tok != ';')
2440 initexpr = parse_expression_leave(parser, false, false);
2445 /* move on to condition */
2446 if (parser->tok != ';') {
2447 parseerror(parser, "expected semicolon after for-loop initializer");
2450 if (!parser_next(parser)) {
2451 parseerror(parser, "expected for-loop condition");
2455 /* parse the condition */
2456 if (parser->tok != ';') {
2457 cond = parse_expression_leave(parser, false, true);
2462 /* move on to incrementor */
2463 if (parser->tok != ';') {
2464 parseerror(parser, "expected semicolon after for-loop initializer");
2467 if (!parser_next(parser)) {
2468 parseerror(parser, "expected for-loop condition");
2472 /* parse the incrementor */
2473 if (parser->tok != ')') {
2474 increment = parse_expression_leave(parser, false, false);
2477 if (!ast_side_effects(increment)) {
2478 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2484 if (parser->tok != ')') {
2485 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2488 /* parse into the 'then' branch */
2489 if (!parser_next(parser)) {
2490 parseerror(parser, "expected for-loop body");
2493 if (!parse_statement_or_block(parser, &ontrue))
2497 cond = process_condition(parser, cond, &ifnot);
2501 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2502 *out = (ast_expression*)aloop;
2504 if (!parser_leaveblock(parser))
2508 if (initexpr) ast_delete(initexpr);
2509 if (cond) ast_delete(cond);
2510 if (increment) ast_delete(increment);
2511 (void)!parser_leaveblock(parser);
2515 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2517 ast_expression *exp = NULL;
2518 ast_return *ret = NULL;
2519 ast_value *expected = parser->function->vtype;
2521 lex_ctx ctx = parser_ctx(parser);
2523 (void)block; /* not touching */
2525 if (!parser_next(parser)) {
2526 parseerror(parser, "expected return expression");
2530 if (parser->tok != ';') {
2531 exp = parse_expression(parser, false);
2535 if (exp->expression.vtype != TYPE_NIL &&
2536 exp->expression.vtype != expected->expression.next->expression.vtype)
2538 parseerror(parser, "return with invalid expression");
2541 ret = ast_return_new(ctx, exp);
2547 if (!parser_next(parser))
2548 parseerror(parser, "parse error");
2549 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2550 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2552 ret = ast_return_new(ctx, NULL);
2554 *out = (ast_expression*)ret;
2558 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2561 unsigned int levels = 0;
2562 lex_ctx ctx = parser_ctx(parser);
2563 const char **loops = (is_continue ? parser->continues : parser->breaks);
2565 (void)block; /* not touching */
2566 if (!parser_next(parser)) {
2567 parseerror(parser, "expected semicolon or loop label");
2571 if (parser->tok == TOKEN_IDENT) {
2572 if (!OPTS_FLAG(LOOP_LABELS))
2573 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2574 i = vec_size(loops);
2576 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2579 parseerror(parser, "no such loop to %s: `%s`",
2580 (is_continue ? "continue" : "break out of"),
2581 parser_tokval(parser));
2586 if (!parser_next(parser)) {
2587 parseerror(parser, "expected semicolon");
2592 if (parser->tok != ';') {
2593 parseerror(parser, "expected semicolon");
2597 if (!parser_next(parser))
2598 parseerror(parser, "parse error");
2600 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2604 /* returns true when it was a variable qualifier, false otherwise!
2605 * on error, cvq is set to CV_WRONG
2607 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2609 bool had_const = false;
2610 bool had_var = false;
2611 bool had_noref = false;
2612 bool had_attrib = false;
2613 bool had_static = false;
2618 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2620 /* parse an attribute */
2621 if (!parser_next(parser)) {
2622 parseerror(parser, "expected attribute after `[[`");
2626 if (!strcmp(parser_tokval(parser), "noreturn")) {
2627 flags |= AST_FLAG_NORETURN;
2628 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2629 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2634 else if (!strcmp(parser_tokval(parser), "noref")) {
2636 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2637 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2642 else if (!strcmp(parser_tokval(parser), "inline")) {
2643 flags |= AST_FLAG_INLINE;
2644 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2645 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2652 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2653 flags |= AST_FLAG_DEPRECATED;
2656 if (!parser_next(parser)) {
2657 parseerror(parser, "parse error in attribute");
2661 if (parser->tok == '(') {
2662 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2663 parseerror(parser, "`deprecated` attribute missing parameter");
2667 *message = util_strdup(parser_tokval(parser));
2669 if (!parser_next(parser)) {
2670 parseerror(parser, "parse error in attribute");
2674 if(parser->tok != ')') {
2675 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2679 if (!parser_next(parser)) {
2680 parseerror(parser, "parse error in attribute");
2685 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2686 parseerror(parser, "`deprecated` attribute expected `]]`");
2689 if (*message) mem_d(*message);
2697 /* Skip tokens until we hit a ]] */
2698 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2699 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2700 if (!parser_next(parser)) {
2701 parseerror(parser, "error inside attribute");
2708 else if (!strcmp(parser_tokval(parser), "static"))
2710 else if (!strcmp(parser_tokval(parser), "const"))
2712 else if (!strcmp(parser_tokval(parser), "var"))
2714 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2716 else if (!strcmp(parser_tokval(parser), "noref"))
2718 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2723 if (!parser_next(parser))
2733 *is_static = had_static;
2737 parseerror(parser, "parse error after variable qualifier");
2742 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2743 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2748 /* skip the 'while' and get the body */
2749 if (!parser_next(parser)) {
2750 if (OPTS_FLAG(LOOP_LABELS))
2751 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2753 parseerror(parser, "expected 'switch' operand in parenthesis");
2757 if (parser->tok == ':') {
2758 if (!OPTS_FLAG(LOOP_LABELS))
2759 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2760 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2761 parseerror(parser, "expected loop label");
2764 label = util_strdup(parser_tokval(parser));
2765 if (!parser_next(parser)) {
2767 parseerror(parser, "expected 'switch' operand in parenthesis");
2772 if (parser->tok != '(') {
2773 parseerror(parser, "expected 'switch' operand in parenthesis");
2777 vec_push(parser->breaks, label);
2779 rv = parse_switch_go(parser, block, out);
2782 if (vec_last(parser->breaks) != label) {
2783 parseerror(parser, "internal error: label stack corrupted");
2789 vec_pop(parser->breaks);
2794 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2796 ast_expression *operand;
2799 ast_switch *switchnode;
2800 ast_switch_case swcase;
2803 bool noref, is_static;
2804 uint32_t qflags = 0;
2806 lex_ctx ctx = parser_ctx(parser);
2808 (void)block; /* not touching */
2811 /* parse into the expression */
2812 if (!parser_next(parser)) {
2813 parseerror(parser, "expected switch operand");
2816 /* parse the operand */
2817 operand = parse_expression_leave(parser, false, false);
2821 switchnode = ast_switch_new(ctx, operand);
2824 if (parser->tok != ')') {
2825 ast_delete(switchnode);
2826 parseerror(parser, "expected closing paren after 'switch' operand");
2830 /* parse over the opening paren */
2831 if (!parser_next(parser) || parser->tok != '{') {
2832 ast_delete(switchnode);
2833 parseerror(parser, "expected list of cases");
2837 if (!parser_next(parser)) {
2838 ast_delete(switchnode);
2839 parseerror(parser, "expected 'case' or 'default'");
2843 /* new block; allow some variables to be declared here */
2844 parser_enterblock(parser);
2847 if (parser->tok == TOKEN_IDENT)
2848 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2849 if (typevar || parser->tok == TOKEN_TYPENAME) {
2850 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2851 ast_delete(switchnode);
2856 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2858 if (cvq == CV_WRONG) {
2859 ast_delete(switchnode);
2862 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2863 ast_delete(switchnode);
2872 while (parser->tok != '}') {
2873 ast_block *caseblock;
2875 if (!strcmp(parser_tokval(parser), "case")) {
2876 if (!parser_next(parser)) {
2877 ast_delete(switchnode);
2878 parseerror(parser, "expected expression for case");
2881 swcase.value = parse_expression_leave(parser, false, false);
2882 if (!swcase.value) {
2883 ast_delete(switchnode);
2884 parseerror(parser, "expected expression for case");
2887 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2888 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2889 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2895 else if (!strcmp(parser_tokval(parser), "default")) {
2896 swcase.value = NULL;
2897 if (!parser_next(parser)) {
2898 ast_delete(switchnode);
2899 parseerror(parser, "expected colon");
2904 ast_delete(switchnode);
2905 parseerror(parser, "expected 'case' or 'default'");
2909 /* Now the colon and body */
2910 if (parser->tok != ':') {
2911 if (swcase.value) ast_unref(swcase.value);
2912 ast_delete(switchnode);
2913 parseerror(parser, "expected colon");
2917 if (!parser_next(parser)) {
2918 if (swcase.value) ast_unref(swcase.value);
2919 ast_delete(switchnode);
2920 parseerror(parser, "expected statements or case");
2923 caseblock = ast_block_new(parser_ctx(parser));
2925 if (swcase.value) ast_unref(swcase.value);
2926 ast_delete(switchnode);
2929 swcase.code = (ast_expression*)caseblock;
2930 vec_push(switchnode->cases, swcase);
2932 ast_expression *expr;
2933 if (parser->tok == '}')
2935 if (parser->tok == TOKEN_KEYWORD) {
2936 if (!strcmp(parser_tokval(parser), "case") ||
2937 !strcmp(parser_tokval(parser), "default"))
2942 if (!parse_statement(parser, caseblock, &expr, true)) {
2943 ast_delete(switchnode);
2948 if (!ast_block_add_expr(caseblock, expr)) {
2949 ast_delete(switchnode);
2955 parser_leaveblock(parser);
2958 if (parser->tok != '}') {
2959 ast_delete(switchnode);
2960 parseerror(parser, "expected closing paren of case list");
2963 if (!parser_next(parser)) {
2964 ast_delete(switchnode);
2965 parseerror(parser, "parse error after switch");
2968 *out = (ast_expression*)switchnode;
2972 /* parse computed goto sides */
2973 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression *side) {
2974 ast_expression *on_true;
2975 ast_expression *on_false;
2980 if (ast_istype(side, ast_ternary)) {
2981 on_true = parse_goto_computed(parser, ((ast_ternary*)side)->on_true);
2982 on_false = parse_goto_computed(parser, ((ast_ternary*)side)->on_false);
2984 if (!on_true || !on_false) {
2985 parseerror(parser, "expected label or expression in ternary");
2986 if (((ast_ternary*)side)->on_false) ast_unref(((ast_ternary*)side)->on_false);
2987 if (((ast_ternary*)side)->on_true) ast_unref(((ast_ternary*)side)->on_true);
2991 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), ((ast_ternary*)side)->cond, on_true, on_false);
2992 } else if (ast_istype(side, ast_label)) {
2993 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)side)->name);
2994 ast_goto_set_label(gt, ((ast_label*)side));
2995 return (ast_expression*)gt;
3000 static bool parse_goto(parser_t *parser, ast_expression **out)
3003 ast_goto *gt = NULL;
3005 if (!parser_next(parser))
3008 if (parser->tok != TOKEN_IDENT) {
3009 ast_expression *expression;
3011 /* could be an expression i.e computed goto :-) */
3012 if (parser->tok != '(') {
3013 parseerror(parser, "expected label name after `goto`");
3017 /* failed to parse expression for goto */
3018 if (!(expression = parse_expression(parser, false)) ||
3019 !(*out = parse_goto_computed(parser, expression))) {
3020 parseerror(parser, "invalid goto expression");
3021 ast_unref(expression);
3028 /* not computed goto */
3029 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3031 for (i = 0; i < vec_size(parser->labels); ++i) {
3032 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
3033 ast_goto_set_label(gt, parser->labels[i]);
3037 if (i == vec_size(parser->labels))
3038 vec_push(parser->gotos, gt);
3040 if (!parser_next(parser) || parser->tok != ';') {
3041 parseerror(parser, "semicolon expected after goto label");
3044 if (!parser_next(parser)) {
3045 parseerror(parser, "parse error after goto");
3049 *out = (ast_expression*)gt;
3053 static bool parse_skipwhite(parser_t *parser)
3056 if (!parser_next(parser))
3058 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3059 return parser->tok < TOKEN_ERROR;
3062 static bool parse_eol(parser_t *parser)
3064 if (!parse_skipwhite(parser))
3066 return parser->tok == TOKEN_EOL;
3069 static bool parse_pragma_do(parser_t *parser)
3071 if (!parser_next(parser) ||
3072 parser->tok != TOKEN_IDENT ||
3073 strcmp(parser_tokval(parser), "pragma"))
3075 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3078 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3079 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3083 if (!strcmp(parser_tokval(parser), "noref")) {
3084 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3085 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3088 parser->noref = !!parser_token(parser)->constval.i;
3089 if (!parse_eol(parser)) {
3090 parseerror(parser, "parse error after `noref` pragma");
3096 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3103 static bool parse_pragma(parser_t *parser)
3106 parser->lex->flags.preprocessing = true;
3107 parser->lex->flags.mergelines = true;
3108 rv = parse_pragma_do(parser);
3109 if (parser->tok != TOKEN_EOL) {
3110 parseerror(parser, "junk after pragma");
3113 parser->lex->flags.preprocessing = false;
3114 parser->lex->flags.mergelines = false;
3115 if (!parser_next(parser)) {
3116 parseerror(parser, "parse error after pragma");
3122 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3124 bool noref, is_static;
3126 uint32_t qflags = 0;
3127 ast_value *typevar = NULL;
3128 char *vstring = NULL;
3132 if (parser->tok == TOKEN_IDENT)
3133 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3135 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3137 /* local variable */
3139 parseerror(parser, "cannot declare a variable from here");
3142 if (opts.standard == COMPILER_QCC) {
3143 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3146 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3150 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3152 if (cvq == CV_WRONG)
3154 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3156 else if (parser->tok == TOKEN_KEYWORD)
3158 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3163 if (!parser_next(parser)) {
3164 parseerror(parser, "parse error after __builtin_debug_printtype");
3168 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3170 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3171 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3172 if (!parser_next(parser)) {
3173 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3179 if (!parse_statement(parser, block, out, allow_cases))
3182 con_out("__builtin_debug_printtype: got no output node\n");
3185 ast_type_to_string(*out, ty, sizeof(ty));
3186 con_out("__builtin_debug_printtype: `%s`\n", ty);
3191 else if (!strcmp(parser_tokval(parser), "return"))
3193 return parse_return(parser, block, out);
3195 else if (!strcmp(parser_tokval(parser), "if"))
3197 return parse_if(parser, block, out);
3199 else if (!strcmp(parser_tokval(parser), "while"))
3201 return parse_while(parser, block, out);
3203 else if (!strcmp(parser_tokval(parser), "do"))
3205 return parse_dowhile(parser, block, out);
3207 else if (!strcmp(parser_tokval(parser), "for"))
3209 if (opts.standard == COMPILER_QCC) {
3210 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3213 return parse_for(parser, block, out);
3215 else if (!strcmp(parser_tokval(parser), "break"))
3217 return parse_break_continue(parser, block, out, false);
3219 else if (!strcmp(parser_tokval(parser), "continue"))
3221 return parse_break_continue(parser, block, out, true);
3223 else if (!strcmp(parser_tokval(parser), "switch"))
3225 return parse_switch(parser, block, out);
3227 else if (!strcmp(parser_tokval(parser), "case") ||
3228 !strcmp(parser_tokval(parser), "default"))
3231 parseerror(parser, "unexpected 'case' label");
3236 else if (!strcmp(parser_tokval(parser), "goto"))
3238 return parse_goto(parser, out);
3240 else if (!strcmp(parser_tokval(parser), "typedef"))
3242 if (!parser_next(parser)) {
3243 parseerror(parser, "expected type definition after 'typedef'");
3246 return parse_typedef(parser);
3248 parseerror(parser, "Unexpected keyword");
3251 else if (parser->tok == '{')
3254 inner = parse_block(parser);
3257 *out = (ast_expression*)inner;
3260 else if (parser->tok == ':')
3264 if (!parser_next(parser)) {
3265 parseerror(parser, "expected label name");
3268 if (parser->tok != TOKEN_IDENT) {
3269 parseerror(parser, "label must be an identifier");
3272 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3275 vec_push(parser->labels, label);
3276 *out = (ast_expression*)label;
3277 if (!parser_next(parser)) {
3278 parseerror(parser, "parse error after label");
3281 for (i = 0; i < vec_size(parser->gotos); ++i) {
3282 if (!strcmp(parser->gotos[i]->name, label->name)) {
3283 ast_goto_set_label(parser->gotos[i], label);
3284 vec_remove(parser->gotos, i, 1);
3290 else if (parser->tok == ';')
3292 if (!parser_next(parser)) {
3293 parseerror(parser, "parse error after empty statement");
3300 ast_expression *exp = parse_expression(parser, false);
3304 if (!ast_side_effects(exp)) {
3305 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3312 static bool parse_block_into(parser_t *parser, ast_block *block)
3316 parser_enterblock(parser);
3318 if (!parser_next(parser)) { /* skip the '{' */
3319 parseerror(parser, "expected function body");
3323 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3325 ast_expression *expr = NULL;
3326 if (parser->tok == '}')
3329 if (!parse_statement(parser, block, &expr, false)) {
3330 /* parseerror(parser, "parse error"); */
3336 if (!ast_block_add_expr(block, expr)) {
3343 if (parser->tok != '}') {
3346 (void)parser_next(parser);
3350 if (!parser_leaveblock(parser))
3352 return retval && !!block;
3355 static ast_block* parse_block(parser_t *parser)
3358 block = ast_block_new(parser_ctx(parser));
3361 if (!parse_block_into(parser, block)) {
3362 ast_block_delete(block);
3368 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3370 if (parser->tok == '{') {
3371 *out = (ast_expression*)parse_block(parser);
3374 return parse_statement(parser, NULL, out, false);
3377 static bool create_vector_members(ast_value *var, ast_member **me)
3380 size_t len = strlen(var->name);
3382 for (i = 0; i < 3; ++i) {
3383 char *name = (char*)mem_a(len+3);
3384 memcpy(name, var->name, len);
3386 name[len+1] = 'x'+i;
3388 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3397 do { ast_member_delete(me[--i]); } while(i);
3401 static bool parse_function_body(parser_t *parser, ast_value *var)
3403 ast_block *block = NULL;
3408 ast_expression *framenum = NULL;
3409 ast_expression *nextthink = NULL;
3410 /* None of the following have to be deleted */
3411 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3412 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3413 bool has_frame_think;
3417 has_frame_think = false;
3418 old = parser->function;
3420 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3421 parseerror(parser, "gotos/labels leaking");
3425 if (var->expression.flags & AST_FLAG_VARIADIC) {
3426 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3427 "variadic function with implementation will not be able to access additional parameters"))
3433 if (parser->tok == '[') {
3434 /* got a frame definition: [ framenum, nextthink ]
3435 * this translates to:
3436 * self.frame = framenum;
3437 * self.nextthink = time + 0.1;
3438 * self.think = nextthink;
3442 fld_think = parser_find_field(parser, "think");
3443 fld_nextthink = parser_find_field(parser, "nextthink");
3444 fld_frame = parser_find_field(parser, "frame");
3445 if (!fld_think || !fld_nextthink || !fld_frame) {
3446 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3447 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3450 gbl_time = parser_find_global(parser, "time");
3451 gbl_self = parser_find_global(parser, "self");
3452 if (!gbl_time || !gbl_self) {
3453 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3454 parseerror(parser, "please declare the following globals: `time`, `self`");
3458 if (!parser_next(parser))
3461 framenum = parse_expression_leave(parser, true, false);
3463 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3466 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3467 ast_unref(framenum);
3468 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3472 if (parser->tok != ',') {
3473 ast_unref(framenum);
3474 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3475 parseerror(parser, "Got a %i\n", parser->tok);
3479 if (!parser_next(parser)) {
3480 ast_unref(framenum);
3484 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3486 /* qc allows the use of not-yet-declared functions here
3487 * - this automatically creates a prototype */
3488 ast_value *thinkfunc;
3489 ast_expression *functype = fld_think->expression.next;
3491 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3492 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3493 ast_unref(framenum);
3494 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3498 if (!parser_next(parser)) {
3499 ast_unref(framenum);
3500 ast_delete(thinkfunc);
3504 vec_push(parser->globals, (ast_expression*)thinkfunc);
3505 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3506 nextthink = (ast_expression*)thinkfunc;
3509 nextthink = parse_expression_leave(parser, true, false);
3511 ast_unref(framenum);
3512 parseerror(parser, "expected a think-function in [frame,think] notation");
3517 if (!ast_istype(nextthink, ast_value)) {
3518 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3522 if (retval && parser->tok != ']') {
3523 parseerror(parser, "expected closing `]` for [frame,think] notation");
3527 if (retval && !parser_next(parser)) {
3531 if (retval && parser->tok != '{') {
3532 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3537 ast_unref(nextthink);
3538 ast_unref(framenum);
3542 has_frame_think = true;
3545 block = ast_block_new(parser_ctx(parser));
3547 parseerror(parser, "failed to allocate block");
3548 if (has_frame_think) {
3549 ast_unref(nextthink);
3550 ast_unref(framenum);
3555 if (has_frame_think) {
3557 ast_expression *self_frame;
3558 ast_expression *self_nextthink;
3559 ast_expression *self_think;
3560 ast_expression *time_plus_1;
3561 ast_store *store_frame;
3562 ast_store *store_nextthink;
3563 ast_store *store_think;
3565 ctx = parser_ctx(parser);
3566 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3567 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3568 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3570 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3571 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3573 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3574 if (self_frame) ast_delete(self_frame);
3575 if (self_nextthink) ast_delete(self_nextthink);
3576 if (self_think) ast_delete(self_think);
3577 if (time_plus_1) ast_delete(time_plus_1);
3583 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3584 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3585 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3588 ast_delete(self_frame);
3591 if (!store_nextthink) {
3592 ast_delete(self_nextthink);
3596 ast_delete(self_think);
3600 if (store_frame) ast_delete(store_frame);
3601 if (store_nextthink) ast_delete(store_nextthink);
3602 if (store_think) ast_delete(store_think);
3605 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3606 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3607 !ast_block_add_expr(block, (ast_expression*)store_think))
3614 parseerror(parser, "failed to generate code for [frame,think]");
3615 ast_unref(nextthink);
3616 ast_unref(framenum);
3622 parser_enterblock(parser);
3624 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3626 ast_value *param = var->expression.params[parami];
3629 if (param->expression.vtype != TYPE_VECTOR &&
3630 (param->expression.vtype != TYPE_FIELD ||
3631 param->expression.next->expression.vtype != TYPE_VECTOR))
3636 if (!create_vector_members(param, me)) {
3637 ast_block_delete(block);
3641 for (e = 0; e < 3; ++e) {
3642 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3643 ast_block_collect(block, (ast_expression*)me[e]);
3647 func = ast_function_new(ast_ctx(var), var->name, var);
3649 parseerror(parser, "failed to allocate function for `%s`", var->name);
3650 ast_block_delete(block);
3653 vec_push(parser->functions, func);
3655 parser->function = func;
3656 if (!parse_block_into(parser, block)) {
3657 ast_block_delete(block);
3661 vec_push(func->blocks, block);
3663 parser->function = old;
3664 if (!parser_leaveblock(parser))
3666 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3667 parseerror(parser, "internal error: local scopes left");
3671 if (parser->tok == ';')
3672 return parser_next(parser);
3673 else if (opts.standard == COMPILER_QCC)
3674 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3678 vec_pop(parser->functions);
3679 ast_function_delete(func);
3680 var->constval.vfunc = NULL;
3683 (void)!parser_leaveblock(parser);
3684 parser->function = old;
3688 static ast_expression *array_accessor_split(
3693 ast_expression *left,
3694 ast_expression *right
3700 lex_ctx ctx = ast_ctx(array);
3702 if (!left || !right) {
3703 if (left) ast_delete(left);
3704 if (right) ast_delete(right);
3708 cmp = ast_binary_new(ctx, INSTR_LT,
3709 (ast_expression*)index,
3710 (ast_expression*)parser_const_float(parser, middle));
3714 parseerror(parser, "internal error: failed to create comparison for array setter");
3718 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3720 ast_delete(cmp); /* will delete left and right */
3721 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3725 return (ast_expression*)ifthen;
3728 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3730 lex_ctx ctx = ast_ctx(array);
3732 if (from+1 == afterend) {
3733 /* set this value */
3736 ast_array_index *subscript;
3738 int assignop = type_store_instr[value->expression.vtype];
3740 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3741 assignop = INSTR_STORE_V;
3743 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3747 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3749 ast_delete(subscript);
3753 block = ast_block_new(ctx);
3759 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3764 ret = ast_return_new(ctx, NULL);
3770 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3775 return (ast_expression*)block;
3777 ast_expression *left, *right;
3778 size_t diff = afterend - from;
3779 size_t middle = from + diff/2;
3780 left = array_setter_node(parser, array, index, value, from, middle);
3781 right = array_setter_node(parser, array, index, value, middle, afterend);
3782 return array_accessor_split(parser, array, index, middle, left, right);
3786 static ast_expression *array_field_setter_node(
3795 lex_ctx ctx = ast_ctx(array);
3797 if (from+1 == afterend) {
3798 /* set this value */
3801 ast_entfield *entfield;
3802 ast_array_index *subscript;
3804 int assignop = type_storep_instr[value->expression.vtype];
3806 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3807 assignop = INSTR_STOREP_V;
3809 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3813 entfield = ast_entfield_new_force(ctx,
3814 (ast_expression*)entity,
3815 (ast_expression*)subscript,
3816 (ast_expression*)subscript);
3818 ast_delete(subscript);
3822 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3824 ast_delete(entfield);
3828 block = ast_block_new(ctx);
3834 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3839 ret = ast_return_new(ctx, NULL);
3845 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3850 return (ast_expression*)block;
3852 ast_expression *left, *right;
3853 size_t diff = afterend - from;
3854 size_t middle = from + diff/2;
3855 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3856 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3857 return array_accessor_split(parser, array, index, middle, left, right);
3861 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3863 lex_ctx ctx = ast_ctx(array);
3865 if (from+1 == afterend) {
3867 ast_array_index *subscript;
3869 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3873 ret = ast_return_new(ctx, (ast_expression*)subscript);
3875 ast_delete(subscript);
3879 return (ast_expression*)ret;
3881 ast_expression *left, *right;
3882 size_t diff = afterend - from;
3883 size_t middle = from + diff/2;
3884 left = array_getter_node(parser, array, index, from, middle);
3885 right = array_getter_node(parser, array, index, middle, afterend);
3886 return array_accessor_split(parser, array, index, middle, left, right);
3890 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3892 ast_function *func = NULL;
3893 ast_value *fval = NULL;
3894 ast_block *body = NULL;
3896 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3898 parseerror(parser, "failed to create accessor function value");
3902 func = ast_function_new(ast_ctx(array), funcname, fval);
3905 parseerror(parser, "failed to create accessor function node");
3909 body = ast_block_new(ast_ctx(array));
3911 parseerror(parser, "failed to create block for array accessor");
3917 vec_push(func->blocks, body);
3920 vec_push(parser->accessors, fval);
3925 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3927 ast_expression *root = NULL;
3928 ast_value *index = NULL;
3929 ast_value *value = NULL;
3933 if (!ast_istype(array->expression.next, ast_value)) {
3934 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3938 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3940 func = fval->constval.vfunc;
3941 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3943 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3944 value = ast_value_copy((ast_value*)array->expression.next);
3946 if (!index || !value) {
3947 parseerror(parser, "failed to create locals for array accessor");
3950 (void)!ast_value_set_name(value, "value"); /* not important */
3951 vec_push(fval->expression.params, index);
3952 vec_push(fval->expression.params, value);
3954 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3956 parseerror(parser, "failed to build accessor search tree");
3960 array->setter = fval;
3961 return ast_block_add_expr(func->blocks[0], root);
3963 if (index) ast_delete(index);
3964 if (value) ast_delete(value);
3965 if (root) ast_delete(root);
3971 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3973 ast_expression *root = NULL;
3974 ast_value *entity = NULL;
3975 ast_value *index = NULL;
3976 ast_value *value = NULL;
3980 if (!ast_istype(array->expression.next, ast_value)) {
3981 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3985 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3987 func = fval->constval.vfunc;
3988 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3990 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3991 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3992 value = ast_value_copy((ast_value*)array->expression.next);
3993 if (!entity || !index || !value) {
3994 parseerror(parser, "failed to create locals for array accessor");
3997 (void)!ast_value_set_name(value, "value"); /* not important */
3998 vec_push(fval->expression.params, entity);
3999 vec_push(fval->expression.params, index);
4000 vec_push(fval->expression.params, value);
4002 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4004 parseerror(parser, "failed to build accessor search tree");
4008 array->setter = fval;
4009 return ast_block_add_expr(func->blocks[0], root);
4011 if (entity) ast_delete(entity);
4012 if (index) ast_delete(index);
4013 if (value) ast_delete(value);
4014 if (root) ast_delete(root);
4020 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4022 ast_expression *root = NULL;
4023 ast_value *index = NULL;
4027 /* NOTE: checking array->expression.next rather than elemtype since
4028 * for fields elemtype is a temporary fieldtype.
4030 if (!ast_istype(array->expression.next, ast_value)) {
4031 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4035 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4037 func = fval->constval.vfunc;
4038 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4040 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4043 parseerror(parser, "failed to create locals for array accessor");
4046 vec_push(fval->expression.params, index);
4048 root = array_getter_node(parser, array, index, 0, array->expression.count);
4050 parseerror(parser, "failed to build accessor search tree");
4054 array->getter = fval;
4055 return ast_block_add_expr(func->blocks[0], root);
4057 if (index) ast_delete(index);
4058 if (root) ast_delete(root);
4064 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4065 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4073 bool variadic = false;
4075 ctx = parser_ctx(parser);
4077 /* for the sake of less code we parse-in in this function */
4078 if (!parser_next(parser)) {
4079 parseerror(parser, "expected parameter list");
4085 /* parse variables until we hit a closing paren */
4086 while (parser->tok != ')') {
4088 /* there must be commas between them */
4089 if (parser->tok != ',') {
4090 parseerror(parser, "expected comma or end of parameter list");
4093 if (!parser_next(parser)) {
4094 parseerror(parser, "expected parameter");
4100 if (parser->tok == TOKEN_DOTS) {
4101 /* '...' indicates a varargs function */
4103 if (!parser_next(parser)) {
4104 parseerror(parser, "expected parameter");
4107 if (parser->tok != ')') {
4108 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4114 /* for anything else just parse a typename */
4115 param = parse_typename(parser, NULL, NULL);
4118 vec_push(params, param);
4119 if (param->expression.vtype >= TYPE_VARIANT) {
4120 char tname[1024]; /* typename is reserved in C++ */
4121 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4122 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4128 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4132 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4133 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4136 if (!parser_next(parser)) {
4137 parseerror(parser, "parse error after typename");
4141 /* now turn 'var' into a function type */
4142 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4143 fval->expression.next = (ast_expression*)var;
4145 fval->expression.flags |= AST_FLAG_VARIADIC;
4148 var->expression.params = params;
4155 for (i = 0; i < vec_size(params); ++i)
4156 ast_delete(params[i]);
4161 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4163 ast_expression *cexp;
4164 ast_value *cval, *tmp;
4167 ctx = parser_ctx(parser);
4169 if (!parser_next(parser)) {
4171 parseerror(parser, "expected array-size");
4175 cexp = parse_expression_leave(parser, true, false);
4177 if (!cexp || !ast_istype(cexp, ast_value)) {
4181 parseerror(parser, "expected array-size as constant positive integer");
4184 cval = (ast_value*)cexp;
4186 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4187 tmp->expression.next = (ast_expression*)var;
4190 if (cval->expression.vtype == TYPE_INTEGER)
4191 tmp->expression.count = cval->constval.vint;
4192 else if (cval->expression.vtype == TYPE_FLOAT)
4193 tmp->expression.count = cval->constval.vfloat;
4197 parseerror(parser, "array-size must be a positive integer constant");
4202 if (parser->tok != ']') {
4204 parseerror(parser, "expected ']' after array-size");
4207 if (!parser_next(parser)) {
4209 parseerror(parser, "error after parsing array size");
4215 /* Parse a complete typename.
4216 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4217 * but when parsing variables separated by comma
4218 * 'storebase' should point to where the base-type should be kept.
4219 * The base type makes up every bit of type information which comes *before* the
4222 * The following will be parsed in its entirety:
4224 * The 'basetype' in this case is 'void()'
4225 * and if there's a comma after it, say:
4227 * then the type-information 'void()' can be stored in 'storebase'
4229 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4231 ast_value *var, *tmp;
4234 const char *name = NULL;
4235 bool isfield = false;
4236 bool wasarray = false;
4237 size_t morefields = 0;
4239 ctx = parser_ctx(parser);
4241 /* types may start with a dot */
4242 if (parser->tok == '.') {
4244 /* if we parsed a dot we need a typename now */
4245 if (!parser_next(parser)) {
4246 parseerror(parser, "expected typename for field definition");
4250 /* Further dots are handled seperately because they won't be part of the
4253 while (parser->tok == '.') {
4255 if (!parser_next(parser)) {
4256 parseerror(parser, "expected typename for field definition");
4261 if (parser->tok == TOKEN_IDENT)
4262 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4263 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4264 parseerror(parser, "expected typename");
4268 /* generate the basic type value */
4269 if (cached_typedef) {
4270 var = ast_value_copy(cached_typedef);
4271 ast_value_set_name(var, "<type(from_def)>");
4273 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4275 for (; morefields; --morefields) {
4276 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4277 tmp->expression.next = (ast_expression*)var;
4281 /* do not yet turn into a field - remember:
4282 * .void() foo; is a field too
4283 * .void()() foo; is a function
4287 if (!parser_next(parser)) {
4289 parseerror(parser, "parse error after typename");
4293 /* an opening paren now starts the parameter-list of a function
4294 * this is where original-QC has parameter lists.
4295 * We allow a single parameter list here.
4296 * Much like fteqcc we don't allow `float()() x`
4298 if (parser->tok == '(') {
4299 var = parse_parameter_list(parser, var);
4304 /* store the base if requested */
4306 *storebase = ast_value_copy(var);
4308 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4309 tmp->expression.next = (ast_expression*)*storebase;
4314 /* there may be a name now */
4315 if (parser->tok == TOKEN_IDENT) {
4316 name = util_strdup(parser_tokval(parser));
4318 if (!parser_next(parser)) {
4320 parseerror(parser, "error after variable or field declaration");
4325 /* now this may be an array */
4326 if (parser->tok == '[') {
4328 var = parse_arraysize(parser, var);
4333 /* This is the point where we can turn it into a field */
4335 /* turn it into a field if desired */
4336 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4337 tmp->expression.next = (ast_expression*)var;
4341 /* now there may be function parens again */
4342 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4343 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4344 if (parser->tok == '(' && wasarray)
4345 parseerror(parser, "arrays as part of a return type is not supported");
4346 while (parser->tok == '(') {
4347 var = parse_parameter_list(parser, var);
4356 /* finally name it */
4358 if (!ast_value_set_name(var, name)) {
4360 parseerror(parser, "internal error: failed to set name");
4363 /* free the name, ast_value_set_name duplicates */
4370 static bool parse_typedef(parser_t *parser)
4372 ast_value *typevar, *oldtype;
4373 ast_expression *old;
4375 typevar = parse_typename(parser, NULL, NULL);
4380 if ( (old = parser_find_var(parser, typevar->name)) ) {
4381 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4382 " -> `%s` has been declared here: %s:%i",
4383 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4384 ast_delete(typevar);
4388 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4389 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4390 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4391 ast_delete(typevar);
4395 vec_push(parser->_typedefs, typevar);
4396 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4398 if (parser->tok != ';') {
4399 parseerror(parser, "expected semicolon after typedef");
4402 if (!parser_next(parser)) {
4403 parseerror(parser, "parse error after typedef");
4410 static const char *cvq_to_str(int cvq) {
4412 case CV_NONE: return "none";
4413 case CV_VAR: return "`var`";
4414 case CV_CONST: return "`const`";
4415 default: return "<INVALID>";
4419 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4422 if (proto->cvq != var->cvq) {
4423 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4424 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4425 parser->tok == '='))
4427 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4428 "`%s` declared with different qualifiers: %s\n"
4429 " -> previous declaration here: %s:%i uses %s",
4430 var->name, cvq_to_str(var->cvq),
4431 ast_ctx(proto).file, ast_ctx(proto).line,
4432 cvq_to_str(proto->cvq));
4435 av = (var ->expression.flags & AST_FLAG_NORETURN);
4436 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4438 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4439 "`%s` declared with different attributes%s\n"
4440 " -> previous declaration here: %s:%i",
4441 var->name, (av ? ": noreturn" : ""),
4442 ast_ctx(proto).file, ast_ctx(proto).line,
4443 (ao ? ": noreturn" : ""));
4448 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)
4452 ast_expression *old;
4456 ast_value *basetype = NULL;
4458 bool isparam = false;
4459 bool isvector = false;
4460 bool cleanvar = true;
4461 bool wasarray = false;
4465 if (!localblock && is_static)
4466 parseerror(parser, "`static` qualifier is not supported in global scope");
4468 /* get the first complete variable */
4469 var = parse_typename(parser, &basetype, cached_typedef);
4472 ast_delete(basetype);
4480 /* Part 0: finish the type */
4481 if (parser->tok == '(') {
4482 if (opts.standard == COMPILER_QCC)
4483 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4484 var = parse_parameter_list(parser, var);
4490 /* we only allow 1-dimensional arrays */
4491 if (parser->tok == '[') {
4493 var = parse_arraysize(parser, var);
4499 if (parser->tok == '(' && wasarray) {
4500 parseerror(parser, "arrays as part of a return type is not supported");
4501 /* we'll still parse the type completely for now */
4503 /* for functions returning functions */
4504 while (parser->tok == '(') {
4505 if (opts.standard == COMPILER_QCC)
4506 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4507 var = parse_parameter_list(parser, var);
4514 var->cvq = qualifier;
4515 var->expression.flags |= qflags;
4516 if (var->expression.flags & AST_FLAG_DEPRECATED)
4517 var->desc = vstring;
4520 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4521 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4522 * is then filled with the previous definition and the parameter-names replaced.
4524 if (!strcmp(var->name, "nil")) {
4525 if (OPTS_FLAG(UNTYPED_NIL)) {
4526 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4527 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4529 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4532 /* Deal with end_sys_ vars */
4534 if (!strcmp(var->name, "end_sys_globals")) {
4536 parser->crc_globals = vec_size(parser->globals);
4539 else if (!strcmp(var->name, "end_sys_fields")) {
4541 parser->crc_fields = vec_size(parser->fields);
4544 if (was_end && var->expression.vtype == TYPE_FIELD) {
4545 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4546 "global '%s' hint should not be a field",
4547 parser_tokval(parser)))
4554 if (!nofields && var->expression.vtype == TYPE_FIELD)
4556 /* deal with field declarations */
4557 old = parser_find_field(parser, var->name);
4559 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4560 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4569 parseerror(parser, "field `%s` already declared here: %s:%i",
4570 var->name, ast_ctx(old).file, ast_ctx(old).line);
4575 if (opts.standard == COMPILER_QCC &&
4576 (old = parser_find_global(parser, var->name)))
4578 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4579 parseerror(parser, "field `%s` already declared here: %s:%i",
4580 var->name, ast_ctx(old).file, ast_ctx(old).line);
4587 /* deal with other globals */
4588 old = parser_find_global(parser, var->name);
4589 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4591 /* This is a function which had a prototype */
4592 if (!ast_istype(old, ast_value)) {
4593 parseerror(parser, "internal error: prototype is not an ast_value");
4597 proto = (ast_value*)old;
4598 proto->desc = var->desc;
4599 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4600 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4602 ast_ctx(proto).file, ast_ctx(proto).line);
4606 /* we need the new parameter-names */
4607 for (i = 0; i < vec_size(proto->expression.params); ++i)
4608 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4609 if (!parser_check_qualifiers(parser, var, proto)) {
4616 proto->expression.flags |= var->expression.flags;
4624 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4625 "global `%s` already declared here: %s:%i",
4626 var->name, ast_ctx(old).file, ast_ctx(old).line))
4631 proto = (ast_value*)old;
4632 if (!ast_istype(old, ast_value)) {
4633 parseerror(parser, "internal error: not an ast_value");
4638 if (!parser_check_qualifiers(parser, var, proto)) {
4643 proto->expression.flags |= var->expression.flags;
4647 if (opts.standard == COMPILER_QCC &&
4648 (old = parser_find_field(parser, var->name)))
4650 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4651 parseerror(parser, "global `%s` already declared here: %s:%i",
4652 var->name, ast_ctx(old).file, ast_ctx(old).line);
4659 else /* it's not a global */
4661 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4662 if (old && !isparam) {
4663 parseerror(parser, "local `%s` already declared here: %s:%i",
4664 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4668 old = parser_find_local(parser, var->name, 0, &isparam);
4669 if (old && isparam) {
4670 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4671 "local `%s` is shadowing a parameter", var->name))
4673 parseerror(parser, "local `%s` already declared here: %s:%i",
4674 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4678 if (opts.standard != COMPILER_GMQCC) {
4686 /* in a noref section we simply bump the usecount */
4687 if (noref || parser->noref)
4691 * Create the global/local, and deal with vector types.
4694 if (var->expression.vtype == TYPE_VECTOR)
4696 else if (var->expression.vtype == TYPE_FIELD &&
4697 var->expression.next->expression.vtype == TYPE_VECTOR)
4701 if (!create_vector_members(var, me)) {
4708 /* deal with global variables, fields, functions */
4709 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4710 var->isfield = true;
4711 vec_push(parser->fields, (ast_expression*)var);
4712 util_htset(parser->htfields, var->name, var);
4714 for (i = 0; i < 3; ++i) {
4715 vec_push(parser->fields, (ast_expression*)me[i]);
4716 util_htset(parser->htfields, me[i]->name, me[i]);
4721 vec_push(parser->globals, (ast_expression*)var);
4722 util_htset(parser->htglobals, var->name, var);
4724 for (i = 0; i < 3; ++i) {
4725 vec_push(parser->globals, (ast_expression*)me[i]);
4726 util_htset(parser->htglobals, me[i]->name, me[i]);
4732 /* a static adds itself to be generated like any other global
4733 * but is added to the local namespace instead
4735 char *defname = NULL;
4736 size_t prefix_len, ln;
4738 ln = strlen(parser->function->name);
4739 vec_append(defname, ln, parser->function->name);
4741 vec_append(defname, 2, "::");
4742 /* remember the length up to here */
4743 prefix_len = vec_size(defname);
4745 /* Add it to the local scope */
4746 util_htset(vec_last(parser->variables), var->name, (void*)var);
4747 /* now rename the global */
4748 ln = strlen(var->name);
4749 vec_append(defname, ln, var->name);
4750 ast_value_set_name(var, defname);
4752 /* push it to the to-be-generated globals */
4753 vec_push(parser->globals, (ast_expression*)var);
4755 /* same game for the vector members */
4757 for (i = 0; i < 3; ++i) {
4758 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4760 vec_shrinkto(defname, prefix_len);
4761 ln = strlen(me[i]->name);
4762 vec_append(defname, ln, me[i]->name);
4763 ast_member_set_name(me[i], defname);
4765 vec_push(parser->globals, (ast_expression*)me[i]);
4770 vec_push(localblock->locals, var);
4771 parser_addlocal(parser, var->name, (ast_expression*)var);
4773 for (i = 0; i < 3; ++i) {
4774 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4775 ast_block_collect(localblock, (ast_expression*)me[i]);
4781 me[0] = me[1] = me[2] = NULL;
4786 if (var->expression.vtype == TYPE_ARRAY) {
4788 snprintf(name, sizeof(name), "%s##SET", var->name);
4789 if (!parser_create_array_setter(parser, var, name))
4791 snprintf(name, sizeof(name), "%s##GET", var->name);
4792 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4795 else if (!localblock && !nofields &&
4796 var->expression.vtype == TYPE_FIELD &&
4797 var->expression.next->expression.vtype == TYPE_ARRAY)
4800 ast_expression *telem;
4802 ast_value *array = (ast_value*)var->expression.next;
4804 if (!ast_istype(var->expression.next, ast_value)) {
4805 parseerror(parser, "internal error: field element type must be an ast_value");
4809 snprintf(name, sizeof(name), "%s##SETF", var->name);
4810 if (!parser_create_array_field_setter(parser, array, name))
4813 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4814 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4815 tfield->expression.next = telem;
4816 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4817 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4825 if (parser->tok == ';') {
4826 ast_delete(basetype);
4827 if (!parser_next(parser)) {
4828 parseerror(parser, "error after variable declaration");
4834 if (parser->tok == ',')
4838 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4841 parseerror(parser, "missing comma or semicolon while parsing variables");
4845 if (localblock && opts.standard == COMPILER_QCC) {
4846 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4847 "initializing expression turns variable `%s` into a constant in this standard",
4854 if (parser->tok != '{') {
4855 if (parser->tok != '=') {
4856 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4860 if (!parser_next(parser)) {
4861 parseerror(parser, "error parsing initializer");
4865 else if (opts.standard == COMPILER_QCC) {
4866 parseerror(parser, "expected '=' before function body in this standard");
4869 if (parser->tok == '#') {
4870 ast_function *func = NULL;
4873 parseerror(parser, "cannot declare builtins within functions");
4876 if (var->expression.vtype != TYPE_FUNCTION) {
4877 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4880 if (!parser_next(parser)) {
4881 parseerror(parser, "expected builtin number");
4884 if (parser->tok != TOKEN_INTCONST) {
4885 parseerror(parser, "builtin number must be an integer constant");
4888 if (parser_token(parser)->constval.i < 0) {
4889 parseerror(parser, "builtin number must be an integer greater than zero");
4893 if (var->hasvalue) {
4894 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4895 "builtin `%s` has already been defined\n"
4896 " -> previous declaration here: %s:%i",
4897 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4901 func = ast_function_new(ast_ctx(var), var->name, var);
4903 parseerror(parser, "failed to allocate function for `%s`", var->name);
4906 vec_push(parser->functions, func);
4908 func->builtin = -parser_token(parser)->constval.i-1;
4911 if (!parser_next(parser)) {
4912 parseerror(parser, "expected comma or semicolon");
4914 ast_function_delete(func);
4915 var->constval.vfunc = NULL;
4919 else if (parser->tok == '{' || parser->tok == '[')
4922 parseerror(parser, "cannot declare functions within functions");
4927 ast_ctx(proto) = parser_ctx(parser);
4929 if (!parse_function_body(parser, var))
4931 ast_delete(basetype);
4932 for (i = 0; i < vec_size(parser->gotos); ++i)
4933 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4934 vec_free(parser->gotos);
4935 vec_free(parser->labels);
4938 ast_expression *cexp;
4941 cexp = parse_expression_leave(parser, true, false);
4946 cval = (ast_value*)cexp;
4947 if (cval != parser->nil &&
4948 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4951 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4955 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4956 qualifier != CV_VAR)
4958 var->cvq = CV_CONST;
4960 if (cval == parser->nil)
4961 var->expression.flags |= AST_FLAG_INITIALIZED;
4964 var->hasvalue = true;
4965 if (cval->expression.vtype == TYPE_STRING)
4966 var->constval.vstring = parser_strdup(cval->constval.vstring);
4967 else if (cval->expression.vtype == TYPE_FIELD)
4968 var->constval.vfield = cval;
4970 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4976 shunt sy = { NULL, NULL };
4979 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4980 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4981 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4982 if (!parser_sy_apply_operator(parser, &sy))
4985 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4986 parseerror(parser, "internal error: leaked operands");
4987 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4997 if (parser->tok == ',') {
4998 if (!parser_next(parser)) {
4999 parseerror(parser, "expected another variable");
5003 if (parser->tok != TOKEN_IDENT) {
5004 parseerror(parser, "expected another variable");
5007 var = ast_value_copy(basetype);
5009 ast_value_set_name(var, parser_tokval(parser));
5010 if (!parser_next(parser)) {
5011 parseerror(parser, "error parsing variable declaration");
5017 if (parser->tok != ';') {
5018 parseerror(parser, "missing semicolon after variables");
5022 if (!parser_next(parser)) {
5023 parseerror(parser, "parse error after variable declaration");
5027 ast_delete(basetype);
5031 if (cleanvar && var)
5033 ast_delete(basetype);
5037 ast_delete(basetype);
5038 if (cleanvar && var)
5040 if (me[0]) ast_member_delete(me[0]);
5041 if (me[1]) ast_member_delete(me[1]);
5042 if (me[2]) ast_member_delete(me[2]);
5046 static bool parser_global_statement(parser_t *parser)
5050 bool is_static = false;
5051 uint32_t qflags = 0;
5052 ast_value *istype = NULL;
5053 char *vstring = NULL;
5055 if (parser->tok == TOKEN_IDENT)
5056 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5058 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5060 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5062 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5064 if (cvq == CV_WRONG)
5066 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5068 else if (parser->tok == TOKEN_KEYWORD)
5070 if (!strcmp(parser_tokval(parser), "typedef")) {
5071 if (!parser_next(parser)) {
5072 parseerror(parser, "expected type definition after 'typedef'");
5075 return parse_typedef(parser);
5077 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5080 else if (parser->tok == '#')
5082 return parse_pragma(parser);
5084 else if (parser->tok == '$')
5086 if (!parser_next(parser)) {
5087 parseerror(parser, "parse error");
5093 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5099 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5101 return util_crc16(old, str, strlen(str));
5104 static void progdefs_crc_file(const char *str)
5106 /* write to progdefs.h here */
5110 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5112 old = progdefs_crc_sum(old, str);
5113 progdefs_crc_file(str);
5117 static void generate_checksum(parser_t *parser)
5119 uint16_t crc = 0xFFFF;
5123 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5124 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5126 progdefs_crc_file("\tint\tpad;\n");
5127 progdefs_crc_file("\tint\tofs_return[3];\n");
5128 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5129 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5130 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5131 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5132 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5133 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5134 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5135 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5137 for (i = 0; i < parser->crc_globals; ++i) {
5138 if (!ast_istype(parser->globals[i], ast_value))
5140 value = (ast_value*)(parser->globals[i]);
5141 switch (value->expression.vtype) {
5142 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5143 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5144 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5145 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5147 crc = progdefs_crc_both(crc, "\tint\t");
5150 crc = progdefs_crc_both(crc, value->name);
5151 crc = progdefs_crc_both(crc, ";\n");
5153 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5154 for (i = 0; i < parser->crc_fields; ++i) {
5155 if (!ast_istype(parser->fields[i], ast_value))
5157 value = (ast_value*)(parser->fields[i]);
5158 switch (value->expression.next->expression.vtype) {
5159 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5160 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5161 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5162 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5164 crc = progdefs_crc_both(crc, "\tint\t");
5167 crc = progdefs_crc_both(crc, value->name);
5168 crc = progdefs_crc_both(crc, ";\n");
5170 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5175 static parser_t *parser;
5182 parser = (parser_t*)mem_a(sizeof(parser_t));
5186 memset(parser, 0, sizeof(*parser));
5188 for (i = 0; i < operator_count; ++i) {
5189 if (operators[i].id == opid1('=')) {
5190 parser->assign_op = operators+i;
5194 if (!parser->assign_op) {
5195 printf("internal error: initializing parser: failed to find assign operator\n");
5200 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5201 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5202 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5203 vec_push(parser->_blocktypedefs, 0);
5205 empty_ctx.file = "<internal>";
5207 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5208 parser->nil->cvq = CV_CONST;
5209 if (OPTS_FLAG(UNTYPED_NIL))
5210 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5214 bool parser_compile()
5216 /* initial lexer/parser state */
5217 parser->lex->flags.noops = true;
5219 if (parser_next(parser))
5221 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5223 if (!parser_global_statement(parser)) {
5224 if (parser->tok == TOKEN_EOF)
5225 parseerror(parser, "unexpected eof");
5226 else if (compile_errors)
5227 parseerror(parser, "there have been errors, bailing out");
5228 lex_close(parser->lex);
5234 parseerror(parser, "parse error");
5235 lex_close(parser->lex);
5240 lex_close(parser->lex);
5243 return !compile_errors;
5246 bool parser_compile_file(const char *filename)
5248 parser->lex = lex_open(filename);
5250 con_err("failed to open file \"%s\"\n", filename);
5253 return parser_compile();
5256 bool parser_compile_string(const char *name, const char *str, size_t len)
5258 parser->lex = lex_open_string(str, len, name);
5260 con_err("failed to create lexer for string \"%s\"\n", name);
5263 return parser_compile();
5266 void parser_cleanup()
5269 for (i = 0; i < vec_size(parser->accessors); ++i) {
5270 ast_delete(parser->accessors[i]->constval.vfunc);
5271 parser->accessors[i]->constval.vfunc = NULL;
5272 ast_delete(parser->accessors[i]);
5274 for (i = 0; i < vec_size(parser->functions); ++i) {
5275 ast_delete(parser->functions[i]);
5277 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5278 ast_delete(parser->imm_vector[i]);
5280 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5281 ast_delete(parser->imm_string[i]);
5283 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5284 ast_delete(parser->imm_float[i]);
5286 for (i = 0; i < vec_size(parser->fields); ++i) {
5287 ast_delete(parser->fields[i]);
5289 for (i = 0; i < vec_size(parser->globals); ++i) {
5290 ast_delete(parser->globals[i]);
5292 vec_free(parser->accessors);
5293 vec_free(parser->functions);
5294 vec_free(parser->imm_vector);
5295 vec_free(parser->imm_string);
5296 vec_free(parser->imm_float);
5297 vec_free(parser->globals);
5298 vec_free(parser->fields);
5300 for (i = 0; i < vec_size(parser->variables); ++i)
5301 util_htdel(parser->variables[i]);
5302 vec_free(parser->variables);
5303 vec_free(parser->_blocklocals);
5304 vec_free(parser->_locals);
5306 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5307 ast_delete(parser->_typedefs[i]);
5308 vec_free(parser->_typedefs);
5309 for (i = 0; i < vec_size(parser->typedefs); ++i)
5310 util_htdel(parser->typedefs[i]);
5311 vec_free(parser->typedefs);
5312 vec_free(parser->_blocktypedefs);
5314 vec_free(parser->_block_ctx);
5316 vec_free(parser->labels);
5317 vec_free(parser->gotos);
5318 vec_free(parser->breaks);
5319 vec_free(parser->continues);
5321 ast_value_delete(parser->nil);
5326 bool parser_finish(const char *output)
5332 if (compile_errors) {
5333 con_out("*** there were compile errors\n");
5337 ir = ir_builder_new("gmqcc_out");
5339 con_out("failed to allocate builder\n");
5343 for (i = 0; i < vec_size(parser->fields); ++i) {
5346 if (!ast_istype(parser->fields[i], ast_value))
5348 field = (ast_value*)parser->fields[i];
5349 hasvalue = field->hasvalue;
5350 field->hasvalue = false;
5351 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5352 con_out("failed to generate field %s\n", field->name);
5353 ir_builder_delete(ir);
5358 ast_expression *subtype;
5359 field->hasvalue = true;
5360 subtype = field->expression.next;
5361 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5362 if (subtype->expression.vtype == TYPE_FIELD)
5363 ifld->fieldtype = subtype->expression.next->expression.vtype;
5364 else if (subtype->expression.vtype == TYPE_FUNCTION)
5365 ifld->outtype = subtype->expression.next->expression.vtype;
5366 (void)!ir_value_set_field(field->ir_v, ifld);
5369 for (i = 0; i < vec_size(parser->globals); ++i) {
5371 if (!ast_istype(parser->globals[i], ast_value))
5373 asvalue = (ast_value*)(parser->globals[i]);
5374 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5375 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5376 "unused global: `%s`", asvalue->name);
5378 if (!ast_global_codegen(asvalue, ir, false)) {
5379 con_out("failed to generate global %s\n", asvalue->name);
5380 ir_builder_delete(ir);
5384 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5385 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5386 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5387 ir_builder_delete(ir);
5391 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5392 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5393 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5394 ir_builder_delete(ir);
5398 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5399 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5400 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5401 ir_builder_delete(ir);
5405 for (i = 0; i < vec_size(parser->globals); ++i) {
5407 if (!ast_istype(parser->globals[i], ast_value))
5409 asvalue = (ast_value*)(parser->globals[i]);
5410 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5412 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5413 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5414 "uninitialized constant: `%s`",
5416 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5417 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5418 "uninitialized global: `%s`",
5421 if (!ast_generate_accessors(asvalue, ir)) {
5422 ir_builder_delete(ir);
5426 for (i = 0; i < vec_size(parser->fields); ++i) {
5428 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5430 if (!ast_istype((ast_expression*)asvalue, ast_value))
5432 if (asvalue->expression.vtype != TYPE_ARRAY)
5434 if (!ast_generate_accessors(asvalue, ir)) {
5435 ir_builder_delete(ir);
5439 for (i = 0; i < vec_size(parser->functions); ++i) {
5440 if (!ast_function_codegen(parser->functions[i], ir)) {
5441 con_out("failed to generate function %s\n", parser->functions[i]->name);
5442 ir_builder_delete(ir);
5447 ir_builder_dump(ir, con_out);
5448 for (i = 0; i < vec_size(parser->functions); ++i) {
5449 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5450 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5451 ir_builder_delete(ir);
5456 if (compile_Werrors) {
5457 con_out("*** there were warnings treated as errors\n");
5458 compile_show_werrors();
5464 ir_builder_dump(ir, con_out);
5466 generate_checksum(parser);
5468 if (!ir_builder_generate(ir, output)) {
5469 con_out("*** failed to generate output file\n");
5470 ir_builder_delete(ir);
5475 ir_builder_delete(ir);