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 if (!ast_block_set_type(blocks[0], exprs[1]))
677 vec_push(sy->out, syblock(ctx, blocks[0]));
684 switch (exprs[0]->expression.vtype) {
686 if (CanConstFold1(exprs[0]))
687 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
689 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
690 (ast_expression*)parser_const_float_0(parser),
694 if (CanConstFold1(exprs[0]))
695 out = (ast_expression*)parser_const_vector_f(parser,
696 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
698 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
699 (ast_expression*)parser_const_vector_0(parser),
703 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
704 type_name[exprs[0]->expression.vtype]);
710 switch (exprs[0]->expression.vtype) {
712 if (CanConstFold1(exprs[0]))
713 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
715 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
718 if (CanConstFold1(exprs[0]))
719 out = (ast_expression*)parser_const_float(parser,
720 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
725 if (CanConstFold1(exprs[0])) {
726 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
727 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
729 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
731 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
732 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
734 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
737 /* we don't constant-fold NOT for these types */
739 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
742 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
745 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
746 type_name[exprs[0]->expression.vtype]);
752 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
753 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
755 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
756 type_name[exprs[0]->expression.vtype],
757 type_name[exprs[1]->expression.vtype]);
760 switch (exprs[0]->expression.vtype) {
762 if (CanConstFold(exprs[0], exprs[1]))
764 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
767 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
770 if (CanConstFold(exprs[0], exprs[1]))
771 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
773 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
776 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
777 type_name[exprs[0]->expression.vtype],
778 type_name[exprs[1]->expression.vtype]);
783 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
784 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
786 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
787 type_name[exprs[1]->expression.vtype],
788 type_name[exprs[0]->expression.vtype]);
791 switch (exprs[0]->expression.vtype) {
793 if (CanConstFold(exprs[0], exprs[1]))
794 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
796 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
799 if (CanConstFold(exprs[0], exprs[1]))
800 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
802 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
805 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
806 type_name[exprs[1]->expression.vtype],
807 type_name[exprs[0]->expression.vtype]);
812 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
813 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
814 exprs[1]->expression.vtype == TYPE_FLOAT) &&
815 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
816 exprs[0]->expression.vtype == TYPE_FLOAT)
819 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
820 type_name[exprs[1]->expression.vtype],
821 type_name[exprs[0]->expression.vtype]);
824 switch (exprs[0]->expression.vtype) {
826 if (exprs[1]->expression.vtype == TYPE_VECTOR)
828 if (CanConstFold(exprs[0], exprs[1]))
829 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
831 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
835 if (CanConstFold(exprs[0], exprs[1]))
836 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
838 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
842 if (exprs[1]->expression.vtype == TYPE_FLOAT)
844 if (CanConstFold(exprs[0], exprs[1]))
845 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
847 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
851 if (CanConstFold(exprs[0], exprs[1]))
852 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
853 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
854 vector vec = ConstV(0);
855 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
856 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
857 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
858 out->expression.node.keep = false;
859 ((ast_member*)out)->rvalue = true;
861 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
863 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
864 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
865 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
866 out->expression.node.keep = false;
867 ((ast_member*)out)->rvalue = true;
869 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
871 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
872 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
873 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
874 out->expression.node.keep = false;
875 ((ast_member*)out)->rvalue = true;
877 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
880 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
882 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
883 vector vec = ConstV(1);
884 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
885 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
886 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
887 out->expression.node.keep = false;
888 ((ast_member*)out)->rvalue = true;
890 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
892 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
893 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
894 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
895 out->expression.node.keep = false;
896 ((ast_member*)out)->rvalue = true;
898 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
900 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
901 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
902 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
903 out->expression.node.keep = false;
904 ((ast_member*)out)->rvalue = true;
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
909 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
912 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
916 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
917 type_name[exprs[1]->expression.vtype],
918 type_name[exprs[0]->expression.vtype]);
923 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
924 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
925 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
926 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
929 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
930 if (CanConstFold(exprs[0], exprs[1]))
931 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
933 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
935 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
936 if (CanConstFold(exprs[0], exprs[1]))
937 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
939 if (CanConstFold1(exprs[1])) {
940 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
942 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
943 (ast_expression*)parser_const_float_1(parser),
947 compile_error(ctx, "internal error: failed to generate division");
950 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
955 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
956 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
957 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
963 compile_error(ctx, "qc does not have a modulo operator");
967 if (NotSameType(TYPE_FLOAT)) {
968 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
969 type_name[exprs[0]->expression.vtype],
970 type_name[exprs[1]->expression.vtype]);
973 if (CanConstFold(exprs[0], exprs[1]))
974 out = (ast_expression*)parser_const_float(parser,
975 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
976 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
978 out = (ast_expression*)ast_binary_new(ctx,
979 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
983 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
988 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
989 if (op->id == opid2('<','<'))
990 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
992 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
995 case opid3('<','<','='):
996 case opid3('>','>','='):
997 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1000 case opid2('|','|'):
1001 generated_op += 1; /* INSTR_OR */
1002 case opid2('&','&'):
1003 generated_op += INSTR_AND;
1004 if (CanConstFold(exprs[0], exprs[1]))
1006 if (OPTS_FLAG(PERL_LOGIC)) {
1007 if (immediate_is_true(ctx, asvalue[0]))
1011 out = (ast_expression*)parser_const_float(parser,
1012 ( (generated_op == INSTR_OR)
1013 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1014 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1019 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1020 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1021 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1022 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1025 for (i = 0; i < 2; ++i) {
1026 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1027 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1029 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1031 exprs[i] = out; out = NULL;
1032 if (OPTS_FLAG(PERL_LOGIC)) {
1033 /* here we want to keep the right expressions' type */
1037 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1038 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1040 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1042 exprs[i] = out; out = NULL;
1043 if (OPTS_FLAG(PERL_LOGIC)) {
1044 /* here we want to keep the right expressions' type */
1049 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1053 case opid2('?',':'):
1054 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1055 compile_error(ctx, "mismatched parenthesis/ternary");
1059 if (!ast_compare_type(exprs[1], exprs[2])) {
1060 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1061 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1062 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1065 if (CanConstFold1(exprs[0]))
1066 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1068 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1071 case opid3('<', '=', '>'): /* -1, 0, or 1 */
1072 if (NotSameType(TYPE_FLOAT)) {
1073 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1075 compile_error(ctx, "invalid types used in comparision: %s and %s",
1081 if (CanConstFold(exprs[0], exprs[1])) {
1082 if (ConstF(0) < ConstF(1))
1083 out = (ast_expression*)parser_const_float_neg1(parser);
1084 else if (ConstF(0) == ConstF(1))
1085 out = (ast_expression*)parser_const_float_0(parser);
1086 else if (ConstF(0) > ConstF(1))
1087 out = (ast_expression*)parser_const_float_1(parser);
1090 out = (ast_expression*)ast_ternary_new(ctx,
1091 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1094 (ast_expression*)parser_const_float_neg1(parser),
1098 (ast_expression*)ast_ternary_new(ctx,
1099 (ast_expression*)ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]),
1102 (ast_expression*)parser_const_float_0(parser),
1107 (ast_expression*)parser_const_float_1(parser)
1117 generated_op += 1; /* INSTR_GT */
1119 generated_op += 1; /* INSTR_LT */
1120 case opid2('>', '='):
1121 generated_op += 1; /* INSTR_GE */
1122 case opid2('<', '='):
1123 generated_op += INSTR_LE;
1124 if (NotSameType(TYPE_FLOAT)) {
1125 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1126 type_name[exprs[0]->expression.vtype],
1127 type_name[exprs[1]->expression.vtype]);
1130 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1132 case opid2('!', '='):
1133 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1134 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1135 type_name[exprs[0]->expression.vtype],
1136 type_name[exprs[1]->expression.vtype]);
1139 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1141 case opid2('=', '='):
1142 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1143 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1144 type_name[exprs[0]->expression.vtype],
1145 type_name[exprs[1]->expression.vtype]);
1148 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1152 if (ast_istype(exprs[0], ast_entfield)) {
1153 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1154 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1155 exprs[0]->expression.vtype == TYPE_FIELD &&
1156 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1158 assignop = type_storep_instr[TYPE_VECTOR];
1161 assignop = type_storep_instr[exprs[0]->expression.vtype];
1162 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1164 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1165 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1166 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1167 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1168 exprs[1]->expression.vtype == TYPE_FUNCTION)
1170 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1171 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1174 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1179 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1180 exprs[0]->expression.vtype == TYPE_FIELD &&
1181 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1183 assignop = type_store_instr[TYPE_VECTOR];
1186 assignop = type_store_instr[exprs[0]->expression.vtype];
1189 if (assignop == VINSTR_END) {
1190 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1191 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1192 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1194 else if (!ast_compare_type(exprs[0], exprs[1]))
1196 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1197 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1198 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1199 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1200 exprs[1]->expression.vtype == TYPE_FUNCTION)
1202 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1203 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1206 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1209 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1210 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1212 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1214 case opid3('+','+','P'):
1215 case opid3('-','-','P'):
1217 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1218 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1219 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1222 if (op->id == opid3('+','+','P'))
1223 addop = INSTR_ADD_F;
1225 addop = INSTR_SUB_F;
1226 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1227 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1229 if (ast_istype(exprs[0], ast_entfield)) {
1230 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1232 (ast_expression*)parser_const_float_1(parser));
1234 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1236 (ast_expression*)parser_const_float_1(parser));
1239 case opid3('S','+','+'):
1240 case opid3('S','-','-'):
1242 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1243 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1244 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1247 if (op->id == opid3('S','+','+')) {
1248 addop = INSTR_ADD_F;
1249 subop = INSTR_SUB_F;
1251 addop = INSTR_SUB_F;
1252 subop = INSTR_ADD_F;
1254 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1255 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1257 if (ast_istype(exprs[0], ast_entfield)) {
1258 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1260 (ast_expression*)parser_const_float_1(parser));
1262 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1264 (ast_expression*)parser_const_float_1(parser));
1268 out = (ast_expression*)ast_binary_new(ctx, subop,
1270 (ast_expression*)parser_const_float_1(parser));
1272 case opid2('+','='):
1273 case opid2('-','='):
1274 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1275 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1277 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1278 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1279 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1283 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1284 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1286 if (ast_istype(exprs[0], ast_entfield))
1287 assignop = type_storep_instr[exprs[0]->expression.vtype];
1289 assignop = type_store_instr[exprs[0]->expression.vtype];
1290 switch (exprs[0]->expression.vtype) {
1292 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1293 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1294 exprs[0], exprs[1]);
1297 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1298 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1299 exprs[0], exprs[1]);
1302 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1303 type_name[exprs[0]->expression.vtype],
1304 type_name[exprs[1]->expression.vtype]);
1308 case opid2('*','='):
1309 case opid2('/','='):
1310 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1311 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1312 exprs[0]->expression.vtype == TYPE_VECTOR))
1314 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1315 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1316 compile_error(ctx, "invalid types used in expression: %s and %s",
1320 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1321 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1323 if (ast_istype(exprs[0], ast_entfield))
1324 assignop = type_storep_instr[exprs[0]->expression.vtype];
1326 assignop = type_store_instr[exprs[0]->expression.vtype];
1327 switch (exprs[0]->expression.vtype) {
1329 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1330 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1331 exprs[0], exprs[1]);
1334 if (op->id == opid2('*','=')) {
1335 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1336 exprs[0], exprs[1]);
1338 /* there's no DIV_VF */
1339 if (CanConstFold1(exprs[1])) {
1340 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1342 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1343 (ast_expression*)parser_const_float_1(parser),
1347 compile_error(ctx, "internal error: failed to generate division");
1350 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1355 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1356 type_name[exprs[0]->expression.vtype],
1357 type_name[exprs[1]->expression.vtype]);
1361 case opid2('&','='):
1362 case opid2('|','='):
1363 if (NotSameType(TYPE_FLOAT)) {
1364 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1365 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1366 compile_error(ctx, "invalid types used in expression: %s and %s",
1370 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1371 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1373 if (ast_istype(exprs[0], ast_entfield))
1374 assignop = type_storep_instr[exprs[0]->expression.vtype];
1376 assignop = type_store_instr[exprs[0]->expression.vtype];
1377 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1378 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1379 exprs[0], exprs[1]);
1381 case opid3('&','~','='):
1382 /* This is like: a &= ~(b);
1383 * But QC has no bitwise-not, so we implement it as
1386 if (NotSameType(TYPE_FLOAT)) {
1387 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1388 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1389 compile_error(ctx, "invalid types used in expression: %s and %s",
1393 if (ast_istype(exprs[0], ast_entfield))
1394 assignop = type_storep_instr[exprs[0]->expression.vtype];
1396 assignop = type_store_instr[exprs[0]->expression.vtype];
1397 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1400 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1401 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1403 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1404 asbinstore->keep_dest = true;
1405 out = (ast_expression*)asbinstore;
1408 case opid2('~', 'P'):
1409 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1410 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1411 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1415 if(CanConstFold1(exprs[0]))
1416 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1418 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1424 compile_error(ctx, "failed to apply operator %s", op->op);
1428 vec_push(sy->out, syexp(ctx, out));
1432 static bool parser_close_call(parser_t *parser, shunt *sy)
1434 /* was a function call */
1435 ast_expression *fun;
1436 ast_value *funval = NULL;
1440 size_t paramcount, i;
1442 fid = vec_last(sy->ops).off;
1443 vec_shrinkby(sy->ops, 1);
1445 /* out[fid] is the function
1446 * everything above is parameters...
1448 if (!vec_size(sy->argc)) {
1449 parseerror(parser, "internal error: no argument counter available");
1453 paramcount = vec_last(sy->argc);
1456 if (vec_size(sy->out) < fid) {
1457 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1458 (unsigned long)vec_size(sy->out),
1460 (unsigned long)paramcount);
1464 fun = sy->out[fid].out;
1466 if (fun == intrinsic_debug_typestring) {
1468 if (fid+2 != vec_size(sy->out) ||
1469 vec_last(sy->out).block)
1471 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1474 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1475 ast_unref(vec_last(sy->out).out);
1476 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1477 (ast_expression*)parser_const_string(parser, ty, false));
1478 vec_shrinkby(sy->out, 1);
1482 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1486 if (fid+1 < vec_size(sy->out))
1489 if (fid+1 + paramcount != vec_size(sy->out)) {
1490 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1491 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1495 for (i = 0; i < paramcount; ++i)
1496 vec_push(call->params, sy->out[fid+1 + i].out);
1497 vec_shrinkby(sy->out, paramcount);
1498 (void)!ast_call_check_types(call);
1499 if (parser->max_param_count < paramcount)
1500 parser->max_param_count = paramcount;
1502 if (ast_istype(fun, ast_value)) {
1503 funval = (ast_value*)fun;
1504 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1505 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1507 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1511 /* overwrite fid, the function, with a call */
1512 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1514 if (fun->expression.vtype != TYPE_FUNCTION) {
1515 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1519 if (!fun->expression.next) {
1520 parseerror(parser, "could not determine function return type");
1523 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1525 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1527 return !parsewarning(parser, WARN_DEPRECATED,
1528 "call to function (which is marked deprecated)\n",
1529 "-> it has been declared here: %s:%i",
1530 ast_ctx(fun).file, ast_ctx(fun).line);
1533 return !parsewarning(parser, WARN_DEPRECATED,
1534 "call to `%s` (which is marked deprecated)\n"
1535 "-> `%s` declared here: %s:%i",
1536 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1538 return !parsewarning(parser, WARN_DEPRECATED,
1539 "call to `%s` (deprecated: %s)\n"
1540 "-> `%s` declared here: %s:%i",
1541 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1545 if (vec_size(fun->expression.params) != paramcount &&
1546 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1547 vec_size(fun->expression.params) < paramcount))
1549 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1551 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1552 "too %s parameters for call to %s: expected %i, got %i\n"
1553 " -> `%s` has been declared here: %s:%i",
1554 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1555 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1557 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1558 "too %s parameters for function call: expected %i, got %i\n"
1559 " -> it has been declared here: %s:%i",
1560 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1561 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1568 static bool parser_close_paren(parser_t *parser, shunt *sy)
1570 if (!vec_size(sy->ops)) {
1571 parseerror(parser, "unmatched closing paren");
1575 while (vec_size(sy->ops)) {
1576 if (vec_last(sy->ops).isparen) {
1577 if (vec_last(sy->paren) == PAREN_FUNC) {
1579 if (!parser_close_call(parser, sy))
1583 if (vec_last(sy->paren) == PAREN_EXPR) {
1585 if (!vec_size(sy->out)) {
1586 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1587 vec_shrinkby(sy->ops, 1);
1590 vec_shrinkby(sy->ops, 1);
1593 if (vec_last(sy->paren) == PAREN_INDEX) {
1595 /* pop off the parenthesis */
1596 vec_shrinkby(sy->ops, 1);
1597 /* then apply the index operator */
1598 if (!parser_sy_apply_operator(parser, sy))
1602 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1603 vec_last(sy->paren) = PAREN_TERNARY2;
1604 /* pop off the parenthesis */
1605 vec_shrinkby(sy->ops, 1);
1608 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1611 if (!parser_sy_apply_operator(parser, sy))
1617 static void parser_reclassify_token(parser_t *parser)
1620 for (i = 0; i < operator_count; ++i) {
1621 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1622 parser->tok = TOKEN_OPERATOR;
1628 static ast_expression* parse_vararg_do(parser_t *parser)
1630 ast_expression *idx, *out;
1632 ast_value *funtype = parser->function->vtype;
1634 lex_ctx ctx = parser_ctx(parser);
1636 if (!parser_next(parser) || parser->tok != '(') {
1637 parseerror(parser, "expected parameter index and type in parenthesis");
1640 if (!parser_next(parser)) {
1641 parseerror(parser, "error parsing parameter index");
1645 idx = parse_expression_leave(parser, true, false, false);
1649 if (parser->tok != ',') {
1651 parseerror(parser, "expected comma after parameter index");
1655 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1657 parseerror(parser, "expected typename for vararg");
1661 typevar = parse_typename(parser, NULL, NULL);
1667 if (parser->tok != ')') {
1669 ast_delete(typevar);
1670 parseerror(parser, "expected closing paren");
1675 if (!parser_next(parser)) {
1677 ast_delete(typevar);
1678 parseerror(parser, "parse error after vararg");
1683 if (!parser->function->varargs) {
1685 ast_delete(typevar);
1686 parseerror(parser, "function has no variable argument list");
1690 if (funtype->expression.varparam &&
1691 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1695 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1696 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1697 compile_error(ast_ctx(typevar),
1698 "function was declared to take varargs of type `%s`, requested type is: %s",
1702 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1703 ast_type_adopt(out, typevar);
1704 ast_delete(typevar);
1708 static ast_expression* parse_vararg(parser_t *parser)
1710 bool old_noops = parser->lex->flags.noops;
1712 ast_expression *out;
1714 parser->lex->flags.noops = true;
1715 out = parse_vararg_do(parser);
1717 parser->lex->flags.noops = old_noops;
1721 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1723 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1724 parser->tok == TOKEN_IDENT &&
1725 !strcmp(parser_tokval(parser), "_"))
1727 /* a translatable string */
1730 parser->lex->flags.noops = true;
1731 if (!parser_next(parser) || parser->tok != '(') {
1732 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1735 parser->lex->flags.noops = false;
1736 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1737 parseerror(parser, "expected a constant string in translatable-string extension");
1740 val = parser_const_string(parser, parser_tokval(parser), true);
1743 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1745 if (!parser_next(parser) || parser->tok != ')') {
1746 parseerror(parser, "expected closing paren after translatable string");
1751 else if (parser->tok == TOKEN_DOTS)
1754 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1755 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1758 va = parse_vararg(parser);
1761 vec_push(sy->out, syexp(parser_ctx(parser), va));
1764 else if (parser->tok == TOKEN_FLOATCONST) {
1766 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1769 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1772 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1774 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1777 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1780 else if (parser->tok == TOKEN_STRINGCONST) {
1782 val = parser_const_string(parser, parser_tokval(parser), false);
1785 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1788 else if (parser->tok == TOKEN_VECTORCONST) {
1790 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1793 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1796 else if (parser->tok == TOKEN_IDENT)
1798 const char *ctoken = parser_tokval(parser);
1799 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1800 ast_expression *var;
1801 /* a_vector.{x,y,z} */
1802 if (!vec_size(sy->ops) ||
1803 !vec_last(sy->ops).etype ||
1804 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1805 (prev >= intrinsic_debug_typestring &&
1806 prev <= intrinsic_debug_typestring))
1808 /* When adding more intrinsics, fix the above condition */
1811 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1813 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1815 var = parser_find_var(parser, parser_tokval(parser));
1817 var = parser_find_field(parser, parser_tokval(parser));
1819 if (!var && with_labels) {
1820 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1822 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1823 var = (ast_expression*)lbl;
1824 vec_push(parser->labels, lbl);
1829 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1830 var = (ast_expression*)intrinsic_debug_typestring;
1834 char *correct = NULL;
1838 * sometimes people use preprocessing predefs without enabling them
1839 * i've done this thousands of times already myself. Lets check for
1840 * it in the predef table. And diagnose it better :)
1842 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1843 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1844 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1845 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1852 * TODO: determine the best score for the identifier: be it
1853 * a variable, a field.
1855 * We should also consider adding correction tables for
1856 * other things as well.
1858 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1860 correct_init(&corr);
1862 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1863 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1864 if (strcmp(correct, parser_tokval(parser))) {
1866 } else if (correct) {
1871 correct_free(&corr);
1874 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1879 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1885 if (ast_istype(var, ast_value)) {
1886 ((ast_value*)var)->uses++;
1888 else if (ast_istype(var, ast_member)) {
1889 ast_member *mem = (ast_member*)var;
1890 if (ast_istype(mem->owner, ast_value))
1891 ((ast_value*)(mem->owner))->uses++;
1894 vec_push(sy->out, syexp(parser_ctx(parser), var));
1897 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1901 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1903 ast_expression *expr = NULL;
1906 bool wantop = false;
1907 /* only warn once about an assignment in a truth value because the current code
1908 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1910 bool warn_truthvalue = true;
1912 /* count the parens because an if starts with one, so the
1913 * end of a condition is an unmatched closing paren
1917 memset(&sy, 0, sizeof(sy));
1919 parser->lex->flags.noops = false;
1921 parser_reclassify_token(parser);
1925 if (parser->tok == TOKEN_TYPENAME) {
1926 parseerror(parser, "unexpected typename");
1930 if (parser->tok == TOKEN_OPERATOR)
1932 /* classify the operator */
1933 const oper_info *op;
1934 const oper_info *olast = NULL;
1936 for (o = 0; o < operator_count; ++o) {
1937 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1938 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1939 !strcmp(parser_tokval(parser), operators[o].op))
1944 if (o == operator_count) {
1945 /* no operator found... must be the end of the statement */
1946 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1949 /*Are there any expressions which actually end with an operator?*/
1952 /* found an operator */
1955 /* when declaring variables, a comma starts a new variable */
1956 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1957 /* fixup the token */
1962 /* a colon without a pervious question mark cannot be a ternary */
1963 if (!ternaries && op->id == opid2(':','?')) {
1968 if (op->id == opid1(',')) {
1969 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1970 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1974 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1975 olast = &operators[vec_last(sy.ops).etype-1];
1977 #define IsAssignOp(x) (\
1978 (x) == opid1('=') || \
1979 (x) == opid2('+','=') || \
1980 (x) == opid2('-','=') || \
1981 (x) == opid2('*','=') || \
1982 (x) == opid2('/','=') || \
1983 (x) == opid2('%','=') || \
1984 (x) == opid2('&','=') || \
1985 (x) == opid2('|','=') || \
1986 (x) == opid3('&','~','=') \
1988 if (warn_truthvalue) {
1989 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1990 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1991 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1994 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1995 warn_truthvalue = false;
2000 (op->prec < olast->prec) ||
2001 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2003 if (!parser_sy_apply_operator(parser, &sy))
2005 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2006 olast = &operators[vec_last(sy.ops).etype-1];
2011 if (op->id == opid1('(')) {
2013 size_t sycount = vec_size(sy.out);
2014 /* we expected an operator, this is the function-call operator */
2015 vec_push(sy.paren, PAREN_FUNC);
2016 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2017 vec_push(sy.argc, 0);
2019 vec_push(sy.paren, PAREN_EXPR);
2020 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2023 } else if (op->id == opid1('[')) {
2025 parseerror(parser, "unexpected array subscript");
2028 vec_push(sy.paren, PAREN_INDEX);
2029 /* push both the operator and the paren, this makes life easier */
2030 vec_push(sy.ops, syop(parser_ctx(parser), op));
2031 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2033 } else if (op->id == opid2('?',':')) {
2034 vec_push(sy.ops, syop(parser_ctx(parser), op));
2035 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2038 vec_push(sy.paren, PAREN_TERNARY1);
2039 } else if (op->id == opid2(':','?')) {
2040 if (!vec_size(sy.paren)) {
2041 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2044 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2045 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2048 if (!parser_close_paren(parser, &sy))
2050 vec_push(sy.ops, syop(parser_ctx(parser), op));
2054 vec_push(sy.ops, syop(parser_ctx(parser), op));
2055 wantop = !!(op->flags & OP_SUFFIX);
2058 else if (parser->tok == ')') {
2059 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2060 if (!parser_sy_apply_operator(parser, &sy))
2063 if (!vec_size(sy.paren))
2066 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2067 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2070 if (!parser_close_paren(parser, &sy))
2073 /* must be a function call without parameters */
2074 if (vec_last(sy.paren) != PAREN_FUNC) {
2075 parseerror(parser, "closing paren in invalid position");
2078 if (!parser_close_paren(parser, &sy))
2083 else if (parser->tok == '(') {
2084 parseerror(parser, "internal error: '(' should be classified as operator");
2087 else if (parser->tok == '[') {
2088 parseerror(parser, "internal error: '[' should be classified as operator");
2091 else if (parser->tok == ']') {
2092 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2093 if (!parser_sy_apply_operator(parser, &sy))
2096 if (!vec_size(sy.paren))
2098 if (vec_last(sy.paren) != PAREN_INDEX) {
2099 parseerror(parser, "mismatched parentheses, unexpected ']'");
2102 if (!parser_close_paren(parser, &sy))
2107 if (!parse_sya_operand(parser, &sy, with_labels))
2110 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2111 vec_last(sy.argc)++;
2116 parseerror(parser, "expected operator or end of statement");
2120 if (!parser_next(parser)) {
2123 if (parser->tok == ';' ||
2124 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2125 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2131 while (vec_size(sy.ops)) {
2132 if (!parser_sy_apply_operator(parser, &sy))
2136 parser->lex->flags.noops = true;
2137 if (!vec_size(sy.out)) {
2138 parseerror(parser, "empty expression");
2141 expr = sy.out[0].out;
2144 if (vec_size(sy.paren)) {
2145 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2153 parser->lex->flags.noops = true;
2154 for (i = 0; i < vec_size(sy.out); ++i) {
2156 ast_unref(sy.out[i].out);
2165 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2167 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2170 if (parser->tok != ';') {
2171 parseerror(parser, "semicolon expected after expression");
2175 if (!parser_next(parser)) {
2182 static void parser_enterblock(parser_t *parser)
2184 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2185 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2186 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2187 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2188 vec_push(parser->_block_ctx, parser_ctx(parser));
2191 vec_push(parser->correct_variables, correct_trie_new());
2192 vec_push(parser->correct_variables_score, NULL);
2195 static bool parser_leaveblock(parser_t *parser)
2198 size_t locals, typedefs;
2200 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2201 parseerror(parser, "internal error: parser_leaveblock with no block");
2205 util_htdel(vec_last(parser->variables));
2206 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2208 vec_pop(parser->variables);
2209 vec_pop(parser->correct_variables);
2210 vec_pop(parser->correct_variables_score);
2211 if (!vec_size(parser->_blocklocals)) {
2212 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2216 locals = vec_last(parser->_blocklocals);
2217 vec_pop(parser->_blocklocals);
2218 while (vec_size(parser->_locals) != locals) {
2219 ast_expression *e = vec_last(parser->_locals);
2220 ast_value *v = (ast_value*)e;
2221 vec_pop(parser->_locals);
2222 if (ast_istype(e, ast_value) && !v->uses) {
2223 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2228 typedefs = vec_last(parser->_blocktypedefs);
2229 while (vec_size(parser->_typedefs) != typedefs) {
2230 ast_delete(vec_last(parser->_typedefs));
2231 vec_pop(parser->_typedefs);
2233 util_htdel(vec_last(parser->typedefs));
2234 vec_pop(parser->typedefs);
2236 vec_pop(parser->_block_ctx);
2241 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2243 vec_push(parser->_locals, e);
2244 util_htset(vec_last(parser->variables), name, (void*)e);
2248 vec_last(parser->correct_variables),
2249 &vec_last(parser->correct_variables_score),
2254 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2256 vec_push(parser->globals, e);
2257 util_htset(parser->htglobals, name, e);
2261 parser->correct_variables[0],
2262 &parser->correct_variables_score[0],
2267 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2271 ast_expression *prev;
2273 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2275 ast_type_to_string(cond, ty, sizeof(ty));
2276 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2279 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2282 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2285 parseerror(parser, "internal error: failed to process condition");
2290 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2292 /* vector types need to be cast to true booleans */
2293 ast_binary *bin = (ast_binary*)cond;
2294 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2296 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2298 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2301 parseerror(parser, "internal error: failed to process condition");
2308 unary = (ast_unary*)cond;
2309 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2311 cond = unary->operand;
2312 unary->operand = NULL;
2315 unary = (ast_unary*)cond;
2319 parseerror(parser, "internal error: failed to process condition");
2321 if (ifnot) *_ifnot = !*_ifnot;
2325 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2328 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2331 lex_ctx ctx = parser_ctx(parser);
2333 (void)block; /* not touching */
2335 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2336 if (!parser_next(parser)) {
2337 parseerror(parser, "expected condition or 'not'");
2340 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2342 if (!parser_next(parser)) {
2343 parseerror(parser, "expected condition in parenthesis");
2347 if (parser->tok != '(') {
2348 parseerror(parser, "expected 'if' condition in parenthesis");
2351 /* parse into the expression */
2352 if (!parser_next(parser)) {
2353 parseerror(parser, "expected 'if' condition after opening paren");
2356 /* parse the condition */
2357 cond = parse_expression_leave(parser, false, true, false);
2361 if (parser->tok != ')') {
2362 parseerror(parser, "expected closing paren after 'if' condition");
2366 /* parse into the 'then' branch */
2367 if (!parser_next(parser)) {
2368 parseerror(parser, "expected statement for on-true branch of 'if'");
2372 if (!parse_statement_or_block(parser, &ontrue)) {
2377 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2378 /* check for an else */
2379 if (!strcmp(parser_tokval(parser), "else")) {
2380 /* parse into the 'else' branch */
2381 if (!parser_next(parser)) {
2382 parseerror(parser, "expected on-false branch after 'else'");
2387 if (!parse_statement_or_block(parser, &onfalse)) {
2394 cond = process_condition(parser, cond, &ifnot);
2396 if (ontrue) ast_delete(ontrue);
2397 if (onfalse) ast_delete(onfalse);
2402 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2404 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2405 *out = (ast_expression*)ifthen;
2409 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2410 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2415 /* skip the 'while' and get the body */
2416 if (!parser_next(parser)) {
2417 if (OPTS_FLAG(LOOP_LABELS))
2418 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2420 parseerror(parser, "expected 'while' condition in parenthesis");
2424 if (parser->tok == ':') {
2425 if (!OPTS_FLAG(LOOP_LABELS))
2426 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2427 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2428 parseerror(parser, "expected loop label");
2431 label = util_strdup(parser_tokval(parser));
2432 if (!parser_next(parser)) {
2434 parseerror(parser, "expected 'while' condition in parenthesis");
2439 if (parser->tok != '(') {
2440 parseerror(parser, "expected 'while' condition in parenthesis");
2444 vec_push(parser->breaks, label);
2445 vec_push(parser->continues, label);
2447 rv = parse_while_go(parser, block, out);
2450 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2451 parseerror(parser, "internal error: label stack corrupted");
2457 vec_pop(parser->breaks);
2458 vec_pop(parser->continues);
2463 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2466 ast_expression *cond, *ontrue;
2470 lex_ctx ctx = parser_ctx(parser);
2472 (void)block; /* not touching */
2474 /* parse into the expression */
2475 if (!parser_next(parser)) {
2476 parseerror(parser, "expected 'while' condition after opening paren");
2479 /* parse the condition */
2480 cond = parse_expression_leave(parser, false, true, false);
2484 if (parser->tok != ')') {
2485 parseerror(parser, "expected closing paren after 'while' condition");
2489 /* parse into the 'then' branch */
2490 if (!parser_next(parser)) {
2491 parseerror(parser, "expected while-loop body");
2495 if (!parse_statement_or_block(parser, &ontrue)) {
2500 cond = process_condition(parser, cond, &ifnot);
2505 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2506 *out = (ast_expression*)aloop;
2510 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2511 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2516 /* skip the 'do' and get the body */
2517 if (!parser_next(parser)) {
2518 if (OPTS_FLAG(LOOP_LABELS))
2519 parseerror(parser, "expected loop label or body");
2521 parseerror(parser, "expected loop body");
2525 if (parser->tok == ':') {
2526 if (!OPTS_FLAG(LOOP_LABELS))
2527 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2528 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2529 parseerror(parser, "expected loop label");
2532 label = util_strdup(parser_tokval(parser));
2533 if (!parser_next(parser)) {
2535 parseerror(parser, "expected loop body");
2540 vec_push(parser->breaks, label);
2541 vec_push(parser->continues, label);
2543 rv = parse_dowhile_go(parser, block, out);
2546 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2547 parseerror(parser, "internal error: label stack corrupted");
2553 vec_pop(parser->breaks);
2554 vec_pop(parser->continues);
2559 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2562 ast_expression *cond, *ontrue;
2566 lex_ctx ctx = parser_ctx(parser);
2568 (void)block; /* not touching */
2570 if (!parse_statement_or_block(parser, &ontrue))
2573 /* expect the "while" */
2574 if (parser->tok != TOKEN_KEYWORD ||
2575 strcmp(parser_tokval(parser), "while"))
2577 parseerror(parser, "expected 'while' and condition");
2582 /* skip the 'while' and check for opening paren */
2583 if (!parser_next(parser) || parser->tok != '(') {
2584 parseerror(parser, "expected 'while' condition in parenthesis");
2588 /* parse into the expression */
2589 if (!parser_next(parser)) {
2590 parseerror(parser, "expected 'while' condition after opening paren");
2594 /* parse the condition */
2595 cond = parse_expression_leave(parser, false, true, false);
2599 if (parser->tok != ')') {
2600 parseerror(parser, "expected closing paren after 'while' condition");
2606 if (!parser_next(parser) || parser->tok != ';') {
2607 parseerror(parser, "expected semicolon after condition");
2613 if (!parser_next(parser)) {
2614 parseerror(parser, "parse error");
2620 cond = process_condition(parser, cond, &ifnot);
2625 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2626 *out = (ast_expression*)aloop;
2630 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2631 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2636 /* skip the 'for' and check for opening paren */
2637 if (!parser_next(parser)) {
2638 if (OPTS_FLAG(LOOP_LABELS))
2639 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2641 parseerror(parser, "expected 'for' expressions in parenthesis");
2645 if (parser->tok == ':') {
2646 if (!OPTS_FLAG(LOOP_LABELS))
2647 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2648 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2649 parseerror(parser, "expected loop label");
2652 label = util_strdup(parser_tokval(parser));
2653 if (!parser_next(parser)) {
2655 parseerror(parser, "expected 'for' expressions in parenthesis");
2660 if (parser->tok != '(') {
2661 parseerror(parser, "expected 'for' expressions in parenthesis");
2665 vec_push(parser->breaks, label);
2666 vec_push(parser->continues, label);
2668 rv = parse_for_go(parser, block, out);
2671 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2672 parseerror(parser, "internal error: label stack corrupted");
2678 vec_pop(parser->breaks);
2679 vec_pop(parser->continues);
2683 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2686 ast_expression *initexpr, *cond, *increment, *ontrue;
2692 lex_ctx ctx = parser_ctx(parser);
2694 parser_enterblock(parser);
2701 /* parse into the expression */
2702 if (!parser_next(parser)) {
2703 parseerror(parser, "expected 'for' initializer after opening paren");
2708 if (parser->tok == TOKEN_IDENT)
2709 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2711 if (typevar || parser->tok == TOKEN_TYPENAME) {
2713 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2714 if (parsewarning(parser, WARN_EXTENSIONS,
2715 "current standard does not allow variable declarations in for-loop initializers"))
2719 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2722 else if (parser->tok != ';')
2724 initexpr = parse_expression_leave(parser, false, false, false);
2729 /* move on to condition */
2730 if (parser->tok != ';') {
2731 parseerror(parser, "expected semicolon after for-loop initializer");
2734 if (!parser_next(parser)) {
2735 parseerror(parser, "expected for-loop condition");
2739 /* parse the condition */
2740 if (parser->tok != ';') {
2741 cond = parse_expression_leave(parser, false, true, false);
2746 /* move on to incrementor */
2747 if (parser->tok != ';') {
2748 parseerror(parser, "expected semicolon after for-loop initializer");
2751 if (!parser_next(parser)) {
2752 parseerror(parser, "expected for-loop condition");
2756 /* parse the incrementor */
2757 if (parser->tok != ')') {
2758 lex_ctx condctx = parser_ctx(parser);
2759 increment = parse_expression_leave(parser, false, false, false);
2762 if (!ast_side_effects(increment)) {
2763 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2769 if (parser->tok != ')') {
2770 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2773 /* parse into the 'then' branch */
2774 if (!parser_next(parser)) {
2775 parseerror(parser, "expected for-loop body");
2778 if (!parse_statement_or_block(parser, &ontrue))
2782 cond = process_condition(parser, cond, &ifnot);
2786 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2787 *out = (ast_expression*)aloop;
2789 if (!parser_leaveblock(parser))
2793 if (initexpr) ast_delete(initexpr);
2794 if (cond) ast_delete(cond);
2795 if (increment) ast_delete(increment);
2796 (void)!parser_leaveblock(parser);
2800 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2802 ast_expression *exp = NULL;
2803 ast_return *ret = NULL;
2804 ast_value *expected = parser->function->vtype;
2806 lex_ctx ctx = parser_ctx(parser);
2808 (void)block; /* not touching */
2810 if (!parser_next(parser)) {
2811 parseerror(parser, "expected return expression");
2815 if (parser->tok != ';') {
2816 exp = parse_expression(parser, false, false);
2820 if (exp->expression.vtype != TYPE_NIL &&
2821 exp->expression.vtype != expected->expression.next->expression.vtype)
2823 parseerror(parser, "return with invalid expression");
2826 ret = ast_return_new(ctx, exp);
2832 if (!parser_next(parser))
2833 parseerror(parser, "parse error");
2834 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2835 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2837 ret = ast_return_new(ctx, NULL);
2839 *out = (ast_expression*)ret;
2843 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2846 unsigned int levels = 0;
2847 lex_ctx ctx = parser_ctx(parser);
2848 const char **loops = (is_continue ? parser->continues : parser->breaks);
2850 (void)block; /* not touching */
2851 if (!parser_next(parser)) {
2852 parseerror(parser, "expected semicolon or loop label");
2856 if (!vec_size(loops)) {
2858 parseerror(parser, "`continue` can only be used inside loops");
2860 parseerror(parser, "`break` can only be used inside loops or switches");
2863 if (parser->tok == TOKEN_IDENT) {
2864 if (!OPTS_FLAG(LOOP_LABELS))
2865 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2866 i = vec_size(loops);
2868 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2871 parseerror(parser, "no such loop to %s: `%s`",
2872 (is_continue ? "continue" : "break out of"),
2873 parser_tokval(parser));
2878 if (!parser_next(parser)) {
2879 parseerror(parser, "expected semicolon");
2884 if (parser->tok != ';') {
2885 parseerror(parser, "expected semicolon");
2889 if (!parser_next(parser))
2890 parseerror(parser, "parse error");
2892 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2896 /* returns true when it was a variable qualifier, false otherwise!
2897 * on error, cvq is set to CV_WRONG
2899 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2901 bool had_const = false;
2902 bool had_var = false;
2903 bool had_noref = false;
2904 bool had_attrib = false;
2905 bool had_static = false;
2910 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2912 /* parse an attribute */
2913 if (!parser_next(parser)) {
2914 parseerror(parser, "expected attribute after `[[`");
2918 if (!strcmp(parser_tokval(parser), "noreturn")) {
2919 flags |= AST_FLAG_NORETURN;
2920 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2921 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2926 else if (!strcmp(parser_tokval(parser), "noref")) {
2928 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2929 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2934 else if (!strcmp(parser_tokval(parser), "inline")) {
2935 flags |= AST_FLAG_INLINE;
2936 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2937 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2944 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2945 flags |= AST_FLAG_DEPRECATED;
2948 if (!parser_next(parser)) {
2949 parseerror(parser, "parse error in attribute");
2953 if (parser->tok == '(') {
2954 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2955 parseerror(parser, "`deprecated` attribute missing parameter");
2959 *message = util_strdup(parser_tokval(parser));
2961 if (!parser_next(parser)) {
2962 parseerror(parser, "parse error in attribute");
2966 if(parser->tok != ')') {
2967 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2971 if (!parser_next(parser)) {
2972 parseerror(parser, "parse error in attribute");
2977 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2978 parseerror(parser, "`deprecated` attribute expected `]]`");
2981 if (*message) mem_d(*message);
2989 /* Skip tokens until we hit a ]] */
2990 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2991 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2992 if (!parser_next(parser)) {
2993 parseerror(parser, "error inside attribute");
3000 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3002 else if (!strcmp(parser_tokval(parser), "const"))
3004 else if (!strcmp(parser_tokval(parser), "var"))
3006 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3008 else if (!strcmp(parser_tokval(parser), "noref"))
3010 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3015 if (!parser_next(parser))
3025 *is_static = had_static;
3029 parseerror(parser, "parse error after variable qualifier");
3034 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3035 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3040 /* skip the 'while' and get the body */
3041 if (!parser_next(parser)) {
3042 if (OPTS_FLAG(LOOP_LABELS))
3043 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3045 parseerror(parser, "expected 'switch' operand in parenthesis");
3049 if (parser->tok == ':') {
3050 if (!OPTS_FLAG(LOOP_LABELS))
3051 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3052 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3053 parseerror(parser, "expected loop label");
3056 label = util_strdup(parser_tokval(parser));
3057 if (!parser_next(parser)) {
3059 parseerror(parser, "expected 'switch' operand in parenthesis");
3064 if (parser->tok != '(') {
3065 parseerror(parser, "expected 'switch' operand in parenthesis");
3069 vec_push(parser->breaks, label);
3071 rv = parse_switch_go(parser, block, out);
3074 if (vec_last(parser->breaks) != label) {
3075 parseerror(parser, "internal error: label stack corrupted");
3081 vec_pop(parser->breaks);
3086 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3088 ast_expression *operand;
3091 ast_switch *switchnode;
3092 ast_switch_case swcase;
3095 bool noref, is_static;
3096 uint32_t qflags = 0;
3098 lex_ctx ctx = parser_ctx(parser);
3100 (void)block; /* not touching */
3103 /* parse into the expression */
3104 if (!parser_next(parser)) {
3105 parseerror(parser, "expected switch operand");
3108 /* parse the operand */
3109 operand = parse_expression_leave(parser, false, false, false);
3113 switchnode = ast_switch_new(ctx, operand);
3116 if (parser->tok != ')') {
3117 ast_delete(switchnode);
3118 parseerror(parser, "expected closing paren after 'switch' operand");
3122 /* parse over the opening paren */
3123 if (!parser_next(parser) || parser->tok != '{') {
3124 ast_delete(switchnode);
3125 parseerror(parser, "expected list of cases");
3129 if (!parser_next(parser)) {
3130 ast_delete(switchnode);
3131 parseerror(parser, "expected 'case' or 'default'");
3135 /* new block; allow some variables to be declared here */
3136 parser_enterblock(parser);
3139 if (parser->tok == TOKEN_IDENT)
3140 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3141 if (typevar || parser->tok == TOKEN_TYPENAME) {
3142 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3143 ast_delete(switchnode);
3148 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3150 if (cvq == CV_WRONG) {
3151 ast_delete(switchnode);
3154 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3155 ast_delete(switchnode);
3164 while (parser->tok != '}') {
3165 ast_block *caseblock;
3167 if (!strcmp(parser_tokval(parser), "case")) {
3168 if (!parser_next(parser)) {
3169 ast_delete(switchnode);
3170 parseerror(parser, "expected expression for case");
3173 swcase.value = parse_expression_leave(parser, false, false, false);
3174 if (!swcase.value) {
3175 ast_delete(switchnode);
3176 parseerror(parser, "expected expression for case");
3179 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3180 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3181 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3187 else if (!strcmp(parser_tokval(parser), "default")) {
3188 swcase.value = NULL;
3189 if (!parser_next(parser)) {
3190 ast_delete(switchnode);
3191 parseerror(parser, "expected colon");
3196 ast_delete(switchnode);
3197 parseerror(parser, "expected 'case' or 'default'");
3201 /* Now the colon and body */
3202 if (parser->tok != ':') {
3203 if (swcase.value) ast_unref(swcase.value);
3204 ast_delete(switchnode);
3205 parseerror(parser, "expected colon");
3209 if (!parser_next(parser)) {
3210 if (swcase.value) ast_unref(swcase.value);
3211 ast_delete(switchnode);
3212 parseerror(parser, "expected statements or case");
3215 caseblock = ast_block_new(parser_ctx(parser));
3217 if (swcase.value) ast_unref(swcase.value);
3218 ast_delete(switchnode);
3221 swcase.code = (ast_expression*)caseblock;
3222 vec_push(switchnode->cases, swcase);
3224 ast_expression *expr;
3225 if (parser->tok == '}')
3227 if (parser->tok == TOKEN_KEYWORD) {
3228 if (!strcmp(parser_tokval(parser), "case") ||
3229 !strcmp(parser_tokval(parser), "default"))
3234 if (!parse_statement(parser, caseblock, &expr, true)) {
3235 ast_delete(switchnode);
3240 if (!ast_block_add_expr(caseblock, expr)) {
3241 ast_delete(switchnode);
3247 parser_leaveblock(parser);
3250 if (parser->tok != '}') {
3251 ast_delete(switchnode);
3252 parseerror(parser, "expected closing paren of case list");
3255 if (!parser_next(parser)) {
3256 ast_delete(switchnode);
3257 parseerror(parser, "parse error after switch");
3260 *out = (ast_expression*)switchnode;
3264 /* parse computed goto sides */
3265 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3266 ast_expression *on_true;
3267 ast_expression *on_false;
3268 ast_expression *cond;
3273 if (ast_istype(*side, ast_ternary)) {
3274 ast_ternary *tern = (ast_ternary*)*side;
3275 on_true = parse_goto_computed(parser, &tern->on_true);
3276 on_false = parse_goto_computed(parser, &tern->on_false);
3278 if (!on_true || !on_false) {
3279 parseerror(parser, "expected label or expression in ternary");
3280 if (on_true) ast_unref(on_true);
3281 if (on_false) ast_unref(on_false);
3289 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3290 } else if (ast_istype(*side, ast_label)) {
3291 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3292 ast_goto_set_label(gt, ((ast_label*)*side));
3294 return (ast_expression*)gt;
3299 static bool parse_goto(parser_t *parser, ast_expression **out)
3301 ast_goto *gt = NULL;
3302 ast_expression *lbl;
3304 if (!parser_next(parser))
3307 if (parser->tok != TOKEN_IDENT) {
3308 ast_expression *expression;
3310 /* could be an expression i.e computed goto :-) */
3311 if (parser->tok != '(') {
3312 parseerror(parser, "expected label name after `goto`");
3316 /* failed to parse expression for goto */
3317 if (!(expression = parse_expression(parser, false, true)) ||
3318 !(*out = parse_goto_computed(parser, &expression))) {
3319 parseerror(parser, "invalid goto expression");
3320 ast_unref(expression);
3327 /* not computed goto */
3328 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3329 lbl = parser_find_label(parser, gt->name);
3331 if (!ast_istype(lbl, ast_label)) {
3332 parseerror(parser, "internal error: label is not an ast_label");
3336 ast_goto_set_label(gt, (ast_label*)lbl);
3339 vec_push(parser->gotos, gt);
3341 if (!parser_next(parser) || parser->tok != ';') {
3342 parseerror(parser, "semicolon expected after goto label");
3345 if (!parser_next(parser)) {
3346 parseerror(parser, "parse error after goto");
3350 *out = (ast_expression*)gt;
3354 static bool parse_skipwhite(parser_t *parser)
3357 if (!parser_next(parser))
3359 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3360 return parser->tok < TOKEN_ERROR;
3363 static bool parse_eol(parser_t *parser)
3365 if (!parse_skipwhite(parser))
3367 return parser->tok == TOKEN_EOL;
3370 static bool parse_pragma_do(parser_t *parser)
3372 if (!parser_next(parser) ||
3373 parser->tok != TOKEN_IDENT ||
3374 strcmp(parser_tokval(parser), "pragma"))
3376 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3379 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3380 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3384 if (!strcmp(parser_tokval(parser), "noref")) {
3385 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3386 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3389 parser->noref = !!parser_token(parser)->constval.i;
3390 if (!parse_eol(parser)) {
3391 parseerror(parser, "parse error after `noref` pragma");
3397 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3404 static bool parse_pragma(parser_t *parser)
3407 parser->lex->flags.preprocessing = true;
3408 parser->lex->flags.mergelines = true;
3409 rv = parse_pragma_do(parser);
3410 if (parser->tok != TOKEN_EOL) {
3411 parseerror(parser, "junk after pragma");
3414 parser->lex->flags.preprocessing = false;
3415 parser->lex->flags.mergelines = false;
3416 if (!parser_next(parser)) {
3417 parseerror(parser, "parse error after pragma");
3423 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3425 bool noref, is_static;
3427 uint32_t qflags = 0;
3428 ast_value *typevar = NULL;
3429 char *vstring = NULL;
3433 if (parser->tok == TOKEN_IDENT)
3434 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3436 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3438 /* local variable */
3440 parseerror(parser, "cannot declare a variable from here");
3443 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3444 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3447 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3451 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3453 if (cvq == CV_WRONG)
3455 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3457 else if (parser->tok == TOKEN_KEYWORD)
3459 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3464 if (!parser_next(parser)) {
3465 parseerror(parser, "parse error after __builtin_debug_printtype");
3469 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3471 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3472 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3473 if (!parser_next(parser)) {
3474 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3480 if (!parse_statement(parser, block, out, allow_cases))
3483 con_out("__builtin_debug_printtype: got no output node\n");
3486 ast_type_to_string(*out, ty, sizeof(ty));
3487 con_out("__builtin_debug_printtype: `%s`\n", ty);
3492 else if (!strcmp(parser_tokval(parser), "return"))
3494 return parse_return(parser, block, out);
3496 else if (!strcmp(parser_tokval(parser), "if"))
3498 return parse_if(parser, block, out);
3500 else if (!strcmp(parser_tokval(parser), "while"))
3502 return parse_while(parser, block, out);
3504 else if (!strcmp(parser_tokval(parser), "do"))
3506 return parse_dowhile(parser, block, out);
3508 else if (!strcmp(parser_tokval(parser), "for"))
3510 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3511 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3514 return parse_for(parser, block, out);
3516 else if (!strcmp(parser_tokval(parser), "break"))
3518 return parse_break_continue(parser, block, out, false);
3520 else if (!strcmp(parser_tokval(parser), "continue"))
3522 return parse_break_continue(parser, block, out, true);
3524 else if (!strcmp(parser_tokval(parser), "switch"))
3526 return parse_switch(parser, block, out);
3528 else if (!strcmp(parser_tokval(parser), "case") ||
3529 !strcmp(parser_tokval(parser), "default"))
3532 parseerror(parser, "unexpected 'case' label");
3537 else if (!strcmp(parser_tokval(parser), "goto"))
3539 return parse_goto(parser, out);
3541 else if (!strcmp(parser_tokval(parser), "typedef"))
3543 if (!parser_next(parser)) {
3544 parseerror(parser, "expected type definition after 'typedef'");
3547 return parse_typedef(parser);
3549 parseerror(parser, "Unexpected keyword");
3552 else if (parser->tok == '{')
3555 inner = parse_block(parser);
3558 *out = (ast_expression*)inner;
3561 else if (parser->tok == ':')
3565 if (!parser_next(parser)) {
3566 parseerror(parser, "expected label name");
3569 if (parser->tok != TOKEN_IDENT) {
3570 parseerror(parser, "label must be an identifier");
3573 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3575 if (!label->undefined) {
3576 parseerror(parser, "label `%s` already defined", label->name);
3579 label->undefined = false;
3582 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3583 vec_push(parser->labels, label);
3585 *out = (ast_expression*)label;
3586 if (!parser_next(parser)) {
3587 parseerror(parser, "parse error after label");
3590 for (i = 0; i < vec_size(parser->gotos); ++i) {
3591 if (!strcmp(parser->gotos[i]->name, label->name)) {
3592 ast_goto_set_label(parser->gotos[i], label);
3593 vec_remove(parser->gotos, i, 1);
3599 else if (parser->tok == ';')
3601 if (!parser_next(parser)) {
3602 parseerror(parser, "parse error after empty statement");
3609 lex_ctx ctx = parser_ctx(parser);
3610 ast_expression *exp = parse_expression(parser, false, false);
3614 if (!ast_side_effects(exp)) {
3615 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3622 static bool parse_enum(parser_t *parser)
3625 ast_value **values = NULL;
3626 ast_value *var = NULL;
3629 ast_expression *old;
3631 if (!parser_next(parser) || parser->tok != '{') {
3632 parseerror(parser, "expected `{` after `enum` keyword");
3637 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3638 if (parser->tok == '}') {
3639 /* allow an empty enum */
3642 parseerror(parser, "expected identifier or `}`");
3646 old = parser_find_field(parser, parser_tokval(parser));
3648 old = parser_find_global(parser, parser_tokval(parser));
3650 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3651 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3655 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3656 vec_push(values, var);
3657 var->cvq = CV_CONST;
3658 var->hasvalue = true;
3659 var->constval.vfloat = num++;
3661 parser_addglobal(parser, var->name, (ast_expression*)var);
3663 if (!parser_next(parser)) {
3664 parseerror(parser, "expected `=`, `}` or comma after identifier");
3668 if (parser->tok == ',')
3670 if (parser->tok == '}')
3672 if (parser->tok != '=') {
3673 parseerror(parser, "expected `=`, `}` or comma after identifier");
3677 if (!parser_next(parser)) {
3678 parseerror(parser, "expected expression after `=`");
3682 /* We got a value! */
3683 old = parse_expression_leave(parser, true, false, false);
3684 asvalue = (ast_value*)old;
3685 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3686 compile_error(ast_ctx(var), "constant value or expression expected");
3689 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3691 if (parser->tok == '}')
3693 if (parser->tok != ',') {
3694 parseerror(parser, "expected `}` or comma after expression");
3699 if (parser->tok != '}') {
3700 parseerror(parser, "internal error: breaking without `}`");
3704 if (!parser_next(parser) || parser->tok != ';') {
3705 parseerror(parser, "expected semicolon after enumeration");
3709 if (!parser_next(parser)) {
3710 parseerror(parser, "parse error after enumeration");
3722 static bool parse_block_into(parser_t *parser, ast_block *block)
3726 parser_enterblock(parser);
3728 if (!parser_next(parser)) { /* skip the '{' */
3729 parseerror(parser, "expected function body");
3733 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3735 ast_expression *expr = NULL;
3736 if (parser->tok == '}')
3739 if (!parse_statement(parser, block, &expr, false)) {
3740 /* parseerror(parser, "parse error"); */
3746 if (!ast_block_add_expr(block, expr)) {
3753 if (parser->tok != '}') {
3756 (void)parser_next(parser);
3760 if (!parser_leaveblock(parser))
3762 return retval && !!block;
3765 static ast_block* parse_block(parser_t *parser)
3768 block = ast_block_new(parser_ctx(parser));
3771 if (!parse_block_into(parser, block)) {
3772 ast_block_delete(block);
3778 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3780 if (parser->tok == '{') {
3781 *out = (ast_expression*)parse_block(parser);
3784 return parse_statement(parser, NULL, out, false);
3787 static bool create_vector_members(ast_value *var, ast_member **me)
3790 size_t len = strlen(var->name);
3792 for (i = 0; i < 3; ++i) {
3793 char *name = (char*)mem_a(len+3);
3794 memcpy(name, var->name, len);
3796 name[len+1] = 'x'+i;
3798 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3807 do { ast_member_delete(me[--i]); } while(i);
3811 static bool parse_function_body(parser_t *parser, ast_value *var)
3813 ast_block *block = NULL;
3818 ast_expression *framenum = NULL;
3819 ast_expression *nextthink = NULL;
3820 /* None of the following have to be deleted */
3821 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3822 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3823 bool has_frame_think;
3827 has_frame_think = false;
3828 old = parser->function;
3830 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3831 parseerror(parser, "gotos/labels leaking");
3835 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3836 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3837 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3843 if (parser->tok == '[') {
3844 /* got a frame definition: [ framenum, nextthink ]
3845 * this translates to:
3846 * self.frame = framenum;
3847 * self.nextthink = time + 0.1;
3848 * self.think = nextthink;
3852 fld_think = parser_find_field(parser, "think");
3853 fld_nextthink = parser_find_field(parser, "nextthink");
3854 fld_frame = parser_find_field(parser, "frame");
3855 if (!fld_think || !fld_nextthink || !fld_frame) {
3856 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3857 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3860 gbl_time = parser_find_global(parser, "time");
3861 gbl_self = parser_find_global(parser, "self");
3862 if (!gbl_time || !gbl_self) {
3863 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3864 parseerror(parser, "please declare the following globals: `time`, `self`");
3868 if (!parser_next(parser))
3871 framenum = parse_expression_leave(parser, true, false, false);
3873 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3876 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3877 ast_unref(framenum);
3878 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3882 if (parser->tok != ',') {
3883 ast_unref(framenum);
3884 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3885 parseerror(parser, "Got a %i\n", parser->tok);
3889 if (!parser_next(parser)) {
3890 ast_unref(framenum);
3894 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3896 /* qc allows the use of not-yet-declared functions here
3897 * - this automatically creates a prototype */
3898 ast_value *thinkfunc;
3899 ast_expression *functype = fld_think->expression.next;
3901 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3902 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3903 ast_unref(framenum);
3904 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3908 if (!parser_next(parser)) {
3909 ast_unref(framenum);
3910 ast_delete(thinkfunc);
3914 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3916 nextthink = (ast_expression*)thinkfunc;
3919 nextthink = parse_expression_leave(parser, true, false, false);
3921 ast_unref(framenum);
3922 parseerror(parser, "expected a think-function in [frame,think] notation");
3927 if (!ast_istype(nextthink, ast_value)) {
3928 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3932 if (retval && parser->tok != ']') {
3933 parseerror(parser, "expected closing `]` for [frame,think] notation");
3937 if (retval && !parser_next(parser)) {
3941 if (retval && parser->tok != '{') {
3942 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3947 ast_unref(nextthink);
3948 ast_unref(framenum);
3952 has_frame_think = true;
3955 block = ast_block_new(parser_ctx(parser));
3957 parseerror(parser, "failed to allocate block");
3958 if (has_frame_think) {
3959 ast_unref(nextthink);
3960 ast_unref(framenum);
3965 if (has_frame_think) {
3967 ast_expression *self_frame;
3968 ast_expression *self_nextthink;
3969 ast_expression *self_think;
3970 ast_expression *time_plus_1;
3971 ast_store *store_frame;
3972 ast_store *store_nextthink;
3973 ast_store *store_think;
3975 ctx = parser_ctx(parser);
3976 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3977 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3978 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3980 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3981 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3983 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3984 if (self_frame) ast_delete(self_frame);
3985 if (self_nextthink) ast_delete(self_nextthink);
3986 if (self_think) ast_delete(self_think);
3987 if (time_plus_1) ast_delete(time_plus_1);
3993 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3994 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3995 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3998 ast_delete(self_frame);
4001 if (!store_nextthink) {
4002 ast_delete(self_nextthink);
4006 ast_delete(self_think);
4010 if (store_frame) ast_delete(store_frame);
4011 if (store_nextthink) ast_delete(store_nextthink);
4012 if (store_think) ast_delete(store_think);
4015 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4016 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4017 !ast_block_add_expr(block, (ast_expression*)store_think))
4024 parseerror(parser, "failed to generate code for [frame,think]");
4025 ast_unref(nextthink);
4026 ast_unref(framenum);
4032 if (var->hasvalue) {
4033 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4034 ast_block_delete(block);
4038 func = ast_function_new(ast_ctx(var), var->name, var);
4040 parseerror(parser, "failed to allocate function for `%s`", var->name);
4041 ast_block_delete(block);
4044 vec_push(parser->functions, func);
4046 parser_enterblock(parser);
4048 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4050 ast_value *param = var->expression.params[parami];
4053 if (param->expression.vtype != TYPE_VECTOR &&
4054 (param->expression.vtype != TYPE_FIELD ||
4055 param->expression.next->expression.vtype != TYPE_VECTOR))
4060 if (!create_vector_members(param, me)) {
4061 ast_block_delete(block);
4065 for (e = 0; e < 3; ++e) {
4066 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4067 ast_block_collect(block, (ast_expression*)me[e]);
4071 if (var->argcounter) {
4072 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4073 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4077 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4079 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4080 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4081 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4082 varargs->expression.count = 0;
4083 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4084 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4085 ast_delete(varargs);
4086 ast_block_delete(block);
4089 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4090 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4091 ast_delete(varargs);
4092 ast_block_delete(block);
4095 func->varargs = varargs;
4097 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4100 parser->function = func;
4101 if (!parse_block_into(parser, block)) {
4102 ast_block_delete(block);
4106 vec_push(func->blocks, block);
4108 parser->function = old;
4109 if (!parser_leaveblock(parser))
4111 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4112 parseerror(parser, "internal error: local scopes left");
4116 if (parser->tok == ';')
4117 return parser_next(parser);
4118 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4119 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4123 (void)!parser_leaveblock(parser);
4124 vec_pop(parser->functions);
4125 ast_function_delete(func);
4126 var->constval.vfunc = NULL;
4129 parser->function = old;
4133 static ast_expression *array_accessor_split(
4138 ast_expression *left,
4139 ast_expression *right
4145 lex_ctx ctx = ast_ctx(array);
4147 if (!left || !right) {
4148 if (left) ast_delete(left);
4149 if (right) ast_delete(right);
4153 cmp = ast_binary_new(ctx, INSTR_LT,
4154 (ast_expression*)index,
4155 (ast_expression*)parser_const_float(parser, middle));
4159 parseerror(parser, "internal error: failed to create comparison for array setter");
4163 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4165 ast_delete(cmp); /* will delete left and right */
4166 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4170 return (ast_expression*)ifthen;
4173 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4175 lex_ctx ctx = ast_ctx(array);
4177 if (from+1 == afterend) {
4178 /* set this value */
4181 ast_array_index *subscript;
4183 int assignop = type_store_instr[value->expression.vtype];
4185 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4186 assignop = INSTR_STORE_V;
4188 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4192 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4194 ast_delete(subscript);
4198 block = ast_block_new(ctx);
4204 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4209 ret = ast_return_new(ctx, NULL);
4215 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4220 return (ast_expression*)block;
4222 ast_expression *left, *right;
4223 size_t diff = afterend - from;
4224 size_t middle = from + diff/2;
4225 left = array_setter_node(parser, array, index, value, from, middle);
4226 right = array_setter_node(parser, array, index, value, middle, afterend);
4227 return array_accessor_split(parser, array, index, middle, left, right);
4231 static ast_expression *array_field_setter_node(
4240 lex_ctx ctx = ast_ctx(array);
4242 if (from+1 == afterend) {
4243 /* set this value */
4246 ast_entfield *entfield;
4247 ast_array_index *subscript;
4249 int assignop = type_storep_instr[value->expression.vtype];
4251 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4252 assignop = INSTR_STOREP_V;
4254 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4258 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4259 subscript->expression.vtype = TYPE_FIELD;
4261 entfield = ast_entfield_new_force(ctx,
4262 (ast_expression*)entity,
4263 (ast_expression*)subscript,
4264 (ast_expression*)subscript);
4266 ast_delete(subscript);
4270 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4272 ast_delete(entfield);
4276 block = ast_block_new(ctx);
4282 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4287 ret = ast_return_new(ctx, NULL);
4293 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4298 return (ast_expression*)block;
4300 ast_expression *left, *right;
4301 size_t diff = afterend - from;
4302 size_t middle = from + diff/2;
4303 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4304 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4305 return array_accessor_split(parser, array, index, middle, left, right);
4309 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4311 lex_ctx ctx = ast_ctx(array);
4313 if (from+1 == afterend) {
4315 ast_array_index *subscript;
4317 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4321 ret = ast_return_new(ctx, (ast_expression*)subscript);
4323 ast_delete(subscript);
4327 return (ast_expression*)ret;
4329 ast_expression *left, *right;
4330 size_t diff = afterend - from;
4331 size_t middle = from + diff/2;
4332 left = array_getter_node(parser, array, index, from, middle);
4333 right = array_getter_node(parser, array, index, middle, afterend);
4334 return array_accessor_split(parser, array, index, middle, left, right);
4338 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4340 ast_function *func = NULL;
4341 ast_value *fval = NULL;
4342 ast_block *body = NULL;
4344 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4346 parseerror(parser, "failed to create accessor function value");
4350 func = ast_function_new(ast_ctx(array), funcname, fval);
4353 parseerror(parser, "failed to create accessor function node");
4357 body = ast_block_new(ast_ctx(array));
4359 parseerror(parser, "failed to create block for array accessor");
4365 vec_push(func->blocks, body);
4368 vec_push(parser->accessors, fval);
4373 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4375 ast_value *index = NULL;
4376 ast_value *value = NULL;
4380 if (!ast_istype(array->expression.next, ast_value)) {
4381 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4385 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4387 func = fval->constval.vfunc;
4388 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4390 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4391 value = ast_value_copy((ast_value*)array->expression.next);
4393 if (!index || !value) {
4394 parseerror(parser, "failed to create locals for array accessor");
4397 (void)!ast_value_set_name(value, "value"); /* not important */
4398 vec_push(fval->expression.params, index);
4399 vec_push(fval->expression.params, value);
4401 array->setter = fval;
4404 if (index) ast_delete(index);
4405 if (value) ast_delete(value);
4411 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4413 ast_expression *root = NULL;
4414 root = array_setter_node(parser, array,
4415 array->setter->expression.params[0],
4416 array->setter->expression.params[1],
4417 0, array->expression.count);
4419 parseerror(parser, "failed to build accessor search tree");
4422 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4429 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4431 if (!parser_create_array_setter_proto(parser, array, funcname))
4433 return parser_create_array_setter_impl(parser, array);
4436 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4438 ast_expression *root = NULL;
4439 ast_value *entity = NULL;
4440 ast_value *index = NULL;
4441 ast_value *value = NULL;
4445 if (!ast_istype(array->expression.next, ast_value)) {
4446 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4450 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4452 func = fval->constval.vfunc;
4453 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4455 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4456 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4457 value = ast_value_copy((ast_value*)array->expression.next);
4458 if (!entity || !index || !value) {
4459 parseerror(parser, "failed to create locals for array accessor");
4462 (void)!ast_value_set_name(value, "value"); /* not important */
4463 vec_push(fval->expression.params, entity);
4464 vec_push(fval->expression.params, index);
4465 vec_push(fval->expression.params, value);
4467 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4469 parseerror(parser, "failed to build accessor search tree");
4473 array->setter = fval;
4474 return ast_block_add_expr(func->blocks[0], root);
4476 if (entity) ast_delete(entity);
4477 if (index) ast_delete(index);
4478 if (value) ast_delete(value);
4479 if (root) ast_delete(root);
4485 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4487 ast_value *index = NULL;
4491 /* NOTE: checking array->expression.next rather than elemtype since
4492 * for fields elemtype is a temporary fieldtype.
4494 if (!ast_istype(array->expression.next, ast_value)) {
4495 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4499 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4501 func = fval->constval.vfunc;
4502 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4504 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4507 parseerror(parser, "failed to create locals for array accessor");
4510 vec_push(fval->expression.params, index);
4512 array->getter = fval;
4515 if (index) ast_delete(index);
4521 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4523 ast_expression *root = NULL;
4525 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4527 parseerror(parser, "failed to build accessor search tree");
4530 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4537 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4539 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4541 return parser_create_array_getter_impl(parser, array);
4544 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4545 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4553 bool variadic = false;
4554 ast_value *varparam = NULL;
4555 char *argcounter = NULL;
4557 ctx = parser_ctx(parser);
4559 /* for the sake of less code we parse-in in this function */
4560 if (!parser_next(parser)) {
4561 parseerror(parser, "expected parameter list");
4567 /* parse variables until we hit a closing paren */
4568 while (parser->tok != ')') {
4570 /* there must be commas between them */
4571 if (parser->tok != ',') {
4572 parseerror(parser, "expected comma or end of parameter list");
4575 if (!parser_next(parser)) {
4576 parseerror(parser, "expected parameter");
4582 if (parser->tok == TOKEN_DOTS) {
4583 /* '...' indicates a varargs function */
4585 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4586 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4589 if (parser->tok == TOKEN_IDENT) {
4590 argcounter = util_strdup(parser_tokval(parser));
4591 if (!parser_next(parser) || parser->tok != ')') {
4592 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4599 /* for anything else just parse a typename */
4600 param = parse_typename(parser, NULL, NULL);
4603 vec_push(params, param);
4604 if (param->expression.vtype >= TYPE_VARIANT) {
4605 char tname[1024]; /* typename is reserved in C++ */
4606 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4607 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4610 /* type-restricted varargs */
4611 if (parser->tok == TOKEN_DOTS) {
4613 varparam = vec_last(params);
4615 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4616 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4619 if (parser->tok == TOKEN_IDENT) {
4620 argcounter = util_strdup(parser_tokval(parser));
4621 if (!parser_next(parser) || parser->tok != ')') {
4622 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4630 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4634 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4635 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4638 if (!parser_next(parser)) {
4639 parseerror(parser, "parse error after typename");
4643 /* now turn 'var' into a function type */
4644 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4645 fval->expression.next = (ast_expression*)var;
4647 fval->expression.flags |= AST_FLAG_VARIADIC;
4650 var->expression.params = params;
4651 var->expression.varparam = (ast_expression*)varparam;
4652 var->argcounter = argcounter;
4661 for (i = 0; i < vec_size(params); ++i)
4662 ast_delete(params[i]);
4667 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4669 ast_expression *cexp;
4670 ast_value *cval, *tmp;
4673 ctx = parser_ctx(parser);
4675 if (!parser_next(parser)) {
4677 parseerror(parser, "expected array-size");
4681 cexp = parse_expression_leave(parser, true, false, false);
4683 if (!cexp || !ast_istype(cexp, ast_value)) {
4687 parseerror(parser, "expected array-size as constant positive integer");
4690 cval = (ast_value*)cexp;
4692 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4693 tmp->expression.next = (ast_expression*)var;
4696 if (cval->expression.vtype == TYPE_INTEGER)
4697 tmp->expression.count = cval->constval.vint;
4698 else if (cval->expression.vtype == TYPE_FLOAT)
4699 tmp->expression.count = cval->constval.vfloat;
4703 parseerror(parser, "array-size must be a positive integer constant");
4708 if (parser->tok != ']') {
4710 parseerror(parser, "expected ']' after array-size");
4713 if (!parser_next(parser)) {
4715 parseerror(parser, "error after parsing array size");
4721 /* Parse a complete typename.
4722 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4723 * but when parsing variables separated by comma
4724 * 'storebase' should point to where the base-type should be kept.
4725 * The base type makes up every bit of type information which comes *before* the
4728 * The following will be parsed in its entirety:
4730 * The 'basetype' in this case is 'void()'
4731 * and if there's a comma after it, say:
4733 * then the type-information 'void()' can be stored in 'storebase'
4735 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4737 ast_value *var, *tmp;
4740 const char *name = NULL;
4741 bool isfield = false;
4742 bool wasarray = false;
4743 size_t morefields = 0;
4745 ctx = parser_ctx(parser);
4747 /* types may start with a dot */
4748 if (parser->tok == '.') {
4750 /* if we parsed a dot we need a typename now */
4751 if (!parser_next(parser)) {
4752 parseerror(parser, "expected typename for field definition");
4756 /* Further dots are handled seperately because they won't be part of the
4759 while (parser->tok == '.') {
4761 if (!parser_next(parser)) {
4762 parseerror(parser, "expected typename for field definition");
4767 if (parser->tok == TOKEN_IDENT)
4768 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4769 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4770 parseerror(parser, "expected typename");
4774 /* generate the basic type value */
4775 if (cached_typedef) {
4776 var = ast_value_copy(cached_typedef);
4777 ast_value_set_name(var, "<type(from_def)>");
4779 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4781 for (; morefields; --morefields) {
4782 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4783 tmp->expression.next = (ast_expression*)var;
4787 /* do not yet turn into a field - remember:
4788 * .void() foo; is a field too
4789 * .void()() foo; is a function
4793 if (!parser_next(parser)) {
4795 parseerror(parser, "parse error after typename");
4799 /* an opening paren now starts the parameter-list of a function
4800 * this is where original-QC has parameter lists.
4801 * We allow a single parameter list here.
4802 * Much like fteqcc we don't allow `float()() x`
4804 if (parser->tok == '(') {
4805 var = parse_parameter_list(parser, var);
4810 /* store the base if requested */
4812 *storebase = ast_value_copy(var);
4814 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4815 tmp->expression.next = (ast_expression*)*storebase;
4820 /* there may be a name now */
4821 if (parser->tok == TOKEN_IDENT) {
4822 name = util_strdup(parser_tokval(parser));
4824 if (!parser_next(parser)) {
4826 parseerror(parser, "error after variable or field declaration");
4831 /* now this may be an array */
4832 if (parser->tok == '[') {
4834 var = parse_arraysize(parser, var);
4839 /* This is the point where we can turn it into a field */
4841 /* turn it into a field if desired */
4842 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4843 tmp->expression.next = (ast_expression*)var;
4847 /* now there may be function parens again */
4848 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4849 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4850 if (parser->tok == '(' && wasarray)
4851 parseerror(parser, "arrays as part of a return type is not supported");
4852 while (parser->tok == '(') {
4853 var = parse_parameter_list(parser, var);
4861 /* finally name it */
4863 if (!ast_value_set_name(var, name)) {
4865 parseerror(parser, "internal error: failed to set name");
4868 /* free the name, ast_value_set_name duplicates */
4875 static bool parse_typedef(parser_t *parser)
4877 ast_value *typevar, *oldtype;
4878 ast_expression *old;
4880 typevar = parse_typename(parser, NULL, NULL);
4885 if ( (old = parser_find_var(parser, typevar->name)) ) {
4886 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4887 " -> `%s` has been declared here: %s:%i",
4888 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4889 ast_delete(typevar);
4893 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4894 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4895 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4896 ast_delete(typevar);
4900 vec_push(parser->_typedefs, typevar);
4901 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4903 if (parser->tok != ';') {
4904 parseerror(parser, "expected semicolon after typedef");
4907 if (!parser_next(parser)) {
4908 parseerror(parser, "parse error after typedef");
4915 static const char *cvq_to_str(int cvq) {
4917 case CV_NONE: return "none";
4918 case CV_VAR: return "`var`";
4919 case CV_CONST: return "`const`";
4920 default: return "<INVALID>";
4924 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4927 if (proto->cvq != var->cvq) {
4928 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4929 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4930 parser->tok == '='))
4932 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4933 "`%s` declared with different qualifiers: %s\n"
4934 " -> previous declaration here: %s:%i uses %s",
4935 var->name, cvq_to_str(var->cvq),
4936 ast_ctx(proto).file, ast_ctx(proto).line,
4937 cvq_to_str(proto->cvq));
4940 av = (var ->expression.flags & AST_FLAG_NORETURN);
4941 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4943 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4944 "`%s` declared with different attributes%s\n"
4945 " -> previous declaration here: %s:%i",
4946 var->name, (av ? ": noreturn" : ""),
4947 ast_ctx(proto).file, ast_ctx(proto).line,
4948 (ao ? ": noreturn" : ""));
4953 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)
4957 ast_expression *old;
4961 ast_value *basetype = NULL;
4963 bool isparam = false;
4964 bool isvector = false;
4965 bool cleanvar = true;
4966 bool wasarray = false;
4970 if (!localblock && is_static)
4971 parseerror(parser, "`static` qualifier is not supported in global scope");
4973 /* get the first complete variable */
4974 var = parse_typename(parser, &basetype, cached_typedef);
4977 ast_delete(basetype);
4985 /* Part 0: finish the type */
4986 if (parser->tok == '(') {
4987 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4988 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4989 var = parse_parameter_list(parser, var);
4995 /* we only allow 1-dimensional arrays */
4996 if (parser->tok == '[') {
4998 var = parse_arraysize(parser, var);
5004 if (parser->tok == '(' && wasarray) {
5005 parseerror(parser, "arrays as part of a return type is not supported");
5006 /* we'll still parse the type completely for now */
5008 /* for functions returning functions */
5009 while (parser->tok == '(') {
5010 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5011 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5012 var = parse_parameter_list(parser, var);
5019 var->cvq = qualifier;
5020 var->expression.flags |= qflags;
5021 if (var->expression.flags & AST_FLAG_DEPRECATED)
5022 var->desc = vstring;
5025 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5026 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5027 * is then filled with the previous definition and the parameter-names replaced.
5029 if (!strcmp(var->name, "nil")) {
5030 if (OPTS_FLAG(UNTYPED_NIL)) {
5031 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5032 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5034 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5037 /* Deal with end_sys_ vars */
5039 if (!strcmp(var->name, "end_sys_globals")) {
5041 parser->crc_globals = vec_size(parser->globals);
5044 else if (!strcmp(var->name, "end_sys_fields")) {
5046 parser->crc_fields = vec_size(parser->fields);
5049 if (was_end && var->expression.vtype == TYPE_FIELD) {
5050 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5051 "global '%s' hint should not be a field",
5052 parser_tokval(parser)))
5059 if (!nofields && var->expression.vtype == TYPE_FIELD)
5061 /* deal with field declarations */
5062 old = parser_find_field(parser, var->name);
5064 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5065 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5074 parseerror(parser, "field `%s` already declared here: %s:%i",
5075 var->name, ast_ctx(old).file, ast_ctx(old).line);
5080 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5081 (old = parser_find_global(parser, var->name)))
5083 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5084 parseerror(parser, "field `%s` already declared here: %s:%i",
5085 var->name, ast_ctx(old).file, ast_ctx(old).line);
5092 /* deal with other globals */
5093 old = parser_find_global(parser, var->name);
5094 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5096 /* This is a function which had a prototype */
5097 if (!ast_istype(old, ast_value)) {
5098 parseerror(parser, "internal error: prototype is not an ast_value");
5102 proto = (ast_value*)old;
5103 proto->desc = var->desc;
5104 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5105 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5107 ast_ctx(proto).file, ast_ctx(proto).line);
5111 /* we need the new parameter-names */
5112 for (i = 0; i < vec_size(proto->expression.params); ++i)
5113 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5114 if (!parser_check_qualifiers(parser, var, proto)) {
5121 proto->expression.flags |= var->expression.flags;
5129 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5130 "global `%s` already declared here: %s:%i",
5131 var->name, ast_ctx(old).file, ast_ctx(old).line))
5136 proto = (ast_value*)old;
5137 if (!ast_istype(old, ast_value)) {
5138 parseerror(parser, "internal error: not an ast_value");
5143 if (!parser_check_qualifiers(parser, var, proto)) {
5148 proto->expression.flags |= var->expression.flags;
5152 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5153 (old = parser_find_field(parser, var->name)))
5155 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5156 parseerror(parser, "global `%s` already declared here: %s:%i",
5157 var->name, ast_ctx(old).file, ast_ctx(old).line);
5164 else /* it's not a global */
5166 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5167 if (old && !isparam) {
5168 parseerror(parser, "local `%s` already declared here: %s:%i",
5169 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5173 old = parser_find_local(parser, var->name, 0, &isparam);
5174 if (old && isparam) {
5175 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5176 "local `%s` is shadowing a parameter", var->name))
5178 parseerror(parser, "local `%s` already declared here: %s:%i",
5179 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5183 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5191 /* in a noref section we simply bump the usecount */
5192 if (noref || parser->noref)
5196 * Create the global/local, and deal with vector types.
5199 if (var->expression.vtype == TYPE_VECTOR)
5201 else if (var->expression.vtype == TYPE_FIELD &&
5202 var->expression.next->expression.vtype == TYPE_VECTOR)
5206 if (!create_vector_members(var, me)) {
5213 /* deal with global variables, fields, functions */
5214 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5215 var->isfield = true;
5216 vec_push(parser->fields, (ast_expression*)var);
5217 util_htset(parser->htfields, var->name, var);
5219 for (i = 0; i < 3; ++i) {
5220 vec_push(parser->fields, (ast_expression*)me[i]);
5221 util_htset(parser->htfields, me[i]->name, me[i]);
5226 parser_addglobal(parser, var->name, (ast_expression*)var);
5228 for (i = 0; i < 3; ++i) {
5229 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5235 /* a static adds itself to be generated like any other global
5236 * but is added to the local namespace instead
5238 char *defname = NULL;
5239 size_t prefix_len, ln;
5241 ln = strlen(parser->function->name);
5242 vec_append(defname, ln, parser->function->name);
5244 vec_append(defname, 2, "::");
5245 /* remember the length up to here */
5246 prefix_len = vec_size(defname);
5248 /* Add it to the local scope */
5249 util_htset(vec_last(parser->variables), var->name, (void*)var);
5253 vec_last(parser->correct_variables),
5254 &vec_last(parser->correct_variables_score),
5258 /* now rename the global */
5259 ln = strlen(var->name);
5260 vec_append(defname, ln, var->name);
5261 ast_value_set_name(var, defname);
5263 /* push it to the to-be-generated globals */
5264 vec_push(parser->globals, (ast_expression*)var);
5266 /* same game for the vector members */
5268 for (i = 0; i < 3; ++i) {
5269 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5273 vec_last(parser->correct_variables),
5274 &vec_last(parser->correct_variables_score),
5278 vec_shrinkto(defname, prefix_len);
5279 ln = strlen(me[i]->name);
5280 vec_append(defname, ln, me[i]->name);
5281 ast_member_set_name(me[i], defname);
5283 vec_push(parser->globals, (ast_expression*)me[i]);
5288 vec_push(localblock->locals, var);
5289 parser_addlocal(parser, var->name, (ast_expression*)var);
5291 for (i = 0; i < 3; ++i) {
5292 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5293 ast_block_collect(localblock, (ast_expression*)me[i]);
5299 me[0] = me[1] = me[2] = NULL;
5304 if (var->expression.vtype == TYPE_ARRAY) {
5306 snprintf(name, sizeof(name), "%s##SET", var->name);
5307 if (!parser_create_array_setter(parser, var, name))
5309 snprintf(name, sizeof(name), "%s##GET", var->name);
5310 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5313 else if (!localblock && !nofields &&
5314 var->expression.vtype == TYPE_FIELD &&
5315 var->expression.next->expression.vtype == TYPE_ARRAY)
5318 ast_expression *telem;
5320 ast_value *array = (ast_value*)var->expression.next;
5322 if (!ast_istype(var->expression.next, ast_value)) {
5323 parseerror(parser, "internal error: field element type must be an ast_value");
5327 snprintf(name, sizeof(name), "%s##SETF", var->name);
5328 if (!parser_create_array_field_setter(parser, array, name))
5331 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5332 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5333 tfield->expression.next = telem;
5334 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5335 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5343 if (parser->tok == ';') {
5344 ast_delete(basetype);
5345 if (!parser_next(parser)) {
5346 parseerror(parser, "error after variable declaration");
5352 if (parser->tok == ',')
5356 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5359 parseerror(parser, "missing comma or semicolon while parsing variables");
5363 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5364 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5365 "initializing expression turns variable `%s` into a constant in this standard",
5372 if (parser->tok != '{') {
5373 if (parser->tok != '=') {
5374 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5378 if (!parser_next(parser)) {
5379 parseerror(parser, "error parsing initializer");
5383 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5384 parseerror(parser, "expected '=' before function body in this standard");
5387 if (parser->tok == '#') {
5388 ast_function *func = NULL;
5391 parseerror(parser, "cannot declare builtins within functions");
5394 if (var->expression.vtype != TYPE_FUNCTION) {
5395 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5398 if (!parser_next(parser)) {
5399 parseerror(parser, "expected builtin number");
5402 if (parser->tok != TOKEN_INTCONST) {
5403 parseerror(parser, "builtin number must be an integer constant");
5406 if (parser_token(parser)->constval.i < 0) {
5407 parseerror(parser, "builtin number must be an integer greater than zero");
5411 if (var->hasvalue) {
5412 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5413 "builtin `%s` has already been defined\n"
5414 " -> previous declaration here: %s:%i",
5415 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5419 func = ast_function_new(ast_ctx(var), var->name, var);
5421 parseerror(parser, "failed to allocate function for `%s`", var->name);
5424 vec_push(parser->functions, func);
5426 func->builtin = -parser_token(parser)->constval.i-1;
5429 if (!parser_next(parser)) {
5430 parseerror(parser, "expected comma or semicolon");
5432 ast_function_delete(func);
5433 var->constval.vfunc = NULL;
5437 else if (parser->tok == '{' || parser->tok == '[')
5440 parseerror(parser, "cannot declare functions within functions");
5445 ast_ctx(proto) = parser_ctx(parser);
5447 if (!parse_function_body(parser, var))
5449 ast_delete(basetype);
5450 for (i = 0; i < vec_size(parser->gotos); ++i)
5451 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5452 vec_free(parser->gotos);
5453 vec_free(parser->labels);
5456 ast_expression *cexp;
5459 cexp = parse_expression_leave(parser, true, false, false);
5464 cval = (ast_value*)cexp;
5465 if (cval != parser->nil &&
5466 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5469 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5473 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5474 qualifier != CV_VAR)
5476 var->cvq = CV_CONST;
5478 if (cval == parser->nil)
5479 var->expression.flags |= AST_FLAG_INITIALIZED;
5482 var->hasvalue = true;
5483 if (cval->expression.vtype == TYPE_STRING)
5484 var->constval.vstring = parser_strdup(cval->constval.vstring);
5485 else if (cval->expression.vtype == TYPE_FIELD)
5486 var->constval.vfield = cval;
5488 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5494 shunt sy = { NULL, NULL, NULL, NULL };
5497 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5498 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5499 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5500 if (!parser_sy_apply_operator(parser, &sy))
5503 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5504 parseerror(parser, "internal error: leaked operands");
5505 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5515 if (parser->tok == ',') {
5516 if (!parser_next(parser)) {
5517 parseerror(parser, "expected another variable");
5521 if (parser->tok != TOKEN_IDENT) {
5522 parseerror(parser, "expected another variable");
5525 var = ast_value_copy(basetype);
5527 ast_value_set_name(var, parser_tokval(parser));
5528 if (!parser_next(parser)) {
5529 parseerror(parser, "error parsing variable declaration");
5535 if (parser->tok != ';') {
5536 parseerror(parser, "missing semicolon after variables");
5540 if (!parser_next(parser)) {
5541 parseerror(parser, "parse error after variable declaration");
5545 ast_delete(basetype);
5549 if (cleanvar && var)
5551 ast_delete(basetype);
5555 ast_delete(basetype);
5556 if (cleanvar && var)
5558 if (me[0]) ast_member_delete(me[0]);
5559 if (me[1]) ast_member_delete(me[1]);
5560 if (me[2]) ast_member_delete(me[2]);
5564 static bool parser_global_statement(parser_t *parser)
5568 bool is_static = false;
5569 uint32_t qflags = 0;
5570 ast_value *istype = NULL;
5571 char *vstring = NULL;
5573 if (parser->tok == TOKEN_IDENT)
5574 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5576 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5578 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5580 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5582 if (cvq == CV_WRONG)
5584 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5586 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5588 return parse_enum(parser);
5590 else if (parser->tok == TOKEN_KEYWORD)
5592 if (!strcmp(parser_tokval(parser), "typedef")) {
5593 if (!parser_next(parser)) {
5594 parseerror(parser, "expected type definition after 'typedef'");
5597 return parse_typedef(parser);
5599 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5602 else if (parser->tok == '#')
5604 return parse_pragma(parser);
5606 else if (parser->tok == '$')
5608 if (!parser_next(parser)) {
5609 parseerror(parser, "parse error");
5615 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5621 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5623 return util_crc16(old, str, strlen(str));
5626 static void progdefs_crc_file(const char *str)
5628 /* write to progdefs.h here */
5632 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5634 old = progdefs_crc_sum(old, str);
5635 progdefs_crc_file(str);
5639 static void generate_checksum(parser_t *parser)
5641 uint16_t crc = 0xFFFF;
5645 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5646 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5648 progdefs_crc_file("\tint\tpad;\n");
5649 progdefs_crc_file("\tint\tofs_return[3];\n");
5650 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5651 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5652 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5653 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5654 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5655 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5656 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5657 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5659 for (i = 0; i < parser->crc_globals; ++i) {
5660 if (!ast_istype(parser->globals[i], ast_value))
5662 value = (ast_value*)(parser->globals[i]);
5663 switch (value->expression.vtype) {
5664 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5665 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5666 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5667 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5669 crc = progdefs_crc_both(crc, "\tint\t");
5672 crc = progdefs_crc_both(crc, value->name);
5673 crc = progdefs_crc_both(crc, ";\n");
5675 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5676 for (i = 0; i < parser->crc_fields; ++i) {
5677 if (!ast_istype(parser->fields[i], ast_value))
5679 value = (ast_value*)(parser->fields[i]);
5680 switch (value->expression.next->expression.vtype) {
5681 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5682 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5683 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5684 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5686 crc = progdefs_crc_both(crc, "\tint\t");
5689 crc = progdefs_crc_both(crc, value->name);
5690 crc = progdefs_crc_both(crc, ";\n");
5692 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5697 static parser_t *parser;
5704 parser = (parser_t*)mem_a(sizeof(parser_t));
5708 memset(parser, 0, sizeof(*parser));
5710 for (i = 0; i < operator_count; ++i) {
5711 if (operators[i].id == opid1('=')) {
5712 parser->assign_op = operators+i;
5716 if (!parser->assign_op) {
5717 printf("internal error: initializing parser: failed to find assign operator\n");
5722 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5723 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5724 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5725 vec_push(parser->_blocktypedefs, 0);
5728 vec_push(parser->correct_variables, correct_trie_new());
5729 vec_push(parser->correct_variables_score, NULL);
5731 empty_ctx.file = "<internal>";
5733 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5734 parser->nil->cvq = CV_CONST;
5735 if (OPTS_FLAG(UNTYPED_NIL))
5736 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5738 parser->max_param_count = 1;
5740 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5741 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5742 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5744 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5745 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5746 parser->reserved_version->cvq = CV_CONST;
5747 parser->reserved_version->hasvalue = true;
5748 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5749 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5751 parser->reserved_version = NULL;
5756 bool parser_compile()
5758 /* initial lexer/parser state */
5759 parser->lex->flags.noops = true;
5761 if (parser_next(parser))
5763 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5765 if (!parser_global_statement(parser)) {
5766 if (parser->tok == TOKEN_EOF)
5767 parseerror(parser, "unexpected eof");
5768 else if (compile_errors)
5769 parseerror(parser, "there have been errors, bailing out");
5770 lex_close(parser->lex);
5776 parseerror(parser, "parse error");
5777 lex_close(parser->lex);
5782 lex_close(parser->lex);
5785 return !compile_errors;
5788 bool parser_compile_file(const char *filename)
5790 parser->lex = lex_open(filename);
5792 con_err("failed to open file \"%s\"\n", filename);
5795 return parser_compile();
5798 bool parser_compile_string(const char *name, const char *str, size_t len)
5800 parser->lex = lex_open_string(str, len, name);
5802 con_err("failed to create lexer for string \"%s\"\n", name);
5805 return parser_compile();
5808 void parser_cleanup()
5811 for (i = 0; i < vec_size(parser->accessors); ++i) {
5812 ast_delete(parser->accessors[i]->constval.vfunc);
5813 parser->accessors[i]->constval.vfunc = NULL;
5814 ast_delete(parser->accessors[i]);
5816 for (i = 0; i < vec_size(parser->functions); ++i) {
5817 ast_delete(parser->functions[i]);
5819 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5820 ast_delete(parser->imm_vector[i]);
5822 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5823 ast_delete(parser->imm_string[i]);
5825 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5826 ast_delete(parser->imm_float[i]);
5828 for (i = 0; i < vec_size(parser->fields); ++i) {
5829 ast_delete(parser->fields[i]);
5831 for (i = 0; i < vec_size(parser->globals); ++i) {
5832 ast_delete(parser->globals[i]);
5834 vec_free(parser->accessors);
5835 vec_free(parser->functions);
5836 vec_free(parser->imm_vector);
5837 vec_free(parser->imm_string);
5838 vec_free(parser->imm_float);
5839 vec_free(parser->globals);
5840 vec_free(parser->fields);
5842 for (i = 0; i < vec_size(parser->variables); ++i)
5843 util_htdel(parser->variables[i]);
5844 vec_free(parser->variables);
5845 vec_free(parser->_blocklocals);
5846 vec_free(parser->_locals);
5849 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5850 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5852 vec_free(parser->correct_variables);
5853 vec_free(parser->correct_variables_score);
5856 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5857 ast_delete(parser->_typedefs[i]);
5858 vec_free(parser->_typedefs);
5859 for (i = 0; i < vec_size(parser->typedefs); ++i)
5860 util_htdel(parser->typedefs[i]);
5861 vec_free(parser->typedefs);
5862 vec_free(parser->_blocktypedefs);
5864 vec_free(parser->_block_ctx);
5866 vec_free(parser->labels);
5867 vec_free(parser->gotos);
5868 vec_free(parser->breaks);
5869 vec_free(parser->continues);
5871 ast_value_delete(parser->nil);
5873 ast_value_delete(parser->const_vec[0]);
5874 ast_value_delete(parser->const_vec[1]);
5875 ast_value_delete(parser->const_vec[2]);
5880 bool parser_finish(const char *output)
5886 if (compile_errors) {
5887 con_out("*** there were compile errors\n");
5891 ir = ir_builder_new("gmqcc_out");
5893 con_out("failed to allocate builder\n");
5897 for (i = 0; i < vec_size(parser->fields); ++i) {
5900 if (!ast_istype(parser->fields[i], ast_value))
5902 field = (ast_value*)parser->fields[i];
5903 hasvalue = field->hasvalue;
5904 field->hasvalue = false;
5905 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5906 con_out("failed to generate field %s\n", field->name);
5907 ir_builder_delete(ir);
5912 ast_expression *subtype;
5913 field->hasvalue = true;
5914 subtype = field->expression.next;
5915 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5916 if (subtype->expression.vtype == TYPE_FIELD)
5917 ifld->fieldtype = subtype->expression.next->expression.vtype;
5918 else if (subtype->expression.vtype == TYPE_FUNCTION)
5919 ifld->outtype = subtype->expression.next->expression.vtype;
5920 (void)!ir_value_set_field(field->ir_v, ifld);
5923 for (i = 0; i < vec_size(parser->globals); ++i) {
5925 if (!ast_istype(parser->globals[i], ast_value))
5927 asvalue = (ast_value*)(parser->globals[i]);
5928 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5929 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5930 "unused global: `%s`", asvalue->name);
5932 if (!ast_global_codegen(asvalue, ir, false)) {
5933 con_out("failed to generate global %s\n", asvalue->name);
5934 ir_builder_delete(ir);
5938 /* Build function vararg accessor ast tree now before generating
5939 * immediates, because the accessors may add new immediates
5941 for (i = 0; i < vec_size(parser->functions); ++i) {
5942 ast_function *f = parser->functions[i];
5944 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5945 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5946 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5947 con_out("failed to generate vararg setter for %s\n", f->name);
5948 ir_builder_delete(ir);
5951 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5952 con_out("failed to generate vararg getter for %s\n", f->name);
5953 ir_builder_delete(ir);
5957 ast_delete(f->varargs);
5962 /* Now we can generate immediates */
5963 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5964 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5965 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5966 ir_builder_delete(ir);
5970 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5971 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5972 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5973 ir_builder_delete(ir);
5977 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5978 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5979 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5980 ir_builder_delete(ir);
5984 for (i = 0; i < vec_size(parser->globals); ++i) {
5986 if (!ast_istype(parser->globals[i], ast_value))
5988 asvalue = (ast_value*)(parser->globals[i]);
5989 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5991 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5992 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5993 "uninitialized constant: `%s`",
5995 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5996 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5997 "uninitialized global: `%s`",
6000 if (!ast_generate_accessors(asvalue, ir)) {
6001 ir_builder_delete(ir);
6005 for (i = 0; i < vec_size(parser->fields); ++i) {
6007 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6009 if (!ast_istype((ast_expression*)asvalue, ast_value))
6011 if (asvalue->expression.vtype != TYPE_ARRAY)
6013 if (!ast_generate_accessors(asvalue, ir)) {
6014 ir_builder_delete(ir);
6018 if (parser->reserved_version &&
6019 !ast_global_codegen(parser->reserved_version, ir, false))
6021 con_out("failed to generate reserved::version");
6022 ir_builder_delete(ir);
6025 for (i = 0; i < vec_size(parser->functions); ++i) {
6026 ast_function *f = parser->functions[i];
6027 if (!ast_function_codegen(f, ir)) {
6028 con_out("failed to generate function %s\n", f->name);
6029 ir_builder_delete(ir);
6033 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6034 ir_builder_dump(ir, con_out);
6035 for (i = 0; i < vec_size(parser->functions); ++i) {
6036 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6037 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6038 ir_builder_delete(ir);
6043 if (compile_Werrors) {
6044 con_out("*** there were warnings treated as errors\n");
6045 compile_show_werrors();
6050 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6051 ir_builder_dump(ir, con_out);
6053 generate_checksum(parser);
6055 if (!ir_builder_generate(ir, output)) {
6056 con_out("*** failed to generate output file\n");
6057 ir_builder_delete(ir);
6062 ir_builder_delete(ir);