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 128
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_float_neg_one;
56 ast_value *imm_vector_zero;
59 ast_value *reserved_version;
64 ast_function *function;
66 /* All the labels the function defined...
67 * Should they be in ast_function instead?
72 const char **continues;
74 /* A list of hashtables for each scope */
80 /* same as above but for the spelling corrector */
81 correct_trie_t **correct_variables;
82 size_t ***correct_variables_score; /* vector of vector of size_t* */
84 /* not to be used directly, we use the hash table */
85 ast_expression **_locals;
87 ast_value **_typedefs;
88 size_t *_blocktypedefs;
91 /* we store the '=' operator info */
92 const oper_info *assign_op;
95 ast_value *const_vec[3];
100 /* collected information */
101 size_t max_param_count;
104 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
106 static void parser_enterblock(parser_t *parser);
107 static bool parser_leaveblock(parser_t *parser);
108 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
109 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
110 static bool parse_typedef(parser_t *parser);
111 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);
112 static ast_block* parse_block(parser_t *parser);
113 static bool parse_block_into(parser_t *parser, ast_block *block);
114 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
115 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
116 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
117 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
118 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
119 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
120 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
122 static void parseerror(parser_t *parser, const char *fmt, ...)
126 vcompile_error(parser->lex->tok.ctx, fmt, ap);
130 /* returns true if it counts as an error */
131 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
136 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
141 /**********************************************************************
142 * some maths used for constant folding
145 vector vec3_add(vector a, vector b)
154 vector vec3_sub(vector a, vector b)
163 qcfloat vec3_mulvv(vector a, vector b)
165 return (a.x * b.x + a.y * b.y + a.z * b.z);
168 vector vec3_mulvf(vector a, float b)
177 /**********************************************************************
181 bool parser_next(parser_t *parser)
183 /* lex_do kills the previous token */
184 parser->tok = lex_do(parser->lex);
185 if (parser->tok == TOKEN_EOF)
187 if (parser->tok >= TOKEN_ERROR) {
188 parseerror(parser, "lex error");
194 #define parser_tokval(p) ((p)->lex->tok.value)
195 #define parser_token(p) (&((p)->lex->tok))
196 #define parser_ctx(p) ((p)->lex->tok.ctx)
198 static ast_value* parser_const_float(parser_t *parser, double d)
203 for (i = 0; i < vec_size(parser->imm_float); ++i) {
204 const double compare = parser->imm_float[i]->constval.vfloat;
205 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
206 return parser->imm_float[i];
209 ctx = parser_ctx(parser);
211 memset(&ctx, 0, sizeof(ctx));
213 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
215 out->hasvalue = true;
216 out->constval.vfloat = d;
217 vec_push(parser->imm_float, out);
221 static ast_value* parser_const_float_0(parser_t *parser)
223 if (!parser->imm_float_zero)
224 parser->imm_float_zero = parser_const_float(parser, 0);
225 return parser->imm_float_zero;
228 static ast_value* parser_const_float_neg1(parser_t *parser) {
229 if (!parser->imm_float_neg_one)
230 parser->imm_float_neg_one = parser_const_float(parser, -1);
231 return parser->imm_float_neg_one;
234 static ast_value* parser_const_float_1(parser_t *parser)
236 if (!parser->imm_float_one)
237 parser->imm_float_one = parser_const_float(parser, 1);
238 return parser->imm_float_one;
241 static char *parser_strdup(const char *str)
244 /* actually dup empty strings */
245 char *out = (char*)mem_a(1);
249 return util_strdup(str);
252 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
256 for (i = 0; i < vec_size(parser->imm_string); ++i) {
257 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
258 return parser->imm_string[i];
262 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
263 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
265 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
267 out->hasvalue = true;
268 out->constval.vstring = parser_strdup(str);
269 vec_push(parser->imm_string, out);
273 static ast_value* parser_const_vector(parser_t *parser, vector v)
277 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
278 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
279 return parser->imm_vector[i];
281 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
283 out->hasvalue = true;
284 out->constval.vvec = v;
285 vec_push(parser->imm_vector, out);
289 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
295 return parser_const_vector(parser, v);
298 static ast_value* parser_const_vector_0(parser_t *parser)
300 if (!parser->imm_vector_zero)
301 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
302 return parser->imm_vector_zero;
305 static ast_expression* parser_find_field(parser_t *parser, const char *name)
307 return ( ast_expression*)util_htget(parser->htfields, name);
310 static ast_expression* parser_find_label(parser_t *parser, const char *name)
313 for(i = 0; i < vec_size(parser->labels); i++)
314 if (!strcmp(parser->labels[i]->name, name))
315 return (ast_expression*)parser->labels[i];
319 static ast_expression* parser_find_global(parser_t *parser, const char *name)
321 return (ast_expression*)util_htget(parser->htglobals, name);
324 static ast_expression* parser_find_param(parser_t *parser, const char *name)
328 if (!parser->function)
330 fun = parser->function->vtype;
331 for (i = 0; i < vec_size(fun->expression.params); ++i) {
332 if (!strcmp(fun->expression.params[i]->name, name))
333 return (ast_expression*)(fun->expression.params[i]);
338 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
343 hash = util_hthash(parser->htglobals, name);
346 for (i = vec_size(parser->variables); i > upto;) {
348 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
352 return parser_find_param(parser, name);
355 static ast_expression* parser_find_var(parser_t *parser, const char *name)
359 v = parser_find_local(parser, name, 0, &dummy);
360 if (!v) v = parser_find_global(parser, name);
364 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
368 hash = util_hthash(parser->typedefs[0], name);
370 for (i = vec_size(parser->typedefs); i > upto;) {
372 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
380 size_t etype; /* 0 = expression, others are operators */
384 ast_block *block; /* for commas and function calls */
403 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
414 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
418 e.out = (ast_expression*)v;
425 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
427 e.etype = 1 + (op - operators);
436 static sy_elem syparen(lex_ctx ctx, size_t off) {
447 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
448 * so we need to rotate it to become ent.(foo[n]).
450 static bool rotate_entfield_array_index_nodes(ast_expression **out)
452 ast_array_index *index, *oldindex;
453 ast_entfield *entfield;
457 ast_expression *entity;
459 lex_ctx ctx = ast_ctx(*out);
461 if (!ast_istype(*out, ast_array_index))
463 index = (ast_array_index*)*out;
465 if (!ast_istype(index->array, ast_entfield))
467 entfield = (ast_entfield*)index->array;
469 if (!ast_istype(entfield->field, ast_value))
471 field = (ast_value*)entfield->field;
474 entity = entfield->entity;
478 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
479 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
480 *out = (ast_expression*)entfield;
482 oldindex->array = NULL;
483 oldindex->index = NULL;
484 ast_delete(oldindex);
489 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
491 switch (v->expression.vtype) {
493 return !!v->constval.vfloat;
495 return !!v->constval.vint;
497 if (OPTS_FLAG(CORRECT_LOGIC))
498 return v->constval.vvec.x &&
499 v->constval.vvec.y &&
502 return !!(v->constval.vvec.x);
504 if (!v->constval.vstring)
506 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
508 return !!v->constval.vstring[0];
510 compile_error(ctx, "internal error: immediate_is_true on invalid type");
511 return !!v->constval.vfunc;
515 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
519 ast_expression *out = NULL;
520 ast_expression *exprs[3];
521 ast_block *blocks[3];
522 ast_value *asvalue[3];
523 ast_binstore *asbinstore;
524 size_t i, assignop, addop, subop;
525 qcint generated_op = 0;
530 if (!vec_size(sy->ops)) {
531 parseerror(parser, "internal error: missing operator");
535 if (vec_last(sy->ops).isparen) {
536 parseerror(parser, "unmatched parenthesis");
540 op = &operators[vec_last(sy->ops).etype - 1];
541 ctx = vec_last(sy->ops).ctx;
543 if (vec_size(sy->out) < op->operands) {
544 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
545 op->op, (int)op->id);
549 vec_shrinkby(sy->ops, 1);
551 /* op(:?) has no input and no output */
555 vec_shrinkby(sy->out, op->operands);
556 for (i = 0; i < op->operands; ++i) {
557 exprs[i] = sy->out[vec_size(sy->out)+i].out;
558 blocks[i] = sy->out[vec_size(sy->out)+i].block;
559 asvalue[i] = (ast_value*)exprs[i];
561 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
562 !(i != 0 && op->id == opid2('?',':')) &&
563 !(i == 1 && op->id == opid1('.')))
565 if (ast_istype(exprs[i], ast_label))
566 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
568 compile_error(ast_ctx(exprs[i]), "not an expression");
569 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
573 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
574 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
578 #define NotSameType(T) \
579 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
580 exprs[0]->expression.vtype != T)
581 #define CanConstFold1(A) \
582 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
583 (A)->expression.vtype != TYPE_FUNCTION)
584 #define CanConstFold(A, B) \
585 (CanConstFold1(A) && CanConstFold1(B))
586 #define ConstV(i) (asvalue[(i)]->constval.vvec)
587 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
588 #define ConstS(i) (asvalue[(i)]->constval.vstring)
592 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
596 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
597 exprs[1]->expression.vtype == TYPE_NOEXPR)
599 if (exprs[1] == (ast_expression*)parser->const_vec[0])
600 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
601 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
602 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
603 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
604 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
606 compile_error(ctx, "access to invalid vector component");
610 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
611 if (exprs[1]->expression.vtype != TYPE_FIELD) {
612 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
615 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
617 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
618 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
622 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
628 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
629 !(exprs[0]->expression.vtype == TYPE_FIELD &&
630 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
632 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
633 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
636 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
637 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
638 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
641 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
642 if (rotate_entfield_array_index_nodes(&out))
645 /* This is not broken in fteqcc anymore */
646 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
647 /* this error doesn't need to make us bail out */
648 (void)!parsewarning(parser, WARN_EXTENSIONS,
649 "accessing array-field members of an entity without parenthesis\n"
650 " -> this is an extension from -std=gmqcc");
657 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
658 vec_push(sy->out, syexp(ctx, exprs[0]));
659 vec_push(sy->out, syexp(ctx, exprs[1]));
660 vec_last(sy->argc)++;
664 if (!ast_block_add_expr(blocks[0], exprs[1]))
667 blocks[0] = ast_block_new(ctx);
668 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
669 !ast_block_add_expr(blocks[0], exprs[1]))
674 ast_block_set_type(blocks[0], exprs[1]);
676 vec_push(sy->out, syblock(ctx, blocks[0]));
683 switch (exprs[0]->expression.vtype) {
685 if (CanConstFold1(exprs[0]))
686 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
688 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
689 (ast_expression*)parser_const_float_0(parser),
693 if (CanConstFold1(exprs[0]))
694 out = (ast_expression*)parser_const_vector_f(parser,
695 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
697 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
698 (ast_expression*)parser_const_vector_0(parser),
702 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
703 type_name[exprs[0]->expression.vtype]);
709 switch (exprs[0]->expression.vtype) {
711 if (CanConstFold1(exprs[0]))
712 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
714 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
717 if (CanConstFold1(exprs[0]))
718 out = (ast_expression*)parser_const_float(parser,
719 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
721 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
724 if (CanConstFold1(exprs[0])) {
725 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
726 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
728 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
730 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
731 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
733 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
736 /* we don't constant-fold NOT for these types */
738 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
741 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
744 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
745 type_name[exprs[0]->expression.vtype]);
751 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
752 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
754 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
755 type_name[exprs[0]->expression.vtype],
756 type_name[exprs[1]->expression.vtype]);
759 switch (exprs[0]->expression.vtype) {
761 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
766 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
769 if (CanConstFold(exprs[0], exprs[1]))
770 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
772 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
775 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
776 type_name[exprs[0]->expression.vtype],
777 type_name[exprs[1]->expression.vtype]);
782 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
783 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
785 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
786 type_name[exprs[1]->expression.vtype],
787 type_name[exprs[0]->expression.vtype]);
790 switch (exprs[0]->expression.vtype) {
792 if (CanConstFold(exprs[0], exprs[1]))
793 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
795 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
798 if (CanConstFold(exprs[0], exprs[1]))
799 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
801 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
804 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
805 type_name[exprs[1]->expression.vtype],
806 type_name[exprs[0]->expression.vtype]);
811 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
812 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
813 exprs[1]->expression.vtype == TYPE_FLOAT) &&
814 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
815 exprs[0]->expression.vtype == TYPE_FLOAT)
818 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
819 type_name[exprs[1]->expression.vtype],
820 type_name[exprs[0]->expression.vtype]);
823 switch (exprs[0]->expression.vtype) {
825 if (exprs[1]->expression.vtype == TYPE_VECTOR)
827 if (CanConstFold(exprs[0], exprs[1]))
828 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
830 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
834 if (CanConstFold(exprs[0], exprs[1]))
835 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
837 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
841 if (exprs[1]->expression.vtype == TYPE_FLOAT)
843 if (CanConstFold(exprs[0], exprs[1]))
844 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
846 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
850 if (CanConstFold(exprs[0], exprs[1]))
851 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
852 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
853 vector vec = ConstV(0);
854 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
855 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
856 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
857 out->expression.node.keep = false;
858 ((ast_member*)out)->rvalue = true;
860 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
862 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
863 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
864 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
865 out->expression.node.keep = false;
866 ((ast_member*)out)->rvalue = true;
868 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
870 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
871 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
872 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
873 out->expression.node.keep = false;
874 ((ast_member*)out)->rvalue = true;
876 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
879 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
881 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
882 vector vec = ConstV(1);
883 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
884 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
885 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
886 out->expression.node.keep = false;
887 ((ast_member*)out)->rvalue = true;
889 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
891 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
892 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
893 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
894 out->expression.node.keep = false;
895 ((ast_member*)out)->rvalue = true;
897 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
899 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
900 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
901 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
902 out->expression.node.keep = false;
903 ((ast_member*)out)->rvalue = true;
905 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
908 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
911 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
915 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
916 type_name[exprs[1]->expression.vtype],
917 type_name[exprs[0]->expression.vtype]);
922 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
923 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
924 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
928 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
929 if (CanConstFold(exprs[0], exprs[1]))
930 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
932 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
934 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
935 if (CanConstFold(exprs[0], exprs[1]))
936 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
938 if (CanConstFold1(exprs[1])) {
939 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
941 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
942 (ast_expression*)parser_const_float_1(parser),
946 compile_error(ctx, "internal error: failed to generate division");
949 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
954 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
955 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
956 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
962 compile_error(ctx, "qc does not have a modulo operator");
966 if (NotSameType(TYPE_FLOAT)) {
967 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
968 type_name[exprs[0]->expression.vtype],
969 type_name[exprs[1]->expression.vtype]);
972 if (CanConstFold(exprs[0], exprs[1]))
973 out = (ast_expression*)parser_const_float(parser,
974 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
975 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
977 out = (ast_expression*)ast_binary_new(ctx,
978 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
982 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
987 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
988 if (op->id == opid2('<','<'))
989 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
991 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
994 case opid3('<','<','='):
995 case opid3('>','>','='):
996 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1000 generated_op += 1; /* INSTR_OR */
1001 case opid2('&','&'):
1002 generated_op += INSTR_AND;
1003 if (CanConstFold(exprs[0], exprs[1]))
1005 if (OPTS_FLAG(PERL_LOGIC)) {
1006 if (immediate_is_true(ctx, asvalue[0]))
1010 out = (ast_expression*)parser_const_float(parser,
1011 ( (generated_op == INSTR_OR)
1012 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1013 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1018 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1019 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1020 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1021 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1024 for (i = 0; i < 2; ++i) {
1025 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1026 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1028 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1030 exprs[i] = out; out = NULL;
1031 if (OPTS_FLAG(PERL_LOGIC)) {
1032 /* here we want to keep the right expressions' type */
1036 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1037 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1039 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1041 exprs[i] = out; out = NULL;
1042 if (OPTS_FLAG(PERL_LOGIC)) {
1043 /* here we want to keep the right expressions' type */
1048 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1052 case opid2('?',':'):
1053 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1054 compile_error(ctx, "mismatched parenthesis/ternary");
1058 if (!ast_compare_type(exprs[1], exprs[2])) {
1059 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1060 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1061 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1064 if (CanConstFold1(exprs[0]))
1065 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1067 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1070 case opid3('<','=','>'): /* -1, 0, or 1 */
1071 if (NotSameType(TYPE_FLOAT)) {
1072 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1073 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1074 compile_error(ctx, "invalid types used in comparision: %s and %s",
1080 if (CanConstFold(exprs[0], exprs[1])) {
1081 if (ConstF(0) < ConstF(1))
1082 out = (ast_expression*)parser_const_float_neg1(parser);
1083 else if (ConstF(0) == ConstF(1))
1084 out = (ast_expression*)parser_const_float_0(parser);
1085 else if (ConstF(0) > ConstF(1))
1086 out = (ast_expression*)parser_const_float_1(parser);
1089 out = (ast_expression*)ast_ternary_new(ctx,
1090 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1093 (ast_expression*)parser_const_float_neg1(parser),
1097 (ast_expression*)ast_ternary_new(ctx,
1098 (ast_expression*)ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]),
1101 (ast_expression*)parser_const_float_0(parser),
1106 (ast_expression*)parser_const_float_1(parser)
1116 generated_op += 1; /* INSTR_GT */
1118 generated_op += 1; /* INSTR_LT */
1119 case opid2('>', '='):
1120 generated_op += 1; /* INSTR_GE */
1121 case opid2('<', '='):
1122 generated_op += INSTR_LE;
1123 if (NotSameType(TYPE_FLOAT)) {
1124 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1125 type_name[exprs[0]->expression.vtype],
1126 type_name[exprs[1]->expression.vtype]);
1129 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1131 case opid2('!', '='):
1132 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1133 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1134 type_name[exprs[0]->expression.vtype],
1135 type_name[exprs[1]->expression.vtype]);
1138 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1140 case opid2('=', '='):
1141 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1142 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1143 type_name[exprs[0]->expression.vtype],
1144 type_name[exprs[1]->expression.vtype]);
1147 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1151 if (ast_istype(exprs[0], ast_entfield)) {
1152 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1153 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1154 exprs[0]->expression.vtype == TYPE_FIELD &&
1155 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1157 assignop = type_storep_instr[TYPE_VECTOR];
1160 assignop = type_storep_instr[exprs[0]->expression.vtype];
1161 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1163 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1164 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1165 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1166 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1167 exprs[1]->expression.vtype == TYPE_FUNCTION)
1169 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1170 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1173 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1178 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1179 exprs[0]->expression.vtype == TYPE_FIELD &&
1180 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1182 assignop = type_store_instr[TYPE_VECTOR];
1185 assignop = type_store_instr[exprs[0]->expression.vtype];
1188 if (assignop == VINSTR_END) {
1189 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1190 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1191 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1193 else if (!ast_compare_type(exprs[0], exprs[1]))
1195 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1196 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1197 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1198 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1199 exprs[1]->expression.vtype == TYPE_FUNCTION)
1201 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1202 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1205 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1208 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1209 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1211 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1213 case opid3('+','+','P'):
1214 case opid3('-','-','P'):
1216 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1217 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1218 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1221 if (op->id == opid3('+','+','P'))
1222 addop = INSTR_ADD_F;
1224 addop = INSTR_SUB_F;
1225 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1226 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1228 if (ast_istype(exprs[0], ast_entfield)) {
1229 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1231 (ast_expression*)parser_const_float_1(parser));
1233 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1235 (ast_expression*)parser_const_float_1(parser));
1238 case opid3('S','+','+'):
1239 case opid3('S','-','-'):
1241 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1242 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1243 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1246 if (op->id == opid3('S','+','+')) {
1247 addop = INSTR_ADD_F;
1248 subop = INSTR_SUB_F;
1250 addop = INSTR_SUB_F;
1251 subop = INSTR_ADD_F;
1253 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1254 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1256 if (ast_istype(exprs[0], ast_entfield)) {
1257 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1259 (ast_expression*)parser_const_float_1(parser));
1261 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1263 (ast_expression*)parser_const_float_1(parser));
1267 out = (ast_expression*)ast_binary_new(ctx, subop,
1269 (ast_expression*)parser_const_float_1(parser));
1271 case opid2('+','='):
1272 case opid2('-','='):
1273 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1274 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1276 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1277 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1278 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1282 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1283 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1285 if (ast_istype(exprs[0], ast_entfield))
1286 assignop = type_storep_instr[exprs[0]->expression.vtype];
1288 assignop = type_store_instr[exprs[0]->expression.vtype];
1289 switch (exprs[0]->expression.vtype) {
1291 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1292 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1293 exprs[0], exprs[1]);
1296 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1297 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1298 exprs[0], exprs[1]);
1301 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1302 type_name[exprs[0]->expression.vtype],
1303 type_name[exprs[1]->expression.vtype]);
1307 case opid2('*','='):
1308 case opid2('/','='):
1309 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1310 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1311 exprs[0]->expression.vtype == TYPE_VECTOR))
1313 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1314 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1315 compile_error(ctx, "invalid types used in expression: %s and %s",
1319 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1320 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1322 if (ast_istype(exprs[0], ast_entfield))
1323 assignop = type_storep_instr[exprs[0]->expression.vtype];
1325 assignop = type_store_instr[exprs[0]->expression.vtype];
1326 switch (exprs[0]->expression.vtype) {
1328 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1329 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1330 exprs[0], exprs[1]);
1333 if (op->id == opid2('*','=')) {
1334 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1335 exprs[0], exprs[1]);
1337 /* there's no DIV_VF */
1338 if (CanConstFold1(exprs[1])) {
1339 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1341 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1342 (ast_expression*)parser_const_float_1(parser),
1346 compile_error(ctx, "internal error: failed to generate division");
1349 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1354 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1355 type_name[exprs[0]->expression.vtype],
1356 type_name[exprs[1]->expression.vtype]);
1360 case opid2('&','='):
1361 case opid2('|','='):
1362 if (NotSameType(TYPE_FLOAT)) {
1363 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1364 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1365 compile_error(ctx, "invalid types used in expression: %s and %s",
1369 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1370 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1372 if (ast_istype(exprs[0], ast_entfield))
1373 assignop = type_storep_instr[exprs[0]->expression.vtype];
1375 assignop = type_store_instr[exprs[0]->expression.vtype];
1376 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1377 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1378 exprs[0], exprs[1]);
1380 case opid3('&','~','='):
1381 /* This is like: a &= ~(b);
1382 * But QC has no bitwise-not, so we implement it as
1385 if (NotSameType(TYPE_FLOAT)) {
1386 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1387 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1388 compile_error(ctx, "invalid types used in expression: %s and %s",
1392 if (ast_istype(exprs[0], ast_entfield))
1393 assignop = type_storep_instr[exprs[0]->expression.vtype];
1395 assignop = type_store_instr[exprs[0]->expression.vtype];
1396 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1399 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1400 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1402 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1403 asbinstore->keep_dest = true;
1404 out = (ast_expression*)asbinstore;
1407 case opid2('~', 'P'):
1408 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1409 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1410 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1414 if(CanConstFold1(exprs[0]))
1415 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1417 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1423 compile_error(ctx, "failed to apply operator %s", op->op);
1427 vec_push(sy->out, syexp(ctx, out));
1431 static bool parser_close_call(parser_t *parser, shunt *sy)
1433 /* was a function call */
1434 ast_expression *fun;
1435 ast_value *funval = NULL;
1439 size_t paramcount, i;
1441 fid = vec_last(sy->ops).off;
1442 vec_shrinkby(sy->ops, 1);
1444 /* out[fid] is the function
1445 * everything above is parameters...
1447 if (!vec_size(sy->argc)) {
1448 parseerror(parser, "internal error: no argument counter available");
1452 paramcount = vec_last(sy->argc);
1455 if (vec_size(sy->out) < fid) {
1456 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1457 (unsigned long)vec_size(sy->out),
1459 (unsigned long)paramcount);
1463 fun = sy->out[fid].out;
1465 if (fun == intrinsic_debug_typestring) {
1467 if (fid+2 != vec_size(sy->out) ||
1468 vec_last(sy->out).block)
1470 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1473 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1474 ast_unref(vec_last(sy->out).out);
1475 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1476 (ast_expression*)parser_const_string(parser, ty, false));
1477 vec_shrinkby(sy->out, 1);
1481 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1485 if (fid+1 < vec_size(sy->out))
1488 if (fid+1 + paramcount != vec_size(sy->out)) {
1489 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1490 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1494 for (i = 0; i < paramcount; ++i)
1495 vec_push(call->params, sy->out[fid+1 + i].out);
1496 vec_shrinkby(sy->out, paramcount);
1497 (void)!ast_call_check_types(call);
1498 if (parser->max_param_count < paramcount)
1499 parser->max_param_count = paramcount;
1501 if (ast_istype(fun, ast_value)) {
1502 funval = (ast_value*)fun;
1503 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1504 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1506 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1510 /* overwrite fid, the function, with a call */
1511 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1513 if (fun->expression.vtype != TYPE_FUNCTION) {
1514 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1518 if (!fun->expression.next) {
1519 parseerror(parser, "could not determine function return type");
1522 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1524 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1526 return !parsewarning(parser, WARN_DEPRECATED,
1527 "call to function (which is marked deprecated)\n",
1528 "-> it has been declared here: %s:%i",
1529 ast_ctx(fun).file, ast_ctx(fun).line);
1532 return !parsewarning(parser, WARN_DEPRECATED,
1533 "call to `%s` (which is marked deprecated)\n"
1534 "-> `%s` declared here: %s:%i",
1535 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1537 return !parsewarning(parser, WARN_DEPRECATED,
1538 "call to `%s` (deprecated: %s)\n"
1539 "-> `%s` declared here: %s:%i",
1540 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1544 if (vec_size(fun->expression.params) != paramcount &&
1545 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1546 vec_size(fun->expression.params) < paramcount))
1548 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1550 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1551 "too %s parameters for call to %s: expected %i, got %i\n"
1552 " -> `%s` has been declared here: %s:%i",
1553 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1554 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1556 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1557 "too %s parameters for function call: expected %i, got %i\n"
1558 " -> it has been declared here: %s:%i",
1559 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1560 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1567 static bool parser_close_paren(parser_t *parser, shunt *sy)
1569 if (!vec_size(sy->ops)) {
1570 parseerror(parser, "unmatched closing paren");
1574 while (vec_size(sy->ops)) {
1575 if (vec_last(sy->ops).isparen) {
1576 if (vec_last(sy->paren) == PAREN_FUNC) {
1578 if (!parser_close_call(parser, sy))
1582 if (vec_last(sy->paren) == PAREN_EXPR) {
1584 if (!vec_size(sy->out)) {
1585 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1586 vec_shrinkby(sy->ops, 1);
1589 vec_shrinkby(sy->ops, 1);
1592 if (vec_last(sy->paren) == PAREN_INDEX) {
1594 /* pop off the parenthesis */
1595 vec_shrinkby(sy->ops, 1);
1596 /* then apply the index operator */
1597 if (!parser_sy_apply_operator(parser, sy))
1601 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1602 vec_last(sy->paren) = PAREN_TERNARY2;
1603 /* pop off the parenthesis */
1604 vec_shrinkby(sy->ops, 1);
1607 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1610 if (!parser_sy_apply_operator(parser, sy))
1616 static void parser_reclassify_token(parser_t *parser)
1619 for (i = 0; i < operator_count; ++i) {
1620 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1621 parser->tok = TOKEN_OPERATOR;
1627 static ast_expression* parse_vararg_do(parser_t *parser)
1629 ast_expression *idx, *out;
1631 ast_value *funtype = parser->function->vtype;
1633 lex_ctx ctx = parser_ctx(parser);
1635 if (!parser_next(parser) || parser->tok != '(') {
1636 parseerror(parser, "expected parameter index and type in parenthesis");
1639 if (!parser_next(parser)) {
1640 parseerror(parser, "error parsing parameter index");
1644 idx = parse_expression_leave(parser, true, false, false);
1648 if (parser->tok != ',') {
1650 parseerror(parser, "expected comma after parameter index");
1654 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1656 parseerror(parser, "expected typename for vararg");
1660 typevar = parse_typename(parser, NULL, NULL);
1666 if (parser->tok != ')') {
1668 ast_delete(typevar);
1669 parseerror(parser, "expected closing paren");
1674 if (!parser_next(parser)) {
1676 ast_delete(typevar);
1677 parseerror(parser, "parse error after vararg");
1682 if (!parser->function->varargs) {
1684 ast_delete(typevar);
1685 parseerror(parser, "function has no variable argument list");
1689 if (funtype->expression.varparam &&
1690 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1694 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1695 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1696 compile_error(ast_ctx(typevar),
1697 "function was declared to take varargs of type `%s`, requested type is: %s",
1701 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1702 ast_type_adopt(out, typevar);
1703 ast_delete(typevar);
1707 static ast_expression* parse_vararg(parser_t *parser)
1709 bool old_noops = parser->lex->flags.noops;
1711 ast_expression *out;
1713 parser->lex->flags.noops = true;
1714 out = parse_vararg_do(parser);
1716 parser->lex->flags.noops = old_noops;
1720 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1722 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1723 parser->tok == TOKEN_IDENT &&
1724 !strcmp(parser_tokval(parser), "_"))
1726 /* a translatable string */
1729 parser->lex->flags.noops = true;
1730 if (!parser_next(parser) || parser->tok != '(') {
1731 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1734 parser->lex->flags.noops = false;
1735 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1736 parseerror(parser, "expected a constant string in translatable-string extension");
1739 val = parser_const_string(parser, parser_tokval(parser), true);
1742 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1744 if (!parser_next(parser) || parser->tok != ')') {
1745 parseerror(parser, "expected closing paren after translatable string");
1750 else if (parser->tok == TOKEN_DOTS)
1753 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1754 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1757 va = parse_vararg(parser);
1760 vec_push(sy->out, syexp(parser_ctx(parser), va));
1763 else if (parser->tok == TOKEN_FLOATCONST) {
1765 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1768 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1771 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1773 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1776 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1779 else if (parser->tok == TOKEN_STRINGCONST) {
1781 val = parser_const_string(parser, parser_tokval(parser), false);
1784 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1787 else if (parser->tok == TOKEN_VECTORCONST) {
1789 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1792 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1795 else if (parser->tok == TOKEN_IDENT)
1797 const char *ctoken = parser_tokval(parser);
1798 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1799 ast_expression *var;
1800 /* a_vector.{x,y,z} */
1801 if (!vec_size(sy->ops) ||
1802 !vec_last(sy->ops).etype ||
1803 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1804 (prev >= intrinsic_debug_typestring &&
1805 prev <= intrinsic_debug_typestring))
1807 /* When adding more intrinsics, fix the above condition */
1810 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1812 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1814 var = parser_find_var(parser, parser_tokval(parser));
1816 var = parser_find_field(parser, parser_tokval(parser));
1818 if (!var && with_labels) {
1819 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1821 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1822 var = (ast_expression*)lbl;
1823 vec_push(parser->labels, lbl);
1828 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1829 var = (ast_expression*)intrinsic_debug_typestring;
1833 char *correct = NULL;
1837 * sometimes people use preprocessing predefs without enabling them
1838 * i've done this thousands of times already myself. Lets check for
1839 * it in the predef table. And diagnose it better :)
1841 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1842 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1843 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1844 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1851 * TODO: determine the best score for the identifier: be it
1852 * a variable, a field.
1854 * We should also consider adding correction tables for
1855 * other things as well.
1857 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1859 correct_init(&corr);
1861 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1862 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1863 if (strcmp(correct, parser_tokval(parser))) {
1865 } else if (correct) {
1870 correct_free(&corr);
1873 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1878 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1884 if (ast_istype(var, ast_value)) {
1885 ((ast_value*)var)->uses++;
1887 else if (ast_istype(var, ast_member)) {
1888 ast_member *mem = (ast_member*)var;
1889 if (ast_istype(mem->owner, ast_value))
1890 ((ast_value*)(mem->owner))->uses++;
1893 vec_push(sy->out, syexp(parser_ctx(parser), var));
1896 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1900 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1902 ast_expression *expr = NULL;
1905 bool wantop = false;
1906 /* only warn once about an assignment in a truth value because the current code
1907 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1909 bool warn_truthvalue = true;
1911 /* count the parens because an if starts with one, so the
1912 * end of a condition is an unmatched closing paren
1916 memset(&sy, 0, sizeof(sy));
1918 parser->lex->flags.noops = false;
1920 parser_reclassify_token(parser);
1924 if (parser->tok == TOKEN_TYPENAME) {
1925 parseerror(parser, "unexpected typename");
1929 if (parser->tok == TOKEN_OPERATOR)
1931 /* classify the operator */
1932 const oper_info *op;
1933 const oper_info *olast = NULL;
1935 for (o = 0; o < operator_count; ++o) {
1936 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1937 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1938 !strcmp(parser_tokval(parser), operators[o].op))
1943 if (o == operator_count) {
1944 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1947 /* found an operator */
1950 /* when declaring variables, a comma starts a new variable */
1951 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1952 /* fixup the token */
1957 /* a colon without a pervious question mark cannot be a ternary */
1958 if (!ternaries && op->id == opid2(':','?')) {
1963 if (op->id == opid1(',')) {
1964 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1965 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1969 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1970 olast = &operators[vec_last(sy.ops).etype-1];
1972 #define IsAssignOp(x) (\
1973 (x) == opid1('=') || \
1974 (x) == opid2('+','=') || \
1975 (x) == opid2('-','=') || \
1976 (x) == opid2('*','=') || \
1977 (x) == opid2('/','=') || \
1978 (x) == opid2('%','=') || \
1979 (x) == opid2('&','=') || \
1980 (x) == opid2('|','=') || \
1981 (x) == opid3('&','~','=') \
1983 if (warn_truthvalue) {
1984 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1985 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1986 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1989 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1990 warn_truthvalue = false;
1995 (op->prec < olast->prec) ||
1996 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1998 if (!parser_sy_apply_operator(parser, &sy))
2000 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2001 olast = &operators[vec_last(sy.ops).etype-1];
2006 if (op->id == opid1('(')) {
2008 size_t sycount = vec_size(sy.out);
2009 /* we expected an operator, this is the function-call operator */
2010 vec_push(sy.paren, PAREN_FUNC);
2011 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2012 vec_push(sy.argc, 0);
2014 vec_push(sy.paren, PAREN_EXPR);
2015 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2018 } else if (op->id == opid1('[')) {
2020 parseerror(parser, "unexpected array subscript");
2023 vec_push(sy.paren, PAREN_INDEX);
2024 /* push both the operator and the paren, this makes life easier */
2025 vec_push(sy.ops, syop(parser_ctx(parser), op));
2026 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2028 } else if (op->id == opid2('?',':')) {
2029 vec_push(sy.ops, syop(parser_ctx(parser), op));
2030 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2033 vec_push(sy.paren, PAREN_TERNARY1);
2034 } else if (op->id == opid2(':','?')) {
2035 if (!vec_size(sy.paren)) {
2036 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2039 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2040 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2043 if (!parser_close_paren(parser, &sy))
2045 vec_push(sy.ops, syop(parser_ctx(parser), op));
2049 vec_push(sy.ops, syop(parser_ctx(parser), op));
2050 wantop = !!(op->flags & OP_SUFFIX);
2053 else if (parser->tok == ')') {
2054 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2055 if (!parser_sy_apply_operator(parser, &sy))
2058 if (!vec_size(sy.paren))
2061 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2062 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2065 if (!parser_close_paren(parser, &sy))
2068 /* must be a function call without parameters */
2069 if (vec_last(sy.paren) != PAREN_FUNC) {
2070 parseerror(parser, "closing paren in invalid position");
2073 if (!parser_close_paren(parser, &sy))
2078 else if (parser->tok == '(') {
2079 parseerror(parser, "internal error: '(' should be classified as operator");
2082 else if (parser->tok == '[') {
2083 parseerror(parser, "internal error: '[' should be classified as operator");
2086 else if (parser->tok == ']') {
2087 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2088 if (!parser_sy_apply_operator(parser, &sy))
2091 if (!vec_size(sy.paren))
2093 if (vec_last(sy.paren) != PAREN_INDEX) {
2094 parseerror(parser, "mismatched parentheses, unexpected ']'");
2097 if (!parser_close_paren(parser, &sy))
2102 if (!parse_sya_operand(parser, &sy, with_labels))
2105 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2106 vec_last(sy.argc)++;
2111 parseerror(parser, "expected operator or end of statement");
2115 if (!parser_next(parser)) {
2118 if (parser->tok == ';' ||
2119 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2120 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2126 while (vec_size(sy.ops)) {
2127 if (!parser_sy_apply_operator(parser, &sy))
2131 parser->lex->flags.noops = true;
2132 if (!vec_size(sy.out)) {
2133 parseerror(parser, "empty expression");
2136 expr = sy.out[0].out;
2139 if (vec_size(sy.paren)) {
2140 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2148 parser->lex->flags.noops = true;
2149 for (i = 0; i < vec_size(sy.out); ++i) {
2151 ast_unref(sy.out[i].out);
2160 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2162 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2165 if (parser->tok != ';') {
2166 parseerror(parser, "semicolon expected after expression");
2170 if (!parser_next(parser)) {
2177 static void parser_enterblock(parser_t *parser)
2179 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2180 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2181 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2182 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2183 vec_push(parser->_block_ctx, parser_ctx(parser));
2186 vec_push(parser->correct_variables, correct_trie_new());
2187 vec_push(parser->correct_variables_score, NULL);
2190 static bool parser_leaveblock(parser_t *parser)
2193 size_t locals, typedefs;
2195 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2196 parseerror(parser, "internal error: parser_leaveblock with no block");
2200 util_htdel(vec_last(parser->variables));
2201 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2203 vec_pop(parser->variables);
2204 vec_pop(parser->correct_variables);
2205 vec_pop(parser->correct_variables_score);
2206 if (!vec_size(parser->_blocklocals)) {
2207 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2211 locals = vec_last(parser->_blocklocals);
2212 vec_pop(parser->_blocklocals);
2213 while (vec_size(parser->_locals) != locals) {
2214 ast_expression *e = vec_last(parser->_locals);
2215 ast_value *v = (ast_value*)e;
2216 vec_pop(parser->_locals);
2217 if (ast_istype(e, ast_value) && !v->uses) {
2218 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2223 typedefs = vec_last(parser->_blocktypedefs);
2224 while (vec_size(parser->_typedefs) != typedefs) {
2225 ast_delete(vec_last(parser->_typedefs));
2226 vec_pop(parser->_typedefs);
2228 util_htdel(vec_last(parser->typedefs));
2229 vec_pop(parser->typedefs);
2231 vec_pop(parser->_block_ctx);
2236 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2238 vec_push(parser->_locals, e);
2239 util_htset(vec_last(parser->variables), name, (void*)e);
2243 vec_last(parser->correct_variables),
2244 &vec_last(parser->correct_variables_score),
2249 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2251 vec_push(parser->globals, e);
2252 util_htset(parser->htglobals, name, e);
2256 parser->correct_variables[0],
2257 &parser->correct_variables_score[0],
2262 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2266 ast_expression *prev;
2268 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2270 ast_type_to_string(cond, ty, sizeof(ty));
2271 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2274 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2277 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2280 parseerror(parser, "internal error: failed to process condition");
2285 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2287 /* vector types need to be cast to true booleans */
2288 ast_binary *bin = (ast_binary*)cond;
2289 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2291 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2293 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2296 parseerror(parser, "internal error: failed to process condition");
2303 unary = (ast_unary*)cond;
2304 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2306 cond = unary->operand;
2307 unary->operand = NULL;
2310 unary = (ast_unary*)cond;
2314 parseerror(parser, "internal error: failed to process condition");
2316 if (ifnot) *_ifnot = !*_ifnot;
2320 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2323 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2326 lex_ctx ctx = parser_ctx(parser);
2328 (void)block; /* not touching */
2330 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2331 if (!parser_next(parser)) {
2332 parseerror(parser, "expected condition or 'not'");
2335 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2337 if (!parser_next(parser)) {
2338 parseerror(parser, "expected condition in parenthesis");
2342 if (parser->tok != '(') {
2343 parseerror(parser, "expected 'if' condition in parenthesis");
2346 /* parse into the expression */
2347 if (!parser_next(parser)) {
2348 parseerror(parser, "expected 'if' condition after opening paren");
2351 /* parse the condition */
2352 cond = parse_expression_leave(parser, false, true, false);
2356 if (parser->tok != ')') {
2357 parseerror(parser, "expected closing paren after 'if' condition");
2361 /* parse into the 'then' branch */
2362 if (!parser_next(parser)) {
2363 parseerror(parser, "expected statement for on-true branch of 'if'");
2367 if (!parse_statement_or_block(parser, &ontrue)) {
2372 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2373 /* check for an else */
2374 if (!strcmp(parser_tokval(parser), "else")) {
2375 /* parse into the 'else' branch */
2376 if (!parser_next(parser)) {
2377 parseerror(parser, "expected on-false branch after 'else'");
2382 if (!parse_statement_or_block(parser, &onfalse)) {
2389 cond = process_condition(parser, cond, &ifnot);
2391 if (ontrue) ast_delete(ontrue);
2392 if (onfalse) ast_delete(onfalse);
2397 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2399 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2400 *out = (ast_expression*)ifthen;
2404 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2405 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2410 /* skip the 'while' and get the body */
2411 if (!parser_next(parser)) {
2412 if (OPTS_FLAG(LOOP_LABELS))
2413 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2415 parseerror(parser, "expected 'while' condition in parenthesis");
2419 if (parser->tok == ':') {
2420 if (!OPTS_FLAG(LOOP_LABELS))
2421 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2422 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2423 parseerror(parser, "expected loop label");
2426 label = util_strdup(parser_tokval(parser));
2427 if (!parser_next(parser)) {
2429 parseerror(parser, "expected 'while' condition in parenthesis");
2434 if (parser->tok != '(') {
2435 parseerror(parser, "expected 'while' condition in parenthesis");
2439 vec_push(parser->breaks, label);
2440 vec_push(parser->continues, label);
2442 rv = parse_while_go(parser, block, out);
2445 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2446 parseerror(parser, "internal error: label stack corrupted");
2452 vec_pop(parser->breaks);
2453 vec_pop(parser->continues);
2458 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2461 ast_expression *cond, *ontrue;
2465 lex_ctx ctx = parser_ctx(parser);
2467 (void)block; /* not touching */
2469 /* parse into the expression */
2470 if (!parser_next(parser)) {
2471 parseerror(parser, "expected 'while' condition after opening paren");
2474 /* parse the condition */
2475 cond = parse_expression_leave(parser, false, true, false);
2479 if (parser->tok != ')') {
2480 parseerror(parser, "expected closing paren after 'while' condition");
2484 /* parse into the 'then' branch */
2485 if (!parser_next(parser)) {
2486 parseerror(parser, "expected while-loop body");
2490 if (!parse_statement_or_block(parser, &ontrue)) {
2495 cond = process_condition(parser, cond, &ifnot);
2500 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2501 *out = (ast_expression*)aloop;
2505 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2506 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2511 /* skip the 'do' and get the body */
2512 if (!parser_next(parser)) {
2513 if (OPTS_FLAG(LOOP_LABELS))
2514 parseerror(parser, "expected loop label or body");
2516 parseerror(parser, "expected loop body");
2520 if (parser->tok == ':') {
2521 if (!OPTS_FLAG(LOOP_LABELS))
2522 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2523 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2524 parseerror(parser, "expected loop label");
2527 label = util_strdup(parser_tokval(parser));
2528 if (!parser_next(parser)) {
2530 parseerror(parser, "expected loop body");
2535 vec_push(parser->breaks, label);
2536 vec_push(parser->continues, label);
2538 rv = parse_dowhile_go(parser, block, out);
2541 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2542 parseerror(parser, "internal error: label stack corrupted");
2548 vec_pop(parser->breaks);
2549 vec_pop(parser->continues);
2554 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2557 ast_expression *cond, *ontrue;
2561 lex_ctx ctx = parser_ctx(parser);
2563 (void)block; /* not touching */
2565 if (!parse_statement_or_block(parser, &ontrue))
2568 /* expect the "while" */
2569 if (parser->tok != TOKEN_KEYWORD ||
2570 strcmp(parser_tokval(parser), "while"))
2572 parseerror(parser, "expected 'while' and condition");
2577 /* skip the 'while' and check for opening paren */
2578 if (!parser_next(parser) || parser->tok != '(') {
2579 parseerror(parser, "expected 'while' condition in parenthesis");
2583 /* parse into the expression */
2584 if (!parser_next(parser)) {
2585 parseerror(parser, "expected 'while' condition after opening paren");
2589 /* parse the condition */
2590 cond = parse_expression_leave(parser, false, true, false);
2594 if (parser->tok != ')') {
2595 parseerror(parser, "expected closing paren after 'while' condition");
2601 if (!parser_next(parser) || parser->tok != ';') {
2602 parseerror(parser, "expected semicolon after condition");
2608 if (!parser_next(parser)) {
2609 parseerror(parser, "parse error");
2615 cond = process_condition(parser, cond, &ifnot);
2620 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2621 *out = (ast_expression*)aloop;
2625 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2626 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2631 /* skip the 'for' and check for opening paren */
2632 if (!parser_next(parser)) {
2633 if (OPTS_FLAG(LOOP_LABELS))
2634 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2636 parseerror(parser, "expected 'for' expressions in parenthesis");
2640 if (parser->tok == ':') {
2641 if (!OPTS_FLAG(LOOP_LABELS))
2642 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2643 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2644 parseerror(parser, "expected loop label");
2647 label = util_strdup(parser_tokval(parser));
2648 if (!parser_next(parser)) {
2650 parseerror(parser, "expected 'for' expressions in parenthesis");
2655 if (parser->tok != '(') {
2656 parseerror(parser, "expected 'for' expressions in parenthesis");
2660 vec_push(parser->breaks, label);
2661 vec_push(parser->continues, label);
2663 rv = parse_for_go(parser, block, out);
2666 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2667 parseerror(parser, "internal error: label stack corrupted");
2673 vec_pop(parser->breaks);
2674 vec_pop(parser->continues);
2678 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2681 ast_expression *initexpr, *cond, *increment, *ontrue;
2687 lex_ctx ctx = parser_ctx(parser);
2689 parser_enterblock(parser);
2696 /* parse into the expression */
2697 if (!parser_next(parser)) {
2698 parseerror(parser, "expected 'for' initializer after opening paren");
2703 if (parser->tok == TOKEN_IDENT)
2704 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2706 if (typevar || parser->tok == TOKEN_TYPENAME) {
2708 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2709 if (parsewarning(parser, WARN_EXTENSIONS,
2710 "current standard does not allow variable declarations in for-loop initializers"))
2714 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2717 else if (parser->tok != ';')
2719 initexpr = parse_expression_leave(parser, false, false, false);
2724 /* move on to condition */
2725 if (parser->tok != ';') {
2726 parseerror(parser, "expected semicolon after for-loop initializer");
2729 if (!parser_next(parser)) {
2730 parseerror(parser, "expected for-loop condition");
2734 /* parse the condition */
2735 if (parser->tok != ';') {
2736 cond = parse_expression_leave(parser, false, true, false);
2741 /* move on to incrementor */
2742 if (parser->tok != ';') {
2743 parseerror(parser, "expected semicolon after for-loop initializer");
2746 if (!parser_next(parser)) {
2747 parseerror(parser, "expected for-loop condition");
2751 /* parse the incrementor */
2752 if (parser->tok != ')') {
2753 lex_ctx condctx = parser_ctx(parser);
2754 increment = parse_expression_leave(parser, false, false, false);
2757 if (!ast_side_effects(increment)) {
2758 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2764 if (parser->tok != ')') {
2765 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2768 /* parse into the 'then' branch */
2769 if (!parser_next(parser)) {
2770 parseerror(parser, "expected for-loop body");
2773 if (!parse_statement_or_block(parser, &ontrue))
2777 cond = process_condition(parser, cond, &ifnot);
2781 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2782 *out = (ast_expression*)aloop;
2784 if (!parser_leaveblock(parser))
2788 if (initexpr) ast_delete(initexpr);
2789 if (cond) ast_delete(cond);
2790 if (increment) ast_delete(increment);
2791 (void)!parser_leaveblock(parser);
2795 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2797 ast_expression *exp = NULL;
2798 ast_return *ret = NULL;
2799 ast_value *expected = parser->function->vtype;
2801 lex_ctx ctx = parser_ctx(parser);
2803 (void)block; /* not touching */
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "expected return expression");
2810 if (parser->tok != ';') {
2811 exp = parse_expression(parser, false, false);
2815 if (exp->expression.vtype != TYPE_NIL &&
2816 exp->expression.vtype != expected->expression.next->expression.vtype)
2818 parseerror(parser, "return with invalid expression");
2821 ret = ast_return_new(ctx, exp);
2827 if (!parser_next(parser))
2828 parseerror(parser, "parse error");
2829 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2830 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2832 ret = ast_return_new(ctx, NULL);
2834 *out = (ast_expression*)ret;
2838 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2841 unsigned int levels = 0;
2842 lex_ctx ctx = parser_ctx(parser);
2843 const char **loops = (is_continue ? parser->continues : parser->breaks);
2845 (void)block; /* not touching */
2846 if (!parser_next(parser)) {
2847 parseerror(parser, "expected semicolon or loop label");
2851 if (!vec_size(loops)) {
2853 parseerror(parser, "`continue` can only be used inside loops");
2855 parseerror(parser, "`break` can only be used inside loops or switches");
2858 if (parser->tok == TOKEN_IDENT) {
2859 if (!OPTS_FLAG(LOOP_LABELS))
2860 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2861 i = vec_size(loops);
2863 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2866 parseerror(parser, "no such loop to %s: `%s`",
2867 (is_continue ? "continue" : "break out of"),
2868 parser_tokval(parser));
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "expected semicolon");
2879 if (parser->tok != ';') {
2880 parseerror(parser, "expected semicolon");
2884 if (!parser_next(parser))
2885 parseerror(parser, "parse error");
2887 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2891 /* returns true when it was a variable qualifier, false otherwise!
2892 * on error, cvq is set to CV_WRONG
2894 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2896 bool had_const = false;
2897 bool had_var = false;
2898 bool had_noref = false;
2899 bool had_attrib = false;
2900 bool had_static = false;
2905 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2907 /* parse an attribute */
2908 if (!parser_next(parser)) {
2909 parseerror(parser, "expected attribute after `[[`");
2913 if (!strcmp(parser_tokval(parser), "noreturn")) {
2914 flags |= AST_FLAG_NORETURN;
2915 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2916 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2921 else if (!strcmp(parser_tokval(parser), "noref")) {
2923 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2924 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2929 else if (!strcmp(parser_tokval(parser), "inline")) {
2930 flags |= AST_FLAG_INLINE;
2931 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2932 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2939 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2940 flags |= AST_FLAG_DEPRECATED;
2943 if (!parser_next(parser)) {
2944 parseerror(parser, "parse error in attribute");
2948 if (parser->tok == '(') {
2949 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2950 parseerror(parser, "`deprecated` attribute missing parameter");
2954 *message = util_strdup(parser_tokval(parser));
2956 if (!parser_next(parser)) {
2957 parseerror(parser, "parse error in attribute");
2961 if(parser->tok != ')') {
2962 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2966 if (!parser_next(parser)) {
2967 parseerror(parser, "parse error in attribute");
2972 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2973 parseerror(parser, "`deprecated` attribute expected `]]`");
2976 if (*message) mem_d(*message);
2984 /* Skip tokens until we hit a ]] */
2985 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2986 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2987 if (!parser_next(parser)) {
2988 parseerror(parser, "error inside attribute");
2995 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2997 else if (!strcmp(parser_tokval(parser), "const"))
2999 else if (!strcmp(parser_tokval(parser), "var"))
3001 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3003 else if (!strcmp(parser_tokval(parser), "noref"))
3005 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3010 if (!parser_next(parser))
3020 *is_static = had_static;
3024 parseerror(parser, "parse error after variable qualifier");
3029 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3030 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3035 /* skip the 'while' and get the body */
3036 if (!parser_next(parser)) {
3037 if (OPTS_FLAG(LOOP_LABELS))
3038 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3040 parseerror(parser, "expected 'switch' operand in parenthesis");
3044 if (parser->tok == ':') {
3045 if (!OPTS_FLAG(LOOP_LABELS))
3046 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3047 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3048 parseerror(parser, "expected loop label");
3051 label = util_strdup(parser_tokval(parser));
3052 if (!parser_next(parser)) {
3054 parseerror(parser, "expected 'switch' operand in parenthesis");
3059 if (parser->tok != '(') {
3060 parseerror(parser, "expected 'switch' operand in parenthesis");
3064 vec_push(parser->breaks, label);
3066 rv = parse_switch_go(parser, block, out);
3069 if (vec_last(parser->breaks) != label) {
3070 parseerror(parser, "internal error: label stack corrupted");
3076 vec_pop(parser->breaks);
3081 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3083 ast_expression *operand;
3086 ast_switch *switchnode;
3087 ast_switch_case swcase;
3090 bool noref, is_static;
3091 uint32_t qflags = 0;
3093 lex_ctx ctx = parser_ctx(parser);
3095 (void)block; /* not touching */
3098 /* parse into the expression */
3099 if (!parser_next(parser)) {
3100 parseerror(parser, "expected switch operand");
3103 /* parse the operand */
3104 operand = parse_expression_leave(parser, false, false, false);
3108 switchnode = ast_switch_new(ctx, operand);
3111 if (parser->tok != ')') {
3112 ast_delete(switchnode);
3113 parseerror(parser, "expected closing paren after 'switch' operand");
3117 /* parse over the opening paren */
3118 if (!parser_next(parser) || parser->tok != '{') {
3119 ast_delete(switchnode);
3120 parseerror(parser, "expected list of cases");
3124 if (!parser_next(parser)) {
3125 ast_delete(switchnode);
3126 parseerror(parser, "expected 'case' or 'default'");
3130 /* new block; allow some variables to be declared here */
3131 parser_enterblock(parser);
3134 if (parser->tok == TOKEN_IDENT)
3135 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3136 if (typevar || parser->tok == TOKEN_TYPENAME) {
3137 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3138 ast_delete(switchnode);
3143 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3145 if (cvq == CV_WRONG) {
3146 ast_delete(switchnode);
3149 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3150 ast_delete(switchnode);
3159 while (parser->tok != '}') {
3160 ast_block *caseblock;
3162 if (!strcmp(parser_tokval(parser), "case")) {
3163 if (!parser_next(parser)) {
3164 ast_delete(switchnode);
3165 parseerror(parser, "expected expression for case");
3168 swcase.value = parse_expression_leave(parser, false, false, false);
3169 if (!swcase.value) {
3170 ast_delete(switchnode);
3171 parseerror(parser, "expected expression for case");
3174 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3175 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3176 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3182 else if (!strcmp(parser_tokval(parser), "default")) {
3183 swcase.value = NULL;
3184 if (!parser_next(parser)) {
3185 ast_delete(switchnode);
3186 parseerror(parser, "expected colon");
3191 ast_delete(switchnode);
3192 parseerror(parser, "expected 'case' or 'default'");
3196 /* Now the colon and body */
3197 if (parser->tok != ':') {
3198 if (swcase.value) ast_unref(swcase.value);
3199 ast_delete(switchnode);
3200 parseerror(parser, "expected colon");
3204 if (!parser_next(parser)) {
3205 if (swcase.value) ast_unref(swcase.value);
3206 ast_delete(switchnode);
3207 parseerror(parser, "expected statements or case");
3210 caseblock = ast_block_new(parser_ctx(parser));
3212 if (swcase.value) ast_unref(swcase.value);
3213 ast_delete(switchnode);
3216 swcase.code = (ast_expression*)caseblock;
3217 vec_push(switchnode->cases, swcase);
3219 ast_expression *expr;
3220 if (parser->tok == '}')
3222 if (parser->tok == TOKEN_KEYWORD) {
3223 if (!strcmp(parser_tokval(parser), "case") ||
3224 !strcmp(parser_tokval(parser), "default"))
3229 if (!parse_statement(parser, caseblock, &expr, true)) {
3230 ast_delete(switchnode);
3235 if (!ast_block_add_expr(caseblock, expr)) {
3236 ast_delete(switchnode);
3242 parser_leaveblock(parser);
3245 if (parser->tok != '}') {
3246 ast_delete(switchnode);
3247 parseerror(parser, "expected closing paren of case list");
3250 if (!parser_next(parser)) {
3251 ast_delete(switchnode);
3252 parseerror(parser, "parse error after switch");
3255 *out = (ast_expression*)switchnode;
3259 /* parse computed goto sides */
3260 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3261 ast_expression *on_true;
3262 ast_expression *on_false;
3263 ast_expression *cond;
3268 if (ast_istype(*side, ast_ternary)) {
3269 ast_ternary *tern = (ast_ternary*)*side;
3270 on_true = parse_goto_computed(parser, &tern->on_true);
3271 on_false = parse_goto_computed(parser, &tern->on_false);
3273 if (!on_true || !on_false) {
3274 parseerror(parser, "expected label or expression in ternary");
3275 if (on_true) ast_unref(on_true);
3276 if (on_false) ast_unref(on_false);
3284 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3285 } else if (ast_istype(*side, ast_label)) {
3286 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3287 ast_goto_set_label(gt, ((ast_label*)*side));
3289 return (ast_expression*)gt;
3294 static bool parse_goto(parser_t *parser, ast_expression **out)
3296 ast_goto *gt = NULL;
3297 ast_expression *lbl;
3299 if (!parser_next(parser))
3302 if (parser->tok != TOKEN_IDENT) {
3303 ast_expression *expression;
3305 /* could be an expression i.e computed goto :-) */
3306 if (parser->tok != '(') {
3307 parseerror(parser, "expected label name after `goto`");
3311 /* failed to parse expression for goto */
3312 if (!(expression = parse_expression(parser, false, true)) ||
3313 !(*out = parse_goto_computed(parser, &expression))) {
3314 parseerror(parser, "invalid goto expression");
3315 ast_unref(expression);
3322 /* not computed goto */
3323 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3324 lbl = parser_find_label(parser, gt->name);
3326 if (!ast_istype(lbl, ast_label)) {
3327 parseerror(parser, "internal error: label is not an ast_label");
3331 ast_goto_set_label(gt, (ast_label*)lbl);
3334 vec_push(parser->gotos, gt);
3336 if (!parser_next(parser) || parser->tok != ';') {
3337 parseerror(parser, "semicolon expected after goto label");
3340 if (!parser_next(parser)) {
3341 parseerror(parser, "parse error after goto");
3345 *out = (ast_expression*)gt;
3349 static bool parse_skipwhite(parser_t *parser)
3352 if (!parser_next(parser))
3354 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3355 return parser->tok < TOKEN_ERROR;
3358 static bool parse_eol(parser_t *parser)
3360 if (!parse_skipwhite(parser))
3362 return parser->tok == TOKEN_EOL;
3365 static bool parse_pragma_do(parser_t *parser)
3367 if (!parser_next(parser) ||
3368 parser->tok != TOKEN_IDENT ||
3369 strcmp(parser_tokval(parser), "pragma"))
3371 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3374 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3375 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3379 if (!strcmp(parser_tokval(parser), "noref")) {
3380 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3381 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3384 parser->noref = !!parser_token(parser)->constval.i;
3385 if (!parse_eol(parser)) {
3386 parseerror(parser, "parse error after `noref` pragma");
3392 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3399 static bool parse_pragma(parser_t *parser)
3402 parser->lex->flags.preprocessing = true;
3403 parser->lex->flags.mergelines = true;
3404 rv = parse_pragma_do(parser);
3405 if (parser->tok != TOKEN_EOL) {
3406 parseerror(parser, "junk after pragma");
3409 parser->lex->flags.preprocessing = false;
3410 parser->lex->flags.mergelines = false;
3411 if (!parser_next(parser)) {
3412 parseerror(parser, "parse error after pragma");
3418 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3420 bool noref, is_static;
3422 uint32_t qflags = 0;
3423 ast_value *typevar = NULL;
3424 char *vstring = NULL;
3428 if (parser->tok == TOKEN_IDENT)
3429 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3431 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3433 /* local variable */
3435 parseerror(parser, "cannot declare a variable from here");
3438 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3439 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3442 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3446 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3448 if (cvq == CV_WRONG)
3450 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3452 else if (parser->tok == TOKEN_KEYWORD)
3454 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3459 if (!parser_next(parser)) {
3460 parseerror(parser, "parse error after __builtin_debug_printtype");
3464 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3466 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3467 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3468 if (!parser_next(parser)) {
3469 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3475 if (!parse_statement(parser, block, out, allow_cases))
3478 con_out("__builtin_debug_printtype: got no output node\n");
3481 ast_type_to_string(*out, ty, sizeof(ty));
3482 con_out("__builtin_debug_printtype: `%s`\n", ty);
3487 else if (!strcmp(parser_tokval(parser), "return"))
3489 return parse_return(parser, block, out);
3491 else if (!strcmp(parser_tokval(parser), "if"))
3493 return parse_if(parser, block, out);
3495 else if (!strcmp(parser_tokval(parser), "while"))
3497 return parse_while(parser, block, out);
3499 else if (!strcmp(parser_tokval(parser), "do"))
3501 return parse_dowhile(parser, block, out);
3503 else if (!strcmp(parser_tokval(parser), "for"))
3505 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3506 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3509 return parse_for(parser, block, out);
3511 else if (!strcmp(parser_tokval(parser), "break"))
3513 return parse_break_continue(parser, block, out, false);
3515 else if (!strcmp(parser_tokval(parser), "continue"))
3517 return parse_break_continue(parser, block, out, true);
3519 else if (!strcmp(parser_tokval(parser), "switch"))
3521 return parse_switch(parser, block, out);
3523 else if (!strcmp(parser_tokval(parser), "case") ||
3524 !strcmp(parser_tokval(parser), "default"))
3527 parseerror(parser, "unexpected 'case' label");
3532 else if (!strcmp(parser_tokval(parser), "goto"))
3534 return parse_goto(parser, out);
3536 else if (!strcmp(parser_tokval(parser), "typedef"))
3538 if (!parser_next(parser)) {
3539 parseerror(parser, "expected type definition after 'typedef'");
3542 return parse_typedef(parser);
3544 parseerror(parser, "Unexpected keyword");
3547 else if (parser->tok == '{')
3550 inner = parse_block(parser);
3553 *out = (ast_expression*)inner;
3556 else if (parser->tok == ':')
3560 if (!parser_next(parser)) {
3561 parseerror(parser, "expected label name");
3564 if (parser->tok != TOKEN_IDENT) {
3565 parseerror(parser, "label must be an identifier");
3568 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3570 if (!label->undefined) {
3571 parseerror(parser, "label `%s` already defined", label->name);
3574 label->undefined = false;
3577 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3578 vec_push(parser->labels, label);
3580 *out = (ast_expression*)label;
3581 if (!parser_next(parser)) {
3582 parseerror(parser, "parse error after label");
3585 for (i = 0; i < vec_size(parser->gotos); ++i) {
3586 if (!strcmp(parser->gotos[i]->name, label->name)) {
3587 ast_goto_set_label(parser->gotos[i], label);
3588 vec_remove(parser->gotos, i, 1);
3594 else if (parser->tok == ';')
3596 if (!parser_next(parser)) {
3597 parseerror(parser, "parse error after empty statement");
3604 lex_ctx ctx = parser_ctx(parser);
3605 ast_expression *exp = parse_expression(parser, false, false);
3609 if (!ast_side_effects(exp)) {
3610 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3617 static bool parse_enum(parser_t *parser)
3620 ast_value **values = NULL;
3621 ast_value *var = NULL;
3624 ast_expression *old;
3626 if (!parser_next(parser) || parser->tok != '{') {
3627 parseerror(parser, "expected `{` after `enum` keyword");
3632 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3633 if (parser->tok == '}') {
3634 /* allow an empty enum */
3637 parseerror(parser, "expected identifier or `}`");
3641 old = parser_find_field(parser, parser_tokval(parser));
3643 old = parser_find_global(parser, parser_tokval(parser));
3645 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3646 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3650 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3651 vec_push(values, var);
3652 var->cvq = CV_CONST;
3653 var->hasvalue = true;
3654 var->constval.vfloat = num++;
3656 parser_addglobal(parser, var->name, (ast_expression*)var);
3658 if (!parser_next(parser)) {
3659 parseerror(parser, "expected `=`, `}` or comma after identifier");
3663 if (parser->tok == ',')
3665 if (parser->tok == '}')
3667 if (parser->tok != '=') {
3668 parseerror(parser, "expected `=`, `}` or comma after identifier");
3672 if (!parser_next(parser)) {
3673 parseerror(parser, "expected expression after `=`");
3677 /* We got a value! */
3678 old = parse_expression_leave(parser, true, false, false);
3679 asvalue = (ast_value*)old;
3680 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3681 compile_error(ast_ctx(var), "constant value or expression expected");
3684 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3686 if (parser->tok == '}')
3688 if (parser->tok != ',') {
3689 parseerror(parser, "expected `}` or comma after expression");
3694 if (parser->tok != '}') {
3695 parseerror(parser, "internal error: breaking without `}`");
3699 if (!parser_next(parser) || parser->tok != ';') {
3700 parseerror(parser, "expected semicolon after enumeration");
3704 if (!parser_next(parser)) {
3705 parseerror(parser, "parse error after enumeration");
3717 static bool parse_block_into(parser_t *parser, ast_block *block)
3721 parser_enterblock(parser);
3723 if (!parser_next(parser)) { /* skip the '{' */
3724 parseerror(parser, "expected function body");
3728 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3730 ast_expression *expr = NULL;
3731 if (parser->tok == '}')
3734 if (!parse_statement(parser, block, &expr, false)) {
3735 /* parseerror(parser, "parse error"); */
3741 if (!ast_block_add_expr(block, expr)) {
3748 if (parser->tok != '}') {
3751 (void)parser_next(parser);
3755 if (!parser_leaveblock(parser))
3757 return retval && !!block;
3760 static ast_block* parse_block(parser_t *parser)
3763 block = ast_block_new(parser_ctx(parser));
3766 if (!parse_block_into(parser, block)) {
3767 ast_block_delete(block);
3773 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3775 if (parser->tok == '{') {
3776 *out = (ast_expression*)parse_block(parser);
3779 return parse_statement(parser, NULL, out, false);
3782 static bool create_vector_members(ast_value *var, ast_member **me)
3785 size_t len = strlen(var->name);
3787 for (i = 0; i < 3; ++i) {
3788 char *name = (char*)mem_a(len+3);
3789 memcpy(name, var->name, len);
3791 name[len+1] = 'x'+i;
3793 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3802 do { ast_member_delete(me[--i]); } while(i);
3806 static bool parse_function_body(parser_t *parser, ast_value *var)
3808 ast_block *block = NULL;
3813 ast_expression *framenum = NULL;
3814 ast_expression *nextthink = NULL;
3815 /* None of the following have to be deleted */
3816 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3817 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3818 bool has_frame_think;
3822 has_frame_think = false;
3823 old = parser->function;
3825 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3826 parseerror(parser, "gotos/labels leaking");
3830 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3831 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3832 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3838 if (parser->tok == '[') {
3839 /* got a frame definition: [ framenum, nextthink ]
3840 * this translates to:
3841 * self.frame = framenum;
3842 * self.nextthink = time + 0.1;
3843 * self.think = nextthink;
3847 fld_think = parser_find_field(parser, "think");
3848 fld_nextthink = parser_find_field(parser, "nextthink");
3849 fld_frame = parser_find_field(parser, "frame");
3850 if (!fld_think || !fld_nextthink || !fld_frame) {
3851 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3852 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3855 gbl_time = parser_find_global(parser, "time");
3856 gbl_self = parser_find_global(parser, "self");
3857 if (!gbl_time || !gbl_self) {
3858 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3859 parseerror(parser, "please declare the following globals: `time`, `self`");
3863 if (!parser_next(parser))
3866 framenum = parse_expression_leave(parser, true, false, false);
3868 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3871 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3872 ast_unref(framenum);
3873 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3877 if (parser->tok != ',') {
3878 ast_unref(framenum);
3879 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3880 parseerror(parser, "Got a %i\n", parser->tok);
3884 if (!parser_next(parser)) {
3885 ast_unref(framenum);
3889 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3891 /* qc allows the use of not-yet-declared functions here
3892 * - this automatically creates a prototype */
3893 ast_value *thinkfunc;
3894 ast_expression *functype = fld_think->expression.next;
3896 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3897 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3898 ast_unref(framenum);
3899 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3902 ast_type_adopt(thinkfunc, functype);
3904 if (!parser_next(parser)) {
3905 ast_unref(framenum);
3906 ast_delete(thinkfunc);
3910 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3912 nextthink = (ast_expression*)thinkfunc;
3915 nextthink = parse_expression_leave(parser, true, false, false);
3917 ast_unref(framenum);
3918 parseerror(parser, "expected a think-function in [frame,think] notation");
3923 if (!ast_istype(nextthink, ast_value)) {
3924 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3928 if (retval && parser->tok != ']') {
3929 parseerror(parser, "expected closing `]` for [frame,think] notation");
3933 if (retval && !parser_next(parser)) {
3937 if (retval && parser->tok != '{') {
3938 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3943 ast_unref(nextthink);
3944 ast_unref(framenum);
3948 has_frame_think = true;
3951 block = ast_block_new(parser_ctx(parser));
3953 parseerror(parser, "failed to allocate block");
3954 if (has_frame_think) {
3955 ast_unref(nextthink);
3956 ast_unref(framenum);
3961 if (has_frame_think) {
3963 ast_expression *self_frame;
3964 ast_expression *self_nextthink;
3965 ast_expression *self_think;
3966 ast_expression *time_plus_1;
3967 ast_store *store_frame;
3968 ast_store *store_nextthink;
3969 ast_store *store_think;
3971 ctx = parser_ctx(parser);
3972 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3973 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3974 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3976 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3977 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3979 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3980 if (self_frame) ast_delete(self_frame);
3981 if (self_nextthink) ast_delete(self_nextthink);
3982 if (self_think) ast_delete(self_think);
3983 if (time_plus_1) ast_delete(time_plus_1);
3989 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3990 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3991 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3994 ast_delete(self_frame);
3997 if (!store_nextthink) {
3998 ast_delete(self_nextthink);
4002 ast_delete(self_think);
4006 if (store_frame) ast_delete(store_frame);
4007 if (store_nextthink) ast_delete(store_nextthink);
4008 if (store_think) ast_delete(store_think);
4011 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4012 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4013 !ast_block_add_expr(block, (ast_expression*)store_think))
4020 parseerror(parser, "failed to generate code for [frame,think]");
4021 ast_unref(nextthink);
4022 ast_unref(framenum);
4028 if (var->hasvalue) {
4029 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4030 ast_block_delete(block);
4034 func = ast_function_new(ast_ctx(var), var->name, var);
4036 parseerror(parser, "failed to allocate function for `%s`", var->name);
4037 ast_block_delete(block);
4040 vec_push(parser->functions, func);
4042 parser_enterblock(parser);
4044 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4046 ast_value *param = var->expression.params[parami];
4049 if (param->expression.vtype != TYPE_VECTOR &&
4050 (param->expression.vtype != TYPE_FIELD ||
4051 param->expression.next->expression.vtype != TYPE_VECTOR))
4056 if (!create_vector_members(param, me)) {
4057 ast_block_delete(block);
4061 for (e = 0; e < 3; ++e) {
4062 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4063 ast_block_collect(block, (ast_expression*)me[e]);
4067 if (var->argcounter) {
4068 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4069 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4073 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4075 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4076 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4077 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4078 varargs->expression.count = 0;
4079 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4080 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4081 ast_delete(varargs);
4082 ast_block_delete(block);
4085 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4086 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4087 ast_delete(varargs);
4088 ast_block_delete(block);
4091 func->varargs = varargs;
4093 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4096 parser->function = func;
4097 if (!parse_block_into(parser, block)) {
4098 ast_block_delete(block);
4102 vec_push(func->blocks, block);
4104 parser->function = old;
4105 if (!parser_leaveblock(parser))
4107 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4108 parseerror(parser, "internal error: local scopes left");
4112 if (parser->tok == ';')
4113 return parser_next(parser);
4114 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4115 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4119 (void)!parser_leaveblock(parser);
4120 vec_pop(parser->functions);
4121 ast_function_delete(func);
4122 var->constval.vfunc = NULL;
4125 parser->function = old;
4129 static ast_expression *array_accessor_split(
4134 ast_expression *left,
4135 ast_expression *right
4141 lex_ctx ctx = ast_ctx(array);
4143 if (!left || !right) {
4144 if (left) ast_delete(left);
4145 if (right) ast_delete(right);
4149 cmp = ast_binary_new(ctx, INSTR_LT,
4150 (ast_expression*)index,
4151 (ast_expression*)parser_const_float(parser, middle));
4155 parseerror(parser, "internal error: failed to create comparison for array setter");
4159 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4161 ast_delete(cmp); /* will delete left and right */
4162 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4166 return (ast_expression*)ifthen;
4169 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4171 lex_ctx ctx = ast_ctx(array);
4173 if (from+1 == afterend) {
4174 /* set this value */
4177 ast_array_index *subscript;
4179 int assignop = type_store_instr[value->expression.vtype];
4181 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4182 assignop = INSTR_STORE_V;
4184 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4188 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4190 ast_delete(subscript);
4194 block = ast_block_new(ctx);
4200 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4205 ret = ast_return_new(ctx, NULL);
4211 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4216 return (ast_expression*)block;
4218 ast_expression *left, *right;
4219 size_t diff = afterend - from;
4220 size_t middle = from + diff/2;
4221 left = array_setter_node(parser, array, index, value, from, middle);
4222 right = array_setter_node(parser, array, index, value, middle, afterend);
4223 return array_accessor_split(parser, array, index, middle, left, right);
4227 static ast_expression *array_field_setter_node(
4236 lex_ctx ctx = ast_ctx(array);
4238 if (from+1 == afterend) {
4239 /* set this value */
4242 ast_entfield *entfield;
4243 ast_array_index *subscript;
4245 int assignop = type_storep_instr[value->expression.vtype];
4247 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4248 assignop = INSTR_STOREP_V;
4250 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4254 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4255 subscript->expression.vtype = TYPE_FIELD;
4257 entfield = ast_entfield_new_force(ctx,
4258 (ast_expression*)entity,
4259 (ast_expression*)subscript,
4260 (ast_expression*)subscript);
4262 ast_delete(subscript);
4266 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4268 ast_delete(entfield);
4272 block = ast_block_new(ctx);
4278 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4283 ret = ast_return_new(ctx, NULL);
4289 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4294 return (ast_expression*)block;
4296 ast_expression *left, *right;
4297 size_t diff = afterend - from;
4298 size_t middle = from + diff/2;
4299 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4300 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4301 return array_accessor_split(parser, array, index, middle, left, right);
4305 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4307 lex_ctx ctx = ast_ctx(array);
4309 if (from+1 == afterend) {
4311 ast_array_index *subscript;
4313 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4317 ret = ast_return_new(ctx, (ast_expression*)subscript);
4319 ast_delete(subscript);
4323 return (ast_expression*)ret;
4325 ast_expression *left, *right;
4326 size_t diff = afterend - from;
4327 size_t middle = from + diff/2;
4328 left = array_getter_node(parser, array, index, from, middle);
4329 right = array_getter_node(parser, array, index, middle, afterend);
4330 return array_accessor_split(parser, array, index, middle, left, right);
4334 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4336 ast_function *func = NULL;
4337 ast_value *fval = NULL;
4338 ast_block *body = NULL;
4340 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4342 parseerror(parser, "failed to create accessor function value");
4346 func = ast_function_new(ast_ctx(array), funcname, fval);
4349 parseerror(parser, "failed to create accessor function node");
4353 body = ast_block_new(ast_ctx(array));
4355 parseerror(parser, "failed to create block for array accessor");
4361 vec_push(func->blocks, body);
4364 vec_push(parser->accessors, fval);
4369 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4371 ast_value *index = NULL;
4372 ast_value *value = NULL;
4376 if (!ast_istype(array->expression.next, ast_value)) {
4377 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4381 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4383 func = fval->constval.vfunc;
4384 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4386 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4387 value = ast_value_copy((ast_value*)array->expression.next);
4389 if (!index || !value) {
4390 parseerror(parser, "failed to create locals for array accessor");
4393 (void)!ast_value_set_name(value, "value"); /* not important */
4394 vec_push(fval->expression.params, index);
4395 vec_push(fval->expression.params, value);
4397 array->setter = fval;
4400 if (index) ast_delete(index);
4401 if (value) ast_delete(value);
4407 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4409 ast_expression *root = NULL;
4410 root = array_setter_node(parser, array,
4411 array->setter->expression.params[0],
4412 array->setter->expression.params[1],
4413 0, array->expression.count);
4415 parseerror(parser, "failed to build accessor search tree");
4418 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4425 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4427 if (!parser_create_array_setter_proto(parser, array, funcname))
4429 return parser_create_array_setter_impl(parser, array);
4432 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4434 ast_expression *root = NULL;
4435 ast_value *entity = NULL;
4436 ast_value *index = NULL;
4437 ast_value *value = NULL;
4441 if (!ast_istype(array->expression.next, ast_value)) {
4442 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4446 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4448 func = fval->constval.vfunc;
4449 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4451 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4452 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4453 value = ast_value_copy((ast_value*)array->expression.next);
4454 if (!entity || !index || !value) {
4455 parseerror(parser, "failed to create locals for array accessor");
4458 (void)!ast_value_set_name(value, "value"); /* not important */
4459 vec_push(fval->expression.params, entity);
4460 vec_push(fval->expression.params, index);
4461 vec_push(fval->expression.params, value);
4463 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4465 parseerror(parser, "failed to build accessor search tree");
4469 array->setter = fval;
4470 return ast_block_add_expr(func->blocks[0], root);
4472 if (entity) ast_delete(entity);
4473 if (index) ast_delete(index);
4474 if (value) ast_delete(value);
4475 if (root) ast_delete(root);
4481 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4483 ast_value *index = NULL;
4487 /* NOTE: checking array->expression.next rather than elemtype since
4488 * for fields elemtype is a temporary fieldtype.
4490 if (!ast_istype(array->expression.next, ast_value)) {
4491 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4495 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4497 func = fval->constval.vfunc;
4498 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4500 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4503 parseerror(parser, "failed to create locals for array accessor");
4506 vec_push(fval->expression.params, index);
4508 array->getter = fval;
4511 if (index) ast_delete(index);
4517 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4519 ast_expression *root = NULL;
4521 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4523 parseerror(parser, "failed to build accessor search tree");
4526 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4533 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4535 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4537 return parser_create_array_getter_impl(parser, array);
4540 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4541 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4549 bool variadic = false;
4550 ast_value *varparam = NULL;
4551 char *argcounter = NULL;
4553 ctx = parser_ctx(parser);
4555 /* for the sake of less code we parse-in in this function */
4556 if (!parser_next(parser)) {
4557 parseerror(parser, "expected parameter list");
4563 /* parse variables until we hit a closing paren */
4564 while (parser->tok != ')') {
4566 /* there must be commas between them */
4567 if (parser->tok != ',') {
4568 parseerror(parser, "expected comma or end of parameter list");
4571 if (!parser_next(parser)) {
4572 parseerror(parser, "expected parameter");
4578 if (parser->tok == TOKEN_DOTS) {
4579 /* '...' indicates a varargs function */
4581 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4582 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4585 if (parser->tok == TOKEN_IDENT) {
4586 argcounter = util_strdup(parser_tokval(parser));
4587 if (!parser_next(parser) || parser->tok != ')') {
4588 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4595 /* for anything else just parse a typename */
4596 param = parse_typename(parser, NULL, NULL);
4599 vec_push(params, param);
4600 if (param->expression.vtype >= TYPE_VARIANT) {
4601 char tname[1024]; /* typename is reserved in C++ */
4602 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4603 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4606 /* type-restricted varargs */
4607 if (parser->tok == TOKEN_DOTS) {
4609 varparam = vec_last(params);
4611 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4612 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4615 if (parser->tok == TOKEN_IDENT) {
4616 argcounter = util_strdup(parser_tokval(parser));
4617 if (!parser_next(parser) || parser->tok != ')') {
4618 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4626 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4630 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4631 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4634 if (!parser_next(parser)) {
4635 parseerror(parser, "parse error after typename");
4639 /* now turn 'var' into a function type */
4640 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4641 fval->expression.next = (ast_expression*)var;
4643 fval->expression.flags |= AST_FLAG_VARIADIC;
4646 var->expression.params = params;
4647 var->expression.varparam = (ast_expression*)varparam;
4648 var->argcounter = argcounter;
4657 for (i = 0; i < vec_size(params); ++i)
4658 ast_delete(params[i]);
4663 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4665 ast_expression *cexp;
4666 ast_value *cval, *tmp;
4669 ctx = parser_ctx(parser);
4671 if (!parser_next(parser)) {
4673 parseerror(parser, "expected array-size");
4677 cexp = parse_expression_leave(parser, true, false, false);
4679 if (!cexp || !ast_istype(cexp, ast_value)) {
4683 parseerror(parser, "expected array-size as constant positive integer");
4686 cval = (ast_value*)cexp;
4688 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4689 tmp->expression.next = (ast_expression*)var;
4692 if (cval->expression.vtype == TYPE_INTEGER)
4693 tmp->expression.count = cval->constval.vint;
4694 else if (cval->expression.vtype == TYPE_FLOAT)
4695 tmp->expression.count = cval->constval.vfloat;
4699 parseerror(parser, "array-size must be a positive integer constant");
4704 if (parser->tok != ']') {
4706 parseerror(parser, "expected ']' after array-size");
4709 if (!parser_next(parser)) {
4711 parseerror(parser, "error after parsing array size");
4717 /* Parse a complete typename.
4718 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4719 * but when parsing variables separated by comma
4720 * 'storebase' should point to where the base-type should be kept.
4721 * The base type makes up every bit of type information which comes *before* the
4724 * The following will be parsed in its entirety:
4726 * The 'basetype' in this case is 'void()'
4727 * and if there's a comma after it, say:
4729 * then the type-information 'void()' can be stored in 'storebase'
4731 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4733 ast_value *var, *tmp;
4736 const char *name = NULL;
4737 bool isfield = false;
4738 bool wasarray = false;
4739 size_t morefields = 0;
4741 ctx = parser_ctx(parser);
4743 /* types may start with a dot */
4744 if (parser->tok == '.') {
4746 /* if we parsed a dot we need a typename now */
4747 if (!parser_next(parser)) {
4748 parseerror(parser, "expected typename for field definition");
4752 /* Further dots are handled seperately because they won't be part of the
4755 while (parser->tok == '.') {
4757 if (!parser_next(parser)) {
4758 parseerror(parser, "expected typename for field definition");
4763 if (parser->tok == TOKEN_IDENT)
4764 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4765 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4766 parseerror(parser, "expected typename");
4770 /* generate the basic type value */
4771 if (cached_typedef) {
4772 var = ast_value_copy(cached_typedef);
4773 ast_value_set_name(var, "<type(from_def)>");
4775 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4777 for (; morefields; --morefields) {
4778 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4779 tmp->expression.next = (ast_expression*)var;
4783 /* do not yet turn into a field - remember:
4784 * .void() foo; is a field too
4785 * .void()() foo; is a function
4789 if (!parser_next(parser)) {
4791 parseerror(parser, "parse error after typename");
4795 /* an opening paren now starts the parameter-list of a function
4796 * this is where original-QC has parameter lists.
4797 * We allow a single parameter list here.
4798 * Much like fteqcc we don't allow `float()() x`
4800 if (parser->tok == '(') {
4801 var = parse_parameter_list(parser, var);
4806 /* store the base if requested */
4808 *storebase = ast_value_copy(var);
4810 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4811 tmp->expression.next = (ast_expression*)*storebase;
4816 /* there may be a name now */
4817 if (parser->tok == TOKEN_IDENT) {
4818 name = util_strdup(parser_tokval(parser));
4820 if (!parser_next(parser)) {
4822 parseerror(parser, "error after variable or field declaration");
4827 /* now this may be an array */
4828 if (parser->tok == '[') {
4830 var = parse_arraysize(parser, var);
4835 /* This is the point where we can turn it into a field */
4837 /* turn it into a field if desired */
4838 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4839 tmp->expression.next = (ast_expression*)var;
4843 /* now there may be function parens again */
4844 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4845 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4846 if (parser->tok == '(' && wasarray)
4847 parseerror(parser, "arrays as part of a return type is not supported");
4848 while (parser->tok == '(') {
4849 var = parse_parameter_list(parser, var);
4857 /* finally name it */
4859 if (!ast_value_set_name(var, name)) {
4861 parseerror(parser, "internal error: failed to set name");
4864 /* free the name, ast_value_set_name duplicates */
4871 static bool parse_typedef(parser_t *parser)
4873 ast_value *typevar, *oldtype;
4874 ast_expression *old;
4876 typevar = parse_typename(parser, NULL, NULL);
4881 if ( (old = parser_find_var(parser, typevar->name)) ) {
4882 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4883 " -> `%s` has been declared here: %s:%i",
4884 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4885 ast_delete(typevar);
4889 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4890 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4891 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4892 ast_delete(typevar);
4896 vec_push(parser->_typedefs, typevar);
4897 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4899 if (parser->tok != ';') {
4900 parseerror(parser, "expected semicolon after typedef");
4903 if (!parser_next(parser)) {
4904 parseerror(parser, "parse error after typedef");
4911 static const char *cvq_to_str(int cvq) {
4913 case CV_NONE: return "none";
4914 case CV_VAR: return "`var`";
4915 case CV_CONST: return "`const`";
4916 default: return "<INVALID>";
4920 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4923 if (proto->cvq != var->cvq) {
4924 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4925 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4926 parser->tok == '='))
4928 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4929 "`%s` declared with different qualifiers: %s\n"
4930 " -> previous declaration here: %s:%i uses %s",
4931 var->name, cvq_to_str(var->cvq),
4932 ast_ctx(proto).file, ast_ctx(proto).line,
4933 cvq_to_str(proto->cvq));
4936 av = (var ->expression.flags & AST_FLAG_NORETURN);
4937 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4939 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4940 "`%s` declared with different attributes%s\n"
4941 " -> previous declaration here: %s:%i",
4942 var->name, (av ? ": noreturn" : ""),
4943 ast_ctx(proto).file, ast_ctx(proto).line,
4944 (ao ? ": noreturn" : ""));
4949 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)
4953 ast_expression *old;
4957 ast_value *basetype = NULL;
4959 bool isparam = false;
4960 bool isvector = false;
4961 bool cleanvar = true;
4962 bool wasarray = false;
4966 if (!localblock && is_static)
4967 parseerror(parser, "`static` qualifier is not supported in global scope");
4969 /* get the first complete variable */
4970 var = parse_typename(parser, &basetype, cached_typedef);
4973 ast_delete(basetype);
4981 /* Part 0: finish the type */
4982 if (parser->tok == '(') {
4983 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4984 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4985 var = parse_parameter_list(parser, var);
4991 /* we only allow 1-dimensional arrays */
4992 if (parser->tok == '[') {
4994 var = parse_arraysize(parser, var);
5000 if (parser->tok == '(' && wasarray) {
5001 parseerror(parser, "arrays as part of a return type is not supported");
5002 /* we'll still parse the type completely for now */
5004 /* for functions returning functions */
5005 while (parser->tok == '(') {
5006 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5007 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5008 var = parse_parameter_list(parser, var);
5015 var->cvq = qualifier;
5016 var->expression.flags |= qflags;
5017 if (var->expression.flags & AST_FLAG_DEPRECATED)
5018 var->desc = vstring;
5021 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5022 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5023 * is then filled with the previous definition and the parameter-names replaced.
5025 if (!strcmp(var->name, "nil")) {
5026 if (OPTS_FLAG(UNTYPED_NIL)) {
5027 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5028 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5030 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5033 /* Deal with end_sys_ vars */
5035 if (!strcmp(var->name, "end_sys_globals")) {
5037 parser->crc_globals = vec_size(parser->globals);
5040 else if (!strcmp(var->name, "end_sys_fields")) {
5042 parser->crc_fields = vec_size(parser->fields);
5045 if (was_end && var->expression.vtype == TYPE_FIELD) {
5046 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5047 "global '%s' hint should not be a field",
5048 parser_tokval(parser)))
5055 if (!nofields && var->expression.vtype == TYPE_FIELD)
5057 /* deal with field declarations */
5058 old = parser_find_field(parser, var->name);
5060 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5061 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5070 parseerror(parser, "field `%s` already declared here: %s:%i",
5071 var->name, ast_ctx(old).file, ast_ctx(old).line);
5076 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5077 (old = parser_find_global(parser, var->name)))
5079 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5080 parseerror(parser, "field `%s` already declared here: %s:%i",
5081 var->name, ast_ctx(old).file, ast_ctx(old).line);
5088 /* deal with other globals */
5089 old = parser_find_global(parser, var->name);
5090 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5092 /* This is a function which had a prototype */
5093 if (!ast_istype(old, ast_value)) {
5094 parseerror(parser, "internal error: prototype is not an ast_value");
5098 proto = (ast_value*)old;
5099 proto->desc = var->desc;
5100 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5101 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5103 ast_ctx(proto).file, ast_ctx(proto).line);
5107 /* we need the new parameter-names */
5108 for (i = 0; i < vec_size(proto->expression.params); ++i)
5109 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5110 if (!parser_check_qualifiers(parser, var, proto)) {
5117 proto->expression.flags |= var->expression.flags;
5125 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5126 "global `%s` already declared here: %s:%i",
5127 var->name, ast_ctx(old).file, ast_ctx(old).line))
5132 proto = (ast_value*)old;
5133 if (!ast_istype(old, ast_value)) {
5134 parseerror(parser, "internal error: not an ast_value");
5139 if (!parser_check_qualifiers(parser, var, proto)) {
5144 proto->expression.flags |= var->expression.flags;
5148 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5149 (old = parser_find_field(parser, var->name)))
5151 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5152 parseerror(parser, "global `%s` already declared here: %s:%i",
5153 var->name, ast_ctx(old).file, ast_ctx(old).line);
5160 else /* it's not a global */
5162 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5163 if (old && !isparam) {
5164 parseerror(parser, "local `%s` already declared here: %s:%i",
5165 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5169 old = parser_find_local(parser, var->name, 0, &isparam);
5170 if (old && isparam) {
5171 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5172 "local `%s` is shadowing a parameter", var->name))
5174 parseerror(parser, "local `%s` already declared here: %s:%i",
5175 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5179 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5187 /* in a noref section we simply bump the usecount */
5188 if (noref || parser->noref)
5192 * Create the global/local, and deal with vector types.
5195 if (var->expression.vtype == TYPE_VECTOR)
5197 else if (var->expression.vtype == TYPE_FIELD &&
5198 var->expression.next->expression.vtype == TYPE_VECTOR)
5202 if (!create_vector_members(var, me)) {
5209 /* deal with global variables, fields, functions */
5210 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5211 var->isfield = true;
5212 vec_push(parser->fields, (ast_expression*)var);
5213 util_htset(parser->htfields, var->name, var);
5215 for (i = 0; i < 3; ++i) {
5216 vec_push(parser->fields, (ast_expression*)me[i]);
5217 util_htset(parser->htfields, me[i]->name, me[i]);
5222 parser_addglobal(parser, var->name, (ast_expression*)var);
5224 for (i = 0; i < 3; ++i) {
5225 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5231 /* a static adds itself to be generated like any other global
5232 * but is added to the local namespace instead
5234 char *defname = NULL;
5235 size_t prefix_len, ln;
5237 ln = strlen(parser->function->name);
5238 vec_append(defname, ln, parser->function->name);
5240 vec_append(defname, 2, "::");
5241 /* remember the length up to here */
5242 prefix_len = vec_size(defname);
5244 /* Add it to the local scope */
5245 util_htset(vec_last(parser->variables), var->name, (void*)var);
5249 vec_last(parser->correct_variables),
5250 &vec_last(parser->correct_variables_score),
5254 /* now rename the global */
5255 ln = strlen(var->name);
5256 vec_append(defname, ln, var->name);
5257 ast_value_set_name(var, defname);
5259 /* push it to the to-be-generated globals */
5260 vec_push(parser->globals, (ast_expression*)var);
5262 /* same game for the vector members */
5264 for (i = 0; i < 3; ++i) {
5265 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5269 vec_last(parser->correct_variables),
5270 &vec_last(parser->correct_variables_score),
5274 vec_shrinkto(defname, prefix_len);
5275 ln = strlen(me[i]->name);
5276 vec_append(defname, ln, me[i]->name);
5277 ast_member_set_name(me[i], defname);
5279 vec_push(parser->globals, (ast_expression*)me[i]);
5284 vec_push(localblock->locals, var);
5285 parser_addlocal(parser, var->name, (ast_expression*)var);
5287 for (i = 0; i < 3; ++i) {
5288 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5289 ast_block_collect(localblock, (ast_expression*)me[i]);
5295 me[0] = me[1] = me[2] = NULL;
5300 if (var->expression.vtype == TYPE_ARRAY) {
5302 snprintf(name, sizeof(name), "%s##SET", var->name);
5303 if (!parser_create_array_setter(parser, var, name))
5305 snprintf(name, sizeof(name), "%s##GET", var->name);
5306 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5309 else if (!localblock && !nofields &&
5310 var->expression.vtype == TYPE_FIELD &&
5311 var->expression.next->expression.vtype == TYPE_ARRAY)
5314 ast_expression *telem;
5316 ast_value *array = (ast_value*)var->expression.next;
5318 if (!ast_istype(var->expression.next, ast_value)) {
5319 parseerror(parser, "internal error: field element type must be an ast_value");
5323 snprintf(name, sizeof(name), "%s##SETF", var->name);
5324 if (!parser_create_array_field_setter(parser, array, name))
5327 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5328 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5329 tfield->expression.next = telem;
5330 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5331 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5339 if (parser->tok == ';') {
5340 ast_delete(basetype);
5341 if (!parser_next(parser)) {
5342 parseerror(parser, "error after variable declaration");
5348 if (parser->tok == ',')
5352 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5355 parseerror(parser, "missing comma or semicolon while parsing variables");
5359 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5360 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5361 "initializing expression turns variable `%s` into a constant in this standard",
5368 if (parser->tok != '{') {
5369 if (parser->tok != '=') {
5370 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5374 if (!parser_next(parser)) {
5375 parseerror(parser, "error parsing initializer");
5379 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5380 parseerror(parser, "expected '=' before function body in this standard");
5383 if (parser->tok == '#') {
5384 ast_function *func = NULL;
5387 parseerror(parser, "cannot declare builtins within functions");
5390 if (var->expression.vtype != TYPE_FUNCTION) {
5391 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5394 if (!parser_next(parser)) {
5395 parseerror(parser, "expected builtin number");
5398 if (parser->tok != TOKEN_INTCONST) {
5399 parseerror(parser, "builtin number must be an integer constant");
5402 if (parser_token(parser)->constval.i < 0) {
5403 parseerror(parser, "builtin number must be an integer greater than zero");
5407 if (var->hasvalue) {
5408 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5409 "builtin `%s` has already been defined\n"
5410 " -> previous declaration here: %s:%i",
5411 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5415 func = ast_function_new(ast_ctx(var), var->name, var);
5417 parseerror(parser, "failed to allocate function for `%s`", var->name);
5420 vec_push(parser->functions, func);
5422 func->builtin = -parser_token(parser)->constval.i-1;
5425 if (!parser_next(parser)) {
5426 parseerror(parser, "expected comma or semicolon");
5428 ast_function_delete(func);
5429 var->constval.vfunc = NULL;
5433 else if (parser->tok == '{' || parser->tok == '[')
5436 parseerror(parser, "cannot declare functions within functions");
5441 ast_ctx(proto) = parser_ctx(parser);
5443 if (!parse_function_body(parser, var))
5445 ast_delete(basetype);
5446 for (i = 0; i < vec_size(parser->gotos); ++i)
5447 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5448 vec_free(parser->gotos);
5449 vec_free(parser->labels);
5452 ast_expression *cexp;
5455 cexp = parse_expression_leave(parser, true, false, false);
5460 cval = (ast_value*)cexp;
5461 if (cval != parser->nil &&
5462 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5465 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5469 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5470 qualifier != CV_VAR)
5472 var->cvq = CV_CONST;
5474 if (cval == parser->nil)
5475 var->expression.flags |= AST_FLAG_INITIALIZED;
5478 var->hasvalue = true;
5479 if (cval->expression.vtype == TYPE_STRING)
5480 var->constval.vstring = parser_strdup(cval->constval.vstring);
5481 else if (cval->expression.vtype == TYPE_FIELD)
5482 var->constval.vfield = cval;
5484 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5490 shunt sy = { NULL, NULL, NULL, NULL };
5493 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5494 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5495 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5496 if (!parser_sy_apply_operator(parser, &sy))
5499 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5500 parseerror(parser, "internal error: leaked operands");
5501 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5511 if (parser->tok == ',') {
5512 if (!parser_next(parser)) {
5513 parseerror(parser, "expected another variable");
5517 if (parser->tok != TOKEN_IDENT) {
5518 parseerror(parser, "expected another variable");
5521 var = ast_value_copy(basetype);
5523 ast_value_set_name(var, parser_tokval(parser));
5524 if (!parser_next(parser)) {
5525 parseerror(parser, "error parsing variable declaration");
5531 if (parser->tok != ';') {
5532 parseerror(parser, "missing semicolon after variables");
5536 if (!parser_next(parser)) {
5537 parseerror(parser, "parse error after variable declaration");
5541 ast_delete(basetype);
5545 if (cleanvar && var)
5547 ast_delete(basetype);
5551 ast_delete(basetype);
5552 if (cleanvar && var)
5554 if (me[0]) ast_member_delete(me[0]);
5555 if (me[1]) ast_member_delete(me[1]);
5556 if (me[2]) ast_member_delete(me[2]);
5560 static bool parser_global_statement(parser_t *parser)
5564 bool is_static = false;
5565 uint32_t qflags = 0;
5566 ast_value *istype = NULL;
5567 char *vstring = NULL;
5569 if (parser->tok == TOKEN_IDENT)
5570 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5572 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5574 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5576 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5578 if (cvq == CV_WRONG)
5580 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5582 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5584 return parse_enum(parser);
5586 else if (parser->tok == TOKEN_KEYWORD)
5588 if (!strcmp(parser_tokval(parser), "typedef")) {
5589 if (!parser_next(parser)) {
5590 parseerror(parser, "expected type definition after 'typedef'");
5593 return parse_typedef(parser);
5595 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5598 else if (parser->tok == '#')
5600 return parse_pragma(parser);
5602 else if (parser->tok == '$')
5604 if (!parser_next(parser)) {
5605 parseerror(parser, "parse error");
5611 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5617 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5619 return util_crc16(old, str, strlen(str));
5622 static void progdefs_crc_file(const char *str)
5624 /* write to progdefs.h here */
5628 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5630 old = progdefs_crc_sum(old, str);
5631 progdefs_crc_file(str);
5635 static void generate_checksum(parser_t *parser)
5637 uint16_t crc = 0xFFFF;
5641 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5642 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5644 progdefs_crc_file("\tint\tpad;\n");
5645 progdefs_crc_file("\tint\tofs_return[3];\n");
5646 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5647 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5648 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5649 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5650 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5651 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5652 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5653 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5655 for (i = 0; i < parser->crc_globals; ++i) {
5656 if (!ast_istype(parser->globals[i], ast_value))
5658 value = (ast_value*)(parser->globals[i]);
5659 switch (value->expression.vtype) {
5660 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5661 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5662 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5663 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5665 crc = progdefs_crc_both(crc, "\tint\t");
5668 crc = progdefs_crc_both(crc, value->name);
5669 crc = progdefs_crc_both(crc, ";\n");
5671 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5672 for (i = 0; i < parser->crc_fields; ++i) {
5673 if (!ast_istype(parser->fields[i], ast_value))
5675 value = (ast_value*)(parser->fields[i]);
5676 switch (value->expression.next->expression.vtype) {
5677 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5678 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5679 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5680 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5682 crc = progdefs_crc_both(crc, "\tint\t");
5685 crc = progdefs_crc_both(crc, value->name);
5686 crc = progdefs_crc_both(crc, ";\n");
5688 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5693 static parser_t *parser;
5700 parser = (parser_t*)mem_a(sizeof(parser_t));
5704 memset(parser, 0, sizeof(*parser));
5706 for (i = 0; i < operator_count; ++i) {
5707 if (operators[i].id == opid1('=')) {
5708 parser->assign_op = operators+i;
5712 if (!parser->assign_op) {
5713 printf("internal error: initializing parser: failed to find assign operator\n");
5718 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5719 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5720 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5721 vec_push(parser->_blocktypedefs, 0);
5724 vec_push(parser->correct_variables, correct_trie_new());
5725 vec_push(parser->correct_variables_score, NULL);
5727 empty_ctx.file = "<internal>";
5729 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5730 parser->nil->cvq = CV_CONST;
5731 if (OPTS_FLAG(UNTYPED_NIL))
5732 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5734 parser->max_param_count = 1;
5736 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5737 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5738 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5740 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5741 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5742 parser->reserved_version->cvq = CV_CONST;
5743 parser->reserved_version->hasvalue = true;
5744 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5745 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5747 parser->reserved_version = NULL;
5752 bool parser_compile()
5754 /* initial lexer/parser state */
5755 parser->lex->flags.noops = true;
5757 if (parser_next(parser))
5759 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5761 if (!parser_global_statement(parser)) {
5762 if (parser->tok == TOKEN_EOF)
5763 parseerror(parser, "unexpected eof");
5764 else if (compile_errors)
5765 parseerror(parser, "there have been errors, bailing out");
5766 lex_close(parser->lex);
5772 parseerror(parser, "parse error");
5773 lex_close(parser->lex);
5778 lex_close(parser->lex);
5781 return !compile_errors;
5784 bool parser_compile_file(const char *filename)
5786 parser->lex = lex_open(filename);
5788 con_err("failed to open file \"%s\"\n", filename);
5791 return parser_compile();
5794 bool parser_compile_string(const char *name, const char *str, size_t len)
5796 parser->lex = lex_open_string(str, len, name);
5798 con_err("failed to create lexer for string \"%s\"\n", name);
5801 return parser_compile();
5804 void parser_cleanup()
5807 for (i = 0; i < vec_size(parser->accessors); ++i) {
5808 ast_delete(parser->accessors[i]->constval.vfunc);
5809 parser->accessors[i]->constval.vfunc = NULL;
5810 ast_delete(parser->accessors[i]);
5812 for (i = 0; i < vec_size(parser->functions); ++i) {
5813 ast_delete(parser->functions[i]);
5815 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5816 ast_delete(parser->imm_vector[i]);
5818 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5819 ast_delete(parser->imm_string[i]);
5821 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5822 ast_delete(parser->imm_float[i]);
5824 for (i = 0; i < vec_size(parser->fields); ++i) {
5825 ast_delete(parser->fields[i]);
5827 for (i = 0; i < vec_size(parser->globals); ++i) {
5828 ast_delete(parser->globals[i]);
5830 vec_free(parser->accessors);
5831 vec_free(parser->functions);
5832 vec_free(parser->imm_vector);
5833 vec_free(parser->imm_string);
5834 vec_free(parser->imm_float);
5835 vec_free(parser->globals);
5836 vec_free(parser->fields);
5838 for (i = 0; i < vec_size(parser->variables); ++i)
5839 util_htdel(parser->variables[i]);
5840 vec_free(parser->variables);
5841 vec_free(parser->_blocklocals);
5842 vec_free(parser->_locals);
5845 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5846 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5848 vec_free(parser->correct_variables);
5849 vec_free(parser->correct_variables_score);
5852 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5853 ast_delete(parser->_typedefs[i]);
5854 vec_free(parser->_typedefs);
5855 for (i = 0; i < vec_size(parser->typedefs); ++i)
5856 util_htdel(parser->typedefs[i]);
5857 vec_free(parser->typedefs);
5858 vec_free(parser->_blocktypedefs);
5860 vec_free(parser->_block_ctx);
5862 vec_free(parser->labels);
5863 vec_free(parser->gotos);
5864 vec_free(parser->breaks);
5865 vec_free(parser->continues);
5867 ast_value_delete(parser->nil);
5869 ast_value_delete(parser->const_vec[0]);
5870 ast_value_delete(parser->const_vec[1]);
5871 ast_value_delete(parser->const_vec[2]);
5876 bool parser_finish(const char *output)
5882 if (compile_errors) {
5883 con_out("*** there were compile errors\n");
5887 ir = ir_builder_new("gmqcc_out");
5889 con_out("failed to allocate builder\n");
5893 for (i = 0; i < vec_size(parser->fields); ++i) {
5896 if (!ast_istype(parser->fields[i], ast_value))
5898 field = (ast_value*)parser->fields[i];
5899 hasvalue = field->hasvalue;
5900 field->hasvalue = false;
5901 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5902 con_out("failed to generate field %s\n", field->name);
5903 ir_builder_delete(ir);
5908 ast_expression *subtype;
5909 field->hasvalue = true;
5910 subtype = field->expression.next;
5911 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5912 if (subtype->expression.vtype == TYPE_FIELD)
5913 ifld->fieldtype = subtype->expression.next->expression.vtype;
5914 else if (subtype->expression.vtype == TYPE_FUNCTION)
5915 ifld->outtype = subtype->expression.next->expression.vtype;
5916 (void)!ir_value_set_field(field->ir_v, ifld);
5919 for (i = 0; i < vec_size(parser->globals); ++i) {
5921 if (!ast_istype(parser->globals[i], ast_value))
5923 asvalue = (ast_value*)(parser->globals[i]);
5924 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5925 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5926 "unused global: `%s`", asvalue->name);
5928 if (!ast_global_codegen(asvalue, ir, false)) {
5929 con_out("failed to generate global %s\n", asvalue->name);
5930 ir_builder_delete(ir);
5934 /* Build function vararg accessor ast tree now before generating
5935 * immediates, because the accessors may add new immediates
5937 for (i = 0; i < vec_size(parser->functions); ++i) {
5938 ast_function *f = parser->functions[i];
5940 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5941 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5942 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5943 con_out("failed to generate vararg setter for %s\n", f->name);
5944 ir_builder_delete(ir);
5947 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5948 con_out("failed to generate vararg getter for %s\n", f->name);
5949 ir_builder_delete(ir);
5953 ast_delete(f->varargs);
5958 /* Now we can generate immediates */
5959 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5960 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5961 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5962 ir_builder_delete(ir);
5966 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5967 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5968 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5969 ir_builder_delete(ir);
5973 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5974 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5975 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5976 ir_builder_delete(ir);
5980 for (i = 0; i < vec_size(parser->globals); ++i) {
5982 if (!ast_istype(parser->globals[i], ast_value))
5984 asvalue = (ast_value*)(parser->globals[i]);
5985 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5987 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5988 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5989 "uninitialized constant: `%s`",
5991 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5992 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5993 "uninitialized global: `%s`",
5996 if (!ast_generate_accessors(asvalue, ir)) {
5997 ir_builder_delete(ir);
6001 for (i = 0; i < vec_size(parser->fields); ++i) {
6003 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6005 if (!ast_istype((ast_expression*)asvalue, ast_value))
6007 if (asvalue->expression.vtype != TYPE_ARRAY)
6009 if (!ast_generate_accessors(asvalue, ir)) {
6010 ir_builder_delete(ir);
6014 if (parser->reserved_version &&
6015 !ast_global_codegen(parser->reserved_version, ir, false))
6017 con_out("failed to generate reserved::version");
6018 ir_builder_delete(ir);
6021 for (i = 0; i < vec_size(parser->functions); ++i) {
6022 ast_function *f = parser->functions[i];
6023 if (!ast_function_codegen(f, ir)) {
6024 con_out("failed to generate function %s\n", f->name);
6025 ir_builder_delete(ir);
6029 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6030 ir_builder_dump(ir, con_out);
6031 for (i = 0; i < vec_size(parser->functions); ++i) {
6032 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6033 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6034 ir_builder_delete(ir);
6039 if (compile_Werrors) {
6040 con_out("*** there were warnings treated as errors\n");
6041 compile_show_werrors();
6046 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6047 ir_builder_dump(ir, con_out);
6049 generate_checksum(parser);
6051 if (!ir_builder_generate(ir, output)) {
6052 con_out("*** failed to generate output file\n");
6053 ir_builder_delete(ir);
6058 ir_builder_delete(ir);