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
32 /* beginning of locals */
33 #define PARSER_HT_LOCALS 2
35 #define PARSER_HT_SIZE 128
36 #define TYPEDEF_HT_SIZE 16
38 typedef struct parser_s {
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
52 /* must be deleted first, they reference immediates and values */
53 ast_value **accessors;
55 ast_value *imm_float_zero;
56 ast_value *imm_float_one;
57 ast_value *imm_float_neg_one;
59 ast_value *imm_vector_zero;
62 ast_value *reserved_version;
67 ast_function *function;
70 /* All the labels the function defined...
71 * Should they be in ast_function instead?
76 const char **continues;
78 /* A list of hashtables for each scope */
84 /* same as above but for the spelling corrector */
85 correct_trie_t **correct_variables;
86 size_t ***correct_variables_score; /* vector of vector of size_t* */
88 /* not to be used directly, we use the hash table */
89 ast_expression **_locals;
91 ast_value **_typedefs;
92 size_t *_blocktypedefs;
95 /* we store the '=' operator info */
96 const oper_info *assign_op;
99 ast_value *const_vec[3];
104 /* collected information */
105 size_t max_param_count;
111 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
113 static void parser_enterblock(parser_t *parser);
114 static bool parser_leaveblock(parser_t *parser);
115 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
116 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
117 static bool parse_typedef(parser_t *parser);
118 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);
119 static ast_block* parse_block(parser_t *parser);
120 static bool parse_block_into(parser_t *parser, ast_block *block);
121 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
122 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
123 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
124 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
125 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
126 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
127 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
129 static void parseerror(parser_t *parser, const char *fmt, ...)
133 vcompile_error(parser->lex->tok.ctx, fmt, ap);
137 /* returns true if it counts as an error */
138 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
143 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
148 /**********************************************************************
149 * some maths used for constant folding
152 vector vec3_add(vector a, vector b)
161 vector vec3_sub(vector a, vector b)
170 qcfloat vec3_mulvv(vector a, vector b)
172 return (a.x * b.x + a.y * b.y + a.z * b.z);
175 vector vec3_mulvf(vector a, float b)
184 /**********************************************************************
188 bool parser_next(parser_t *parser)
190 /* lex_do kills the previous token */
191 parser->tok = lex_do(parser->lex);
192 if (parser->tok == TOKEN_EOF)
194 if (parser->tok >= TOKEN_ERROR) {
195 parseerror(parser, "lex error");
201 #define parser_tokval(p) ((p)->lex->tok.value)
202 #define parser_token(p) (&((p)->lex->tok))
203 #define parser_ctx(p) ((p)->lex->tok.ctx)
205 static ast_value* parser_const_float(parser_t *parser, double d)
210 for (i = 0; i < vec_size(parser->imm_float); ++i) {
211 const double compare = parser->imm_float[i]->constval.vfloat;
212 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
213 return parser->imm_float[i];
216 ctx = parser_ctx(parser);
218 memset(&ctx, 0, sizeof(ctx));
220 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
222 out->hasvalue = true;
224 out->constval.vfloat = d;
225 vec_push(parser->imm_float, out);
229 static ast_value* parser_const_float_0(parser_t *parser)
231 if (!parser->imm_float_zero)
232 parser->imm_float_zero = parser_const_float(parser, 0);
233 return parser->imm_float_zero;
236 static ast_value* parser_const_float_neg1(parser_t *parser) {
237 if (!parser->imm_float_neg_one)
238 parser->imm_float_neg_one = parser_const_float(parser, -1);
239 return parser->imm_float_neg_one;
242 static ast_value* parser_const_float_1(parser_t *parser)
244 if (!parser->imm_float_one)
245 parser->imm_float_one = parser_const_float(parser, 1);
246 return parser->imm_float_one;
249 static char *parser_strdup(const char *str)
252 /* actually dup empty strings */
253 char *out = (char*)mem_a(1);
257 return util_strdup(str);
260 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
262 size_t hash = util_hthash(parser->ht_imm_string, str);
264 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
265 if (dotranslate && out->name[0] == '#') {
267 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
268 ast_value_set_name(out, name);
273 for (i = 0; i < vec_size(parser->imm_string); ++i) {
274 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
275 return parser->imm_string[i];
280 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
281 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
283 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
285 out->hasvalue = true;
287 out->constval.vstring = parser_strdup(str);
288 vec_push(parser->imm_string, out);
289 util_htseth(parser->ht_imm_string, str, hash, out);
293 static ast_value* parser_const_vector(parser_t *parser, vector v)
297 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
298 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
299 return parser->imm_vector[i];
301 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
303 out->hasvalue = true;
305 out->constval.vvec = v;
306 vec_push(parser->imm_vector, out);
310 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
316 return parser_const_vector(parser, v);
319 static ast_value* parser_const_vector_0(parser_t *parser)
321 if (!parser->imm_vector_zero)
322 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
323 return parser->imm_vector_zero;
326 static ast_expression* parser_find_field(parser_t *parser, const char *name)
328 return ( ast_expression*)util_htget(parser->htfields, name);
331 static ast_expression* parser_find_label(parser_t *parser, const char *name)
334 for(i = 0; i < vec_size(parser->labels); i++)
335 if (!strcmp(parser->labels[i]->name, name))
336 return (ast_expression*)parser->labels[i];
340 static ast_expression* parser_find_global(parser_t *parser, const char *name)
342 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
345 return (ast_expression*)util_htget(parser->htglobals, name);
348 static ast_expression* parser_find_param(parser_t *parser, const char *name)
352 if (!parser->function)
354 fun = parser->function->vtype;
355 for (i = 0; i < vec_size(fun->expression.params); ++i) {
356 if (!strcmp(fun->expression.params[i]->name, name))
357 return (ast_expression*)(fun->expression.params[i]);
362 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
367 hash = util_hthash(parser->htglobals, name);
370 for (i = vec_size(parser->variables); i > upto;) {
372 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
376 return parser_find_param(parser, name);
379 static ast_expression* parser_find_var(parser_t *parser, const char *name)
383 v = parser_find_local(parser, name, 0, &dummy);
384 if (!v) v = parser_find_global(parser, name);
388 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
392 hash = util_hthash(parser->typedefs[0], name);
394 for (i = vec_size(parser->typedefs); i > upto;) {
396 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
402 /* include intrinsics */
407 size_t etype; /* 0 = expression, others are operators */
411 ast_block *block; /* for commas and function calls */
430 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
441 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
445 e.out = (ast_expression*)v;
452 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
454 e.etype = 1 + (op - operators);
463 static sy_elem syparen(lex_ctx ctx, size_t off) {
474 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
475 * so we need to rotate it to become ent.(foo[n]).
477 static bool rotate_entfield_array_index_nodes(ast_expression **out)
479 ast_array_index *index, *oldindex;
480 ast_entfield *entfield;
484 ast_expression *entity;
486 lex_ctx ctx = ast_ctx(*out);
488 if (!ast_istype(*out, ast_array_index))
490 index = (ast_array_index*)*out;
492 if (!ast_istype(index->array, ast_entfield))
494 entfield = (ast_entfield*)index->array;
496 if (!ast_istype(entfield->field, ast_value))
498 field = (ast_value*)entfield->field;
501 entity = entfield->entity;
505 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
506 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
507 *out = (ast_expression*)entfield;
509 oldindex->array = NULL;
510 oldindex->index = NULL;
511 ast_delete(oldindex);
516 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
518 switch (v->expression.vtype) {
520 return !!v->constval.vfloat;
522 return !!v->constval.vint;
524 if (OPTS_FLAG(CORRECT_LOGIC))
525 return v->constval.vvec.x &&
526 v->constval.vvec.y &&
529 return !!(v->constval.vvec.x);
531 if (!v->constval.vstring)
533 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
535 return !!v->constval.vstring[0];
537 compile_error(ctx, "internal error: immediate_is_true on invalid type");
538 return !!v->constval.vfunc;
542 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
546 ast_expression *out = NULL;
547 ast_expression *exprs[3];
548 ast_block *blocks[3];
549 ast_value *asvalue[3];
550 ast_binstore *asbinstore;
551 size_t i, assignop, addop, subop;
552 qcint generated_op = 0;
557 if (!vec_size(sy->ops)) {
558 parseerror(parser, "internal error: missing operator");
562 if (vec_last(sy->ops).isparen) {
563 parseerror(parser, "unmatched parenthesis");
567 op = &operators[vec_last(sy->ops).etype - 1];
568 ctx = vec_last(sy->ops).ctx;
570 if (vec_size(sy->out) < op->operands) {
571 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
572 op->op, (int)op->id);
576 vec_shrinkby(sy->ops, 1);
578 /* op(:?) has no input and no output */
582 vec_shrinkby(sy->out, op->operands);
583 for (i = 0; i < op->operands; ++i) {
584 exprs[i] = sy->out[vec_size(sy->out)+i].out;
585 blocks[i] = sy->out[vec_size(sy->out)+i].block;
586 asvalue[i] = (ast_value*)exprs[i];
588 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
589 !(i != 0 && op->id == opid2('?',':')) &&
590 !(i == 1 && op->id == opid1('.')))
592 if (ast_istype(exprs[i], ast_label))
593 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
595 compile_error(ast_ctx(exprs[i]), "not an expression");
596 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
600 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
601 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
605 #define NotSameType(T) \
606 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
607 exprs[0]->expression.vtype != T)
608 #define CanConstFold1(A) \
609 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
610 (A)->expression.vtype != TYPE_FUNCTION)
611 #define CanConstFold(A, B) \
612 (CanConstFold1(A) && CanConstFold1(B))
613 #define ConstV(i) (asvalue[(i)]->constval.vvec)
614 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
615 #define ConstS(i) (asvalue[(i)]->constval.vstring)
619 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
623 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
624 exprs[1]->expression.vtype == TYPE_NOEXPR)
626 if (exprs[1] == (ast_expression*)parser->const_vec[0])
627 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
628 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
629 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
630 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
631 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
633 compile_error(ctx, "access to invalid vector component");
637 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
638 if (exprs[1]->expression.vtype != TYPE_FIELD) {
639 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
642 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
644 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
645 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
649 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
655 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
656 !(exprs[0]->expression.vtype == TYPE_FIELD &&
657 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
659 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
660 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
663 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
664 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
665 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
668 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
669 if (rotate_entfield_array_index_nodes(&out))
672 /* This is not broken in fteqcc anymore */
673 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
674 /* this error doesn't need to make us bail out */
675 (void)!parsewarning(parser, WARN_EXTENSIONS,
676 "accessing array-field members of an entity without parenthesis\n"
677 " -> this is an extension from -std=gmqcc");
684 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
685 vec_push(sy->out, syexp(ctx, exprs[0]));
686 vec_push(sy->out, syexp(ctx, exprs[1]));
687 vec_last(sy->argc)++;
691 if (!ast_block_add_expr(blocks[0], exprs[1]))
694 blocks[0] = ast_block_new(ctx);
695 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
696 !ast_block_add_expr(blocks[0], exprs[1]))
701 ast_block_set_type(blocks[0], exprs[1]);
703 vec_push(sy->out, syblock(ctx, blocks[0]));
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_binary_new(ctx, INSTR_SUB_F,
716 (ast_expression*)parser_const_float_0(parser),
720 if (CanConstFold1(exprs[0]))
721 out = (ast_expression*)parser_const_vector_f(parser,
722 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
725 (ast_expression*)parser_const_vector_0(parser),
729 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
730 type_name[exprs[0]->expression.vtype]);
736 switch (exprs[0]->expression.vtype) {
738 if (CanConstFold1(exprs[0]))
739 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
741 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
744 if (CanConstFold1(exprs[0]))
745 out = (ast_expression*)parser_const_float(parser,
746 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
748 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
751 if (CanConstFold1(exprs[0])) {
752 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
753 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
755 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
757 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
758 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
760 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
763 /* we don't constant-fold NOT for these types */
765 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
768 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
771 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
772 type_name[exprs[0]->expression.vtype]);
778 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
779 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
781 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
782 type_name[exprs[0]->expression.vtype],
783 type_name[exprs[1]->expression.vtype]);
786 switch (exprs[0]->expression.vtype) {
788 if (CanConstFold(exprs[0], exprs[1]))
790 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
793 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
799 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
802 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
803 type_name[exprs[0]->expression.vtype],
804 type_name[exprs[1]->expression.vtype]);
809 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
810 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
812 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
813 type_name[exprs[1]->expression.vtype],
814 type_name[exprs[0]->expression.vtype]);
817 switch (exprs[0]->expression.vtype) {
819 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
825 if (CanConstFold(exprs[0], exprs[1]))
826 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
828 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
831 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
832 type_name[exprs[1]->expression.vtype],
833 type_name[exprs[0]->expression.vtype]);
838 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
839 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
840 exprs[1]->expression.vtype == TYPE_FLOAT) &&
841 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
842 exprs[0]->expression.vtype == TYPE_FLOAT)
845 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
846 type_name[exprs[1]->expression.vtype],
847 type_name[exprs[0]->expression.vtype]);
850 switch (exprs[0]->expression.vtype) {
852 if (exprs[1]->expression.vtype == TYPE_VECTOR)
854 if (CanConstFold(exprs[0], exprs[1]))
855 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
857 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
861 if (CanConstFold(exprs[0], exprs[1]))
862 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
864 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
868 if (exprs[1]->expression.vtype == TYPE_FLOAT)
870 if (CanConstFold(exprs[0], exprs[1]))
871 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
873 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
877 if (CanConstFold(exprs[0], exprs[1]))
878 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
879 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
880 vector vec = ConstV(0);
881 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
882 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
883 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
884 out->expression.node.keep = false;
885 ((ast_member*)out)->rvalue = true;
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
889 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
890 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
891 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
892 out->expression.node.keep = false;
893 ((ast_member*)out)->rvalue = true;
895 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
897 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
898 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
899 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
900 out->expression.node.keep = false;
901 ((ast_member*)out)->rvalue = true;
903 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
908 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
909 vector vec = ConstV(1);
910 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
911 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
912 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
913 out->expression.node.keep = false;
914 ((ast_member*)out)->rvalue = true;
916 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
918 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
919 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
920 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
921 out->expression.node.keep = false;
922 ((ast_member*)out)->rvalue = true;
924 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
926 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
927 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
928 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
929 out->expression.node.keep = false;
930 ((ast_member*)out)->rvalue = true;
932 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
935 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
938 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
942 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
943 type_name[exprs[1]->expression.vtype],
944 type_name[exprs[0]->expression.vtype]);
949 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
950 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
951 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
952 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
955 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
956 if (CanConstFold(exprs[0], exprs[1]))
957 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
959 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
961 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
962 if (CanConstFold(exprs[0], exprs[1]))
963 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
965 if (CanConstFold1(exprs[1])) {
966 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
968 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
969 (ast_expression*)parser_const_float_1(parser),
973 compile_error(ctx, "internal error: failed to generate division");
976 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
981 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
982 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
983 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
989 if (NotSameType(TYPE_FLOAT)) {
990 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
991 type_name[exprs[0]->expression.vtype],
992 type_name[exprs[1]->expression.vtype]);
995 if (CanConstFold(exprs[0], exprs[1])) {
996 out = (ast_expression*)parser_const_float(parser,
997 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
999 /* generate a call to __builtin_mod */
1000 ast_expression *mod = intrin_func(parser, "mod");
1001 ast_call *call = NULL;
1002 if (!mod) return false; /* can return null for missing floor */
1004 call = ast_call_new(parser_ctx(parser), mod);
1005 vec_push(call->params, exprs[0]);
1006 vec_push(call->params, exprs[1]);
1008 out = (ast_expression*)call;
1012 case opid2('%','='):
1013 compile_error(ctx, "%= is unimplemented");
1018 if (NotSameType(TYPE_FLOAT)) {
1019 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1020 type_name[exprs[0]->expression.vtype],
1021 type_name[exprs[1]->expression.vtype]);
1024 if (CanConstFold(exprs[0], exprs[1]))
1025 out = (ast_expression*)parser_const_float(parser,
1026 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1027 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1029 out = (ast_expression*)ast_binary_new(ctx,
1030 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1031 exprs[0], exprs[1]);
1034 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1037 case opid2('<','<'):
1038 case opid2('>','>'):
1039 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1040 if (op->id == opid2('<','<'))
1041 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1043 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1046 case opid3('<','<','='):
1047 case opid3('>','>','='):
1048 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1051 case opid2('|','|'):
1052 generated_op += 1; /* INSTR_OR */
1053 case opid2('&','&'):
1054 generated_op += INSTR_AND;
1055 if (CanConstFold(exprs[0], exprs[1]))
1057 if (OPTS_FLAG(PERL_LOGIC)) {
1058 if (immediate_is_true(ctx, asvalue[0]))
1062 out = (ast_expression*)parser_const_float(parser,
1063 ( (generated_op == INSTR_OR)
1064 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1065 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1070 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1071 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1072 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1073 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1076 for (i = 0; i < 2; ++i) {
1077 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1078 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1080 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1082 exprs[i] = out; out = NULL;
1083 if (OPTS_FLAG(PERL_LOGIC)) {
1084 /* here we want to keep the right expressions' type */
1088 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1089 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1091 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1093 exprs[i] = out; out = NULL;
1094 if (OPTS_FLAG(PERL_LOGIC)) {
1095 /* here we want to keep the right expressions' type */
1100 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1104 case opid2('?',':'):
1105 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1106 compile_error(ctx, "mismatched parenthesis/ternary");
1110 if (!ast_compare_type(exprs[1], exprs[2])) {
1111 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1112 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1113 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1116 if (CanConstFold1(exprs[0]))
1117 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1119 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1122 case opid2('*', '*'):
1123 if (NotSameType(TYPE_FLOAT)) {
1124 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1125 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1126 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1132 if (CanConstFold(exprs[0], exprs[1])) {
1133 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1135 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1136 vec_push(gencall->params, exprs[0]);
1137 vec_push(gencall->params, exprs[1]);
1138 out = (ast_expression*)gencall;
1142 case opid3('<','=','>'): /* -1, 0, or 1 */
1143 if (NotSameType(TYPE_FLOAT)) {
1144 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1145 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1146 compile_error(ctx, "invalid types used in comparision: %s and %s",
1152 if (CanConstFold(exprs[0], exprs[1])) {
1153 if (ConstF(0) < ConstF(1))
1154 out = (ast_expression*)parser_const_float_neg1(parser);
1155 else if (ConstF(0) == ConstF(1))
1156 out = (ast_expression*)parser_const_float_0(parser);
1157 else if (ConstF(0) > ConstF(1))
1158 out = (ast_expression*)parser_const_float_1(parser);
1160 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1162 eq->refs = (ast_binary_ref)false; /* references nothing */
1165 out = (ast_expression*)ast_ternary_new(ctx,
1166 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1168 (ast_expression*)parser_const_float_neg1(parser),
1171 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1173 (ast_expression*)parser_const_float_0(parser),
1176 (ast_expression*)parser_const_float_1(parser)
1186 generated_op += 1; /* INSTR_GT */
1188 generated_op += 1; /* INSTR_LT */
1189 case opid2('>', '='):
1190 generated_op += 1; /* INSTR_GE */
1191 case opid2('<', '='):
1192 generated_op += INSTR_LE;
1193 if (NotSameType(TYPE_FLOAT)) {
1194 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1195 type_name[exprs[0]->expression.vtype],
1196 type_name[exprs[1]->expression.vtype]);
1199 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1201 case opid2('!', '='):
1202 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1203 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1204 type_name[exprs[0]->expression.vtype],
1205 type_name[exprs[1]->expression.vtype]);
1208 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1210 case opid2('=', '='):
1211 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1212 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1213 type_name[exprs[0]->expression.vtype],
1214 type_name[exprs[1]->expression.vtype]);
1217 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1221 if (ast_istype(exprs[0], ast_entfield)) {
1222 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1223 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1224 exprs[0]->expression.vtype == TYPE_FIELD &&
1225 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1227 assignop = type_storep_instr[TYPE_VECTOR];
1230 assignop = type_storep_instr[exprs[0]->expression.vtype];
1231 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1233 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1234 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1235 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1236 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1237 exprs[1]->expression.vtype == TYPE_FUNCTION)
1239 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1240 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1243 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1248 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1249 exprs[0]->expression.vtype == TYPE_FIELD &&
1250 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1252 assignop = type_store_instr[TYPE_VECTOR];
1255 assignop = type_store_instr[exprs[0]->expression.vtype];
1258 if (assignop == VINSTR_END) {
1259 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1260 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1261 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1263 else if (!ast_compare_type(exprs[0], exprs[1]))
1265 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1266 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1267 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1268 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1269 exprs[1]->expression.vtype == TYPE_FUNCTION)
1271 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1272 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1275 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1278 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1279 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1281 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1283 case opid3('+','+','P'):
1284 case opid3('-','-','P'):
1286 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1287 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1288 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1291 if (op->id == opid3('+','+','P'))
1292 addop = INSTR_ADD_F;
1294 addop = INSTR_SUB_F;
1295 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1296 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1298 if (ast_istype(exprs[0], ast_entfield)) {
1299 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1301 (ast_expression*)parser_const_float_1(parser));
1303 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1305 (ast_expression*)parser_const_float_1(parser));
1308 case opid3('S','+','+'):
1309 case opid3('S','-','-'):
1311 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1312 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1313 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1316 if (op->id == opid3('S','+','+')) {
1317 addop = INSTR_ADD_F;
1318 subop = INSTR_SUB_F;
1320 addop = INSTR_SUB_F;
1321 subop = INSTR_ADD_F;
1323 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1324 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1326 if (ast_istype(exprs[0], ast_entfield)) {
1327 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1329 (ast_expression*)parser_const_float_1(parser));
1331 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1333 (ast_expression*)parser_const_float_1(parser));
1337 out = (ast_expression*)ast_binary_new(ctx, subop,
1339 (ast_expression*)parser_const_float_1(parser));
1341 case opid2('+','='):
1342 case opid2('-','='):
1343 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1344 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1346 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1347 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1348 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1352 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1353 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1355 if (ast_istype(exprs[0], ast_entfield))
1356 assignop = type_storep_instr[exprs[0]->expression.vtype];
1358 assignop = type_store_instr[exprs[0]->expression.vtype];
1359 switch (exprs[0]->expression.vtype) {
1361 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1362 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1363 exprs[0], exprs[1]);
1366 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1367 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1368 exprs[0], exprs[1]);
1371 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1372 type_name[exprs[0]->expression.vtype],
1373 type_name[exprs[1]->expression.vtype]);
1377 case opid2('*','='):
1378 case opid2('/','='):
1379 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1380 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1381 exprs[0]->expression.vtype == TYPE_VECTOR))
1383 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1384 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1385 compile_error(ctx, "invalid types used in expression: %s and %s",
1389 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1390 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1392 if (ast_istype(exprs[0], ast_entfield))
1393 assignop = type_storep_instr[exprs[0]->expression.vtype];
1395 assignop = type_store_instr[exprs[0]->expression.vtype];
1396 switch (exprs[0]->expression.vtype) {
1398 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1399 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1400 exprs[0], exprs[1]);
1403 if (op->id == opid2('*','=')) {
1404 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1405 exprs[0], exprs[1]);
1407 /* there's no DIV_VF */
1408 if (CanConstFold1(exprs[1])) {
1409 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1411 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1412 (ast_expression*)parser_const_float_1(parser),
1416 compile_error(ctx, "internal error: failed to generate division");
1419 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1424 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1425 type_name[exprs[0]->expression.vtype],
1426 type_name[exprs[1]->expression.vtype]);
1430 case opid2('&','='):
1431 case opid2('|','='):
1432 if (NotSameType(TYPE_FLOAT)) {
1433 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1434 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1435 compile_error(ctx, "invalid types used in expression: %s and %s",
1439 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1440 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1442 if (ast_istype(exprs[0], ast_entfield))
1443 assignop = type_storep_instr[exprs[0]->expression.vtype];
1445 assignop = type_store_instr[exprs[0]->expression.vtype];
1446 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1447 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1448 exprs[0], exprs[1]);
1450 case opid3('&','~','='):
1451 /* This is like: a &= ~(b);
1452 * But QC has no bitwise-not, so we implement it as
1455 if (NotSameType(TYPE_FLOAT)) {
1456 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1457 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1458 compile_error(ctx, "invalid types used in expression: %s and %s",
1462 if (ast_istype(exprs[0], ast_entfield))
1463 assignop = type_storep_instr[exprs[0]->expression.vtype];
1465 assignop = type_store_instr[exprs[0]->expression.vtype];
1466 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1469 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1470 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1472 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1473 asbinstore->keep_dest = true;
1474 out = (ast_expression*)asbinstore;
1477 case opid2('~', 'P'):
1478 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1479 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1480 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1484 if(CanConstFold1(exprs[0]))
1485 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1487 out = (ast_expression*)
1488 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1494 compile_error(ctx, "failed to apply operator %s", op->op);
1498 vec_push(sy->out, syexp(ctx, out));
1502 static bool parser_close_call(parser_t *parser, shunt *sy)
1504 /* was a function call */
1505 ast_expression *fun;
1506 ast_value *funval = NULL;
1510 size_t paramcount, i;
1512 fid = vec_last(sy->ops).off;
1513 vec_shrinkby(sy->ops, 1);
1515 /* out[fid] is the function
1516 * everything above is parameters...
1518 if (!vec_size(sy->argc)) {
1519 parseerror(parser, "internal error: no argument counter available");
1523 paramcount = vec_last(sy->argc);
1526 if (vec_size(sy->out) < fid) {
1527 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1528 (unsigned long)vec_size(sy->out),
1530 (unsigned long)paramcount);
1534 fun = sy->out[fid].out;
1536 if (fun == intrinsic_debug_typestring) {
1538 if (fid+2 != vec_size(sy->out) ||
1539 vec_last(sy->out).block)
1541 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1544 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1545 ast_unref(vec_last(sy->out).out);
1546 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1547 (ast_expression*)parser_const_string(parser, ty, false));
1548 vec_shrinkby(sy->out, 1);
1552 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1556 if (fid+1 < vec_size(sy->out))
1559 if (fid+1 + paramcount != vec_size(sy->out)) {
1560 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1561 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1565 for (i = 0; i < paramcount; ++i)
1566 vec_push(call->params, sy->out[fid+1 + i].out);
1567 vec_shrinkby(sy->out, paramcount);
1568 (void)!ast_call_check_types(call);
1569 if (parser->max_param_count < paramcount)
1570 parser->max_param_count = paramcount;
1572 if (ast_istype(fun, ast_value)) {
1573 funval = (ast_value*)fun;
1574 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1575 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1577 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1581 /* overwrite fid, the function, with a call */
1582 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1584 if (fun->expression.vtype != TYPE_FUNCTION) {
1585 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1589 if (!fun->expression.next) {
1590 parseerror(parser, "could not determine function return type");
1593 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1595 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1597 return !parsewarning(parser, WARN_DEPRECATED,
1598 "call to function (which is marked deprecated)\n",
1599 "-> it has been declared here: %s:%i",
1600 ast_ctx(fun).file, ast_ctx(fun).line);
1603 return !parsewarning(parser, WARN_DEPRECATED,
1604 "call to `%s` (which is marked deprecated)\n"
1605 "-> `%s` declared here: %s:%i",
1606 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1608 return !parsewarning(parser, WARN_DEPRECATED,
1609 "call to `%s` (deprecated: %s)\n"
1610 "-> `%s` declared here: %s:%i",
1611 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1615 if (vec_size(fun->expression.params) != paramcount &&
1616 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1617 vec_size(fun->expression.params) < paramcount))
1619 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1621 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1622 "too %s parameters for call to %s: expected %i, got %i\n"
1623 " -> `%s` has been declared here: %s:%i",
1624 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1625 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1627 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1628 "too %s parameters for function call: expected %i, got %i\n"
1629 " -> it has been declared here: %s:%i",
1630 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1631 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1638 static bool parser_close_paren(parser_t *parser, shunt *sy)
1640 if (!vec_size(sy->ops)) {
1641 parseerror(parser, "unmatched closing paren");
1645 while (vec_size(sy->ops)) {
1646 if (vec_last(sy->ops).isparen) {
1647 if (vec_last(sy->paren) == PAREN_FUNC) {
1649 if (!parser_close_call(parser, sy))
1653 if (vec_last(sy->paren) == PAREN_EXPR) {
1655 if (!vec_size(sy->out)) {
1656 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1657 vec_shrinkby(sy->ops, 1);
1660 vec_shrinkby(sy->ops, 1);
1663 if (vec_last(sy->paren) == PAREN_INDEX) {
1665 /* pop off the parenthesis */
1666 vec_shrinkby(sy->ops, 1);
1667 /* then apply the index operator */
1668 if (!parser_sy_apply_operator(parser, sy))
1672 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1673 vec_last(sy->paren) = PAREN_TERNARY2;
1674 /* pop off the parenthesis */
1675 vec_shrinkby(sy->ops, 1);
1678 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1681 if (!parser_sy_apply_operator(parser, sy))
1687 static void parser_reclassify_token(parser_t *parser)
1690 for (i = 0; i < operator_count; ++i) {
1691 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1692 parser->tok = TOKEN_OPERATOR;
1698 static ast_expression* parse_vararg_do(parser_t *parser)
1700 ast_expression *idx, *out;
1702 ast_value *funtype = parser->function->vtype;
1704 lex_ctx ctx = parser_ctx(parser);
1706 if (!parser_next(parser) || parser->tok != '(') {
1707 parseerror(parser, "expected parameter index and type in parenthesis");
1710 if (!parser_next(parser)) {
1711 parseerror(parser, "error parsing parameter index");
1715 idx = parse_expression_leave(parser, true, false, false);
1719 if (parser->tok != ',') {
1721 parseerror(parser, "expected comma after parameter index");
1725 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1727 parseerror(parser, "expected typename for vararg");
1731 typevar = parse_typename(parser, NULL, NULL);
1737 if (parser->tok != ')') {
1739 ast_delete(typevar);
1740 parseerror(parser, "expected closing paren");
1745 if (!parser_next(parser)) {
1747 ast_delete(typevar);
1748 parseerror(parser, "parse error after vararg");
1753 if (!parser->function->varargs) {
1755 ast_delete(typevar);
1756 parseerror(parser, "function has no variable argument list");
1760 if (funtype->expression.varparam &&
1761 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1765 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1766 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1767 compile_error(ast_ctx(typevar),
1768 "function was declared to take varargs of type `%s`, requested type is: %s",
1772 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1773 ast_type_adopt(out, typevar);
1774 ast_delete(typevar);
1778 static ast_expression* parse_vararg(parser_t *parser)
1780 bool old_noops = parser->lex->flags.noops;
1782 ast_expression *out;
1784 parser->lex->flags.noops = true;
1785 out = parse_vararg_do(parser);
1787 parser->lex->flags.noops = old_noops;
1791 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1793 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1794 parser->tok == TOKEN_IDENT &&
1795 !strcmp(parser_tokval(parser), "_"))
1797 /* a translatable string */
1800 parser->lex->flags.noops = true;
1801 if (!parser_next(parser) || parser->tok != '(') {
1802 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1805 parser->lex->flags.noops = false;
1806 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1807 parseerror(parser, "expected a constant string in translatable-string extension");
1810 val = parser_const_string(parser, parser_tokval(parser), true);
1813 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1815 if (!parser_next(parser) || parser->tok != ')') {
1816 parseerror(parser, "expected closing paren after translatable string");
1821 else if (parser->tok == TOKEN_DOTS)
1824 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1825 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1828 va = parse_vararg(parser);
1831 vec_push(sy->out, syexp(parser_ctx(parser), va));
1834 else if (parser->tok == TOKEN_FLOATCONST) {
1836 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1839 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1842 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1844 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1847 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1850 else if (parser->tok == TOKEN_STRINGCONST) {
1852 val = parser_const_string(parser, parser_tokval(parser), false);
1855 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1858 else if (parser->tok == TOKEN_VECTORCONST) {
1860 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1863 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1866 else if (parser->tok == TOKEN_IDENT)
1868 const char *ctoken = parser_tokval(parser);
1869 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1870 ast_expression *var;
1871 /* a_vector.{x,y,z} */
1872 if (!vec_size(sy->ops) ||
1873 !vec_last(sy->ops).etype ||
1874 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1875 (prev >= intrinsic_debug_typestring &&
1876 prev <= intrinsic_debug_typestring))
1878 /* When adding more intrinsics, fix the above condition */
1881 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1883 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1885 var = parser_find_var(parser, parser_tokval(parser));
1887 var = parser_find_field(parser, parser_tokval(parser));
1889 if (!var && with_labels) {
1890 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1892 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1893 var = (ast_expression*)lbl;
1894 vec_push(parser->labels, lbl);
1897 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1898 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1901 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1902 var = (ast_expression*)intrinsic_debug_typestring;
1904 /* now we try for the real intrinsic hashtable. If the string
1905 * begins with __builtin, we simply skip past it, otherwise we
1906 * use the identifier as is.
1908 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1909 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1913 char *correct = NULL;
1917 * sometimes people use preprocessing predefs without enabling them
1918 * i've done this thousands of times already myself. Lets check for
1919 * it in the predef table. And diagnose it better :)
1921 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1922 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1923 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1924 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1931 * TODO: determine the best score for the identifier: be it
1932 * a variable, a field.
1934 * We should also consider adding correction tables for
1935 * other things as well.
1937 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1939 correct_init(&corr);
1941 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1942 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1943 if (strcmp(correct, parser_tokval(parser))) {
1945 } else if (correct) {
1950 correct_free(&corr);
1953 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1958 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1964 if (ast_istype(var, ast_value)) {
1965 ((ast_value*)var)->uses++;
1967 else if (ast_istype(var, ast_member)) {
1968 ast_member *mem = (ast_member*)var;
1969 if (ast_istype(mem->owner, ast_value))
1970 ((ast_value*)(mem->owner))->uses++;
1973 vec_push(sy->out, syexp(parser_ctx(parser), var));
1976 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1980 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1982 ast_expression *expr = NULL;
1985 bool wantop = false;
1986 /* only warn once about an assignment in a truth value because the current code
1987 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1989 bool warn_truthvalue = true;
1991 /* count the parens because an if starts with one, so the
1992 * end of a condition is an unmatched closing paren
1996 memset(&sy, 0, sizeof(sy));
1998 parser->lex->flags.noops = false;
2000 parser_reclassify_token(parser);
2004 if (parser->tok == TOKEN_TYPENAME) {
2005 parseerror(parser, "unexpected typename");
2009 if (parser->tok == TOKEN_OPERATOR)
2011 /* classify the operator */
2012 const oper_info *op;
2013 const oper_info *olast = NULL;
2015 for (o = 0; o < operator_count; ++o) {
2016 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2017 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2018 !strcmp(parser_tokval(parser), operators[o].op))
2023 if (o == operator_count) {
2024 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2027 /* found an operator */
2030 /* when declaring variables, a comma starts a new variable */
2031 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2032 /* fixup the token */
2037 /* a colon without a pervious question mark cannot be a ternary */
2038 if (!ternaries && op->id == opid2(':','?')) {
2043 if (op->id == opid1(',')) {
2044 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2045 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2049 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2050 olast = &operators[vec_last(sy.ops).etype-1];
2052 #define IsAssignOp(x) (\
2053 (x) == opid1('=') || \
2054 (x) == opid2('+','=') || \
2055 (x) == opid2('-','=') || \
2056 (x) == opid2('*','=') || \
2057 (x) == opid2('/','=') || \
2058 (x) == opid2('%','=') || \
2059 (x) == opid2('&','=') || \
2060 (x) == opid2('|','=') || \
2061 (x) == opid3('&','~','=') \
2063 if (warn_truthvalue) {
2064 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2065 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2066 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2069 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2070 warn_truthvalue = false;
2075 (op->prec < olast->prec) ||
2076 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2078 if (!parser_sy_apply_operator(parser, &sy))
2080 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2081 olast = &operators[vec_last(sy.ops).etype-1];
2086 if (op->id == opid1('(')) {
2088 size_t sycount = vec_size(sy.out);
2089 /* we expected an operator, this is the function-call operator */
2090 vec_push(sy.paren, PAREN_FUNC);
2091 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2092 vec_push(sy.argc, 0);
2094 vec_push(sy.paren, PAREN_EXPR);
2095 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2098 } else if (op->id == opid1('[')) {
2100 parseerror(parser, "unexpected array subscript");
2103 vec_push(sy.paren, PAREN_INDEX);
2104 /* push both the operator and the paren, this makes life easier */
2105 vec_push(sy.ops, syop(parser_ctx(parser), op));
2106 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2108 } else if (op->id == opid2('?',':')) {
2109 vec_push(sy.ops, syop(parser_ctx(parser), op));
2110 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2113 vec_push(sy.paren, PAREN_TERNARY1);
2114 } else if (op->id == opid2(':','?')) {
2115 if (!vec_size(sy.paren)) {
2116 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2119 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2120 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2123 if (!parser_close_paren(parser, &sy))
2125 vec_push(sy.ops, syop(parser_ctx(parser), op));
2129 vec_push(sy.ops, syop(parser_ctx(parser), op));
2130 wantop = !!(op->flags & OP_SUFFIX);
2133 else if (parser->tok == ')') {
2134 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2135 if (!parser_sy_apply_operator(parser, &sy))
2138 if (!vec_size(sy.paren))
2141 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2142 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2145 if (!parser_close_paren(parser, &sy))
2148 /* must be a function call without parameters */
2149 if (vec_last(sy.paren) != PAREN_FUNC) {
2150 parseerror(parser, "closing paren in invalid position");
2153 if (!parser_close_paren(parser, &sy))
2158 else if (parser->tok == '(') {
2159 parseerror(parser, "internal error: '(' should be classified as operator");
2162 else if (parser->tok == '[') {
2163 parseerror(parser, "internal error: '[' should be classified as operator");
2166 else if (parser->tok == ']') {
2167 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2168 if (!parser_sy_apply_operator(parser, &sy))
2171 if (!vec_size(sy.paren))
2173 if (vec_last(sy.paren) != PAREN_INDEX) {
2174 parseerror(parser, "mismatched parentheses, unexpected ']'");
2177 if (!parser_close_paren(parser, &sy))
2182 if (!parse_sya_operand(parser, &sy, with_labels))
2185 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2186 vec_last(sy.argc)++;
2191 /* in this case we might want to allow constant string concatenation */
2192 bool concatenated = false;
2193 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2194 ast_expression *lexpr = vec_last(sy.out).out;
2195 if (ast_istype(lexpr, ast_value)) {
2196 ast_value *last = (ast_value*)lexpr;
2197 if (last->isimm == true && last->cvq == CV_CONST &&
2198 last->hasvalue && last->expression.vtype == TYPE_STRING)
2200 char *newstr = NULL;
2201 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2202 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2204 concatenated = true;
2208 if (!concatenated) {
2209 parseerror(parser, "expected operator or end of statement");
2214 if (!parser_next(parser)) {
2217 if (parser->tok == ';' ||
2218 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2219 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2225 while (vec_size(sy.ops)) {
2226 if (!parser_sy_apply_operator(parser, &sy))
2230 parser->lex->flags.noops = true;
2231 if (!vec_size(sy.out)) {
2232 parseerror(parser, "empty expression");
2235 expr = sy.out[0].out;
2238 if (vec_size(sy.paren)) {
2239 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2247 parser->lex->flags.noops = true;
2248 for (i = 0; i < vec_size(sy.out); ++i) {
2250 ast_unref(sy.out[i].out);
2259 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2261 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2264 if (parser->tok != ';') {
2265 parseerror(parser, "semicolon expected after expression");
2269 if (!parser_next(parser)) {
2276 static void parser_enterblock(parser_t *parser)
2278 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2279 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2280 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2281 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2282 vec_push(parser->_block_ctx, parser_ctx(parser));
2285 vec_push(parser->correct_variables, correct_trie_new());
2286 vec_push(parser->correct_variables_score, NULL);
2289 static bool parser_leaveblock(parser_t *parser)
2292 size_t locals, typedefs;
2294 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2295 parseerror(parser, "internal error: parser_leaveblock with no block");
2299 util_htdel(vec_last(parser->variables));
2300 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2302 vec_pop(parser->variables);
2303 vec_pop(parser->correct_variables);
2304 vec_pop(parser->correct_variables_score);
2305 if (!vec_size(parser->_blocklocals)) {
2306 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2310 locals = vec_last(parser->_blocklocals);
2311 vec_pop(parser->_blocklocals);
2312 while (vec_size(parser->_locals) != locals) {
2313 ast_expression *e = vec_last(parser->_locals);
2314 ast_value *v = (ast_value*)e;
2315 vec_pop(parser->_locals);
2316 if (ast_istype(e, ast_value) && !v->uses) {
2317 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2322 typedefs = vec_last(parser->_blocktypedefs);
2323 while (vec_size(parser->_typedefs) != typedefs) {
2324 ast_delete(vec_last(parser->_typedefs));
2325 vec_pop(parser->_typedefs);
2327 util_htdel(vec_last(parser->typedefs));
2328 vec_pop(parser->typedefs);
2330 vec_pop(parser->_block_ctx);
2335 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2337 vec_push(parser->_locals, e);
2338 util_htset(vec_last(parser->variables), name, (void*)e);
2342 vec_last(parser->correct_variables),
2343 &vec_last(parser->correct_variables_score),
2348 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2350 vec_push(parser->globals, e);
2351 util_htset(parser->htglobals, name, e);
2355 parser->correct_variables[0],
2356 &parser->correct_variables_score[0],
2361 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2365 ast_expression *prev;
2367 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2369 ast_type_to_string(cond, ty, sizeof(ty));
2370 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2373 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2376 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2379 parseerror(parser, "internal error: failed to process condition");
2384 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2386 /* vector types need to be cast to true booleans */
2387 ast_binary *bin = (ast_binary*)cond;
2388 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2390 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2392 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2395 parseerror(parser, "internal error: failed to process condition");
2402 unary = (ast_unary*)cond;
2403 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2405 cond = unary->operand;
2406 unary->operand = NULL;
2409 unary = (ast_unary*)cond;
2413 parseerror(parser, "internal error: failed to process condition");
2415 if (ifnot) *_ifnot = !*_ifnot;
2419 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2422 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2425 lex_ctx ctx = parser_ctx(parser);
2427 (void)block; /* not touching */
2429 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2430 if (!parser_next(parser)) {
2431 parseerror(parser, "expected condition or 'not'");
2434 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2436 if (!parser_next(parser)) {
2437 parseerror(parser, "expected condition in parenthesis");
2441 if (parser->tok != '(') {
2442 parseerror(parser, "expected 'if' condition in parenthesis");
2445 /* parse into the expression */
2446 if (!parser_next(parser)) {
2447 parseerror(parser, "expected 'if' condition after opening paren");
2450 /* parse the condition */
2451 cond = parse_expression_leave(parser, false, true, false);
2455 if (parser->tok != ')') {
2456 parseerror(parser, "expected closing paren after 'if' condition");
2460 /* parse into the 'then' branch */
2461 if (!parser_next(parser)) {
2462 parseerror(parser, "expected statement for on-true branch of 'if'");
2466 if (!parse_statement_or_block(parser, &ontrue)) {
2471 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2472 /* check for an else */
2473 if (!strcmp(parser_tokval(parser), "else")) {
2474 /* parse into the 'else' branch */
2475 if (!parser_next(parser)) {
2476 parseerror(parser, "expected on-false branch after 'else'");
2481 if (!parse_statement_or_block(parser, &onfalse)) {
2488 cond = process_condition(parser, cond, &ifnot);
2490 if (ontrue) ast_delete(ontrue);
2491 if (onfalse) ast_delete(onfalse);
2496 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2498 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2499 *out = (ast_expression*)ifthen;
2503 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2504 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2509 /* skip the 'while' and get the body */
2510 if (!parser_next(parser)) {
2511 if (OPTS_FLAG(LOOP_LABELS))
2512 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2514 parseerror(parser, "expected 'while' condition in parenthesis");
2518 if (parser->tok == ':') {
2519 if (!OPTS_FLAG(LOOP_LABELS))
2520 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2521 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2522 parseerror(parser, "expected loop label");
2525 label = util_strdup(parser_tokval(parser));
2526 if (!parser_next(parser)) {
2528 parseerror(parser, "expected 'while' condition in parenthesis");
2533 if (parser->tok != '(') {
2534 parseerror(parser, "expected 'while' condition in parenthesis");
2538 vec_push(parser->breaks, label);
2539 vec_push(parser->continues, label);
2541 rv = parse_while_go(parser, block, out);
2544 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2545 parseerror(parser, "internal error: label stack corrupted");
2551 vec_pop(parser->breaks);
2552 vec_pop(parser->continues);
2557 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2560 ast_expression *cond, *ontrue;
2564 lex_ctx ctx = parser_ctx(parser);
2566 (void)block; /* not touching */
2568 /* parse into the expression */
2569 if (!parser_next(parser)) {
2570 parseerror(parser, "expected 'while' condition after opening paren");
2573 /* parse the condition */
2574 cond = parse_expression_leave(parser, false, true, false);
2578 if (parser->tok != ')') {
2579 parseerror(parser, "expected closing paren after 'while' condition");
2583 /* parse into the 'then' branch */
2584 if (!parser_next(parser)) {
2585 parseerror(parser, "expected while-loop body");
2589 if (!parse_statement_or_block(parser, &ontrue)) {
2594 cond = process_condition(parser, cond, &ifnot);
2599 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2600 *out = (ast_expression*)aloop;
2604 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2605 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2610 /* skip the 'do' and get the body */
2611 if (!parser_next(parser)) {
2612 if (OPTS_FLAG(LOOP_LABELS))
2613 parseerror(parser, "expected loop label or body");
2615 parseerror(parser, "expected loop body");
2619 if (parser->tok == ':') {
2620 if (!OPTS_FLAG(LOOP_LABELS))
2621 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2622 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2623 parseerror(parser, "expected loop label");
2626 label = util_strdup(parser_tokval(parser));
2627 if (!parser_next(parser)) {
2629 parseerror(parser, "expected loop body");
2634 vec_push(parser->breaks, label);
2635 vec_push(parser->continues, label);
2637 rv = parse_dowhile_go(parser, block, out);
2640 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2641 parseerror(parser, "internal error: label stack corrupted");
2647 vec_pop(parser->breaks);
2648 vec_pop(parser->continues);
2653 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2656 ast_expression *cond, *ontrue;
2660 lex_ctx ctx = parser_ctx(parser);
2662 (void)block; /* not touching */
2664 if (!parse_statement_or_block(parser, &ontrue))
2667 /* expect the "while" */
2668 if (parser->tok != TOKEN_KEYWORD ||
2669 strcmp(parser_tokval(parser), "while"))
2671 parseerror(parser, "expected 'while' and condition");
2676 /* skip the 'while' and check for opening paren */
2677 if (!parser_next(parser) || parser->tok != '(') {
2678 parseerror(parser, "expected 'while' condition in parenthesis");
2682 /* parse into the expression */
2683 if (!parser_next(parser)) {
2684 parseerror(parser, "expected 'while' condition after opening paren");
2688 /* parse the condition */
2689 cond = parse_expression_leave(parser, false, true, false);
2693 if (parser->tok != ')') {
2694 parseerror(parser, "expected closing paren after 'while' condition");
2700 if (!parser_next(parser) || parser->tok != ';') {
2701 parseerror(parser, "expected semicolon after condition");
2707 if (!parser_next(parser)) {
2708 parseerror(parser, "parse error");
2714 cond = process_condition(parser, cond, &ifnot);
2719 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2720 *out = (ast_expression*)aloop;
2724 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2725 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2730 /* skip the 'for' and check for opening paren */
2731 if (!parser_next(parser)) {
2732 if (OPTS_FLAG(LOOP_LABELS))
2733 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2735 parseerror(parser, "expected 'for' expressions in parenthesis");
2739 if (parser->tok == ':') {
2740 if (!OPTS_FLAG(LOOP_LABELS))
2741 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2742 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2743 parseerror(parser, "expected loop label");
2746 label = util_strdup(parser_tokval(parser));
2747 if (!parser_next(parser)) {
2749 parseerror(parser, "expected 'for' expressions in parenthesis");
2754 if (parser->tok != '(') {
2755 parseerror(parser, "expected 'for' expressions in parenthesis");
2759 vec_push(parser->breaks, label);
2760 vec_push(parser->continues, label);
2762 rv = parse_for_go(parser, block, out);
2765 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2766 parseerror(parser, "internal error: label stack corrupted");
2772 vec_pop(parser->breaks);
2773 vec_pop(parser->continues);
2777 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2780 ast_expression *initexpr, *cond, *increment, *ontrue;
2786 lex_ctx ctx = parser_ctx(parser);
2788 parser_enterblock(parser);
2795 /* parse into the expression */
2796 if (!parser_next(parser)) {
2797 parseerror(parser, "expected 'for' initializer after opening paren");
2802 if (parser->tok == TOKEN_IDENT)
2803 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2805 if (typevar || parser->tok == TOKEN_TYPENAME) {
2807 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2808 if (parsewarning(parser, WARN_EXTENSIONS,
2809 "current standard does not allow variable declarations in for-loop initializers"))
2813 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2816 else if (parser->tok != ';')
2818 initexpr = parse_expression_leave(parser, false, false, false);
2823 /* move on to condition */
2824 if (parser->tok != ';') {
2825 parseerror(parser, "expected semicolon after for-loop initializer");
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "expected for-loop condition");
2833 /* parse the condition */
2834 if (parser->tok != ';') {
2835 cond = parse_expression_leave(parser, false, true, false);
2840 /* move on to incrementor */
2841 if (parser->tok != ';') {
2842 parseerror(parser, "expected semicolon after for-loop initializer");
2845 if (!parser_next(parser)) {
2846 parseerror(parser, "expected for-loop condition");
2850 /* parse the incrementor */
2851 if (parser->tok != ')') {
2852 lex_ctx condctx = parser_ctx(parser);
2853 increment = parse_expression_leave(parser, false, false, false);
2856 if (!ast_side_effects(increment)) {
2857 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2863 if (parser->tok != ')') {
2864 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2867 /* parse into the 'then' branch */
2868 if (!parser_next(parser)) {
2869 parseerror(parser, "expected for-loop body");
2872 if (!parse_statement_or_block(parser, &ontrue))
2876 cond = process_condition(parser, cond, &ifnot);
2880 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2881 *out = (ast_expression*)aloop;
2883 if (!parser_leaveblock(parser))
2887 if (initexpr) ast_delete(initexpr);
2888 if (cond) ast_delete(cond);
2889 if (increment) ast_delete(increment);
2890 (void)!parser_leaveblock(parser);
2894 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2896 ast_expression *exp = NULL;
2897 ast_return *ret = NULL;
2898 ast_value *expected = parser->function->vtype;
2900 lex_ctx ctx = parser_ctx(parser);
2902 (void)block; /* not touching */
2904 if (!parser_next(parser)) {
2905 parseerror(parser, "expected return expression");
2909 if (parser->tok != ';') {
2910 exp = parse_expression(parser, false, false);
2914 if (exp->expression.vtype != TYPE_NIL &&
2915 exp->expression.vtype != expected->expression.next->expression.vtype)
2917 parseerror(parser, "return with invalid expression");
2920 ret = ast_return_new(ctx, exp);
2926 if (!parser_next(parser))
2927 parseerror(parser, "parse error");
2928 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2929 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2931 ret = ast_return_new(ctx, NULL);
2933 *out = (ast_expression*)ret;
2937 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2940 unsigned int levels = 0;
2941 lex_ctx ctx = parser_ctx(parser);
2942 const char **loops = (is_continue ? parser->continues : parser->breaks);
2944 (void)block; /* not touching */
2945 if (!parser_next(parser)) {
2946 parseerror(parser, "expected semicolon or loop label");
2950 if (!vec_size(loops)) {
2952 parseerror(parser, "`continue` can only be used inside loops");
2954 parseerror(parser, "`break` can only be used inside loops or switches");
2957 if (parser->tok == TOKEN_IDENT) {
2958 if (!OPTS_FLAG(LOOP_LABELS))
2959 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2960 i = vec_size(loops);
2962 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2965 parseerror(parser, "no such loop to %s: `%s`",
2966 (is_continue ? "continue" : "break out of"),
2967 parser_tokval(parser));
2972 if (!parser_next(parser)) {
2973 parseerror(parser, "expected semicolon");
2978 if (parser->tok != ';') {
2979 parseerror(parser, "expected semicolon");
2983 if (!parser_next(parser))
2984 parseerror(parser, "parse error");
2986 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2990 /* returns true when it was a variable qualifier, false otherwise!
2991 * on error, cvq is set to CV_WRONG
2993 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2995 bool had_const = false;
2996 bool had_var = false;
2997 bool had_noref = false;
2998 bool had_attrib = false;
2999 bool had_static = false;
3004 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3006 /* parse an attribute */
3007 if (!parser_next(parser)) {
3008 parseerror(parser, "expected attribute after `[[`");
3012 if (!strcmp(parser_tokval(parser), "noreturn")) {
3013 flags |= AST_FLAG_NORETURN;
3014 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3015 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3020 else if (!strcmp(parser_tokval(parser), "noref")) {
3022 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3023 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3028 else if (!strcmp(parser_tokval(parser), "inline")) {
3029 flags |= AST_FLAG_INLINE;
3030 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3031 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3036 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3037 flags |= AST_FLAG_ALIAS;
3040 if (!parser_next(parser)) {
3041 parseerror(parser, "parse error in attribute");
3045 if (parser->tok == '(') {
3046 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3047 parseerror(parser, "`alias` attribute missing parameter");
3051 *message = util_strdup(parser_tokval(parser));
3053 if (!parser_next(parser)) {
3054 parseerror(parser, "parse error in attribute");
3058 if (parser->tok != ')') {
3059 parseerror(parser, "`alias` attribute expected `)` after parameter");
3063 if (!parser_next(parser)) {
3064 parseerror(parser, "parse error in attribute");
3069 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3070 parseerror(parser, "`alias` attribute expected `]]`");
3074 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3075 flags |= AST_FLAG_DEPRECATED;
3078 if (!parser_next(parser)) {
3079 parseerror(parser, "parse error in attribute");
3083 if (parser->tok == '(') {
3084 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3085 parseerror(parser, "`deprecated` attribute missing parameter");
3089 *message = util_strdup(parser_tokval(parser));
3091 if (!parser_next(parser)) {
3092 parseerror(parser, "parse error in attribute");
3096 if(parser->tok != ')') {
3097 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3101 if (!parser_next(parser)) {
3102 parseerror(parser, "parse error in attribute");
3107 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3108 parseerror(parser, "`deprecated` attribute expected `]]`");
3111 if (*message) mem_d(*message);
3119 /* Skip tokens until we hit a ]] */
3120 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3121 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3122 if (!parser_next(parser)) {
3123 parseerror(parser, "error inside attribute");
3130 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3132 else if (!strcmp(parser_tokval(parser), "const"))
3134 else if (!strcmp(parser_tokval(parser), "var"))
3136 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3138 else if (!strcmp(parser_tokval(parser), "noref"))
3140 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3145 if (!parser_next(parser))
3155 *is_static = had_static;
3159 parseerror(parser, "parse error after variable qualifier");
3164 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3165 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3170 /* skip the 'while' and get the body */
3171 if (!parser_next(parser)) {
3172 if (OPTS_FLAG(LOOP_LABELS))
3173 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3175 parseerror(parser, "expected 'switch' operand in parenthesis");
3179 if (parser->tok == ':') {
3180 if (!OPTS_FLAG(LOOP_LABELS))
3181 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3182 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3183 parseerror(parser, "expected loop label");
3186 label = util_strdup(parser_tokval(parser));
3187 if (!parser_next(parser)) {
3189 parseerror(parser, "expected 'switch' operand in parenthesis");
3194 if (parser->tok != '(') {
3195 parseerror(parser, "expected 'switch' operand in parenthesis");
3199 vec_push(parser->breaks, label);
3201 rv = parse_switch_go(parser, block, out);
3204 if (vec_last(parser->breaks) != label) {
3205 parseerror(parser, "internal error: label stack corrupted");
3211 vec_pop(parser->breaks);
3216 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3218 ast_expression *operand;
3221 ast_switch *switchnode;
3222 ast_switch_case swcase;
3225 bool noref, is_static;
3226 uint32_t qflags = 0;
3228 lex_ctx ctx = parser_ctx(parser);
3230 (void)block; /* not touching */
3233 /* parse into the expression */
3234 if (!parser_next(parser)) {
3235 parseerror(parser, "expected switch operand");
3238 /* parse the operand */
3239 operand = parse_expression_leave(parser, false, false, false);
3243 switchnode = ast_switch_new(ctx, operand);
3246 if (parser->tok != ')') {
3247 ast_delete(switchnode);
3248 parseerror(parser, "expected closing paren after 'switch' operand");
3252 /* parse over the opening paren */
3253 if (!parser_next(parser) || parser->tok != '{') {
3254 ast_delete(switchnode);
3255 parseerror(parser, "expected list of cases");
3259 if (!parser_next(parser)) {
3260 ast_delete(switchnode);
3261 parseerror(parser, "expected 'case' or 'default'");
3265 /* new block; allow some variables to be declared here */
3266 parser_enterblock(parser);
3269 if (parser->tok == TOKEN_IDENT)
3270 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3271 if (typevar || parser->tok == TOKEN_TYPENAME) {
3272 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3273 ast_delete(switchnode);
3278 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3280 if (cvq == CV_WRONG) {
3281 ast_delete(switchnode);
3284 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3285 ast_delete(switchnode);
3294 while (parser->tok != '}') {
3295 ast_block *caseblock;
3297 if (!strcmp(parser_tokval(parser), "case")) {
3298 if (!parser_next(parser)) {
3299 ast_delete(switchnode);
3300 parseerror(parser, "expected expression for case");
3303 swcase.value = parse_expression_leave(parser, false, false, false);
3304 if (!swcase.value) {
3305 ast_delete(switchnode);
3306 parseerror(parser, "expected expression for case");
3309 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3310 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3311 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3317 else if (!strcmp(parser_tokval(parser), "default")) {
3318 swcase.value = NULL;
3319 if (!parser_next(parser)) {
3320 ast_delete(switchnode);
3321 parseerror(parser, "expected colon");
3326 ast_delete(switchnode);
3327 parseerror(parser, "expected 'case' or 'default'");
3331 /* Now the colon and body */
3332 if (parser->tok != ':') {
3333 if (swcase.value) ast_unref(swcase.value);
3334 ast_delete(switchnode);
3335 parseerror(parser, "expected colon");
3339 if (!parser_next(parser)) {
3340 if (swcase.value) ast_unref(swcase.value);
3341 ast_delete(switchnode);
3342 parseerror(parser, "expected statements or case");
3345 caseblock = ast_block_new(parser_ctx(parser));
3347 if (swcase.value) ast_unref(swcase.value);
3348 ast_delete(switchnode);
3351 swcase.code = (ast_expression*)caseblock;
3352 vec_push(switchnode->cases, swcase);
3354 ast_expression *expr;
3355 if (parser->tok == '}')
3357 if (parser->tok == TOKEN_KEYWORD) {
3358 if (!strcmp(parser_tokval(parser), "case") ||
3359 !strcmp(parser_tokval(parser), "default"))
3364 if (!parse_statement(parser, caseblock, &expr, true)) {
3365 ast_delete(switchnode);
3370 if (!ast_block_add_expr(caseblock, expr)) {
3371 ast_delete(switchnode);
3377 parser_leaveblock(parser);
3380 if (parser->tok != '}') {
3381 ast_delete(switchnode);
3382 parseerror(parser, "expected closing paren of case list");
3385 if (!parser_next(parser)) {
3386 ast_delete(switchnode);
3387 parseerror(parser, "parse error after switch");
3390 *out = (ast_expression*)switchnode;
3394 /* parse computed goto sides */
3395 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3396 ast_expression *on_true;
3397 ast_expression *on_false;
3398 ast_expression *cond;
3403 if (ast_istype(*side, ast_ternary)) {
3404 ast_ternary *tern = (ast_ternary*)*side;
3405 on_true = parse_goto_computed(parser, &tern->on_true);
3406 on_false = parse_goto_computed(parser, &tern->on_false);
3408 if (!on_true || !on_false) {
3409 parseerror(parser, "expected label or expression in ternary");
3410 if (on_true) ast_unref(on_true);
3411 if (on_false) ast_unref(on_false);
3419 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3420 } else if (ast_istype(*side, ast_label)) {
3421 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3422 ast_goto_set_label(gt, ((ast_label*)*side));
3424 return (ast_expression*)gt;
3429 static bool parse_goto(parser_t *parser, ast_expression **out)
3431 ast_goto *gt = NULL;
3432 ast_expression *lbl;
3434 if (!parser_next(parser))
3437 if (parser->tok != TOKEN_IDENT) {
3438 ast_expression *expression;
3440 /* could be an expression i.e computed goto :-) */
3441 if (parser->tok != '(') {
3442 parseerror(parser, "expected label name after `goto`");
3446 /* failed to parse expression for goto */
3447 if (!(expression = parse_expression(parser, false, true)) ||
3448 !(*out = parse_goto_computed(parser, &expression))) {
3449 parseerror(parser, "invalid goto expression");
3450 ast_unref(expression);
3457 /* not computed goto */
3458 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3459 lbl = parser_find_label(parser, gt->name);
3461 if (!ast_istype(lbl, ast_label)) {
3462 parseerror(parser, "internal error: label is not an ast_label");
3466 ast_goto_set_label(gt, (ast_label*)lbl);
3469 vec_push(parser->gotos, gt);
3471 if (!parser_next(parser) || parser->tok != ';') {
3472 parseerror(parser, "semicolon expected after goto label");
3475 if (!parser_next(parser)) {
3476 parseerror(parser, "parse error after goto");
3480 *out = (ast_expression*)gt;
3484 static bool parse_skipwhite(parser_t *parser)
3487 if (!parser_next(parser))
3489 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3490 return parser->tok < TOKEN_ERROR;
3493 static bool parse_eol(parser_t *parser)
3495 if (!parse_skipwhite(parser))
3497 return parser->tok == TOKEN_EOL;
3500 static bool parse_pragma_do(parser_t *parser)
3502 if (!parser_next(parser) ||
3503 parser->tok != TOKEN_IDENT ||
3504 strcmp(parser_tokval(parser), "pragma"))
3506 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3509 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3510 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3514 if (!strcmp(parser_tokval(parser), "noref")) {
3515 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3516 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3519 parser->noref = !!parser_token(parser)->constval.i;
3520 if (!parse_eol(parser)) {
3521 parseerror(parser, "parse error after `noref` pragma");
3527 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3534 static bool parse_pragma(parser_t *parser)
3537 parser->lex->flags.preprocessing = true;
3538 parser->lex->flags.mergelines = true;
3539 rv = parse_pragma_do(parser);
3540 if (parser->tok != TOKEN_EOL) {
3541 parseerror(parser, "junk after pragma");
3544 parser->lex->flags.preprocessing = false;
3545 parser->lex->flags.mergelines = false;
3546 if (!parser_next(parser)) {
3547 parseerror(parser, "parse error after pragma");
3553 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3555 bool noref, is_static;
3557 uint32_t qflags = 0;
3558 ast_value *typevar = NULL;
3559 char *vstring = NULL;
3563 if (parser->tok == TOKEN_IDENT)
3564 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3566 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3568 /* local variable */
3570 parseerror(parser, "cannot declare a variable from here");
3573 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3574 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3577 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3581 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3583 if (cvq == CV_WRONG)
3585 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3587 else if (parser->tok == TOKEN_KEYWORD)
3589 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3594 if (!parser_next(parser)) {
3595 parseerror(parser, "parse error after __builtin_debug_printtype");
3599 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3601 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3602 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3603 if (!parser_next(parser)) {
3604 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3610 if (!parse_statement(parser, block, out, allow_cases))
3613 con_out("__builtin_debug_printtype: got no output node\n");
3616 ast_type_to_string(*out, ty, sizeof(ty));
3617 con_out("__builtin_debug_printtype: `%s`\n", ty);
3622 else if (!strcmp(parser_tokval(parser), "return"))
3624 return parse_return(parser, block, out);
3626 else if (!strcmp(parser_tokval(parser), "if"))
3628 return parse_if(parser, block, out);
3630 else if (!strcmp(parser_tokval(parser), "while"))
3632 return parse_while(parser, block, out);
3634 else if (!strcmp(parser_tokval(parser), "do"))
3636 return parse_dowhile(parser, block, out);
3638 else if (!strcmp(parser_tokval(parser), "for"))
3640 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3641 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3644 return parse_for(parser, block, out);
3646 else if (!strcmp(parser_tokval(parser), "break"))
3648 return parse_break_continue(parser, block, out, false);
3650 else if (!strcmp(parser_tokval(parser), "continue"))
3652 return parse_break_continue(parser, block, out, true);
3654 else if (!strcmp(parser_tokval(parser), "switch"))
3656 return parse_switch(parser, block, out);
3658 else if (!strcmp(parser_tokval(parser), "case") ||
3659 !strcmp(parser_tokval(parser), "default"))
3662 parseerror(parser, "unexpected 'case' label");
3667 else if (!strcmp(parser_tokval(parser), "goto"))
3669 return parse_goto(parser, out);
3671 else if (!strcmp(parser_tokval(parser), "typedef"))
3673 if (!parser_next(parser)) {
3674 parseerror(parser, "expected type definition after 'typedef'");
3677 return parse_typedef(parser);
3679 parseerror(parser, "Unexpected keyword");
3682 else if (parser->tok == '{')
3685 inner = parse_block(parser);
3688 *out = (ast_expression*)inner;
3691 else if (parser->tok == ':')
3695 if (!parser_next(parser)) {
3696 parseerror(parser, "expected label name");
3699 if (parser->tok != TOKEN_IDENT) {
3700 parseerror(parser, "label must be an identifier");
3703 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3705 if (!label->undefined) {
3706 parseerror(parser, "label `%s` already defined", label->name);
3709 label->undefined = false;
3712 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3713 vec_push(parser->labels, label);
3715 *out = (ast_expression*)label;
3716 if (!parser_next(parser)) {
3717 parseerror(parser, "parse error after label");
3720 for (i = 0; i < vec_size(parser->gotos); ++i) {
3721 if (!strcmp(parser->gotos[i]->name, label->name)) {
3722 ast_goto_set_label(parser->gotos[i], label);
3723 vec_remove(parser->gotos, i, 1);
3729 else if (parser->tok == ';')
3731 if (!parser_next(parser)) {
3732 parseerror(parser, "parse error after empty statement");
3739 lex_ctx ctx = parser_ctx(parser);
3740 ast_expression *exp = parse_expression(parser, false, false);
3744 if (!ast_side_effects(exp)) {
3745 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3752 static bool parse_enum(parser_t *parser)
3755 bool reverse = false;
3757 ast_value **values = NULL;
3758 ast_value *var = NULL;
3761 ast_expression *old;
3763 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3764 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3768 /* enumeration attributes (can add more later) */
3769 if (parser->tok == ':') {
3770 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3771 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3776 if (!strcmp(parser_tokval(parser), "flag")) {
3780 else if (!strcmp(parser_tokval(parser), "reverse")) {
3784 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3788 if (!parser_next(parser) || parser->tok != '{') {
3789 parseerror(parser, "expected `{` after enum attribute ");
3795 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3796 if (parser->tok == '}') {
3797 /* allow an empty enum */
3800 parseerror(parser, "expected identifier or `}`");
3804 old = parser_find_field(parser, parser_tokval(parser));
3806 old = parser_find_global(parser, parser_tokval(parser));
3808 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3809 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3813 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3814 vec_push(values, var);
3815 var->cvq = CV_CONST;
3816 var->hasvalue = true;
3818 /* for flagged enumerations increment in POTs of TWO */
3819 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3820 parser_addglobal(parser, var->name, (ast_expression*)var);
3822 if (!parser_next(parser)) {
3823 parseerror(parser, "expected `=`, `}` or comma after identifier");
3827 if (parser->tok == ',')
3829 if (parser->tok == '}')
3831 if (parser->tok != '=') {
3832 parseerror(parser, "expected `=`, `}` or comma after identifier");
3836 if (!parser_next(parser)) {
3837 parseerror(parser, "expected expression after `=`");
3841 /* We got a value! */
3842 old = parse_expression_leave(parser, true, false, false);
3843 asvalue = (ast_value*)old;
3844 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3845 compile_error(ast_ctx(var), "constant value or expression expected");
3848 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3850 if (parser->tok == '}')
3852 if (parser->tok != ',') {
3853 parseerror(parser, "expected `}` or comma after expression");
3858 /* patch them all (for reversed attribute) */
3861 for (i = 0; i < vec_size(values); i++)
3862 values[i]->constval.vfloat = vec_size(values) - i - 1;
3865 if (parser->tok != '}') {
3866 parseerror(parser, "internal error: breaking without `}`");
3870 if (!parser_next(parser) || parser->tok != ';') {
3871 parseerror(parser, "expected semicolon after enumeration");
3875 if (!parser_next(parser)) {
3876 parseerror(parser, "parse error after enumeration");
3888 static bool parse_block_into(parser_t *parser, ast_block *block)
3892 parser_enterblock(parser);
3894 if (!parser_next(parser)) { /* skip the '{' */
3895 parseerror(parser, "expected function body");
3899 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3901 ast_expression *expr = NULL;
3902 if (parser->tok == '}')
3905 if (!parse_statement(parser, block, &expr, false)) {
3906 /* parseerror(parser, "parse error"); */
3912 if (!ast_block_add_expr(block, expr)) {
3919 if (parser->tok != '}') {
3922 (void)parser_next(parser);
3926 if (!parser_leaveblock(parser))
3928 return retval && !!block;
3931 static ast_block* parse_block(parser_t *parser)
3934 block = ast_block_new(parser_ctx(parser));
3937 if (!parse_block_into(parser, block)) {
3938 ast_block_delete(block);
3944 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3946 if (parser->tok == '{') {
3947 *out = (ast_expression*)parse_block(parser);
3950 return parse_statement(parser, NULL, out, false);
3953 static bool create_vector_members(ast_value *var, ast_member **me)
3956 size_t len = strlen(var->name);
3958 for (i = 0; i < 3; ++i) {
3959 char *name = (char*)mem_a(len+3);
3960 memcpy(name, var->name, len);
3962 name[len+1] = 'x'+i;
3964 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3973 do { ast_member_delete(me[--i]); } while(i);
3977 static bool parse_function_body(parser_t *parser, ast_value *var)
3979 ast_block *block = NULL;
3984 ast_expression *framenum = NULL;
3985 ast_expression *nextthink = NULL;
3986 /* None of the following have to be deleted */
3987 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3988 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3989 bool has_frame_think;
3993 has_frame_think = false;
3994 old = parser->function;
3996 if (var->expression.flags & AST_FLAG_ALIAS) {
3997 parseerror(parser, "function aliases cannot have bodies");
4001 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4002 parseerror(parser, "gotos/labels leaking");
4006 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4007 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4008 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4014 if (parser->tok == '[') {
4015 /* got a frame definition: [ framenum, nextthink ]
4016 * this translates to:
4017 * self.frame = framenum;
4018 * self.nextthink = time + 0.1;
4019 * self.think = nextthink;
4023 fld_think = parser_find_field(parser, "think");
4024 fld_nextthink = parser_find_field(parser, "nextthink");
4025 fld_frame = parser_find_field(parser, "frame");
4026 if (!fld_think || !fld_nextthink || !fld_frame) {
4027 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4028 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4031 gbl_time = parser_find_global(parser, "time");
4032 gbl_self = parser_find_global(parser, "self");
4033 if (!gbl_time || !gbl_self) {
4034 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4035 parseerror(parser, "please declare the following globals: `time`, `self`");
4039 if (!parser_next(parser))
4042 framenum = parse_expression_leave(parser, true, false, false);
4044 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4047 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4048 ast_unref(framenum);
4049 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4053 if (parser->tok != ',') {
4054 ast_unref(framenum);
4055 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4056 parseerror(parser, "Got a %i\n", parser->tok);
4060 if (!parser_next(parser)) {
4061 ast_unref(framenum);
4065 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4067 /* qc allows the use of not-yet-declared functions here
4068 * - this automatically creates a prototype */
4069 ast_value *thinkfunc;
4070 ast_expression *functype = fld_think->expression.next;
4072 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4073 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4074 ast_unref(framenum);
4075 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4078 ast_type_adopt(thinkfunc, functype);
4080 if (!parser_next(parser)) {
4081 ast_unref(framenum);
4082 ast_delete(thinkfunc);
4086 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4088 nextthink = (ast_expression*)thinkfunc;
4091 nextthink = parse_expression_leave(parser, true, false, false);
4093 ast_unref(framenum);
4094 parseerror(parser, "expected a think-function in [frame,think] notation");
4099 if (!ast_istype(nextthink, ast_value)) {
4100 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4104 if (retval && parser->tok != ']') {
4105 parseerror(parser, "expected closing `]` for [frame,think] notation");
4109 if (retval && !parser_next(parser)) {
4113 if (retval && parser->tok != '{') {
4114 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4119 ast_unref(nextthink);
4120 ast_unref(framenum);
4124 has_frame_think = true;
4127 block = ast_block_new(parser_ctx(parser));
4129 parseerror(parser, "failed to allocate block");
4130 if (has_frame_think) {
4131 ast_unref(nextthink);
4132 ast_unref(framenum);
4137 if (has_frame_think) {
4139 ast_expression *self_frame;
4140 ast_expression *self_nextthink;
4141 ast_expression *self_think;
4142 ast_expression *time_plus_1;
4143 ast_store *store_frame;
4144 ast_store *store_nextthink;
4145 ast_store *store_think;
4147 ctx = parser_ctx(parser);
4148 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4149 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4150 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4152 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4153 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4155 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4156 if (self_frame) ast_delete(self_frame);
4157 if (self_nextthink) ast_delete(self_nextthink);
4158 if (self_think) ast_delete(self_think);
4159 if (time_plus_1) ast_delete(time_plus_1);
4165 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4166 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4167 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4170 ast_delete(self_frame);
4173 if (!store_nextthink) {
4174 ast_delete(self_nextthink);
4178 ast_delete(self_think);
4182 if (store_frame) ast_delete(store_frame);
4183 if (store_nextthink) ast_delete(store_nextthink);
4184 if (store_think) ast_delete(store_think);
4187 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4188 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4189 !ast_block_add_expr(block, (ast_expression*)store_think))
4196 parseerror(parser, "failed to generate code for [frame,think]");
4197 ast_unref(nextthink);
4198 ast_unref(framenum);
4204 if (var->hasvalue) {
4205 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4206 ast_block_delete(block);
4210 func = ast_function_new(ast_ctx(var), var->name, var);
4212 parseerror(parser, "failed to allocate function for `%s`", var->name);
4213 ast_block_delete(block);
4216 vec_push(parser->functions, func);
4218 parser_enterblock(parser);
4220 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4222 ast_value *param = var->expression.params[parami];
4225 if (param->expression.vtype != TYPE_VECTOR &&
4226 (param->expression.vtype != TYPE_FIELD ||
4227 param->expression.next->expression.vtype != TYPE_VECTOR))
4232 if (!create_vector_members(param, me)) {
4233 ast_block_delete(block);
4237 for (e = 0; e < 3; ++e) {
4238 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4239 ast_block_collect(block, (ast_expression*)me[e]);
4243 if (var->argcounter) {
4244 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4245 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4249 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4251 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4252 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4253 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4254 varargs->expression.count = 0;
4255 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4256 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4257 ast_delete(varargs);
4258 ast_block_delete(block);
4261 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4262 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4263 ast_delete(varargs);
4264 ast_block_delete(block);
4267 func->varargs = varargs;
4269 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4272 parser->function = func;
4273 if (!parse_block_into(parser, block)) {
4274 ast_block_delete(block);
4278 vec_push(func->blocks, block);
4280 parser->function = old;
4281 if (!parser_leaveblock(parser))
4283 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4284 parseerror(parser, "internal error: local scopes left");
4288 if (parser->tok == ';')
4289 return parser_next(parser);
4290 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4291 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4295 (void)!parser_leaveblock(parser);
4296 vec_pop(parser->functions);
4297 ast_function_delete(func);
4298 var->constval.vfunc = NULL;
4301 parser->function = old;
4305 static ast_expression *array_accessor_split(
4310 ast_expression *left,
4311 ast_expression *right
4317 lex_ctx ctx = ast_ctx(array);
4319 if (!left || !right) {
4320 if (left) ast_delete(left);
4321 if (right) ast_delete(right);
4325 cmp = ast_binary_new(ctx, INSTR_LT,
4326 (ast_expression*)index,
4327 (ast_expression*)parser_const_float(parser, middle));
4331 parseerror(parser, "internal error: failed to create comparison for array setter");
4335 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4337 ast_delete(cmp); /* will delete left and right */
4338 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4342 return (ast_expression*)ifthen;
4345 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4347 lex_ctx ctx = ast_ctx(array);
4349 if (from+1 == afterend) {
4350 /* set this value */
4353 ast_array_index *subscript;
4355 int assignop = type_store_instr[value->expression.vtype];
4357 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4358 assignop = INSTR_STORE_V;
4360 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4364 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4366 ast_delete(subscript);
4370 block = ast_block_new(ctx);
4376 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4381 ret = ast_return_new(ctx, NULL);
4387 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4392 return (ast_expression*)block;
4394 ast_expression *left, *right;
4395 size_t diff = afterend - from;
4396 size_t middle = from + diff/2;
4397 left = array_setter_node(parser, array, index, value, from, middle);
4398 right = array_setter_node(parser, array, index, value, middle, afterend);
4399 return array_accessor_split(parser, array, index, middle, left, right);
4403 static ast_expression *array_field_setter_node(
4412 lex_ctx ctx = ast_ctx(array);
4414 if (from+1 == afterend) {
4415 /* set this value */
4418 ast_entfield *entfield;
4419 ast_array_index *subscript;
4421 int assignop = type_storep_instr[value->expression.vtype];
4423 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4424 assignop = INSTR_STOREP_V;
4426 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4430 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4431 subscript->expression.vtype = TYPE_FIELD;
4433 entfield = ast_entfield_new_force(ctx,
4434 (ast_expression*)entity,
4435 (ast_expression*)subscript,
4436 (ast_expression*)subscript);
4438 ast_delete(subscript);
4442 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4444 ast_delete(entfield);
4448 block = ast_block_new(ctx);
4454 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4459 ret = ast_return_new(ctx, NULL);
4465 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4470 return (ast_expression*)block;
4472 ast_expression *left, *right;
4473 size_t diff = afterend - from;
4474 size_t middle = from + diff/2;
4475 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4476 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4477 return array_accessor_split(parser, array, index, middle, left, right);
4481 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4483 lex_ctx ctx = ast_ctx(array);
4485 if (from+1 == afterend) {
4487 ast_array_index *subscript;
4489 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4493 ret = ast_return_new(ctx, (ast_expression*)subscript);
4495 ast_delete(subscript);
4499 return (ast_expression*)ret;
4501 ast_expression *left, *right;
4502 size_t diff = afterend - from;
4503 size_t middle = from + diff/2;
4504 left = array_getter_node(parser, array, index, from, middle);
4505 right = array_getter_node(parser, array, index, middle, afterend);
4506 return array_accessor_split(parser, array, index, middle, left, right);
4510 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4512 ast_function *func = NULL;
4513 ast_value *fval = NULL;
4514 ast_block *body = NULL;
4516 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4518 parseerror(parser, "failed to create accessor function value");
4522 func = ast_function_new(ast_ctx(array), funcname, fval);
4525 parseerror(parser, "failed to create accessor function node");
4529 body = ast_block_new(ast_ctx(array));
4531 parseerror(parser, "failed to create block for array accessor");
4537 vec_push(func->blocks, body);
4540 vec_push(parser->accessors, fval);
4545 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4547 ast_value *index = NULL;
4548 ast_value *value = NULL;
4552 if (!ast_istype(array->expression.next, ast_value)) {
4553 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4557 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4559 func = fval->constval.vfunc;
4560 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4562 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4563 value = ast_value_copy((ast_value*)array->expression.next);
4565 if (!index || !value) {
4566 parseerror(parser, "failed to create locals for array accessor");
4569 (void)!ast_value_set_name(value, "value"); /* not important */
4570 vec_push(fval->expression.params, index);
4571 vec_push(fval->expression.params, value);
4573 array->setter = fval;
4576 if (index) ast_delete(index);
4577 if (value) ast_delete(value);
4583 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4585 ast_expression *root = NULL;
4586 root = array_setter_node(parser, array,
4587 array->setter->expression.params[0],
4588 array->setter->expression.params[1],
4589 0, array->expression.count);
4591 parseerror(parser, "failed to build accessor search tree");
4594 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4601 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4603 if (!parser_create_array_setter_proto(parser, array, funcname))
4605 return parser_create_array_setter_impl(parser, array);
4608 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4610 ast_expression *root = NULL;
4611 ast_value *entity = NULL;
4612 ast_value *index = NULL;
4613 ast_value *value = NULL;
4617 if (!ast_istype(array->expression.next, ast_value)) {
4618 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4622 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4624 func = fval->constval.vfunc;
4625 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4627 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4628 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4629 value = ast_value_copy((ast_value*)array->expression.next);
4630 if (!entity || !index || !value) {
4631 parseerror(parser, "failed to create locals for array accessor");
4634 (void)!ast_value_set_name(value, "value"); /* not important */
4635 vec_push(fval->expression.params, entity);
4636 vec_push(fval->expression.params, index);
4637 vec_push(fval->expression.params, value);
4639 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4641 parseerror(parser, "failed to build accessor search tree");
4645 array->setter = fval;
4646 return ast_block_add_expr(func->blocks[0], root);
4648 if (entity) ast_delete(entity);
4649 if (index) ast_delete(index);
4650 if (value) ast_delete(value);
4651 if (root) ast_delete(root);
4657 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4659 ast_value *index = NULL;
4663 /* NOTE: checking array->expression.next rather than elemtype since
4664 * for fields elemtype is a temporary fieldtype.
4666 if (!ast_istype(array->expression.next, ast_value)) {
4667 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4671 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4673 func = fval->constval.vfunc;
4674 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4676 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4679 parseerror(parser, "failed to create locals for array accessor");
4682 vec_push(fval->expression.params, index);
4684 array->getter = fval;
4687 if (index) ast_delete(index);
4693 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4695 ast_expression *root = NULL;
4697 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4699 parseerror(parser, "failed to build accessor search tree");
4702 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4709 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4711 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4713 return parser_create_array_getter_impl(parser, array);
4716 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4717 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4725 bool variadic = false;
4726 ast_value *varparam = NULL;
4727 char *argcounter = NULL;
4729 ctx = parser_ctx(parser);
4731 /* for the sake of less code we parse-in in this function */
4732 if (!parser_next(parser)) {
4733 parseerror(parser, "expected parameter list");
4739 /* parse variables until we hit a closing paren */
4740 while (parser->tok != ')') {
4742 /* there must be commas between them */
4743 if (parser->tok != ',') {
4744 parseerror(parser, "expected comma or end of parameter list");
4747 if (!parser_next(parser)) {
4748 parseerror(parser, "expected parameter");
4754 if (parser->tok == TOKEN_DOTS) {
4755 /* '...' indicates a varargs function */
4757 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4758 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4761 if (parser->tok == TOKEN_IDENT) {
4762 argcounter = util_strdup(parser_tokval(parser));
4763 if (!parser_next(parser) || parser->tok != ')') {
4764 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4771 /* for anything else just parse a typename */
4772 param = parse_typename(parser, NULL, NULL);
4775 vec_push(params, param);
4776 if (param->expression.vtype >= TYPE_VARIANT) {
4777 char tname[1024]; /* typename is reserved in C++ */
4778 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4779 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4782 /* type-restricted varargs */
4783 if (parser->tok == TOKEN_DOTS) {
4785 varparam = vec_last(params);
4787 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4788 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4791 if (parser->tok == TOKEN_IDENT) {
4792 argcounter = util_strdup(parser_tokval(parser));
4793 if (!parser_next(parser) || parser->tok != ')') {
4794 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4802 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4806 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4807 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4810 if (!parser_next(parser)) {
4811 parseerror(parser, "parse error after typename");
4815 /* now turn 'var' into a function type */
4816 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4817 fval->expression.next = (ast_expression*)var;
4819 fval->expression.flags |= AST_FLAG_VARIADIC;
4822 var->expression.params = params;
4823 var->expression.varparam = (ast_expression*)varparam;
4824 var->argcounter = argcounter;
4833 ast_delete(varparam);
4835 for (i = 0; i < vec_size(params); ++i)
4836 ast_delete(params[i]);
4841 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4843 ast_expression *cexp;
4844 ast_value *cval, *tmp;
4847 ctx = parser_ctx(parser);
4849 if (!parser_next(parser)) {
4851 parseerror(parser, "expected array-size");
4855 cexp = parse_expression_leave(parser, true, false, false);
4857 if (!cexp || !ast_istype(cexp, ast_value)) {
4861 parseerror(parser, "expected array-size as constant positive integer");
4864 cval = (ast_value*)cexp;
4866 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4867 tmp->expression.next = (ast_expression*)var;
4870 if (cval->expression.vtype == TYPE_INTEGER)
4871 tmp->expression.count = cval->constval.vint;
4872 else if (cval->expression.vtype == TYPE_FLOAT)
4873 tmp->expression.count = cval->constval.vfloat;
4877 parseerror(parser, "array-size must be a positive integer constant");
4882 if (parser->tok != ']') {
4884 parseerror(parser, "expected ']' after array-size");
4887 if (!parser_next(parser)) {
4889 parseerror(parser, "error after parsing array size");
4895 /* Parse a complete typename.
4896 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4897 * but when parsing variables separated by comma
4898 * 'storebase' should point to where the base-type should be kept.
4899 * The base type makes up every bit of type information which comes *before* the
4902 * The following will be parsed in its entirety:
4904 * The 'basetype' in this case is 'void()'
4905 * and if there's a comma after it, say:
4907 * then the type-information 'void()' can be stored in 'storebase'
4909 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4911 ast_value *var, *tmp;
4914 const char *name = NULL;
4915 bool isfield = false;
4916 bool wasarray = false;
4917 size_t morefields = 0;
4919 ctx = parser_ctx(parser);
4921 /* types may start with a dot */
4922 if (parser->tok == '.') {
4924 /* if we parsed a dot we need a typename now */
4925 if (!parser_next(parser)) {
4926 parseerror(parser, "expected typename for field definition");
4930 /* Further dots are handled seperately because they won't be part of the
4933 while (parser->tok == '.') {
4935 if (!parser_next(parser)) {
4936 parseerror(parser, "expected typename for field definition");
4941 if (parser->tok == TOKEN_IDENT)
4942 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4943 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4944 parseerror(parser, "expected typename");
4948 /* generate the basic type value */
4949 if (cached_typedef) {
4950 var = ast_value_copy(cached_typedef);
4951 ast_value_set_name(var, "<type(from_def)>");
4953 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4955 for (; morefields; --morefields) {
4956 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4957 tmp->expression.next = (ast_expression*)var;
4961 /* do not yet turn into a field - remember:
4962 * .void() foo; is a field too
4963 * .void()() foo; is a function
4967 if (!parser_next(parser)) {
4969 parseerror(parser, "parse error after typename");
4973 /* an opening paren now starts the parameter-list of a function
4974 * this is where original-QC has parameter lists.
4975 * We allow a single parameter list here.
4976 * Much like fteqcc we don't allow `float()() x`
4978 if (parser->tok == '(') {
4979 var = parse_parameter_list(parser, var);
4984 /* store the base if requested */
4986 *storebase = ast_value_copy(var);
4988 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4989 tmp->expression.next = (ast_expression*)*storebase;
4994 /* there may be a name now */
4995 if (parser->tok == TOKEN_IDENT) {
4996 name = util_strdup(parser_tokval(parser));
4998 if (!parser_next(parser)) {
5000 parseerror(parser, "error after variable or field declaration");
5005 /* now this may be an array */
5006 if (parser->tok == '[') {
5008 var = parse_arraysize(parser, var);
5013 /* This is the point where we can turn it into a field */
5015 /* turn it into a field if desired */
5016 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5017 tmp->expression.next = (ast_expression*)var;
5021 /* now there may be function parens again */
5022 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5023 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5024 if (parser->tok == '(' && wasarray)
5025 parseerror(parser, "arrays as part of a return type is not supported");
5026 while (parser->tok == '(') {
5027 var = parse_parameter_list(parser, var);
5035 /* finally name it */
5037 if (!ast_value_set_name(var, name)) {
5039 parseerror(parser, "internal error: failed to set name");
5042 /* free the name, ast_value_set_name duplicates */
5049 static bool parse_typedef(parser_t *parser)
5051 ast_value *typevar, *oldtype;
5052 ast_expression *old;
5054 typevar = parse_typename(parser, NULL, NULL);
5059 if ( (old = parser_find_var(parser, typevar->name)) ) {
5060 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5061 " -> `%s` has been declared here: %s:%i",
5062 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5063 ast_delete(typevar);
5067 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5068 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5069 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5070 ast_delete(typevar);
5074 vec_push(parser->_typedefs, typevar);
5075 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5077 if (parser->tok != ';') {
5078 parseerror(parser, "expected semicolon after typedef");
5081 if (!parser_next(parser)) {
5082 parseerror(parser, "parse error after typedef");
5089 static const char *cvq_to_str(int cvq) {
5091 case CV_NONE: return "none";
5092 case CV_VAR: return "`var`";
5093 case CV_CONST: return "`const`";
5094 default: return "<INVALID>";
5098 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5101 if (proto->cvq != var->cvq) {
5102 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5103 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5104 parser->tok == '='))
5106 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5107 "`%s` declared with different qualifiers: %s\n"
5108 " -> previous declaration here: %s:%i uses %s",
5109 var->name, cvq_to_str(var->cvq),
5110 ast_ctx(proto).file, ast_ctx(proto).line,
5111 cvq_to_str(proto->cvq));
5114 av = (var ->expression.flags & AST_FLAG_NORETURN);
5115 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5117 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5118 "`%s` declared with different attributes%s\n"
5119 " -> previous declaration here: %s:%i",
5120 var->name, (av ? ": noreturn" : ""),
5121 ast_ctx(proto).file, ast_ctx(proto).line,
5122 (ao ? ": noreturn" : ""));
5127 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)
5131 ast_expression *old;
5135 ast_value *basetype = NULL;
5137 bool isparam = false;
5138 bool isvector = false;
5139 bool cleanvar = true;
5140 bool wasarray = false;
5142 ast_member *me[3] = { NULL, NULL, NULL };
5144 if (!localblock && is_static)
5145 parseerror(parser, "`static` qualifier is not supported in global scope");
5147 /* get the first complete variable */
5148 var = parse_typename(parser, &basetype, cached_typedef);
5151 ast_delete(basetype);
5159 /* Part 0: finish the type */
5160 if (parser->tok == '(') {
5161 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5162 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5163 var = parse_parameter_list(parser, var);
5169 /* we only allow 1-dimensional arrays */
5170 if (parser->tok == '[') {
5172 var = parse_arraysize(parser, var);
5178 if (parser->tok == '(' && wasarray) {
5179 parseerror(parser, "arrays as part of a return type is not supported");
5180 /* we'll still parse the type completely for now */
5182 /* for functions returning functions */
5183 while (parser->tok == '(') {
5184 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5185 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5186 var = parse_parameter_list(parser, var);
5193 var->cvq = qualifier;
5194 var->expression.flags |= qflags;
5197 * store the vstring back to var for alias and
5198 * deprecation messages.
5200 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5201 var->expression.flags & AST_FLAG_ALIAS)
5202 var->desc = vstring;
5205 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5206 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5207 * is then filled with the previous definition and the parameter-names replaced.
5209 if (!strcmp(var->name, "nil")) {
5210 if (OPTS_FLAG(UNTYPED_NIL)) {
5211 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5212 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5214 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5217 /* Deal with end_sys_ vars */
5219 if (!strcmp(var->name, "end_sys_globals")) {
5221 parser->crc_globals = vec_size(parser->globals);
5224 else if (!strcmp(var->name, "end_sys_fields")) {
5226 parser->crc_fields = vec_size(parser->fields);
5229 if (was_end && var->expression.vtype == TYPE_FIELD) {
5230 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5231 "global '%s' hint should not be a field",
5232 parser_tokval(parser)))
5239 if (!nofields && var->expression.vtype == TYPE_FIELD)
5241 /* deal with field declarations */
5242 old = parser_find_field(parser, var->name);
5244 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5245 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5254 parseerror(parser, "field `%s` already declared here: %s:%i",
5255 var->name, ast_ctx(old).file, ast_ctx(old).line);
5260 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5261 (old = parser_find_global(parser, var->name)))
5263 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5264 parseerror(parser, "field `%s` already declared here: %s:%i",
5265 var->name, ast_ctx(old).file, ast_ctx(old).line);
5272 /* deal with other globals */
5273 old = parser_find_global(parser, var->name);
5274 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5276 /* This is a function which had a prototype */
5277 if (!ast_istype(old, ast_value)) {
5278 parseerror(parser, "internal error: prototype is not an ast_value");
5282 proto = (ast_value*)old;
5283 proto->desc = var->desc;
5284 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5285 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5287 ast_ctx(proto).file, ast_ctx(proto).line);
5291 /* we need the new parameter-names */
5292 for (i = 0; i < vec_size(proto->expression.params); ++i)
5293 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5294 if (!parser_check_qualifiers(parser, var, proto)) {
5301 proto->expression.flags |= var->expression.flags;
5309 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5310 "global `%s` already declared here: %s:%i",
5311 var->name, ast_ctx(old).file, ast_ctx(old).line))
5316 proto = (ast_value*)old;
5317 if (!ast_istype(old, ast_value)) {
5318 parseerror(parser, "internal error: not an ast_value");
5323 if (!parser_check_qualifiers(parser, var, proto)) {
5328 proto->expression.flags |= var->expression.flags;
5332 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5333 (old = parser_find_field(parser, var->name)))
5335 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5336 parseerror(parser, "global `%s` already declared here: %s:%i",
5337 var->name, ast_ctx(old).file, ast_ctx(old).line);
5344 else /* it's not a global */
5346 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5347 if (old && !isparam) {
5348 parseerror(parser, "local `%s` already declared here: %s:%i",
5349 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5353 old = parser_find_local(parser, var->name, 0, &isparam);
5354 if (old && isparam) {
5355 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5356 "local `%s` is shadowing a parameter", var->name))
5358 parseerror(parser, "local `%s` already declared here: %s:%i",
5359 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5363 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5371 /* in a noref section we simply bump the usecount */
5372 if (noref || parser->noref)
5376 * Create the global/local, and deal with vector types.
5379 if (var->expression.vtype == TYPE_VECTOR)
5381 else if (var->expression.vtype == TYPE_FIELD &&
5382 var->expression.next->expression.vtype == TYPE_VECTOR)
5386 if (!create_vector_members(var, me)) {
5393 /* deal with global variables, fields, functions */
5394 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5395 var->isfield = true;
5396 vec_push(parser->fields, (ast_expression*)var);
5397 util_htset(parser->htfields, var->name, var);
5399 for (i = 0; i < 3; ++i) {
5400 vec_push(parser->fields, (ast_expression*)me[i]);
5401 util_htset(parser->htfields, me[i]->name, me[i]);
5406 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5407 parser_addglobal(parser, var->name, (ast_expression*)var);
5409 for (i = 0; i < 3; ++i) {
5410 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5414 ast_expression *find = parser_find_global(parser, var->desc);
5417 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5421 if (var->expression.vtype != find->expression.vtype) {
5425 ast_type_to_string(find, ty1, sizeof(ty1));
5426 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5428 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5435 * add alias to aliases table and to corrector
5436 * so corrections can apply for aliases as well.
5438 util_htset(parser->aliases, var->name, find);
5441 * add to corrector so corrections can work
5442 * even for aliases too.
5445 vec_last(parser->correct_variables),
5446 &vec_last(parser->correct_variables_score),
5450 /* generate aliases for vector components */
5454 util_asprintf(&buffer[0], "%s_x", var->desc);
5455 util_asprintf(&buffer[1], "%s_y", var->desc);
5456 util_asprintf(&buffer[2], "%s_z", var->desc);
5458 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5459 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5460 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5467 * add to corrector so corrections can work
5468 * even for aliases too.
5471 vec_last(parser->correct_variables),
5472 &vec_last(parser->correct_variables_score),
5476 vec_last(parser->correct_variables),
5477 &vec_last(parser->correct_variables_score),
5481 vec_last(parser->correct_variables),
5482 &vec_last(parser->correct_variables_score),
5490 /* a static adds itself to be generated like any other global
5491 * but is added to the local namespace instead
5493 char *defname = NULL;
5494 size_t prefix_len, ln;
5496 ln = strlen(parser->function->name);
5497 vec_append(defname, ln, parser->function->name);
5499 vec_append(defname, 2, "::");
5500 /* remember the length up to here */
5501 prefix_len = vec_size(defname);
5503 /* Add it to the local scope */
5504 util_htset(vec_last(parser->variables), var->name, (void*)var);
5508 vec_last(parser->correct_variables),
5509 &vec_last(parser->correct_variables_score),
5513 /* now rename the global */
5514 ln = strlen(var->name);
5515 vec_append(defname, ln, var->name);
5516 ast_value_set_name(var, defname);
5518 /* push it to the to-be-generated globals */
5519 vec_push(parser->globals, (ast_expression*)var);
5521 /* same game for the vector members */
5523 for (i = 0; i < 3; ++i) {
5524 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5528 vec_last(parser->correct_variables),
5529 &vec_last(parser->correct_variables_score),
5533 vec_shrinkto(defname, prefix_len);
5534 ln = strlen(me[i]->name);
5535 vec_append(defname, ln, me[i]->name);
5536 ast_member_set_name(me[i], defname);
5538 vec_push(parser->globals, (ast_expression*)me[i]);
5543 vec_push(localblock->locals, var);
5544 parser_addlocal(parser, var->name, (ast_expression*)var);
5546 for (i = 0; i < 3; ++i) {
5547 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5548 ast_block_collect(localblock, (ast_expression*)me[i]);
5554 me[0] = me[1] = me[2] = NULL;
5559 if (var->expression.vtype == TYPE_ARRAY) {
5561 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5562 if (!parser_create_array_setter(parser, var, name))
5564 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5565 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5568 else if (!localblock && !nofields &&
5569 var->expression.vtype == TYPE_FIELD &&
5570 var->expression.next->expression.vtype == TYPE_ARRAY)
5573 ast_expression *telem;
5575 ast_value *array = (ast_value*)var->expression.next;
5577 if (!ast_istype(var->expression.next, ast_value)) {
5578 parseerror(parser, "internal error: field element type must be an ast_value");
5582 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5583 if (!parser_create_array_field_setter(parser, array, name))
5586 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5587 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5588 tfield->expression.next = telem;
5589 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5590 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5598 if (parser->tok == ';') {
5599 ast_delete(basetype);
5600 if (!parser_next(parser)) {
5601 parseerror(parser, "error after variable declaration");
5607 if (parser->tok == ',')
5611 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5614 parseerror(parser, "missing comma or semicolon while parsing variables");
5618 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5619 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5620 "initializing expression turns variable `%s` into a constant in this standard",
5627 if (parser->tok != '{') {
5628 if (parser->tok != '=') {
5629 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5633 if (!parser_next(parser)) {
5634 parseerror(parser, "error parsing initializer");
5638 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5639 parseerror(parser, "expected '=' before function body in this standard");
5642 if (parser->tok == '#') {
5643 ast_function *func = NULL;
5646 parseerror(parser, "cannot declare builtins within functions");
5649 if (var->expression.vtype != TYPE_FUNCTION) {
5650 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5653 if (!parser_next(parser)) {
5654 parseerror(parser, "expected builtin number");
5657 if (parser->tok != TOKEN_INTCONST) {
5658 parseerror(parser, "builtin number must be an integer constant");
5661 if (parser_token(parser)->constval.i < 0) {
5662 parseerror(parser, "builtin number must be an integer greater than zero");
5666 if (var->hasvalue) {
5667 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5668 "builtin `%s` has already been defined\n"
5669 " -> previous declaration here: %s:%i",
5670 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5674 func = ast_function_new(ast_ctx(var), var->name, var);
5676 parseerror(parser, "failed to allocate function for `%s`", var->name);
5679 vec_push(parser->functions, func);
5681 func->builtin = -parser_token(parser)->constval.i-1;
5684 if (!parser_next(parser)) {
5685 parseerror(parser, "expected comma or semicolon");
5687 ast_function_delete(func);
5688 var->constval.vfunc = NULL;
5692 else if (parser->tok == '{' || parser->tok == '[')
5695 parseerror(parser, "cannot declare functions within functions");
5700 ast_ctx(proto) = parser_ctx(parser);
5702 if (!parse_function_body(parser, var))
5704 ast_delete(basetype);
5705 for (i = 0; i < vec_size(parser->gotos); ++i)
5706 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5707 vec_free(parser->gotos);
5708 vec_free(parser->labels);
5711 ast_expression *cexp;
5714 cexp = parse_expression_leave(parser, true, false, false);
5719 cval = (ast_value*)cexp;
5720 if (cval != parser->nil &&
5721 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5724 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5728 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5729 qualifier != CV_VAR)
5731 var->cvq = CV_CONST;
5733 if (cval == parser->nil)
5734 var->expression.flags |= AST_FLAG_INITIALIZED;
5737 var->hasvalue = true;
5738 if (cval->expression.vtype == TYPE_STRING)
5739 var->constval.vstring = parser_strdup(cval->constval.vstring);
5740 else if (cval->expression.vtype == TYPE_FIELD)
5741 var->constval.vfield = cval;
5743 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5749 shunt sy = { NULL, NULL, NULL, NULL };
5752 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5753 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5754 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5755 if (!parser_sy_apply_operator(parser, &sy))
5758 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5759 parseerror(parser, "internal error: leaked operands");
5760 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5770 if (parser->tok == ',') {
5771 if (!parser_next(parser)) {
5772 parseerror(parser, "expected another variable");
5776 if (parser->tok != TOKEN_IDENT) {
5777 parseerror(parser, "expected another variable");
5780 var = ast_value_copy(basetype);
5782 ast_value_set_name(var, parser_tokval(parser));
5783 if (!parser_next(parser)) {
5784 parseerror(parser, "error parsing variable declaration");
5790 if (parser->tok != ';') {
5791 parseerror(parser, "missing semicolon after variables");
5795 if (!parser_next(parser)) {
5796 parseerror(parser, "parse error after variable declaration");
5800 ast_delete(basetype);
5804 if (cleanvar && var)
5806 ast_delete(basetype);
5810 ast_delete(basetype);
5811 if (cleanvar && var)
5813 if (me[0]) ast_member_delete(me[0]);
5814 if (me[1]) ast_member_delete(me[1]);
5815 if (me[2]) ast_member_delete(me[2]);
5819 static bool parser_global_statement(parser_t *parser)
5823 bool is_static = false;
5824 uint32_t qflags = 0;
5825 ast_value *istype = NULL;
5826 char *vstring = NULL;
5828 if (parser->tok == TOKEN_IDENT)
5829 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5831 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5833 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5835 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5837 if (cvq == CV_WRONG)
5839 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5841 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5843 return parse_enum(parser);
5845 else if (parser->tok == TOKEN_KEYWORD)
5847 if (!strcmp(parser_tokval(parser), "typedef")) {
5848 if (!parser_next(parser)) {
5849 parseerror(parser, "expected type definition after 'typedef'");
5852 return parse_typedef(parser);
5854 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5857 else if (parser->tok == '#')
5859 return parse_pragma(parser);
5861 else if (parser->tok == '$')
5863 if (!parser_next(parser)) {
5864 parseerror(parser, "parse error");
5870 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5876 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5878 return util_crc16(old, str, strlen(str));
5881 static void progdefs_crc_file(const char *str)
5883 /* write to progdefs.h here */
5887 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5889 old = progdefs_crc_sum(old, str);
5890 progdefs_crc_file(str);
5894 static void generate_checksum(parser_t *parser)
5896 uint16_t crc = 0xFFFF;
5900 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5901 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5903 progdefs_crc_file("\tint\tpad;\n");
5904 progdefs_crc_file("\tint\tofs_return[3];\n");
5905 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5906 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5907 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5908 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5909 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5910 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5911 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5912 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5914 for (i = 0; i < parser->crc_globals; ++i) {
5915 if (!ast_istype(parser->globals[i], ast_value))
5917 value = (ast_value*)(parser->globals[i]);
5918 switch (value->expression.vtype) {
5919 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5920 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5921 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5922 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5924 crc = progdefs_crc_both(crc, "\tint\t");
5927 crc = progdefs_crc_both(crc, value->name);
5928 crc = progdefs_crc_both(crc, ";\n");
5930 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5931 for (i = 0; i < parser->crc_fields; ++i) {
5932 if (!ast_istype(parser->fields[i], ast_value))
5934 value = (ast_value*)(parser->fields[i]);
5935 switch (value->expression.next->expression.vtype) {
5936 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5937 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5938 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5939 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5941 crc = progdefs_crc_both(crc, "\tint\t");
5944 crc = progdefs_crc_both(crc, value->name);
5945 crc = progdefs_crc_both(crc, ";\n");
5947 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5949 parser->code->crc = crc;
5952 parser_t *parser_create()
5958 parser = (parser_t*)mem_a(sizeof(parser_t));
5962 memset(parser, 0, sizeof(*parser));
5964 if (!(parser->code = code_init())) {
5970 for (i = 0; i < operator_count; ++i) {
5971 if (operators[i].id == opid1('=')) {
5972 parser->assign_op = operators+i;
5976 if (!parser->assign_op) {
5977 printf("internal error: initializing parser: failed to find assign operator\n");
5982 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5983 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5984 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5985 vec_push(parser->_blocktypedefs, 0);
5987 parser->aliases = util_htnew(PARSER_HT_SIZE);
5989 parser->ht_imm_string = util_htnew(512);
5992 vec_push(parser->correct_variables, correct_trie_new());
5993 vec_push(parser->correct_variables_score, NULL);
5995 empty_ctx.file = "<internal>";
5997 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5998 parser->nil->cvq = CV_CONST;
5999 if (OPTS_FLAG(UNTYPED_NIL))
6000 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6002 parser->max_param_count = 1;
6004 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6005 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6006 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6008 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6009 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6010 parser->reserved_version->cvq = CV_CONST;
6011 parser->reserved_version->hasvalue = true;
6012 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6013 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6015 parser->reserved_version = NULL;
6021 bool parser_compile(parser_t *parser)
6023 /* initial lexer/parser state */
6024 parser->lex->flags.noops = true;
6026 if (parser_next(parser))
6028 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6030 if (!parser_global_statement(parser)) {
6031 if (parser->tok == TOKEN_EOF)
6032 parseerror(parser, "unexpected eof");
6033 else if (compile_errors)
6034 parseerror(parser, "there have been errors, bailing out");
6035 lex_close(parser->lex);
6041 parseerror(parser, "parse error");
6042 lex_close(parser->lex);
6047 lex_close(parser->lex);
6050 return !compile_errors;
6053 bool parser_compile_file(parser_t *parser, const char *filename)
6055 parser->lex = lex_open(filename);
6057 con_err("failed to open file \"%s\"\n", filename);
6060 return parser_compile(parser);
6063 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6065 parser->lex = lex_open_string(str, len, name);
6067 con_err("failed to create lexer for string \"%s\"\n", name);
6070 return parser_compile(parser);
6073 void parser_cleanup(parser_t *parser)
6076 for (i = 0; i < vec_size(parser->accessors); ++i) {
6077 ast_delete(parser->accessors[i]->constval.vfunc);
6078 parser->accessors[i]->constval.vfunc = NULL;
6079 ast_delete(parser->accessors[i]);
6081 for (i = 0; i < vec_size(parser->functions); ++i) {
6082 ast_delete(parser->functions[i]);
6084 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6085 ast_delete(parser->imm_vector[i]);
6087 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6088 ast_delete(parser->imm_string[i]);
6090 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6091 ast_delete(parser->imm_float[i]);
6093 for (i = 0; i < vec_size(parser->fields); ++i) {
6094 ast_delete(parser->fields[i]);
6096 for (i = 0; i < vec_size(parser->globals); ++i) {
6097 ast_delete(parser->globals[i]);
6099 vec_free(parser->accessors);
6100 vec_free(parser->functions);
6101 vec_free(parser->imm_vector);
6102 vec_free(parser->imm_string);
6103 util_htdel(parser->ht_imm_string);
6104 vec_free(parser->imm_float);
6105 vec_free(parser->globals);
6106 vec_free(parser->fields);
6108 for (i = 0; i < vec_size(parser->variables); ++i)
6109 util_htdel(parser->variables[i]);
6110 vec_free(parser->variables);
6111 vec_free(parser->_blocklocals);
6112 vec_free(parser->_locals);
6115 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6116 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6118 vec_free(parser->correct_variables);
6119 vec_free(parser->correct_variables_score);
6122 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6123 ast_delete(parser->_typedefs[i]);
6124 vec_free(parser->_typedefs);
6125 for (i = 0; i < vec_size(parser->typedefs); ++i)
6126 util_htdel(parser->typedefs[i]);
6127 vec_free(parser->typedefs);
6128 vec_free(parser->_blocktypedefs);
6130 vec_free(parser->_block_ctx);
6132 vec_free(parser->labels);
6133 vec_free(parser->gotos);
6134 vec_free(parser->breaks);
6135 vec_free(parser->continues);
6137 ast_value_delete(parser->nil);
6139 ast_value_delete(parser->const_vec[0]);
6140 ast_value_delete(parser->const_vec[1]);
6141 ast_value_delete(parser->const_vec[2]);
6143 util_htdel(parser->aliases);
6145 intrin_intrinsics_destroy(parser);
6150 bool parser_finish(parser_t *parser, const char *output)
6156 if (compile_errors) {
6157 con_out("*** there were compile errors\n");
6161 ir = ir_builder_new("gmqcc_out");
6163 con_out("failed to allocate builder\n");
6167 for (i = 0; i < vec_size(parser->fields); ++i) {
6170 if (!ast_istype(parser->fields[i], ast_value))
6172 field = (ast_value*)parser->fields[i];
6173 hasvalue = field->hasvalue;
6174 field->hasvalue = false;
6175 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6176 con_out("failed to generate field %s\n", field->name);
6177 ir_builder_delete(ir);
6182 ast_expression *subtype;
6183 field->hasvalue = true;
6184 subtype = field->expression.next;
6185 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6186 if (subtype->expression.vtype == TYPE_FIELD)
6187 ifld->fieldtype = subtype->expression.next->expression.vtype;
6188 else if (subtype->expression.vtype == TYPE_FUNCTION)
6189 ifld->outtype = subtype->expression.next->expression.vtype;
6190 (void)!ir_value_set_field(field->ir_v, ifld);
6193 for (i = 0; i < vec_size(parser->globals); ++i) {
6195 if (!ast_istype(parser->globals[i], ast_value))
6197 asvalue = (ast_value*)(parser->globals[i]);
6198 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6199 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6200 "unused global: `%s`", asvalue->name);
6202 if (!ast_global_codegen(asvalue, ir, false)) {
6203 con_out("failed to generate global %s\n", asvalue->name);
6204 ir_builder_delete(ir);
6208 /* Build function vararg accessor ast tree now before generating
6209 * immediates, because the accessors may add new immediates
6211 for (i = 0; i < vec_size(parser->functions); ++i) {
6212 ast_function *f = parser->functions[i];
6214 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6215 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6216 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6217 con_out("failed to generate vararg setter for %s\n", f->name);
6218 ir_builder_delete(ir);
6221 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6222 con_out("failed to generate vararg getter for %s\n", f->name);
6223 ir_builder_delete(ir);
6227 ast_delete(f->varargs);
6232 /* Now we can generate immediates */
6233 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6234 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6235 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6236 ir_builder_delete(ir);
6240 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6241 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6242 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6243 ir_builder_delete(ir);
6247 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6248 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6249 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6250 ir_builder_delete(ir);
6254 for (i = 0; i < vec_size(parser->globals); ++i) {
6256 if (!ast_istype(parser->globals[i], ast_value))
6258 asvalue = (ast_value*)(parser->globals[i]);
6259 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6261 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6262 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6263 "uninitialized constant: `%s`",
6265 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6266 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6267 "uninitialized global: `%s`",
6270 if (!ast_generate_accessors(asvalue, ir)) {
6271 ir_builder_delete(ir);
6275 for (i = 0; i < vec_size(parser->fields); ++i) {
6277 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6279 if (!ast_istype((ast_expression*)asvalue, ast_value))
6281 if (asvalue->expression.vtype != TYPE_ARRAY)
6283 if (!ast_generate_accessors(asvalue, ir)) {
6284 ir_builder_delete(ir);
6288 if (parser->reserved_version &&
6289 !ast_global_codegen(parser->reserved_version, ir, false))
6291 con_out("failed to generate reserved::version");
6292 ir_builder_delete(ir);
6295 for (i = 0; i < vec_size(parser->functions); ++i) {
6296 ast_function *f = parser->functions[i];
6297 if (!ast_function_codegen(f, ir)) {
6298 con_out("failed to generate function %s\n", f->name);
6299 ir_builder_delete(ir);
6303 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6304 ir_builder_dump(ir, con_out);
6305 for (i = 0; i < vec_size(parser->functions); ++i) {
6306 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6307 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6308 ir_builder_delete(ir);
6313 if (compile_Werrors) {
6314 con_out("*** there were warnings treated as errors\n");
6315 compile_show_werrors();
6320 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6321 ir_builder_dump(ir, con_out);
6323 generate_checksum(parser);
6325 if (!ir_builder_generate(parser->code, ir, output)) {
6326 con_out("*** failed to generate output file\n");
6327 ir_builder_delete(ir);
6332 ir_builder_delete(ir);