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;
110 /* vector of global return vars.
111 * for example, you can return string, float, vector, or other
112 * things, hese will be created as globals here instead of
113 * locals in a function (saves space).
118 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
120 static void parser_enterblock(parser_t *parser);
121 static bool parser_leaveblock(parser_t *parser);
122 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
123 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
124 static bool parse_typedef(parser_t *parser);
125 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);
126 static ast_block* parse_block(parser_t *parser);
127 static bool parse_block_into(parser_t *parser, ast_block *block);
128 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
129 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
130 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
131 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
132 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
133 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
134 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
136 static void parseerror(parser_t *parser, const char *fmt, ...)
140 vcompile_error(parser->lex->tok.ctx, fmt, ap);
144 /* returns true if it counts as an error */
145 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
150 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
155 /**********************************************************************
156 * some maths used for constant folding
159 vector vec3_add(vector a, vector b)
168 vector vec3_sub(vector a, vector b)
177 qcfloat vec3_mulvv(vector a, vector b)
179 return (a.x * b.x + a.y * b.y + a.z * b.z);
182 vector vec3_mulvf(vector a, float b)
191 /**********************************************************************
195 static bool parser_next(parser_t *parser)
197 /* lex_do kills the previous token */
198 parser->tok = lex_do(parser->lex);
199 if (parser->tok == TOKEN_EOF)
201 if (parser->tok >= TOKEN_ERROR) {
202 parseerror(parser, "lex error");
208 #define parser_tokval(p) ((p)->lex->tok.value)
209 #define parser_token(p) (&((p)->lex->tok))
210 #define parser_ctx(p) ((p)->lex->tok.ctx)
212 static ast_value* parser_const_float(parser_t *parser, double d)
217 for (i = 0; i < vec_size(parser->imm_float); ++i) {
218 const double compare = parser->imm_float[i]->constval.vfloat;
219 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
220 return parser->imm_float[i];
223 ctx = parser_ctx(parser);
225 memset(&ctx, 0, sizeof(ctx));
227 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
229 out->hasvalue = true;
231 out->constval.vfloat = d;
232 vec_push(parser->imm_float, out);
236 static ast_value* parser_const_float_0(parser_t *parser)
238 if (!parser->imm_float_zero)
239 parser->imm_float_zero = parser_const_float(parser, 0);
240 return parser->imm_float_zero;
243 static ast_value* parser_const_float_neg1(parser_t *parser) {
244 if (!parser->imm_float_neg_one)
245 parser->imm_float_neg_one = parser_const_float(parser, -1);
246 return parser->imm_float_neg_one;
249 static ast_value* parser_const_float_1(parser_t *parser)
251 if (!parser->imm_float_one)
252 parser->imm_float_one = parser_const_float(parser, 1);
253 return parser->imm_float_one;
256 static char *parser_strdup(const char *str)
259 /* actually dup empty strings */
260 char *out = (char*)mem_a(1);
264 return util_strdup(str);
267 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
269 size_t hash = util_hthash(parser->ht_imm_string, str);
271 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
272 if (dotranslate && out->name[0] == '#') {
274 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
275 ast_value_set_name(out, name);
280 for (i = 0; i < vec_size(parser->imm_string); ++i) {
281 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
282 return parser->imm_string[i];
287 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
288 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
290 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
292 out->hasvalue = true;
294 out->constval.vstring = parser_strdup(str);
295 vec_push(parser->imm_string, out);
296 util_htseth(parser->ht_imm_string, str, hash, out);
300 static ast_value* parser_const_vector(parser_t *parser, vector v)
304 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
305 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
306 return parser->imm_vector[i];
308 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
310 out->hasvalue = true;
312 out->constval.vvec = v;
313 vec_push(parser->imm_vector, out);
317 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
323 return parser_const_vector(parser, v);
326 static ast_value* parser_const_vector_0(parser_t *parser)
328 if (!parser->imm_vector_zero)
329 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
330 return parser->imm_vector_zero;
333 static ast_expression* parser_find_field(parser_t *parser, const char *name)
335 return ( ast_expression*)util_htget(parser->htfields, name);
338 static ast_expression* parser_find_label(parser_t *parser, const char *name)
341 for(i = 0; i < vec_size(parser->labels); i++)
342 if (!strcmp(parser->labels[i]->name, name))
343 return (ast_expression*)parser->labels[i];
347 static ast_expression* parser_find_global(parser_t *parser, const char *name)
349 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
352 return (ast_expression*)util_htget(parser->htglobals, name);
355 static ast_value* parser_find_returnvalue(parser_t *parser, int vtype)
361 /* find existing global for the job */
362 for (i = 0; i < vec_size(parser->returns); i++)
363 if (parser->returns[i]->expression.vtype == vtype)
364 return parser->returns[i];
366 util_asprintf(&name, "#ret_%s", type_name[vtype]);
368 out = ast_value_new(parser_ctx(parser), name, vtype);
369 out->hasvalue = false;
372 vec_push(parser->returns, out);
378 static ast_expression* parser_find_param(parser_t *parser, const char *name)
382 if (!parser->function)
384 fun = parser->function->vtype;
385 for (i = 0; i < vec_size(fun->expression.params); ++i) {
386 if (!strcmp(fun->expression.params[i]->name, name))
387 return (ast_expression*)(fun->expression.params[i]);
392 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
397 hash = util_hthash(parser->htglobals, name);
400 for (i = vec_size(parser->variables); i > upto;) {
402 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
406 return parser_find_param(parser, name);
409 static ast_expression* parser_find_var(parser_t *parser, const char *name)
413 v = parser_find_local(parser, name, 0, &dummy);
414 if (!v) v = parser_find_global(parser, name);
418 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
422 hash = util_hthash(parser->typedefs[0], name);
424 for (i = vec_size(parser->typedefs); i > upto;) {
426 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
432 /* include intrinsics */
437 size_t etype; /* 0 = expression, others are operators */
441 ast_block *block; /* for commas and function calls */
460 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
471 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
475 e.out = (ast_expression*)v;
482 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
484 e.etype = 1 + (op - operators);
493 static sy_elem syparen(lex_ctx ctx, size_t off) {
504 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
505 * so we need to rotate it to become ent.(foo[n]).
507 static bool rotate_entfield_array_index_nodes(ast_expression **out)
509 ast_array_index *index, *oldindex;
510 ast_entfield *entfield;
514 ast_expression *entity;
516 lex_ctx ctx = ast_ctx(*out);
518 if (!ast_istype(*out, ast_array_index))
520 index = (ast_array_index*)*out;
522 if (!ast_istype(index->array, ast_entfield))
524 entfield = (ast_entfield*)index->array;
526 if (!ast_istype(entfield->field, ast_value))
528 field = (ast_value*)entfield->field;
531 entity = entfield->entity;
535 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
536 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
537 *out = (ast_expression*)entfield;
539 oldindex->array = NULL;
540 oldindex->index = NULL;
541 ast_delete(oldindex);
546 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
548 switch (v->expression.vtype) {
550 return !!v->constval.vfloat;
552 return !!v->constval.vint;
554 if (OPTS_FLAG(CORRECT_LOGIC))
555 return v->constval.vvec.x &&
556 v->constval.vvec.y &&
559 return !!(v->constval.vvec.x);
561 if (!v->constval.vstring)
563 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
565 return !!v->constval.vstring[0];
567 compile_error(ctx, "internal error: immediate_is_true on invalid type");
568 return !!v->constval.vfunc;
572 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
576 ast_expression *out = NULL;
577 ast_expression *exprs[3];
578 ast_block *blocks[3];
579 ast_value *asvalue[3];
580 ast_binstore *asbinstore;
581 size_t i, assignop, addop, subop;
582 qcint generated_op = 0;
587 if (!vec_size(sy->ops)) {
588 parseerror(parser, "internal error: missing operator");
592 if (vec_last(sy->ops).isparen) {
593 parseerror(parser, "unmatched parenthesis");
597 op = &operators[vec_last(sy->ops).etype - 1];
598 ctx = vec_last(sy->ops).ctx;
600 if (vec_size(sy->out) < op->operands) {
601 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
602 op->op, (int)op->id);
606 vec_shrinkby(sy->ops, 1);
608 /* op(:?) has no input and no output */
612 vec_shrinkby(sy->out, op->operands);
613 for (i = 0; i < op->operands; ++i) {
614 exprs[i] = sy->out[vec_size(sy->out)+i].out;
615 blocks[i] = sy->out[vec_size(sy->out)+i].block;
616 asvalue[i] = (ast_value*)exprs[i];
618 if (exprs[i]->vtype == TYPE_NOEXPR &&
619 !(i != 0 && op->id == opid2('?',':')) &&
620 !(i == 1 && op->id == opid1('.')))
622 if (ast_istype(exprs[i], ast_label))
623 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
625 compile_error(ast_ctx(exprs[i]), "not an expression");
626 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
630 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
631 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
635 #define NotSameType(T) \
636 (exprs[0]->vtype != exprs[1]->vtype || \
637 exprs[0]->vtype != T)
638 #define CanConstFold1(A) \
639 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
640 (A)->vtype != TYPE_FUNCTION)
641 #define CanConstFold(A, B) \
642 (CanConstFold1(A) && CanConstFold1(B))
643 #define ConstV(i) (asvalue[(i)]->constval.vvec)
644 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
645 #define ConstS(i) (asvalue[(i)]->constval.vstring)
649 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
653 if (exprs[0]->vtype == TYPE_VECTOR &&
654 exprs[1]->vtype == TYPE_NOEXPR)
656 if (exprs[1] == (ast_expression*)parser->const_vec[0])
657 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
658 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
659 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
660 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
661 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
663 compile_error(ctx, "access to invalid vector component");
667 else if (exprs[0]->vtype == TYPE_ENTITY) {
668 if (exprs[1]->vtype != TYPE_FIELD) {
669 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
672 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
674 else if (exprs[0]->vtype == TYPE_VECTOR) {
675 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
679 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
685 if (exprs[0]->vtype != TYPE_ARRAY &&
686 !(exprs[0]->vtype == TYPE_FIELD &&
687 exprs[0]->next->vtype == TYPE_ARRAY))
689 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
690 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
693 if (exprs[1]->vtype != TYPE_FLOAT) {
694 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
695 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
698 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
699 if (rotate_entfield_array_index_nodes(&out))
702 /* This is not broken in fteqcc anymore */
703 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
704 /* this error doesn't need to make us bail out */
705 (void)!parsewarning(parser, WARN_EXTENSIONS,
706 "accessing array-field members of an entity without parenthesis\n"
707 " -> this is an extension from -std=gmqcc");
714 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
715 vec_push(sy->out, syexp(ctx, exprs[0]));
716 vec_push(sy->out, syexp(ctx, exprs[1]));
717 vec_last(sy->argc)++;
721 if (!ast_block_add_expr(blocks[0], exprs[1]))
724 blocks[0] = ast_block_new(ctx);
725 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
726 !ast_block_add_expr(blocks[0], exprs[1]))
731 ast_block_set_type(blocks[0], exprs[1]);
733 vec_push(sy->out, syblock(ctx, blocks[0]));
740 switch (exprs[0]->vtype) {
742 if (CanConstFold1(exprs[0]))
743 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
745 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
746 (ast_expression*)parser_const_float_0(parser),
750 if (CanConstFold1(exprs[0]))
751 out = (ast_expression*)parser_const_vector_f(parser,
752 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
754 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
755 (ast_expression*)parser_const_vector_0(parser),
759 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
760 type_name[exprs[0]->vtype]);
766 switch (exprs[0]->vtype) {
768 if (CanConstFold1(exprs[0]))
769 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
771 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
774 if (CanConstFold1(exprs[0]))
775 out = (ast_expression*)parser_const_float(parser,
776 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
778 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
781 if (CanConstFold1(exprs[0])) {
782 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
783 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
785 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
787 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
788 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
790 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
793 /* we don't constant-fold NOT for these types */
795 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
798 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
801 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
802 type_name[exprs[0]->vtype]);
808 if (exprs[0]->vtype != exprs[1]->vtype ||
809 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
811 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
812 type_name[exprs[0]->vtype],
813 type_name[exprs[1]->vtype]);
816 switch (exprs[0]->vtype) {
818 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
823 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
826 if (CanConstFold(exprs[0], exprs[1]))
827 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
829 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
832 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
833 type_name[exprs[0]->vtype],
834 type_name[exprs[1]->vtype]);
839 if (exprs[0]->vtype != exprs[1]->vtype ||
840 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
842 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
843 type_name[exprs[1]->vtype],
844 type_name[exprs[0]->vtype]);
847 switch (exprs[0]->vtype) {
849 if (CanConstFold(exprs[0], exprs[1]))
850 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
852 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
855 if (CanConstFold(exprs[0], exprs[1]))
856 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
858 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
861 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
862 type_name[exprs[1]->vtype],
863 type_name[exprs[0]->vtype]);
868 if (exprs[0]->vtype != exprs[1]->vtype &&
869 !(exprs[0]->vtype == TYPE_VECTOR &&
870 exprs[1]->vtype == TYPE_FLOAT) &&
871 !(exprs[1]->vtype == TYPE_VECTOR &&
872 exprs[0]->vtype == TYPE_FLOAT)
875 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
876 type_name[exprs[1]->vtype],
877 type_name[exprs[0]->vtype]);
880 switch (exprs[0]->vtype) {
882 if (exprs[1]->vtype == TYPE_VECTOR)
884 if (CanConstFold(exprs[0], exprs[1]))
885 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
891 if (CanConstFold(exprs[0], exprs[1]))
892 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
894 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
898 if (exprs[1]->vtype == TYPE_FLOAT)
900 if (CanConstFold(exprs[0], exprs[1]))
901 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
903 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
907 if (CanConstFold(exprs[0], exprs[1]))
908 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
909 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
910 vector vec = ConstV(0);
911 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
912 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
913 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
914 out->node.keep = false;
915 ((ast_member*)out)->rvalue = true;
917 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
919 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
920 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
921 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
922 out->node.keep = false;
923 ((ast_member*)out)->rvalue = true;
925 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
927 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
928 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
929 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
930 out->node.keep = false;
931 ((ast_member*)out)->rvalue = true;
933 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
936 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
938 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
939 vector vec = ConstV(1);
940 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
941 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
942 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
943 out->node.keep = false;
944 ((ast_member*)out)->rvalue = true;
946 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
948 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
949 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
950 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
951 out->node.keep = false;
952 ((ast_member*)out)->rvalue = true;
954 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
956 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
957 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
958 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
959 out->node.keep = false;
960 ((ast_member*)out)->rvalue = true;
962 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
965 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
968 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
972 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
973 type_name[exprs[1]->vtype],
974 type_name[exprs[0]->vtype]);
979 if (exprs[1]->vtype != TYPE_FLOAT) {
980 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
981 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
982 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
985 if (exprs[0]->vtype == TYPE_FLOAT) {
986 if (CanConstFold(exprs[0], exprs[1]))
987 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
989 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
991 else if (exprs[0]->vtype == TYPE_VECTOR) {
992 if (CanConstFold(exprs[0], exprs[1]))
993 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
995 if (CanConstFold1(exprs[1])) {
996 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
998 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
999 (ast_expression*)parser_const_float_1(parser),
1003 compile_error(ctx, "internal error: failed to generate division");
1006 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
1011 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1012 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1013 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
1019 if (NotSameType(TYPE_FLOAT)) {
1020 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
1021 type_name[exprs[0]->vtype],
1022 type_name[exprs[1]->vtype]);
1025 if (CanConstFold(exprs[0], exprs[1])) {
1026 out = (ast_expression*)parser_const_float(parser,
1027 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
1029 /* generate a call to __builtin_mod */
1030 ast_expression *mod = intrin_func(parser, "mod");
1031 ast_call *call = NULL;
1032 if (!mod) return false; /* can return null for missing floor */
1034 call = ast_call_new(parser_ctx(parser), mod);
1035 vec_push(call->params, exprs[0]);
1036 vec_push(call->params, exprs[1]);
1038 out = (ast_expression*)call;
1042 case opid2('%','='):
1043 compile_error(ctx, "%= is unimplemented");
1048 if (NotSameType(TYPE_FLOAT)) {
1049 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1050 type_name[exprs[0]->vtype],
1051 type_name[exprs[1]->vtype]);
1054 if (CanConstFold(exprs[0], exprs[1]))
1055 out = (ast_expression*)parser_const_float(parser,
1056 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1057 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1059 out = (ast_expression*)ast_binary_new(ctx,
1060 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1061 exprs[0], exprs[1]);
1064 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1067 case opid2('<','<'):
1068 case opid2('>','>'):
1069 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1070 if (op->id == opid2('<','<'))
1071 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1073 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1076 case opid3('<','<','='):
1077 case opid3('>','>','='):
1078 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1081 case opid2('|','|'):
1082 generated_op += 1; /* INSTR_OR */
1083 case opid2('&','&'):
1084 generated_op += INSTR_AND;
1085 if (CanConstFold(exprs[0], exprs[1]))
1087 if (OPTS_FLAG(PERL_LOGIC)) {
1088 if (immediate_is_true(ctx, asvalue[0]))
1092 out = (ast_expression*)parser_const_float(parser,
1093 ( (generated_op == INSTR_OR)
1094 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1095 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1100 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1101 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1102 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1103 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1106 for (i = 0; i < 2; ++i) {
1107 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1108 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1110 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1112 exprs[i] = out; out = NULL;
1113 if (OPTS_FLAG(PERL_LOGIC)) {
1114 /* here we want to keep the right expressions' type */
1118 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1119 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1121 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1123 exprs[i] = out; out = NULL;
1124 if (OPTS_FLAG(PERL_LOGIC)) {
1125 /* here we want to keep the right expressions' type */
1130 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1134 case opid2('?',':'):
1135 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1136 compile_error(ctx, "mismatched parenthesis/ternary");
1140 if (!ast_compare_type(exprs[1], exprs[2])) {
1141 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1142 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1143 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1146 if (CanConstFold1(exprs[0]))
1147 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1149 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1152 case opid2('*', '*'):
1153 if (NotSameType(TYPE_FLOAT)) {
1154 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1155 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1156 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1162 if (CanConstFold(exprs[0], exprs[1])) {
1163 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1165 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1166 vec_push(gencall->params, exprs[0]);
1167 vec_push(gencall->params, exprs[1]);
1168 out = (ast_expression*)gencall;
1172 case opid3('<','=','>'): /* -1, 0, or 1 */
1173 if (NotSameType(TYPE_FLOAT)) {
1174 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1175 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1176 compile_error(ctx, "invalid types used in comparision: %s and %s",
1182 if (CanConstFold(exprs[0], exprs[1])) {
1183 if (ConstF(0) < ConstF(1))
1184 out = (ast_expression*)parser_const_float_neg1(parser);
1185 else if (ConstF(0) == ConstF(1))
1186 out = (ast_expression*)parser_const_float_0(parser);
1187 else if (ConstF(0) > ConstF(1))
1188 out = (ast_expression*)parser_const_float_1(parser);
1190 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1192 eq->refs = (ast_binary_ref)false; /* references nothing */
1195 out = (ast_expression*)ast_ternary_new(ctx,
1196 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1198 (ast_expression*)parser_const_float_neg1(parser),
1201 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1203 (ast_expression*)parser_const_float_0(parser),
1206 (ast_expression*)parser_const_float_1(parser)
1216 generated_op += 1; /* INSTR_GT */
1218 generated_op += 1; /* INSTR_LT */
1219 case opid2('>', '='):
1220 generated_op += 1; /* INSTR_GE */
1221 case opid2('<', '='):
1222 generated_op += INSTR_LE;
1223 if (NotSameType(TYPE_FLOAT)) {
1224 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1225 type_name[exprs[0]->vtype],
1226 type_name[exprs[1]->vtype]);
1229 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1231 case opid2('!', '='):
1232 if (exprs[0]->vtype != exprs[1]->vtype) {
1233 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1234 type_name[exprs[0]->vtype],
1235 type_name[exprs[1]->vtype]);
1238 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1240 case opid2('=', '='):
1241 if (exprs[0]->vtype != exprs[1]->vtype) {
1242 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1243 type_name[exprs[0]->vtype],
1244 type_name[exprs[1]->vtype]);
1247 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1251 if (ast_istype(exprs[0], ast_entfield)) {
1252 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1253 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1254 exprs[0]->vtype == TYPE_FIELD &&
1255 exprs[0]->next->vtype == TYPE_VECTOR)
1257 assignop = type_storep_instr[TYPE_VECTOR];
1260 assignop = type_storep_instr[exprs[0]->vtype];
1261 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1263 ast_type_to_string(field->next, ty1, sizeof(ty1));
1264 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1265 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1266 field->next->vtype == TYPE_FUNCTION &&
1267 exprs[1]->vtype == TYPE_FUNCTION)
1269 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1270 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1273 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1278 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1279 exprs[0]->vtype == TYPE_FIELD &&
1280 exprs[0]->next->vtype == TYPE_VECTOR)
1282 assignop = type_store_instr[TYPE_VECTOR];
1285 assignop = type_store_instr[exprs[0]->vtype];
1288 if (assignop == VINSTR_END) {
1289 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1290 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1291 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1293 else if (!ast_compare_type(exprs[0], exprs[1]))
1295 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1296 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1297 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1298 exprs[0]->vtype == TYPE_FUNCTION &&
1299 exprs[1]->vtype == TYPE_FUNCTION)
1301 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1302 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1305 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1308 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1309 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1311 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1313 case opid3('+','+','P'):
1314 case opid3('-','-','P'):
1316 if (exprs[0]->vtype != TYPE_FLOAT) {
1317 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1318 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1321 if (op->id == opid3('+','+','P'))
1322 addop = INSTR_ADD_F;
1324 addop = INSTR_SUB_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));
1338 case opid3('S','+','+'):
1339 case opid3('S','-','-'):
1341 if (exprs[0]->vtype != TYPE_FLOAT) {
1342 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1343 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1346 if (op->id == opid3('S','+','+')) {
1347 addop = INSTR_ADD_F;
1348 subop = INSTR_SUB_F;
1350 addop = INSTR_SUB_F;
1351 subop = INSTR_ADD_F;
1353 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1354 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1356 if (ast_istype(exprs[0], ast_entfield)) {
1357 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1359 (ast_expression*)parser_const_float_1(parser));
1361 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1363 (ast_expression*)parser_const_float_1(parser));
1367 out = (ast_expression*)ast_binary_new(ctx, subop,
1369 (ast_expression*)parser_const_float_1(parser));
1371 case opid2('+','='):
1372 case opid2('-','='):
1373 if (exprs[0]->vtype != exprs[1]->vtype ||
1374 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1376 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1377 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1378 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1382 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1383 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1385 if (ast_istype(exprs[0], ast_entfield))
1386 assignop = type_storep_instr[exprs[0]->vtype];
1388 assignop = type_store_instr[exprs[0]->vtype];
1389 switch (exprs[0]->vtype) {
1391 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1392 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1393 exprs[0], exprs[1]);
1396 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1397 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1398 exprs[0], exprs[1]);
1401 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1402 type_name[exprs[0]->vtype],
1403 type_name[exprs[1]->vtype]);
1407 case opid2('*','='):
1408 case opid2('/','='):
1409 if (exprs[1]->vtype != TYPE_FLOAT ||
1410 !(exprs[0]->vtype == TYPE_FLOAT ||
1411 exprs[0]->vtype == TYPE_VECTOR))
1413 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1414 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1415 compile_error(ctx, "invalid types used in expression: %s and %s",
1419 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1420 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1422 if (ast_istype(exprs[0], ast_entfield))
1423 assignop = type_storep_instr[exprs[0]->vtype];
1425 assignop = type_store_instr[exprs[0]->vtype];
1426 switch (exprs[0]->vtype) {
1428 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1429 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1430 exprs[0], exprs[1]);
1433 if (op->id == opid2('*','=')) {
1434 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1435 exprs[0], exprs[1]);
1437 /* there's no DIV_VF */
1438 if (CanConstFold1(exprs[1])) {
1439 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1441 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1442 (ast_expression*)parser_const_float_1(parser),
1446 compile_error(ctx, "internal error: failed to generate division");
1449 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1454 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1455 type_name[exprs[0]->vtype],
1456 type_name[exprs[1]->vtype]);
1460 case opid2('&','='):
1461 case opid2('|','='):
1462 if (NotSameType(TYPE_FLOAT)) {
1463 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1464 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1465 compile_error(ctx, "invalid types used in expression: %s and %s",
1469 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1470 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1472 if (ast_istype(exprs[0], ast_entfield))
1473 assignop = type_storep_instr[exprs[0]->vtype];
1475 assignop = type_store_instr[exprs[0]->vtype];
1476 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1477 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1478 exprs[0], exprs[1]);
1480 case opid3('&','~','='):
1481 /* This is like: a &= ~(b);
1482 * But QC has no bitwise-not, so we implement it as
1485 if (NotSameType(TYPE_FLOAT)) {
1486 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1487 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1488 compile_error(ctx, "invalid types used in expression: %s and %s",
1492 if (ast_istype(exprs[0], ast_entfield))
1493 assignop = type_storep_instr[exprs[0]->vtype];
1495 assignop = type_store_instr[exprs[0]->vtype];
1496 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1499 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1500 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1502 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1503 asbinstore->keep_dest = true;
1504 out = (ast_expression*)asbinstore;
1507 case opid2('~', 'P'):
1508 if (exprs[0]->vtype != TYPE_FLOAT) {
1509 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1510 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1514 if(CanConstFold1(exprs[0]))
1515 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1517 out = (ast_expression*)
1518 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1524 compile_error(ctx, "failed to apply operator %s", op->op);
1528 vec_push(sy->out, syexp(ctx, out));
1532 static bool parser_close_call(parser_t *parser, shunt *sy)
1534 /* was a function call */
1535 ast_expression *fun;
1536 ast_value *funval = NULL;
1540 size_t paramcount, i;
1542 fid = vec_last(sy->ops).off;
1543 vec_shrinkby(sy->ops, 1);
1545 /* out[fid] is the function
1546 * everything above is parameters...
1548 if (!vec_size(sy->argc)) {
1549 parseerror(parser, "internal error: no argument counter available");
1553 paramcount = vec_last(sy->argc);
1556 if (vec_size(sy->out) < fid) {
1557 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1558 (unsigned long)vec_size(sy->out),
1560 (unsigned long)paramcount);
1564 fun = sy->out[fid].out;
1566 if (fun == intrinsic_debug_typestring) {
1568 if (fid+2 != vec_size(sy->out) ||
1569 vec_last(sy->out).block)
1571 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1574 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1575 ast_unref(vec_last(sy->out).out);
1576 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1577 (ast_expression*)parser_const_string(parser, ty, false));
1578 vec_shrinkby(sy->out, 1);
1582 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1586 if (fid+1 < vec_size(sy->out))
1589 if (fid+1 + paramcount != vec_size(sy->out)) {
1590 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1591 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1595 for (i = 0; i < paramcount; ++i)
1596 vec_push(call->params, sy->out[fid+1 + i].out);
1597 vec_shrinkby(sy->out, paramcount);
1598 (void)!ast_call_check_types(call);
1599 if (parser->max_param_count < paramcount)
1600 parser->max_param_count = paramcount;
1602 if (ast_istype(fun, ast_value)) {
1603 funval = (ast_value*)fun;
1604 if ((fun->flags & AST_FLAG_VARIADIC) &&
1605 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1607 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1611 /* overwrite fid, the function, with a call */
1612 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1614 if (fun->vtype != TYPE_FUNCTION) {
1615 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1620 parseerror(parser, "could not determine function return type");
1623 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1625 if (fun->flags & AST_FLAG_DEPRECATED) {
1627 return !parsewarning(parser, WARN_DEPRECATED,
1628 "call to function (which is marked deprecated)\n",
1629 "-> it has been declared here: %s:%i",
1630 ast_ctx(fun).file, ast_ctx(fun).line);
1633 return !parsewarning(parser, WARN_DEPRECATED,
1634 "call to `%s` (which is marked deprecated)\n"
1635 "-> `%s` declared here: %s:%i",
1636 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1638 return !parsewarning(parser, WARN_DEPRECATED,
1639 "call to `%s` (deprecated: %s)\n"
1640 "-> `%s` declared here: %s:%i",
1641 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1645 if (vec_size(fun->params) != paramcount &&
1646 !((fun->flags & AST_FLAG_VARIADIC) &&
1647 vec_size(fun->params) < paramcount))
1649 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1651 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1652 "too %s parameters for call to %s: expected %i, got %i\n"
1653 " -> `%s` has been declared here: %s:%i",
1654 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1655 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1657 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1658 "too %s parameters for function call: expected %i, got %i\n"
1659 " -> it has been declared here: %s:%i",
1660 fewmany, (int)vec_size(fun->params), (int)paramcount,
1661 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1668 static bool parser_close_paren(parser_t *parser, shunt *sy)
1670 if (!vec_size(sy->ops)) {
1671 parseerror(parser, "unmatched closing paren");
1675 while (vec_size(sy->ops)) {
1676 if (vec_last(sy->ops).isparen) {
1677 if (vec_last(sy->paren) == PAREN_FUNC) {
1679 if (!parser_close_call(parser, sy))
1683 if (vec_last(sy->paren) == PAREN_EXPR) {
1685 if (!vec_size(sy->out)) {
1686 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1687 vec_shrinkby(sy->ops, 1);
1690 vec_shrinkby(sy->ops, 1);
1693 if (vec_last(sy->paren) == PAREN_INDEX) {
1695 /* pop off the parenthesis */
1696 vec_shrinkby(sy->ops, 1);
1697 /* then apply the index operator */
1698 if (!parser_sy_apply_operator(parser, sy))
1702 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1703 vec_last(sy->paren) = PAREN_TERNARY2;
1704 /* pop off the parenthesis */
1705 vec_shrinkby(sy->ops, 1);
1708 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1711 if (!parser_sy_apply_operator(parser, sy))
1717 static void parser_reclassify_token(parser_t *parser)
1720 for (i = 0; i < operator_count; ++i) {
1721 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1722 parser->tok = TOKEN_OPERATOR;
1728 static ast_expression* parse_vararg_do(parser_t *parser)
1730 ast_expression *idx, *out;
1732 ast_value *funtype = parser->function->vtype;
1734 lex_ctx ctx = parser_ctx(parser);
1736 if (!parser_next(parser) || parser->tok != '(') {
1737 parseerror(parser, "expected parameter index and type in parenthesis");
1740 if (!parser_next(parser)) {
1741 parseerror(parser, "error parsing parameter index");
1745 idx = parse_expression_leave(parser, true, false, false);
1749 if (parser->tok != ',') {
1751 parseerror(parser, "expected comma after parameter index");
1755 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1757 parseerror(parser, "expected typename for vararg");
1761 typevar = parse_typename(parser, NULL, NULL);
1767 if (parser->tok != ')') {
1769 ast_delete(typevar);
1770 parseerror(parser, "expected closing paren");
1775 if (!parser_next(parser)) {
1777 ast_delete(typevar);
1778 parseerror(parser, "parse error after vararg");
1783 if (!parser->function->varargs) {
1785 ast_delete(typevar);
1786 parseerror(parser, "function has no variable argument list");
1790 if (funtype->expression.varparam &&
1791 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1795 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1796 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1797 compile_error(ast_ctx(typevar),
1798 "function was declared to take varargs of type `%s`, requested type is: %s",
1802 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1803 ast_type_adopt(out, typevar);
1804 ast_delete(typevar);
1808 static ast_expression* parse_vararg(parser_t *parser)
1810 bool old_noops = parser->lex->flags.noops;
1812 ast_expression *out;
1814 parser->lex->flags.noops = true;
1815 out = parse_vararg_do(parser);
1817 parser->lex->flags.noops = old_noops;
1821 /* not to be exposed */
1822 extern bool ftepp_predef_exists(const char *name);
1824 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1826 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1827 parser->tok == TOKEN_IDENT &&
1828 !strcmp(parser_tokval(parser), "_"))
1830 /* a translatable string */
1833 parser->lex->flags.noops = true;
1834 if (!parser_next(parser) || parser->tok != '(') {
1835 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1838 parser->lex->flags.noops = false;
1839 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1840 parseerror(parser, "expected a constant string in translatable-string extension");
1843 val = parser_const_string(parser, parser_tokval(parser), true);
1846 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1848 if (!parser_next(parser) || parser->tok != ')') {
1849 parseerror(parser, "expected closing paren after translatable string");
1854 else if (parser->tok == TOKEN_DOTS)
1857 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1858 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1861 va = parse_vararg(parser);
1864 vec_push(sy->out, syexp(parser_ctx(parser), va));
1867 else if (parser->tok == TOKEN_FLOATCONST) {
1869 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1872 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1875 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1877 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1880 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1883 else if (parser->tok == TOKEN_STRINGCONST) {
1885 val = parser_const_string(parser, parser_tokval(parser), false);
1888 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1891 else if (parser->tok == TOKEN_VECTORCONST) {
1893 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1896 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1899 else if (parser->tok == TOKEN_IDENT)
1901 const char *ctoken = parser_tokval(parser);
1902 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1903 ast_expression *var;
1904 /* a_vector.{x,y,z} */
1905 if (!vec_size(sy->ops) ||
1906 !vec_last(sy->ops).etype ||
1907 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1908 (prev >= intrinsic_debug_typestring &&
1909 prev <= intrinsic_debug_typestring))
1911 /* When adding more intrinsics, fix the above condition */
1914 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1916 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1918 var = parser_find_var(parser, parser_tokval(parser));
1920 var = parser_find_field(parser, parser_tokval(parser));
1922 if (!var && with_labels) {
1923 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1925 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1926 var = (ast_expression*)lbl;
1927 vec_push(parser->labels, lbl);
1930 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1931 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1934 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1935 var = (ast_expression*)intrinsic_debug_typestring;
1937 /* now we try for the real intrinsic hashtable. If the string
1938 * begins with __builtin, we simply skip past it, otherwise we
1939 * use the identifier as is.
1941 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1942 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1946 char *correct = NULL;
1950 * sometimes people use preprocessing predefs without enabling them
1951 * i've done this thousands of times already myself. Lets check for
1952 * it in the predef table. And diagnose it better :)
1954 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1955 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1960 * TODO: determine the best score for the identifier: be it
1961 * a variable, a field.
1963 * We should also consider adding correction tables for
1964 * other things as well.
1966 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1968 correct_init(&corr);
1970 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1971 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1972 if (strcmp(correct, parser_tokval(parser))) {
1974 } else if (correct) {
1979 correct_free(&corr);
1982 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1987 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1993 if (ast_istype(var, ast_value)) {
1994 ((ast_value*)var)->uses++;
1996 else if (ast_istype(var, ast_member)) {
1997 ast_member *mem = (ast_member*)var;
1998 if (ast_istype(mem->owner, ast_value))
1999 ((ast_value*)(mem->owner))->uses++;
2002 vec_push(sy->out, syexp(parser_ctx(parser), var));
2005 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2009 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2011 ast_expression *expr = NULL;
2014 bool wantop = false;
2015 /* only warn once about an assignment in a truth value because the current code
2016 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2018 bool warn_truthvalue = true;
2020 /* count the parens because an if starts with one, so the
2021 * end of a condition is an unmatched closing paren
2025 memset(&sy, 0, sizeof(sy));
2027 parser->lex->flags.noops = false;
2029 parser_reclassify_token(parser);
2033 if (parser->tok == TOKEN_TYPENAME) {
2034 parseerror(parser, "unexpected typename");
2038 if (parser->tok == TOKEN_OPERATOR)
2040 /* classify the operator */
2041 const oper_info *op;
2042 const oper_info *olast = NULL;
2044 for (o = 0; o < operator_count; ++o) {
2045 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2046 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2047 !strcmp(parser_tokval(parser), operators[o].op))
2052 if (o == operator_count) {
2053 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2056 /* found an operator */
2059 /* when declaring variables, a comma starts a new variable */
2060 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2061 /* fixup the token */
2066 /* a colon without a pervious question mark cannot be a ternary */
2067 if (!ternaries && op->id == opid2(':','?')) {
2072 if (op->id == opid1(',')) {
2073 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2074 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2078 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2079 olast = &operators[vec_last(sy.ops).etype-1];
2081 #define IsAssignOp(x) (\
2082 (x) == opid1('=') || \
2083 (x) == opid2('+','=') || \
2084 (x) == opid2('-','=') || \
2085 (x) == opid2('*','=') || \
2086 (x) == opid2('/','=') || \
2087 (x) == opid2('%','=') || \
2088 (x) == opid2('&','=') || \
2089 (x) == opid2('|','=') || \
2090 (x) == opid3('&','~','=') \
2092 if (warn_truthvalue) {
2093 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2094 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2095 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2098 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2099 warn_truthvalue = false;
2104 (op->prec < olast->prec) ||
2105 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2107 if (!parser_sy_apply_operator(parser, &sy))
2109 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2110 olast = &operators[vec_last(sy.ops).etype-1];
2115 if (op->id == opid1('(')) {
2117 size_t sycount = vec_size(sy.out);
2118 /* we expected an operator, this is the function-call operator */
2119 vec_push(sy.paren, PAREN_FUNC);
2120 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2121 vec_push(sy.argc, 0);
2123 vec_push(sy.paren, PAREN_EXPR);
2124 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2127 } else if (op->id == opid1('[')) {
2129 parseerror(parser, "unexpected array subscript");
2132 vec_push(sy.paren, PAREN_INDEX);
2133 /* push both the operator and the paren, this makes life easier */
2134 vec_push(sy.ops, syop(parser_ctx(parser), op));
2135 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2137 } else if (op->id == opid2('?',':')) {
2138 vec_push(sy.ops, syop(parser_ctx(parser), op));
2139 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2142 vec_push(sy.paren, PAREN_TERNARY1);
2143 } else if (op->id == opid2(':','?')) {
2144 if (!vec_size(sy.paren)) {
2145 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2148 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2149 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2152 if (!parser_close_paren(parser, &sy))
2154 vec_push(sy.ops, syop(parser_ctx(parser), op));
2158 vec_push(sy.ops, syop(parser_ctx(parser), op));
2159 wantop = !!(op->flags & OP_SUFFIX);
2162 else if (parser->tok == ')') {
2163 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2164 if (!parser_sy_apply_operator(parser, &sy))
2167 if (!vec_size(sy.paren))
2170 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2171 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2174 if (!parser_close_paren(parser, &sy))
2177 /* must be a function call without parameters */
2178 if (vec_last(sy.paren) != PAREN_FUNC) {
2179 parseerror(parser, "closing paren in invalid position");
2182 if (!parser_close_paren(parser, &sy))
2187 else if (parser->tok == '(') {
2188 parseerror(parser, "internal error: '(' should be classified as operator");
2191 else if (parser->tok == '[') {
2192 parseerror(parser, "internal error: '[' should be classified as operator");
2195 else if (parser->tok == ']') {
2196 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2197 if (!parser_sy_apply_operator(parser, &sy))
2200 if (!vec_size(sy.paren))
2202 if (vec_last(sy.paren) != PAREN_INDEX) {
2203 parseerror(parser, "mismatched parentheses, unexpected ']'");
2206 if (!parser_close_paren(parser, &sy))
2211 if (!parse_sya_operand(parser, &sy, with_labels))
2214 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2215 vec_last(sy.argc)++;
2220 /* in this case we might want to allow constant string concatenation */
2221 bool concatenated = false;
2222 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2223 ast_expression *lexpr = vec_last(sy.out).out;
2224 if (ast_istype(lexpr, ast_value)) {
2225 ast_value *last = (ast_value*)lexpr;
2226 if (last->isimm == true && last->cvq == CV_CONST &&
2227 last->hasvalue && last->expression.vtype == TYPE_STRING)
2229 char *newstr = NULL;
2230 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2231 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2233 concatenated = true;
2237 if (!concatenated) {
2238 parseerror(parser, "expected operator or end of statement");
2243 if (!parser_next(parser)) {
2246 if (parser->tok == ';' ||
2247 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2248 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2254 while (vec_size(sy.ops)) {
2255 if (!parser_sy_apply_operator(parser, &sy))
2259 parser->lex->flags.noops = true;
2260 if (vec_size(sy.out) != 1) {
2261 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2264 expr = sy.out[0].out;
2267 if (vec_size(sy.paren)) {
2268 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2276 parser->lex->flags.noops = true;
2277 for (i = 0; i < vec_size(sy.out); ++i) {
2279 ast_unref(sy.out[i].out);
2288 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2290 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2293 if (parser->tok != ';') {
2294 parseerror(parser, "semicolon expected after expression");
2298 if (!parser_next(parser)) {
2305 static void parser_enterblock(parser_t *parser)
2307 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2308 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2309 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2310 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2311 vec_push(parser->_block_ctx, parser_ctx(parser));
2314 vec_push(parser->correct_variables, correct_trie_new());
2315 vec_push(parser->correct_variables_score, NULL);
2318 static bool parser_leaveblock(parser_t *parser)
2321 size_t locals, typedefs;
2323 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2324 parseerror(parser, "internal error: parser_leaveblock with no block");
2328 util_htdel(vec_last(parser->variables));
2329 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2331 vec_pop(parser->variables);
2332 vec_pop(parser->correct_variables);
2333 vec_pop(parser->correct_variables_score);
2334 if (!vec_size(parser->_blocklocals)) {
2335 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2339 locals = vec_last(parser->_blocklocals);
2340 vec_pop(parser->_blocklocals);
2341 while (vec_size(parser->_locals) != locals) {
2342 ast_expression *e = vec_last(parser->_locals);
2343 ast_value *v = (ast_value*)e;
2344 vec_pop(parser->_locals);
2345 if (ast_istype(e, ast_value) && !v->uses) {
2346 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2351 typedefs = vec_last(parser->_blocktypedefs);
2352 while (vec_size(parser->_typedefs) != typedefs) {
2353 ast_delete(vec_last(parser->_typedefs));
2354 vec_pop(parser->_typedefs);
2356 util_htdel(vec_last(parser->typedefs));
2357 vec_pop(parser->typedefs);
2359 vec_pop(parser->_block_ctx);
2364 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2366 vec_push(parser->_locals, e);
2367 util_htset(vec_last(parser->variables), name, (void*)e);
2371 vec_last(parser->correct_variables),
2372 &vec_last(parser->correct_variables_score),
2377 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2379 vec_push(parser->globals, e);
2380 util_htset(parser->htglobals, name, e);
2384 parser->correct_variables[0],
2385 &parser->correct_variables_score[0],
2390 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2394 ast_expression *prev;
2396 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2398 ast_type_to_string(cond, ty, sizeof(ty));
2399 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2402 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2405 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2408 parseerror(parser, "internal error: failed to process condition");
2413 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2415 /* vector types need to be cast to true booleans */
2416 ast_binary *bin = (ast_binary*)cond;
2417 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2419 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2421 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2424 parseerror(parser, "internal error: failed to process condition");
2431 unary = (ast_unary*)cond;
2432 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2434 cond = unary->operand;
2435 unary->operand = NULL;
2438 unary = (ast_unary*)cond;
2442 parseerror(parser, "internal error: failed to process condition");
2444 if (ifnot) *_ifnot = !*_ifnot;
2448 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2451 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2454 lex_ctx ctx = parser_ctx(parser);
2456 (void)block; /* not touching */
2458 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2459 if (!parser_next(parser)) {
2460 parseerror(parser, "expected condition or 'not'");
2463 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2465 if (!parser_next(parser)) {
2466 parseerror(parser, "expected condition in parenthesis");
2470 if (parser->tok != '(') {
2471 parseerror(parser, "expected 'if' condition in parenthesis");
2474 /* parse into the expression */
2475 if (!parser_next(parser)) {
2476 parseerror(parser, "expected 'if' condition after opening paren");
2479 /* parse the condition */
2480 cond = parse_expression_leave(parser, false, true, false);
2484 if (parser->tok != ')') {
2485 parseerror(parser, "expected closing paren after 'if' condition");
2489 /* parse into the 'then' branch */
2490 if (!parser_next(parser)) {
2491 parseerror(parser, "expected statement for on-true branch of 'if'");
2495 if (!parse_statement_or_block(parser, &ontrue)) {
2500 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2501 /* check for an else */
2502 if (!strcmp(parser_tokval(parser), "else")) {
2503 /* parse into the 'else' branch */
2504 if (!parser_next(parser)) {
2505 parseerror(parser, "expected on-false branch after 'else'");
2510 if (!parse_statement_or_block(parser, &onfalse)) {
2517 cond = process_condition(parser, cond, &ifnot);
2519 if (ontrue) ast_delete(ontrue);
2520 if (onfalse) ast_delete(onfalse);
2525 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2527 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2528 *out = (ast_expression*)ifthen;
2532 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2533 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2538 /* skip the 'while' and get the body */
2539 if (!parser_next(parser)) {
2540 if (OPTS_FLAG(LOOP_LABELS))
2541 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2543 parseerror(parser, "expected 'while' condition in parenthesis");
2547 if (parser->tok == ':') {
2548 if (!OPTS_FLAG(LOOP_LABELS))
2549 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2550 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2551 parseerror(parser, "expected loop label");
2554 label = util_strdup(parser_tokval(parser));
2555 if (!parser_next(parser)) {
2557 parseerror(parser, "expected 'while' condition in parenthesis");
2562 if (parser->tok != '(') {
2563 parseerror(parser, "expected 'while' condition in parenthesis");
2567 vec_push(parser->breaks, label);
2568 vec_push(parser->continues, label);
2570 rv = parse_while_go(parser, block, out);
2573 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2574 parseerror(parser, "internal error: label stack corrupted");
2580 vec_pop(parser->breaks);
2581 vec_pop(parser->continues);
2586 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2589 ast_expression *cond, *ontrue;
2593 lex_ctx ctx = parser_ctx(parser);
2595 (void)block; /* not touching */
2597 /* parse into the expression */
2598 if (!parser_next(parser)) {
2599 parseerror(parser, "expected 'while' condition after opening paren");
2602 /* parse the condition */
2603 cond = parse_expression_leave(parser, false, true, false);
2607 if (parser->tok != ')') {
2608 parseerror(parser, "expected closing paren after 'while' condition");
2612 /* parse into the 'then' branch */
2613 if (!parser_next(parser)) {
2614 parseerror(parser, "expected while-loop body");
2618 if (!parse_statement_or_block(parser, &ontrue)) {
2623 cond = process_condition(parser, cond, &ifnot);
2628 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2629 *out = (ast_expression*)aloop;
2633 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2634 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2639 /* skip the 'do' and get the body */
2640 if (!parser_next(parser)) {
2641 if (OPTS_FLAG(LOOP_LABELS))
2642 parseerror(parser, "expected loop label or body");
2644 parseerror(parser, "expected loop body");
2648 if (parser->tok == ':') {
2649 if (!OPTS_FLAG(LOOP_LABELS))
2650 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2651 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2652 parseerror(parser, "expected loop label");
2655 label = util_strdup(parser_tokval(parser));
2656 if (!parser_next(parser)) {
2658 parseerror(parser, "expected loop body");
2663 vec_push(parser->breaks, label);
2664 vec_push(parser->continues, label);
2666 rv = parse_dowhile_go(parser, block, out);
2669 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2670 parseerror(parser, "internal error: label stack corrupted");
2676 vec_pop(parser->breaks);
2677 vec_pop(parser->continues);
2682 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2685 ast_expression *cond, *ontrue;
2689 lex_ctx ctx = parser_ctx(parser);
2691 (void)block; /* not touching */
2693 if (!parse_statement_or_block(parser, &ontrue))
2696 /* expect the "while" */
2697 if (parser->tok != TOKEN_KEYWORD ||
2698 strcmp(parser_tokval(parser), "while"))
2700 parseerror(parser, "expected 'while' and condition");
2705 /* skip the 'while' and check for opening paren */
2706 if (!parser_next(parser) || parser->tok != '(') {
2707 parseerror(parser, "expected 'while' condition in parenthesis");
2711 /* parse into the expression */
2712 if (!parser_next(parser)) {
2713 parseerror(parser, "expected 'while' condition after opening paren");
2717 /* parse the condition */
2718 cond = parse_expression_leave(parser, false, true, false);
2722 if (parser->tok != ')') {
2723 parseerror(parser, "expected closing paren after 'while' condition");
2729 if (!parser_next(parser) || parser->tok != ';') {
2730 parseerror(parser, "expected semicolon after condition");
2736 if (!parser_next(parser)) {
2737 parseerror(parser, "parse error");
2743 cond = process_condition(parser, cond, &ifnot);
2748 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2749 *out = (ast_expression*)aloop;
2753 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2754 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2759 /* skip the 'for' and check for opening paren */
2760 if (!parser_next(parser)) {
2761 if (OPTS_FLAG(LOOP_LABELS))
2762 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2764 parseerror(parser, "expected 'for' expressions in parenthesis");
2768 if (parser->tok == ':') {
2769 if (!OPTS_FLAG(LOOP_LABELS))
2770 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2771 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2772 parseerror(parser, "expected loop label");
2775 label = util_strdup(parser_tokval(parser));
2776 if (!parser_next(parser)) {
2778 parseerror(parser, "expected 'for' expressions in parenthesis");
2783 if (parser->tok != '(') {
2784 parseerror(parser, "expected 'for' expressions in parenthesis");
2788 vec_push(parser->breaks, label);
2789 vec_push(parser->continues, label);
2791 rv = parse_for_go(parser, block, out);
2794 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2795 parseerror(parser, "internal error: label stack corrupted");
2801 vec_pop(parser->breaks);
2802 vec_pop(parser->continues);
2806 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2809 ast_expression *initexpr, *cond, *increment, *ontrue;
2814 lex_ctx ctx = parser_ctx(parser);
2816 parser_enterblock(parser);
2823 /* parse into the expression */
2824 if (!parser_next(parser)) {
2825 parseerror(parser, "expected 'for' initializer after opening paren");
2830 if (parser->tok == TOKEN_IDENT)
2831 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2833 if (typevar || parser->tok == TOKEN_TYPENAME) {
2835 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2836 if (parsewarning(parser, WARN_EXTENSIONS,
2837 "current standard does not allow variable declarations in for-loop initializers"))
2841 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2844 else if (parser->tok != ';')
2846 initexpr = parse_expression_leave(parser, false, false, false);
2851 /* move on to condition */
2852 if (parser->tok != ';') {
2853 parseerror(parser, "expected semicolon after for-loop initializer");
2856 if (!parser_next(parser)) {
2857 parseerror(parser, "expected for-loop condition");
2861 /* parse the condition */
2862 if (parser->tok != ';') {
2863 cond = parse_expression_leave(parser, false, true, false);
2868 /* move on to incrementor */
2869 if (parser->tok != ';') {
2870 parseerror(parser, "expected semicolon after for-loop initializer");
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "expected for-loop condition");
2878 /* parse the incrementor */
2879 if (parser->tok != ')') {
2880 lex_ctx condctx = parser_ctx(parser);
2881 increment = parse_expression_leave(parser, false, false, false);
2884 if (!ast_side_effects(increment)) {
2885 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2891 if (parser->tok != ')') {
2892 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2895 /* parse into the 'then' branch */
2896 if (!parser_next(parser)) {
2897 parseerror(parser, "expected for-loop body");
2900 if (!parse_statement_or_block(parser, &ontrue))
2904 cond = process_condition(parser, cond, &ifnot);
2908 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2909 *out = (ast_expression*)aloop;
2911 if (!parser_leaveblock(parser)) {
2917 if (initexpr) ast_unref(initexpr);
2918 if (cond) ast_unref(cond);
2919 if (increment) ast_unref(increment);
2920 (void)!parser_leaveblock(parser);
2924 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2926 ast_expression *exp = NULL;
2927 ast_expression *var = NULL;
2928 ast_return *ret = NULL;
2929 ast_expression *find = NULL;
2930 ast_value *expected = parser->function->vtype;
2932 lex_ctx ctx = parser_ctx(parser);
2934 (void)block; /* not touching */
2936 if (!parser_next(parser)) {
2937 parseerror(parser, "expected return expression");
2941 /* return assignments */
2942 if (parser->tok == '=') {
2943 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2944 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2948 if (!parser_next(parser)) {
2949 parseerror(parser, "expected return assignment expression");
2953 if (!(exp = parse_expression_leave(parser, false, false, false)))
2956 if (exp->vtype != TYPE_NIL &&
2957 exp->vtype != ((ast_expression*)expected)->next->vtype)
2959 parseerror(parser, "return assignment with invalid expression");
2962 /* store to 'return' local variable */
2963 var = (ast_expression*)ast_store_new(
2965 type_store_instr[exp->vtype],
2966 (ast_expression*)parser_find_returnvalue(parser, exp->vtype),
2967 (ast_expression*)exp
2979 if (parser->tok != ';') {
2980 exp = parse_expression(parser, false, false);
2984 if (exp->vtype != TYPE_NIL &&
2985 exp->vtype != ((ast_expression*)expected)->next->vtype)
2987 parseerror(parser, "return with invalid expression");
2990 ret = ast_return_new(ctx, exp);
2996 if (!parser_next(parser))
2997 parseerror(parser, "parse error");
2999 /* build expression to return */
3000 if ((find = (ast_expression*)parser_find_returnvalue(parser, expected->expression.next->vtype)) && OPTS_FLAG(RETURN_ASSIGNMENTS))
3001 ret = ast_return_new(ctx, find);
3003 else if (expected->expression.next->vtype != TYPE_VOID)
3005 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3006 ret = ast_return_new(ctx, NULL);
3009 *out = (ast_expression*)ret;
3013 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3016 unsigned int levels = 0;
3017 lex_ctx ctx = parser_ctx(parser);
3018 const char **loops = (is_continue ? parser->continues : parser->breaks);
3020 (void)block; /* not touching */
3021 if (!parser_next(parser)) {
3022 parseerror(parser, "expected semicolon or loop label");
3026 if (!vec_size(loops)) {
3028 parseerror(parser, "`continue` can only be used inside loops");
3030 parseerror(parser, "`break` can only be used inside loops or switches");
3033 if (parser->tok == TOKEN_IDENT) {
3034 if (!OPTS_FLAG(LOOP_LABELS))
3035 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3036 i = vec_size(loops);
3038 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3041 parseerror(parser, "no such loop to %s: `%s`",
3042 (is_continue ? "continue" : "break out of"),
3043 parser_tokval(parser));
3048 if (!parser_next(parser)) {
3049 parseerror(parser, "expected semicolon");
3054 if (parser->tok != ';') {
3055 parseerror(parser, "expected semicolon");
3059 if (!parser_next(parser))
3060 parseerror(parser, "parse error");
3062 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3066 /* returns true when it was a variable qualifier, false otherwise!
3067 * on error, cvq is set to CV_WRONG
3069 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3071 bool had_const = false;
3072 bool had_var = false;
3073 bool had_noref = false;
3074 bool had_attrib = false;
3075 bool had_static = false;
3080 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3082 /* parse an attribute */
3083 if (!parser_next(parser)) {
3084 parseerror(parser, "expected attribute after `[[`");
3088 if (!strcmp(parser_tokval(parser), "noreturn")) {
3089 flags |= AST_FLAG_NORETURN;
3090 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3091 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3096 else if (!strcmp(parser_tokval(parser), "noref")) {
3098 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3099 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3104 else if (!strcmp(parser_tokval(parser), "inline")) {
3105 flags |= AST_FLAG_INLINE;
3106 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3107 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3112 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3113 flags |= AST_FLAG_ALIAS;
3116 if (!parser_next(parser)) {
3117 parseerror(parser, "parse error in attribute");
3121 if (parser->tok == '(') {
3122 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3123 parseerror(parser, "`alias` attribute missing parameter");
3127 *message = util_strdup(parser_tokval(parser));
3129 if (!parser_next(parser)) {
3130 parseerror(parser, "parse error in attribute");
3134 if (parser->tok != ')') {
3135 parseerror(parser, "`alias` attribute expected `)` after parameter");
3139 if (!parser_next(parser)) {
3140 parseerror(parser, "parse error in attribute");
3145 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3146 parseerror(parser, "`alias` attribute expected `]]`");
3150 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3151 flags |= AST_FLAG_DEPRECATED;
3154 if (!parser_next(parser)) {
3155 parseerror(parser, "parse error in attribute");
3159 if (parser->tok == '(') {
3160 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3161 parseerror(parser, "`deprecated` attribute missing parameter");
3165 *message = util_strdup(parser_tokval(parser));
3167 if (!parser_next(parser)) {
3168 parseerror(parser, "parse error in attribute");
3172 if(parser->tok != ')') {
3173 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3177 if (!parser_next(parser)) {
3178 parseerror(parser, "parse error in attribute");
3183 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3184 parseerror(parser, "`deprecated` attribute expected `]]`");
3187 if (*message) mem_d(*message);
3195 /* Skip tokens until we hit a ]] */
3196 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3197 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3198 if (!parser_next(parser)) {
3199 parseerror(parser, "error inside attribute");
3206 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3208 else if (!strcmp(parser_tokval(parser), "const"))
3210 else if (!strcmp(parser_tokval(parser), "var"))
3212 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3214 else if (!strcmp(parser_tokval(parser), "noref"))
3216 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3221 if (!parser_next(parser))
3231 *is_static = had_static;
3235 parseerror(parser, "parse error after variable qualifier");
3240 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3241 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3246 /* skip the 'while' and get the body */
3247 if (!parser_next(parser)) {
3248 if (OPTS_FLAG(LOOP_LABELS))
3249 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3251 parseerror(parser, "expected 'switch' operand in parenthesis");
3255 if (parser->tok == ':') {
3256 if (!OPTS_FLAG(LOOP_LABELS))
3257 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3258 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3259 parseerror(parser, "expected loop label");
3262 label = util_strdup(parser_tokval(parser));
3263 if (!parser_next(parser)) {
3265 parseerror(parser, "expected 'switch' operand in parenthesis");
3270 if (parser->tok != '(') {
3271 parseerror(parser, "expected 'switch' operand in parenthesis");
3275 vec_push(parser->breaks, label);
3277 rv = parse_switch_go(parser, block, out);
3280 if (vec_last(parser->breaks) != label) {
3281 parseerror(parser, "internal error: label stack corrupted");
3287 vec_pop(parser->breaks);
3292 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3294 ast_expression *operand;
3297 ast_switch *switchnode;
3298 ast_switch_case swcase;
3301 bool noref, is_static;
3302 uint32_t qflags = 0;
3304 lex_ctx ctx = parser_ctx(parser);
3306 (void)block; /* not touching */
3309 /* parse into the expression */
3310 if (!parser_next(parser)) {
3311 parseerror(parser, "expected switch operand");
3314 /* parse the operand */
3315 operand = parse_expression_leave(parser, false, false, false);
3319 switchnode = ast_switch_new(ctx, operand);
3322 if (parser->tok != ')') {
3323 ast_delete(switchnode);
3324 parseerror(parser, "expected closing paren after 'switch' operand");
3328 /* parse over the opening paren */
3329 if (!parser_next(parser) || parser->tok != '{') {
3330 ast_delete(switchnode);
3331 parseerror(parser, "expected list of cases");
3335 if (!parser_next(parser)) {
3336 ast_delete(switchnode);
3337 parseerror(parser, "expected 'case' or 'default'");
3341 /* new block; allow some variables to be declared here */
3342 parser_enterblock(parser);
3345 if (parser->tok == TOKEN_IDENT)
3346 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3347 if (typevar || parser->tok == TOKEN_TYPENAME) {
3348 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3349 ast_delete(switchnode);
3354 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3356 if (cvq == CV_WRONG) {
3357 ast_delete(switchnode);
3360 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3361 ast_delete(switchnode);
3370 while (parser->tok != '}') {
3371 ast_block *caseblock;
3373 if (!strcmp(parser_tokval(parser), "case")) {
3374 if (!parser_next(parser)) {
3375 ast_delete(switchnode);
3376 parseerror(parser, "expected expression for case");
3379 swcase.value = parse_expression_leave(parser, false, false, false);
3380 if (!swcase.value) {
3381 ast_delete(switchnode);
3382 parseerror(parser, "expected expression for case");
3385 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3386 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3387 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3393 else if (!strcmp(parser_tokval(parser), "default")) {
3394 swcase.value = NULL;
3395 if (!parser_next(parser)) {
3396 ast_delete(switchnode);
3397 parseerror(parser, "expected colon");
3402 ast_delete(switchnode);
3403 parseerror(parser, "expected 'case' or 'default'");
3407 /* Now the colon and body */
3408 if (parser->tok != ':') {
3409 if (swcase.value) ast_unref(swcase.value);
3410 ast_delete(switchnode);
3411 parseerror(parser, "expected colon");
3415 if (!parser_next(parser)) {
3416 if (swcase.value) ast_unref(swcase.value);
3417 ast_delete(switchnode);
3418 parseerror(parser, "expected statements or case");
3421 caseblock = ast_block_new(parser_ctx(parser));
3423 if (swcase.value) ast_unref(swcase.value);
3424 ast_delete(switchnode);
3427 swcase.code = (ast_expression*)caseblock;
3428 vec_push(switchnode->cases, swcase);
3430 ast_expression *expr;
3431 if (parser->tok == '}')
3433 if (parser->tok == TOKEN_KEYWORD) {
3434 if (!strcmp(parser_tokval(parser), "case") ||
3435 !strcmp(parser_tokval(parser), "default"))
3440 if (!parse_statement(parser, caseblock, &expr, true)) {
3441 ast_delete(switchnode);
3446 if (!ast_block_add_expr(caseblock, expr)) {
3447 ast_delete(switchnode);
3453 parser_leaveblock(parser);
3456 if (parser->tok != '}') {
3457 ast_delete(switchnode);
3458 parseerror(parser, "expected closing paren of case list");
3461 if (!parser_next(parser)) {
3462 ast_delete(switchnode);
3463 parseerror(parser, "parse error after switch");
3466 *out = (ast_expression*)switchnode;
3470 /* parse computed goto sides */
3471 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3472 ast_expression *on_true;
3473 ast_expression *on_false;
3474 ast_expression *cond;
3479 if (ast_istype(*side, ast_ternary)) {
3480 ast_ternary *tern = (ast_ternary*)*side;
3481 on_true = parse_goto_computed(parser, &tern->on_true);
3482 on_false = parse_goto_computed(parser, &tern->on_false);
3484 if (!on_true || !on_false) {
3485 parseerror(parser, "expected label or expression in ternary");
3486 if (on_true) ast_unref(on_true);
3487 if (on_false) ast_unref(on_false);
3495 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3496 } else if (ast_istype(*side, ast_label)) {
3497 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3498 ast_goto_set_label(gt, ((ast_label*)*side));
3500 return (ast_expression*)gt;
3505 static bool parse_goto(parser_t *parser, ast_expression **out)
3507 ast_goto *gt = NULL;
3508 ast_expression *lbl;
3510 if (!parser_next(parser))
3513 if (parser->tok != TOKEN_IDENT) {
3514 ast_expression *expression;
3516 /* could be an expression i.e computed goto :-) */
3517 if (parser->tok != '(') {
3518 parseerror(parser, "expected label name after `goto`");
3522 /* failed to parse expression for goto */
3523 if (!(expression = parse_expression(parser, false, true)) ||
3524 !(*out = parse_goto_computed(parser, &expression))) {
3525 parseerror(parser, "invalid goto expression");
3526 ast_unref(expression);
3533 /* not computed goto */
3534 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3535 lbl = parser_find_label(parser, gt->name);
3537 if (!ast_istype(lbl, ast_label)) {
3538 parseerror(parser, "internal error: label is not an ast_label");
3542 ast_goto_set_label(gt, (ast_label*)lbl);
3545 vec_push(parser->gotos, gt);
3547 if (!parser_next(parser) || parser->tok != ';') {
3548 parseerror(parser, "semicolon expected after goto label");
3551 if (!parser_next(parser)) {
3552 parseerror(parser, "parse error after goto");
3556 *out = (ast_expression*)gt;
3560 static bool parse_skipwhite(parser_t *parser)
3563 if (!parser_next(parser))
3565 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3566 return parser->tok < TOKEN_ERROR;
3569 static bool parse_eol(parser_t *parser)
3571 if (!parse_skipwhite(parser))
3573 return parser->tok == TOKEN_EOL;
3576 static bool parse_pragma_do(parser_t *parser)
3578 if (!parser_next(parser) ||
3579 parser->tok != TOKEN_IDENT ||
3580 strcmp(parser_tokval(parser), "pragma"))
3582 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3585 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3586 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3590 if (!strcmp(parser_tokval(parser), "noref")) {
3591 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3592 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3595 parser->noref = !!parser_token(parser)->constval.i;
3596 if (!parse_eol(parser)) {
3597 parseerror(parser, "parse error after `noref` pragma");
3603 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3610 static bool parse_pragma(parser_t *parser)
3613 parser->lex->flags.preprocessing = true;
3614 parser->lex->flags.mergelines = true;
3615 rv = parse_pragma_do(parser);
3616 if (parser->tok != TOKEN_EOL) {
3617 parseerror(parser, "junk after pragma");
3620 parser->lex->flags.preprocessing = false;
3621 parser->lex->flags.mergelines = false;
3622 if (!parser_next(parser)) {
3623 parseerror(parser, "parse error after pragma");
3629 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3631 bool noref, is_static;
3633 uint32_t qflags = 0;
3634 ast_value *typevar = NULL;
3635 char *vstring = NULL;
3639 if (parser->tok == TOKEN_IDENT)
3640 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3642 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3644 /* local variable */
3646 parseerror(parser, "cannot declare a variable from here");
3649 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3650 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3653 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3657 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3659 if (cvq == CV_WRONG)
3661 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3663 else if (parser->tok == TOKEN_KEYWORD)
3665 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3670 if (!parser_next(parser)) {
3671 parseerror(parser, "parse error after __builtin_debug_printtype");
3675 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3677 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3678 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3679 if (!parser_next(parser)) {
3680 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3686 if (!parse_statement(parser, block, out, allow_cases))
3689 con_out("__builtin_debug_printtype: got no output node\n");
3692 ast_type_to_string(*out, ty, sizeof(ty));
3693 con_out("__builtin_debug_printtype: `%s`\n", ty);
3698 else if (!strcmp(parser_tokval(parser), "return"))
3700 return parse_return(parser, block, out);
3702 else if (!strcmp(parser_tokval(parser), "if"))
3704 return parse_if(parser, block, out);
3706 else if (!strcmp(parser_tokval(parser), "while"))
3708 return parse_while(parser, block, out);
3710 else if (!strcmp(parser_tokval(parser), "do"))
3712 return parse_dowhile(parser, block, out);
3714 else if (!strcmp(parser_tokval(parser), "for"))
3716 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3717 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3720 return parse_for(parser, block, out);
3722 else if (!strcmp(parser_tokval(parser), "break"))
3724 return parse_break_continue(parser, block, out, false);
3726 else if (!strcmp(parser_tokval(parser), "continue"))
3728 return parse_break_continue(parser, block, out, true);
3730 else if (!strcmp(parser_tokval(parser), "switch"))
3732 return parse_switch(parser, block, out);
3734 else if (!strcmp(parser_tokval(parser), "case") ||
3735 !strcmp(parser_tokval(parser), "default"))
3738 parseerror(parser, "unexpected 'case' label");
3743 else if (!strcmp(parser_tokval(parser), "goto"))
3745 return parse_goto(parser, out);
3747 else if (!strcmp(parser_tokval(parser), "typedef"))
3749 if (!parser_next(parser)) {
3750 parseerror(parser, "expected type definition after 'typedef'");
3753 return parse_typedef(parser);
3755 parseerror(parser, "Unexpected keyword");
3758 else if (parser->tok == '{')
3761 inner = parse_block(parser);
3764 *out = (ast_expression*)inner;
3767 else if (parser->tok == ':')
3771 if (!parser_next(parser)) {
3772 parseerror(parser, "expected label name");
3775 if (parser->tok != TOKEN_IDENT) {
3776 parseerror(parser, "label must be an identifier");
3779 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3781 if (!label->undefined) {
3782 parseerror(parser, "label `%s` already defined", label->name);
3785 label->undefined = false;
3788 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3789 vec_push(parser->labels, label);
3791 *out = (ast_expression*)label;
3792 if (!parser_next(parser)) {
3793 parseerror(parser, "parse error after label");
3796 for (i = 0; i < vec_size(parser->gotos); ++i) {
3797 if (!strcmp(parser->gotos[i]->name, label->name)) {
3798 ast_goto_set_label(parser->gotos[i], label);
3799 vec_remove(parser->gotos, i, 1);
3805 else if (parser->tok == ';')
3807 if (!parser_next(parser)) {
3808 parseerror(parser, "parse error after empty statement");
3815 lex_ctx ctx = parser_ctx(parser);
3816 ast_expression *exp = parse_expression(parser, false, false);
3820 if (!ast_side_effects(exp)) {
3821 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3828 static bool parse_enum(parser_t *parser)
3831 bool reverse = false;
3833 ast_value **values = NULL;
3834 ast_value *var = NULL;
3837 ast_expression *old;
3839 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3840 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3844 /* enumeration attributes (can add more later) */
3845 if (parser->tok == ':') {
3846 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3847 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3852 if (!strcmp(parser_tokval(parser), "flag")) {
3856 else if (!strcmp(parser_tokval(parser), "reverse")) {
3860 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3864 if (!parser_next(parser) || parser->tok != '{') {
3865 parseerror(parser, "expected `{` after enum attribute ");
3871 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3872 if (parser->tok == '}') {
3873 /* allow an empty enum */
3876 parseerror(parser, "expected identifier or `}`");
3880 old = parser_find_field(parser, parser_tokval(parser));
3882 old = parser_find_global(parser, parser_tokval(parser));
3884 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3885 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3889 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3890 vec_push(values, var);
3891 var->cvq = CV_CONST;
3892 var->hasvalue = true;
3894 /* for flagged enumerations increment in POTs of TWO */
3895 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3896 parser_addglobal(parser, var->name, (ast_expression*)var);
3898 if (!parser_next(parser)) {
3899 parseerror(parser, "expected `=`, `}` or comma after identifier");
3903 if (parser->tok == ',')
3905 if (parser->tok == '}')
3907 if (parser->tok != '=') {
3908 parseerror(parser, "expected `=`, `}` or comma after identifier");
3912 if (!parser_next(parser)) {
3913 parseerror(parser, "expected expression after `=`");
3917 /* We got a value! */
3918 old = parse_expression_leave(parser, true, false, false);
3919 asvalue = (ast_value*)old;
3920 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3921 compile_error(ast_ctx(var), "constant value or expression expected");
3924 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3926 if (parser->tok == '}')
3928 if (parser->tok != ',') {
3929 parseerror(parser, "expected `}` or comma after expression");
3934 /* patch them all (for reversed attribute) */
3937 for (i = 0; i < vec_size(values); i++)
3938 values[i]->constval.vfloat = vec_size(values) - i - 1;
3941 if (parser->tok != '}') {
3942 parseerror(parser, "internal error: breaking without `}`");
3946 if (!parser_next(parser) || parser->tok != ';') {
3947 parseerror(parser, "expected semicolon after enumeration");
3951 if (!parser_next(parser)) {
3952 parseerror(parser, "parse error after enumeration");
3964 static bool parse_block_into(parser_t *parser, ast_block *block)
3968 parser_enterblock(parser);
3970 if (!parser_next(parser)) { /* skip the '{' */
3971 parseerror(parser, "expected function body");
3975 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3977 ast_expression *expr = NULL;
3978 if (parser->tok == '}')
3981 if (!parse_statement(parser, block, &expr, false)) {
3982 /* parseerror(parser, "parse error"); */
3988 if (!ast_block_add_expr(block, expr)) {
3995 if (parser->tok != '}') {
3998 (void)parser_next(parser);
4002 if (!parser_leaveblock(parser))
4004 return retval && !!block;
4007 static ast_block* parse_block(parser_t *parser)
4010 block = ast_block_new(parser_ctx(parser));
4013 if (!parse_block_into(parser, block)) {
4014 ast_block_delete(block);
4020 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4022 if (parser->tok == '{') {
4023 *out = (ast_expression*)parse_block(parser);
4026 return parse_statement(parser, NULL, out, false);
4029 static bool create_vector_members(ast_value *var, ast_member **me)
4032 size_t len = strlen(var->name);
4034 for (i = 0; i < 3; ++i) {
4035 char *name = (char*)mem_a(len+3);
4036 memcpy(name, var->name, len);
4038 name[len+1] = 'x'+i;
4040 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4049 do { ast_member_delete(me[--i]); } while(i);
4053 static bool parse_function_body(parser_t *parser, ast_value *var)
4055 ast_block *block = NULL;
4060 ast_expression *framenum = NULL;
4061 ast_expression *nextthink = NULL;
4062 /* None of the following have to be deleted */
4063 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4064 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4065 bool has_frame_think;
4069 has_frame_think = false;
4070 old = parser->function;
4072 if (var->expression.flags & AST_FLAG_ALIAS) {
4073 parseerror(parser, "function aliases cannot have bodies");
4077 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4078 parseerror(parser, "gotos/labels leaking");
4082 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4083 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4084 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4090 if (parser->tok == '[') {
4091 /* got a frame definition: [ framenum, nextthink ]
4092 * this translates to:
4093 * self.frame = framenum;
4094 * self.nextthink = time + 0.1;
4095 * self.think = nextthink;
4099 fld_think = parser_find_field(parser, "think");
4100 fld_nextthink = parser_find_field(parser, "nextthink");
4101 fld_frame = parser_find_field(parser, "frame");
4102 if (!fld_think || !fld_nextthink || !fld_frame) {
4103 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4104 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4107 gbl_time = parser_find_global(parser, "time");
4108 gbl_self = parser_find_global(parser, "self");
4109 if (!gbl_time || !gbl_self) {
4110 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4111 parseerror(parser, "please declare the following globals: `time`, `self`");
4115 if (!parser_next(parser))
4118 framenum = parse_expression_leave(parser, true, false, false);
4120 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4123 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4124 ast_unref(framenum);
4125 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4129 if (parser->tok != ',') {
4130 ast_unref(framenum);
4131 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4132 parseerror(parser, "Got a %i\n", parser->tok);
4136 if (!parser_next(parser)) {
4137 ast_unref(framenum);
4141 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4143 /* qc allows the use of not-yet-declared functions here
4144 * - this automatically creates a prototype */
4145 ast_value *thinkfunc;
4146 ast_expression *functype = fld_think->next;
4148 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4149 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4150 ast_unref(framenum);
4151 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4154 ast_type_adopt(thinkfunc, functype);
4156 if (!parser_next(parser)) {
4157 ast_unref(framenum);
4158 ast_delete(thinkfunc);
4162 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4164 nextthink = (ast_expression*)thinkfunc;
4167 nextthink = parse_expression_leave(parser, true, false, false);
4169 ast_unref(framenum);
4170 parseerror(parser, "expected a think-function in [frame,think] notation");
4175 if (!ast_istype(nextthink, ast_value)) {
4176 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4180 if (retval && parser->tok != ']') {
4181 parseerror(parser, "expected closing `]` for [frame,think] notation");
4185 if (retval && !parser_next(parser)) {
4189 if (retval && parser->tok != '{') {
4190 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4195 ast_unref(nextthink);
4196 ast_unref(framenum);
4200 has_frame_think = true;
4203 block = ast_block_new(parser_ctx(parser));
4205 parseerror(parser, "failed to allocate block");
4206 if (has_frame_think) {
4207 ast_unref(nextthink);
4208 ast_unref(framenum);
4213 if (has_frame_think) {
4215 ast_expression *self_frame;
4216 ast_expression *self_nextthink;
4217 ast_expression *self_think;
4218 ast_expression *time_plus_1;
4219 ast_store *store_frame;
4220 ast_store *store_nextthink;
4221 ast_store *store_think;
4223 ctx = parser_ctx(parser);
4224 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4225 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4226 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4228 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4229 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4231 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4232 if (self_frame) ast_delete(self_frame);
4233 if (self_nextthink) ast_delete(self_nextthink);
4234 if (self_think) ast_delete(self_think);
4235 if (time_plus_1) ast_delete(time_plus_1);
4241 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4242 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4243 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4246 ast_delete(self_frame);
4249 if (!store_nextthink) {
4250 ast_delete(self_nextthink);
4254 ast_delete(self_think);
4258 if (store_frame) ast_delete(store_frame);
4259 if (store_nextthink) ast_delete(store_nextthink);
4260 if (store_think) ast_delete(store_think);
4263 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4264 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4265 !ast_block_add_expr(block, (ast_expression*)store_think))
4272 parseerror(parser, "failed to generate code for [frame,think]");
4273 ast_unref(nextthink);
4274 ast_unref(framenum);
4280 if (var->hasvalue) {
4281 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4282 ast_block_delete(block);
4286 func = ast_function_new(ast_ctx(var), var->name, var);
4288 parseerror(parser, "failed to allocate function for `%s`", var->name);
4289 ast_block_delete(block);
4292 vec_push(parser->functions, func);
4294 parser_enterblock(parser);
4296 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4298 ast_value *param = var->expression.params[parami];
4301 if (param->expression.vtype != TYPE_VECTOR &&
4302 (param->expression.vtype != TYPE_FIELD ||
4303 param->expression.next->vtype != TYPE_VECTOR))
4308 if (!create_vector_members(param, me)) {
4309 ast_block_delete(block);
4313 for (e = 0; e < 3; ++e) {
4314 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4315 ast_block_collect(block, (ast_expression*)me[e]);
4319 if (var->argcounter) {
4320 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4321 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4325 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4327 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4328 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4329 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4330 varargs->expression.count = 0;
4331 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4332 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4333 ast_delete(varargs);
4334 ast_block_delete(block);
4337 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4338 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4339 ast_delete(varargs);
4340 ast_block_delete(block);
4343 func->varargs = varargs;
4345 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4348 parser->function = func;
4349 if (!parse_block_into(parser, block)) {
4350 ast_block_delete(block);
4354 vec_push(func->blocks, block);
4357 parser->function = old;
4358 if (!parser_leaveblock(parser))
4360 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4361 parseerror(parser, "internal error: local scopes left");
4365 if (parser->tok == ';')
4366 return parser_next(parser);
4367 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4368 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4372 (void)!parser_leaveblock(parser);
4373 vec_pop(parser->functions);
4374 ast_function_delete(func);
4375 var->constval.vfunc = NULL;
4378 parser->function = old;
4382 static ast_expression *array_accessor_split(
4387 ast_expression *left,
4388 ast_expression *right
4394 lex_ctx ctx = ast_ctx(array);
4396 if (!left || !right) {
4397 if (left) ast_delete(left);
4398 if (right) ast_delete(right);
4402 cmp = ast_binary_new(ctx, INSTR_LT,
4403 (ast_expression*)index,
4404 (ast_expression*)parser_const_float(parser, middle));
4408 parseerror(parser, "internal error: failed to create comparison for array setter");
4412 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4414 ast_delete(cmp); /* will delete left and right */
4415 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4419 return (ast_expression*)ifthen;
4422 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4424 lex_ctx ctx = ast_ctx(array);
4426 if (from+1 == afterend) {
4427 /* set this value */
4430 ast_array_index *subscript;
4432 int assignop = type_store_instr[value->expression.vtype];
4434 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4435 assignop = INSTR_STORE_V;
4437 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4441 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4443 ast_delete(subscript);
4447 block = ast_block_new(ctx);
4453 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4458 ret = ast_return_new(ctx, NULL);
4464 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4469 return (ast_expression*)block;
4471 ast_expression *left, *right;
4472 size_t diff = afterend - from;
4473 size_t middle = from + diff/2;
4474 left = array_setter_node(parser, array, index, value, from, middle);
4475 right = array_setter_node(parser, array, index, value, middle, afterend);
4476 return array_accessor_split(parser, array, index, middle, left, right);
4480 static ast_expression *array_field_setter_node(
4489 lex_ctx ctx = ast_ctx(array);
4491 if (from+1 == afterend) {
4492 /* set this value */
4495 ast_entfield *entfield;
4496 ast_array_index *subscript;
4498 int assignop = type_storep_instr[value->expression.vtype];
4500 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4501 assignop = INSTR_STOREP_V;
4503 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4507 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4508 subscript->expression.vtype = TYPE_FIELD;
4510 entfield = ast_entfield_new_force(ctx,
4511 (ast_expression*)entity,
4512 (ast_expression*)subscript,
4513 (ast_expression*)subscript);
4515 ast_delete(subscript);
4519 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4521 ast_delete(entfield);
4525 block = ast_block_new(ctx);
4531 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4536 ret = ast_return_new(ctx, NULL);
4542 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4547 return (ast_expression*)block;
4549 ast_expression *left, *right;
4550 size_t diff = afterend - from;
4551 size_t middle = from + diff/2;
4552 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4553 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4554 return array_accessor_split(parser, array, index, middle, left, right);
4558 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4560 lex_ctx ctx = ast_ctx(array);
4562 if (from+1 == afterend) {
4564 ast_array_index *subscript;
4566 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4570 ret = ast_return_new(ctx, (ast_expression*)subscript);
4572 ast_delete(subscript);
4576 return (ast_expression*)ret;
4578 ast_expression *left, *right;
4579 size_t diff = afterend - from;
4580 size_t middle = from + diff/2;
4581 left = array_getter_node(parser, array, index, from, middle);
4582 right = array_getter_node(parser, array, index, middle, afterend);
4583 return array_accessor_split(parser, array, index, middle, left, right);
4587 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4589 ast_function *func = NULL;
4590 ast_value *fval = NULL;
4591 ast_block *body = NULL;
4593 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4595 parseerror(parser, "failed to create accessor function value");
4599 func = ast_function_new(ast_ctx(array), funcname, fval);
4602 parseerror(parser, "failed to create accessor function node");
4606 body = ast_block_new(ast_ctx(array));
4608 parseerror(parser, "failed to create block for array accessor");
4614 vec_push(func->blocks, body);
4617 vec_push(parser->accessors, fval);
4622 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4624 ast_value *index = NULL;
4625 ast_value *value = NULL;
4629 if (!ast_istype(array->expression.next, ast_value)) {
4630 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4634 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4636 func = fval->constval.vfunc;
4637 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4639 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4640 value = ast_value_copy((ast_value*)array->expression.next);
4642 if (!index || !value) {
4643 parseerror(parser, "failed to create locals for array accessor");
4646 (void)!ast_value_set_name(value, "value"); /* not important */
4647 vec_push(fval->expression.params, index);
4648 vec_push(fval->expression.params, value);
4650 array->setter = fval;
4653 if (index) ast_delete(index);
4654 if (value) ast_delete(value);
4660 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4662 ast_expression *root = NULL;
4663 root = array_setter_node(parser, array,
4664 array->setter->expression.params[0],
4665 array->setter->expression.params[1],
4666 0, array->expression.count);
4668 parseerror(parser, "failed to build accessor search tree");
4671 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4678 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4680 if (!parser_create_array_setter_proto(parser, array, funcname))
4682 return parser_create_array_setter_impl(parser, array);
4685 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4687 ast_expression *root = NULL;
4688 ast_value *entity = NULL;
4689 ast_value *index = NULL;
4690 ast_value *value = NULL;
4694 if (!ast_istype(array->expression.next, ast_value)) {
4695 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4699 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4701 func = fval->constval.vfunc;
4702 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4704 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4705 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4706 value = ast_value_copy((ast_value*)array->expression.next);
4707 if (!entity || !index || !value) {
4708 parseerror(parser, "failed to create locals for array accessor");
4711 (void)!ast_value_set_name(value, "value"); /* not important */
4712 vec_push(fval->expression.params, entity);
4713 vec_push(fval->expression.params, index);
4714 vec_push(fval->expression.params, value);
4716 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4718 parseerror(parser, "failed to build accessor search tree");
4722 array->setter = fval;
4723 return ast_block_add_expr(func->blocks[0], root);
4725 if (entity) ast_delete(entity);
4726 if (index) ast_delete(index);
4727 if (value) ast_delete(value);
4728 if (root) ast_delete(root);
4734 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4736 ast_value *index = NULL;
4740 /* NOTE: checking array->expression.next rather than elemtype since
4741 * for fields elemtype is a temporary fieldtype.
4743 if (!ast_istype(array->expression.next, ast_value)) {
4744 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4748 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4750 func = fval->constval.vfunc;
4751 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4753 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4756 parseerror(parser, "failed to create locals for array accessor");
4759 vec_push(fval->expression.params, index);
4761 array->getter = fval;
4764 if (index) ast_delete(index);
4770 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4772 ast_expression *root = NULL;
4774 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4776 parseerror(parser, "failed to build accessor search tree");
4779 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4786 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4788 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4790 return parser_create_array_getter_impl(parser, array);
4793 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4794 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4802 bool variadic = false;
4803 ast_value *varparam = NULL;
4804 char *argcounter = NULL;
4806 ctx = parser_ctx(parser);
4808 /* for the sake of less code we parse-in in this function */
4809 if (!parser_next(parser)) {
4810 parseerror(parser, "expected parameter list");
4816 /* parse variables until we hit a closing paren */
4817 while (parser->tok != ')') {
4819 /* there must be commas between them */
4820 if (parser->tok != ',') {
4821 parseerror(parser, "expected comma or end of parameter list");
4824 if (!parser_next(parser)) {
4825 parseerror(parser, "expected parameter");
4831 if (parser->tok == TOKEN_DOTS) {
4832 /* '...' indicates a varargs function */
4834 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4835 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4838 if (parser->tok == TOKEN_IDENT) {
4839 argcounter = util_strdup(parser_tokval(parser));
4840 if (!parser_next(parser) || parser->tok != ')') {
4841 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4848 /* for anything else just parse a typename */
4849 param = parse_typename(parser, NULL, NULL);
4852 vec_push(params, param);
4853 if (param->expression.vtype >= TYPE_VARIANT) {
4854 char tname[1024]; /* typename is reserved in C++ */
4855 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4856 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4859 /* type-restricted varargs */
4860 if (parser->tok == TOKEN_DOTS) {
4862 varparam = vec_last(params);
4864 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4865 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4868 if (parser->tok == TOKEN_IDENT) {
4869 argcounter = util_strdup(parser_tokval(parser));
4870 if (!parser_next(parser) || parser->tok != ')') {
4871 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4879 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4883 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4884 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4887 if (!parser_next(parser)) {
4888 parseerror(parser, "parse error after typename");
4892 /* now turn 'var' into a function type */
4893 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4894 fval->expression.next = (ast_expression*)var;
4896 fval->expression.flags |= AST_FLAG_VARIADIC;
4899 var->expression.params = params;
4900 var->expression.varparam = (ast_expression*)varparam;
4901 var->argcounter = argcounter;
4910 ast_delete(varparam);
4912 for (i = 0; i < vec_size(params); ++i)
4913 ast_delete(params[i]);
4918 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4920 ast_expression *cexp;
4921 ast_value *cval, *tmp;
4924 ctx = parser_ctx(parser);
4926 if (!parser_next(parser)) {
4928 parseerror(parser, "expected array-size");
4932 cexp = parse_expression_leave(parser, true, false, false);
4934 if (!cexp || !ast_istype(cexp, ast_value)) {
4938 parseerror(parser, "expected array-size as constant positive integer");
4941 cval = (ast_value*)cexp;
4943 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4944 tmp->expression.next = (ast_expression*)var;
4947 if (cval->expression.vtype == TYPE_INTEGER)
4948 tmp->expression.count = cval->constval.vint;
4949 else if (cval->expression.vtype == TYPE_FLOAT)
4950 tmp->expression.count = cval->constval.vfloat;
4954 parseerror(parser, "array-size must be a positive integer constant");
4959 if (parser->tok != ']') {
4961 parseerror(parser, "expected ']' after array-size");
4964 if (!parser_next(parser)) {
4966 parseerror(parser, "error after parsing array size");
4972 /* Parse a complete typename.
4973 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4974 * but when parsing variables separated by comma
4975 * 'storebase' should point to where the base-type should be kept.
4976 * The base type makes up every bit of type information which comes *before* the
4979 * The following will be parsed in its entirety:
4981 * The 'basetype' in this case is 'void()'
4982 * and if there's a comma after it, say:
4984 * then the type-information 'void()' can be stored in 'storebase'
4986 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4988 ast_value *var, *tmp;
4991 const char *name = NULL;
4992 bool isfield = false;
4993 bool wasarray = false;
4994 size_t morefields = 0;
4996 ctx = parser_ctx(parser);
4998 /* types may start with a dot */
4999 if (parser->tok == '.') {
5001 /* if we parsed a dot we need a typename now */
5002 if (!parser_next(parser)) {
5003 parseerror(parser, "expected typename for field definition");
5007 /* Further dots are handled seperately because they won't be part of the
5010 while (parser->tok == '.') {
5012 if (!parser_next(parser)) {
5013 parseerror(parser, "expected typename for field definition");
5018 if (parser->tok == TOKEN_IDENT)
5019 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5020 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5021 parseerror(parser, "expected typename");
5025 /* generate the basic type value */
5026 if (cached_typedef) {
5027 var = ast_value_copy(cached_typedef);
5028 ast_value_set_name(var, "<type(from_def)>");
5030 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5032 for (; morefields; --morefields) {
5033 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5034 tmp->expression.next = (ast_expression*)var;
5038 /* do not yet turn into a field - remember:
5039 * .void() foo; is a field too
5040 * .void()() foo; is a function
5044 if (!parser_next(parser)) {
5046 parseerror(parser, "parse error after typename");
5050 /* an opening paren now starts the parameter-list of a function
5051 * this is where original-QC has parameter lists.
5052 * We allow a single parameter list here.
5053 * Much like fteqcc we don't allow `float()() x`
5055 if (parser->tok == '(') {
5056 var = parse_parameter_list(parser, var);
5061 /* store the base if requested */
5063 *storebase = ast_value_copy(var);
5065 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5066 tmp->expression.next = (ast_expression*)*storebase;
5071 /* there may be a name now */
5072 if (parser->tok == TOKEN_IDENT) {
5073 name = util_strdup(parser_tokval(parser));
5075 if (!parser_next(parser)) {
5077 parseerror(parser, "error after variable or field declaration");
5082 /* now this may be an array */
5083 if (parser->tok == '[') {
5085 var = parse_arraysize(parser, var);
5090 /* This is the point where we can turn it into a field */
5092 /* turn it into a field if desired */
5093 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5094 tmp->expression.next = (ast_expression*)var;
5098 /* now there may be function parens again */
5099 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5100 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5101 if (parser->tok == '(' && wasarray)
5102 parseerror(parser, "arrays as part of a return type is not supported");
5103 while (parser->tok == '(') {
5104 var = parse_parameter_list(parser, var);
5112 /* finally name it */
5114 if (!ast_value_set_name(var, name)) {
5116 parseerror(parser, "internal error: failed to set name");
5119 /* free the name, ast_value_set_name duplicates */
5126 static bool parse_typedef(parser_t *parser)
5128 ast_value *typevar, *oldtype;
5129 ast_expression *old;
5131 typevar = parse_typename(parser, NULL, NULL);
5136 if ( (old = parser_find_var(parser, typevar->name)) ) {
5137 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5138 " -> `%s` has been declared here: %s:%i",
5139 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5140 ast_delete(typevar);
5144 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5145 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5146 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5147 ast_delete(typevar);
5151 vec_push(parser->_typedefs, typevar);
5152 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5154 if (parser->tok != ';') {
5155 parseerror(parser, "expected semicolon after typedef");
5158 if (!parser_next(parser)) {
5159 parseerror(parser, "parse error after typedef");
5166 static const char *cvq_to_str(int cvq) {
5168 case CV_NONE: return "none";
5169 case CV_VAR: return "`var`";
5170 case CV_CONST: return "`const`";
5171 default: return "<INVALID>";
5175 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5178 if (proto->cvq != var->cvq) {
5179 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5180 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5181 parser->tok == '='))
5183 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5184 "`%s` declared with different qualifiers: %s\n"
5185 " -> previous declaration here: %s:%i uses %s",
5186 var->name, cvq_to_str(var->cvq),
5187 ast_ctx(proto).file, ast_ctx(proto).line,
5188 cvq_to_str(proto->cvq));
5191 av = (var ->expression.flags & AST_FLAG_NORETURN);
5192 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5194 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5195 "`%s` declared with different attributes%s\n"
5196 " -> previous declaration here: %s:%i",
5197 var->name, (av ? ": noreturn" : ""),
5198 ast_ctx(proto).file, ast_ctx(proto).line,
5199 (ao ? ": noreturn" : ""));
5204 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)
5208 ast_expression *old;
5212 ast_value *basetype = NULL;
5214 bool isparam = false;
5215 bool isvector = false;
5216 bool cleanvar = true;
5217 bool wasarray = false;
5219 ast_member *me[3] = { NULL, NULL, NULL };
5221 if (!localblock && is_static)
5222 parseerror(parser, "`static` qualifier is not supported in global scope");
5224 /* get the first complete variable */
5225 var = parse_typename(parser, &basetype, cached_typedef);
5228 ast_delete(basetype);
5236 /* Part 0: finish the type */
5237 if (parser->tok == '(') {
5238 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5239 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5240 var = parse_parameter_list(parser, var);
5246 /* we only allow 1-dimensional arrays */
5247 if (parser->tok == '[') {
5249 var = parse_arraysize(parser, var);
5255 if (parser->tok == '(' && wasarray) {
5256 parseerror(parser, "arrays as part of a return type is not supported");
5257 /* we'll still parse the type completely for now */
5259 /* for functions returning functions */
5260 while (parser->tok == '(') {
5261 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5262 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5263 var = parse_parameter_list(parser, var);
5270 var->cvq = qualifier;
5271 var->expression.flags |= qflags;
5274 * store the vstring back to var for alias and
5275 * deprecation messages.
5277 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5278 var->expression.flags & AST_FLAG_ALIAS)
5279 var->desc = vstring;
5282 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5283 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5284 * is then filled with the previous definition and the parameter-names replaced.
5286 if (!strcmp(var->name, "nil")) {
5287 if (OPTS_FLAG(UNTYPED_NIL)) {
5288 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5289 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5291 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5294 /* Deal with end_sys_ vars */
5296 if (!strcmp(var->name, "end_sys_globals")) {
5298 parser->crc_globals = vec_size(parser->globals);
5301 else if (!strcmp(var->name, "end_sys_fields")) {
5303 parser->crc_fields = vec_size(parser->fields);
5306 if (was_end && var->expression.vtype == TYPE_FIELD) {
5307 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5308 "global '%s' hint should not be a field",
5309 parser_tokval(parser)))
5316 if (!nofields && var->expression.vtype == TYPE_FIELD)
5318 /* deal with field declarations */
5319 old = parser_find_field(parser, var->name);
5321 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5322 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5331 parseerror(parser, "field `%s` already declared here: %s:%i",
5332 var->name, ast_ctx(old).file, ast_ctx(old).line);
5337 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5338 (old = parser_find_global(parser, var->name)))
5340 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5341 parseerror(parser, "field `%s` already declared here: %s:%i",
5342 var->name, ast_ctx(old).file, ast_ctx(old).line);
5349 /* deal with other globals */
5350 old = parser_find_global(parser, var->name);
5351 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5353 /* This is a function which had a prototype */
5354 if (!ast_istype(old, ast_value)) {
5355 parseerror(parser, "internal error: prototype is not an ast_value");
5359 proto = (ast_value*)old;
5360 proto->desc = var->desc;
5361 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5362 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5364 ast_ctx(proto).file, ast_ctx(proto).line);
5368 /* we need the new parameter-names */
5369 for (i = 0; i < vec_size(proto->expression.params); ++i)
5370 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5371 if (!parser_check_qualifiers(parser, var, proto)) {
5378 proto->expression.flags |= var->expression.flags;
5386 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5387 "global `%s` already declared here: %s:%i",
5388 var->name, ast_ctx(old).file, ast_ctx(old).line))
5393 proto = (ast_value*)old;
5394 if (!ast_istype(old, ast_value)) {
5395 parseerror(parser, "internal error: not an ast_value");
5400 if (!parser_check_qualifiers(parser, var, proto)) {
5405 proto->expression.flags |= var->expression.flags;
5409 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5410 (old = parser_find_field(parser, var->name)))
5412 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5413 parseerror(parser, "global `%s` already declared here: %s:%i",
5414 var->name, ast_ctx(old).file, ast_ctx(old).line);
5421 else /* it's not a global */
5423 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5424 if (old && !isparam) {
5425 parseerror(parser, "local `%s` already declared here: %s:%i",
5426 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5430 old = parser_find_local(parser, var->name, 0, &isparam);
5431 if (old && isparam) {
5432 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5433 "local `%s` is shadowing a parameter", var->name))
5435 parseerror(parser, "local `%s` already declared here: %s:%i",
5436 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5440 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5448 /* in a noref section we simply bump the usecount */
5449 if (noref || parser->noref)
5453 * Create the global/local, and deal with vector types.
5456 if (var->expression.vtype == TYPE_VECTOR)
5458 else if (var->expression.vtype == TYPE_FIELD &&
5459 var->expression.next->vtype == TYPE_VECTOR)
5463 if (!create_vector_members(var, me)) {
5470 /* deal with global variables, fields, functions */
5471 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5472 var->isfield = true;
5473 vec_push(parser->fields, (ast_expression*)var);
5474 util_htset(parser->htfields, var->name, var);
5476 for (i = 0; i < 3; ++i) {
5477 vec_push(parser->fields, (ast_expression*)me[i]);
5478 util_htset(parser->htfields, me[i]->name, me[i]);
5483 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5484 parser_addglobal(parser, var->name, (ast_expression*)var);
5486 for (i = 0; i < 3; ++i) {
5487 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5491 ast_expression *find = parser_find_global(parser, var->desc);
5494 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5498 if (var->expression.vtype != find->vtype) {
5502 ast_type_to_string(find, ty1, sizeof(ty1));
5503 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5505 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5512 * add alias to aliases table and to corrector
5513 * so corrections can apply for aliases as well.
5515 util_htset(parser->aliases, var->name, find);
5518 * add to corrector so corrections can work
5519 * even for aliases too.
5522 vec_last(parser->correct_variables),
5523 &vec_last(parser->correct_variables_score),
5527 /* generate aliases for vector components */
5531 util_asprintf(&buffer[0], "%s_x", var->desc);
5532 util_asprintf(&buffer[1], "%s_y", var->desc);
5533 util_asprintf(&buffer[2], "%s_z", var->desc);
5535 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5536 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5537 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5544 * add to corrector so corrections can work
5545 * even for aliases too.
5548 vec_last(parser->correct_variables),
5549 &vec_last(parser->correct_variables_score),
5553 vec_last(parser->correct_variables),
5554 &vec_last(parser->correct_variables_score),
5558 vec_last(parser->correct_variables),
5559 &vec_last(parser->correct_variables_score),
5567 /* a static adds itself to be generated like any other global
5568 * but is added to the local namespace instead
5570 char *defname = NULL;
5571 size_t prefix_len, ln;
5573 ln = strlen(parser->function->name);
5574 vec_append(defname, ln, parser->function->name);
5576 vec_append(defname, 2, "::");
5577 /* remember the length up to here */
5578 prefix_len = vec_size(defname);
5580 /* Add it to the local scope */
5581 util_htset(vec_last(parser->variables), var->name, (void*)var);
5585 vec_last(parser->correct_variables),
5586 &vec_last(parser->correct_variables_score),
5590 /* now rename the global */
5591 ln = strlen(var->name);
5592 vec_append(defname, ln, var->name);
5593 ast_value_set_name(var, defname);
5595 /* push it to the to-be-generated globals */
5596 vec_push(parser->globals, (ast_expression*)var);
5598 /* same game for the vector members */
5600 for (i = 0; i < 3; ++i) {
5601 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5605 vec_last(parser->correct_variables),
5606 &vec_last(parser->correct_variables_score),
5610 vec_shrinkto(defname, prefix_len);
5611 ln = strlen(me[i]->name);
5612 vec_append(defname, ln, me[i]->name);
5613 ast_member_set_name(me[i], defname);
5615 vec_push(parser->globals, (ast_expression*)me[i]);
5620 vec_push(localblock->locals, var);
5621 parser_addlocal(parser, var->name, (ast_expression*)var);
5623 for (i = 0; i < 3; ++i) {
5624 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5625 ast_block_collect(localblock, (ast_expression*)me[i]);
5631 me[0] = me[1] = me[2] = NULL;
5636 if (var->expression.vtype == TYPE_ARRAY) {
5638 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5639 if (!parser_create_array_setter(parser, var, name))
5641 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5642 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5645 else if (!localblock && !nofields &&
5646 var->expression.vtype == TYPE_FIELD &&
5647 var->expression.next->vtype == TYPE_ARRAY)
5650 ast_expression *telem;
5652 ast_value *array = (ast_value*)var->expression.next;
5654 if (!ast_istype(var->expression.next, ast_value)) {
5655 parseerror(parser, "internal error: field element type must be an ast_value");
5659 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5660 if (!parser_create_array_field_setter(parser, array, name))
5663 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5664 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5665 tfield->expression.next = telem;
5666 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5667 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5675 if (parser->tok == ';') {
5676 ast_delete(basetype);
5677 if (!parser_next(parser)) {
5678 parseerror(parser, "error after variable declaration");
5684 if (parser->tok == ',')
5688 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5691 parseerror(parser, "missing comma or semicolon while parsing variables");
5695 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5696 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5697 "initializing expression turns variable `%s` into a constant in this standard",
5704 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5705 if (parser->tok != '=') {
5706 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5710 if (!parser_next(parser)) {
5711 parseerror(parser, "error parsing initializer");
5715 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5716 parseerror(parser, "expected '=' before function body in this standard");
5719 if (parser->tok == '#') {
5720 ast_function *func = NULL;
5721 ast_value *number = NULL;
5727 parseerror(parser, "cannot declare builtins within functions");
5730 if (var->expression.vtype != TYPE_FUNCTION) {
5731 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5734 if (!parser_next(parser)) {
5735 parseerror(parser, "expected builtin number");
5739 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5740 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5742 parseerror(parser, "builtin number expected");
5745 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5748 parseerror(parser, "builtin number must be a compile time constant");
5751 if (number->expression.vtype == TYPE_INTEGER)
5752 builtin_num = number->constval.vint;
5753 else if (number->expression.vtype == TYPE_FLOAT)
5754 builtin_num = number->constval.vfloat;
5757 parseerror(parser, "builtin number must be an integer constant");
5762 fractional = modff(builtin_num, &integral);
5763 if (builtin_num < 0 || fractional != 0) {
5764 parseerror(parser, "builtin number must be an integer greater than zero");
5768 /* we only want the integral part anyways */
5769 builtin_num = integral;
5770 } else if (parser->tok == TOKEN_INTCONST) {
5771 builtin_num = parser_token(parser)->constval.i;
5773 parseerror(parser, "builtin number must be a compile time constant");
5777 if (var->hasvalue) {
5778 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5779 "builtin `%s` has already been defined\n"
5780 " -> previous declaration here: %s:%i",
5781 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5785 func = ast_function_new(ast_ctx(var), var->name, var);
5787 parseerror(parser, "failed to allocate function for `%s`", var->name);
5790 vec_push(parser->functions, func);
5792 func->builtin = -builtin_num-1;
5795 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5796 ? (parser->tok != ',' && parser->tok != ';')
5797 : (!parser_next(parser)))
5799 parseerror(parser, "expected comma or semicolon");
5801 ast_function_delete(func);
5802 var->constval.vfunc = NULL;
5806 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5809 /* Note that fteqcc and most others don't even *have*
5810 * local arrays, so this is not a high priority.
5812 parseerror(parser, "TODO: initializers for local arrays");
5816 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
5818 parseerror(parser, "TODO: initializing global arrays is not supported yet!");
5821 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5824 parseerror(parser, "cannot declare functions within functions");
5829 ast_ctx(proto) = parser_ctx(parser);
5831 if (!parse_function_body(parser, var))
5833 ast_delete(basetype);
5834 for (i = 0; i < vec_size(parser->gotos); ++i)
5835 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5836 vec_free(parser->gotos);
5837 vec_free(parser->labels);
5840 ast_expression *cexp;
5843 cexp = parse_expression_leave(parser, true, false, false);
5848 cval = (ast_value*)cexp;
5849 if (cval != parser->nil &&
5850 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5853 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5857 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5858 qualifier != CV_VAR)
5860 var->cvq = CV_CONST;
5862 if (cval == parser->nil)
5863 var->expression.flags |= AST_FLAG_INITIALIZED;
5866 var->hasvalue = true;
5867 if (cval->expression.vtype == TYPE_STRING)
5868 var->constval.vstring = parser_strdup(cval->constval.vstring);
5869 else if (cval->expression.vtype == TYPE_FIELD)
5870 var->constval.vfield = cval;
5872 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5878 shunt sy = { NULL, NULL, NULL, NULL };
5881 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5882 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5883 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5884 if (!parser_sy_apply_operator(parser, &sy))
5887 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5888 parseerror(parser, "internal error: leaked operands");
5889 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5900 if (parser->tok == ',') {
5901 if (!parser_next(parser)) {
5902 parseerror(parser, "expected another variable");
5906 if (parser->tok != TOKEN_IDENT) {
5907 parseerror(parser, "expected another variable");
5910 var = ast_value_copy(basetype);
5912 ast_value_set_name(var, parser_tokval(parser));
5913 if (!parser_next(parser)) {
5914 parseerror(parser, "error parsing variable declaration");
5920 if (parser->tok != ';') {
5921 parseerror(parser, "missing semicolon after variables");
5925 if (!parser_next(parser)) {
5926 parseerror(parser, "parse error after variable declaration");
5930 ast_delete(basetype);
5934 if (cleanvar && var)
5936 ast_delete(basetype);
5940 ast_delete(basetype);
5941 if (cleanvar && var)
5943 if (me[0]) ast_member_delete(me[0]);
5944 if (me[1]) ast_member_delete(me[1]);
5945 if (me[2]) ast_member_delete(me[2]);
5949 static bool parser_global_statement(parser_t *parser)
5953 bool is_static = false;
5954 uint32_t qflags = 0;
5955 ast_value *istype = NULL;
5956 char *vstring = NULL;
5958 if (parser->tok == TOKEN_IDENT)
5959 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5961 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5963 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5965 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5967 if (cvq == CV_WRONG)
5969 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5971 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5973 return parse_enum(parser);
5975 else if (parser->tok == TOKEN_KEYWORD)
5977 if (!strcmp(parser_tokval(parser), "typedef")) {
5978 if (!parser_next(parser)) {
5979 parseerror(parser, "expected type definition after 'typedef'");
5982 return parse_typedef(parser);
5984 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5987 else if (parser->tok == '#')
5989 return parse_pragma(parser);
5991 else if (parser->tok == '$')
5993 if (!parser_next(parser)) {
5994 parseerror(parser, "parse error");
6000 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6006 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6008 return util_crc16(old, str, strlen(str));
6011 static void progdefs_crc_file(const char *str)
6013 /* write to progdefs.h here */
6017 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6019 old = progdefs_crc_sum(old, str);
6020 progdefs_crc_file(str);
6024 static void generate_checksum(parser_t *parser)
6026 uint16_t crc = 0xFFFF;
6030 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6031 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6033 progdefs_crc_file("\tint\tpad;\n");
6034 progdefs_crc_file("\tint\tofs_return[3];\n");
6035 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6036 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6037 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6038 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6039 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6040 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6041 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6042 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6044 for (i = 0; i < parser->crc_globals; ++i) {
6045 if (!ast_istype(parser->globals[i], ast_value))
6047 value = (ast_value*)(parser->globals[i]);
6048 switch (value->expression.vtype) {
6049 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6050 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6051 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6052 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6054 crc = progdefs_crc_both(crc, "\tint\t");
6057 crc = progdefs_crc_both(crc, value->name);
6058 crc = progdefs_crc_both(crc, ";\n");
6060 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6061 for (i = 0; i < parser->crc_fields; ++i) {
6062 if (!ast_istype(parser->fields[i], ast_value))
6064 value = (ast_value*)(parser->fields[i]);
6065 switch (value->expression.next->vtype) {
6066 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6067 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6068 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6069 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6071 crc = progdefs_crc_both(crc, "\tint\t");
6074 crc = progdefs_crc_both(crc, value->name);
6075 crc = progdefs_crc_both(crc, ";\n");
6077 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6079 parser->code->crc = crc;
6082 parser_t *parser_create()
6088 parser = (parser_t*)mem_a(sizeof(parser_t));
6092 memset(parser, 0, sizeof(*parser));
6094 if (!(parser->code = code_init())) {
6099 for (i = 0; i < operator_count; ++i) {
6100 if (operators[i].id == opid1('=')) {
6101 parser->assign_op = operators+i;
6105 if (!parser->assign_op) {
6106 printf("internal error: initializing parser: failed to find assign operator\n");
6111 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6112 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6113 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6114 vec_push(parser->_blocktypedefs, 0);
6116 parser->aliases = util_htnew(PARSER_HT_SIZE);
6118 parser->ht_imm_string = util_htnew(512);
6121 vec_push(parser->correct_variables, correct_trie_new());
6122 vec_push(parser->correct_variables_score, NULL);
6124 empty_ctx.file = "<internal>";
6126 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6127 parser->nil->cvq = CV_CONST;
6128 if (OPTS_FLAG(UNTYPED_NIL))
6129 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6131 parser->max_param_count = 1;
6133 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6134 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6135 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6137 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6138 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6139 parser->reserved_version->cvq = CV_CONST;
6140 parser->reserved_version->hasvalue = true;
6141 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6142 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6144 parser->reserved_version = NULL;
6147 parser->returns = NULL;
6151 static bool parser_compile(parser_t *parser)
6153 /* initial lexer/parser state */
6154 parser->lex->flags.noops = true;
6156 if (parser_next(parser))
6158 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6160 if (!parser_global_statement(parser)) {
6161 if (parser->tok == TOKEN_EOF)
6162 parseerror(parser, "unexpected eof");
6163 else if (compile_errors)
6164 parseerror(parser, "there have been errors, bailing out");
6165 lex_close(parser->lex);
6171 parseerror(parser, "parse error");
6172 lex_close(parser->lex);
6177 lex_close(parser->lex);
6180 return !compile_errors;
6183 bool parser_compile_file(parser_t *parser, const char *filename)
6185 parser->lex = lex_open(filename);
6187 con_err("failed to open file \"%s\"\n", filename);
6190 return parser_compile(parser);
6193 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6195 parser->lex = lex_open_string(str, len, name);
6197 con_err("failed to create lexer for string \"%s\"\n", name);
6200 return parser_compile(parser);
6203 void parser_cleanup(parser_t *parser)
6206 for (i = 0; i < vec_size(parser->accessors); ++i) {
6207 ast_delete(parser->accessors[i]->constval.vfunc);
6208 parser->accessors[i]->constval.vfunc = NULL;
6209 ast_delete(parser->accessors[i]);
6211 for (i = 0; i < vec_size(parser->functions); ++i) {
6212 ast_delete(parser->functions[i]);
6214 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6215 ast_delete(parser->imm_vector[i]);
6217 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6218 ast_delete(parser->imm_string[i]);
6220 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6221 ast_delete(parser->imm_float[i]);
6223 for (i = 0; i < vec_size(parser->fields); ++i) {
6224 ast_delete(parser->fields[i]);
6226 for (i = 0; i < vec_size(parser->globals); ++i) {
6227 ast_delete(parser->globals[i]);
6229 for (i = 0; i < vec_size(parser->returns); ++i) {
6230 ast_delete(parser->returns[i]);
6232 vec_free(parser->accessors);
6233 vec_free(parser->functions);
6234 vec_free(parser->imm_vector);
6235 vec_free(parser->imm_string);
6236 util_htdel(parser->ht_imm_string);
6237 vec_free(parser->imm_float);
6238 vec_free(parser->globals);
6239 vec_free(parser->fields);
6241 for (i = 0; i < vec_size(parser->variables); ++i)
6242 util_htdel(parser->variables[i]);
6243 vec_free(parser->variables);
6244 vec_free(parser->_blocklocals);
6245 vec_free(parser->_locals);
6248 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6249 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6251 vec_free(parser->correct_variables);
6252 vec_free(parser->correct_variables_score);
6255 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6256 ast_delete(parser->_typedefs[i]);
6257 vec_free(parser->_typedefs);
6258 for (i = 0; i < vec_size(parser->typedefs); ++i)
6259 util_htdel(parser->typedefs[i]);
6260 vec_free(parser->typedefs);
6261 vec_free(parser->_blocktypedefs);
6263 vec_free(parser->_block_ctx);
6265 vec_free(parser->labels);
6266 vec_free(parser->gotos);
6267 vec_free(parser->breaks);
6268 vec_free(parser->continues);
6270 ast_value_delete(parser->nil);
6272 ast_value_delete(parser->const_vec[0]);
6273 ast_value_delete(parser->const_vec[1]);
6274 ast_value_delete(parser->const_vec[2]);
6276 util_htdel(parser->aliases);
6278 intrin_intrinsics_destroy(parser);
6280 code_cleanup(parser->code);
6285 bool parser_finish(parser_t *parser, const char *output)
6291 if (compile_errors) {
6292 con_out("*** there were compile errors\n");
6296 ir = ir_builder_new("gmqcc_out");
6298 con_out("failed to allocate builder\n");
6302 for (i = 0; i < vec_size(parser->fields); ++i) {
6305 if (!ast_istype(parser->fields[i], ast_value))
6307 field = (ast_value*)parser->fields[i];
6308 hasvalue = field->hasvalue;
6309 field->hasvalue = false;
6310 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6311 con_out("failed to generate field %s\n", field->name);
6312 ir_builder_delete(ir);
6317 ast_expression *subtype;
6318 field->hasvalue = true;
6319 subtype = field->expression.next;
6320 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6321 if (subtype->vtype == TYPE_FIELD)
6322 ifld->fieldtype = subtype->next->vtype;
6323 else if (subtype->vtype == TYPE_FUNCTION)
6324 ifld->outtype = subtype->next->vtype;
6325 (void)!ir_value_set_field(field->ir_v, ifld);
6328 for (i = 0; i < vec_size(parser->globals); ++i) {
6330 if (!ast_istype(parser->globals[i], ast_value))
6332 asvalue = (ast_value*)(parser->globals[i]);
6333 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6334 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6335 "unused global: `%s`", asvalue->name);
6337 if (!ast_global_codegen(asvalue, ir, false)) {
6338 con_out("failed to generate global %s\n", asvalue->name);
6339 ir_builder_delete(ir);
6343 /* Build function vararg accessor ast tree now before generating
6344 * immediates, because the accessors may add new immediates
6346 for (i = 0; i < vec_size(parser->functions); ++i) {
6347 ast_function *f = parser->functions[i];
6349 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6350 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6351 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6352 con_out("failed to generate vararg setter for %s\n", f->name);
6353 ir_builder_delete(ir);
6356 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6357 con_out("failed to generate vararg getter for %s\n", f->name);
6358 ir_builder_delete(ir);
6362 ast_delete(f->varargs);
6367 /* Now we can generate immediates */
6368 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6369 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6370 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6371 ir_builder_delete(ir);
6375 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6376 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6377 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6378 ir_builder_delete(ir);
6382 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6383 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6384 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6385 ir_builder_delete(ir);
6389 for (i = 0; i < vec_size(parser->globals); ++i) {
6391 if (!ast_istype(parser->globals[i], ast_value))
6393 asvalue = (ast_value*)(parser->globals[i]);
6394 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6396 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6397 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6398 "uninitialized constant: `%s`",
6400 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6401 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6402 "uninitialized global: `%s`",
6405 if (!ast_generate_accessors(asvalue, ir)) {
6406 ir_builder_delete(ir);
6410 for (i = 0; i < vec_size(parser->fields); ++i) {
6412 asvalue = (ast_value*)(parser->fields[i]->next);
6414 if (!ast_istype((ast_expression*)asvalue, ast_value))
6416 if (asvalue->expression.vtype != TYPE_ARRAY)
6418 if (!ast_generate_accessors(asvalue, ir)) {
6419 ir_builder_delete(ir);
6423 for (i = 0; i < vec_size(parser->returns); ++i) {
6424 if (!ast_global_codegen(parser->returns[i], ir, false)) {
6425 con_out("internal error: failed to generate return assignment %s\n", parser->returns[i]->name);
6426 ir_builder_delete(ir);
6430 if (parser->reserved_version &&
6431 !ast_global_codegen(parser->reserved_version, ir, false))
6433 con_out("failed to generate reserved::version");
6434 ir_builder_delete(ir);
6437 for (i = 0; i < vec_size(parser->functions); ++i) {
6438 ast_function *f = parser->functions[i];
6439 if (!ast_function_codegen(f, ir)) {
6440 con_out("failed to generate function %s\n", f->name);
6441 ir_builder_delete(ir);
6445 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6446 ir_builder_dump(ir, con_out);
6447 for (i = 0; i < vec_size(parser->functions); ++i) {
6448 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6449 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6450 ir_builder_delete(ir);
6455 if (compile_Werrors) {
6456 con_out("*** there were warnings treated as errors\n");
6457 compile_show_werrors();
6462 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6463 ir_builder_dump(ir, con_out);
6465 generate_checksum(parser);
6467 if (!ir_builder_generate(parser->code, ir, output)) {
6468 con_out("*** failed to generate output file\n");
6469 ir_builder_delete(ir);
6474 ir_builder_delete(ir);