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;
67 /* All the labels the function defined...
68 * Should they be in ast_function instead?
73 const char **continues;
75 /* A list of hashtables for each scope */
81 /* same as above but for the spelling corrector */
82 correct_trie_t **correct_variables;
83 size_t ***correct_variables_score; /* vector of vector of size_t* */
85 /* not to be used directly, we use the hash table */
86 ast_expression **_locals;
88 ast_value **_typedefs;
89 size_t *_blocktypedefs;
92 /* we store the '=' operator info */
93 const oper_info *assign_op;
96 ast_value *const_vec[3];
101 /* collected information */
102 size_t max_param_count;
105 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
107 static void parser_enterblock(parser_t *parser);
108 static bool parser_leaveblock(parser_t *parser);
109 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
110 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
111 static bool parse_typedef(parser_t *parser);
112 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);
113 static ast_block* parse_block(parser_t *parser);
114 static bool parse_block_into(parser_t *parser, ast_block *block);
115 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
116 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
117 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
118 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
119 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
120 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
121 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
123 static void parseerror(parser_t *parser, const char *fmt, ...)
127 vcompile_error(parser->lex->tok.ctx, fmt, ap);
131 /* returns true if it counts as an error */
132 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
137 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
142 /**********************************************************************
143 * some maths used for constant folding
146 vector vec3_add(vector a, vector b)
155 vector vec3_sub(vector a, vector b)
164 qcfloat vec3_mulvv(vector a, vector b)
166 return (a.x * b.x + a.y * b.y + a.z * b.z);
169 vector vec3_mulvf(vector a, float b)
178 /**********************************************************************
182 bool parser_next(parser_t *parser)
184 /* lex_do kills the previous token */
185 parser->tok = lex_do(parser->lex);
186 if (parser->tok == TOKEN_EOF)
188 if (parser->tok >= TOKEN_ERROR) {
189 parseerror(parser, "lex error");
195 #define parser_tokval(p) ((p)->lex->tok.value)
196 #define parser_token(p) (&((p)->lex->tok))
197 #define parser_ctx(p) ((p)->lex->tok.ctx)
199 static ast_value* parser_const_float(parser_t *parser, double d)
204 for (i = 0; i < vec_size(parser->imm_float); ++i) {
205 const double compare = parser->imm_float[i]->constval.vfloat;
206 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
207 return parser->imm_float[i];
210 ctx = parser_ctx(parser);
212 memset(&ctx, 0, sizeof(ctx));
214 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
216 out->hasvalue = true;
217 out->constval.vfloat = d;
218 vec_push(parser->imm_float, out);
222 static ast_value* parser_const_float_0(parser_t *parser)
224 if (!parser->imm_float_zero)
225 parser->imm_float_zero = parser_const_float(parser, 0);
226 return parser->imm_float_zero;
229 static ast_value* parser_const_float_neg1(parser_t *parser) {
230 if (!parser->imm_float_neg_one)
231 parser->imm_float_neg_one = parser_const_float(parser, -1);
232 return parser->imm_float_neg_one;
235 static ast_value* parser_const_float_1(parser_t *parser)
237 if (!parser->imm_float_one)
238 parser->imm_float_one = parser_const_float(parser, 1);
239 return parser->imm_float_one;
242 static char *parser_strdup(const char *str)
245 /* actually dup empty strings */
246 char *out = (char*)mem_a(1);
250 return util_strdup(str);
253 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
257 for (i = 0; i < vec_size(parser->imm_string); ++i) {
258 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
259 return parser->imm_string[i];
263 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
264 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
266 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
268 out->hasvalue = true;
269 out->constval.vstring = parser_strdup(str);
270 vec_push(parser->imm_string, out);
274 static ast_value* parser_const_vector(parser_t *parser, vector v)
278 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
279 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
280 return parser->imm_vector[i];
282 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
284 out->hasvalue = true;
285 out->constval.vvec = v;
286 vec_push(parser->imm_vector, out);
290 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
296 return parser_const_vector(parser, v);
299 static ast_value* parser_const_vector_0(parser_t *parser)
301 if (!parser->imm_vector_zero)
302 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
303 return parser->imm_vector_zero;
306 static ast_expression* parser_find_field(parser_t *parser, const char *name)
308 return ( ast_expression*)util_htget(parser->htfields, name);
311 static ast_expression* parser_find_label(parser_t *parser, const char *name)
314 for(i = 0; i < vec_size(parser->labels); i++)
315 if (!strcmp(parser->labels[i]->name, name))
316 return (ast_expression*)parser->labels[i];
320 static ast_expression* parser_find_global(parser_t *parser, const char *name)
322 return (ast_expression*)util_htget(parser->htglobals, name);
325 static ast_expression* parser_find_param(parser_t *parser, const char *name)
329 if (!parser->function)
331 fun = parser->function->vtype;
332 for (i = 0; i < vec_size(fun->expression.params); ++i) {
333 if (!strcmp(fun->expression.params[i]->name, name))
334 return (ast_expression*)(fun->expression.params[i]);
339 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
344 hash = util_hthash(parser->htglobals, name);
347 for (i = vec_size(parser->variables); i > upto;) {
349 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
353 return parser_find_param(parser, name);
356 static ast_expression* parser_find_var(parser_t *parser, const char *name)
360 v = parser_find_local(parser, name, 0, &dummy);
361 if (!v) v = parser_find_global(parser, name);
365 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
369 hash = util_hthash(parser->typedefs[0], name);
371 for (i = vec_size(parser->typedefs); i > upto;) {
373 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
381 size_t etype; /* 0 = expression, others are operators */
385 ast_block *block; /* for commas and function calls */
404 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
415 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
419 e.out = (ast_expression*)v;
426 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
428 e.etype = 1 + (op - operators);
437 static sy_elem syparen(lex_ctx ctx, size_t off) {
448 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
449 * so we need to rotate it to become ent.(foo[n]).
451 static bool rotate_entfield_array_index_nodes(ast_expression **out)
453 ast_array_index *index, *oldindex;
454 ast_entfield *entfield;
458 ast_expression *entity;
460 lex_ctx ctx = ast_ctx(*out);
462 if (!ast_istype(*out, ast_array_index))
464 index = (ast_array_index*)*out;
466 if (!ast_istype(index->array, ast_entfield))
468 entfield = (ast_entfield*)index->array;
470 if (!ast_istype(entfield->field, ast_value))
472 field = (ast_value*)entfield->field;
475 entity = entfield->entity;
479 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
480 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
481 *out = (ast_expression*)entfield;
483 oldindex->array = NULL;
484 oldindex->index = NULL;
485 ast_delete(oldindex);
490 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
492 switch (v->expression.vtype) {
494 return !!v->constval.vfloat;
496 return !!v->constval.vint;
498 if (OPTS_FLAG(CORRECT_LOGIC))
499 return v->constval.vvec.x &&
500 v->constval.vvec.y &&
503 return !!(v->constval.vvec.x);
505 if (!v->constval.vstring)
507 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
509 return !!v->constval.vstring[0];
511 compile_error(ctx, "internal error: immediate_is_true on invalid type");
512 return !!v->constval.vfunc;
516 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
520 ast_expression *out = NULL;
521 ast_expression *exprs[3];
522 ast_block *blocks[3];
523 ast_value *asvalue[3];
524 ast_binstore *asbinstore;
525 size_t i, assignop, addop, subop;
526 qcint generated_op = 0;
531 if (!vec_size(sy->ops)) {
532 parseerror(parser, "internal error: missing operator");
536 if (vec_last(sy->ops).isparen) {
537 parseerror(parser, "unmatched parenthesis");
541 op = &operators[vec_last(sy->ops).etype - 1];
542 ctx = vec_last(sy->ops).ctx;
544 if (vec_size(sy->out) < op->operands) {
545 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
546 op->op, (int)op->id);
550 vec_shrinkby(sy->ops, 1);
552 /* op(:?) has no input and no output */
556 vec_shrinkby(sy->out, op->operands);
557 for (i = 0; i < op->operands; ++i) {
558 exprs[i] = sy->out[vec_size(sy->out)+i].out;
559 blocks[i] = sy->out[vec_size(sy->out)+i].block;
560 asvalue[i] = (ast_value*)exprs[i];
562 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
563 !(i != 0 && op->id == opid2('?',':')) &&
564 !(i == 1 && op->id == opid1('.')))
566 if (ast_istype(exprs[i], ast_label))
567 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
569 compile_error(ast_ctx(exprs[i]), "not an expression");
570 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
574 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
575 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
579 #define NotSameType(T) \
580 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
581 exprs[0]->expression.vtype != T)
582 #define CanConstFold1(A) \
583 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
584 (A)->expression.vtype != TYPE_FUNCTION)
585 #define CanConstFold(A, B) \
586 (CanConstFold1(A) && CanConstFold1(B))
587 #define ConstV(i) (asvalue[(i)]->constval.vvec)
588 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
589 #define ConstS(i) (asvalue[(i)]->constval.vstring)
593 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
597 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
598 exprs[1]->expression.vtype == TYPE_NOEXPR)
600 if (exprs[1] == (ast_expression*)parser->const_vec[0])
601 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
602 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
603 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
604 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
605 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
607 compile_error(ctx, "access to invalid vector component");
611 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
612 if (exprs[1]->expression.vtype != TYPE_FIELD) {
613 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
616 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
618 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
619 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
623 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
629 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
630 !(exprs[0]->expression.vtype == TYPE_FIELD &&
631 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
633 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
634 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
637 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
638 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
639 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
642 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
643 if (rotate_entfield_array_index_nodes(&out))
646 /* This is not broken in fteqcc anymore */
647 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
648 /* this error doesn't need to make us bail out */
649 (void)!parsewarning(parser, WARN_EXTENSIONS,
650 "accessing array-field members of an entity without parenthesis\n"
651 " -> this is an extension from -std=gmqcc");
658 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
659 vec_push(sy->out, syexp(ctx, exprs[0]));
660 vec_push(sy->out, syexp(ctx, exprs[1]));
661 vec_last(sy->argc)++;
665 if (!ast_block_add_expr(blocks[0], exprs[1]))
668 blocks[0] = ast_block_new(ctx);
669 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
670 !ast_block_add_expr(blocks[0], exprs[1]))
675 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);
1089 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1091 eq->refs = false; /* references nothing */
1094 out = (ast_expression*)ast_ternary_new(ctx,
1095 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1097 (ast_expression*)parser_const_float_neg1(parser),
1100 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1102 (ast_expression*)parser_const_float_0(parser),
1105 (ast_expression*)parser_const_float_1(parser)
1115 generated_op += 1; /* INSTR_GT */
1117 generated_op += 1; /* INSTR_LT */
1118 case opid2('>', '='):
1119 generated_op += 1; /* INSTR_GE */
1120 case opid2('<', '='):
1121 generated_op += INSTR_LE;
1122 if (NotSameType(TYPE_FLOAT)) {
1123 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1124 type_name[exprs[0]->expression.vtype],
1125 type_name[exprs[1]->expression.vtype]);
1128 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1130 case opid2('!', '='):
1131 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1132 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1133 type_name[exprs[0]->expression.vtype],
1134 type_name[exprs[1]->expression.vtype]);
1137 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1139 case opid2('=', '='):
1140 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1141 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1142 type_name[exprs[0]->expression.vtype],
1143 type_name[exprs[1]->expression.vtype]);
1146 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1150 if (ast_istype(exprs[0], ast_entfield)) {
1151 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1152 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1153 exprs[0]->expression.vtype == TYPE_FIELD &&
1154 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1156 assignop = type_storep_instr[TYPE_VECTOR];
1159 assignop = type_storep_instr[exprs[0]->expression.vtype];
1160 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1162 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1163 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1164 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1165 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1166 exprs[1]->expression.vtype == TYPE_FUNCTION)
1168 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1169 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1172 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1177 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1178 exprs[0]->expression.vtype == TYPE_FIELD &&
1179 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1181 assignop = type_store_instr[TYPE_VECTOR];
1184 assignop = type_store_instr[exprs[0]->expression.vtype];
1187 if (assignop == VINSTR_END) {
1188 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1189 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1190 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1192 else if (!ast_compare_type(exprs[0], exprs[1]))
1194 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1195 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1196 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1197 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1198 exprs[1]->expression.vtype == TYPE_FUNCTION)
1200 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1201 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1204 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1207 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1208 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1210 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1212 case opid3('+','+','P'):
1213 case opid3('-','-','P'):
1215 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1216 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1217 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1220 if (op->id == opid3('+','+','P'))
1221 addop = INSTR_ADD_F;
1223 addop = INSTR_SUB_F;
1224 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1225 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1227 if (ast_istype(exprs[0], ast_entfield)) {
1228 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1230 (ast_expression*)parser_const_float_1(parser));
1232 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1234 (ast_expression*)parser_const_float_1(parser));
1237 case opid3('S','+','+'):
1238 case opid3('S','-','-'):
1240 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1241 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1242 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1245 if (op->id == opid3('S','+','+')) {
1246 addop = INSTR_ADD_F;
1247 subop = INSTR_SUB_F;
1249 addop = INSTR_SUB_F;
1250 subop = INSTR_ADD_F;
1252 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1253 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1255 if (ast_istype(exprs[0], ast_entfield)) {
1256 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1258 (ast_expression*)parser_const_float_1(parser));
1260 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1262 (ast_expression*)parser_const_float_1(parser));
1266 out = (ast_expression*)ast_binary_new(ctx, subop,
1268 (ast_expression*)parser_const_float_1(parser));
1270 case opid2('+','='):
1271 case opid2('-','='):
1272 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1273 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1275 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1276 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1277 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1281 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1282 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1284 if (ast_istype(exprs[0], ast_entfield))
1285 assignop = type_storep_instr[exprs[0]->expression.vtype];
1287 assignop = type_store_instr[exprs[0]->expression.vtype];
1288 switch (exprs[0]->expression.vtype) {
1290 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1291 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1292 exprs[0], exprs[1]);
1295 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1296 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1297 exprs[0], exprs[1]);
1300 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1301 type_name[exprs[0]->expression.vtype],
1302 type_name[exprs[1]->expression.vtype]);
1306 case opid2('*','='):
1307 case opid2('/','='):
1308 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1309 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1310 exprs[0]->expression.vtype == TYPE_VECTOR))
1312 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1313 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1314 compile_error(ctx, "invalid types used in expression: %s and %s",
1318 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1319 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1321 if (ast_istype(exprs[0], ast_entfield))
1322 assignop = type_storep_instr[exprs[0]->expression.vtype];
1324 assignop = type_store_instr[exprs[0]->expression.vtype];
1325 switch (exprs[0]->expression.vtype) {
1327 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1328 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1329 exprs[0], exprs[1]);
1332 if (op->id == opid2('*','=')) {
1333 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1334 exprs[0], exprs[1]);
1336 /* there's no DIV_VF */
1337 if (CanConstFold1(exprs[1])) {
1338 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1340 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1341 (ast_expression*)parser_const_float_1(parser),
1345 compile_error(ctx, "internal error: failed to generate division");
1348 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1353 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1354 type_name[exprs[0]->expression.vtype],
1355 type_name[exprs[1]->expression.vtype]);
1359 case opid2('&','='):
1360 case opid2('|','='):
1361 if (NotSameType(TYPE_FLOAT)) {
1362 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1363 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1364 compile_error(ctx, "invalid types used in expression: %s and %s",
1368 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1369 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1371 if (ast_istype(exprs[0], ast_entfield))
1372 assignop = type_storep_instr[exprs[0]->expression.vtype];
1374 assignop = type_store_instr[exprs[0]->expression.vtype];
1375 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1376 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1377 exprs[0], exprs[1]);
1379 case opid3('&','~','='):
1380 /* This is like: a &= ~(b);
1381 * But QC has no bitwise-not, so we implement it as
1384 if (NotSameType(TYPE_FLOAT)) {
1385 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1386 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1387 compile_error(ctx, "invalid types used in expression: %s and %s",
1391 if (ast_istype(exprs[0], ast_entfield))
1392 assignop = type_storep_instr[exprs[0]->expression.vtype];
1394 assignop = type_store_instr[exprs[0]->expression.vtype];
1395 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1398 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1399 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1401 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1402 asbinstore->keep_dest = true;
1403 out = (ast_expression*)asbinstore;
1406 case opid2('~', 'P'):
1407 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1408 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1409 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1413 if(CanConstFold1(exprs[0]))
1414 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1416 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1422 compile_error(ctx, "failed to apply operator %s", op->op);
1426 vec_push(sy->out, syexp(ctx, out));
1430 static bool parser_close_call(parser_t *parser, shunt *sy)
1432 /* was a function call */
1433 ast_expression *fun;
1434 ast_value *funval = NULL;
1438 size_t paramcount, i;
1440 fid = vec_last(sy->ops).off;
1441 vec_shrinkby(sy->ops, 1);
1443 /* out[fid] is the function
1444 * everything above is parameters...
1446 if (!vec_size(sy->argc)) {
1447 parseerror(parser, "internal error: no argument counter available");
1451 paramcount = vec_last(sy->argc);
1454 if (vec_size(sy->out) < fid) {
1455 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1456 (unsigned long)vec_size(sy->out),
1458 (unsigned long)paramcount);
1462 fun = sy->out[fid].out;
1464 if (fun == intrinsic_debug_typestring) {
1466 if (fid+2 != vec_size(sy->out) ||
1467 vec_last(sy->out).block)
1469 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1472 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1473 ast_unref(vec_last(sy->out).out);
1474 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1475 (ast_expression*)parser_const_string(parser, ty, false));
1476 vec_shrinkby(sy->out, 1);
1480 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1484 if (fid+1 < vec_size(sy->out))
1487 if (fid+1 + paramcount != vec_size(sy->out)) {
1488 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1489 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1493 for (i = 0; i < paramcount; ++i)
1494 vec_push(call->params, sy->out[fid+1 + i].out);
1495 vec_shrinkby(sy->out, paramcount);
1496 (void)!ast_call_check_types(call);
1497 if (parser->max_param_count < paramcount)
1498 parser->max_param_count = paramcount;
1500 if (ast_istype(fun, ast_value)) {
1501 funval = (ast_value*)fun;
1502 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1503 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1505 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1509 /* overwrite fid, the function, with a call */
1510 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1512 if (fun->expression.vtype != TYPE_FUNCTION) {
1513 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1517 if (!fun->expression.next) {
1518 parseerror(parser, "could not determine function return type");
1521 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1523 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1525 return !parsewarning(parser, WARN_DEPRECATED,
1526 "call to function (which is marked deprecated)\n",
1527 "-> it has been declared here: %s:%i",
1528 ast_ctx(fun).file, ast_ctx(fun).line);
1531 return !parsewarning(parser, WARN_DEPRECATED,
1532 "call to `%s` (which is marked deprecated)\n"
1533 "-> `%s` declared here: %s:%i",
1534 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1536 return !parsewarning(parser, WARN_DEPRECATED,
1537 "call to `%s` (deprecated: %s)\n"
1538 "-> `%s` declared here: %s:%i",
1539 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1543 if (vec_size(fun->expression.params) != paramcount &&
1544 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1545 vec_size(fun->expression.params) < paramcount))
1547 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1549 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1550 "too %s parameters for call to %s: expected %i, got %i\n"
1551 " -> `%s` has been declared here: %s:%i",
1552 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1553 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1555 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1556 "too %s parameters for function call: expected %i, got %i\n"
1557 " -> it has been declared here: %s:%i",
1558 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1559 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1566 static bool parser_close_paren(parser_t *parser, shunt *sy)
1568 if (!vec_size(sy->ops)) {
1569 parseerror(parser, "unmatched closing paren");
1573 while (vec_size(sy->ops)) {
1574 if (vec_last(sy->ops).isparen) {
1575 if (vec_last(sy->paren) == PAREN_FUNC) {
1577 if (!parser_close_call(parser, sy))
1581 if (vec_last(sy->paren) == PAREN_EXPR) {
1583 if (!vec_size(sy->out)) {
1584 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1585 vec_shrinkby(sy->ops, 1);
1588 vec_shrinkby(sy->ops, 1);
1591 if (vec_last(sy->paren) == PAREN_INDEX) {
1593 /* pop off the parenthesis */
1594 vec_shrinkby(sy->ops, 1);
1595 /* then apply the index operator */
1596 if (!parser_sy_apply_operator(parser, sy))
1600 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1601 vec_last(sy->paren) = PAREN_TERNARY2;
1602 /* pop off the parenthesis */
1603 vec_shrinkby(sy->ops, 1);
1606 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1609 if (!parser_sy_apply_operator(parser, sy))
1615 static void parser_reclassify_token(parser_t *parser)
1618 for (i = 0; i < operator_count; ++i) {
1619 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1620 parser->tok = TOKEN_OPERATOR;
1626 static ast_expression* parse_vararg_do(parser_t *parser)
1628 ast_expression *idx, *out;
1630 ast_value *funtype = parser->function->vtype;
1632 lex_ctx ctx = parser_ctx(parser);
1634 if (!parser_next(parser) || parser->tok != '(') {
1635 parseerror(parser, "expected parameter index and type in parenthesis");
1638 if (!parser_next(parser)) {
1639 parseerror(parser, "error parsing parameter index");
1643 idx = parse_expression_leave(parser, true, false, false);
1647 if (parser->tok != ',') {
1649 parseerror(parser, "expected comma after parameter index");
1653 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1655 parseerror(parser, "expected typename for vararg");
1659 typevar = parse_typename(parser, NULL, NULL);
1665 if (parser->tok != ')') {
1667 ast_delete(typevar);
1668 parseerror(parser, "expected closing paren");
1673 if (!parser_next(parser)) {
1675 ast_delete(typevar);
1676 parseerror(parser, "parse error after vararg");
1681 if (!parser->function->varargs) {
1683 ast_delete(typevar);
1684 parseerror(parser, "function has no variable argument list");
1688 if (funtype->expression.varparam &&
1689 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1693 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1694 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1695 compile_error(ast_ctx(typevar),
1696 "function was declared to take varargs of type `%s`, requested type is: %s",
1700 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1701 ast_type_adopt(out, typevar);
1702 ast_delete(typevar);
1706 static ast_expression* parse_vararg(parser_t *parser)
1708 bool old_noops = parser->lex->flags.noops;
1710 ast_expression *out;
1712 parser->lex->flags.noops = true;
1713 out = parse_vararg_do(parser);
1715 parser->lex->flags.noops = old_noops;
1719 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1721 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1722 parser->tok == TOKEN_IDENT &&
1723 !strcmp(parser_tokval(parser), "_"))
1725 /* a translatable string */
1728 parser->lex->flags.noops = true;
1729 if (!parser_next(parser) || parser->tok != '(') {
1730 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1733 parser->lex->flags.noops = false;
1734 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1735 parseerror(parser, "expected a constant string in translatable-string extension");
1738 val = parser_const_string(parser, parser_tokval(parser), true);
1741 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1743 if (!parser_next(parser) || parser->tok != ')') {
1744 parseerror(parser, "expected closing paren after translatable string");
1749 else if (parser->tok == TOKEN_DOTS)
1752 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1753 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1756 va = parse_vararg(parser);
1759 vec_push(sy->out, syexp(parser_ctx(parser), va));
1762 else if (parser->tok == TOKEN_FLOATCONST) {
1764 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1767 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1770 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1772 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1775 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1778 else if (parser->tok == TOKEN_STRINGCONST) {
1780 val = parser_const_string(parser, parser_tokval(parser), false);
1783 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1786 else if (parser->tok == TOKEN_VECTORCONST) {
1788 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1791 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1794 else if (parser->tok == TOKEN_IDENT)
1796 const char *ctoken = parser_tokval(parser);
1797 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1798 ast_expression *var;
1799 /* a_vector.{x,y,z} */
1800 if (!vec_size(sy->ops) ||
1801 !vec_last(sy->ops).etype ||
1802 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1803 (prev >= intrinsic_debug_typestring &&
1804 prev <= intrinsic_debug_typestring))
1806 /* When adding more intrinsics, fix the above condition */
1809 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1811 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1813 var = parser_find_var(parser, parser_tokval(parser));
1815 var = parser_find_field(parser, parser_tokval(parser));
1817 if (!var && with_labels) {
1818 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1820 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1821 var = (ast_expression*)lbl;
1822 vec_push(parser->labels, lbl);
1827 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1828 var = (ast_expression*)intrinsic_debug_typestring;
1830 var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
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 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1948 /* found an operator */
1951 /* when declaring variables, a comma starts a new variable */
1952 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1953 /* fixup the token */
1958 /* a colon without a pervious question mark cannot be a ternary */
1959 if (!ternaries && op->id == opid2(':','?')) {
1964 if (op->id == opid1(',')) {
1965 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1966 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1970 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1971 olast = &operators[vec_last(sy.ops).etype-1];
1973 #define IsAssignOp(x) (\
1974 (x) == opid1('=') || \
1975 (x) == opid2('+','=') || \
1976 (x) == opid2('-','=') || \
1977 (x) == opid2('*','=') || \
1978 (x) == opid2('/','=') || \
1979 (x) == opid2('%','=') || \
1980 (x) == opid2('&','=') || \
1981 (x) == opid2('|','=') || \
1982 (x) == opid3('&','~','=') \
1984 if (warn_truthvalue) {
1985 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1986 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1987 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1990 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1991 warn_truthvalue = false;
1996 (op->prec < olast->prec) ||
1997 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1999 if (!parser_sy_apply_operator(parser, &sy))
2001 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2002 olast = &operators[vec_last(sy.ops).etype-1];
2007 if (op->id == opid1('(')) {
2009 size_t sycount = vec_size(sy.out);
2010 /* we expected an operator, this is the function-call operator */
2011 vec_push(sy.paren, PAREN_FUNC);
2012 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2013 vec_push(sy.argc, 0);
2015 vec_push(sy.paren, PAREN_EXPR);
2016 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2019 } else if (op->id == opid1('[')) {
2021 parseerror(parser, "unexpected array subscript");
2024 vec_push(sy.paren, PAREN_INDEX);
2025 /* push both the operator and the paren, this makes life easier */
2026 vec_push(sy.ops, syop(parser_ctx(parser), op));
2027 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2029 } else if (op->id == opid2('?',':')) {
2030 vec_push(sy.ops, syop(parser_ctx(parser), op));
2031 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2034 vec_push(sy.paren, PAREN_TERNARY1);
2035 } else if (op->id == opid2(':','?')) {
2036 if (!vec_size(sy.paren)) {
2037 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2040 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2041 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2044 if (!parser_close_paren(parser, &sy))
2046 vec_push(sy.ops, syop(parser_ctx(parser), op));
2050 vec_push(sy.ops, syop(parser_ctx(parser), op));
2051 wantop = !!(op->flags & OP_SUFFIX);
2054 else if (parser->tok == ')') {
2055 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2056 if (!parser_sy_apply_operator(parser, &sy))
2059 if (!vec_size(sy.paren))
2062 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2063 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2066 if (!parser_close_paren(parser, &sy))
2069 /* must be a function call without parameters */
2070 if (vec_last(sy.paren) != PAREN_FUNC) {
2071 parseerror(parser, "closing paren in invalid position");
2074 if (!parser_close_paren(parser, &sy))
2079 else if (parser->tok == '(') {
2080 parseerror(parser, "internal error: '(' should be classified as operator");
2083 else if (parser->tok == '[') {
2084 parseerror(parser, "internal error: '[' should be classified as operator");
2087 else if (parser->tok == ']') {
2088 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2089 if (!parser_sy_apply_operator(parser, &sy))
2092 if (!vec_size(sy.paren))
2094 if (vec_last(sy.paren) != PAREN_INDEX) {
2095 parseerror(parser, "mismatched parentheses, unexpected ']'");
2098 if (!parser_close_paren(parser, &sy))
2103 if (!parse_sya_operand(parser, &sy, with_labels))
2106 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2107 vec_last(sy.argc)++;
2112 parseerror(parser, "expected operator or end of statement");
2116 if (!parser_next(parser)) {
2119 if (parser->tok == ';' ||
2120 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2121 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2127 while (vec_size(sy.ops)) {
2128 if (!parser_sy_apply_operator(parser, &sy))
2132 parser->lex->flags.noops = true;
2133 if (!vec_size(sy.out)) {
2134 parseerror(parser, "empty expression");
2137 expr = sy.out[0].out;
2140 if (vec_size(sy.paren)) {
2141 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2149 parser->lex->flags.noops = true;
2150 for (i = 0; i < vec_size(sy.out); ++i) {
2152 ast_unref(sy.out[i].out);
2161 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2163 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2166 if (parser->tok != ';') {
2167 parseerror(parser, "semicolon expected after expression");
2171 if (!parser_next(parser)) {
2178 static void parser_enterblock(parser_t *parser)
2180 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2181 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2182 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2183 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2184 vec_push(parser->_block_ctx, parser_ctx(parser));
2187 vec_push(parser->correct_variables, correct_trie_new());
2188 vec_push(parser->correct_variables_score, NULL);
2191 static bool parser_leaveblock(parser_t *parser)
2194 size_t locals, typedefs;
2196 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2197 parseerror(parser, "internal error: parser_leaveblock with no block");
2201 util_htdel(vec_last(parser->variables));
2202 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2204 vec_pop(parser->variables);
2205 vec_pop(parser->correct_variables);
2206 vec_pop(parser->correct_variables_score);
2207 if (!vec_size(parser->_blocklocals)) {
2208 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2212 locals = vec_last(parser->_blocklocals);
2213 vec_pop(parser->_blocklocals);
2214 while (vec_size(parser->_locals) != locals) {
2215 ast_expression *e = vec_last(parser->_locals);
2216 ast_value *v = (ast_value*)e;
2217 vec_pop(parser->_locals);
2218 if (ast_istype(e, ast_value) && !v->uses) {
2219 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2224 typedefs = vec_last(parser->_blocktypedefs);
2225 while (vec_size(parser->_typedefs) != typedefs) {
2226 ast_delete(vec_last(parser->_typedefs));
2227 vec_pop(parser->_typedefs);
2229 util_htdel(vec_last(parser->typedefs));
2230 vec_pop(parser->typedefs);
2232 vec_pop(parser->_block_ctx);
2237 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2239 vec_push(parser->_locals, e);
2240 util_htset(vec_last(parser->variables), name, (void*)e);
2244 vec_last(parser->correct_variables),
2245 &vec_last(parser->correct_variables_score),
2250 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2252 vec_push(parser->globals, e);
2253 util_htset(parser->htglobals, name, e);
2257 parser->correct_variables[0],
2258 &parser->correct_variables_score[0],
2263 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2267 ast_expression *prev;
2269 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2271 ast_type_to_string(cond, ty, sizeof(ty));
2272 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2275 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2278 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2281 parseerror(parser, "internal error: failed to process condition");
2286 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2288 /* vector types need to be cast to true booleans */
2289 ast_binary *bin = (ast_binary*)cond;
2290 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2292 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2294 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2297 parseerror(parser, "internal error: failed to process condition");
2304 unary = (ast_unary*)cond;
2305 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2307 cond = unary->operand;
2308 unary->operand = NULL;
2311 unary = (ast_unary*)cond;
2315 parseerror(parser, "internal error: failed to process condition");
2317 if (ifnot) *_ifnot = !*_ifnot;
2321 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2324 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2327 lex_ctx ctx = parser_ctx(parser);
2329 (void)block; /* not touching */
2331 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2332 if (!parser_next(parser)) {
2333 parseerror(parser, "expected condition or 'not'");
2336 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2338 if (!parser_next(parser)) {
2339 parseerror(parser, "expected condition in parenthesis");
2343 if (parser->tok != '(') {
2344 parseerror(parser, "expected 'if' condition in parenthesis");
2347 /* parse into the expression */
2348 if (!parser_next(parser)) {
2349 parseerror(parser, "expected 'if' condition after opening paren");
2352 /* parse the condition */
2353 cond = parse_expression_leave(parser, false, true, false);
2357 if (parser->tok != ')') {
2358 parseerror(parser, "expected closing paren after 'if' condition");
2362 /* parse into the 'then' branch */
2363 if (!parser_next(parser)) {
2364 parseerror(parser, "expected statement for on-true branch of 'if'");
2368 if (!parse_statement_or_block(parser, &ontrue)) {
2373 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2374 /* check for an else */
2375 if (!strcmp(parser_tokval(parser), "else")) {
2376 /* parse into the 'else' branch */
2377 if (!parser_next(parser)) {
2378 parseerror(parser, "expected on-false branch after 'else'");
2383 if (!parse_statement_or_block(parser, &onfalse)) {
2390 cond = process_condition(parser, cond, &ifnot);
2392 if (ontrue) ast_delete(ontrue);
2393 if (onfalse) ast_delete(onfalse);
2398 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2400 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2401 *out = (ast_expression*)ifthen;
2405 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2406 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2411 /* skip the 'while' and get the body */
2412 if (!parser_next(parser)) {
2413 if (OPTS_FLAG(LOOP_LABELS))
2414 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2416 parseerror(parser, "expected 'while' condition in parenthesis");
2420 if (parser->tok == ':') {
2421 if (!OPTS_FLAG(LOOP_LABELS))
2422 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2423 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2424 parseerror(parser, "expected loop label");
2427 label = util_strdup(parser_tokval(parser));
2428 if (!parser_next(parser)) {
2430 parseerror(parser, "expected 'while' condition in parenthesis");
2435 if (parser->tok != '(') {
2436 parseerror(parser, "expected 'while' condition in parenthesis");
2440 vec_push(parser->breaks, label);
2441 vec_push(parser->continues, label);
2443 rv = parse_while_go(parser, block, out);
2446 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2447 parseerror(parser, "internal error: label stack corrupted");
2453 vec_pop(parser->breaks);
2454 vec_pop(parser->continues);
2459 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2462 ast_expression *cond, *ontrue;
2466 lex_ctx ctx = parser_ctx(parser);
2468 (void)block; /* not touching */
2470 /* parse into the expression */
2471 if (!parser_next(parser)) {
2472 parseerror(parser, "expected 'while' condition after opening paren");
2475 /* parse the condition */
2476 cond = parse_expression_leave(parser, false, true, false);
2480 if (parser->tok != ')') {
2481 parseerror(parser, "expected closing paren after 'while' condition");
2485 /* parse into the 'then' branch */
2486 if (!parser_next(parser)) {
2487 parseerror(parser, "expected while-loop body");
2491 if (!parse_statement_or_block(parser, &ontrue)) {
2496 cond = process_condition(parser, cond, &ifnot);
2501 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2502 *out = (ast_expression*)aloop;
2506 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2507 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2512 /* skip the 'do' and get the body */
2513 if (!parser_next(parser)) {
2514 if (OPTS_FLAG(LOOP_LABELS))
2515 parseerror(parser, "expected loop label or body");
2517 parseerror(parser, "expected loop body");
2521 if (parser->tok == ':') {
2522 if (!OPTS_FLAG(LOOP_LABELS))
2523 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2524 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2525 parseerror(parser, "expected loop label");
2528 label = util_strdup(parser_tokval(parser));
2529 if (!parser_next(parser)) {
2531 parseerror(parser, "expected loop body");
2536 vec_push(parser->breaks, label);
2537 vec_push(parser->continues, label);
2539 rv = parse_dowhile_go(parser, block, out);
2542 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2543 parseerror(parser, "internal error: label stack corrupted");
2549 vec_pop(parser->breaks);
2550 vec_pop(parser->continues);
2555 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2558 ast_expression *cond, *ontrue;
2562 lex_ctx ctx = parser_ctx(parser);
2564 (void)block; /* not touching */
2566 if (!parse_statement_or_block(parser, &ontrue))
2569 /* expect the "while" */
2570 if (parser->tok != TOKEN_KEYWORD ||
2571 strcmp(parser_tokval(parser), "while"))
2573 parseerror(parser, "expected 'while' and condition");
2578 /* skip the 'while' and check for opening paren */
2579 if (!parser_next(parser) || parser->tok != '(') {
2580 parseerror(parser, "expected 'while' condition in parenthesis");
2584 /* parse into the expression */
2585 if (!parser_next(parser)) {
2586 parseerror(parser, "expected 'while' condition after opening paren");
2590 /* parse the condition */
2591 cond = parse_expression_leave(parser, false, true, false);
2595 if (parser->tok != ')') {
2596 parseerror(parser, "expected closing paren after 'while' condition");
2602 if (!parser_next(parser) || parser->tok != ';') {
2603 parseerror(parser, "expected semicolon after condition");
2609 if (!parser_next(parser)) {
2610 parseerror(parser, "parse error");
2616 cond = process_condition(parser, cond, &ifnot);
2621 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2622 *out = (ast_expression*)aloop;
2626 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2627 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2632 /* skip the 'for' and check for opening paren */
2633 if (!parser_next(parser)) {
2634 if (OPTS_FLAG(LOOP_LABELS))
2635 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2637 parseerror(parser, "expected 'for' expressions in parenthesis");
2641 if (parser->tok == ':') {
2642 if (!OPTS_FLAG(LOOP_LABELS))
2643 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2644 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2645 parseerror(parser, "expected loop label");
2648 label = util_strdup(parser_tokval(parser));
2649 if (!parser_next(parser)) {
2651 parseerror(parser, "expected 'for' expressions in parenthesis");
2656 if (parser->tok != '(') {
2657 parseerror(parser, "expected 'for' expressions in parenthesis");
2661 vec_push(parser->breaks, label);
2662 vec_push(parser->continues, label);
2664 rv = parse_for_go(parser, block, out);
2667 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2668 parseerror(parser, "internal error: label stack corrupted");
2674 vec_pop(parser->breaks);
2675 vec_pop(parser->continues);
2679 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2682 ast_expression *initexpr, *cond, *increment, *ontrue;
2688 lex_ctx ctx = parser_ctx(parser);
2690 parser_enterblock(parser);
2697 /* parse into the expression */
2698 if (!parser_next(parser)) {
2699 parseerror(parser, "expected 'for' initializer after opening paren");
2704 if (parser->tok == TOKEN_IDENT)
2705 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2707 if (typevar || parser->tok == TOKEN_TYPENAME) {
2709 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2710 if (parsewarning(parser, WARN_EXTENSIONS,
2711 "current standard does not allow variable declarations in for-loop initializers"))
2715 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2718 else if (parser->tok != ';')
2720 initexpr = parse_expression_leave(parser, false, false, false);
2725 /* move on to condition */
2726 if (parser->tok != ';') {
2727 parseerror(parser, "expected semicolon after for-loop initializer");
2730 if (!parser_next(parser)) {
2731 parseerror(parser, "expected for-loop condition");
2735 /* parse the condition */
2736 if (parser->tok != ';') {
2737 cond = parse_expression_leave(parser, false, true, false);
2742 /* move on to incrementor */
2743 if (parser->tok != ';') {
2744 parseerror(parser, "expected semicolon after for-loop initializer");
2747 if (!parser_next(parser)) {
2748 parseerror(parser, "expected for-loop condition");
2752 /* parse the incrementor */
2753 if (parser->tok != ')') {
2754 lex_ctx condctx = parser_ctx(parser);
2755 increment = parse_expression_leave(parser, false, false, false);
2758 if (!ast_side_effects(increment)) {
2759 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2765 if (parser->tok != ')') {
2766 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2769 /* parse into the 'then' branch */
2770 if (!parser_next(parser)) {
2771 parseerror(parser, "expected for-loop body");
2774 if (!parse_statement_or_block(parser, &ontrue))
2778 cond = process_condition(parser, cond, &ifnot);
2782 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2783 *out = (ast_expression*)aloop;
2785 if (!parser_leaveblock(parser))
2789 if (initexpr) ast_delete(initexpr);
2790 if (cond) ast_delete(cond);
2791 if (increment) ast_delete(increment);
2792 (void)!parser_leaveblock(parser);
2796 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2798 ast_expression *exp = NULL;
2799 ast_return *ret = NULL;
2800 ast_value *expected = parser->function->vtype;
2802 lex_ctx ctx = parser_ctx(parser);
2804 (void)block; /* not touching */
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "expected return expression");
2811 if (parser->tok != ';') {
2812 exp = parse_expression(parser, false, false);
2816 if (exp->expression.vtype != TYPE_NIL &&
2817 exp->expression.vtype != expected->expression.next->expression.vtype)
2819 parseerror(parser, "return with invalid expression");
2822 ret = ast_return_new(ctx, exp);
2828 if (!parser_next(parser))
2829 parseerror(parser, "parse error");
2830 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2831 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2833 ret = ast_return_new(ctx, NULL);
2835 *out = (ast_expression*)ret;
2839 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2842 unsigned int levels = 0;
2843 lex_ctx ctx = parser_ctx(parser);
2844 const char **loops = (is_continue ? parser->continues : parser->breaks);
2846 (void)block; /* not touching */
2847 if (!parser_next(parser)) {
2848 parseerror(parser, "expected semicolon or loop label");
2852 if (!vec_size(loops)) {
2854 parseerror(parser, "`continue` can only be used inside loops");
2856 parseerror(parser, "`break` can only be used inside loops or switches");
2859 if (parser->tok == TOKEN_IDENT) {
2860 if (!OPTS_FLAG(LOOP_LABELS))
2861 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2862 i = vec_size(loops);
2864 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2867 parseerror(parser, "no such loop to %s: `%s`",
2868 (is_continue ? "continue" : "break out of"),
2869 parser_tokval(parser));
2874 if (!parser_next(parser)) {
2875 parseerror(parser, "expected semicolon");
2880 if (parser->tok != ';') {
2881 parseerror(parser, "expected semicolon");
2885 if (!parser_next(parser))
2886 parseerror(parser, "parse error");
2888 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2892 /* returns true when it was a variable qualifier, false otherwise!
2893 * on error, cvq is set to CV_WRONG
2895 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2897 bool had_const = false;
2898 bool had_var = false;
2899 bool had_noref = false;
2900 bool had_attrib = false;
2901 bool had_static = false;
2906 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2908 /* parse an attribute */
2909 if (!parser_next(parser)) {
2910 parseerror(parser, "expected attribute after `[[`");
2914 if (!strcmp(parser_tokval(parser), "noreturn")) {
2915 flags |= AST_FLAG_NORETURN;
2916 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2917 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2922 else if (!strcmp(parser_tokval(parser), "noref")) {
2924 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2925 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2930 else if (!strcmp(parser_tokval(parser), "inline")) {
2931 flags |= AST_FLAG_INLINE;
2932 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2933 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2938 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2939 flags |= AST_FLAG_ALIAS;
2942 if (!parser_next(parser)) {
2943 parseerror(parser, "parse error in attribute");
2947 if (parser->tok == '(') {
2948 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2949 parseerror(parser, "`alias` attribute missing parameter");
2953 *message = util_strdup(parser_tokval(parser));
2955 if (!parser_next(parser)) {
2956 parseerror(parser, "parse error in attribute");
2960 if (parser->tok != ')') {
2961 parseerror(parser, "`alias` attribute expected `)` after parameter");
2965 if (!parser_next(parser)) {
2966 parseerror(parser, "parse error in attribute");
2971 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2972 parseerror(parser, "`alias` attribute expected `]]`");
2976 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2977 flags |= AST_FLAG_DEPRECATED;
2980 if (!parser_next(parser)) {
2981 parseerror(parser, "parse error in attribute");
2985 if (parser->tok == '(') {
2986 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2987 parseerror(parser, "`deprecated` attribute missing parameter");
2991 *message = util_strdup(parser_tokval(parser));
2993 if (!parser_next(parser)) {
2994 parseerror(parser, "parse error in attribute");
2998 if(parser->tok != ')') {
2999 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3003 if (!parser_next(parser)) {
3004 parseerror(parser, "parse error in attribute");
3009 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3010 parseerror(parser, "`deprecated` attribute expected `]]`");
3013 if (*message) mem_d(*message);
3021 /* Skip tokens until we hit a ]] */
3022 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3023 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3024 if (!parser_next(parser)) {
3025 parseerror(parser, "error inside attribute");
3032 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3034 else if (!strcmp(parser_tokval(parser), "const"))
3036 else if (!strcmp(parser_tokval(parser), "var"))
3038 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3040 else if (!strcmp(parser_tokval(parser), "noref"))
3042 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3047 if (!parser_next(parser))
3057 *is_static = had_static;
3061 parseerror(parser, "parse error after variable qualifier");
3066 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3067 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3072 /* skip the 'while' and get the body */
3073 if (!parser_next(parser)) {
3074 if (OPTS_FLAG(LOOP_LABELS))
3075 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3077 parseerror(parser, "expected 'switch' operand in parenthesis");
3081 if (parser->tok == ':') {
3082 if (!OPTS_FLAG(LOOP_LABELS))
3083 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3084 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3085 parseerror(parser, "expected loop label");
3088 label = util_strdup(parser_tokval(parser));
3089 if (!parser_next(parser)) {
3091 parseerror(parser, "expected 'switch' operand in parenthesis");
3096 if (parser->tok != '(') {
3097 parseerror(parser, "expected 'switch' operand in parenthesis");
3101 vec_push(parser->breaks, label);
3103 rv = parse_switch_go(parser, block, out);
3106 if (vec_last(parser->breaks) != label) {
3107 parseerror(parser, "internal error: label stack corrupted");
3113 vec_pop(parser->breaks);
3118 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3120 ast_expression *operand;
3123 ast_switch *switchnode;
3124 ast_switch_case swcase;
3127 bool noref, is_static;
3128 uint32_t qflags = 0;
3130 lex_ctx ctx = parser_ctx(parser);
3132 (void)block; /* not touching */
3135 /* parse into the expression */
3136 if (!parser_next(parser)) {
3137 parseerror(parser, "expected switch operand");
3140 /* parse the operand */
3141 operand = parse_expression_leave(parser, false, false, false);
3145 switchnode = ast_switch_new(ctx, operand);
3148 if (parser->tok != ')') {
3149 ast_delete(switchnode);
3150 parseerror(parser, "expected closing paren after 'switch' operand");
3154 /* parse over the opening paren */
3155 if (!parser_next(parser) || parser->tok != '{') {
3156 ast_delete(switchnode);
3157 parseerror(parser, "expected list of cases");
3161 if (!parser_next(parser)) {
3162 ast_delete(switchnode);
3163 parseerror(parser, "expected 'case' or 'default'");
3167 /* new block; allow some variables to be declared here */
3168 parser_enterblock(parser);
3171 if (parser->tok == TOKEN_IDENT)
3172 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3173 if (typevar || parser->tok == TOKEN_TYPENAME) {
3174 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3175 ast_delete(switchnode);
3180 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3182 if (cvq == CV_WRONG) {
3183 ast_delete(switchnode);
3186 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3187 ast_delete(switchnode);
3196 while (parser->tok != '}') {
3197 ast_block *caseblock;
3199 if (!strcmp(parser_tokval(parser), "case")) {
3200 if (!parser_next(parser)) {
3201 ast_delete(switchnode);
3202 parseerror(parser, "expected expression for case");
3205 swcase.value = parse_expression_leave(parser, false, false, false);
3206 if (!swcase.value) {
3207 ast_delete(switchnode);
3208 parseerror(parser, "expected expression for case");
3211 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3212 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3213 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3219 else if (!strcmp(parser_tokval(parser), "default")) {
3220 swcase.value = NULL;
3221 if (!parser_next(parser)) {
3222 ast_delete(switchnode);
3223 parseerror(parser, "expected colon");
3228 ast_delete(switchnode);
3229 parseerror(parser, "expected 'case' or 'default'");
3233 /* Now the colon and body */
3234 if (parser->tok != ':') {
3235 if (swcase.value) ast_unref(swcase.value);
3236 ast_delete(switchnode);
3237 parseerror(parser, "expected colon");
3241 if (!parser_next(parser)) {
3242 if (swcase.value) ast_unref(swcase.value);
3243 ast_delete(switchnode);
3244 parseerror(parser, "expected statements or case");
3247 caseblock = ast_block_new(parser_ctx(parser));
3249 if (swcase.value) ast_unref(swcase.value);
3250 ast_delete(switchnode);
3253 swcase.code = (ast_expression*)caseblock;
3254 vec_push(switchnode->cases, swcase);
3256 ast_expression *expr;
3257 if (parser->tok == '}')
3259 if (parser->tok == TOKEN_KEYWORD) {
3260 if (!strcmp(parser_tokval(parser), "case") ||
3261 !strcmp(parser_tokval(parser), "default"))
3266 if (!parse_statement(parser, caseblock, &expr, true)) {
3267 ast_delete(switchnode);
3272 if (!ast_block_add_expr(caseblock, expr)) {
3273 ast_delete(switchnode);
3279 parser_leaveblock(parser);
3282 if (parser->tok != '}') {
3283 ast_delete(switchnode);
3284 parseerror(parser, "expected closing paren of case list");
3287 if (!parser_next(parser)) {
3288 ast_delete(switchnode);
3289 parseerror(parser, "parse error after switch");
3292 *out = (ast_expression*)switchnode;
3296 /* parse computed goto sides */
3297 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3298 ast_expression *on_true;
3299 ast_expression *on_false;
3300 ast_expression *cond;
3305 if (ast_istype(*side, ast_ternary)) {
3306 ast_ternary *tern = (ast_ternary*)*side;
3307 on_true = parse_goto_computed(parser, &tern->on_true);
3308 on_false = parse_goto_computed(parser, &tern->on_false);
3310 if (!on_true || !on_false) {
3311 parseerror(parser, "expected label or expression in ternary");
3312 if (on_true) ast_unref(on_true);
3313 if (on_false) ast_unref(on_false);
3321 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3322 } else if (ast_istype(*side, ast_label)) {
3323 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3324 ast_goto_set_label(gt, ((ast_label*)*side));
3326 return (ast_expression*)gt;
3331 static bool parse_goto(parser_t *parser, ast_expression **out)
3333 ast_goto *gt = NULL;
3334 ast_expression *lbl;
3336 if (!parser_next(parser))
3339 if (parser->tok != TOKEN_IDENT) {
3340 ast_expression *expression;
3342 /* could be an expression i.e computed goto :-) */
3343 if (parser->tok != '(') {
3344 parseerror(parser, "expected label name after `goto`");
3348 /* failed to parse expression for goto */
3349 if (!(expression = parse_expression(parser, false, true)) ||
3350 !(*out = parse_goto_computed(parser, &expression))) {
3351 parseerror(parser, "invalid goto expression");
3352 ast_unref(expression);
3359 /* not computed goto */
3360 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3361 lbl = parser_find_label(parser, gt->name);
3363 if (!ast_istype(lbl, ast_label)) {
3364 parseerror(parser, "internal error: label is not an ast_label");
3368 ast_goto_set_label(gt, (ast_label*)lbl);
3371 vec_push(parser->gotos, gt);
3373 if (!parser_next(parser) || parser->tok != ';') {
3374 parseerror(parser, "semicolon expected after goto label");
3377 if (!parser_next(parser)) {
3378 parseerror(parser, "parse error after goto");
3382 *out = (ast_expression*)gt;
3386 static bool parse_skipwhite(parser_t *parser)
3389 if (!parser_next(parser))
3391 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3392 return parser->tok < TOKEN_ERROR;
3395 static bool parse_eol(parser_t *parser)
3397 if (!parse_skipwhite(parser))
3399 return parser->tok == TOKEN_EOL;
3402 static bool parse_pragma_do(parser_t *parser)
3404 if (!parser_next(parser) ||
3405 parser->tok != TOKEN_IDENT ||
3406 strcmp(parser_tokval(parser), "pragma"))
3408 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3411 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3412 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3416 if (!strcmp(parser_tokval(parser), "noref")) {
3417 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3418 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3421 parser->noref = !!parser_token(parser)->constval.i;
3422 if (!parse_eol(parser)) {
3423 parseerror(parser, "parse error after `noref` pragma");
3429 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3436 static bool parse_pragma(parser_t *parser)
3439 parser->lex->flags.preprocessing = true;
3440 parser->lex->flags.mergelines = true;
3441 rv = parse_pragma_do(parser);
3442 if (parser->tok != TOKEN_EOL) {
3443 parseerror(parser, "junk after pragma");
3446 parser->lex->flags.preprocessing = false;
3447 parser->lex->flags.mergelines = false;
3448 if (!parser_next(parser)) {
3449 parseerror(parser, "parse error after pragma");
3455 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3457 bool noref, is_static;
3459 uint32_t qflags = 0;
3460 ast_value *typevar = NULL;
3461 char *vstring = NULL;
3465 if (parser->tok == TOKEN_IDENT)
3466 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3468 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3470 /* local variable */
3472 parseerror(parser, "cannot declare a variable from here");
3475 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3476 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3479 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3483 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3485 if (cvq == CV_WRONG)
3487 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3489 else if (parser->tok == TOKEN_KEYWORD)
3491 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3496 if (!parser_next(parser)) {
3497 parseerror(parser, "parse error after __builtin_debug_printtype");
3501 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3503 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3504 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3505 if (!parser_next(parser)) {
3506 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3512 if (!parse_statement(parser, block, out, allow_cases))
3515 con_out("__builtin_debug_printtype: got no output node\n");
3518 ast_type_to_string(*out, ty, sizeof(ty));
3519 con_out("__builtin_debug_printtype: `%s`\n", ty);
3524 else if (!strcmp(parser_tokval(parser), "return"))
3526 return parse_return(parser, block, out);
3528 else if (!strcmp(parser_tokval(parser), "if"))
3530 return parse_if(parser, block, out);
3532 else if (!strcmp(parser_tokval(parser), "while"))
3534 return parse_while(parser, block, out);
3536 else if (!strcmp(parser_tokval(parser), "do"))
3538 return parse_dowhile(parser, block, out);
3540 else if (!strcmp(parser_tokval(parser), "for"))
3542 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3543 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3546 return parse_for(parser, block, out);
3548 else if (!strcmp(parser_tokval(parser), "break"))
3550 return parse_break_continue(parser, block, out, false);
3552 else if (!strcmp(parser_tokval(parser), "continue"))
3554 return parse_break_continue(parser, block, out, true);
3556 else if (!strcmp(parser_tokval(parser), "switch"))
3558 return parse_switch(parser, block, out);
3560 else if (!strcmp(parser_tokval(parser), "case") ||
3561 !strcmp(parser_tokval(parser), "default"))
3564 parseerror(parser, "unexpected 'case' label");
3569 else if (!strcmp(parser_tokval(parser), "goto"))
3571 return parse_goto(parser, out);
3573 else if (!strcmp(parser_tokval(parser), "typedef"))
3575 if (!parser_next(parser)) {
3576 parseerror(parser, "expected type definition after 'typedef'");
3579 return parse_typedef(parser);
3581 parseerror(parser, "Unexpected keyword");
3584 else if (parser->tok == '{')
3587 inner = parse_block(parser);
3590 *out = (ast_expression*)inner;
3593 else if (parser->tok == ':')
3597 if (!parser_next(parser)) {
3598 parseerror(parser, "expected label name");
3601 if (parser->tok != TOKEN_IDENT) {
3602 parseerror(parser, "label must be an identifier");
3605 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3607 if (!label->undefined) {
3608 parseerror(parser, "label `%s` already defined", label->name);
3611 label->undefined = false;
3614 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3615 vec_push(parser->labels, label);
3617 *out = (ast_expression*)label;
3618 if (!parser_next(parser)) {
3619 parseerror(parser, "parse error after label");
3622 for (i = 0; i < vec_size(parser->gotos); ++i) {
3623 if (!strcmp(parser->gotos[i]->name, label->name)) {
3624 ast_goto_set_label(parser->gotos[i], label);
3625 vec_remove(parser->gotos, i, 1);
3631 else if (parser->tok == ';')
3633 if (!parser_next(parser)) {
3634 parseerror(parser, "parse error after empty statement");
3641 lex_ctx ctx = parser_ctx(parser);
3642 ast_expression *exp = parse_expression(parser, false, false);
3646 if (!ast_side_effects(exp)) {
3647 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3654 static bool parse_enum(parser_t *parser)
3657 ast_value **values = NULL;
3658 ast_value *var = NULL;
3661 ast_expression *old;
3663 if (!parser_next(parser) || parser->tok != '{') {
3664 parseerror(parser, "expected `{` after `enum` keyword");
3669 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3670 if (parser->tok == '}') {
3671 /* allow an empty enum */
3674 parseerror(parser, "expected identifier or `}`");
3678 old = parser_find_field(parser, parser_tokval(parser));
3680 old = parser_find_global(parser, parser_tokval(parser));
3682 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3683 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3687 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3688 vec_push(values, var);
3689 var->cvq = CV_CONST;
3690 var->hasvalue = true;
3691 var->constval.vfloat = num++;
3693 parser_addglobal(parser, var->name, (ast_expression*)var);
3695 if (!parser_next(parser)) {
3696 parseerror(parser, "expected `=`, `}` or comma after identifier");
3700 if (parser->tok == ',')
3702 if (parser->tok == '}')
3704 if (parser->tok != '=') {
3705 parseerror(parser, "expected `=`, `}` or comma after identifier");
3709 if (!parser_next(parser)) {
3710 parseerror(parser, "expected expression after `=`");
3714 /* We got a value! */
3715 old = parse_expression_leave(parser, true, false, false);
3716 asvalue = (ast_value*)old;
3717 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3718 compile_error(ast_ctx(var), "constant value or expression expected");
3721 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3723 if (parser->tok == '}')
3725 if (parser->tok != ',') {
3726 parseerror(parser, "expected `}` or comma after expression");
3731 if (parser->tok != '}') {
3732 parseerror(parser, "internal error: breaking without `}`");
3736 if (!parser_next(parser) || parser->tok != ';') {
3737 parseerror(parser, "expected semicolon after enumeration");
3741 if (!parser_next(parser)) {
3742 parseerror(parser, "parse error after enumeration");
3754 static bool parse_block_into(parser_t *parser, ast_block *block)
3758 parser_enterblock(parser);
3760 if (!parser_next(parser)) { /* skip the '{' */
3761 parseerror(parser, "expected function body");
3765 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3767 ast_expression *expr = NULL;
3768 if (parser->tok == '}')
3771 if (!parse_statement(parser, block, &expr, false)) {
3772 /* parseerror(parser, "parse error"); */
3778 if (!ast_block_add_expr(block, expr)) {
3785 if (parser->tok != '}') {
3788 (void)parser_next(parser);
3792 if (!parser_leaveblock(parser))
3794 return retval && !!block;
3797 static ast_block* parse_block(parser_t *parser)
3800 block = ast_block_new(parser_ctx(parser));
3803 if (!parse_block_into(parser, block)) {
3804 ast_block_delete(block);
3810 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3812 if (parser->tok == '{') {
3813 *out = (ast_expression*)parse_block(parser);
3816 return parse_statement(parser, NULL, out, false);
3819 static bool create_vector_members(ast_value *var, ast_member **me)
3822 size_t len = strlen(var->name);
3824 for (i = 0; i < 3; ++i) {
3825 char *name = (char*)mem_a(len+3);
3826 memcpy(name, var->name, len);
3828 name[len+1] = 'x'+i;
3830 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3839 do { ast_member_delete(me[--i]); } while(i);
3843 static bool parse_function_body(parser_t *parser, ast_value *var)
3845 ast_block *block = NULL;
3850 ast_expression *framenum = NULL;
3851 ast_expression *nextthink = NULL;
3852 /* None of the following have to be deleted */
3853 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3854 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3855 bool has_frame_think;
3859 has_frame_think = false;
3860 old = parser->function;
3862 if (var->expression.flags & AST_FLAG_ALIAS) {
3863 parseerror(parser, "function aliases cannot have bodies");
3867 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3868 parseerror(parser, "gotos/labels leaking");
3872 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3873 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3874 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3880 if (parser->tok == '[') {
3881 /* got a frame definition: [ framenum, nextthink ]
3882 * this translates to:
3883 * self.frame = framenum;
3884 * self.nextthink = time + 0.1;
3885 * self.think = nextthink;
3889 fld_think = parser_find_field(parser, "think");
3890 fld_nextthink = parser_find_field(parser, "nextthink");
3891 fld_frame = parser_find_field(parser, "frame");
3892 if (!fld_think || !fld_nextthink || !fld_frame) {
3893 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3894 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3897 gbl_time = parser_find_global(parser, "time");
3898 gbl_self = parser_find_global(parser, "self");
3899 if (!gbl_time || !gbl_self) {
3900 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3901 parseerror(parser, "please declare the following globals: `time`, `self`");
3905 if (!parser_next(parser))
3908 framenum = parse_expression_leave(parser, true, false, false);
3910 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3913 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3914 ast_unref(framenum);
3915 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3919 if (parser->tok != ',') {
3920 ast_unref(framenum);
3921 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3922 parseerror(parser, "Got a %i\n", parser->tok);
3926 if (!parser_next(parser)) {
3927 ast_unref(framenum);
3931 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3933 /* qc allows the use of not-yet-declared functions here
3934 * - this automatically creates a prototype */
3935 ast_value *thinkfunc;
3936 ast_expression *functype = fld_think->expression.next;
3938 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3939 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3940 ast_unref(framenum);
3941 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3944 ast_type_adopt(thinkfunc, functype);
3946 if (!parser_next(parser)) {
3947 ast_unref(framenum);
3948 ast_delete(thinkfunc);
3952 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3954 nextthink = (ast_expression*)thinkfunc;
3957 nextthink = parse_expression_leave(parser, true, false, false);
3959 ast_unref(framenum);
3960 parseerror(parser, "expected a think-function in [frame,think] notation");
3965 if (!ast_istype(nextthink, ast_value)) {
3966 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3970 if (retval && parser->tok != ']') {
3971 parseerror(parser, "expected closing `]` for [frame,think] notation");
3975 if (retval && !parser_next(parser)) {
3979 if (retval && parser->tok != '{') {
3980 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3985 ast_unref(nextthink);
3986 ast_unref(framenum);
3990 has_frame_think = true;
3993 block = ast_block_new(parser_ctx(parser));
3995 parseerror(parser, "failed to allocate block");
3996 if (has_frame_think) {
3997 ast_unref(nextthink);
3998 ast_unref(framenum);
4003 if (has_frame_think) {
4005 ast_expression *self_frame;
4006 ast_expression *self_nextthink;
4007 ast_expression *self_think;
4008 ast_expression *time_plus_1;
4009 ast_store *store_frame;
4010 ast_store *store_nextthink;
4011 ast_store *store_think;
4013 ctx = parser_ctx(parser);
4014 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4015 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4016 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4018 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4019 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4021 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4022 if (self_frame) ast_delete(self_frame);
4023 if (self_nextthink) ast_delete(self_nextthink);
4024 if (self_think) ast_delete(self_think);
4025 if (time_plus_1) ast_delete(time_plus_1);
4031 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4032 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4033 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4036 ast_delete(self_frame);
4039 if (!store_nextthink) {
4040 ast_delete(self_nextthink);
4044 ast_delete(self_think);
4048 if (store_frame) ast_delete(store_frame);
4049 if (store_nextthink) ast_delete(store_nextthink);
4050 if (store_think) ast_delete(store_think);
4053 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4054 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4055 !ast_block_add_expr(block, (ast_expression*)store_think))
4062 parseerror(parser, "failed to generate code for [frame,think]");
4063 ast_unref(nextthink);
4064 ast_unref(framenum);
4070 if (var->hasvalue) {
4071 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4072 ast_block_delete(block);
4076 func = ast_function_new(ast_ctx(var), var->name, var);
4078 parseerror(parser, "failed to allocate function for `%s`", var->name);
4079 ast_block_delete(block);
4082 vec_push(parser->functions, func);
4084 parser_enterblock(parser);
4086 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4088 ast_value *param = var->expression.params[parami];
4091 if (param->expression.vtype != TYPE_VECTOR &&
4092 (param->expression.vtype != TYPE_FIELD ||
4093 param->expression.next->expression.vtype != TYPE_VECTOR))
4098 if (!create_vector_members(param, me)) {
4099 ast_block_delete(block);
4103 for (e = 0; e < 3; ++e) {
4104 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4105 ast_block_collect(block, (ast_expression*)me[e]);
4109 if (var->argcounter) {
4110 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4111 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4115 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4117 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4118 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4119 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4120 varargs->expression.count = 0;
4121 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4122 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4123 ast_delete(varargs);
4124 ast_block_delete(block);
4127 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4128 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4129 ast_delete(varargs);
4130 ast_block_delete(block);
4133 func->varargs = varargs;
4135 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4138 parser->function = func;
4139 if (!parse_block_into(parser, block)) {
4140 ast_block_delete(block);
4144 vec_push(func->blocks, block);
4146 parser->function = old;
4147 if (!parser_leaveblock(parser))
4149 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4150 parseerror(parser, "internal error: local scopes left");
4154 if (parser->tok == ';')
4155 return parser_next(parser);
4156 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4157 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4161 (void)!parser_leaveblock(parser);
4162 vec_pop(parser->functions);
4163 ast_function_delete(func);
4164 var->constval.vfunc = NULL;
4167 parser->function = old;
4171 static ast_expression *array_accessor_split(
4176 ast_expression *left,
4177 ast_expression *right
4183 lex_ctx ctx = ast_ctx(array);
4185 if (!left || !right) {
4186 if (left) ast_delete(left);
4187 if (right) ast_delete(right);
4191 cmp = ast_binary_new(ctx, INSTR_LT,
4192 (ast_expression*)index,
4193 (ast_expression*)parser_const_float(parser, middle));
4197 parseerror(parser, "internal error: failed to create comparison for array setter");
4201 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4203 ast_delete(cmp); /* will delete left and right */
4204 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4208 return (ast_expression*)ifthen;
4211 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4213 lex_ctx ctx = ast_ctx(array);
4215 if (from+1 == afterend) {
4216 /* set this value */
4219 ast_array_index *subscript;
4221 int assignop = type_store_instr[value->expression.vtype];
4223 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4224 assignop = INSTR_STORE_V;
4226 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4230 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4232 ast_delete(subscript);
4236 block = ast_block_new(ctx);
4242 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4247 ret = ast_return_new(ctx, NULL);
4253 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4258 return (ast_expression*)block;
4260 ast_expression *left, *right;
4261 size_t diff = afterend - from;
4262 size_t middle = from + diff/2;
4263 left = array_setter_node(parser, array, index, value, from, middle);
4264 right = array_setter_node(parser, array, index, value, middle, afterend);
4265 return array_accessor_split(parser, array, index, middle, left, right);
4269 static ast_expression *array_field_setter_node(
4278 lex_ctx ctx = ast_ctx(array);
4280 if (from+1 == afterend) {
4281 /* set this value */
4284 ast_entfield *entfield;
4285 ast_array_index *subscript;
4287 int assignop = type_storep_instr[value->expression.vtype];
4289 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4290 assignop = INSTR_STOREP_V;
4292 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4296 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4297 subscript->expression.vtype = TYPE_FIELD;
4299 entfield = ast_entfield_new_force(ctx,
4300 (ast_expression*)entity,
4301 (ast_expression*)subscript,
4302 (ast_expression*)subscript);
4304 ast_delete(subscript);
4308 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4310 ast_delete(entfield);
4314 block = ast_block_new(ctx);
4320 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4325 ret = ast_return_new(ctx, NULL);
4331 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4336 return (ast_expression*)block;
4338 ast_expression *left, *right;
4339 size_t diff = afterend - from;
4340 size_t middle = from + diff/2;
4341 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4342 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4343 return array_accessor_split(parser, array, index, middle, left, right);
4347 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4349 lex_ctx ctx = ast_ctx(array);
4351 if (from+1 == afterend) {
4353 ast_array_index *subscript;
4355 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4359 ret = ast_return_new(ctx, (ast_expression*)subscript);
4361 ast_delete(subscript);
4365 return (ast_expression*)ret;
4367 ast_expression *left, *right;
4368 size_t diff = afterend - from;
4369 size_t middle = from + diff/2;
4370 left = array_getter_node(parser, array, index, from, middle);
4371 right = array_getter_node(parser, array, index, middle, afterend);
4372 return array_accessor_split(parser, array, index, middle, left, right);
4376 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4378 ast_function *func = NULL;
4379 ast_value *fval = NULL;
4380 ast_block *body = NULL;
4382 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4384 parseerror(parser, "failed to create accessor function value");
4388 func = ast_function_new(ast_ctx(array), funcname, fval);
4391 parseerror(parser, "failed to create accessor function node");
4395 body = ast_block_new(ast_ctx(array));
4397 parseerror(parser, "failed to create block for array accessor");
4403 vec_push(func->blocks, body);
4406 vec_push(parser->accessors, fval);
4411 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4413 ast_value *index = NULL;
4414 ast_value *value = NULL;
4418 if (!ast_istype(array->expression.next, ast_value)) {
4419 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4423 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4425 func = fval->constval.vfunc;
4426 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4428 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4429 value = ast_value_copy((ast_value*)array->expression.next);
4431 if (!index || !value) {
4432 parseerror(parser, "failed to create locals for array accessor");
4435 (void)!ast_value_set_name(value, "value"); /* not important */
4436 vec_push(fval->expression.params, index);
4437 vec_push(fval->expression.params, value);
4439 array->setter = fval;
4442 if (index) ast_delete(index);
4443 if (value) ast_delete(value);
4449 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4451 ast_expression *root = NULL;
4452 root = array_setter_node(parser, array,
4453 array->setter->expression.params[0],
4454 array->setter->expression.params[1],
4455 0, array->expression.count);
4457 parseerror(parser, "failed to build accessor search tree");
4460 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4467 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4469 if (!parser_create_array_setter_proto(parser, array, funcname))
4471 return parser_create_array_setter_impl(parser, array);
4474 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4476 ast_expression *root = NULL;
4477 ast_value *entity = NULL;
4478 ast_value *index = NULL;
4479 ast_value *value = NULL;
4483 if (!ast_istype(array->expression.next, ast_value)) {
4484 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4488 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4490 func = fval->constval.vfunc;
4491 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4493 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4494 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4495 value = ast_value_copy((ast_value*)array->expression.next);
4496 if (!entity || !index || !value) {
4497 parseerror(parser, "failed to create locals for array accessor");
4500 (void)!ast_value_set_name(value, "value"); /* not important */
4501 vec_push(fval->expression.params, entity);
4502 vec_push(fval->expression.params, index);
4503 vec_push(fval->expression.params, value);
4505 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4507 parseerror(parser, "failed to build accessor search tree");
4511 array->setter = fval;
4512 return ast_block_add_expr(func->blocks[0], root);
4514 if (entity) ast_delete(entity);
4515 if (index) ast_delete(index);
4516 if (value) ast_delete(value);
4517 if (root) ast_delete(root);
4523 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4525 ast_value *index = NULL;
4529 /* NOTE: checking array->expression.next rather than elemtype since
4530 * for fields elemtype is a temporary fieldtype.
4532 if (!ast_istype(array->expression.next, ast_value)) {
4533 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4537 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4539 func = fval->constval.vfunc;
4540 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4542 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4545 parseerror(parser, "failed to create locals for array accessor");
4548 vec_push(fval->expression.params, index);
4550 array->getter = fval;
4553 if (index) ast_delete(index);
4559 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4561 ast_expression *root = NULL;
4563 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4565 parseerror(parser, "failed to build accessor search tree");
4568 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4575 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4577 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4579 return parser_create_array_getter_impl(parser, array);
4582 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4583 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4591 bool variadic = false;
4592 ast_value *varparam = NULL;
4593 char *argcounter = NULL;
4595 ctx = parser_ctx(parser);
4597 /* for the sake of less code we parse-in in this function */
4598 if (!parser_next(parser)) {
4599 parseerror(parser, "expected parameter list");
4605 /* parse variables until we hit a closing paren */
4606 while (parser->tok != ')') {
4608 /* there must be commas between them */
4609 if (parser->tok != ',') {
4610 parseerror(parser, "expected comma or end of parameter list");
4613 if (!parser_next(parser)) {
4614 parseerror(parser, "expected parameter");
4620 if (parser->tok == TOKEN_DOTS) {
4621 /* '...' indicates a varargs function */
4623 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4624 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4627 if (parser->tok == TOKEN_IDENT) {
4628 argcounter = util_strdup(parser_tokval(parser));
4629 if (!parser_next(parser) || parser->tok != ')') {
4630 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4637 /* for anything else just parse a typename */
4638 param = parse_typename(parser, NULL, NULL);
4641 vec_push(params, param);
4642 if (param->expression.vtype >= TYPE_VARIANT) {
4643 char tname[1024]; /* typename is reserved in C++ */
4644 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4645 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4648 /* type-restricted varargs */
4649 if (parser->tok == TOKEN_DOTS) {
4651 varparam = vec_last(params);
4653 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4654 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4657 if (parser->tok == TOKEN_IDENT) {
4658 argcounter = util_strdup(parser_tokval(parser));
4659 if (!parser_next(parser) || parser->tok != ')') {
4660 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4668 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4672 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4673 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4676 if (!parser_next(parser)) {
4677 parseerror(parser, "parse error after typename");
4681 /* now turn 'var' into a function type */
4682 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4683 fval->expression.next = (ast_expression*)var;
4685 fval->expression.flags |= AST_FLAG_VARIADIC;
4688 var->expression.params = params;
4689 var->expression.varparam = (ast_expression*)varparam;
4690 var->argcounter = argcounter;
4699 for (i = 0; i < vec_size(params); ++i)
4700 ast_delete(params[i]);
4705 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4707 ast_expression *cexp;
4708 ast_value *cval, *tmp;
4711 ctx = parser_ctx(parser);
4713 if (!parser_next(parser)) {
4715 parseerror(parser, "expected array-size");
4719 cexp = parse_expression_leave(parser, true, false, false);
4721 if (!cexp || !ast_istype(cexp, ast_value)) {
4725 parseerror(parser, "expected array-size as constant positive integer");
4728 cval = (ast_value*)cexp;
4730 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4731 tmp->expression.next = (ast_expression*)var;
4734 if (cval->expression.vtype == TYPE_INTEGER)
4735 tmp->expression.count = cval->constval.vint;
4736 else if (cval->expression.vtype == TYPE_FLOAT)
4737 tmp->expression.count = cval->constval.vfloat;
4741 parseerror(parser, "array-size must be a positive integer constant");
4746 if (parser->tok != ']') {
4748 parseerror(parser, "expected ']' after array-size");
4751 if (!parser_next(parser)) {
4753 parseerror(parser, "error after parsing array size");
4759 /* Parse a complete typename.
4760 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4761 * but when parsing variables separated by comma
4762 * 'storebase' should point to where the base-type should be kept.
4763 * The base type makes up every bit of type information which comes *before* the
4766 * The following will be parsed in its entirety:
4768 * The 'basetype' in this case is 'void()'
4769 * and if there's a comma after it, say:
4771 * then the type-information 'void()' can be stored in 'storebase'
4773 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4775 ast_value *var, *tmp;
4778 const char *name = NULL;
4779 bool isfield = false;
4780 bool wasarray = false;
4781 size_t morefields = 0;
4783 ctx = parser_ctx(parser);
4785 /* types may start with a dot */
4786 if (parser->tok == '.') {
4788 /* if we parsed a dot we need a typename now */
4789 if (!parser_next(parser)) {
4790 parseerror(parser, "expected typename for field definition");
4794 /* Further dots are handled seperately because they won't be part of the
4797 while (parser->tok == '.') {
4799 if (!parser_next(parser)) {
4800 parseerror(parser, "expected typename for field definition");
4805 if (parser->tok == TOKEN_IDENT)
4806 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4807 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4808 parseerror(parser, "expected typename");
4812 /* generate the basic type value */
4813 if (cached_typedef) {
4814 var = ast_value_copy(cached_typedef);
4815 ast_value_set_name(var, "<type(from_def)>");
4817 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4819 for (; morefields; --morefields) {
4820 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4821 tmp->expression.next = (ast_expression*)var;
4825 /* do not yet turn into a field - remember:
4826 * .void() foo; is a field too
4827 * .void()() foo; is a function
4831 if (!parser_next(parser)) {
4833 parseerror(parser, "parse error after typename");
4837 /* an opening paren now starts the parameter-list of a function
4838 * this is where original-QC has parameter lists.
4839 * We allow a single parameter list here.
4840 * Much like fteqcc we don't allow `float()() x`
4842 if (parser->tok == '(') {
4843 var = parse_parameter_list(parser, var);
4848 /* store the base if requested */
4850 *storebase = ast_value_copy(var);
4852 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4853 tmp->expression.next = (ast_expression*)*storebase;
4858 /* there may be a name now */
4859 if (parser->tok == TOKEN_IDENT) {
4860 name = util_strdup(parser_tokval(parser));
4862 if (!parser_next(parser)) {
4864 parseerror(parser, "error after variable or field declaration");
4869 /* now this may be an array */
4870 if (parser->tok == '[') {
4872 var = parse_arraysize(parser, var);
4877 /* This is the point where we can turn it into a field */
4879 /* turn it into a field if desired */
4880 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4881 tmp->expression.next = (ast_expression*)var;
4885 /* now there may be function parens again */
4886 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4887 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4888 if (parser->tok == '(' && wasarray)
4889 parseerror(parser, "arrays as part of a return type is not supported");
4890 while (parser->tok == '(') {
4891 var = parse_parameter_list(parser, var);
4899 /* finally name it */
4901 if (!ast_value_set_name(var, name)) {
4903 parseerror(parser, "internal error: failed to set name");
4906 /* free the name, ast_value_set_name duplicates */
4913 static bool parse_typedef(parser_t *parser)
4915 ast_value *typevar, *oldtype;
4916 ast_expression *old;
4918 typevar = parse_typename(parser, NULL, NULL);
4923 if ( (old = parser_find_var(parser, typevar->name)) ) {
4924 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4925 " -> `%s` has been declared here: %s:%i",
4926 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4927 ast_delete(typevar);
4931 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4932 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4933 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4934 ast_delete(typevar);
4938 vec_push(parser->_typedefs, typevar);
4939 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4941 if (parser->tok != ';') {
4942 parseerror(parser, "expected semicolon after typedef");
4945 if (!parser_next(parser)) {
4946 parseerror(parser, "parse error after typedef");
4953 static const char *cvq_to_str(int cvq) {
4955 case CV_NONE: return "none";
4956 case CV_VAR: return "`var`";
4957 case CV_CONST: return "`const`";
4958 default: return "<INVALID>";
4962 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4965 if (proto->cvq != var->cvq) {
4966 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4967 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4968 parser->tok == '='))
4970 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4971 "`%s` declared with different qualifiers: %s\n"
4972 " -> previous declaration here: %s:%i uses %s",
4973 var->name, cvq_to_str(var->cvq),
4974 ast_ctx(proto).file, ast_ctx(proto).line,
4975 cvq_to_str(proto->cvq));
4978 av = (var ->expression.flags & AST_FLAG_NORETURN);
4979 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4981 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4982 "`%s` declared with different attributes%s\n"
4983 " -> previous declaration here: %s:%i",
4984 var->name, (av ? ": noreturn" : ""),
4985 ast_ctx(proto).file, ast_ctx(proto).line,
4986 (ao ? ": noreturn" : ""));
4991 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)
4995 ast_expression *old;
4999 ast_value *basetype = NULL;
5001 bool isparam = false;
5002 bool isvector = false;
5003 bool cleanvar = true;
5004 bool wasarray = false;
5008 if (!localblock && is_static)
5009 parseerror(parser, "`static` qualifier is not supported in global scope");
5011 /* get the first complete variable */
5012 var = parse_typename(parser, &basetype, cached_typedef);
5015 ast_delete(basetype);
5023 /* Part 0: finish the type */
5024 if (parser->tok == '(') {
5025 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5026 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5027 var = parse_parameter_list(parser, var);
5033 /* we only allow 1-dimensional arrays */
5034 if (parser->tok == '[') {
5036 var = parse_arraysize(parser, var);
5042 if (parser->tok == '(' && wasarray) {
5043 parseerror(parser, "arrays as part of a return type is not supported");
5044 /* we'll still parse the type completely for now */
5046 /* for functions returning functions */
5047 while (parser->tok == '(') {
5048 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5049 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5050 var = parse_parameter_list(parser, var);
5057 var->cvq = qualifier;
5058 var->expression.flags |= qflags;
5061 * store the vstring back to var for alias and
5062 * deprecation messages.
5064 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5065 var->expression.flags & AST_FLAG_ALIAS)
5066 var->desc = vstring;
5069 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5070 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5071 * is then filled with the previous definition and the parameter-names replaced.
5073 if (!strcmp(var->name, "nil")) {
5074 if (OPTS_FLAG(UNTYPED_NIL)) {
5075 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5076 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5078 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5081 /* Deal with end_sys_ vars */
5083 if (!strcmp(var->name, "end_sys_globals")) {
5085 parser->crc_globals = vec_size(parser->globals);
5088 else if (!strcmp(var->name, "end_sys_fields")) {
5090 parser->crc_fields = vec_size(parser->fields);
5093 if (was_end && var->expression.vtype == TYPE_FIELD) {
5094 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5095 "global '%s' hint should not be a field",
5096 parser_tokval(parser)))
5103 if (!nofields && var->expression.vtype == TYPE_FIELD)
5105 /* deal with field declarations */
5106 old = parser_find_field(parser, var->name);
5108 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5109 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5118 parseerror(parser, "field `%s` already declared here: %s:%i",
5119 var->name, ast_ctx(old).file, ast_ctx(old).line);
5124 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5125 (old = parser_find_global(parser, var->name)))
5127 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5128 parseerror(parser, "field `%s` already declared here: %s:%i",
5129 var->name, ast_ctx(old).file, ast_ctx(old).line);
5136 /* deal with other globals */
5137 old = parser_find_global(parser, var->name);
5138 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5140 /* This is a function which had a prototype */
5141 if (!ast_istype(old, ast_value)) {
5142 parseerror(parser, "internal error: prototype is not an ast_value");
5146 proto = (ast_value*)old;
5147 proto->desc = var->desc;
5148 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5149 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5151 ast_ctx(proto).file, ast_ctx(proto).line);
5155 /* we need the new parameter-names */
5156 for (i = 0; i < vec_size(proto->expression.params); ++i)
5157 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5158 if (!parser_check_qualifiers(parser, var, proto)) {
5165 proto->expression.flags |= var->expression.flags;
5173 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5174 "global `%s` already declared here: %s:%i",
5175 var->name, ast_ctx(old).file, ast_ctx(old).line))
5180 proto = (ast_value*)old;
5181 if (!ast_istype(old, ast_value)) {
5182 parseerror(parser, "internal error: not an ast_value");
5187 if (!parser_check_qualifiers(parser, var, proto)) {
5192 proto->expression.flags |= var->expression.flags;
5196 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5197 (old = parser_find_field(parser, var->name)))
5199 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5200 parseerror(parser, "global `%s` already declared here: %s:%i",
5201 var->name, ast_ctx(old).file, ast_ctx(old).line);
5208 else /* it's not a global */
5210 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5211 if (old && !isparam) {
5212 parseerror(parser, "local `%s` already declared here: %s:%i",
5213 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5217 old = parser_find_local(parser, var->name, 0, &isparam);
5218 if (old && isparam) {
5219 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5220 "local `%s` is shadowing a parameter", var->name))
5222 parseerror(parser, "local `%s` already declared here: %s:%i",
5223 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5227 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5235 /* in a noref section we simply bump the usecount */
5236 if (noref || parser->noref)
5240 * Create the global/local, and deal with vector types.
5243 if (var->expression.vtype == TYPE_VECTOR)
5245 else if (var->expression.vtype == TYPE_FIELD &&
5246 var->expression.next->expression.vtype == TYPE_VECTOR)
5250 if (!create_vector_members(var, me)) {
5257 /* deal with global variables, fields, functions */
5258 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5259 var->isfield = true;
5260 vec_push(parser->fields, (ast_expression*)var);
5261 util_htset(parser->htfields, var->name, var);
5263 for (i = 0; i < 3; ++i) {
5264 vec_push(parser->fields, (ast_expression*)me[i]);
5265 util_htset(parser->htfields, me[i]->name, me[i]);
5270 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5271 parser_addglobal(parser, var->name, (ast_expression*)var);
5273 for (i = 0; i < 3; ++i) {
5274 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5278 ast_expression *find = parser_find_global(parser, var->desc);
5281 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5285 if (var->expression.vtype != find->expression.vtype) {
5289 ast_type_to_string(find, ty1, sizeof(ty1));
5290 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5292 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5299 * add alias to aliases table and to corrector
5300 * so corrections can apply for aliases as well.
5302 util_htset(parser->aliases, var->name, find);
5305 * add to corrector so corrections can work
5306 * even for aliases too.
5309 vec_last(parser->correct_variables),
5310 &vec_last(parser->correct_variables_score),
5314 /* generate aliases for vector components */
5318 util_asprintf(&buffer[0], "%s_x", var->desc);
5319 util_asprintf(&buffer[1], "%s_y", var->desc);
5320 util_asprintf(&buffer[2], "%s_z", var->desc);
5322 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5323 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5324 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5331 * add to corrector so corrections can work
5332 * even for aliases too.
5335 vec_last(parser->correct_variables),
5336 &vec_last(parser->correct_variables_score),
5340 vec_last(parser->correct_variables),
5341 &vec_last(parser->correct_variables_score),
5345 vec_last(parser->correct_variables),
5346 &vec_last(parser->correct_variables_score),
5354 /* a static adds itself to be generated like any other global
5355 * but is added to the local namespace instead
5357 char *defname = NULL;
5358 size_t prefix_len, ln;
5360 ln = strlen(parser->function->name);
5361 vec_append(defname, ln, parser->function->name);
5363 vec_append(defname, 2, "::");
5364 /* remember the length up to here */
5365 prefix_len = vec_size(defname);
5367 /* Add it to the local scope */
5368 util_htset(vec_last(parser->variables), var->name, (void*)var);
5372 vec_last(parser->correct_variables),
5373 &vec_last(parser->correct_variables_score),
5377 /* now rename the global */
5378 ln = strlen(var->name);
5379 vec_append(defname, ln, var->name);
5380 ast_value_set_name(var, defname);
5382 /* push it to the to-be-generated globals */
5383 vec_push(parser->globals, (ast_expression*)var);
5385 /* same game for the vector members */
5387 for (i = 0; i < 3; ++i) {
5388 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5392 vec_last(parser->correct_variables),
5393 &vec_last(parser->correct_variables_score),
5397 vec_shrinkto(defname, prefix_len);
5398 ln = strlen(me[i]->name);
5399 vec_append(defname, ln, me[i]->name);
5400 ast_member_set_name(me[i], defname);
5402 vec_push(parser->globals, (ast_expression*)me[i]);
5407 vec_push(localblock->locals, var);
5408 parser_addlocal(parser, var->name, (ast_expression*)var);
5410 for (i = 0; i < 3; ++i) {
5411 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5412 ast_block_collect(localblock, (ast_expression*)me[i]);
5418 me[0] = me[1] = me[2] = NULL;
5423 if (var->expression.vtype == TYPE_ARRAY) {
5425 snprintf(name, sizeof(name), "%s##SET", var->name);
5426 if (!parser_create_array_setter(parser, var, name))
5428 snprintf(name, sizeof(name), "%s##GET", var->name);
5429 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5432 else if (!localblock && !nofields &&
5433 var->expression.vtype == TYPE_FIELD &&
5434 var->expression.next->expression.vtype == TYPE_ARRAY)
5437 ast_expression *telem;
5439 ast_value *array = (ast_value*)var->expression.next;
5441 if (!ast_istype(var->expression.next, ast_value)) {
5442 parseerror(parser, "internal error: field element type must be an ast_value");
5446 snprintf(name, sizeof(name), "%s##SETF", var->name);
5447 if (!parser_create_array_field_setter(parser, array, name))
5450 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5451 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5452 tfield->expression.next = telem;
5453 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5454 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5462 if (parser->tok == ';') {
5463 ast_delete(basetype);
5464 if (!parser_next(parser)) {
5465 parseerror(parser, "error after variable declaration");
5471 if (parser->tok == ',')
5475 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5478 parseerror(parser, "missing comma or semicolon while parsing variables");
5482 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5483 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5484 "initializing expression turns variable `%s` into a constant in this standard",
5491 if (parser->tok != '{') {
5492 if (parser->tok != '=') {
5493 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5497 if (!parser_next(parser)) {
5498 parseerror(parser, "error parsing initializer");
5502 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5503 parseerror(parser, "expected '=' before function body in this standard");
5506 if (parser->tok == '#') {
5507 ast_function *func = NULL;
5510 parseerror(parser, "cannot declare builtins within functions");
5513 if (var->expression.vtype != TYPE_FUNCTION) {
5514 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5517 if (!parser_next(parser)) {
5518 parseerror(parser, "expected builtin number");
5521 if (parser->tok != TOKEN_INTCONST) {
5522 parseerror(parser, "builtin number must be an integer constant");
5525 if (parser_token(parser)->constval.i < 0) {
5526 parseerror(parser, "builtin number must be an integer greater than zero");
5530 if (var->hasvalue) {
5531 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5532 "builtin `%s` has already been defined\n"
5533 " -> previous declaration here: %s:%i",
5534 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5538 func = ast_function_new(ast_ctx(var), var->name, var);
5540 parseerror(parser, "failed to allocate function for `%s`", var->name);
5543 vec_push(parser->functions, func);
5545 func->builtin = -parser_token(parser)->constval.i-1;
5548 if (!parser_next(parser)) {
5549 parseerror(parser, "expected comma or semicolon");
5551 ast_function_delete(func);
5552 var->constval.vfunc = NULL;
5556 else if (parser->tok == '{' || parser->tok == '[')
5559 parseerror(parser, "cannot declare functions within functions");
5564 ast_ctx(proto) = parser_ctx(parser);
5566 if (!parse_function_body(parser, var))
5568 ast_delete(basetype);
5569 for (i = 0; i < vec_size(parser->gotos); ++i)
5570 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5571 vec_free(parser->gotos);
5572 vec_free(parser->labels);
5575 ast_expression *cexp;
5578 cexp = parse_expression_leave(parser, true, false, false);
5583 cval = (ast_value*)cexp;
5584 if (cval != parser->nil &&
5585 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5588 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5592 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5593 qualifier != CV_VAR)
5595 var->cvq = CV_CONST;
5597 if (cval == parser->nil)
5598 var->expression.flags |= AST_FLAG_INITIALIZED;
5601 var->hasvalue = true;
5602 if (cval->expression.vtype == TYPE_STRING)
5603 var->constval.vstring = parser_strdup(cval->constval.vstring);
5604 else if (cval->expression.vtype == TYPE_FIELD)
5605 var->constval.vfield = cval;
5607 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5613 shunt sy = { NULL, NULL, NULL, NULL };
5616 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5617 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5618 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5619 if (!parser_sy_apply_operator(parser, &sy))
5622 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5623 parseerror(parser, "internal error: leaked operands");
5624 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5634 if (parser->tok == ',') {
5635 if (!parser_next(parser)) {
5636 parseerror(parser, "expected another variable");
5640 if (parser->tok != TOKEN_IDENT) {
5641 parseerror(parser, "expected another variable");
5644 var = ast_value_copy(basetype);
5646 ast_value_set_name(var, parser_tokval(parser));
5647 if (!parser_next(parser)) {
5648 parseerror(parser, "error parsing variable declaration");
5654 if (parser->tok != ';') {
5655 parseerror(parser, "missing semicolon after variables");
5659 if (!parser_next(parser)) {
5660 parseerror(parser, "parse error after variable declaration");
5664 ast_delete(basetype);
5668 if (cleanvar && var)
5670 ast_delete(basetype);
5674 ast_delete(basetype);
5675 if (cleanvar && var)
5677 if (me[0]) ast_member_delete(me[0]);
5678 if (me[1]) ast_member_delete(me[1]);
5679 if (me[2]) ast_member_delete(me[2]);
5683 static bool parser_global_statement(parser_t *parser)
5687 bool is_static = false;
5688 uint32_t qflags = 0;
5689 ast_value *istype = NULL;
5690 char *vstring = NULL;
5692 if (parser->tok == TOKEN_IDENT)
5693 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5695 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5697 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5699 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5701 if (cvq == CV_WRONG)
5703 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5705 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5707 return parse_enum(parser);
5709 else if (parser->tok == TOKEN_KEYWORD)
5711 if (!strcmp(parser_tokval(parser), "typedef")) {
5712 if (!parser_next(parser)) {
5713 parseerror(parser, "expected type definition after 'typedef'");
5716 return parse_typedef(parser);
5718 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5721 else if (parser->tok == '#')
5723 return parse_pragma(parser);
5725 else if (parser->tok == '$')
5727 if (!parser_next(parser)) {
5728 parseerror(parser, "parse error");
5734 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5740 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5742 return util_crc16(old, str, strlen(str));
5745 static void progdefs_crc_file(const char *str)
5747 /* write to progdefs.h here */
5751 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5753 old = progdefs_crc_sum(old, str);
5754 progdefs_crc_file(str);
5758 static void generate_checksum(parser_t *parser)
5760 uint16_t crc = 0xFFFF;
5764 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5765 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5767 progdefs_crc_file("\tint\tpad;\n");
5768 progdefs_crc_file("\tint\tofs_return[3];\n");
5769 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5770 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5771 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5772 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5773 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5774 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5775 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5776 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5778 for (i = 0; i < parser->crc_globals; ++i) {
5779 if (!ast_istype(parser->globals[i], ast_value))
5781 value = (ast_value*)(parser->globals[i]);
5782 switch (value->expression.vtype) {
5783 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5784 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5785 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5786 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5788 crc = progdefs_crc_both(crc, "\tint\t");
5791 crc = progdefs_crc_both(crc, value->name);
5792 crc = progdefs_crc_both(crc, ";\n");
5794 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5795 for (i = 0; i < parser->crc_fields; ++i) {
5796 if (!ast_istype(parser->fields[i], ast_value))
5798 value = (ast_value*)(parser->fields[i]);
5799 switch (value->expression.next->expression.vtype) {
5800 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5801 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5802 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5803 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5805 crc = progdefs_crc_both(crc, "\tint\t");
5808 crc = progdefs_crc_both(crc, value->name);
5809 crc = progdefs_crc_both(crc, ";\n");
5811 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5816 static parser_t *parser;
5823 parser = (parser_t*)mem_a(sizeof(parser_t));
5827 memset(parser, 0, sizeof(*parser));
5829 for (i = 0; i < operator_count; ++i) {
5830 if (operators[i].id == opid1('=')) {
5831 parser->assign_op = operators+i;
5835 if (!parser->assign_op) {
5836 printf("internal error: initializing parser: failed to find assign operator\n");
5841 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5842 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5843 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5844 vec_push(parser->_blocktypedefs, 0);
5846 parser->aliases = util_htnew(PARSER_HT_SIZE);
5849 vec_push(parser->correct_variables, correct_trie_new());
5850 vec_push(parser->correct_variables_score, NULL);
5852 empty_ctx.file = "<internal>";
5854 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5855 parser->nil->cvq = CV_CONST;
5856 if (OPTS_FLAG(UNTYPED_NIL))
5857 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5859 parser->max_param_count = 1;
5861 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5862 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5863 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5865 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5866 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5867 parser->reserved_version->cvq = CV_CONST;
5868 parser->reserved_version->hasvalue = true;
5869 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5870 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5872 parser->reserved_version = NULL;
5877 bool parser_compile()
5879 /* initial lexer/parser state */
5880 parser->lex->flags.noops = true;
5882 if (parser_next(parser))
5884 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5886 if (!parser_global_statement(parser)) {
5887 if (parser->tok == TOKEN_EOF)
5888 parseerror(parser, "unexpected eof");
5889 else if (compile_errors)
5890 parseerror(parser, "there have been errors, bailing out");
5891 lex_close(parser->lex);
5897 parseerror(parser, "parse error");
5898 lex_close(parser->lex);
5903 lex_close(parser->lex);
5906 return !compile_errors;
5909 bool parser_compile_file(const char *filename)
5911 parser->lex = lex_open(filename);
5913 con_err("failed to open file \"%s\"\n", filename);
5916 return parser_compile();
5919 bool parser_compile_string(const char *name, const char *str, size_t len)
5921 parser->lex = lex_open_string(str, len, name);
5923 con_err("failed to create lexer for string \"%s\"\n", name);
5926 return parser_compile();
5929 void parser_cleanup()
5932 for (i = 0; i < vec_size(parser->accessors); ++i) {
5933 ast_delete(parser->accessors[i]->constval.vfunc);
5934 parser->accessors[i]->constval.vfunc = NULL;
5935 ast_delete(parser->accessors[i]);
5937 for (i = 0; i < vec_size(parser->functions); ++i) {
5938 ast_delete(parser->functions[i]);
5940 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5941 ast_delete(parser->imm_vector[i]);
5943 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5944 ast_delete(parser->imm_string[i]);
5946 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5947 ast_delete(parser->imm_float[i]);
5949 for (i = 0; i < vec_size(parser->fields); ++i) {
5950 ast_delete(parser->fields[i]);
5952 for (i = 0; i < vec_size(parser->globals); ++i) {
5953 ast_delete(parser->globals[i]);
5955 vec_free(parser->accessors);
5956 vec_free(parser->functions);
5957 vec_free(parser->imm_vector);
5958 vec_free(parser->imm_string);
5959 vec_free(parser->imm_float);
5960 vec_free(parser->globals);
5961 vec_free(parser->fields);
5963 for (i = 0; i < vec_size(parser->variables); ++i)
5964 util_htdel(parser->variables[i]);
5965 vec_free(parser->variables);
5966 vec_free(parser->_blocklocals);
5967 vec_free(parser->_locals);
5970 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5971 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5973 vec_free(parser->correct_variables);
5974 vec_free(parser->correct_variables_score);
5977 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5978 ast_delete(parser->_typedefs[i]);
5979 vec_free(parser->_typedefs);
5980 for (i = 0; i < vec_size(parser->typedefs); ++i)
5981 util_htdel(parser->typedefs[i]);
5982 vec_free(parser->typedefs);
5983 vec_free(parser->_blocktypedefs);
5985 vec_free(parser->_block_ctx);
5987 vec_free(parser->labels);
5988 vec_free(parser->gotos);
5989 vec_free(parser->breaks);
5990 vec_free(parser->continues);
5992 ast_value_delete(parser->nil);
5994 ast_value_delete(parser->const_vec[0]);
5995 ast_value_delete(parser->const_vec[1]);
5996 ast_value_delete(parser->const_vec[2]);
5998 util_htdel(parser->aliases);
6003 bool parser_finish(const char *output)
6009 if (compile_errors) {
6010 con_out("*** there were compile errors\n");
6014 ir = ir_builder_new("gmqcc_out");
6016 con_out("failed to allocate builder\n");
6020 for (i = 0; i < vec_size(parser->fields); ++i) {
6023 if (!ast_istype(parser->fields[i], ast_value))
6025 field = (ast_value*)parser->fields[i];
6026 hasvalue = field->hasvalue;
6027 field->hasvalue = false;
6028 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6029 con_out("failed to generate field %s\n", field->name);
6030 ir_builder_delete(ir);
6035 ast_expression *subtype;
6036 field->hasvalue = true;
6037 subtype = field->expression.next;
6038 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6039 if (subtype->expression.vtype == TYPE_FIELD)
6040 ifld->fieldtype = subtype->expression.next->expression.vtype;
6041 else if (subtype->expression.vtype == TYPE_FUNCTION)
6042 ifld->outtype = subtype->expression.next->expression.vtype;
6043 (void)!ir_value_set_field(field->ir_v, ifld);
6046 for (i = 0; i < vec_size(parser->globals); ++i) {
6048 if (!ast_istype(parser->globals[i], ast_value))
6050 asvalue = (ast_value*)(parser->globals[i]);
6051 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6052 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6053 "unused global: `%s`", asvalue->name);
6055 if (!ast_global_codegen(asvalue, ir, false)) {
6056 con_out("failed to generate global %s\n", asvalue->name);
6057 ir_builder_delete(ir);
6061 /* Build function vararg accessor ast tree now before generating
6062 * immediates, because the accessors may add new immediates
6064 for (i = 0; i < vec_size(parser->functions); ++i) {
6065 ast_function *f = parser->functions[i];
6067 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6068 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6069 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6070 con_out("failed to generate vararg setter for %s\n", f->name);
6071 ir_builder_delete(ir);
6074 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6075 con_out("failed to generate vararg getter for %s\n", f->name);
6076 ir_builder_delete(ir);
6080 ast_delete(f->varargs);
6085 /* Now we can generate immediates */
6086 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6087 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6088 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6089 ir_builder_delete(ir);
6093 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6094 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6095 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6096 ir_builder_delete(ir);
6100 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6101 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6102 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6103 ir_builder_delete(ir);
6107 for (i = 0; i < vec_size(parser->globals); ++i) {
6109 if (!ast_istype(parser->globals[i], ast_value))
6111 asvalue = (ast_value*)(parser->globals[i]);
6112 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6114 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6115 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6116 "uninitialized constant: `%s`",
6118 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6119 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6120 "uninitialized global: `%s`",
6123 if (!ast_generate_accessors(asvalue, ir)) {
6124 ir_builder_delete(ir);
6128 for (i = 0; i < vec_size(parser->fields); ++i) {
6130 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6132 if (!ast_istype((ast_expression*)asvalue, ast_value))
6134 if (asvalue->expression.vtype != TYPE_ARRAY)
6136 if (!ast_generate_accessors(asvalue, ir)) {
6137 ir_builder_delete(ir);
6141 if (parser->reserved_version &&
6142 !ast_global_codegen(parser->reserved_version, ir, false))
6144 con_out("failed to generate reserved::version");
6145 ir_builder_delete(ir);
6148 for (i = 0; i < vec_size(parser->functions); ++i) {
6149 ast_function *f = parser->functions[i];
6150 if (!ast_function_codegen(f, ir)) {
6151 con_out("failed to generate function %s\n", f->name);
6152 ir_builder_delete(ir);
6156 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6157 ir_builder_dump(ir, con_out);
6158 for (i = 0; i < vec_size(parser->functions); ++i) {
6159 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6160 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6161 ir_builder_delete(ir);
6166 if (compile_Werrors) {
6167 con_out("*** there were warnings treated as errors\n");
6168 compile_show_werrors();
6173 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6174 ir_builder_dump(ir, con_out);
6176 generate_checksum(parser);
6178 if (!ir_builder_generate(ir, output)) {
6179 con_out("*** failed to generate output file\n");
6180 ir_builder_delete(ir);
6185 ir_builder_delete(ir);