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);
269 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
274 for (i = 0; i < vec_size(parser->imm_string); ++i) {
275 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
276 return parser->imm_string[i];
281 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
282 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
284 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
286 out->hasvalue = true;
288 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
289 out->constval.vstring = parser_strdup(str);
290 vec_push(parser->imm_string, out);
291 util_htseth(parser->ht_imm_string, str, hash, out);
295 static ast_value* parser_const_vector(parser_t *parser, vector v)
299 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
300 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
301 return parser->imm_vector[i];
303 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
305 out->hasvalue = true;
307 out->constval.vvec = v;
308 vec_push(parser->imm_vector, out);
312 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
318 return parser_const_vector(parser, v);
321 static ast_value* parser_const_vector_0(parser_t *parser)
323 if (!parser->imm_vector_zero)
324 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
325 return parser->imm_vector_zero;
328 static ast_expression* parser_find_field(parser_t *parser, const char *name)
330 return ( ast_expression*)util_htget(parser->htfields, name);
333 static ast_expression* parser_find_label(parser_t *parser, const char *name)
336 for(i = 0; i < vec_size(parser->labels); i++)
337 if (!strcmp(parser->labels[i]->name, name))
338 return (ast_expression*)parser->labels[i];
342 static ast_expression* parser_find_global(parser_t *parser, const char *name)
344 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
347 return (ast_expression*)util_htget(parser->htglobals, name);
350 static ast_expression* parser_find_param(parser_t *parser, const char *name)
354 if (!parser->function)
356 fun = parser->function->vtype;
357 for (i = 0; i < vec_size(fun->expression.params); ++i) {
358 if (!strcmp(fun->expression.params[i]->name, name))
359 return (ast_expression*)(fun->expression.params[i]);
364 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
369 hash = util_hthash(parser->htglobals, name);
372 for (i = vec_size(parser->variables); i > upto;) {
374 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
378 return parser_find_param(parser, name);
381 static ast_expression* parser_find_var(parser_t *parser, const char *name)
385 v = parser_find_local(parser, name, 0, &dummy);
386 if (!v) v = parser_find_global(parser, name);
390 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
394 hash = util_hthash(parser->typedefs[0], name);
396 for (i = vec_size(parser->typedefs); i > upto;) {
398 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
404 /* include intrinsics */
409 size_t etype; /* 0 = expression, others are operators */
413 ast_block *block; /* for commas and function calls */
432 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
443 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
447 e.out = (ast_expression*)v;
454 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
456 e.etype = 1 + (op - operators);
465 static sy_elem syparen(lex_ctx ctx, size_t off) {
476 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
477 * so we need to rotate it to become ent.(foo[n]).
479 static bool rotate_entfield_array_index_nodes(ast_expression **out)
481 ast_array_index *index, *oldindex;
482 ast_entfield *entfield;
486 ast_expression *entity;
488 lex_ctx ctx = ast_ctx(*out);
490 if (!ast_istype(*out, ast_array_index))
492 index = (ast_array_index*)*out;
494 if (!ast_istype(index->array, ast_entfield))
496 entfield = (ast_entfield*)index->array;
498 if (!ast_istype(entfield->field, ast_value))
500 field = (ast_value*)entfield->field;
503 entity = entfield->entity;
507 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
508 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
509 *out = (ast_expression*)entfield;
511 oldindex->array = NULL;
512 oldindex->index = NULL;
513 ast_delete(oldindex);
518 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
520 switch (v->expression.vtype) {
522 return !!v->constval.vfloat;
524 return !!v->constval.vint;
526 if (OPTS_FLAG(CORRECT_LOGIC))
527 return v->constval.vvec.x &&
528 v->constval.vvec.y &&
531 return !!(v->constval.vvec.x);
533 if (!v->constval.vstring)
535 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
537 return !!v->constval.vstring[0];
539 compile_error(ctx, "internal error: immediate_is_true on invalid type");
540 return !!v->constval.vfunc;
544 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
548 ast_expression *out = NULL;
549 ast_expression *exprs[3];
550 ast_block *blocks[3];
551 ast_value *asvalue[3];
552 ast_binstore *asbinstore;
553 size_t i, assignop, addop, subop;
554 qcint generated_op = 0;
559 if (!vec_size(sy->ops)) {
560 parseerror(parser, "internal error: missing operator");
564 if (vec_last(sy->ops).isparen) {
565 parseerror(parser, "unmatched parenthesis");
569 op = &operators[vec_last(sy->ops).etype - 1];
570 ctx = vec_last(sy->ops).ctx;
572 if (vec_size(sy->out) < op->operands) {
573 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
574 op->op, (int)op->id);
578 vec_shrinkby(sy->ops, 1);
580 /* op(:?) has no input and no output */
584 vec_shrinkby(sy->out, op->operands);
585 for (i = 0; i < op->operands; ++i) {
586 exprs[i] = sy->out[vec_size(sy->out)+i].out;
587 blocks[i] = sy->out[vec_size(sy->out)+i].block;
588 asvalue[i] = (ast_value*)exprs[i];
590 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
591 !(i != 0 && op->id == opid2('?',':')) &&
592 !(i == 1 && op->id == opid1('.')))
594 if (ast_istype(exprs[i], ast_label))
595 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
597 compile_error(ast_ctx(exprs[i]), "not an expression");
598 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
602 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
603 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
607 #define NotSameType(T) \
608 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
609 exprs[0]->expression.vtype != T)
610 #define CanConstFold1(A) \
611 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
612 (A)->expression.vtype != TYPE_FUNCTION)
613 #define CanConstFold(A, B) \
614 (CanConstFold1(A) && CanConstFold1(B))
615 #define ConstV(i) (asvalue[(i)]->constval.vvec)
616 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
617 #define ConstS(i) (asvalue[(i)]->constval.vstring)
621 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
625 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
626 exprs[1]->expression.vtype == TYPE_NOEXPR)
628 if (exprs[1] == (ast_expression*)parser->const_vec[0])
629 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
630 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
631 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
632 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
633 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
635 compile_error(ctx, "access to invalid vector component");
639 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
640 if (exprs[1]->expression.vtype != TYPE_FIELD) {
641 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
644 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
646 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
647 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
651 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
657 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
658 !(exprs[0]->expression.vtype == TYPE_FIELD &&
659 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
661 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
662 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
665 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
666 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
667 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
670 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
671 if (rotate_entfield_array_index_nodes(&out))
674 /* This is not broken in fteqcc anymore */
675 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
676 /* this error doesn't need to make us bail out */
677 (void)!parsewarning(parser, WARN_EXTENSIONS,
678 "accessing array-field members of an entity without parenthesis\n"
679 " -> this is an extension from -std=gmqcc");
686 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
687 vec_push(sy->out, syexp(ctx, exprs[0]));
688 vec_push(sy->out, syexp(ctx, exprs[1]));
689 vec_last(sy->argc)++;
693 if (!ast_block_add_expr(blocks[0], exprs[1]))
696 blocks[0] = ast_block_new(ctx);
697 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
698 !ast_block_add_expr(blocks[0], exprs[1]))
703 ast_block_set_type(blocks[0], exprs[1]);
705 vec_push(sy->out, syblock(ctx, blocks[0]));
712 switch (exprs[0]->expression.vtype) {
714 if (CanConstFold1(exprs[0]))
715 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
717 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
718 (ast_expression*)parser_const_float_0(parser),
722 if (CanConstFold1(exprs[0]))
723 out = (ast_expression*)parser_const_vector_f(parser,
724 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
726 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
727 (ast_expression*)parser_const_vector_0(parser),
731 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
732 type_name[exprs[0]->expression.vtype]);
738 switch (exprs[0]->expression.vtype) {
740 if (CanConstFold1(exprs[0]))
741 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
743 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
746 if (CanConstFold1(exprs[0]))
747 out = (ast_expression*)parser_const_float(parser,
748 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
750 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
753 if (CanConstFold1(exprs[0])) {
754 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
755 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
757 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
759 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
760 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
762 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
765 /* we don't constant-fold NOT for these types */
767 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
770 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
773 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
774 type_name[exprs[0]->expression.vtype]);
780 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
781 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
783 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
784 type_name[exprs[0]->expression.vtype],
785 type_name[exprs[1]->expression.vtype]);
788 switch (exprs[0]->expression.vtype) {
790 if (CanConstFold(exprs[0], exprs[1]))
792 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
795 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
798 if (CanConstFold(exprs[0], exprs[1]))
799 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
801 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
804 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
805 type_name[exprs[0]->expression.vtype],
806 type_name[exprs[1]->expression.vtype]);
811 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
812 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
814 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
815 type_name[exprs[1]->expression.vtype],
816 type_name[exprs[0]->expression.vtype]);
819 switch (exprs[0]->expression.vtype) {
821 if (CanConstFold(exprs[0], exprs[1]))
822 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
824 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
827 if (CanConstFold(exprs[0], exprs[1]))
828 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
830 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
833 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
834 type_name[exprs[1]->expression.vtype],
835 type_name[exprs[0]->expression.vtype]);
840 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
841 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
842 exprs[1]->expression.vtype == TYPE_FLOAT) &&
843 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
844 exprs[0]->expression.vtype == TYPE_FLOAT)
847 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
848 type_name[exprs[1]->expression.vtype],
849 type_name[exprs[0]->expression.vtype]);
852 switch (exprs[0]->expression.vtype) {
854 if (exprs[1]->expression.vtype == TYPE_VECTOR)
856 if (CanConstFold(exprs[0], exprs[1]))
857 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
859 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
863 if (CanConstFold(exprs[0], exprs[1]))
864 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
866 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
870 if (exprs[1]->expression.vtype == TYPE_FLOAT)
872 if (CanConstFold(exprs[0], exprs[1]))
873 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
875 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
879 if (CanConstFold(exprs[0], exprs[1]))
880 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
881 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
882 vector vec = ConstV(0);
883 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
884 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
885 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
886 out->expression.node.keep = false;
887 ((ast_member*)out)->rvalue = true;
889 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
891 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
892 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
893 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
894 out->expression.node.keep = false;
895 ((ast_member*)out)->rvalue = true;
897 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
899 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
900 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
901 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
902 out->expression.node.keep = false;
903 ((ast_member*)out)->rvalue = true;
905 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
908 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
910 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
911 vector vec = ConstV(1);
912 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
913 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
914 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
915 out->expression.node.keep = false;
916 ((ast_member*)out)->rvalue = true;
918 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
920 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
921 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
922 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
923 out->expression.node.keep = false;
924 ((ast_member*)out)->rvalue = true;
926 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
928 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
929 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
930 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
931 out->expression.node.keep = false;
932 ((ast_member*)out)->rvalue = true;
934 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
937 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
940 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
944 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
945 type_name[exprs[1]->expression.vtype],
946 type_name[exprs[0]->expression.vtype]);
951 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
952 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
957 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
958 if (CanConstFold(exprs[0], exprs[1]))
959 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
961 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
963 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
964 if (CanConstFold(exprs[0], exprs[1]))
965 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
967 if (CanConstFold1(exprs[1])) {
968 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
970 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
971 (ast_expression*)parser_const_float_1(parser),
975 compile_error(ctx, "internal error: failed to generate division");
978 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
983 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
984 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
985 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
991 if (NotSameType(TYPE_FLOAT)) {
992 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
993 type_name[exprs[0]->expression.vtype],
994 type_name[exprs[1]->expression.vtype]);
997 if (CanConstFold(exprs[0], exprs[1])) {
998 out = (ast_expression*)parser_const_float(parser,
999 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
1001 /* generate a call to __builtin_mod */
1002 ast_expression *mod = intrin_func(parser, "mod");
1003 ast_call *call = NULL;
1004 if (!mod) return false; /* can return null for missing floor */
1006 call = ast_call_new(parser_ctx(parser), mod);
1007 vec_push(call->params, exprs[0]);
1008 vec_push(call->params, exprs[1]);
1010 out = (ast_expression*)call;
1014 case opid2('%','='):
1015 compile_error(ctx, "%= is unimplemented");
1020 if (NotSameType(TYPE_FLOAT)) {
1021 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1022 type_name[exprs[0]->expression.vtype],
1023 type_name[exprs[1]->expression.vtype]);
1026 if (CanConstFold(exprs[0], exprs[1]))
1027 out = (ast_expression*)parser_const_float(parser,
1028 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1029 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1031 out = (ast_expression*)ast_binary_new(ctx,
1032 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1033 exprs[0], exprs[1]);
1036 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1039 case opid2('<','<'):
1040 case opid2('>','>'):
1041 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1042 if (op->id == opid2('<','<'))
1043 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1045 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1048 case opid3('<','<','='):
1049 case opid3('>','>','='):
1050 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1053 case opid2('|','|'):
1054 generated_op += 1; /* INSTR_OR */
1055 case opid2('&','&'):
1056 generated_op += INSTR_AND;
1057 if (CanConstFold(exprs[0], exprs[1]))
1059 if (OPTS_FLAG(PERL_LOGIC)) {
1060 if (immediate_is_true(ctx, asvalue[0]))
1064 out = (ast_expression*)parser_const_float(parser,
1065 ( (generated_op == INSTR_OR)
1066 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1067 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1072 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1073 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1074 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1075 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1078 for (i = 0; i < 2; ++i) {
1079 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1080 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1082 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1084 exprs[i] = out; out = NULL;
1085 if (OPTS_FLAG(PERL_LOGIC)) {
1086 /* here we want to keep the right expressions' type */
1090 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1091 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1093 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1095 exprs[i] = out; out = NULL;
1096 if (OPTS_FLAG(PERL_LOGIC)) {
1097 /* here we want to keep the right expressions' type */
1102 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1106 case opid2('?',':'):
1107 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1108 compile_error(ctx, "mismatched parenthesis/ternary");
1112 if (!ast_compare_type(exprs[1], exprs[2])) {
1113 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1114 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1115 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1118 if (CanConstFold1(exprs[0]))
1119 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1121 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1124 case opid2('*', '*'):
1125 if (NotSameType(TYPE_FLOAT)) {
1126 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1134 if (CanConstFold(exprs[0], exprs[1])) {
1135 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1137 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1138 vec_push(gencall->params, exprs[0]);
1139 vec_push(gencall->params, exprs[1]);
1140 out = (ast_expression*)gencall;
1144 case opid3('<','=','>'): /* -1, 0, or 1 */
1145 if (NotSameType(TYPE_FLOAT)) {
1146 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1147 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1148 compile_error(ctx, "invalid types used in comparision: %s and %s",
1154 if (CanConstFold(exprs[0], exprs[1])) {
1155 if (ConstF(0) < ConstF(1))
1156 out = (ast_expression*)parser_const_float_neg1(parser);
1157 else if (ConstF(0) == ConstF(1))
1158 out = (ast_expression*)parser_const_float_0(parser);
1159 else if (ConstF(0) > ConstF(1))
1160 out = (ast_expression*)parser_const_float_1(parser);
1162 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1164 eq->refs = (ast_binary_ref)false; /* references nothing */
1167 out = (ast_expression*)ast_ternary_new(ctx,
1168 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1170 (ast_expression*)parser_const_float_neg1(parser),
1173 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1175 (ast_expression*)parser_const_float_0(parser),
1178 (ast_expression*)parser_const_float_1(parser)
1188 generated_op += 1; /* INSTR_GT */
1190 generated_op += 1; /* INSTR_LT */
1191 case opid2('>', '='):
1192 generated_op += 1; /* INSTR_GE */
1193 case opid2('<', '='):
1194 generated_op += INSTR_LE;
1195 if (NotSameType(TYPE_FLOAT)) {
1196 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1197 type_name[exprs[0]->expression.vtype],
1198 type_name[exprs[1]->expression.vtype]);
1201 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1203 case opid2('!', '='):
1204 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1205 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1206 type_name[exprs[0]->expression.vtype],
1207 type_name[exprs[1]->expression.vtype]);
1210 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1212 case opid2('=', '='):
1213 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1214 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1215 type_name[exprs[0]->expression.vtype],
1216 type_name[exprs[1]->expression.vtype]);
1219 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1223 if (ast_istype(exprs[0], ast_entfield)) {
1224 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1225 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1226 exprs[0]->expression.vtype == TYPE_FIELD &&
1227 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1229 assignop = type_storep_instr[TYPE_VECTOR];
1232 assignop = type_storep_instr[exprs[0]->expression.vtype];
1233 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1235 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1236 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1237 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1238 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1239 exprs[1]->expression.vtype == TYPE_FUNCTION)
1241 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1242 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1245 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1250 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1251 exprs[0]->expression.vtype == TYPE_FIELD &&
1252 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1254 assignop = type_store_instr[TYPE_VECTOR];
1257 assignop = type_store_instr[exprs[0]->expression.vtype];
1260 if (assignop == VINSTR_END) {
1261 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1262 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1263 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1265 else if (!ast_compare_type(exprs[0], exprs[1]))
1267 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1268 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1269 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1270 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1271 exprs[1]->expression.vtype == TYPE_FUNCTION)
1273 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1274 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1277 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1280 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1281 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1283 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1285 case opid3('+','+','P'):
1286 case opid3('-','-','P'):
1288 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1289 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1290 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1293 if (op->id == opid3('+','+','P'))
1294 addop = INSTR_ADD_F;
1296 addop = INSTR_SUB_F;
1297 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1298 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1300 if (ast_istype(exprs[0], ast_entfield)) {
1301 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1303 (ast_expression*)parser_const_float_1(parser));
1305 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1307 (ast_expression*)parser_const_float_1(parser));
1310 case opid3('S','+','+'):
1311 case opid3('S','-','-'):
1313 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1314 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1315 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1318 if (op->id == opid3('S','+','+')) {
1319 addop = INSTR_ADD_F;
1320 subop = INSTR_SUB_F;
1322 addop = INSTR_SUB_F;
1323 subop = INSTR_ADD_F;
1325 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1326 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1328 if (ast_istype(exprs[0], ast_entfield)) {
1329 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1331 (ast_expression*)parser_const_float_1(parser));
1333 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1335 (ast_expression*)parser_const_float_1(parser));
1339 out = (ast_expression*)ast_binary_new(ctx, subop,
1341 (ast_expression*)parser_const_float_1(parser));
1343 case opid2('+','='):
1344 case opid2('-','='):
1345 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1346 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1348 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1349 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1350 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1354 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1355 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1357 if (ast_istype(exprs[0], ast_entfield))
1358 assignop = type_storep_instr[exprs[0]->expression.vtype];
1360 assignop = type_store_instr[exprs[0]->expression.vtype];
1361 switch (exprs[0]->expression.vtype) {
1363 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1364 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1365 exprs[0], exprs[1]);
1368 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1369 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1370 exprs[0], exprs[1]);
1373 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1374 type_name[exprs[0]->expression.vtype],
1375 type_name[exprs[1]->expression.vtype]);
1379 case opid2('*','='):
1380 case opid2('/','='):
1381 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1382 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1383 exprs[0]->expression.vtype == TYPE_VECTOR))
1385 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1386 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1387 compile_error(ctx, "invalid types used in expression: %s and %s",
1391 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1392 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1394 if (ast_istype(exprs[0], ast_entfield))
1395 assignop = type_storep_instr[exprs[0]->expression.vtype];
1397 assignop = type_store_instr[exprs[0]->expression.vtype];
1398 switch (exprs[0]->expression.vtype) {
1400 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1401 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1402 exprs[0], exprs[1]);
1405 if (op->id == opid2('*','=')) {
1406 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1407 exprs[0], exprs[1]);
1409 /* there's no DIV_VF */
1410 if (CanConstFold1(exprs[1])) {
1411 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1413 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1414 (ast_expression*)parser_const_float_1(parser),
1418 compile_error(ctx, "internal error: failed to generate division");
1421 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1426 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1427 type_name[exprs[0]->expression.vtype],
1428 type_name[exprs[1]->expression.vtype]);
1432 case opid2('&','='):
1433 case opid2('|','='):
1434 if (NotSameType(TYPE_FLOAT)) {
1435 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1436 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1437 compile_error(ctx, "invalid types used in expression: %s and %s",
1441 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1442 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1444 if (ast_istype(exprs[0], ast_entfield))
1445 assignop = type_storep_instr[exprs[0]->expression.vtype];
1447 assignop = type_store_instr[exprs[0]->expression.vtype];
1448 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1449 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1450 exprs[0], exprs[1]);
1452 case opid3('&','~','='):
1453 /* This is like: a &= ~(b);
1454 * But QC has no bitwise-not, so we implement it as
1457 if (NotSameType(TYPE_FLOAT)) {
1458 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1459 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1460 compile_error(ctx, "invalid types used in expression: %s and %s",
1464 if (ast_istype(exprs[0], ast_entfield))
1465 assignop = type_storep_instr[exprs[0]->expression.vtype];
1467 assignop = type_store_instr[exprs[0]->expression.vtype];
1468 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1471 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1472 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1474 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1475 asbinstore->keep_dest = true;
1476 out = (ast_expression*)asbinstore;
1479 case opid2('~', 'P'):
1480 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1481 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1482 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1486 if(CanConstFold1(exprs[0]))
1487 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1489 out = (ast_expression*)
1490 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1496 compile_error(ctx, "failed to apply operator %s", op->op);
1500 vec_push(sy->out, syexp(ctx, out));
1504 static bool parser_close_call(parser_t *parser, shunt *sy)
1506 /* was a function call */
1507 ast_expression *fun;
1508 ast_value *funval = NULL;
1512 size_t paramcount, i;
1514 fid = vec_last(sy->ops).off;
1515 vec_shrinkby(sy->ops, 1);
1517 /* out[fid] is the function
1518 * everything above is parameters...
1520 if (!vec_size(sy->argc)) {
1521 parseerror(parser, "internal error: no argument counter available");
1525 paramcount = vec_last(sy->argc);
1528 if (vec_size(sy->out) < fid) {
1529 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1530 (unsigned long)vec_size(sy->out),
1532 (unsigned long)paramcount);
1536 fun = sy->out[fid].out;
1538 if (fun == intrinsic_debug_typestring) {
1540 if (fid+2 != vec_size(sy->out) ||
1541 vec_last(sy->out).block)
1543 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1546 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1547 ast_unref(vec_last(sy->out).out);
1548 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1549 (ast_expression*)parser_const_string(parser, ty, false));
1550 vec_shrinkby(sy->out, 1);
1554 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1558 if (fid+1 < vec_size(sy->out))
1561 if (fid+1 + paramcount != vec_size(sy->out)) {
1562 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1563 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1567 for (i = 0; i < paramcount; ++i)
1568 vec_push(call->params, sy->out[fid+1 + i].out);
1569 vec_shrinkby(sy->out, paramcount);
1570 (void)!ast_call_check_types(call);
1571 if (parser->max_param_count < paramcount)
1572 parser->max_param_count = paramcount;
1574 if (ast_istype(fun, ast_value)) {
1575 funval = (ast_value*)fun;
1576 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1577 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1579 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1583 /* overwrite fid, the function, with a call */
1584 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1586 if (fun->expression.vtype != TYPE_FUNCTION) {
1587 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1591 if (!fun->expression.next) {
1592 parseerror(parser, "could not determine function return type");
1595 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1597 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1599 return !parsewarning(parser, WARN_DEPRECATED,
1600 "call to function (which is marked deprecated)\n",
1601 "-> it has been declared here: %s:%i",
1602 ast_ctx(fun).file, ast_ctx(fun).line);
1605 return !parsewarning(parser, WARN_DEPRECATED,
1606 "call to `%s` (which is marked deprecated)\n"
1607 "-> `%s` declared here: %s:%i",
1608 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1610 return !parsewarning(parser, WARN_DEPRECATED,
1611 "call to `%s` (deprecated: %s)\n"
1612 "-> `%s` declared here: %s:%i",
1613 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1617 if (vec_size(fun->expression.params) != paramcount &&
1618 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1619 vec_size(fun->expression.params) < paramcount))
1621 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1623 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1624 "too %s parameters for call to %s: expected %i, got %i\n"
1625 " -> `%s` has been declared here: %s:%i",
1626 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1627 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1629 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1630 "too %s parameters for function call: expected %i, got %i\n"
1631 " -> it has been declared here: %s:%i",
1632 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1633 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1640 static bool parser_close_paren(parser_t *parser, shunt *sy)
1642 if (!vec_size(sy->ops)) {
1643 parseerror(parser, "unmatched closing paren");
1647 while (vec_size(sy->ops)) {
1648 if (vec_last(sy->ops).isparen) {
1649 if (vec_last(sy->paren) == PAREN_FUNC) {
1651 if (!parser_close_call(parser, sy))
1655 if (vec_last(sy->paren) == PAREN_EXPR) {
1657 if (!vec_size(sy->out)) {
1658 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1659 vec_shrinkby(sy->ops, 1);
1662 vec_shrinkby(sy->ops, 1);
1665 if (vec_last(sy->paren) == PAREN_INDEX) {
1667 /* pop off the parenthesis */
1668 vec_shrinkby(sy->ops, 1);
1669 /* then apply the index operator */
1670 if (!parser_sy_apply_operator(parser, sy))
1674 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1675 vec_last(sy->paren) = PAREN_TERNARY2;
1676 /* pop off the parenthesis */
1677 vec_shrinkby(sy->ops, 1);
1680 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1683 if (!parser_sy_apply_operator(parser, sy))
1689 static void parser_reclassify_token(parser_t *parser)
1692 for (i = 0; i < operator_count; ++i) {
1693 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1694 parser->tok = TOKEN_OPERATOR;
1700 static ast_expression* parse_vararg_do(parser_t *parser)
1702 ast_expression *idx, *out;
1704 ast_value *funtype = parser->function->vtype;
1706 lex_ctx ctx = parser_ctx(parser);
1708 if (!parser_next(parser) || parser->tok != '(') {
1709 parseerror(parser, "expected parameter index and type in parenthesis");
1712 if (!parser_next(parser)) {
1713 parseerror(parser, "error parsing parameter index");
1717 idx = parse_expression_leave(parser, true, false, false);
1721 if (parser->tok != ',') {
1723 parseerror(parser, "expected comma after parameter index");
1727 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1729 parseerror(parser, "expected typename for vararg");
1733 typevar = parse_typename(parser, NULL, NULL);
1739 if (parser->tok != ')') {
1741 ast_delete(typevar);
1742 parseerror(parser, "expected closing paren");
1747 if (!parser_next(parser)) {
1749 ast_delete(typevar);
1750 parseerror(parser, "parse error after vararg");
1755 if (!parser->function->varargs) {
1757 ast_delete(typevar);
1758 parseerror(parser, "function has no variable argument list");
1762 if (funtype->expression.varparam &&
1763 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1767 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1768 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1769 compile_error(ast_ctx(typevar),
1770 "function was declared to take varargs of type `%s`, requested type is: %s",
1774 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1775 ast_type_adopt(out, typevar);
1776 ast_delete(typevar);
1780 static ast_expression* parse_vararg(parser_t *parser)
1782 bool old_noops = parser->lex->flags.noops;
1784 ast_expression *out;
1786 parser->lex->flags.noops = true;
1787 out = parse_vararg_do(parser);
1789 parser->lex->flags.noops = old_noops;
1793 /* not to be exposed */
1794 extern bool ftepp_predef_exists(const char *name);
1796 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1798 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1799 parser->tok == TOKEN_IDENT &&
1800 !strcmp(parser_tokval(parser), "_"))
1802 /* a translatable string */
1805 parser->lex->flags.noops = true;
1806 if (!parser_next(parser) || parser->tok != '(') {
1807 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1810 parser->lex->flags.noops = false;
1811 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1812 parseerror(parser, "expected a constant string in translatable-string extension");
1815 val = parser_const_string(parser, parser_tokval(parser), true);
1818 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1820 if (!parser_next(parser) || parser->tok != ')') {
1821 parseerror(parser, "expected closing paren after translatable string");
1826 else if (parser->tok == TOKEN_DOTS)
1829 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1830 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1833 va = parse_vararg(parser);
1836 vec_push(sy->out, syexp(parser_ctx(parser), va));
1839 else if (parser->tok == TOKEN_FLOATCONST) {
1841 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1844 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1847 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1849 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1852 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1855 else if (parser->tok == TOKEN_STRINGCONST) {
1857 val = parser_const_string(parser, parser_tokval(parser), false);
1860 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1863 else if (parser->tok == TOKEN_VECTORCONST) {
1865 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1868 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1871 else if (parser->tok == TOKEN_IDENT)
1873 const char *ctoken = parser_tokval(parser);
1874 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1875 ast_expression *var;
1876 /* a_vector.{x,y,z} */
1877 if (!vec_size(sy->ops) ||
1878 !vec_last(sy->ops).etype ||
1879 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1880 (prev >= intrinsic_debug_typestring &&
1881 prev <= intrinsic_debug_typestring))
1883 /* When adding more intrinsics, fix the above condition */
1886 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1888 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1890 var = parser_find_var(parser, parser_tokval(parser));
1892 var = parser_find_field(parser, parser_tokval(parser));
1894 if (!var && with_labels) {
1895 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1897 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1898 var = (ast_expression*)lbl;
1899 vec_push(parser->labels, lbl);
1902 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1903 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1906 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1907 var = (ast_expression*)intrinsic_debug_typestring;
1909 /* now we try for the real intrinsic hashtable. If the string
1910 * begins with __builtin, we simply skip past it, otherwise we
1911 * use the identifier as is.
1913 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1914 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1918 char *correct = NULL;
1922 * sometimes people use preprocessing predefs without enabling them
1923 * i've done this thousands of times already myself. Lets check for
1924 * it in the predef table. And diagnose it better :)
1926 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1927 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1932 * TODO: determine the best score for the identifier: be it
1933 * a variable, a field.
1935 * We should also consider adding correction tables for
1936 * other things as well.
1938 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1940 correct_init(&corr);
1942 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1943 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1944 if (strcmp(correct, parser_tokval(parser))) {
1946 } else if (correct) {
1951 correct_free(&corr);
1954 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1959 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1965 if (ast_istype(var, ast_value)) {
1966 ((ast_value*)var)->uses++;
1968 else if (ast_istype(var, ast_member)) {
1969 ast_member *mem = (ast_member*)var;
1970 if (ast_istype(mem->owner, ast_value))
1971 ((ast_value*)(mem->owner))->uses++;
1974 vec_push(sy->out, syexp(parser_ctx(parser), var));
1977 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1981 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1983 ast_expression *expr = NULL;
1986 bool wantop = false;
1987 /* only warn once about an assignment in a truth value because the current code
1988 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1990 bool warn_truthvalue = true;
1992 /* count the parens because an if starts with one, so the
1993 * end of a condition is an unmatched closing paren
1997 memset(&sy, 0, sizeof(sy));
1999 parser->lex->flags.noops = false;
2001 parser_reclassify_token(parser);
2005 if (parser->tok == TOKEN_TYPENAME) {
2006 parseerror(parser, "unexpected typename");
2010 if (parser->tok == TOKEN_OPERATOR)
2012 /* classify the operator */
2013 const oper_info *op;
2014 const oper_info *olast = NULL;
2016 for (o = 0; o < operator_count; ++o) {
2017 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2018 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2019 !strcmp(parser_tokval(parser), operators[o].op))
2024 if (o == operator_count) {
2025 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2028 /* found an operator */
2031 /* when declaring variables, a comma starts a new variable */
2032 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2033 /* fixup the token */
2038 /* a colon without a pervious question mark cannot be a ternary */
2039 if (!ternaries && op->id == opid2(':','?')) {
2044 if (op->id == opid1(',')) {
2045 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2046 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2050 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2051 olast = &operators[vec_last(sy.ops).etype-1];
2053 #define IsAssignOp(x) (\
2054 (x) == opid1('=') || \
2055 (x) == opid2('+','=') || \
2056 (x) == opid2('-','=') || \
2057 (x) == opid2('*','=') || \
2058 (x) == opid2('/','=') || \
2059 (x) == opid2('%','=') || \
2060 (x) == opid2('&','=') || \
2061 (x) == opid2('|','=') || \
2062 (x) == opid3('&','~','=') \
2064 if (warn_truthvalue) {
2065 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2066 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2067 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2070 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2071 warn_truthvalue = false;
2076 (op->prec < olast->prec) ||
2077 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2079 if (!parser_sy_apply_operator(parser, &sy))
2081 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2082 olast = &operators[vec_last(sy.ops).etype-1];
2087 if (op->id == opid1('(')) {
2089 size_t sycount = vec_size(sy.out);
2090 /* we expected an operator, this is the function-call operator */
2091 vec_push(sy.paren, PAREN_FUNC);
2092 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2093 vec_push(sy.argc, 0);
2095 vec_push(sy.paren, PAREN_EXPR);
2096 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2099 } else if (op->id == opid1('[')) {
2101 parseerror(parser, "unexpected array subscript");
2104 vec_push(sy.paren, PAREN_INDEX);
2105 /* push both the operator and the paren, this makes life easier */
2106 vec_push(sy.ops, syop(parser_ctx(parser), op));
2107 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2109 } else if (op->id == opid2('?',':')) {
2110 vec_push(sy.ops, syop(parser_ctx(parser), op));
2111 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2114 vec_push(sy.paren, PAREN_TERNARY1);
2115 } else if (op->id == opid2(':','?')) {
2116 if (!vec_size(sy.paren)) {
2117 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2120 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2121 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2124 if (!parser_close_paren(parser, &sy))
2126 vec_push(sy.ops, syop(parser_ctx(parser), op));
2130 vec_push(sy.ops, syop(parser_ctx(parser), op));
2131 wantop = !!(op->flags & OP_SUFFIX);
2134 else if (parser->tok == ')') {
2135 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2136 if (!parser_sy_apply_operator(parser, &sy))
2139 if (!vec_size(sy.paren))
2142 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2143 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2146 if (!parser_close_paren(parser, &sy))
2149 /* must be a function call without parameters */
2150 if (vec_last(sy.paren) != PAREN_FUNC) {
2151 parseerror(parser, "closing paren in invalid position");
2154 if (!parser_close_paren(parser, &sy))
2159 else if (parser->tok == '(') {
2160 parseerror(parser, "internal error: '(' should be classified as operator");
2163 else if (parser->tok == '[') {
2164 parseerror(parser, "internal error: '[' should be classified as operator");
2167 else if (parser->tok == ']') {
2168 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2169 if (!parser_sy_apply_operator(parser, &sy))
2172 if (!vec_size(sy.paren))
2174 if (vec_last(sy.paren) != PAREN_INDEX) {
2175 parseerror(parser, "mismatched parentheses, unexpected ']'");
2178 if (!parser_close_paren(parser, &sy))
2183 if (!parse_sya_operand(parser, &sy, with_labels))
2186 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2187 vec_last(sy.argc)++;
2192 /* in this case we might want to allow constant string concatenation */
2193 bool concatenated = false;
2194 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2195 ast_expression *lexpr = vec_last(sy.out).out;
2196 if (ast_istype(lexpr, ast_value)) {
2197 ast_value *last = (ast_value*)lexpr;
2198 if (last->isimm == true && last->cvq == CV_CONST &&
2199 last->hasvalue && last->expression.vtype == TYPE_STRING)
2201 char *newstr = NULL;
2202 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2203 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2205 concatenated = true;
2209 if (!concatenated) {
2210 parseerror(parser, "expected operator or end of statement");
2215 if (!parser_next(parser)) {
2218 if (parser->tok == ';' ||
2219 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2220 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2226 while (vec_size(sy.ops)) {
2227 if (!parser_sy_apply_operator(parser, &sy))
2231 parser->lex->flags.noops = true;
2232 if (!vec_size(sy.out)) {
2233 parseerror(parser, "empty expression");
2236 expr = sy.out[0].out;
2239 if (vec_size(sy.paren)) {
2240 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2248 parser->lex->flags.noops = true;
2249 for (i = 0; i < vec_size(sy.out); ++i) {
2251 ast_unref(sy.out[i].out);
2260 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2262 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2265 if (parser->tok != ';') {
2266 parseerror(parser, "semicolon expected after expression");
2270 if (!parser_next(parser)) {
2277 static void parser_enterblock(parser_t *parser)
2279 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2280 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2281 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2282 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2283 vec_push(parser->_block_ctx, parser_ctx(parser));
2286 vec_push(parser->correct_variables, correct_trie_new());
2287 vec_push(parser->correct_variables_score, NULL);
2290 static bool parser_leaveblock(parser_t *parser)
2293 size_t locals, typedefs;
2295 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2296 parseerror(parser, "internal error: parser_leaveblock with no block");
2300 util_htdel(vec_last(parser->variables));
2301 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2303 vec_pop(parser->variables);
2304 vec_pop(parser->correct_variables);
2305 vec_pop(parser->correct_variables_score);
2306 if (!vec_size(parser->_blocklocals)) {
2307 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2311 locals = vec_last(parser->_blocklocals);
2312 vec_pop(parser->_blocklocals);
2313 while (vec_size(parser->_locals) != locals) {
2314 ast_expression *e = vec_last(parser->_locals);
2315 ast_value *v = (ast_value*)e;
2316 vec_pop(parser->_locals);
2317 if (ast_istype(e, ast_value) && !v->uses) {
2318 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2323 typedefs = vec_last(parser->_blocktypedefs);
2324 while (vec_size(parser->_typedefs) != typedefs) {
2325 ast_delete(vec_last(parser->_typedefs));
2326 vec_pop(parser->_typedefs);
2328 util_htdel(vec_last(parser->typedefs));
2329 vec_pop(parser->typedefs);
2331 vec_pop(parser->_block_ctx);
2336 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2338 vec_push(parser->_locals, e);
2339 util_htset(vec_last(parser->variables), name, (void*)e);
2343 vec_last(parser->correct_variables),
2344 &vec_last(parser->correct_variables_score),
2349 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2351 vec_push(parser->globals, e);
2352 util_htset(parser->htglobals, name, e);
2356 parser->correct_variables[0],
2357 &parser->correct_variables_score[0],
2362 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2366 ast_expression *prev;
2368 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2370 ast_type_to_string(cond, ty, sizeof(ty));
2371 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2374 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2377 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2380 parseerror(parser, "internal error: failed to process condition");
2385 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2387 /* vector types need to be cast to true booleans */
2388 ast_binary *bin = (ast_binary*)cond;
2389 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2391 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2393 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2396 parseerror(parser, "internal error: failed to process condition");
2403 unary = (ast_unary*)cond;
2404 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2406 cond = unary->operand;
2407 unary->operand = NULL;
2410 unary = (ast_unary*)cond;
2414 parseerror(parser, "internal error: failed to process condition");
2416 if (ifnot) *_ifnot = !*_ifnot;
2420 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2423 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2426 lex_ctx ctx = parser_ctx(parser);
2428 (void)block; /* not touching */
2430 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2431 if (!parser_next(parser)) {
2432 parseerror(parser, "expected condition or 'not'");
2435 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2437 if (!parser_next(parser)) {
2438 parseerror(parser, "expected condition in parenthesis");
2442 if (parser->tok != '(') {
2443 parseerror(parser, "expected 'if' condition in parenthesis");
2446 /* parse into the expression */
2447 if (!parser_next(parser)) {
2448 parseerror(parser, "expected 'if' condition after opening paren");
2451 /* parse the condition */
2452 cond = parse_expression_leave(parser, false, true, false);
2456 if (parser->tok != ')') {
2457 parseerror(parser, "expected closing paren after 'if' condition");
2461 /* parse into the 'then' branch */
2462 if (!parser_next(parser)) {
2463 parseerror(parser, "expected statement for on-true branch of 'if'");
2467 if (!parse_statement_or_block(parser, &ontrue)) {
2472 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2473 /* check for an else */
2474 if (!strcmp(parser_tokval(parser), "else")) {
2475 /* parse into the 'else' branch */
2476 if (!parser_next(parser)) {
2477 parseerror(parser, "expected on-false branch after 'else'");
2482 if (!parse_statement_or_block(parser, &onfalse)) {
2489 cond = process_condition(parser, cond, &ifnot);
2491 if (ontrue) ast_delete(ontrue);
2492 if (onfalse) ast_delete(onfalse);
2497 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2499 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2500 *out = (ast_expression*)ifthen;
2504 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2505 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2510 /* skip the 'while' and get the body */
2511 if (!parser_next(parser)) {
2512 if (OPTS_FLAG(LOOP_LABELS))
2513 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2515 parseerror(parser, "expected 'while' condition in parenthesis");
2519 if (parser->tok == ':') {
2520 if (!OPTS_FLAG(LOOP_LABELS))
2521 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2522 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2523 parseerror(parser, "expected loop label");
2526 label = util_strdup(parser_tokval(parser));
2527 if (!parser_next(parser)) {
2529 parseerror(parser, "expected 'while' condition in parenthesis");
2534 if (parser->tok != '(') {
2535 parseerror(parser, "expected 'while' condition in parenthesis");
2539 vec_push(parser->breaks, label);
2540 vec_push(parser->continues, label);
2542 rv = parse_while_go(parser, block, out);
2545 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2546 parseerror(parser, "internal error: label stack corrupted");
2552 vec_pop(parser->breaks);
2553 vec_pop(parser->continues);
2558 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2561 ast_expression *cond, *ontrue;
2565 lex_ctx ctx = parser_ctx(parser);
2567 (void)block; /* not touching */
2569 /* parse into the expression */
2570 if (!parser_next(parser)) {
2571 parseerror(parser, "expected 'while' condition after opening paren");
2574 /* parse the condition */
2575 cond = parse_expression_leave(parser, false, true, false);
2579 if (parser->tok != ')') {
2580 parseerror(parser, "expected closing paren after 'while' condition");
2584 /* parse into the 'then' branch */
2585 if (!parser_next(parser)) {
2586 parseerror(parser, "expected while-loop body");
2590 if (!parse_statement_or_block(parser, &ontrue)) {
2595 cond = process_condition(parser, cond, &ifnot);
2600 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2601 *out = (ast_expression*)aloop;
2605 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2606 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2611 /* skip the 'do' and get the body */
2612 if (!parser_next(parser)) {
2613 if (OPTS_FLAG(LOOP_LABELS))
2614 parseerror(parser, "expected loop label or body");
2616 parseerror(parser, "expected loop body");
2620 if (parser->tok == ':') {
2621 if (!OPTS_FLAG(LOOP_LABELS))
2622 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2623 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2624 parseerror(parser, "expected loop label");
2627 label = util_strdup(parser_tokval(parser));
2628 if (!parser_next(parser)) {
2630 parseerror(parser, "expected loop body");
2635 vec_push(parser->breaks, label);
2636 vec_push(parser->continues, label);
2638 rv = parse_dowhile_go(parser, block, out);
2641 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2642 parseerror(parser, "internal error: label stack corrupted");
2648 vec_pop(parser->breaks);
2649 vec_pop(parser->continues);
2654 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2657 ast_expression *cond, *ontrue;
2661 lex_ctx ctx = parser_ctx(parser);
2663 (void)block; /* not touching */
2665 if (!parse_statement_or_block(parser, &ontrue))
2668 /* expect the "while" */
2669 if (parser->tok != TOKEN_KEYWORD ||
2670 strcmp(parser_tokval(parser), "while"))
2672 parseerror(parser, "expected 'while' and condition");
2677 /* skip the 'while' and check for opening paren */
2678 if (!parser_next(parser) || parser->tok != '(') {
2679 parseerror(parser, "expected 'while' condition in parenthesis");
2683 /* parse into the expression */
2684 if (!parser_next(parser)) {
2685 parseerror(parser, "expected 'while' condition after opening paren");
2689 /* parse the condition */
2690 cond = parse_expression_leave(parser, false, true, false);
2694 if (parser->tok != ')') {
2695 parseerror(parser, "expected closing paren after 'while' condition");
2701 if (!parser_next(parser) || parser->tok != ';') {
2702 parseerror(parser, "expected semicolon after condition");
2708 if (!parser_next(parser)) {
2709 parseerror(parser, "parse error");
2715 cond = process_condition(parser, cond, &ifnot);
2720 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2721 *out = (ast_expression*)aloop;
2725 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2726 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2731 /* skip the 'for' and check for opening paren */
2732 if (!parser_next(parser)) {
2733 if (OPTS_FLAG(LOOP_LABELS))
2734 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2736 parseerror(parser, "expected 'for' expressions in parenthesis");
2740 if (parser->tok == ':') {
2741 if (!OPTS_FLAG(LOOP_LABELS))
2742 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2743 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2744 parseerror(parser, "expected loop label");
2747 label = util_strdup(parser_tokval(parser));
2748 if (!parser_next(parser)) {
2750 parseerror(parser, "expected 'for' expressions in parenthesis");
2755 if (parser->tok != '(') {
2756 parseerror(parser, "expected 'for' expressions in parenthesis");
2760 vec_push(parser->breaks, label);
2761 vec_push(parser->continues, label);
2763 rv = parse_for_go(parser, block, out);
2766 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2767 parseerror(parser, "internal error: label stack corrupted");
2773 vec_pop(parser->breaks);
2774 vec_pop(parser->continues);
2778 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2781 ast_expression *initexpr, *cond, *increment, *ontrue;
2787 lex_ctx ctx = parser_ctx(parser);
2789 parser_enterblock(parser);
2796 /* parse into the expression */
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "expected 'for' initializer after opening paren");
2803 if (parser->tok == TOKEN_IDENT)
2804 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2806 if (typevar || parser->tok == TOKEN_TYPENAME) {
2808 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2809 if (parsewarning(parser, WARN_EXTENSIONS,
2810 "current standard does not allow variable declarations in for-loop initializers"))
2814 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2817 else if (parser->tok != ';')
2819 initexpr = parse_expression_leave(parser, false, false, false);
2824 /* move on to condition */
2825 if (parser->tok != ';') {
2826 parseerror(parser, "expected semicolon after for-loop initializer");
2829 if (!parser_next(parser)) {
2830 parseerror(parser, "expected for-loop condition");
2834 /* parse the condition */
2835 if (parser->tok != ';') {
2836 cond = parse_expression_leave(parser, false, true, false);
2841 /* move on to incrementor */
2842 if (parser->tok != ';') {
2843 parseerror(parser, "expected semicolon after for-loop initializer");
2846 if (!parser_next(parser)) {
2847 parseerror(parser, "expected for-loop condition");
2851 /* parse the incrementor */
2852 if (parser->tok != ')') {
2853 lex_ctx condctx = parser_ctx(parser);
2854 increment = parse_expression_leave(parser, false, false, false);
2857 if (!ast_side_effects(increment)) {
2858 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2864 if (parser->tok != ')') {
2865 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2868 /* parse into the 'then' branch */
2869 if (!parser_next(parser)) {
2870 parseerror(parser, "expected for-loop body");
2873 if (!parse_statement_or_block(parser, &ontrue))
2877 cond = process_condition(parser, cond, &ifnot);
2881 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2882 *out = (ast_expression*)aloop;
2884 if (!parser_leaveblock(parser))
2888 if (initexpr) ast_delete(initexpr);
2889 if (cond) ast_delete(cond);
2890 if (increment) ast_delete(increment);
2891 (void)!parser_leaveblock(parser);
2895 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2897 ast_expression *exp = NULL;
2898 ast_return *ret = NULL;
2899 ast_value *expected = parser->function->vtype;
2901 lex_ctx ctx = parser_ctx(parser);
2903 (void)block; /* not touching */
2905 if (!parser_next(parser)) {
2906 parseerror(parser, "expected return expression");
2910 if (parser->tok != ';') {
2911 exp = parse_expression(parser, false, false);
2915 if (exp->expression.vtype != TYPE_NIL &&
2916 exp->expression.vtype != expected->expression.next->expression.vtype)
2918 parseerror(parser, "return with invalid expression");
2921 ret = ast_return_new(ctx, exp);
2927 if (!parser_next(parser))
2928 parseerror(parser, "parse error");
2929 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2930 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2932 ret = ast_return_new(ctx, NULL);
2934 *out = (ast_expression*)ret;
2938 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2941 unsigned int levels = 0;
2942 lex_ctx ctx = parser_ctx(parser);
2943 const char **loops = (is_continue ? parser->continues : parser->breaks);
2945 (void)block; /* not touching */
2946 if (!parser_next(parser)) {
2947 parseerror(parser, "expected semicolon or loop label");
2951 if (!vec_size(loops)) {
2953 parseerror(parser, "`continue` can only be used inside loops");
2955 parseerror(parser, "`break` can only be used inside loops or switches");
2958 if (parser->tok == TOKEN_IDENT) {
2959 if (!OPTS_FLAG(LOOP_LABELS))
2960 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2961 i = vec_size(loops);
2963 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2966 parseerror(parser, "no such loop to %s: `%s`",
2967 (is_continue ? "continue" : "break out of"),
2968 parser_tokval(parser));
2973 if (!parser_next(parser)) {
2974 parseerror(parser, "expected semicolon");
2979 if (parser->tok != ';') {
2980 parseerror(parser, "expected semicolon");
2984 if (!parser_next(parser))
2985 parseerror(parser, "parse error");
2987 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2991 /* returns true when it was a variable qualifier, false otherwise!
2992 * on error, cvq is set to CV_WRONG
2994 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2996 bool had_const = false;
2997 bool had_var = false;
2998 bool had_noref = false;
2999 bool had_attrib = false;
3000 bool had_static = false;
3005 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3007 /* parse an attribute */
3008 if (!parser_next(parser)) {
3009 parseerror(parser, "expected attribute after `[[`");
3013 if (!strcmp(parser_tokval(parser), "noreturn")) {
3014 flags |= AST_FLAG_NORETURN;
3015 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3016 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3021 else if (!strcmp(parser_tokval(parser), "noref")) {
3023 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3024 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3029 else if (!strcmp(parser_tokval(parser), "inline")) {
3030 flags |= AST_FLAG_INLINE;
3031 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3032 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3037 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3038 flags |= AST_FLAG_ALIAS;
3041 if (!parser_next(parser)) {
3042 parseerror(parser, "parse error in attribute");
3046 if (parser->tok == '(') {
3047 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3048 parseerror(parser, "`alias` attribute missing parameter");
3052 *message = util_strdup(parser_tokval(parser));
3054 if (!parser_next(parser)) {
3055 parseerror(parser, "parse error in attribute");
3059 if (parser->tok != ')') {
3060 parseerror(parser, "`alias` attribute expected `)` after parameter");
3064 if (!parser_next(parser)) {
3065 parseerror(parser, "parse error in attribute");
3070 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3071 parseerror(parser, "`alias` attribute expected `]]`");
3075 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3076 flags |= AST_FLAG_DEPRECATED;
3079 if (!parser_next(parser)) {
3080 parseerror(parser, "parse error in attribute");
3084 if (parser->tok == '(') {
3085 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3086 parseerror(parser, "`deprecated` attribute missing parameter");
3090 *message = util_strdup(parser_tokval(parser));
3092 if (!parser_next(parser)) {
3093 parseerror(parser, "parse error in attribute");
3097 if(parser->tok != ')') {
3098 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3102 if (!parser_next(parser)) {
3103 parseerror(parser, "parse error in attribute");
3108 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3109 parseerror(parser, "`deprecated` attribute expected `]]`");
3112 if (*message) mem_d(*message);
3120 /* Skip tokens until we hit a ]] */
3121 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3122 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3123 if (!parser_next(parser)) {
3124 parseerror(parser, "error inside attribute");
3131 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3133 else if (!strcmp(parser_tokval(parser), "const"))
3135 else if (!strcmp(parser_tokval(parser), "var"))
3137 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3139 else if (!strcmp(parser_tokval(parser), "noref"))
3141 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3146 if (!parser_next(parser))
3156 *is_static = had_static;
3160 parseerror(parser, "parse error after variable qualifier");
3165 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3166 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3171 /* skip the 'while' and get the body */
3172 if (!parser_next(parser)) {
3173 if (OPTS_FLAG(LOOP_LABELS))
3174 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3176 parseerror(parser, "expected 'switch' operand in parenthesis");
3180 if (parser->tok == ':') {
3181 if (!OPTS_FLAG(LOOP_LABELS))
3182 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3183 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3184 parseerror(parser, "expected loop label");
3187 label = util_strdup(parser_tokval(parser));
3188 if (!parser_next(parser)) {
3190 parseerror(parser, "expected 'switch' operand in parenthesis");
3195 if (parser->tok != '(') {
3196 parseerror(parser, "expected 'switch' operand in parenthesis");
3200 vec_push(parser->breaks, label);
3202 rv = parse_switch_go(parser, block, out);
3205 if (vec_last(parser->breaks) != label) {
3206 parseerror(parser, "internal error: label stack corrupted");
3212 vec_pop(parser->breaks);
3217 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3219 ast_expression *operand;
3222 ast_switch *switchnode;
3223 ast_switch_case swcase;
3226 bool noref, is_static;
3227 uint32_t qflags = 0;
3229 lex_ctx ctx = parser_ctx(parser);
3231 (void)block; /* not touching */
3234 /* parse into the expression */
3235 if (!parser_next(parser)) {
3236 parseerror(parser, "expected switch operand");
3239 /* parse the operand */
3240 operand = parse_expression_leave(parser, false, false, false);
3244 switchnode = ast_switch_new(ctx, operand);
3247 if (parser->tok != ')') {
3248 ast_delete(switchnode);
3249 parseerror(parser, "expected closing paren after 'switch' operand");
3253 /* parse over the opening paren */
3254 if (!parser_next(parser) || parser->tok != '{') {
3255 ast_delete(switchnode);
3256 parseerror(parser, "expected list of cases");
3260 if (!parser_next(parser)) {
3261 ast_delete(switchnode);
3262 parseerror(parser, "expected 'case' or 'default'");
3266 /* new block; allow some variables to be declared here */
3267 parser_enterblock(parser);
3270 if (parser->tok == TOKEN_IDENT)
3271 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3272 if (typevar || parser->tok == TOKEN_TYPENAME) {
3273 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3274 ast_delete(switchnode);
3279 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3281 if (cvq == CV_WRONG) {
3282 ast_delete(switchnode);
3285 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3286 ast_delete(switchnode);
3295 while (parser->tok != '}') {
3296 ast_block *caseblock;
3298 if (!strcmp(parser_tokval(parser), "case")) {
3299 if (!parser_next(parser)) {
3300 ast_delete(switchnode);
3301 parseerror(parser, "expected expression for case");
3304 swcase.value = parse_expression_leave(parser, false, false, false);
3305 if (!swcase.value) {
3306 ast_delete(switchnode);
3307 parseerror(parser, "expected expression for case");
3310 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3311 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3312 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3318 else if (!strcmp(parser_tokval(parser), "default")) {
3319 swcase.value = NULL;
3320 if (!parser_next(parser)) {
3321 ast_delete(switchnode);
3322 parseerror(parser, "expected colon");
3327 ast_delete(switchnode);
3328 parseerror(parser, "expected 'case' or 'default'");
3332 /* Now the colon and body */
3333 if (parser->tok != ':') {
3334 if (swcase.value) ast_unref(swcase.value);
3335 ast_delete(switchnode);
3336 parseerror(parser, "expected colon");
3340 if (!parser_next(parser)) {
3341 if (swcase.value) ast_unref(swcase.value);
3342 ast_delete(switchnode);
3343 parseerror(parser, "expected statements or case");
3346 caseblock = ast_block_new(parser_ctx(parser));
3348 if (swcase.value) ast_unref(swcase.value);
3349 ast_delete(switchnode);
3352 swcase.code = (ast_expression*)caseblock;
3353 vec_push(switchnode->cases, swcase);
3355 ast_expression *expr;
3356 if (parser->tok == '}')
3358 if (parser->tok == TOKEN_KEYWORD) {
3359 if (!strcmp(parser_tokval(parser), "case") ||
3360 !strcmp(parser_tokval(parser), "default"))
3365 if (!parse_statement(parser, caseblock, &expr, true)) {
3366 ast_delete(switchnode);
3371 if (!ast_block_add_expr(caseblock, expr)) {
3372 ast_delete(switchnode);
3378 parser_leaveblock(parser);
3381 if (parser->tok != '}') {
3382 ast_delete(switchnode);
3383 parseerror(parser, "expected closing paren of case list");
3386 if (!parser_next(parser)) {
3387 ast_delete(switchnode);
3388 parseerror(parser, "parse error after switch");
3391 *out = (ast_expression*)switchnode;
3395 /* parse computed goto sides */
3396 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3397 ast_expression *on_true;
3398 ast_expression *on_false;
3399 ast_expression *cond;
3404 if (ast_istype(*side, ast_ternary)) {
3405 ast_ternary *tern = (ast_ternary*)*side;
3406 on_true = parse_goto_computed(parser, &tern->on_true);
3407 on_false = parse_goto_computed(parser, &tern->on_false);
3409 if (!on_true || !on_false) {
3410 parseerror(parser, "expected label or expression in ternary");
3411 if (on_true) ast_unref(on_true);
3412 if (on_false) ast_unref(on_false);
3420 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3421 } else if (ast_istype(*side, ast_label)) {
3422 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3423 ast_goto_set_label(gt, ((ast_label*)*side));
3425 return (ast_expression*)gt;
3430 static bool parse_goto(parser_t *parser, ast_expression **out)
3432 ast_goto *gt = NULL;
3433 ast_expression *lbl;
3435 if (!parser_next(parser))
3438 if (parser->tok != TOKEN_IDENT) {
3439 ast_expression *expression;
3441 /* could be an expression i.e computed goto :-) */
3442 if (parser->tok != '(') {
3443 parseerror(parser, "expected label name after `goto`");
3447 /* failed to parse expression for goto */
3448 if (!(expression = parse_expression(parser, false, true)) ||
3449 !(*out = parse_goto_computed(parser, &expression))) {
3450 parseerror(parser, "invalid goto expression");
3451 ast_unref(expression);
3458 /* not computed goto */
3459 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3460 lbl = parser_find_label(parser, gt->name);
3462 if (!ast_istype(lbl, ast_label)) {
3463 parseerror(parser, "internal error: label is not an ast_label");
3467 ast_goto_set_label(gt, (ast_label*)lbl);
3470 vec_push(parser->gotos, gt);
3472 if (!parser_next(parser) || parser->tok != ';') {
3473 parseerror(parser, "semicolon expected after goto label");
3476 if (!parser_next(parser)) {
3477 parseerror(parser, "parse error after goto");
3481 *out = (ast_expression*)gt;
3485 static bool parse_skipwhite(parser_t *parser)
3488 if (!parser_next(parser))
3490 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3491 return parser->tok < TOKEN_ERROR;
3494 static bool parse_eol(parser_t *parser)
3496 if (!parse_skipwhite(parser))
3498 return parser->tok == TOKEN_EOL;
3501 static bool parse_pragma_do(parser_t *parser)
3503 if (!parser_next(parser) ||
3504 parser->tok != TOKEN_IDENT ||
3505 strcmp(parser_tokval(parser), "pragma"))
3507 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3510 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3511 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3515 if (!strcmp(parser_tokval(parser), "noref")) {
3516 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3517 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3520 parser->noref = !!parser_token(parser)->constval.i;
3521 if (!parse_eol(parser)) {
3522 parseerror(parser, "parse error after `noref` pragma");
3528 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3535 static bool parse_pragma(parser_t *parser)
3538 parser->lex->flags.preprocessing = true;
3539 parser->lex->flags.mergelines = true;
3540 rv = parse_pragma_do(parser);
3541 if (parser->tok != TOKEN_EOL) {
3542 parseerror(parser, "junk after pragma");
3545 parser->lex->flags.preprocessing = false;
3546 parser->lex->flags.mergelines = false;
3547 if (!parser_next(parser)) {
3548 parseerror(parser, "parse error after pragma");
3554 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3556 bool noref, is_static;
3558 uint32_t qflags = 0;
3559 ast_value *typevar = NULL;
3560 char *vstring = NULL;
3564 if (parser->tok == TOKEN_IDENT)
3565 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3567 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3569 /* local variable */
3571 parseerror(parser, "cannot declare a variable from here");
3574 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3575 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3578 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3582 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3584 if (cvq == CV_WRONG)
3586 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3588 else if (parser->tok == TOKEN_KEYWORD)
3590 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3595 if (!parser_next(parser)) {
3596 parseerror(parser, "parse error after __builtin_debug_printtype");
3600 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3602 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3603 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3604 if (!parser_next(parser)) {
3605 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3611 if (!parse_statement(parser, block, out, allow_cases))
3614 con_out("__builtin_debug_printtype: got no output node\n");
3617 ast_type_to_string(*out, ty, sizeof(ty));
3618 con_out("__builtin_debug_printtype: `%s`\n", ty);
3623 else if (!strcmp(parser_tokval(parser), "return"))
3625 return parse_return(parser, block, out);
3627 else if (!strcmp(parser_tokval(parser), "if"))
3629 return parse_if(parser, block, out);
3631 else if (!strcmp(parser_tokval(parser), "while"))
3633 return parse_while(parser, block, out);
3635 else if (!strcmp(parser_tokval(parser), "do"))
3637 return parse_dowhile(parser, block, out);
3639 else if (!strcmp(parser_tokval(parser), "for"))
3641 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3642 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3645 return parse_for(parser, block, out);
3647 else if (!strcmp(parser_tokval(parser), "break"))
3649 return parse_break_continue(parser, block, out, false);
3651 else if (!strcmp(parser_tokval(parser), "continue"))
3653 return parse_break_continue(parser, block, out, true);
3655 else if (!strcmp(parser_tokval(parser), "switch"))
3657 return parse_switch(parser, block, out);
3659 else if (!strcmp(parser_tokval(parser), "case") ||
3660 !strcmp(parser_tokval(parser), "default"))
3663 parseerror(parser, "unexpected 'case' label");
3668 else if (!strcmp(parser_tokval(parser), "goto"))
3670 return parse_goto(parser, out);
3672 else if (!strcmp(parser_tokval(parser), "typedef"))
3674 if (!parser_next(parser)) {
3675 parseerror(parser, "expected type definition after 'typedef'");
3678 return parse_typedef(parser);
3680 parseerror(parser, "Unexpected keyword");
3683 else if (parser->tok == '{')
3686 inner = parse_block(parser);
3689 *out = (ast_expression*)inner;
3692 else if (parser->tok == ':')
3696 if (!parser_next(parser)) {
3697 parseerror(parser, "expected label name");
3700 if (parser->tok != TOKEN_IDENT) {
3701 parseerror(parser, "label must be an identifier");
3704 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3706 if (!label->undefined) {
3707 parseerror(parser, "label `%s` already defined", label->name);
3710 label->undefined = false;
3713 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3714 vec_push(parser->labels, label);
3716 *out = (ast_expression*)label;
3717 if (!parser_next(parser)) {
3718 parseerror(parser, "parse error after label");
3721 for (i = 0; i < vec_size(parser->gotos); ++i) {
3722 if (!strcmp(parser->gotos[i]->name, label->name)) {
3723 ast_goto_set_label(parser->gotos[i], label);
3724 vec_remove(parser->gotos, i, 1);
3730 else if (parser->tok == ';')
3732 if (!parser_next(parser)) {
3733 parseerror(parser, "parse error after empty statement");
3740 lex_ctx ctx = parser_ctx(parser);
3741 ast_expression *exp = parse_expression(parser, false, false);
3745 if (!ast_side_effects(exp)) {
3746 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3753 static bool parse_enum(parser_t *parser)
3756 bool reverse = false;
3758 ast_value **values = NULL;
3759 ast_value *var = NULL;
3762 ast_expression *old;
3764 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3765 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3769 /* enumeration attributes (can add more later) */
3770 if (parser->tok == ':') {
3771 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3772 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3777 if (!strcmp(parser_tokval(parser), "flag")) {
3781 else if (!strcmp(parser_tokval(parser), "reverse")) {
3785 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3789 if (!parser_next(parser) || parser->tok != '{') {
3790 parseerror(parser, "expected `{` after enum attribute ");
3796 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3797 if (parser->tok == '}') {
3798 /* allow an empty enum */
3801 parseerror(parser, "expected identifier or `}`");
3805 old = parser_find_field(parser, parser_tokval(parser));
3807 old = parser_find_global(parser, parser_tokval(parser));
3809 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3810 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3814 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3815 vec_push(values, var);
3816 var->cvq = CV_CONST;
3817 var->hasvalue = true;
3819 /* for flagged enumerations increment in POTs of TWO */
3820 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3821 parser_addglobal(parser, var->name, (ast_expression*)var);
3823 if (!parser_next(parser)) {
3824 parseerror(parser, "expected `=`, `}` or comma after identifier");
3828 if (parser->tok == ',')
3830 if (parser->tok == '}')
3832 if (parser->tok != '=') {
3833 parseerror(parser, "expected `=`, `}` or comma after identifier");
3837 if (!parser_next(parser)) {
3838 parseerror(parser, "expected expression after `=`");
3842 /* We got a value! */
3843 old = parse_expression_leave(parser, true, false, false);
3844 asvalue = (ast_value*)old;
3845 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3846 compile_error(ast_ctx(var), "constant value or expression expected");
3849 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3851 if (parser->tok == '}')
3853 if (parser->tok != ',') {
3854 parseerror(parser, "expected `}` or comma after expression");
3859 /* patch them all (for reversed attribute) */
3862 for (i = 0; i < vec_size(values); i++)
3863 values[i]->constval.vfloat = vec_size(values) - i - 1;
3866 if (parser->tok != '}') {
3867 parseerror(parser, "internal error: breaking without `}`");
3871 if (!parser_next(parser) || parser->tok != ';') {
3872 parseerror(parser, "expected semicolon after enumeration");
3876 if (!parser_next(parser)) {
3877 parseerror(parser, "parse error after enumeration");
3889 static bool parse_block_into(parser_t *parser, ast_block *block)
3893 parser_enterblock(parser);
3895 if (!parser_next(parser)) { /* skip the '{' */
3896 parseerror(parser, "expected function body");
3900 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3902 ast_expression *expr = NULL;
3903 if (parser->tok == '}')
3906 if (!parse_statement(parser, block, &expr, false)) {
3907 /* parseerror(parser, "parse error"); */
3913 if (!ast_block_add_expr(block, expr)) {
3920 if (parser->tok != '}') {
3923 (void)parser_next(parser);
3927 if (!parser_leaveblock(parser))
3929 return retval && !!block;
3932 static ast_block* parse_block(parser_t *parser)
3935 block = ast_block_new(parser_ctx(parser));
3938 if (!parse_block_into(parser, block)) {
3939 ast_block_delete(block);
3945 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3947 if (parser->tok == '{') {
3948 *out = (ast_expression*)parse_block(parser);
3951 return parse_statement(parser, NULL, out, false);
3954 static bool create_vector_members(ast_value *var, ast_member **me)
3957 size_t len = strlen(var->name);
3959 for (i = 0; i < 3; ++i) {
3960 char *name = (char*)mem_a(len+3);
3961 memcpy(name, var->name, len);
3963 name[len+1] = 'x'+i;
3965 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3974 do { ast_member_delete(me[--i]); } while(i);
3978 static bool parse_function_body(parser_t *parser, ast_value *var)
3980 ast_block *block = NULL;
3985 ast_expression *framenum = NULL;
3986 ast_expression *nextthink = NULL;
3987 /* None of the following have to be deleted */
3988 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3989 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3990 bool has_frame_think;
3994 has_frame_think = false;
3995 old = parser->function;
3997 if (var->expression.flags & AST_FLAG_ALIAS) {
3998 parseerror(parser, "function aliases cannot have bodies");
4002 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4003 parseerror(parser, "gotos/labels leaking");
4007 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4008 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4009 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4015 if (parser->tok == '[') {
4016 /* got a frame definition: [ framenum, nextthink ]
4017 * this translates to:
4018 * self.frame = framenum;
4019 * self.nextthink = time + 0.1;
4020 * self.think = nextthink;
4024 fld_think = parser_find_field(parser, "think");
4025 fld_nextthink = parser_find_field(parser, "nextthink");
4026 fld_frame = parser_find_field(parser, "frame");
4027 if (!fld_think || !fld_nextthink || !fld_frame) {
4028 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4029 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4032 gbl_time = parser_find_global(parser, "time");
4033 gbl_self = parser_find_global(parser, "self");
4034 if (!gbl_time || !gbl_self) {
4035 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4036 parseerror(parser, "please declare the following globals: `time`, `self`");
4040 if (!parser_next(parser))
4043 framenum = parse_expression_leave(parser, true, false, false);
4045 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4048 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4049 ast_unref(framenum);
4050 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4054 if (parser->tok != ',') {
4055 ast_unref(framenum);
4056 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4057 parseerror(parser, "Got a %i\n", parser->tok);
4061 if (!parser_next(parser)) {
4062 ast_unref(framenum);
4066 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4068 /* qc allows the use of not-yet-declared functions here
4069 * - this automatically creates a prototype */
4070 ast_value *thinkfunc;
4071 ast_expression *functype = fld_think->expression.next;
4073 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4074 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4075 ast_unref(framenum);
4076 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4079 ast_type_adopt(thinkfunc, functype);
4081 if (!parser_next(parser)) {
4082 ast_unref(framenum);
4083 ast_delete(thinkfunc);
4087 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4089 nextthink = (ast_expression*)thinkfunc;
4092 nextthink = parse_expression_leave(parser, true, false, false);
4094 ast_unref(framenum);
4095 parseerror(parser, "expected a think-function in [frame,think] notation");
4100 if (!ast_istype(nextthink, ast_value)) {
4101 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4105 if (retval && parser->tok != ']') {
4106 parseerror(parser, "expected closing `]` for [frame,think] notation");
4110 if (retval && !parser_next(parser)) {
4114 if (retval && parser->tok != '{') {
4115 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4120 ast_unref(nextthink);
4121 ast_unref(framenum);
4125 has_frame_think = true;
4128 block = ast_block_new(parser_ctx(parser));
4130 parseerror(parser, "failed to allocate block");
4131 if (has_frame_think) {
4132 ast_unref(nextthink);
4133 ast_unref(framenum);
4138 if (has_frame_think) {
4140 ast_expression *self_frame;
4141 ast_expression *self_nextthink;
4142 ast_expression *self_think;
4143 ast_expression *time_plus_1;
4144 ast_store *store_frame;
4145 ast_store *store_nextthink;
4146 ast_store *store_think;
4148 ctx = parser_ctx(parser);
4149 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4150 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4151 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4153 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4154 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4156 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4157 if (self_frame) ast_delete(self_frame);
4158 if (self_nextthink) ast_delete(self_nextthink);
4159 if (self_think) ast_delete(self_think);
4160 if (time_plus_1) ast_delete(time_plus_1);
4166 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4167 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4168 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4171 ast_delete(self_frame);
4174 if (!store_nextthink) {
4175 ast_delete(self_nextthink);
4179 ast_delete(self_think);
4183 if (store_frame) ast_delete(store_frame);
4184 if (store_nextthink) ast_delete(store_nextthink);
4185 if (store_think) ast_delete(store_think);
4188 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4189 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4190 !ast_block_add_expr(block, (ast_expression*)store_think))
4197 parseerror(parser, "failed to generate code for [frame,think]");
4198 ast_unref(nextthink);
4199 ast_unref(framenum);
4205 if (var->hasvalue) {
4206 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4207 ast_block_delete(block);
4211 func = ast_function_new(ast_ctx(var), var->name, var);
4213 parseerror(parser, "failed to allocate function for `%s`", var->name);
4214 ast_block_delete(block);
4217 vec_push(parser->functions, func);
4219 parser_enterblock(parser);
4221 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4223 ast_value *param = var->expression.params[parami];
4226 if (param->expression.vtype != TYPE_VECTOR &&
4227 (param->expression.vtype != TYPE_FIELD ||
4228 param->expression.next->expression.vtype != TYPE_VECTOR))
4233 if (!create_vector_members(param, me)) {
4234 ast_block_delete(block);
4238 for (e = 0; e < 3; ++e) {
4239 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4240 ast_block_collect(block, (ast_expression*)me[e]);
4244 if (var->argcounter) {
4245 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4246 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4250 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4252 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4253 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4254 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4255 varargs->expression.count = 0;
4256 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4257 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4258 ast_delete(varargs);
4259 ast_block_delete(block);
4262 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4263 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4264 ast_delete(varargs);
4265 ast_block_delete(block);
4268 func->varargs = varargs;
4270 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4273 parser->function = func;
4274 if (!parse_block_into(parser, block)) {
4275 ast_block_delete(block);
4279 vec_push(func->blocks, block);
4281 parser->function = old;
4282 if (!parser_leaveblock(parser))
4284 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4285 parseerror(parser, "internal error: local scopes left");
4289 if (parser->tok == ';')
4290 return parser_next(parser);
4291 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4292 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4296 (void)!parser_leaveblock(parser);
4297 vec_pop(parser->functions);
4298 ast_function_delete(func);
4299 var->constval.vfunc = NULL;
4302 parser->function = old;
4306 static ast_expression *array_accessor_split(
4311 ast_expression *left,
4312 ast_expression *right
4318 lex_ctx ctx = ast_ctx(array);
4320 if (!left || !right) {
4321 if (left) ast_delete(left);
4322 if (right) ast_delete(right);
4326 cmp = ast_binary_new(ctx, INSTR_LT,
4327 (ast_expression*)index,
4328 (ast_expression*)parser_const_float(parser, middle));
4332 parseerror(parser, "internal error: failed to create comparison for array setter");
4336 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4338 ast_delete(cmp); /* will delete left and right */
4339 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4343 return (ast_expression*)ifthen;
4346 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4348 lex_ctx ctx = ast_ctx(array);
4350 if (from+1 == afterend) {
4351 /* set this value */
4354 ast_array_index *subscript;
4356 int assignop = type_store_instr[value->expression.vtype];
4358 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4359 assignop = INSTR_STORE_V;
4361 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4365 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4367 ast_delete(subscript);
4371 block = ast_block_new(ctx);
4377 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4382 ret = ast_return_new(ctx, NULL);
4388 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4393 return (ast_expression*)block;
4395 ast_expression *left, *right;
4396 size_t diff = afterend - from;
4397 size_t middle = from + diff/2;
4398 left = array_setter_node(parser, array, index, value, from, middle);
4399 right = array_setter_node(parser, array, index, value, middle, afterend);
4400 return array_accessor_split(parser, array, index, middle, left, right);
4404 static ast_expression *array_field_setter_node(
4413 lex_ctx ctx = ast_ctx(array);
4415 if (from+1 == afterend) {
4416 /* set this value */
4419 ast_entfield *entfield;
4420 ast_array_index *subscript;
4422 int assignop = type_storep_instr[value->expression.vtype];
4424 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4425 assignop = INSTR_STOREP_V;
4427 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4431 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4432 subscript->expression.vtype = TYPE_FIELD;
4434 entfield = ast_entfield_new_force(ctx,
4435 (ast_expression*)entity,
4436 (ast_expression*)subscript,
4437 (ast_expression*)subscript);
4439 ast_delete(subscript);
4443 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4445 ast_delete(entfield);
4449 block = ast_block_new(ctx);
4455 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4460 ret = ast_return_new(ctx, NULL);
4466 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4471 return (ast_expression*)block;
4473 ast_expression *left, *right;
4474 size_t diff = afterend - from;
4475 size_t middle = from + diff/2;
4476 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4477 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4478 return array_accessor_split(parser, array, index, middle, left, right);
4482 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4484 lex_ctx ctx = ast_ctx(array);
4486 if (from+1 == afterend) {
4488 ast_array_index *subscript;
4490 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4494 ret = ast_return_new(ctx, (ast_expression*)subscript);
4496 ast_delete(subscript);
4500 return (ast_expression*)ret;
4502 ast_expression *left, *right;
4503 size_t diff = afterend - from;
4504 size_t middle = from + diff/2;
4505 left = array_getter_node(parser, array, index, from, middle);
4506 right = array_getter_node(parser, array, index, middle, afterend);
4507 return array_accessor_split(parser, array, index, middle, left, right);
4511 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4513 ast_function *func = NULL;
4514 ast_value *fval = NULL;
4515 ast_block *body = NULL;
4517 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4519 parseerror(parser, "failed to create accessor function value");
4523 func = ast_function_new(ast_ctx(array), funcname, fval);
4526 parseerror(parser, "failed to create accessor function node");
4530 body = ast_block_new(ast_ctx(array));
4532 parseerror(parser, "failed to create block for array accessor");
4538 vec_push(func->blocks, body);
4541 vec_push(parser->accessors, fval);
4546 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4548 ast_value *index = NULL;
4549 ast_value *value = NULL;
4553 if (!ast_istype(array->expression.next, ast_value)) {
4554 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4558 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4560 func = fval->constval.vfunc;
4561 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4563 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4564 value = ast_value_copy((ast_value*)array->expression.next);
4566 if (!index || !value) {
4567 parseerror(parser, "failed to create locals for array accessor");
4570 (void)!ast_value_set_name(value, "value"); /* not important */
4571 vec_push(fval->expression.params, index);
4572 vec_push(fval->expression.params, value);
4574 array->setter = fval;
4577 if (index) ast_delete(index);
4578 if (value) ast_delete(value);
4584 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4586 ast_expression *root = NULL;
4587 root = array_setter_node(parser, array,
4588 array->setter->expression.params[0],
4589 array->setter->expression.params[1],
4590 0, array->expression.count);
4592 parseerror(parser, "failed to build accessor search tree");
4595 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4602 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4604 if (!parser_create_array_setter_proto(parser, array, funcname))
4606 return parser_create_array_setter_impl(parser, array);
4609 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4611 ast_expression *root = NULL;
4612 ast_value *entity = NULL;
4613 ast_value *index = NULL;
4614 ast_value *value = NULL;
4618 if (!ast_istype(array->expression.next, ast_value)) {
4619 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4623 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4625 func = fval->constval.vfunc;
4626 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4628 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4629 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4630 value = ast_value_copy((ast_value*)array->expression.next);
4631 if (!entity || !index || !value) {
4632 parseerror(parser, "failed to create locals for array accessor");
4635 (void)!ast_value_set_name(value, "value"); /* not important */
4636 vec_push(fval->expression.params, entity);
4637 vec_push(fval->expression.params, index);
4638 vec_push(fval->expression.params, value);
4640 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4642 parseerror(parser, "failed to build accessor search tree");
4646 array->setter = fval;
4647 return ast_block_add_expr(func->blocks[0], root);
4649 if (entity) ast_delete(entity);
4650 if (index) ast_delete(index);
4651 if (value) ast_delete(value);
4652 if (root) ast_delete(root);
4658 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4660 ast_value *index = NULL;
4664 /* NOTE: checking array->expression.next rather than elemtype since
4665 * for fields elemtype is a temporary fieldtype.
4667 if (!ast_istype(array->expression.next, ast_value)) {
4668 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4672 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4674 func = fval->constval.vfunc;
4675 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4677 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4680 parseerror(parser, "failed to create locals for array accessor");
4683 vec_push(fval->expression.params, index);
4685 array->getter = fval;
4688 if (index) ast_delete(index);
4694 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4696 ast_expression *root = NULL;
4698 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4700 parseerror(parser, "failed to build accessor search tree");
4703 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4710 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4712 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4714 return parser_create_array_getter_impl(parser, array);
4717 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4718 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4726 bool variadic = false;
4727 ast_value *varparam = NULL;
4728 char *argcounter = NULL;
4730 ctx = parser_ctx(parser);
4732 /* for the sake of less code we parse-in in this function */
4733 if (!parser_next(parser)) {
4734 parseerror(parser, "expected parameter list");
4740 /* parse variables until we hit a closing paren */
4741 while (parser->tok != ')') {
4743 /* there must be commas between them */
4744 if (parser->tok != ',') {
4745 parseerror(parser, "expected comma or end of parameter list");
4748 if (!parser_next(parser)) {
4749 parseerror(parser, "expected parameter");
4755 if (parser->tok == TOKEN_DOTS) {
4756 /* '...' indicates a varargs function */
4758 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4759 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4762 if (parser->tok == TOKEN_IDENT) {
4763 argcounter = util_strdup(parser_tokval(parser));
4764 if (!parser_next(parser) || parser->tok != ')') {
4765 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4772 /* for anything else just parse a typename */
4773 param = parse_typename(parser, NULL, NULL);
4776 vec_push(params, param);
4777 if (param->expression.vtype >= TYPE_VARIANT) {
4778 char tname[1024]; /* typename is reserved in C++ */
4779 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4780 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4783 /* type-restricted varargs */
4784 if (parser->tok == TOKEN_DOTS) {
4786 varparam = vec_last(params);
4788 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4789 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4792 if (parser->tok == TOKEN_IDENT) {
4793 argcounter = util_strdup(parser_tokval(parser));
4794 if (!parser_next(parser) || parser->tok != ')') {
4795 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4803 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4807 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4808 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4811 if (!parser_next(parser)) {
4812 parseerror(parser, "parse error after typename");
4816 /* now turn 'var' into a function type */
4817 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4818 fval->expression.next = (ast_expression*)var;
4820 fval->expression.flags |= AST_FLAG_VARIADIC;
4823 var->expression.params = params;
4824 var->expression.varparam = (ast_expression*)varparam;
4825 var->argcounter = argcounter;
4834 ast_delete(varparam);
4836 for (i = 0; i < vec_size(params); ++i)
4837 ast_delete(params[i]);
4842 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4844 ast_expression *cexp;
4845 ast_value *cval, *tmp;
4848 ctx = parser_ctx(parser);
4850 if (!parser_next(parser)) {
4852 parseerror(parser, "expected array-size");
4856 cexp = parse_expression_leave(parser, true, false, false);
4858 if (!cexp || !ast_istype(cexp, ast_value)) {
4862 parseerror(parser, "expected array-size as constant positive integer");
4865 cval = (ast_value*)cexp;
4867 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4868 tmp->expression.next = (ast_expression*)var;
4871 if (cval->expression.vtype == TYPE_INTEGER)
4872 tmp->expression.count = cval->constval.vint;
4873 else if (cval->expression.vtype == TYPE_FLOAT)
4874 tmp->expression.count = cval->constval.vfloat;
4878 parseerror(parser, "array-size must be a positive integer constant");
4883 if (parser->tok != ']') {
4885 parseerror(parser, "expected ']' after array-size");
4888 if (!parser_next(parser)) {
4890 parseerror(parser, "error after parsing array size");
4896 /* Parse a complete typename.
4897 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4898 * but when parsing variables separated by comma
4899 * 'storebase' should point to where the base-type should be kept.
4900 * The base type makes up every bit of type information which comes *before* the
4903 * The following will be parsed in its entirety:
4905 * The 'basetype' in this case is 'void()'
4906 * and if there's a comma after it, say:
4908 * then the type-information 'void()' can be stored in 'storebase'
4910 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4912 ast_value *var, *tmp;
4915 const char *name = NULL;
4916 bool isfield = false;
4917 bool wasarray = false;
4918 size_t morefields = 0;
4920 ctx = parser_ctx(parser);
4922 /* types may start with a dot */
4923 if (parser->tok == '.') {
4925 /* if we parsed a dot we need a typename now */
4926 if (!parser_next(parser)) {
4927 parseerror(parser, "expected typename for field definition");
4931 /* Further dots are handled seperately because they won't be part of the
4934 while (parser->tok == '.') {
4936 if (!parser_next(parser)) {
4937 parseerror(parser, "expected typename for field definition");
4942 if (parser->tok == TOKEN_IDENT)
4943 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4944 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4945 parseerror(parser, "expected typename");
4949 /* generate the basic type value */
4950 if (cached_typedef) {
4951 var = ast_value_copy(cached_typedef);
4952 ast_value_set_name(var, "<type(from_def)>");
4954 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4956 for (; morefields; --morefields) {
4957 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4958 tmp->expression.next = (ast_expression*)var;
4962 /* do not yet turn into a field - remember:
4963 * .void() foo; is a field too
4964 * .void()() foo; is a function
4968 if (!parser_next(parser)) {
4970 parseerror(parser, "parse error after typename");
4974 /* an opening paren now starts the parameter-list of a function
4975 * this is where original-QC has parameter lists.
4976 * We allow a single parameter list here.
4977 * Much like fteqcc we don't allow `float()() x`
4979 if (parser->tok == '(') {
4980 var = parse_parameter_list(parser, var);
4985 /* store the base if requested */
4987 *storebase = ast_value_copy(var);
4989 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4990 tmp->expression.next = (ast_expression*)*storebase;
4995 /* there may be a name now */
4996 if (parser->tok == TOKEN_IDENT) {
4997 name = util_strdup(parser_tokval(parser));
4999 if (!parser_next(parser)) {
5001 parseerror(parser, "error after variable or field declaration");
5006 /* now this may be an array */
5007 if (parser->tok == '[') {
5009 var = parse_arraysize(parser, var);
5014 /* This is the point where we can turn it into a field */
5016 /* turn it into a field if desired */
5017 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5018 tmp->expression.next = (ast_expression*)var;
5022 /* now there may be function parens again */
5023 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5024 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5025 if (parser->tok == '(' && wasarray)
5026 parseerror(parser, "arrays as part of a return type is not supported");
5027 while (parser->tok == '(') {
5028 var = parse_parameter_list(parser, var);
5036 /* finally name it */
5038 if (!ast_value_set_name(var, name)) {
5040 parseerror(parser, "internal error: failed to set name");
5043 /* free the name, ast_value_set_name duplicates */
5050 static bool parse_typedef(parser_t *parser)
5052 ast_value *typevar, *oldtype;
5053 ast_expression *old;
5055 typevar = parse_typename(parser, NULL, NULL);
5060 if ( (old = parser_find_var(parser, typevar->name)) ) {
5061 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5062 " -> `%s` has been declared here: %s:%i",
5063 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5064 ast_delete(typevar);
5068 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5069 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5070 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5071 ast_delete(typevar);
5075 vec_push(parser->_typedefs, typevar);
5076 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5078 if (parser->tok != ';') {
5079 parseerror(parser, "expected semicolon after typedef");
5082 if (!parser_next(parser)) {
5083 parseerror(parser, "parse error after typedef");
5090 static const char *cvq_to_str(int cvq) {
5092 case CV_NONE: return "none";
5093 case CV_VAR: return "`var`";
5094 case CV_CONST: return "`const`";
5095 default: return "<INVALID>";
5099 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5102 if (proto->cvq != var->cvq) {
5103 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5104 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5105 parser->tok == '='))
5107 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5108 "`%s` declared with different qualifiers: %s\n"
5109 " -> previous declaration here: %s:%i uses %s",
5110 var->name, cvq_to_str(var->cvq),
5111 ast_ctx(proto).file, ast_ctx(proto).line,
5112 cvq_to_str(proto->cvq));
5115 av = (var ->expression.flags & AST_FLAG_NORETURN);
5116 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5118 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5119 "`%s` declared with different attributes%s\n"
5120 " -> previous declaration here: %s:%i",
5121 var->name, (av ? ": noreturn" : ""),
5122 ast_ctx(proto).file, ast_ctx(proto).line,
5123 (ao ? ": noreturn" : ""));
5128 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)
5132 ast_expression *old;
5136 ast_value *basetype = NULL;
5138 bool isparam = false;
5139 bool isvector = false;
5140 bool cleanvar = true;
5141 bool wasarray = false;
5143 ast_member *me[3] = { NULL, NULL, NULL };
5145 if (!localblock && is_static)
5146 parseerror(parser, "`static` qualifier is not supported in global scope");
5148 /* get the first complete variable */
5149 var = parse_typename(parser, &basetype, cached_typedef);
5152 ast_delete(basetype);
5160 /* Part 0: finish the type */
5161 if (parser->tok == '(') {
5162 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5163 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5164 var = parse_parameter_list(parser, var);
5170 /* we only allow 1-dimensional arrays */
5171 if (parser->tok == '[') {
5173 var = parse_arraysize(parser, var);
5179 if (parser->tok == '(' && wasarray) {
5180 parseerror(parser, "arrays as part of a return type is not supported");
5181 /* we'll still parse the type completely for now */
5183 /* for functions returning functions */
5184 while (parser->tok == '(') {
5185 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5186 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5187 var = parse_parameter_list(parser, var);
5194 var->cvq = qualifier;
5195 var->expression.flags |= qflags;
5198 * store the vstring back to var for alias and
5199 * deprecation messages.
5201 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5202 var->expression.flags & AST_FLAG_ALIAS)
5203 var->desc = vstring;
5206 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5207 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5208 * is then filled with the previous definition and the parameter-names replaced.
5210 if (!strcmp(var->name, "nil")) {
5211 if (OPTS_FLAG(UNTYPED_NIL)) {
5212 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5213 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5215 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5218 /* Deal with end_sys_ vars */
5220 if (!strcmp(var->name, "end_sys_globals")) {
5222 parser->crc_globals = vec_size(parser->globals);
5225 else if (!strcmp(var->name, "end_sys_fields")) {
5227 parser->crc_fields = vec_size(parser->fields);
5230 if (was_end && var->expression.vtype == TYPE_FIELD) {
5231 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5232 "global '%s' hint should not be a field",
5233 parser_tokval(parser)))
5240 if (!nofields && var->expression.vtype == TYPE_FIELD)
5242 /* deal with field declarations */
5243 old = parser_find_field(parser, var->name);
5245 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5246 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5255 parseerror(parser, "field `%s` already declared here: %s:%i",
5256 var->name, ast_ctx(old).file, ast_ctx(old).line);
5261 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5262 (old = parser_find_global(parser, var->name)))
5264 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5265 parseerror(parser, "field `%s` already declared here: %s:%i",
5266 var->name, ast_ctx(old).file, ast_ctx(old).line);
5273 /* deal with other globals */
5274 old = parser_find_global(parser, var->name);
5275 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5277 /* This is a function which had a prototype */
5278 if (!ast_istype(old, ast_value)) {
5279 parseerror(parser, "internal error: prototype is not an ast_value");
5283 proto = (ast_value*)old;
5284 proto->desc = var->desc;
5285 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5286 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5288 ast_ctx(proto).file, ast_ctx(proto).line);
5292 /* we need the new parameter-names */
5293 for (i = 0; i < vec_size(proto->expression.params); ++i)
5294 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5295 if (!parser_check_qualifiers(parser, var, proto)) {
5302 proto->expression.flags |= var->expression.flags;
5310 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5311 "global `%s` already declared here: %s:%i",
5312 var->name, ast_ctx(old).file, ast_ctx(old).line))
5317 proto = (ast_value*)old;
5318 if (!ast_istype(old, ast_value)) {
5319 parseerror(parser, "internal error: not an ast_value");
5324 if (!parser_check_qualifiers(parser, var, proto)) {
5329 proto->expression.flags |= var->expression.flags;
5333 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5334 (old = parser_find_field(parser, var->name)))
5336 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5337 parseerror(parser, "global `%s` already declared here: %s:%i",
5338 var->name, ast_ctx(old).file, ast_ctx(old).line);
5345 else /* it's not a global */
5347 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5348 if (old && !isparam) {
5349 parseerror(parser, "local `%s` already declared here: %s:%i",
5350 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5354 old = parser_find_local(parser, var->name, 0, &isparam);
5355 if (old && isparam) {
5356 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5357 "local `%s` is shadowing a parameter", var->name))
5359 parseerror(parser, "local `%s` already declared here: %s:%i",
5360 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5364 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5372 /* in a noref section we simply bump the usecount */
5373 if (noref || parser->noref)
5377 * Create the global/local, and deal with vector types.
5380 if (var->expression.vtype == TYPE_VECTOR)
5382 else if (var->expression.vtype == TYPE_FIELD &&
5383 var->expression.next->expression.vtype == TYPE_VECTOR)
5387 if (!create_vector_members(var, me)) {
5394 /* deal with global variables, fields, functions */
5395 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5396 var->isfield = true;
5397 vec_push(parser->fields, (ast_expression*)var);
5398 util_htset(parser->htfields, var->name, var);
5400 for (i = 0; i < 3; ++i) {
5401 vec_push(parser->fields, (ast_expression*)me[i]);
5402 util_htset(parser->htfields, me[i]->name, me[i]);
5407 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5408 parser_addglobal(parser, var->name, (ast_expression*)var);
5410 for (i = 0; i < 3; ++i) {
5411 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5415 ast_expression *find = parser_find_global(parser, var->desc);
5418 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5422 if (var->expression.vtype != find->expression.vtype) {
5426 ast_type_to_string(find, ty1, sizeof(ty1));
5427 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5429 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5436 * add alias to aliases table and to corrector
5437 * so corrections can apply for aliases as well.
5439 util_htset(parser->aliases, var->name, find);
5442 * add to corrector so corrections can work
5443 * even for aliases too.
5446 vec_last(parser->correct_variables),
5447 &vec_last(parser->correct_variables_score),
5451 /* generate aliases for vector components */
5455 util_asprintf(&buffer[0], "%s_x", var->desc);
5456 util_asprintf(&buffer[1], "%s_y", var->desc);
5457 util_asprintf(&buffer[2], "%s_z", var->desc);
5459 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5460 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5461 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5468 * add to corrector so corrections can work
5469 * even for aliases too.
5472 vec_last(parser->correct_variables),
5473 &vec_last(parser->correct_variables_score),
5477 vec_last(parser->correct_variables),
5478 &vec_last(parser->correct_variables_score),
5482 vec_last(parser->correct_variables),
5483 &vec_last(parser->correct_variables_score),
5491 /* a static adds itself to be generated like any other global
5492 * but is added to the local namespace instead
5494 char *defname = NULL;
5495 size_t prefix_len, ln;
5497 ln = strlen(parser->function->name);
5498 vec_append(defname, ln, parser->function->name);
5500 vec_append(defname, 2, "::");
5501 /* remember the length up to here */
5502 prefix_len = vec_size(defname);
5504 /* Add it to the local scope */
5505 util_htset(vec_last(parser->variables), var->name, (void*)var);
5509 vec_last(parser->correct_variables),
5510 &vec_last(parser->correct_variables_score),
5514 /* now rename the global */
5515 ln = strlen(var->name);
5516 vec_append(defname, ln, var->name);
5517 ast_value_set_name(var, defname);
5519 /* push it to the to-be-generated globals */
5520 vec_push(parser->globals, (ast_expression*)var);
5522 /* same game for the vector members */
5524 for (i = 0; i < 3; ++i) {
5525 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5529 vec_last(parser->correct_variables),
5530 &vec_last(parser->correct_variables_score),
5534 vec_shrinkto(defname, prefix_len);
5535 ln = strlen(me[i]->name);
5536 vec_append(defname, ln, me[i]->name);
5537 ast_member_set_name(me[i], defname);
5539 vec_push(parser->globals, (ast_expression*)me[i]);
5544 vec_push(localblock->locals, var);
5545 parser_addlocal(parser, var->name, (ast_expression*)var);
5547 for (i = 0; i < 3; ++i) {
5548 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5549 ast_block_collect(localblock, (ast_expression*)me[i]);
5555 me[0] = me[1] = me[2] = NULL;
5560 if (var->expression.vtype == TYPE_ARRAY) {
5562 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5563 if (!parser_create_array_setter(parser, var, name))
5565 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5566 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5569 else if (!localblock && !nofields &&
5570 var->expression.vtype == TYPE_FIELD &&
5571 var->expression.next->expression.vtype == TYPE_ARRAY)
5574 ast_expression *telem;
5576 ast_value *array = (ast_value*)var->expression.next;
5578 if (!ast_istype(var->expression.next, ast_value)) {
5579 parseerror(parser, "internal error: field element type must be an ast_value");
5583 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5584 if (!parser_create_array_field_setter(parser, array, name))
5587 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5588 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5589 tfield->expression.next = telem;
5590 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5591 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5599 if (parser->tok == ';') {
5600 ast_delete(basetype);
5601 if (!parser_next(parser)) {
5602 parseerror(parser, "error after variable declaration");
5608 if (parser->tok == ',')
5612 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5615 parseerror(parser, "missing comma or semicolon while parsing variables");
5619 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5620 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5621 "initializing expression turns variable `%s` into a constant in this standard",
5628 if (parser->tok != '{') {
5629 if (parser->tok != '=') {
5630 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5634 if (!parser_next(parser)) {
5635 parseerror(parser, "error parsing initializer");
5639 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5640 parseerror(parser, "expected '=' before function body in this standard");
5643 if (parser->tok == '#') {
5644 ast_function *func = NULL;
5645 ast_value *number = NULL;
5651 parseerror(parser, "cannot declare builtins within functions");
5654 if (var->expression.vtype != TYPE_FUNCTION) {
5655 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5658 if (!parser_next(parser)) {
5659 parseerror(parser, "expected builtin number");
5663 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5664 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5666 parseerror(parser, "builtin number expected");
5669 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5672 parseerror(parser, "builtin number must be a compile time constant");
5675 if (number->expression.vtype == TYPE_INTEGER)
5676 builtin_num = number->constval.vint;
5677 else if (number->expression.vtype == TYPE_FLOAT)
5678 builtin_num = number->constval.vfloat;
5681 parseerror(parser, "builtin number must be an integer constant");
5686 fractional = modff(builtin_num, &integral);
5687 if (builtin_num < 0 || fractional != 0) {
5688 parseerror(parser, "builtin number must be an integer greater than zero");
5692 /* we only want the integral part anyways */
5693 builtin_num = integral;
5694 } else if (parser->tok == TOKEN_INTCONST) {
5695 builtin_num = parser_token(parser)->constval.i;
5697 parseerror(parser, "builtin number must be a compile time constant");
5701 if (var->hasvalue) {
5702 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5703 "builtin `%s` has already been defined\n"
5704 " -> previous declaration here: %s:%i",
5705 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5709 func = ast_function_new(ast_ctx(var), var->name, var);
5711 parseerror(parser, "failed to allocate function for `%s`", var->name);
5714 vec_push(parser->functions, func);
5716 func->builtin = -builtin_num-1;
5719 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5720 ? (parser->tok != ',' && parser->tok != ';')
5721 : (!parser_next(parser)))
5723 parseerror(parser, "expected comma or semicolon");
5725 ast_function_delete(func);
5726 var->constval.vfunc = NULL;
5730 else if (parser->tok == '{' || parser->tok == '[')
5733 parseerror(parser, "cannot declare functions within functions");
5738 ast_ctx(proto) = parser_ctx(parser);
5740 if (!parse_function_body(parser, var))
5742 ast_delete(basetype);
5743 for (i = 0; i < vec_size(parser->gotos); ++i)
5744 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5745 vec_free(parser->gotos);
5746 vec_free(parser->labels);
5749 ast_expression *cexp;
5752 cexp = parse_expression_leave(parser, true, false, false);
5757 cval = (ast_value*)cexp;
5758 if (cval != parser->nil &&
5759 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5762 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5766 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5767 qualifier != CV_VAR)
5769 var->cvq = CV_CONST;
5771 if (cval == parser->nil)
5772 var->expression.flags |= AST_FLAG_INITIALIZED;
5775 var->hasvalue = true;
5776 if (cval->expression.vtype == TYPE_STRING)
5777 var->constval.vstring = parser_strdup(cval->constval.vstring);
5778 else if (cval->expression.vtype == TYPE_FIELD)
5779 var->constval.vfield = cval;
5781 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5787 shunt sy = { NULL, NULL, NULL, NULL };
5790 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5791 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5792 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5793 if (!parser_sy_apply_operator(parser, &sy))
5796 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5797 parseerror(parser, "internal error: leaked operands");
5798 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5808 if (parser->tok == ',') {
5809 if (!parser_next(parser)) {
5810 parseerror(parser, "expected another variable");
5814 if (parser->tok != TOKEN_IDENT) {
5815 parseerror(parser, "expected another variable");
5818 var = ast_value_copy(basetype);
5820 ast_value_set_name(var, parser_tokval(parser));
5821 if (!parser_next(parser)) {
5822 parseerror(parser, "error parsing variable declaration");
5828 if (parser->tok != ';') {
5829 parseerror(parser, "missing semicolon after variables");
5833 if (!parser_next(parser)) {
5834 parseerror(parser, "parse error after variable declaration");
5838 ast_delete(basetype);
5842 if (cleanvar && var)
5844 ast_delete(basetype);
5848 ast_delete(basetype);
5849 if (cleanvar && var)
5851 if (me[0]) ast_member_delete(me[0]);
5852 if (me[1]) ast_member_delete(me[1]);
5853 if (me[2]) ast_member_delete(me[2]);
5857 static bool parser_global_statement(parser_t *parser)
5861 bool is_static = false;
5862 uint32_t qflags = 0;
5863 ast_value *istype = NULL;
5864 char *vstring = NULL;
5866 if (parser->tok == TOKEN_IDENT)
5867 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5869 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5871 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5873 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5875 if (cvq == CV_WRONG)
5877 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5879 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5881 return parse_enum(parser);
5883 else if (parser->tok == TOKEN_KEYWORD)
5885 if (!strcmp(parser_tokval(parser), "typedef")) {
5886 if (!parser_next(parser)) {
5887 parseerror(parser, "expected type definition after 'typedef'");
5890 return parse_typedef(parser);
5892 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5895 else if (parser->tok == '#')
5897 return parse_pragma(parser);
5899 else if (parser->tok == '$')
5901 if (!parser_next(parser)) {
5902 parseerror(parser, "parse error");
5908 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5914 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5916 return util_crc16(old, str, strlen(str));
5919 static void progdefs_crc_file(const char *str)
5921 /* write to progdefs.h here */
5925 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5927 old = progdefs_crc_sum(old, str);
5928 progdefs_crc_file(str);
5932 static void generate_checksum(parser_t *parser)
5934 uint16_t crc = 0xFFFF;
5938 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5939 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5941 progdefs_crc_file("\tint\tpad;\n");
5942 progdefs_crc_file("\tint\tofs_return[3];\n");
5943 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5944 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5945 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5946 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5947 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5948 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5949 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5950 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5952 for (i = 0; i < parser->crc_globals; ++i) {
5953 if (!ast_istype(parser->globals[i], ast_value))
5955 value = (ast_value*)(parser->globals[i]);
5956 switch (value->expression.vtype) {
5957 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5958 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5959 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5960 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5962 crc = progdefs_crc_both(crc, "\tint\t");
5965 crc = progdefs_crc_both(crc, value->name);
5966 crc = progdefs_crc_both(crc, ";\n");
5968 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5969 for (i = 0; i < parser->crc_fields; ++i) {
5970 if (!ast_istype(parser->fields[i], ast_value))
5972 value = (ast_value*)(parser->fields[i]);
5973 switch (value->expression.next->expression.vtype) {
5974 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5975 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5976 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5977 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5979 crc = progdefs_crc_both(crc, "\tint\t");
5982 crc = progdefs_crc_both(crc, value->name);
5983 crc = progdefs_crc_both(crc, ";\n");
5985 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5987 parser->code->crc = crc;
5990 parser_t *parser_create()
5996 parser = (parser_t*)mem_a(sizeof(parser_t));
6000 memset(parser, 0, sizeof(*parser));
6002 if (!(parser->code = code_init())) {
6008 for (i = 0; i < operator_count; ++i) {
6009 if (operators[i].id == opid1('=')) {
6010 parser->assign_op = operators+i;
6014 if (!parser->assign_op) {
6015 printf("internal error: initializing parser: failed to find assign operator\n");
6020 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6021 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6022 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6023 vec_push(parser->_blocktypedefs, 0);
6025 parser->aliases = util_htnew(PARSER_HT_SIZE);
6027 parser->ht_imm_string = util_htnew(512);
6030 vec_push(parser->correct_variables, correct_trie_new());
6031 vec_push(parser->correct_variables_score, NULL);
6033 empty_ctx.file = "<internal>";
6035 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6036 parser->nil->cvq = CV_CONST;
6037 if (OPTS_FLAG(UNTYPED_NIL))
6038 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6040 parser->max_param_count = 1;
6042 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6043 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6044 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6046 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6047 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6048 parser->reserved_version->cvq = CV_CONST;
6049 parser->reserved_version->hasvalue = true;
6050 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6051 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6053 parser->reserved_version = NULL;
6059 bool parser_compile(parser_t *parser)
6061 /* initial lexer/parser state */
6062 parser->lex->flags.noops = true;
6064 if (parser_next(parser))
6066 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6068 if (!parser_global_statement(parser)) {
6069 if (parser->tok == TOKEN_EOF)
6070 parseerror(parser, "unexpected eof");
6071 else if (compile_errors)
6072 parseerror(parser, "there have been errors, bailing out");
6073 lex_close(parser->lex);
6079 parseerror(parser, "parse error");
6080 lex_close(parser->lex);
6085 lex_close(parser->lex);
6088 return !compile_errors;
6091 bool parser_compile_file(parser_t *parser, const char *filename)
6093 parser->lex = lex_open(filename);
6095 con_err("failed to open file \"%s\"\n", filename);
6098 return parser_compile(parser);
6101 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6103 parser->lex = lex_open_string(str, len, name);
6105 con_err("failed to create lexer for string \"%s\"\n", name);
6108 return parser_compile(parser);
6111 void parser_cleanup(parser_t *parser)
6114 for (i = 0; i < vec_size(parser->accessors); ++i) {
6115 ast_delete(parser->accessors[i]->constval.vfunc);
6116 parser->accessors[i]->constval.vfunc = NULL;
6117 ast_delete(parser->accessors[i]);
6119 for (i = 0; i < vec_size(parser->functions); ++i) {
6120 ast_delete(parser->functions[i]);
6122 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6123 ast_delete(parser->imm_vector[i]);
6125 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6126 ast_delete(parser->imm_string[i]);
6128 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6129 ast_delete(parser->imm_float[i]);
6131 for (i = 0; i < vec_size(parser->fields); ++i) {
6132 ast_delete(parser->fields[i]);
6134 for (i = 0; i < vec_size(parser->globals); ++i) {
6135 ast_delete(parser->globals[i]);
6137 vec_free(parser->accessors);
6138 vec_free(parser->functions);
6139 vec_free(parser->imm_vector);
6140 vec_free(parser->imm_string);
6141 util_htdel(parser->ht_imm_string);
6142 vec_free(parser->imm_float);
6143 vec_free(parser->globals);
6144 vec_free(parser->fields);
6146 for (i = 0; i < vec_size(parser->variables); ++i)
6147 util_htdel(parser->variables[i]);
6148 vec_free(parser->variables);
6149 vec_free(parser->_blocklocals);
6150 vec_free(parser->_locals);
6153 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6154 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6156 vec_free(parser->correct_variables);
6157 vec_free(parser->correct_variables_score);
6160 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6161 ast_delete(parser->_typedefs[i]);
6162 vec_free(parser->_typedefs);
6163 for (i = 0; i < vec_size(parser->typedefs); ++i)
6164 util_htdel(parser->typedefs[i]);
6165 vec_free(parser->typedefs);
6166 vec_free(parser->_blocktypedefs);
6168 vec_free(parser->_block_ctx);
6170 vec_free(parser->labels);
6171 vec_free(parser->gotos);
6172 vec_free(parser->breaks);
6173 vec_free(parser->continues);
6175 ast_value_delete(parser->nil);
6177 ast_value_delete(parser->const_vec[0]);
6178 ast_value_delete(parser->const_vec[1]);
6179 ast_value_delete(parser->const_vec[2]);
6181 util_htdel(parser->aliases);
6183 intrin_intrinsics_destroy(parser);
6188 bool parser_finish(parser_t *parser, const char *output)
6194 if (compile_errors) {
6195 con_out("*** there were compile errors\n");
6199 ir = ir_builder_new("gmqcc_out");
6201 con_out("failed to allocate builder\n");
6205 for (i = 0; i < vec_size(parser->fields); ++i) {
6208 if (!ast_istype(parser->fields[i], ast_value))
6210 field = (ast_value*)parser->fields[i];
6211 hasvalue = field->hasvalue;
6212 field->hasvalue = false;
6213 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6214 con_out("failed to generate field %s\n", field->name);
6215 ir_builder_delete(ir);
6220 ast_expression *subtype;
6221 field->hasvalue = true;
6222 subtype = field->expression.next;
6223 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6224 if (subtype->expression.vtype == TYPE_FIELD)
6225 ifld->fieldtype = subtype->expression.next->expression.vtype;
6226 else if (subtype->expression.vtype == TYPE_FUNCTION)
6227 ifld->outtype = subtype->expression.next->expression.vtype;
6228 (void)!ir_value_set_field(field->ir_v, ifld);
6231 for (i = 0; i < vec_size(parser->globals); ++i) {
6233 if (!ast_istype(parser->globals[i], ast_value))
6235 asvalue = (ast_value*)(parser->globals[i]);
6236 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6237 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6238 "unused global: `%s`", asvalue->name);
6240 if (!ast_global_codegen(asvalue, ir, false)) {
6241 con_out("failed to generate global %s\n", asvalue->name);
6242 ir_builder_delete(ir);
6246 /* Build function vararg accessor ast tree now before generating
6247 * immediates, because the accessors may add new immediates
6249 for (i = 0; i < vec_size(parser->functions); ++i) {
6250 ast_function *f = parser->functions[i];
6252 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6253 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6254 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6255 con_out("failed to generate vararg setter for %s\n", f->name);
6256 ir_builder_delete(ir);
6259 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6260 con_out("failed to generate vararg getter for %s\n", f->name);
6261 ir_builder_delete(ir);
6265 ast_delete(f->varargs);
6270 /* Now we can generate immediates */
6271 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6272 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6273 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6274 ir_builder_delete(ir);
6278 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6279 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6280 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6281 ir_builder_delete(ir);
6285 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6286 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6287 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6288 ir_builder_delete(ir);
6292 for (i = 0; i < vec_size(parser->globals); ++i) {
6294 if (!ast_istype(parser->globals[i], ast_value))
6296 asvalue = (ast_value*)(parser->globals[i]);
6297 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6299 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6300 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6301 "uninitialized constant: `%s`",
6303 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6304 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6305 "uninitialized global: `%s`",
6308 if (!ast_generate_accessors(asvalue, ir)) {
6309 ir_builder_delete(ir);
6313 for (i = 0; i < vec_size(parser->fields); ++i) {
6315 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6317 if (!ast_istype((ast_expression*)asvalue, ast_value))
6319 if (asvalue->expression.vtype != TYPE_ARRAY)
6321 if (!ast_generate_accessors(asvalue, ir)) {
6322 ir_builder_delete(ir);
6326 if (parser->reserved_version &&
6327 !ast_global_codegen(parser->reserved_version, ir, false))
6329 con_out("failed to generate reserved::version");
6330 ir_builder_delete(ir);
6333 for (i = 0; i < vec_size(parser->functions); ++i) {
6334 ast_function *f = parser->functions[i];
6335 if (!ast_function_codegen(f, ir)) {
6336 con_out("failed to generate function %s\n", f->name);
6337 ir_builder_delete(ir);
6341 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6342 ir_builder_dump(ir, con_out);
6343 for (i = 0; i < vec_size(parser->functions); ++i) {
6344 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6345 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6346 ir_builder_delete(ir);
6351 if (compile_Werrors) {
6352 con_out("*** there were warnings treated as errors\n");
6353 compile_show_werrors();
6358 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6359 ir_builder_dump(ir, con_out);
6361 generate_checksum(parser);
6363 if (!ir_builder_generate(parser->code, ir, output)) {
6364 con_out("*** failed to generate output file\n");
6365 ir_builder_delete(ir);
6370 ir_builder_delete(ir);