2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 512
35 #define TYPEDEF_HT_SIZE 512
37 typedef struct parser_s {
43 ast_expression **globals;
44 ast_expression **fields;
45 ast_function **functions;
46 ast_value **imm_float;
47 ast_value **imm_string;
48 ast_value **imm_vector;
52 ht ht_imm_string_dotranslate;
54 /* must be deleted first, they reference immediates and values */
55 ast_value **accessors;
57 ast_value *imm_float_zero;
58 ast_value *imm_float_one;
59 ast_value *imm_float_neg_one;
61 ast_value *imm_vector_zero;
64 ast_value *reserved_version;
69 ast_function *function;
72 /* All the labels the function defined...
73 * Should they be in ast_function instead?
78 const char **continues;
80 /* A list of hashtables for each scope */
86 /* same as above but for the spelling corrector */
87 correct_trie_t **correct_variables;
88 size_t ***correct_variables_score; /* vector of vector of size_t* */
90 /* not to be used directly, we use the hash table */
91 ast_expression **_locals;
93 ast_value **_typedefs;
94 size_t *_blocktypedefs;
95 lex_ctx_t *_block_ctx;
97 /* we store the '=' operator info */
98 const oper_info *assign_op;
101 ast_value *const_vec[3];
106 /* collected information */
107 size_t max_param_count;
110 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
112 static void parser_enterblock(parser_t *parser);
113 static bool parser_leaveblock(parser_t *parser);
114 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
115 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
116 static bool parse_typedef(parser_t *parser);
117 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);
118 static ast_block* parse_block(parser_t *parser);
119 static bool parse_block_into(parser_t *parser, ast_block *block);
120 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
121 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
122 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
123 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
124 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
125 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
126 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
128 static void parseerror(parser_t *parser, const char *fmt, ...)
132 vcompile_error(parser->lex->tok.ctx, fmt, ap);
136 /* returns true if it counts as an error */
137 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
142 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
147 /**********************************************************************
148 * some maths used for constant folding
151 vec3_t vec3_add(vec3_t a, vec3_t b)
160 vec3_t vec3_sub(vec3_t a, vec3_t b)
169 qcfloat_t vec3_mulvv(vec3_t a, vec3_t b)
171 return (a.x * b.x + a.y * b.y + a.z * b.z);
174 vec3_t vec3_mulvf(vec3_t a, float b)
183 /**********************************************************************
187 static bool parser_next(parser_t *parser)
189 /* lex_do kills the previous token */
190 parser->tok = lex_do(parser->lex);
191 if (parser->tok == TOKEN_EOF)
193 if (parser->tok >= TOKEN_ERROR) {
194 parseerror(parser, "lex error");
200 #define parser_tokval(p) ((p)->lex->tok.value)
201 #define parser_token(p) (&((p)->lex->tok))
202 #define parser_ctx(p) ((p)->lex->tok.ctx)
204 static ast_value* parser_const_float(parser_t *parser, double d)
209 for (i = 0; i < vec_size(parser->imm_float); ++i) {
210 const double compare = parser->imm_float[i]->constval.vfloat;
211 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
212 return parser->imm_float[i];
215 ctx = parser_ctx(parser);
217 memset(&ctx, 0, sizeof(ctx));
219 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
221 out->hasvalue = true;
223 out->constval.vfloat = d;
224 vec_push(parser->imm_float, out);
228 static ast_value* parser_const_float_0(parser_t *parser)
230 if (!parser->imm_float_zero)
231 parser->imm_float_zero = parser_const_float(parser, 0);
232 return parser->imm_float_zero;
235 static ast_value* parser_const_float_neg1(parser_t *parser) {
236 if (!parser->imm_float_neg_one)
237 parser->imm_float_neg_one = parser_const_float(parser, -1);
238 return parser->imm_float_neg_one;
241 static ast_value* parser_const_float_1(parser_t *parser)
243 if (!parser->imm_float_one)
244 parser->imm_float_one = parser_const_float(parser, 1);
245 return parser->imm_float_one;
248 static char *parser_strdup(const char *str)
251 /* actually dup empty strings */
252 char *out = (char*)mem_a(1);
256 return util_strdup(str);
259 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
261 ht ht_string = (dotranslate)
262 ? parser->ht_imm_string_dotranslate
263 : parser->ht_imm_string;
266 size_t hash = util_hthash(ht_string, str);
268 if ((out = (ast_value*)util_htgeth(ht_string, str, hash)))
271 for (i = 0; i < vec_size(parser->imm_string); ++i) {
272 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
273 return parser->imm_string[i];
278 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
279 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
280 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
282 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
285 out->hasvalue = true;
287 out->constval.vstring = parser_strdup(str);
288 vec_push(parser->imm_string, out);
289 util_htseth(ht_string, str, hash, out);
294 static ast_value* parser_const_vector(parser_t *parser, vec3_t v)
298 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
299 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
300 return parser->imm_vector[i];
302 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
304 out->hasvalue = true;
306 out->constval.vvec = v;
307 vec_push(parser->imm_vector, out);
311 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
317 return parser_const_vector(parser, v);
320 static ast_value* parser_const_vector_0(parser_t *parser)
322 if (!parser->imm_vector_zero)
323 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
324 return parser->imm_vector_zero;
327 static ast_expression* parser_find_field(parser_t *parser, const char *name)
329 return ( ast_expression*)util_htget(parser->htfields, name);
332 static ast_expression* parser_find_label(parser_t *parser, const char *name)
335 for(i = 0; i < vec_size(parser->labels); i++)
336 if (!strcmp(parser->labels[i]->name, name))
337 return (ast_expression*)parser->labels[i];
341 static ast_expression* parser_find_global(parser_t *parser, const char *name)
343 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
346 return (ast_expression*)util_htget(parser->htglobals, name);
349 static ast_expression* parser_find_param(parser_t *parser, const char *name)
353 if (!parser->function)
355 fun = parser->function->vtype;
356 for (i = 0; i < vec_size(fun->expression.params); ++i) {
357 if (!strcmp(fun->expression.params[i]->name, name))
358 return (ast_expression*)(fun->expression.params[i]);
363 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
368 hash = util_hthash(parser->htglobals, name);
371 for (i = vec_size(parser->variables); i > upto;) {
373 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
377 return parser_find_param(parser, name);
380 static ast_expression* parser_find_var(parser_t *parser, const char *name)
384 v = parser_find_local(parser, name, 0, &dummy);
385 if (!v) v = parser_find_global(parser, name);
389 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
393 hash = util_hthash(parser->typedefs[0], name);
395 for (i = vec_size(parser->typedefs); i > upto;) {
397 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
403 /* include intrinsics */
408 size_t etype; /* 0 = expression, others are operators */
412 ast_block *block; /* for commas and function calls */
431 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
442 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
446 e.out = (ast_expression*)v;
453 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
455 e.etype = 1 + (op - operators);
464 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
475 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
476 * so we need to rotate it to become ent.(foo[n]).
478 static bool rotate_entfield_array_index_nodes(ast_expression **out)
480 ast_array_index *index, *oldindex;
481 ast_entfield *entfield;
485 ast_expression *entity;
487 lex_ctx_t ctx = ast_ctx(*out);
489 if (!ast_istype(*out, ast_array_index))
491 index = (ast_array_index*)*out;
493 if (!ast_istype(index->array, ast_entfield))
495 entfield = (ast_entfield*)index->array;
497 if (!ast_istype(entfield->field, ast_value))
499 field = (ast_value*)entfield->field;
502 entity = entfield->entity;
506 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
507 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
508 *out = (ast_expression*)entfield;
510 oldindex->array = NULL;
511 oldindex->index = NULL;
512 ast_delete(oldindex);
517 static bool immediate_is_true(lex_ctx_t ctx, ast_value *v)
519 switch (v->expression.vtype) {
521 return !!v->constval.vfloat;
523 return !!v->constval.vint;
525 if (OPTS_FLAG(CORRECT_LOGIC))
526 return v->constval.vvec.x &&
527 v->constval.vvec.y &&
530 return !!(v->constval.vvec.x);
532 if (!v->constval.vstring)
534 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
536 return !!v->constval.vstring[0];
538 compile_error(ctx, "internal error: immediate_is_true on invalid type");
539 return !!v->constval.vfunc;
543 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
547 ast_expression *out = NULL;
548 ast_expression *exprs[3];
549 ast_block *blocks[3];
550 ast_value *asvalue[3];
551 ast_binstore *asbinstore;
552 size_t i, assignop, addop, subop;
553 qcint_t generated_op = 0;
558 if (!vec_size(sy->ops)) {
559 parseerror(parser, "internal error: missing operator");
563 if (vec_last(sy->ops).isparen) {
564 parseerror(parser, "unmatched parenthesis");
568 op = &operators[vec_last(sy->ops).etype - 1];
569 ctx = vec_last(sy->ops).ctx;
571 if (vec_size(sy->out) < op->operands) {
572 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
573 op->op, (int)op->id);
577 vec_shrinkby(sy->ops, 1);
579 /* op(:?) has no input and no output */
583 vec_shrinkby(sy->out, op->operands);
584 for (i = 0; i < op->operands; ++i) {
585 exprs[i] = sy->out[vec_size(sy->out)+i].out;
586 blocks[i] = sy->out[vec_size(sy->out)+i].block;
587 asvalue[i] = (ast_value*)exprs[i];
589 if (exprs[i]->vtype == TYPE_NOEXPR &&
590 !(i != 0 && op->id == opid2('?',':')) &&
591 !(i == 1 && op->id == opid1('.')))
593 if (ast_istype(exprs[i], ast_label))
594 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
596 compile_error(ast_ctx(exprs[i]), "not an expression");
597 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
601 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
602 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
606 #define NotSameType(T) \
607 (exprs[0]->vtype != exprs[1]->vtype || \
608 exprs[0]->vtype != T)
609 #define CanConstFold1(A) \
610 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
611 (A)->vtype != TYPE_FUNCTION)
612 #define CanConstFold(A, B) \
613 (CanConstFold1(A) && CanConstFold1(B))
614 #define ConstV(i) (asvalue[(i)]->constval.vvec)
615 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
616 #define ConstS(i) (asvalue[(i)]->constval.vstring)
620 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
624 if (exprs[0]->vtype == TYPE_VECTOR &&
625 exprs[1]->vtype == TYPE_NOEXPR)
627 if (exprs[1] == (ast_expression*)parser->const_vec[0])
628 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
629 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
630 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
631 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
632 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
634 compile_error(ctx, "access to invalid vector component");
638 else if (exprs[0]->vtype == TYPE_ENTITY) {
639 if (exprs[1]->vtype != TYPE_FIELD) {
640 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
643 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
645 else if (exprs[0]->vtype == TYPE_VECTOR) {
646 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
650 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
656 if (exprs[0]->vtype != TYPE_ARRAY &&
657 !(exprs[0]->vtype == TYPE_FIELD &&
658 exprs[0]->next->vtype == TYPE_ARRAY))
660 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
661 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
664 if (exprs[1]->vtype != TYPE_FLOAT) {
665 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
666 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
669 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
670 if (rotate_entfield_array_index_nodes(&out))
673 /* This is not broken in fteqcc anymore */
674 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
675 /* this error doesn't need to make us bail out */
676 (void)!parsewarning(parser, WARN_EXTENSIONS,
677 "accessing array-field members of an entity without parenthesis\n"
678 " -> this is an extension from -std=gmqcc");
685 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
686 vec_push(sy->out, syexp(ctx, exprs[0]));
687 vec_push(sy->out, syexp(ctx, exprs[1]));
688 vec_last(sy->argc)++;
692 if (!ast_block_add_expr(blocks[0], exprs[1]))
695 blocks[0] = ast_block_new(ctx);
696 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
697 !ast_block_add_expr(blocks[0], exprs[1]))
702 ast_block_set_type(blocks[0], exprs[1]);
704 vec_push(sy->out, syblock(ctx, blocks[0]));
711 switch (exprs[0]->vtype) {
713 if (CanConstFold1(exprs[0]))
714 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
716 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
717 (ast_expression*)parser_const_float_0(parser),
721 if (CanConstFold1(exprs[0]))
722 out = (ast_expression*)parser_const_vector_f(parser,
723 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
725 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
726 (ast_expression*)parser_const_vector_0(parser),
730 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
731 type_name[exprs[0]->vtype]);
737 switch (exprs[0]->vtype) {
739 if (CanConstFold1(exprs[0]))
740 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
742 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
745 if (CanConstFold1(exprs[0]))
746 out = (ast_expression*)parser_const_float(parser,
747 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
749 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
752 if (CanConstFold1(exprs[0])) {
753 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
754 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
756 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
758 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
759 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
761 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
764 /* we don't constant-fold NOT for these types */
766 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
769 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
772 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
773 type_name[exprs[0]->vtype]);
779 if (exprs[0]->vtype != exprs[1]->vtype ||
780 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
782 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
783 type_name[exprs[0]->vtype],
784 type_name[exprs[1]->vtype]);
787 switch (exprs[0]->vtype) {
789 if (CanConstFold(exprs[0], exprs[1]))
791 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
794 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
797 if (CanConstFold(exprs[0], exprs[1]))
798 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
800 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
803 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
804 type_name[exprs[0]->vtype],
805 type_name[exprs[1]->vtype]);
810 if (exprs[0]->vtype != exprs[1]->vtype ||
811 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
813 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
814 type_name[exprs[1]->vtype],
815 type_name[exprs[0]->vtype]);
818 switch (exprs[0]->vtype) {
820 if (CanConstFold(exprs[0], exprs[1]))
821 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
823 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
826 if (CanConstFold(exprs[0], exprs[1]))
827 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
829 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
832 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
833 type_name[exprs[1]->vtype],
834 type_name[exprs[0]->vtype]);
839 if (exprs[0]->vtype != exprs[1]->vtype &&
840 !(exprs[0]->vtype == TYPE_VECTOR &&
841 exprs[1]->vtype == TYPE_FLOAT) &&
842 !(exprs[1]->vtype == TYPE_VECTOR &&
843 exprs[0]->vtype == TYPE_FLOAT)
846 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
847 type_name[exprs[1]->vtype],
848 type_name[exprs[0]->vtype]);
851 switch (exprs[0]->vtype) {
853 if (exprs[1]->vtype == TYPE_VECTOR)
855 if (CanConstFold(exprs[0], exprs[1]))
856 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
858 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
862 if (CanConstFold(exprs[0], exprs[1]))
863 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
865 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
869 if (exprs[1]->vtype == TYPE_FLOAT)
871 if (CanConstFold(exprs[0], exprs[1]))
872 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
874 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
878 if (CanConstFold(exprs[0], exprs[1]))
879 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
880 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
881 vec3_t vec = ConstV(0);
882 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
883 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
884 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
885 out->node.keep = false;
886 ((ast_member*)out)->rvalue = true;
888 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
890 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
891 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
892 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
893 out->node.keep = false;
894 ((ast_member*)out)->rvalue = true;
896 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
898 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
899 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
900 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
901 out->node.keep = false;
902 ((ast_member*)out)->rvalue = true;
904 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
907 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
909 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
910 vec3_t vec = ConstV(1);
911 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
912 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
913 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
914 out->node.keep = false;
915 ((ast_member*)out)->rvalue = true;
917 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
919 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
920 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
921 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
922 out->node.keep = false;
923 ((ast_member*)out)->rvalue = true;
925 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
927 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
928 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
929 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
930 out->node.keep = false;
931 ((ast_member*)out)->rvalue = true;
933 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
936 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
939 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
943 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
944 type_name[exprs[1]->vtype],
945 type_name[exprs[0]->vtype]);
950 if (exprs[1]->vtype != TYPE_FLOAT) {
951 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
952 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
953 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
956 if (exprs[0]->vtype == TYPE_FLOAT) {
957 if (CanConstFold(exprs[0], exprs[1]))
958 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
960 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
962 else if (exprs[0]->vtype == TYPE_VECTOR) {
963 if (CanConstFold(exprs[0], exprs[1]))
964 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
966 if (CanConstFold1(exprs[1])) {
967 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
969 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
970 (ast_expression*)parser_const_float_1(parser),
974 compile_error(ctx, "internal error: failed to generate division");
977 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
982 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
983 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
984 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
990 if (NotSameType(TYPE_FLOAT)) {
991 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
992 type_name[exprs[0]->vtype],
993 type_name[exprs[1]->vtype]);
996 if (CanConstFold(exprs[0], exprs[1])) {
997 out = (ast_expression*)parser_const_float(parser,
998 (float)(((qcint_t)ConstF(0)) % ((qcint_t)ConstF(1))));
1000 /* generate a call to __builtin_mod */
1001 ast_expression *mod = intrin_func(parser, "mod");
1002 ast_call *call = NULL;
1003 if (!mod) return false; /* can return null for missing floor */
1005 call = ast_call_new(parser_ctx(parser), mod);
1006 vec_push(call->params, exprs[0]);
1007 vec_push(call->params, exprs[1]);
1009 out = (ast_expression*)call;
1013 case opid2('%','='):
1014 compile_error(ctx, "%= is unimplemented");
1019 if (NotSameType(TYPE_FLOAT)) {
1020 compile_error(ctx, "invalid types used in expression: cannot perform bit operations 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 (op->id == opid1('|') ? (float)( ((qcint_t)ConstF(0)) | ((qcint_t)ConstF(1)) ) :
1028 (float)( ((qcint_t)ConstF(0)) & ((qcint_t)ConstF(1)) ) ));
1030 out = (ast_expression*)ast_binary_new(ctx,
1031 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1032 exprs[0], exprs[1]);
1036 * Okay lets designate what the hell is an acceptable use
1037 * of the ^ operator. In many vector processing units, XOR
1038 * is allowed to be used on vectors, but only if the first
1039 * operand is a vector, the second operand can be a float
1040 * or vector. It's never legal for the first operand to be
1041 * a float, and then the following operand to be a vector.
1042 * Further more, the only time it is legal to do XOR otherwise
1043 * is when both operand are floats. This nicely crafted if
1044 * statement catches them all.
1046 * In the event that the first operand is a vector, two
1047 * possible situations can arise, thus, each element of
1048 * vector A (operand A) is exclusive-ORed with the corresponding
1049 * element of vector B (operand B), If B is scalar, the
1050 * scalar value is first replicated for each element.
1052 * The QCVM itself lacks a BITXOR instruction. Thus emulating
1053 * the mathematics of it is required. The following equation
1054 * is used: (LHS | RHS) & ~(LHS & RHS). However, due to the
1055 * QCVM also lacking a BITNEG instruction, we need to emulate
1056 * ~FOO with -1 - FOO, the whole process becoming this nicely
1057 * crafted expression: (LHS | RHS) & (-1 - (LHS & RHS)).
1059 * When A is not scalar, this process is repeated for all
1060 * components of vector A with the value in operand B,
1061 * only if operand B is scalar. When A is not scalar, and B
1062 * is also not scalar, this process is repeated for all
1063 * components of the vector A with the components of vector B.
1064 * Finally when A is scalar and B is scalar, this process is
1065 * simply used once for A and B being LHS and RHS respectfully.
1067 * Yes the semantics are a bit strange (no pun intended).
1068 * But then again BITXOR is strange itself, consdering it's
1069 * commutative, assocative, and elements of the BITXOR operation
1070 * are their own inverse.
1072 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
1073 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
1074 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
1076 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1077 type_name[exprs[0]->vtype],
1078 type_name[exprs[1]->vtype]);
1083 * IF the first expression is float, the following will be too
1084 * since scalar ^ vector is not allowed.
1086 if (exprs[0]->vtype == TYPE_FLOAT) {
1087 if(CanConstFold(exprs[0], exprs[1])) {
1088 out = (ast_expression*)parser_const_float(parser, (float)((qcint_t)(ConstF(0)) ^ ((qcint_t)(ConstF(1)))));
1090 ast_binary *expr = ast_binary_new(
1093 (ast_expression*)parser_const_float_neg1(parser),
1094 (ast_expression*)ast_binary_new(
1101 expr->refs = AST_REF_NONE;
1103 out = (ast_expression*)
1107 (ast_expression*)ast_binary_new(
1113 (ast_expression*)expr
1118 * The first is a vector: vector is allowed to xor with vector and
1119 * with scalar, branch here for the second operand.
1121 if (exprs[1]->vtype == TYPE_VECTOR) {
1123 * Xor all the values of the vector components against the
1124 * vectors components in question.
1126 if (CanConstFold(exprs[0], exprs[1])) {
1127 out = (ast_expression*)parser_const_vector_f(
1129 (float)(((qcint_t)(ConstV(0).x)) ^ ((qcint_t)(ConstV(1).x))),
1130 (float)(((qcint_t)(ConstV(0).y)) ^ ((qcint_t)(ConstV(1).y))),
1131 (float)(((qcint_t)(ConstV(0).z)) ^ ((qcint_t)(ConstV(1).z)))
1134 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against vector");
1139 * Xor all the values of the vector components against the
1140 * scalar in question.
1142 if (CanConstFold(exprs[0], exprs[1])) {
1143 out = (ast_expression*)parser_const_vector_f(
1145 (float)(((qcint_t)(ConstV(0).x)) ^ ((qcint_t)(ConstF(1)))),
1146 (float)(((qcint_t)(ConstV(0).y)) ^ ((qcint_t)(ConstF(1)))),
1147 (float)(((qcint_t)(ConstV(0).z)) ^ ((qcint_t)(ConstF(1))))
1150 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against float");
1158 case opid2('<','<'):
1159 case opid2('>','>'):
1160 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1161 if (op->id == opid2('<','<'))
1162 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1164 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1167 case opid3('<','<','='):
1168 case opid3('>','>','='):
1169 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1172 case opid2('|','|'):
1173 generated_op += 1; /* INSTR_OR */
1174 case opid2('&','&'):
1175 generated_op += INSTR_AND;
1176 if (CanConstFold(exprs[0], exprs[1]))
1178 if (OPTS_FLAG(PERL_LOGIC)) {
1179 if (immediate_is_true(ctx, asvalue[0]))
1183 out = (ast_expression*)parser_const_float(parser,
1184 ( (generated_op == INSTR_OR)
1185 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1186 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1191 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1192 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1193 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1194 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1197 for (i = 0; i < 2; ++i) {
1198 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1199 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1201 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1203 exprs[i] = out; out = NULL;
1204 if (OPTS_FLAG(PERL_LOGIC)) {
1205 /* here we want to keep the right expressions' type */
1209 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1210 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1212 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1214 exprs[i] = out; out = NULL;
1215 if (OPTS_FLAG(PERL_LOGIC)) {
1216 /* here we want to keep the right expressions' type */
1221 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1225 case opid2('?',':'):
1226 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1227 compile_error(ctx, "mismatched parenthesis/ternary");
1231 if (!ast_compare_type(exprs[1], exprs[2])) {
1232 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1233 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1234 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1237 if (CanConstFold1(exprs[0]))
1238 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1240 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1243 case opid2('*', '*'):
1244 if (NotSameType(TYPE_FLOAT)) {
1245 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1246 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1247 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1253 if (CanConstFold(exprs[0], exprs[1])) {
1254 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1256 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1257 vec_push(gencall->params, exprs[0]);
1258 vec_push(gencall->params, exprs[1]);
1259 out = (ast_expression*)gencall;
1263 case opid3('<','=','>'): /* -1, 0, or 1 */
1264 if (NotSameType(TYPE_FLOAT)) {
1265 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1266 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1267 compile_error(ctx, "invalid types used in comparision: %s and %s",
1273 if (CanConstFold(exprs[0], exprs[1])) {
1274 if (ConstF(0) < ConstF(1))
1275 out = (ast_expression*)parser_const_float_neg1(parser);
1276 else if (ConstF(0) == ConstF(1))
1277 out = (ast_expression*)parser_const_float_0(parser);
1278 else if (ConstF(0) > ConstF(1))
1279 out = (ast_expression*)parser_const_float_1(parser);
1281 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1283 eq->refs = AST_REF_NONE;
1286 out = (ast_expression*)ast_ternary_new(ctx,
1287 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1289 (ast_expression*)parser_const_float_neg1(parser),
1292 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1294 (ast_expression*)parser_const_float_0(parser),
1297 (ast_expression*)parser_const_float_1(parser)
1307 generated_op += 1; /* INSTR_GT */
1309 generated_op += 1; /* INSTR_LT */
1310 case opid2('>', '='):
1311 generated_op += 1; /* INSTR_GE */
1312 case opid2('<', '='):
1313 generated_op += INSTR_LE;
1314 if (NotSameType(TYPE_FLOAT)) {
1315 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1316 type_name[exprs[0]->vtype],
1317 type_name[exprs[1]->vtype]);
1320 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1322 case opid2('!', '='):
1323 if (exprs[0]->vtype != exprs[1]->vtype) {
1324 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1325 type_name[exprs[0]->vtype],
1326 type_name[exprs[1]->vtype]);
1329 out = CanConstFold(exprs[0], exprs[1])
1330 ? (ast_expression*)parser_const_float(parser, ConstF(0) != ConstF(1))
1331 : (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1333 case opid2('=', '='):
1334 if (exprs[0]->vtype != exprs[1]->vtype) {
1335 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1336 type_name[exprs[0]->vtype],
1337 type_name[exprs[1]->vtype]);
1340 out = CanConstFold(exprs[0], exprs[1])
1341 ? (ast_expression*)parser_const_float(parser, ConstF(0) == ConstF(1))
1342 : (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1346 if (ast_istype(exprs[0], ast_entfield)) {
1347 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1348 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1349 exprs[0]->vtype == TYPE_FIELD &&
1350 exprs[0]->next->vtype == TYPE_VECTOR)
1352 assignop = type_storep_instr[TYPE_VECTOR];
1355 assignop = type_storep_instr[exprs[0]->vtype];
1356 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1358 ast_type_to_string(field->next, ty1, sizeof(ty1));
1359 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1360 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1361 field->next->vtype == TYPE_FUNCTION &&
1362 exprs[1]->vtype == TYPE_FUNCTION)
1364 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1365 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1368 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1373 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1374 exprs[0]->vtype == TYPE_FIELD &&
1375 exprs[0]->next->vtype == TYPE_VECTOR)
1377 assignop = type_store_instr[TYPE_VECTOR];
1380 assignop = type_store_instr[exprs[0]->vtype];
1383 if (assignop == VINSTR_END) {
1384 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1385 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1386 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1388 else if (!ast_compare_type(exprs[0], exprs[1]))
1390 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1391 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1392 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1393 exprs[0]->vtype == TYPE_FUNCTION &&
1394 exprs[1]->vtype == TYPE_FUNCTION)
1396 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1397 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1400 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1403 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1404 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1406 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1408 case opid3('+','+','P'):
1409 case opid3('-','-','P'):
1411 if (exprs[0]->vtype != TYPE_FLOAT) {
1412 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1413 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1416 if (op->id == opid3('+','+','P'))
1417 addop = INSTR_ADD_F;
1419 addop = INSTR_SUB_F;
1420 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1421 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1423 if (ast_istype(exprs[0], ast_entfield)) {
1424 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1426 (ast_expression*)parser_const_float_1(parser));
1428 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1430 (ast_expression*)parser_const_float_1(parser));
1433 case opid3('S','+','+'):
1434 case opid3('S','-','-'):
1436 if (exprs[0]->vtype != TYPE_FLOAT) {
1437 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1438 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1441 if (op->id == opid3('S','+','+')) {
1442 addop = INSTR_ADD_F;
1443 subop = INSTR_SUB_F;
1445 addop = INSTR_SUB_F;
1446 subop = INSTR_ADD_F;
1448 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1449 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1451 if (ast_istype(exprs[0], ast_entfield)) {
1452 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1454 (ast_expression*)parser_const_float_1(parser));
1456 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1458 (ast_expression*)parser_const_float_1(parser));
1462 out = (ast_expression*)ast_binary_new(ctx, subop,
1464 (ast_expression*)parser_const_float_1(parser));
1466 case opid2('+','='):
1467 case opid2('-','='):
1468 if (exprs[0]->vtype != exprs[1]->vtype ||
1469 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1471 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1472 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1473 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1477 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1478 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1480 if (ast_istype(exprs[0], ast_entfield))
1481 assignop = type_storep_instr[exprs[0]->vtype];
1483 assignop = type_store_instr[exprs[0]->vtype];
1484 switch (exprs[0]->vtype) {
1486 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1487 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1488 exprs[0], exprs[1]);
1491 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1492 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1493 exprs[0], exprs[1]);
1496 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1497 type_name[exprs[0]->vtype],
1498 type_name[exprs[1]->vtype]);
1502 case opid2('*','='):
1503 case opid2('/','='):
1504 if (exprs[1]->vtype != TYPE_FLOAT ||
1505 !(exprs[0]->vtype == TYPE_FLOAT ||
1506 exprs[0]->vtype == TYPE_VECTOR))
1508 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1509 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1510 compile_error(ctx, "invalid types used in expression: %s and %s",
1514 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1515 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1517 if (ast_istype(exprs[0], ast_entfield))
1518 assignop = type_storep_instr[exprs[0]->vtype];
1520 assignop = type_store_instr[exprs[0]->vtype];
1521 switch (exprs[0]->vtype) {
1523 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1524 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1525 exprs[0], exprs[1]);
1528 if (op->id == opid2('*','=')) {
1529 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1530 exprs[0], exprs[1]);
1532 /* there's no DIV_VF */
1533 if (CanConstFold1(exprs[1])) {
1534 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1536 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1537 (ast_expression*)parser_const_float_1(parser),
1541 compile_error(ctx, "internal error: failed to generate division");
1544 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1549 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1550 type_name[exprs[0]->vtype],
1551 type_name[exprs[1]->vtype]);
1555 case opid2('&','='):
1556 case opid2('|','='):
1557 if (NotSameType(TYPE_FLOAT)) {
1558 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1559 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1560 compile_error(ctx, "invalid types used in expression: %s and %s",
1564 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1565 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1567 if (ast_istype(exprs[0], ast_entfield))
1568 assignop = type_storep_instr[exprs[0]->vtype];
1570 assignop = type_store_instr[exprs[0]->vtype];
1571 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1572 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1573 exprs[0], exprs[1]);
1575 case opid3('&','~','='):
1576 /* This is like: a &= ~(b);
1577 * But QC has no bitwise-not, so we implement it as
1580 if (NotSameType(TYPE_FLOAT)) {
1581 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1582 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1583 compile_error(ctx, "invalid types used in expression: %s and %s",
1587 if (ast_istype(exprs[0], ast_entfield))
1588 assignop = type_storep_instr[exprs[0]->vtype];
1590 assignop = type_store_instr[exprs[0]->vtype];
1591 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1594 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1595 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1597 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1598 asbinstore->keep_dest = true;
1599 out = (ast_expression*)asbinstore;
1602 case opid2('~', 'P'):
1603 if (exprs[0]->vtype != TYPE_FLOAT) {
1604 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1605 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1609 if(CanConstFold1(exprs[0]))
1610 out = (ast_expression*)parser_const_float(parser, ~(qcint_t)ConstF(0));
1612 out = (ast_expression*)
1613 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1619 compile_error(ctx, "failed to apply operator %s", op->op);
1623 vec_push(sy->out, syexp(ctx, out));
1627 static bool parser_close_call(parser_t *parser, shunt *sy)
1629 /* was a function call */
1630 ast_expression *fun;
1631 ast_value *funval = NULL;
1635 size_t paramcount, i;
1637 fid = vec_last(sy->ops).off;
1638 vec_shrinkby(sy->ops, 1);
1640 /* out[fid] is the function
1641 * everything above is parameters...
1643 if (!vec_size(sy->argc)) {
1644 parseerror(parser, "internal error: no argument counter available");
1648 paramcount = vec_last(sy->argc);
1651 if (vec_size(sy->out) < fid) {
1652 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1653 (unsigned long)vec_size(sy->out),
1655 (unsigned long)paramcount);
1659 fun = sy->out[fid].out;
1661 if (fun == intrinsic_debug_typestring) {
1663 if (fid+2 != vec_size(sy->out) ||
1664 vec_last(sy->out).block)
1666 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1669 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1670 ast_unref(vec_last(sy->out).out);
1671 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1672 (ast_expression*)parser_const_string(parser, ty, false));
1673 vec_shrinkby(sy->out, 1);
1677 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1681 if (fid+1 < vec_size(sy->out))
1684 if (fid+1 + paramcount != vec_size(sy->out)) {
1685 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1686 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1690 for (i = 0; i < paramcount; ++i)
1691 vec_push(call->params, sy->out[fid+1 + i].out);
1692 vec_shrinkby(sy->out, paramcount);
1693 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1694 if (parser->max_param_count < paramcount)
1695 parser->max_param_count = paramcount;
1697 if (ast_istype(fun, ast_value)) {
1698 funval = (ast_value*)fun;
1699 if ((fun->flags & AST_FLAG_VARIADIC) &&
1700 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1702 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1706 /* overwrite fid, the function, with a call */
1707 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1709 if (fun->vtype != TYPE_FUNCTION) {
1710 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1715 parseerror(parser, "could not determine function return type");
1718 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1720 if (fun->flags & AST_FLAG_DEPRECATED) {
1722 return !parsewarning(parser, WARN_DEPRECATED,
1723 "call to function (which is marked deprecated)\n",
1724 "-> it has been declared here: %s:%i",
1725 ast_ctx(fun).file, ast_ctx(fun).line);
1728 return !parsewarning(parser, WARN_DEPRECATED,
1729 "call to `%s` (which is marked deprecated)\n"
1730 "-> `%s` declared here: %s:%i",
1731 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1733 return !parsewarning(parser, WARN_DEPRECATED,
1734 "call to `%s` (deprecated: %s)\n"
1735 "-> `%s` declared here: %s:%i",
1736 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1740 if (vec_size(fun->params) != paramcount &&
1741 !((fun->flags & AST_FLAG_VARIADIC) &&
1742 vec_size(fun->params) < paramcount))
1744 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1746 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1747 "too %s parameters for call to %s: expected %i, got %i\n"
1748 " -> `%s` has been declared here: %s:%i",
1749 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1750 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1752 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1753 "too %s parameters for function call: expected %i, got %i\n"
1754 " -> it has been declared here: %s:%i",
1755 fewmany, (int)vec_size(fun->params), (int)paramcount,
1756 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1763 static bool parser_close_paren(parser_t *parser, shunt *sy)
1765 if (!vec_size(sy->ops)) {
1766 parseerror(parser, "unmatched closing paren");
1770 while (vec_size(sy->ops)) {
1771 if (vec_last(sy->ops).isparen) {
1772 if (vec_last(sy->paren) == PAREN_FUNC) {
1774 if (!parser_close_call(parser, sy))
1778 if (vec_last(sy->paren) == PAREN_EXPR) {
1780 if (!vec_size(sy->out)) {
1781 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1782 vec_shrinkby(sy->ops, 1);
1785 vec_shrinkby(sy->ops, 1);
1788 if (vec_last(sy->paren) == PAREN_INDEX) {
1790 /* pop off the parenthesis */
1791 vec_shrinkby(sy->ops, 1);
1792 /* then apply the index operator */
1793 if (!parser_sy_apply_operator(parser, sy))
1797 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1798 vec_last(sy->paren) = PAREN_TERNARY2;
1799 /* pop off the parenthesis */
1800 vec_shrinkby(sy->ops, 1);
1803 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1806 if (!parser_sy_apply_operator(parser, sy))
1812 static void parser_reclassify_token(parser_t *parser)
1815 if (parser->tok >= TOKEN_START)
1817 for (i = 0; i < operator_count; ++i) {
1818 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1819 parser->tok = TOKEN_OPERATOR;
1825 static ast_expression* parse_vararg_do(parser_t *parser)
1827 ast_expression *idx, *out;
1829 ast_value *funtype = parser->function->vtype;
1830 lex_ctx_t ctx = parser_ctx(parser);
1832 if (!parser->function->varargs) {
1833 parseerror(parser, "function has no variable argument list");
1837 if (!parser_next(parser) || parser->tok != '(') {
1838 parseerror(parser, "expected parameter index and type in parenthesis");
1841 if (!parser_next(parser)) {
1842 parseerror(parser, "error parsing parameter index");
1846 idx = parse_expression_leave(parser, true, false, false);
1850 if (parser->tok != ',') {
1851 if (parser->tok != ')') {
1853 parseerror(parser, "expected comma after parameter index");
1856 /* vararg piping: ...(start) */
1857 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1861 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1863 parseerror(parser, "expected typename for vararg");
1867 typevar = parse_typename(parser, NULL, NULL);
1873 if (parser->tok != ')') {
1875 ast_delete(typevar);
1876 parseerror(parser, "expected closing paren");
1880 if (funtype->expression.varparam &&
1881 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1885 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1886 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1887 compile_error(ast_ctx(typevar),
1888 "function was declared to take varargs of type `%s`, requested type is: %s",
1892 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1893 ast_type_adopt(out, typevar);
1894 ast_delete(typevar);
1898 static ast_expression* parse_vararg(parser_t *parser)
1900 bool old_noops = parser->lex->flags.noops;
1902 ast_expression *out;
1904 parser->lex->flags.noops = true;
1905 out = parse_vararg_do(parser);
1907 parser->lex->flags.noops = old_noops;
1911 /* not to be exposed */
1912 extern bool ftepp_predef_exists(const char *name);
1914 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1916 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1917 parser->tok == TOKEN_IDENT &&
1918 !strcmp(parser_tokval(parser), "_"))
1920 /* a translatable string */
1923 parser->lex->flags.noops = true;
1924 if (!parser_next(parser) || parser->tok != '(') {
1925 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1928 parser->lex->flags.noops = false;
1929 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1930 parseerror(parser, "expected a constant string in translatable-string extension");
1933 val = parser_const_string(parser, parser_tokval(parser), true);
1936 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1938 if (!parser_next(parser) || parser->tok != ')') {
1939 parseerror(parser, "expected closing paren after translatable string");
1944 else if (parser->tok == TOKEN_DOTS)
1947 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1948 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1951 va = parse_vararg(parser);
1954 vec_push(sy->out, syexp(parser_ctx(parser), va));
1957 else if (parser->tok == TOKEN_FLOATCONST) {
1959 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1962 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1965 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1967 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1970 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1973 else if (parser->tok == TOKEN_STRINGCONST) {
1975 val = parser_const_string(parser, parser_tokval(parser), false);
1978 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1981 else if (parser->tok == TOKEN_VECTORCONST) {
1983 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1986 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1989 else if (parser->tok == TOKEN_IDENT)
1991 const char *ctoken = parser_tokval(parser);
1992 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1993 ast_expression *var;
1994 /* a_vector.{x,y,z} */
1995 if (!vec_size(sy->ops) ||
1996 !vec_last(sy->ops).etype ||
1997 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1998 (prev >= intrinsic_debug_typestring &&
1999 prev <= intrinsic_debug_typestring))
2001 /* When adding more intrinsics, fix the above condition */
2004 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
2006 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
2008 var = parser_find_var(parser, parser_tokval(parser));
2010 var = parser_find_field(parser, parser_tokval(parser));
2012 if (!var && with_labels) {
2013 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
2015 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
2016 var = (ast_expression*)lbl;
2017 vec_push(parser->labels, lbl);
2020 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
2021 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
2024 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
2025 var = (ast_expression*)intrinsic_debug_typestring;
2027 /* now we try for the real intrinsic hashtable. If the string
2028 * begins with __builtin, we simply skip past it, otherwise we
2029 * use the identifier as is.
2031 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
2032 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
2036 char *correct = NULL;
2040 * sometimes people use preprocessing predefs without enabling them
2041 * i've done this thousands of times already myself. Lets check for
2042 * it in the predef table. And diagnose it better :)
2044 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
2045 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
2050 * TODO: determine the best score for the identifier: be it
2051 * a variable, a field.
2053 * We should also consider adding correction tables for
2054 * other things as well.
2056 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
2058 correct_init(&corr);
2060 for (i = 0; i < vec_size(parser->correct_variables); i++) {
2061 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
2062 if (strcmp(correct, parser_tokval(parser))) {
2069 correct_free(&corr);
2072 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
2077 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
2083 if (ast_istype(var, ast_value)) {
2084 ((ast_value*)var)->uses++;
2086 else if (ast_istype(var, ast_member)) {
2087 ast_member *mem = (ast_member*)var;
2088 if (ast_istype(mem->owner, ast_value))
2089 ((ast_value*)(mem->owner))->uses++;
2092 vec_push(sy->out, syexp(parser_ctx(parser), var));
2095 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2099 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2101 ast_expression *expr = NULL;
2104 bool wantop = false;
2105 /* only warn once about an assignment in a truth value because the current code
2106 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2108 bool warn_truthvalue = true;
2110 /* count the parens because an if starts with one, so the
2111 * end of a condition is an unmatched closing paren
2115 memset(&sy, 0, sizeof(sy));
2117 parser->lex->flags.noops = false;
2119 parser_reclassify_token(parser);
2123 if (parser->tok == TOKEN_TYPENAME) {
2124 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
2128 if (parser->tok == TOKEN_OPERATOR)
2130 /* classify the operator */
2131 const oper_info *op;
2132 const oper_info *olast = NULL;
2134 for (o = 0; o < operator_count; ++o) {
2135 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2136 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2137 !strcmp(parser_tokval(parser), operators[o].op))
2142 if (o == operator_count) {
2143 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2146 /* found an operator */
2149 /* when declaring variables, a comma starts a new variable */
2150 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2151 /* fixup the token */
2156 /* a colon without a pervious question mark cannot be a ternary */
2157 if (!ternaries && op->id == opid2(':','?')) {
2162 if (op->id == opid1(',')) {
2163 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2164 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2168 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2169 olast = &operators[vec_last(sy.ops).etype-1];
2171 #define IsAssignOp(x) (\
2172 (x) == opid1('=') || \
2173 (x) == opid2('+','=') || \
2174 (x) == opid2('-','=') || \
2175 (x) == opid2('*','=') || \
2176 (x) == opid2('/','=') || \
2177 (x) == opid2('%','=') || \
2178 (x) == opid2('&','=') || \
2179 (x) == opid2('|','=') || \
2180 (x) == opid3('&','~','=') \
2182 if (warn_truthvalue) {
2183 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2184 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2185 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2188 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2189 warn_truthvalue = false;
2194 (op->prec < olast->prec) ||
2195 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2197 if (!parser_sy_apply_operator(parser, &sy))
2199 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2200 olast = &operators[vec_last(sy.ops).etype-1];
2205 if (op->id == opid1('(')) {
2207 size_t sycount = vec_size(sy.out);
2208 /* we expected an operator, this is the function-call operator */
2209 vec_push(sy.paren, PAREN_FUNC);
2210 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2211 vec_push(sy.argc, 0);
2213 vec_push(sy.paren, PAREN_EXPR);
2214 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2217 } else if (op->id == opid1('[')) {
2219 parseerror(parser, "unexpected array subscript");
2222 vec_push(sy.paren, PAREN_INDEX);
2223 /* push both the operator and the paren, this makes life easier */
2224 vec_push(sy.ops, syop(parser_ctx(parser), op));
2225 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2227 } else if (op->id == opid2('?',':')) {
2228 vec_push(sy.ops, syop(parser_ctx(parser), op));
2229 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2232 vec_push(sy.paren, PAREN_TERNARY1);
2233 } else if (op->id == opid2(':','?')) {
2234 if (!vec_size(sy.paren)) {
2235 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2238 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2239 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2242 if (!parser_close_paren(parser, &sy))
2244 vec_push(sy.ops, syop(parser_ctx(parser), op));
2248 vec_push(sy.ops, syop(parser_ctx(parser), op));
2249 wantop = !!(op->flags & OP_SUFFIX);
2252 else if (parser->tok == ')') {
2253 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2254 if (!parser_sy_apply_operator(parser, &sy))
2257 if (!vec_size(sy.paren))
2260 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2261 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2264 if (!parser_close_paren(parser, &sy))
2267 /* must be a function call without parameters */
2268 if (vec_last(sy.paren) != PAREN_FUNC) {
2269 parseerror(parser, "closing paren in invalid position");
2272 if (!parser_close_paren(parser, &sy))
2277 else if (parser->tok == '(') {
2278 parseerror(parser, "internal error: '(' should be classified as operator");
2281 else if (parser->tok == '[') {
2282 parseerror(parser, "internal error: '[' should be classified as operator");
2285 else if (parser->tok == ']') {
2286 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2287 if (!parser_sy_apply_operator(parser, &sy))
2290 if (!vec_size(sy.paren))
2292 if (vec_last(sy.paren) != PAREN_INDEX) {
2293 parseerror(parser, "mismatched parentheses, unexpected ']'");
2296 if (!parser_close_paren(parser, &sy))
2301 if (!parse_sya_operand(parser, &sy, with_labels))
2304 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2305 vec_last(sy.argc)++;
2310 /* in this case we might want to allow constant string concatenation */
2311 bool concatenated = false;
2312 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2313 ast_expression *lexpr = vec_last(sy.out).out;
2314 if (ast_istype(lexpr, ast_value)) {
2315 ast_value *last = (ast_value*)lexpr;
2316 if (last->isimm == true && last->cvq == CV_CONST &&
2317 last->hasvalue && last->expression.vtype == TYPE_STRING)
2319 char *newstr = NULL;
2320 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2321 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2323 concatenated = true;
2327 if (!concatenated) {
2328 parseerror(parser, "expected operator or end of statement");
2333 if (!parser_next(parser)) {
2336 if (parser->tok == ';' ||
2337 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2338 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2344 while (vec_size(sy.ops)) {
2345 if (!parser_sy_apply_operator(parser, &sy))
2349 parser->lex->flags.noops = true;
2350 if (vec_size(sy.out) != 1) {
2351 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2354 expr = sy.out[0].out;
2357 if (vec_size(sy.paren)) {
2358 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2366 parser->lex->flags.noops = true;
2367 for (i = 0; i < vec_size(sy.out); ++i) {
2369 ast_unref(sy.out[i].out);
2378 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2380 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2383 if (parser->tok != ';') {
2384 parseerror(parser, "semicolon expected after expression");
2388 if (!parser_next(parser)) {
2395 static void parser_enterblock(parser_t *parser)
2397 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2398 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2399 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2400 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2401 vec_push(parser->_block_ctx, parser_ctx(parser));
2404 vec_push(parser->correct_variables, correct_trie_new());
2405 vec_push(parser->correct_variables_score, NULL);
2408 static bool parser_leaveblock(parser_t *parser)
2411 size_t locals, typedefs;
2413 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2414 parseerror(parser, "internal error: parser_leaveblock with no block");
2418 util_htdel(vec_last(parser->variables));
2419 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2421 vec_pop(parser->variables);
2422 vec_pop(parser->correct_variables);
2423 vec_pop(parser->correct_variables_score);
2424 if (!vec_size(parser->_blocklocals)) {
2425 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2429 locals = vec_last(parser->_blocklocals);
2430 vec_pop(parser->_blocklocals);
2431 while (vec_size(parser->_locals) != locals) {
2432 ast_expression *e = vec_last(parser->_locals);
2433 ast_value *v = (ast_value*)e;
2434 vec_pop(parser->_locals);
2435 if (ast_istype(e, ast_value) && !v->uses) {
2436 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2441 typedefs = vec_last(parser->_blocktypedefs);
2442 while (vec_size(parser->_typedefs) != typedefs) {
2443 ast_delete(vec_last(parser->_typedefs));
2444 vec_pop(parser->_typedefs);
2446 util_htdel(vec_last(parser->typedefs));
2447 vec_pop(parser->typedefs);
2449 vec_pop(parser->_block_ctx);
2454 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2456 vec_push(parser->_locals, e);
2457 util_htset(vec_last(parser->variables), name, (void*)e);
2461 vec_last(parser->correct_variables),
2462 &vec_last(parser->correct_variables_score),
2467 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2469 vec_push(parser->globals, e);
2470 util_htset(parser->htglobals, name, e);
2474 parser->correct_variables[0],
2475 &parser->correct_variables_score[0],
2480 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2484 ast_expression *prev;
2486 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2488 ast_type_to_string(cond, ty, sizeof(ty));
2489 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2492 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2495 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2498 parseerror(parser, "internal error: failed to process condition");
2503 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2505 /* vector types need to be cast to true booleans */
2506 ast_binary *bin = (ast_binary*)cond;
2507 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2509 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2511 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2514 parseerror(parser, "internal error: failed to process condition");
2521 unary = (ast_unary*)cond;
2522 /* ast_istype dereferences cond, should test here for safety */
2523 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2525 cond = unary->operand;
2526 unary->operand = NULL;
2529 unary = (ast_unary*)cond;
2533 parseerror(parser, "internal error: failed to process condition");
2535 if (ifnot) *_ifnot = !*_ifnot;
2539 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2542 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2545 lex_ctx_t ctx = parser_ctx(parser);
2547 (void)block; /* not touching */
2549 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2550 if (!parser_next(parser)) {
2551 parseerror(parser, "expected condition or 'not'");
2554 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2556 if (!parser_next(parser)) {
2557 parseerror(parser, "expected condition in parenthesis");
2561 if (parser->tok != '(') {
2562 parseerror(parser, "expected 'if' condition in parenthesis");
2565 /* parse into the expression */
2566 if (!parser_next(parser)) {
2567 parseerror(parser, "expected 'if' condition after opening paren");
2570 /* parse the condition */
2571 cond = parse_expression_leave(parser, false, true, false);
2575 if (parser->tok != ')') {
2576 parseerror(parser, "expected closing paren after 'if' condition");
2580 /* parse into the 'then' branch */
2581 if (!parser_next(parser)) {
2582 parseerror(parser, "expected statement for on-true branch of 'if'");
2586 if (!parse_statement_or_block(parser, &ontrue)) {
2591 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2592 /* check for an else */
2593 if (!strcmp(parser_tokval(parser), "else")) {
2594 /* parse into the 'else' branch */
2595 if (!parser_next(parser)) {
2596 parseerror(parser, "expected on-false branch after 'else'");
2601 if (!parse_statement_or_block(parser, &onfalse)) {
2608 cond = process_condition(parser, cond, &ifnot);
2610 if (ontrue) ast_delete(ontrue);
2611 if (onfalse) ast_delete(onfalse);
2616 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2618 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2619 *out = (ast_expression*)ifthen;
2623 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2624 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2629 /* skip the 'while' and get the body */
2630 if (!parser_next(parser)) {
2631 if (OPTS_FLAG(LOOP_LABELS))
2632 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2634 parseerror(parser, "expected 'while' condition in parenthesis");
2638 if (parser->tok == ':') {
2639 if (!OPTS_FLAG(LOOP_LABELS))
2640 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2641 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2642 parseerror(parser, "expected loop label");
2645 label = util_strdup(parser_tokval(parser));
2646 if (!parser_next(parser)) {
2648 parseerror(parser, "expected 'while' condition in parenthesis");
2653 if (parser->tok != '(') {
2654 parseerror(parser, "expected 'while' condition in parenthesis");
2658 vec_push(parser->breaks, label);
2659 vec_push(parser->continues, label);
2661 rv = parse_while_go(parser, block, out);
2664 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2665 parseerror(parser, "internal error: label stack corrupted");
2671 vec_pop(parser->breaks);
2672 vec_pop(parser->continues);
2677 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2680 ast_expression *cond, *ontrue;
2684 lex_ctx_t ctx = parser_ctx(parser);
2686 (void)block; /* not touching */
2688 /* parse into the expression */
2689 if (!parser_next(parser)) {
2690 parseerror(parser, "expected 'while' condition after opening paren");
2693 /* parse the condition */
2694 cond = parse_expression_leave(parser, false, true, false);
2698 if (parser->tok != ')') {
2699 parseerror(parser, "expected closing paren after 'while' condition");
2703 /* parse into the 'then' branch */
2704 if (!parser_next(parser)) {
2705 parseerror(parser, "expected while-loop body");
2709 if (!parse_statement_or_block(parser, &ontrue)) {
2714 cond = process_condition(parser, cond, &ifnot);
2719 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2720 *out = (ast_expression*)aloop;
2724 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2725 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2730 /* skip the 'do' and get the body */
2731 if (!parser_next(parser)) {
2732 if (OPTS_FLAG(LOOP_LABELS))
2733 parseerror(parser, "expected loop label or body");
2735 parseerror(parser, "expected loop body");
2739 if (parser->tok == ':') {
2740 if (!OPTS_FLAG(LOOP_LABELS))
2741 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2742 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2743 parseerror(parser, "expected loop label");
2746 label = util_strdup(parser_tokval(parser));
2747 if (!parser_next(parser)) {
2749 parseerror(parser, "expected loop body");
2754 vec_push(parser->breaks, label);
2755 vec_push(parser->continues, label);
2757 rv = parse_dowhile_go(parser, block, out);
2760 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2761 parseerror(parser, "internal error: label stack corrupted");
2764 * Test for NULL otherwise ast_delete dereferences null pointer
2772 vec_pop(parser->breaks);
2773 vec_pop(parser->continues);
2778 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2781 ast_expression *cond, *ontrue;
2785 lex_ctx_t ctx = parser_ctx(parser);
2787 (void)block; /* not touching */
2789 if (!parse_statement_or_block(parser, &ontrue))
2792 /* expect the "while" */
2793 if (parser->tok != TOKEN_KEYWORD ||
2794 strcmp(parser_tokval(parser), "while"))
2796 parseerror(parser, "expected 'while' and condition");
2801 /* skip the 'while' and check for opening paren */
2802 if (!parser_next(parser) || parser->tok != '(') {
2803 parseerror(parser, "expected 'while' condition in parenthesis");
2807 /* parse into the expression */
2808 if (!parser_next(parser)) {
2809 parseerror(parser, "expected 'while' condition after opening paren");
2813 /* parse the condition */
2814 cond = parse_expression_leave(parser, false, true, false);
2818 if (parser->tok != ')') {
2819 parseerror(parser, "expected closing paren after 'while' condition");
2825 if (!parser_next(parser) || parser->tok != ';') {
2826 parseerror(parser, "expected semicolon after condition");
2832 if (!parser_next(parser)) {
2833 parseerror(parser, "parse error");
2839 cond = process_condition(parser, cond, &ifnot);
2844 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2845 *out = (ast_expression*)aloop;
2849 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2850 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2855 /* skip the 'for' and check for opening paren */
2856 if (!parser_next(parser)) {
2857 if (OPTS_FLAG(LOOP_LABELS))
2858 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2860 parseerror(parser, "expected 'for' expressions in parenthesis");
2864 if (parser->tok == ':') {
2865 if (!OPTS_FLAG(LOOP_LABELS))
2866 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2867 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2868 parseerror(parser, "expected loop label");
2871 label = util_strdup(parser_tokval(parser));
2872 if (!parser_next(parser)) {
2874 parseerror(parser, "expected 'for' expressions in parenthesis");
2879 if (parser->tok != '(') {
2880 parseerror(parser, "expected 'for' expressions in parenthesis");
2884 vec_push(parser->breaks, label);
2885 vec_push(parser->continues, label);
2887 rv = parse_for_go(parser, block, out);
2890 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2891 parseerror(parser, "internal error: label stack corrupted");
2897 vec_pop(parser->breaks);
2898 vec_pop(parser->continues);
2902 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2905 ast_expression *initexpr, *cond, *increment, *ontrue;
2910 lex_ctx_t ctx = parser_ctx(parser);
2912 parser_enterblock(parser);
2919 /* parse into the expression */
2920 if (!parser_next(parser)) {
2921 parseerror(parser, "expected 'for' initializer after opening paren");
2926 if (parser->tok == TOKEN_IDENT)
2927 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2929 if (typevar || parser->tok == TOKEN_TYPENAME) {
2931 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2932 if (parsewarning(parser, WARN_EXTENSIONS,
2933 "current standard does not allow variable declarations in for-loop initializers"))
2937 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2940 else if (parser->tok != ';')
2942 initexpr = parse_expression_leave(parser, false, false, false);
2947 /* move on to condition */
2948 if (parser->tok != ';') {
2949 parseerror(parser, "expected semicolon after for-loop initializer");
2952 if (!parser_next(parser)) {
2953 parseerror(parser, "expected for-loop condition");
2957 /* parse the condition */
2958 if (parser->tok != ';') {
2959 cond = parse_expression_leave(parser, false, true, false);
2964 /* move on to incrementor */
2965 if (parser->tok != ';') {
2966 parseerror(parser, "expected semicolon after for-loop initializer");
2969 if (!parser_next(parser)) {
2970 parseerror(parser, "expected for-loop condition");
2974 /* parse the incrementor */
2975 if (parser->tok != ')') {
2976 lex_ctx_t condctx = parser_ctx(parser);
2977 increment = parse_expression_leave(parser, false, false, false);
2980 if (!ast_side_effects(increment)) {
2981 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2987 if (parser->tok != ')') {
2988 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2991 /* parse into the 'then' branch */
2992 if (!parser_next(parser)) {
2993 parseerror(parser, "expected for-loop body");
2996 if (!parse_statement_or_block(parser, &ontrue))
3000 cond = process_condition(parser, cond, &ifnot);
3004 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
3005 *out = (ast_expression*)aloop;
3007 if (!parser_leaveblock(parser)) {
3013 if (initexpr) ast_unref(initexpr);
3014 if (cond) ast_unref(cond);
3015 if (increment) ast_unref(increment);
3016 (void)!parser_leaveblock(parser);
3020 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
3022 ast_expression *exp = NULL;
3023 ast_expression *var = NULL;
3024 ast_return *ret = NULL;
3025 ast_value *retval = parser->function->return_value;
3026 ast_value *expected = parser->function->vtype;
3028 lex_ctx_t ctx = parser_ctx(parser);
3030 (void)block; /* not touching */
3032 if (!parser_next(parser)) {
3033 parseerror(parser, "expected return expression");
3037 /* return assignments */
3038 if (parser->tok == '=') {
3039 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
3040 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
3044 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
3046 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
3047 parseerror(parser, "invalid return type: `%s'", ty1);
3051 if (!parser_next(parser)) {
3052 parseerror(parser, "expected return assignment expression");
3056 if (!(exp = parse_expression_leave(parser, false, false, false)))
3059 /* prepare the return value */
3061 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
3062 ast_type_adopt(retval, expected->expression.next);
3063 parser->function->return_value = retval;
3066 if (!ast_compare_type(exp, (ast_expression*)retval)) {
3067 char ty1[1024], ty2[1024];
3068 ast_type_to_string(exp, ty1, sizeof(ty1));
3069 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
3070 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
3073 /* store to 'return' local variable */
3074 var = (ast_expression*)ast_store_new(
3076 type_store_instr[expected->expression.next->vtype],
3077 (ast_expression*)retval, exp);
3084 if (parser->tok != ';')
3085 parseerror(parser, "missing semicolon after return assignment");
3086 else if (!parser_next(parser))
3087 parseerror(parser, "parse error after return assignment");
3093 if (parser->tok != ';') {
3094 exp = parse_expression(parser, false, false);
3098 if (exp->vtype != TYPE_NIL &&
3099 exp->vtype != ((ast_expression*)expected)->next->vtype)
3101 parseerror(parser, "return with invalid expression");
3104 ret = ast_return_new(ctx, exp);
3110 if (!parser_next(parser))
3111 parseerror(parser, "parse error");
3113 if (!retval && expected->expression.next->vtype != TYPE_VOID)
3115 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3117 ret = ast_return_new(ctx, (ast_expression*)retval);
3119 *out = (ast_expression*)ret;
3123 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3126 unsigned int levels = 0;
3127 lex_ctx_t ctx = parser_ctx(parser);
3128 const char **loops = (is_continue ? parser->continues : parser->breaks);
3130 (void)block; /* not touching */
3131 if (!parser_next(parser)) {
3132 parseerror(parser, "expected semicolon or loop label");
3136 if (!vec_size(loops)) {
3138 parseerror(parser, "`continue` can only be used inside loops");
3140 parseerror(parser, "`break` can only be used inside loops or switches");
3143 if (parser->tok == TOKEN_IDENT) {
3144 if (!OPTS_FLAG(LOOP_LABELS))
3145 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3146 i = vec_size(loops);
3148 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3151 parseerror(parser, "no such loop to %s: `%s`",
3152 (is_continue ? "continue" : "break out of"),
3153 parser_tokval(parser));
3158 if (!parser_next(parser)) {
3159 parseerror(parser, "expected semicolon");
3164 if (parser->tok != ';') {
3165 parseerror(parser, "expected semicolon");
3169 if (!parser_next(parser))
3170 parseerror(parser, "parse error");
3172 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3176 /* returns true when it was a variable qualifier, false otherwise!
3177 * on error, cvq is set to CV_WRONG
3179 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3181 bool had_const = false;
3182 bool had_var = false;
3183 bool had_noref = false;
3184 bool had_attrib = false;
3185 bool had_static = false;
3190 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3192 /* parse an attribute */
3193 if (!parser_next(parser)) {
3194 parseerror(parser, "expected attribute after `[[`");
3198 if (!strcmp(parser_tokval(parser), "noreturn")) {
3199 flags |= AST_FLAG_NORETURN;
3200 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3201 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3206 else if (!strcmp(parser_tokval(parser), "noref")) {
3208 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3209 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3214 else if (!strcmp(parser_tokval(parser), "inline")) {
3215 flags |= AST_FLAG_INLINE;
3216 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3217 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3222 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3223 flags |= AST_FLAG_ALIAS;
3226 if (!parser_next(parser)) {
3227 parseerror(parser, "parse error in attribute");
3231 if (parser->tok == '(') {
3232 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3233 parseerror(parser, "`alias` attribute missing parameter");
3237 *message = util_strdup(parser_tokval(parser));
3239 if (!parser_next(parser)) {
3240 parseerror(parser, "parse error in attribute");
3244 if (parser->tok != ')') {
3245 parseerror(parser, "`alias` attribute expected `)` after parameter");
3249 if (!parser_next(parser)) {
3250 parseerror(parser, "parse error in attribute");
3255 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3256 parseerror(parser, "`alias` attribute expected `]]`");
3260 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3261 flags |= AST_FLAG_DEPRECATED;
3264 if (!parser_next(parser)) {
3265 parseerror(parser, "parse error in attribute");
3269 if (parser->tok == '(') {
3270 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3271 parseerror(parser, "`deprecated` attribute missing parameter");
3275 *message = util_strdup(parser_tokval(parser));
3277 if (!parser_next(parser)) {
3278 parseerror(parser, "parse error in attribute");
3282 if(parser->tok != ')') {
3283 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3287 if (!parser_next(parser)) {
3288 parseerror(parser, "parse error in attribute");
3293 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3294 parseerror(parser, "`deprecated` attribute expected `]]`");
3297 if (*message) mem_d(*message);
3305 /* Skip tokens until we hit a ]] */
3306 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3307 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3308 if (!parser_next(parser)) {
3309 parseerror(parser, "error inside attribute");
3316 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3318 else if (!strcmp(parser_tokval(parser), "const"))
3320 else if (!strcmp(parser_tokval(parser), "var"))
3322 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3324 else if (!strcmp(parser_tokval(parser), "noref"))
3326 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3331 if (!parser_next(parser))
3341 *is_static = had_static;
3345 parseerror(parser, "parse error after variable qualifier");
3350 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3351 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3356 /* skip the 'while' and get the body */
3357 if (!parser_next(parser)) {
3358 if (OPTS_FLAG(LOOP_LABELS))
3359 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3361 parseerror(parser, "expected 'switch' operand in parenthesis");
3365 if (parser->tok == ':') {
3366 if (!OPTS_FLAG(LOOP_LABELS))
3367 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3368 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3369 parseerror(parser, "expected loop label");
3372 label = util_strdup(parser_tokval(parser));
3373 if (!parser_next(parser)) {
3375 parseerror(parser, "expected 'switch' operand in parenthesis");
3380 if (parser->tok != '(') {
3381 parseerror(parser, "expected 'switch' operand in parenthesis");
3385 vec_push(parser->breaks, label);
3387 rv = parse_switch_go(parser, block, out);
3390 if (vec_last(parser->breaks) != label) {
3391 parseerror(parser, "internal error: label stack corrupted");
3397 vec_pop(parser->breaks);
3402 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3404 ast_expression *operand;
3407 ast_switch *switchnode;
3408 ast_switch_case swcase;
3411 bool noref, is_static;
3412 uint32_t qflags = 0;
3414 lex_ctx_t ctx = parser_ctx(parser);
3416 (void)block; /* not touching */
3419 /* parse into the expression */
3420 if (!parser_next(parser)) {
3421 parseerror(parser, "expected switch operand");
3424 /* parse the operand */
3425 operand = parse_expression_leave(parser, false, false, false);
3429 switchnode = ast_switch_new(ctx, operand);
3432 if (parser->tok != ')') {
3433 ast_delete(switchnode);
3434 parseerror(parser, "expected closing paren after 'switch' operand");
3438 /* parse over the opening paren */
3439 if (!parser_next(parser) || parser->tok != '{') {
3440 ast_delete(switchnode);
3441 parseerror(parser, "expected list of cases");
3445 if (!parser_next(parser)) {
3446 ast_delete(switchnode);
3447 parseerror(parser, "expected 'case' or 'default'");
3451 /* new block; allow some variables to be declared here */
3452 parser_enterblock(parser);
3455 if (parser->tok == TOKEN_IDENT)
3456 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3457 if (typevar || parser->tok == TOKEN_TYPENAME) {
3458 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3459 ast_delete(switchnode);
3464 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3466 if (cvq == CV_WRONG) {
3467 ast_delete(switchnode);
3470 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3471 ast_delete(switchnode);
3480 while (parser->tok != '}') {
3481 ast_block *caseblock;
3483 if (!strcmp(parser_tokval(parser), "case")) {
3484 if (!parser_next(parser)) {
3485 ast_delete(switchnode);
3486 parseerror(parser, "expected expression for case");
3489 swcase.value = parse_expression_leave(parser, false, false, false);
3490 if (!swcase.value) {
3491 ast_delete(switchnode);
3492 parseerror(parser, "expected expression for case");
3495 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3496 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3497 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3503 else if (!strcmp(parser_tokval(parser), "default")) {
3504 swcase.value = NULL;
3505 if (!parser_next(parser)) {
3506 ast_delete(switchnode);
3507 parseerror(parser, "expected colon");
3512 ast_delete(switchnode);
3513 parseerror(parser, "expected 'case' or 'default'");
3517 /* Now the colon and body */
3518 if (parser->tok != ':') {
3519 if (swcase.value) ast_unref(swcase.value);
3520 ast_delete(switchnode);
3521 parseerror(parser, "expected colon");
3525 if (!parser_next(parser)) {
3526 if (swcase.value) ast_unref(swcase.value);
3527 ast_delete(switchnode);
3528 parseerror(parser, "expected statements or case");
3531 caseblock = ast_block_new(parser_ctx(parser));
3533 if (swcase.value) ast_unref(swcase.value);
3534 ast_delete(switchnode);
3537 swcase.code = (ast_expression*)caseblock;
3538 vec_push(switchnode->cases, swcase);
3540 ast_expression *expr;
3541 if (parser->tok == '}')
3543 if (parser->tok == TOKEN_KEYWORD) {
3544 if (!strcmp(parser_tokval(parser), "case") ||
3545 !strcmp(parser_tokval(parser), "default"))
3550 if (!parse_statement(parser, caseblock, &expr, true)) {
3551 ast_delete(switchnode);
3556 if (!ast_block_add_expr(caseblock, expr)) {
3557 ast_delete(switchnode);
3563 parser_leaveblock(parser);
3566 if (parser->tok != '}') {
3567 ast_delete(switchnode);
3568 parseerror(parser, "expected closing paren of case list");
3571 if (!parser_next(parser)) {
3572 ast_delete(switchnode);
3573 parseerror(parser, "parse error after switch");
3576 *out = (ast_expression*)switchnode;
3580 /* parse computed goto sides */
3581 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3582 ast_expression *on_true;
3583 ast_expression *on_false;
3584 ast_expression *cond;
3589 if (ast_istype(*side, ast_ternary)) {
3590 ast_ternary *tern = (ast_ternary*)*side;
3591 on_true = parse_goto_computed(parser, &tern->on_true);
3592 on_false = parse_goto_computed(parser, &tern->on_false);
3594 if (!on_true || !on_false) {
3595 parseerror(parser, "expected label or expression in ternary");
3596 if (on_true) ast_unref(on_true);
3597 if (on_false) ast_unref(on_false);
3605 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3606 } else if (ast_istype(*side, ast_label)) {
3607 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3608 ast_goto_set_label(gt, ((ast_label*)*side));
3610 return (ast_expression*)gt;
3615 static bool parse_goto(parser_t *parser, ast_expression **out)
3617 ast_goto *gt = NULL;
3618 ast_expression *lbl;
3620 if (!parser_next(parser))
3623 if (parser->tok != TOKEN_IDENT) {
3624 ast_expression *expression;
3626 /* could be an expression i.e computed goto :-) */
3627 if (parser->tok != '(') {
3628 parseerror(parser, "expected label name after `goto`");
3632 /* failed to parse expression for goto */
3633 if (!(expression = parse_expression(parser, false, true)) ||
3634 !(*out = parse_goto_computed(parser, &expression))) {
3635 parseerror(parser, "invalid goto expression");
3637 ast_unref(expression);
3644 /* not computed goto */
3645 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3646 lbl = parser_find_label(parser, gt->name);
3648 if (!ast_istype(lbl, ast_label)) {
3649 parseerror(parser, "internal error: label is not an ast_label");
3653 ast_goto_set_label(gt, (ast_label*)lbl);
3656 vec_push(parser->gotos, gt);
3658 if (!parser_next(parser) || parser->tok != ';') {
3659 parseerror(parser, "semicolon expected after goto label");
3662 if (!parser_next(parser)) {
3663 parseerror(parser, "parse error after goto");
3667 *out = (ast_expression*)gt;
3671 static bool parse_skipwhite(parser_t *parser)
3674 if (!parser_next(parser))
3676 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3677 return parser->tok < TOKEN_ERROR;
3680 static bool parse_eol(parser_t *parser)
3682 if (!parse_skipwhite(parser))
3684 return parser->tok == TOKEN_EOL;
3687 static bool parse_pragma_do(parser_t *parser)
3689 if (!parser_next(parser) ||
3690 parser->tok != TOKEN_IDENT ||
3691 strcmp(parser_tokval(parser), "pragma"))
3693 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3696 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3697 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3701 if (!strcmp(parser_tokval(parser), "noref")) {
3702 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3703 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3706 parser->noref = !!parser_token(parser)->constval.i;
3707 if (!parse_eol(parser)) {
3708 parseerror(parser, "parse error after `noref` pragma");
3714 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3721 static bool parse_pragma(parser_t *parser)
3724 parser->lex->flags.preprocessing = true;
3725 parser->lex->flags.mergelines = true;
3726 rv = parse_pragma_do(parser);
3727 if (parser->tok != TOKEN_EOL) {
3728 parseerror(parser, "junk after pragma");
3731 parser->lex->flags.preprocessing = false;
3732 parser->lex->flags.mergelines = false;
3733 if (!parser_next(parser)) {
3734 parseerror(parser, "parse error after pragma");
3740 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3742 bool noref, is_static;
3744 uint32_t qflags = 0;
3745 ast_value *typevar = NULL;
3746 char *vstring = NULL;
3750 if (parser->tok == TOKEN_IDENT)
3751 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3753 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3755 /* local variable */
3757 parseerror(parser, "cannot declare a variable from here");
3760 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3761 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3764 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3768 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3770 if (cvq == CV_WRONG)
3772 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3774 else if (parser->tok == TOKEN_KEYWORD)
3776 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3781 if (!parser_next(parser)) {
3782 parseerror(parser, "parse error after __builtin_debug_printtype");
3786 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3788 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3789 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3790 if (!parser_next(parser)) {
3791 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3797 if (!parse_statement(parser, block, out, allow_cases))
3800 con_out("__builtin_debug_printtype: got no output node\n");
3803 ast_type_to_string(*out, ty, sizeof(ty));
3804 con_out("__builtin_debug_printtype: `%s`\n", ty);
3809 else if (!strcmp(parser_tokval(parser), "return"))
3811 return parse_return(parser, block, out);
3813 else if (!strcmp(parser_tokval(parser), "if"))
3815 return parse_if(parser, block, out);
3817 else if (!strcmp(parser_tokval(parser), "while"))
3819 return parse_while(parser, block, out);
3821 else if (!strcmp(parser_tokval(parser), "do"))
3823 return parse_dowhile(parser, block, out);
3825 else if (!strcmp(parser_tokval(parser), "for"))
3827 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3828 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3831 return parse_for(parser, block, out);
3833 else if (!strcmp(parser_tokval(parser), "break"))
3835 return parse_break_continue(parser, block, out, false);
3837 else if (!strcmp(parser_tokval(parser), "continue"))
3839 return parse_break_continue(parser, block, out, true);
3841 else if (!strcmp(parser_tokval(parser), "switch"))
3843 return parse_switch(parser, block, out);
3845 else if (!strcmp(parser_tokval(parser), "case") ||
3846 !strcmp(parser_tokval(parser), "default"))
3849 parseerror(parser, "unexpected 'case' label");
3854 else if (!strcmp(parser_tokval(parser), "goto"))
3856 return parse_goto(parser, out);
3858 else if (!strcmp(parser_tokval(parser), "typedef"))
3860 if (!parser_next(parser)) {
3861 parseerror(parser, "expected type definition after 'typedef'");
3864 return parse_typedef(parser);
3866 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3869 else if (parser->tok == '{')
3872 inner = parse_block(parser);
3875 *out = (ast_expression*)inner;
3878 else if (parser->tok == ':')
3882 if (!parser_next(parser)) {
3883 parseerror(parser, "expected label name");
3886 if (parser->tok != TOKEN_IDENT) {
3887 parseerror(parser, "label must be an identifier");
3890 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3892 if (!label->undefined) {
3893 parseerror(parser, "label `%s` already defined", label->name);
3896 label->undefined = false;
3899 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3900 vec_push(parser->labels, label);
3902 *out = (ast_expression*)label;
3903 if (!parser_next(parser)) {
3904 parseerror(parser, "parse error after label");
3907 for (i = 0; i < vec_size(parser->gotos); ++i) {
3908 if (!strcmp(parser->gotos[i]->name, label->name)) {
3909 ast_goto_set_label(parser->gotos[i], label);
3910 vec_remove(parser->gotos, i, 1);
3916 else if (parser->tok == ';')
3918 if (!parser_next(parser)) {
3919 parseerror(parser, "parse error after empty statement");
3926 lex_ctx_t ctx = parser_ctx(parser);
3927 ast_expression *exp = parse_expression(parser, false, false);
3931 if (!ast_side_effects(exp)) {
3932 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3939 static bool parse_enum(parser_t *parser)
3942 bool reverse = false;
3944 ast_value **values = NULL;
3945 ast_value *var = NULL;
3948 ast_expression *old;
3950 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3951 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3955 /* enumeration attributes (can add more later) */
3956 if (parser->tok == ':') {
3957 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3958 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3963 if (!strcmp(parser_tokval(parser), "flag")) {
3967 else if (!strcmp(parser_tokval(parser), "reverse")) {
3971 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3975 if (!parser_next(parser) || parser->tok != '{') {
3976 parseerror(parser, "expected `{` after enum attribute ");
3982 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3983 if (parser->tok == '}') {
3984 /* allow an empty enum */
3987 parseerror(parser, "expected identifier or `}`");
3991 old = parser_find_field(parser, parser_tokval(parser));
3993 old = parser_find_global(parser, parser_tokval(parser));
3995 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3996 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
4000 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
4001 vec_push(values, var);
4002 var->cvq = CV_CONST;
4003 var->hasvalue = true;
4005 /* for flagged enumerations increment in POTs of TWO */
4006 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
4007 parser_addglobal(parser, var->name, (ast_expression*)var);
4009 if (!parser_next(parser)) {
4010 parseerror(parser, "expected `=`, `}` or comma after identifier");
4014 if (parser->tok == ',')
4016 if (parser->tok == '}')
4018 if (parser->tok != '=') {
4019 parseerror(parser, "expected `=`, `}` or comma after identifier");
4023 if (!parser_next(parser)) {
4024 parseerror(parser, "expected expression after `=`");
4028 /* We got a value! */
4029 old = parse_expression_leave(parser, true, false, false);
4030 asvalue = (ast_value*)old;
4031 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4032 compile_error(ast_ctx(var), "constant value or expression expected");
4035 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4037 if (parser->tok == '}')
4039 if (parser->tok != ',') {
4040 parseerror(parser, "expected `}` or comma after expression");
4045 /* patch them all (for reversed attribute) */
4048 for (i = 0; i < vec_size(values); i++)
4049 values[i]->constval.vfloat = vec_size(values) - i - 1;
4052 if (parser->tok != '}') {
4053 parseerror(parser, "internal error: breaking without `}`");
4057 if (!parser_next(parser) || parser->tok != ';') {
4058 parseerror(parser, "expected semicolon after enumeration");
4062 if (!parser_next(parser)) {
4063 parseerror(parser, "parse error after enumeration");
4075 static bool parse_block_into(parser_t *parser, ast_block *block)
4079 parser_enterblock(parser);
4081 if (!parser_next(parser)) { /* skip the '{' */
4082 parseerror(parser, "expected function body");
4086 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4088 ast_expression *expr = NULL;
4089 if (parser->tok == '}')
4092 if (!parse_statement(parser, block, &expr, false)) {
4093 /* parseerror(parser, "parse error"); */
4099 if (!ast_block_add_expr(block, expr)) {
4106 if (parser->tok != '}') {
4109 (void)parser_next(parser);
4113 if (!parser_leaveblock(parser))
4115 return retval && !!block;
4118 static ast_block* parse_block(parser_t *parser)
4121 block = ast_block_new(parser_ctx(parser));
4124 if (!parse_block_into(parser, block)) {
4125 ast_block_delete(block);
4131 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4133 if (parser->tok == '{') {
4134 *out = (ast_expression*)parse_block(parser);
4137 return parse_statement(parser, NULL, out, false);
4140 static bool create_vector_members(ast_value *var, ast_member **me)
4143 size_t len = strlen(var->name);
4145 for (i = 0; i < 3; ++i) {
4146 char *name = (char*)mem_a(len+3);
4147 memcpy(name, var->name, len);
4149 name[len+1] = 'x'+i;
4151 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4160 do { ast_member_delete(me[--i]); } while(i);
4164 static bool parse_function_body(parser_t *parser, ast_value *var)
4166 ast_block *block = NULL;
4171 ast_expression *framenum = NULL;
4172 ast_expression *nextthink = NULL;
4173 /* None of the following have to be deleted */
4174 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4175 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4176 bool has_frame_think;
4180 has_frame_think = false;
4181 old = parser->function;
4183 if (var->expression.flags & AST_FLAG_ALIAS) {
4184 parseerror(parser, "function aliases cannot have bodies");
4188 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4189 parseerror(parser, "gotos/labels leaking");
4193 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4194 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4195 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4201 if (parser->tok == '[') {
4202 /* got a frame definition: [ framenum, nextthink ]
4203 * this translates to:
4204 * self.frame = framenum;
4205 * self.nextthink = time + 0.1;
4206 * self.think = nextthink;
4210 fld_think = parser_find_field(parser, "think");
4211 fld_nextthink = parser_find_field(parser, "nextthink");
4212 fld_frame = parser_find_field(parser, "frame");
4213 if (!fld_think || !fld_nextthink || !fld_frame) {
4214 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4215 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4218 gbl_time = parser_find_global(parser, "time");
4219 gbl_self = parser_find_global(parser, "self");
4220 if (!gbl_time || !gbl_self) {
4221 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4222 parseerror(parser, "please declare the following globals: `time`, `self`");
4226 if (!parser_next(parser))
4229 framenum = parse_expression_leave(parser, true, false, false);
4231 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4234 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4235 ast_unref(framenum);
4236 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4240 if (parser->tok != ',') {
4241 ast_unref(framenum);
4242 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4243 parseerror(parser, "Got a %i\n", parser->tok);
4247 if (!parser_next(parser)) {
4248 ast_unref(framenum);
4252 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4254 /* qc allows the use of not-yet-declared functions here
4255 * - this automatically creates a prototype */
4256 ast_value *thinkfunc;
4257 ast_expression *functype = fld_think->next;
4259 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4260 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4261 ast_unref(framenum);
4262 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4265 ast_type_adopt(thinkfunc, functype);
4267 if (!parser_next(parser)) {
4268 ast_unref(framenum);
4269 ast_delete(thinkfunc);
4273 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4275 nextthink = (ast_expression*)thinkfunc;
4278 nextthink = parse_expression_leave(parser, true, false, false);
4280 ast_unref(framenum);
4281 parseerror(parser, "expected a think-function in [frame,think] notation");
4286 if (!ast_istype(nextthink, ast_value)) {
4287 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4291 if (retval && parser->tok != ']') {
4292 parseerror(parser, "expected closing `]` for [frame,think] notation");
4296 if (retval && !parser_next(parser)) {
4300 if (retval && parser->tok != '{') {
4301 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4306 ast_unref(nextthink);
4307 ast_unref(framenum);
4311 has_frame_think = true;
4314 block = ast_block_new(parser_ctx(parser));
4316 parseerror(parser, "failed to allocate block");
4317 if (has_frame_think) {
4318 ast_unref(nextthink);
4319 ast_unref(framenum);
4324 if (has_frame_think) {
4326 ast_expression *self_frame;
4327 ast_expression *self_nextthink;
4328 ast_expression *self_think;
4329 ast_expression *time_plus_1;
4330 ast_store *store_frame;
4331 ast_store *store_nextthink;
4332 ast_store *store_think;
4334 ctx = parser_ctx(parser);
4335 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4336 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4337 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4339 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4340 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4342 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4343 if (self_frame) ast_delete(self_frame);
4344 if (self_nextthink) ast_delete(self_nextthink);
4345 if (self_think) ast_delete(self_think);
4346 if (time_plus_1) ast_delete(time_plus_1);
4352 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4353 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4354 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4357 ast_delete(self_frame);
4360 if (!store_nextthink) {
4361 ast_delete(self_nextthink);
4365 ast_delete(self_think);
4369 if (store_frame) ast_delete(store_frame);
4370 if (store_nextthink) ast_delete(store_nextthink);
4371 if (store_think) ast_delete(store_think);
4374 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4375 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4376 !ast_block_add_expr(block, (ast_expression*)store_think))
4383 parseerror(parser, "failed to generate code for [frame,think]");
4384 ast_unref(nextthink);
4385 ast_unref(framenum);
4391 if (var->hasvalue) {
4392 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4393 ast_block_delete(block);
4397 func = ast_function_new(ast_ctx(var), var->name, var);
4399 parseerror(parser, "failed to allocate function for `%s`", var->name);
4400 ast_block_delete(block);
4403 vec_push(parser->functions, func);
4405 parser_enterblock(parser);
4407 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4409 ast_value *param = var->expression.params[parami];
4412 if (param->expression.vtype != TYPE_VECTOR &&
4413 (param->expression.vtype != TYPE_FIELD ||
4414 param->expression.next->vtype != TYPE_VECTOR))
4419 if (!create_vector_members(param, me)) {
4420 ast_block_delete(block);
4424 for (e = 0; e < 3; ++e) {
4425 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4426 ast_block_collect(block, (ast_expression*)me[e]);
4430 if (var->argcounter) {
4431 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4432 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4436 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4438 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4439 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4440 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4441 varargs->expression.count = 0;
4442 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4443 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4444 ast_delete(varargs);
4445 ast_block_delete(block);
4448 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4449 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4450 ast_delete(varargs);
4451 ast_block_delete(block);
4454 func->varargs = varargs;
4456 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4459 parser->function = func;
4460 if (!parse_block_into(parser, block)) {
4461 ast_block_delete(block);
4465 vec_push(func->blocks, block);
4468 parser->function = old;
4469 if (!parser_leaveblock(parser))
4471 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4472 parseerror(parser, "internal error: local scopes left");
4476 if (parser->tok == ';')
4477 return parser_next(parser);
4478 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4479 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4483 (void)!parser_leaveblock(parser);
4484 vec_pop(parser->functions);
4485 ast_function_delete(func);
4486 var->constval.vfunc = NULL;
4489 parser->function = old;
4493 static ast_expression *array_accessor_split(
4498 ast_expression *left,
4499 ast_expression *right
4505 lex_ctx_t ctx = ast_ctx(array);
4507 if (!left || !right) {
4508 if (left) ast_delete(left);
4509 if (right) ast_delete(right);
4513 cmp = ast_binary_new(ctx, INSTR_LT,
4514 (ast_expression*)index,
4515 (ast_expression*)parser_const_float(parser, middle));
4519 parseerror(parser, "internal error: failed to create comparison for array setter");
4523 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4525 ast_delete(cmp); /* will delete left and right */
4526 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4530 return (ast_expression*)ifthen;
4533 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4535 lex_ctx_t ctx = ast_ctx(array);
4537 if (from+1 == afterend) {
4538 /* set this value */
4541 ast_array_index *subscript;
4543 int assignop = type_store_instr[value->expression.vtype];
4545 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4546 assignop = INSTR_STORE_V;
4548 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4552 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4554 ast_delete(subscript);
4558 block = ast_block_new(ctx);
4564 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4569 ret = ast_return_new(ctx, NULL);
4575 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4580 return (ast_expression*)block;
4582 ast_expression *left, *right;
4583 size_t diff = afterend - from;
4584 size_t middle = from + diff/2;
4585 left = array_setter_node(parser, array, index, value, from, middle);
4586 right = array_setter_node(parser, array, index, value, middle, afterend);
4587 return array_accessor_split(parser, array, index, middle, left, right);
4591 static ast_expression *array_field_setter_node(
4600 lex_ctx_t ctx = ast_ctx(array);
4602 if (from+1 == afterend) {
4603 /* set this value */
4606 ast_entfield *entfield;
4607 ast_array_index *subscript;
4609 int assignop = type_storep_instr[value->expression.vtype];
4611 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4612 assignop = INSTR_STOREP_V;
4614 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4618 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4619 subscript->expression.vtype = TYPE_FIELD;
4621 entfield = ast_entfield_new_force(ctx,
4622 (ast_expression*)entity,
4623 (ast_expression*)subscript,
4624 (ast_expression*)subscript);
4626 ast_delete(subscript);
4630 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4632 ast_delete(entfield);
4636 block = ast_block_new(ctx);
4642 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4647 ret = ast_return_new(ctx, NULL);
4653 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4658 return (ast_expression*)block;
4660 ast_expression *left, *right;
4661 size_t diff = afterend - from;
4662 size_t middle = from + diff/2;
4663 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4664 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4665 return array_accessor_split(parser, array, index, middle, left, right);
4669 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4671 lex_ctx_t ctx = ast_ctx(array);
4673 if (from+1 == afterend) {
4675 ast_array_index *subscript;
4677 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4681 ret = ast_return_new(ctx, (ast_expression*)subscript);
4683 ast_delete(subscript);
4687 return (ast_expression*)ret;
4689 ast_expression *left, *right;
4690 size_t diff = afterend - from;
4691 size_t middle = from + diff/2;
4692 left = array_getter_node(parser, array, index, from, middle);
4693 right = array_getter_node(parser, array, index, middle, afterend);
4694 return array_accessor_split(parser, array, index, middle, left, right);
4698 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4700 ast_function *func = NULL;
4701 ast_value *fval = NULL;
4702 ast_block *body = NULL;
4704 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4706 parseerror(parser, "failed to create accessor function value");
4710 func = ast_function_new(ast_ctx(array), funcname, fval);
4713 parseerror(parser, "failed to create accessor function node");
4717 body = ast_block_new(ast_ctx(array));
4719 parseerror(parser, "failed to create block for array accessor");
4725 vec_push(func->blocks, body);
4728 vec_push(parser->accessors, fval);
4733 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4735 ast_value *index = NULL;
4736 ast_value *value = NULL;
4740 if (!ast_istype(array->expression.next, ast_value)) {
4741 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4745 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4747 func = fval->constval.vfunc;
4748 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4750 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4751 value = ast_value_copy((ast_value*)array->expression.next);
4753 if (!index || !value) {
4754 parseerror(parser, "failed to create locals for array accessor");
4757 (void)!ast_value_set_name(value, "value"); /* not important */
4758 vec_push(fval->expression.params, index);
4759 vec_push(fval->expression.params, value);
4761 array->setter = fval;
4764 if (index) ast_delete(index);
4765 if (value) ast_delete(value);
4771 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4773 ast_expression *root = NULL;
4774 root = array_setter_node(parser, array,
4775 array->setter->expression.params[0],
4776 array->setter->expression.params[1],
4777 0, array->expression.count);
4779 parseerror(parser, "failed to build accessor search tree");
4782 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4789 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4791 if (!parser_create_array_setter_proto(parser, array, funcname))
4793 return parser_create_array_setter_impl(parser, array);
4796 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4798 ast_expression *root = NULL;
4799 ast_value *entity = NULL;
4800 ast_value *index = NULL;
4801 ast_value *value = NULL;
4805 if (!ast_istype(array->expression.next, ast_value)) {
4806 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4810 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4812 func = fval->constval.vfunc;
4813 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4815 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4816 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4817 value = ast_value_copy((ast_value*)array->expression.next);
4818 if (!entity || !index || !value) {
4819 parseerror(parser, "failed to create locals for array accessor");
4822 (void)!ast_value_set_name(value, "value"); /* not important */
4823 vec_push(fval->expression.params, entity);
4824 vec_push(fval->expression.params, index);
4825 vec_push(fval->expression.params, value);
4827 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4829 parseerror(parser, "failed to build accessor search tree");
4833 array->setter = fval;
4834 return ast_block_add_expr(func->blocks[0], root);
4836 if (entity) ast_delete(entity);
4837 if (index) ast_delete(index);
4838 if (value) ast_delete(value);
4839 if (root) ast_delete(root);
4845 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4847 ast_value *index = NULL;
4851 /* NOTE: checking array->expression.next rather than elemtype since
4852 * for fields elemtype is a temporary fieldtype.
4854 if (!ast_istype(array->expression.next, ast_value)) {
4855 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4859 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4861 func = fval->constval.vfunc;
4862 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4864 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4867 parseerror(parser, "failed to create locals for array accessor");
4870 vec_push(fval->expression.params, index);
4872 array->getter = fval;
4875 if (index) ast_delete(index);
4881 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4883 ast_expression *root = NULL;
4885 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4887 parseerror(parser, "failed to build accessor search tree");
4890 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4897 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4899 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4901 return parser_create_array_getter_impl(parser, array);
4904 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4905 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4913 bool variadic = false;
4914 ast_value *varparam = NULL;
4915 char *argcounter = NULL;
4917 ctx = parser_ctx(parser);
4919 /* for the sake of less code we parse-in in this function */
4920 if (!parser_next(parser)) {
4922 parseerror(parser, "expected parameter list");
4928 /* parse variables until we hit a closing paren */
4929 while (parser->tok != ')') {
4931 /* there must be commas between them */
4932 if (parser->tok != ',') {
4933 parseerror(parser, "expected comma or end of parameter list");
4936 if (!parser_next(parser)) {
4937 parseerror(parser, "expected parameter");
4943 if (parser->tok == TOKEN_DOTS) {
4944 /* '...' indicates a varargs function */
4946 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4947 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4950 if (parser->tok == TOKEN_IDENT) {
4951 argcounter = util_strdup(parser_tokval(parser));
4952 if (!parser_next(parser) || parser->tok != ')') {
4953 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4960 /* for anything else just parse a typename */
4961 param = parse_typename(parser, NULL, NULL);
4964 vec_push(params, param);
4965 if (param->expression.vtype >= TYPE_VARIANT) {
4966 char tname[1024]; /* typename is reserved in C++ */
4967 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4968 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4971 /* type-restricted varargs */
4972 if (parser->tok == TOKEN_DOTS) {
4974 varparam = vec_last(params);
4976 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4977 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4980 if (parser->tok == TOKEN_IDENT) {
4981 argcounter = util_strdup(parser_tokval(parser));
4982 if (!parser_next(parser) || parser->tok != ')') {
4983 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4991 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4995 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4996 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4999 if (!parser_next(parser)) {
5000 parseerror(parser, "parse error after typename");
5004 /* now turn 'var' into a function type */
5005 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
5006 fval->expression.next = (ast_expression*)var;
5008 fval->expression.flags |= AST_FLAG_VARIADIC;
5011 var->expression.params = params;
5012 var->expression.varparam = (ast_expression*)varparam;
5013 var->argcounter = argcounter;
5022 ast_delete(varparam);
5024 for (i = 0; i < vec_size(params); ++i)
5025 ast_delete(params[i]);
5030 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5032 ast_expression *cexp;
5033 ast_value *cval, *tmp;
5036 ctx = parser_ctx(parser);
5038 if (!parser_next(parser)) {
5040 parseerror(parser, "expected array-size");
5044 if (parser->tok != ']') {
5045 cexp = parse_expression_leave(parser, true, false, false);
5047 if (!cexp || !ast_istype(cexp, ast_value)) {
5051 parseerror(parser, "expected array-size as constant positive integer");
5054 cval = (ast_value*)cexp;
5061 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5062 tmp->expression.next = (ast_expression*)var;
5066 if (cval->expression.vtype == TYPE_INTEGER)
5067 tmp->expression.count = cval->constval.vint;
5068 else if (cval->expression.vtype == TYPE_FLOAT)
5069 tmp->expression.count = cval->constval.vfloat;
5073 parseerror(parser, "array-size must be a positive integer constant");
5079 var->expression.count = -1;
5080 var->expression.flags |= AST_FLAG_ARRAY_INIT;
5083 if (parser->tok != ']') {
5085 parseerror(parser, "expected ']' after array-size");
5088 if (!parser_next(parser)) {
5090 parseerror(parser, "error after parsing array size");
5096 /* Parse a complete typename.
5097 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5098 * but when parsing variables separated by comma
5099 * 'storebase' should point to where the base-type should be kept.
5100 * The base type makes up every bit of type information which comes *before* the
5103 * The following will be parsed in its entirety:
5105 * The 'basetype' in this case is 'void()'
5106 * and if there's a comma after it, say:
5108 * then the type-information 'void()' can be stored in 'storebase'
5110 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5112 ast_value *var, *tmp;
5115 const char *name = NULL;
5116 bool isfield = false;
5117 bool wasarray = false;
5118 size_t morefields = 0;
5120 ctx = parser_ctx(parser);
5122 /* types may start with a dot */
5123 if (parser->tok == '.') {
5125 /* if we parsed a dot we need a typename now */
5126 if (!parser_next(parser)) {
5127 parseerror(parser, "expected typename for field definition");
5131 /* Further dots are handled seperately because they won't be part of the
5134 while (parser->tok == '.') {
5136 if (!parser_next(parser)) {
5137 parseerror(parser, "expected typename for field definition");
5142 if (parser->tok == TOKEN_IDENT)
5143 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5144 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5145 parseerror(parser, "expected typename");
5149 /* generate the basic type value */
5150 if (cached_typedef) {
5151 var = ast_value_copy(cached_typedef);
5152 ast_value_set_name(var, "<type(from_def)>");
5154 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5156 for (; morefields; --morefields) {
5157 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5158 tmp->expression.next = (ast_expression*)var;
5162 /* do not yet turn into a field - remember:
5163 * .void() foo; is a field too
5164 * .void()() foo; is a function
5168 if (!parser_next(parser)) {
5170 parseerror(parser, "parse error after typename");
5174 /* an opening paren now starts the parameter-list of a function
5175 * this is where original-QC has parameter lists.
5176 * We allow a single parameter list here.
5177 * Much like fteqcc we don't allow `float()() x`
5179 if (parser->tok == '(') {
5180 var = parse_parameter_list(parser, var);
5185 /* store the base if requested */
5187 *storebase = ast_value_copy(var);
5189 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5190 tmp->expression.next = (ast_expression*)*storebase;
5195 /* there may be a name now */
5196 if (parser->tok == TOKEN_IDENT) {
5197 name = util_strdup(parser_tokval(parser));
5199 if (!parser_next(parser)) {
5202 parseerror(parser, "error after variable or field declaration");
5207 /* now this may be an array */
5208 if (parser->tok == '[') {
5210 var = parse_arraysize(parser, var);
5212 if (name) mem_d(name);
5217 /* This is the point where we can turn it into a field */
5219 /* turn it into a field if desired */
5220 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5221 tmp->expression.next = (ast_expression*)var;
5225 /* now there may be function parens again */
5226 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5227 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5228 if (parser->tok == '(' && wasarray)
5229 parseerror(parser, "arrays as part of a return type is not supported");
5230 while (parser->tok == '(') {
5231 var = parse_parameter_list(parser, var);
5233 if (name) mem_d(name);
5238 /* finally name it */
5240 if (!ast_value_set_name(var, name)) {
5243 parseerror(parser, "internal error: failed to set name");
5246 /* free the name, ast_value_set_name duplicates */
5253 static bool parse_typedef(parser_t *parser)
5255 ast_value *typevar, *oldtype;
5256 ast_expression *old;
5258 typevar = parse_typename(parser, NULL, NULL);
5263 if ( (old = parser_find_var(parser, typevar->name)) ) {
5264 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5265 " -> `%s` has been declared here: %s:%i",
5266 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5267 ast_delete(typevar);
5271 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5272 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5273 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5274 ast_delete(typevar);
5278 vec_push(parser->_typedefs, typevar);
5279 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5281 if (parser->tok != ';') {
5282 parseerror(parser, "expected semicolon after typedef");
5285 if (!parser_next(parser)) {
5286 parseerror(parser, "parse error after typedef");
5293 static const char *cvq_to_str(int cvq) {
5295 case CV_NONE: return "none";
5296 case CV_VAR: return "`var`";
5297 case CV_CONST: return "`const`";
5298 default: return "<INVALID>";
5302 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5305 if (proto->cvq != var->cvq) {
5306 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5307 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5308 parser->tok == '='))
5310 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5311 "`%s` declared with different qualifiers: %s\n"
5312 " -> previous declaration here: %s:%i uses %s",
5313 var->name, cvq_to_str(var->cvq),
5314 ast_ctx(proto).file, ast_ctx(proto).line,
5315 cvq_to_str(proto->cvq));
5318 av = (var ->expression.flags & AST_FLAG_NORETURN);
5319 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5321 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5322 "`%s` declared with different attributes%s\n"
5323 " -> previous declaration here: %s:%i",
5324 var->name, (av ? ": noreturn" : ""),
5325 ast_ctx(proto).file, ast_ctx(proto).line,
5326 (ao ? ": noreturn" : ""));
5331 static bool create_array_accessors(parser_t *parser, ast_value *var)
5334 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5335 if (!parser_create_array_setter(parser, var, name))
5337 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5338 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5343 static bool parse_array(parser_t *parser, ast_value *array)
5346 if (array->initlist) {
5347 parseerror(parser, "array already initialized elsewhere");
5350 if (!parser_next(parser)) {
5351 parseerror(parser, "parse error in array initializer");
5355 while (parser->tok != '}') {
5356 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5359 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5361 parseerror(parser, "initializing element must be a compile time constant");
5364 vec_push(array->initlist, v->constval);
5365 if (v->expression.vtype == TYPE_STRING) {
5366 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5370 if (parser->tok == '}')
5372 if (parser->tok != ',' || !parser_next(parser)) {
5373 parseerror(parser, "expected comma or '}' in element list");
5377 if (!parser_next(parser) || parser->tok != ';') {
5378 parseerror(parser, "expected semicolon after initializer, got %s");
5382 if (!parser_next(parser)) {
5383 parseerror(parser, "parse error after initializer");
5388 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5389 if (array->expression.count != (size_t)-1) {
5390 parseerror(parser, "array `%s' has already been initialized with %u elements",
5391 array->name, (unsigned)array->expression.count);
5393 array->expression.count = vec_size(array->initlist);
5394 if (!create_array_accessors(parser, array))
5400 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)
5404 ast_expression *old;
5408 ast_value *basetype = NULL;
5410 bool isparam = false;
5411 bool isvector = false;
5412 bool cleanvar = true;
5413 bool wasarray = false;
5415 ast_member *me[3] = { NULL, NULL, NULL };
5417 if (!localblock && is_static)
5418 parseerror(parser, "`static` qualifier is not supported in global scope");
5420 /* get the first complete variable */
5421 var = parse_typename(parser, &basetype, cached_typedef);
5424 ast_delete(basetype);
5432 /* Part 0: finish the type */
5433 if (parser->tok == '(') {
5434 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5435 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5436 var = parse_parameter_list(parser, var);
5442 /* we only allow 1-dimensional arrays */
5443 if (parser->tok == '[') {
5445 var = parse_arraysize(parser, var);
5451 if (parser->tok == '(' && wasarray) {
5452 parseerror(parser, "arrays as part of a return type is not supported");
5453 /* we'll still parse the type completely for now */
5455 /* for functions returning functions */
5456 while (parser->tok == '(') {
5457 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5458 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5459 var = parse_parameter_list(parser, var);
5466 var->cvq = qualifier;
5467 var->expression.flags |= qflags;
5470 * store the vstring back to var for alias and
5471 * deprecation messages.
5473 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5474 var->expression.flags & AST_FLAG_ALIAS)
5475 var->desc = vstring;
5478 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5479 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5480 * is then filled with the previous definition and the parameter-names replaced.
5482 if (!strcmp(var->name, "nil")) {
5483 if (OPTS_FLAG(UNTYPED_NIL)) {
5484 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5485 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5487 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5490 /* Deal with end_sys_ vars */
5492 if (!strcmp(var->name, "end_sys_globals")) {
5494 parser->crc_globals = vec_size(parser->globals);
5497 else if (!strcmp(var->name, "end_sys_fields")) {
5499 parser->crc_fields = vec_size(parser->fields);
5502 if (was_end && var->expression.vtype == TYPE_FIELD) {
5503 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5504 "global '%s' hint should not be a field",
5505 parser_tokval(parser)))
5512 if (!nofields && var->expression.vtype == TYPE_FIELD)
5514 /* deal with field declarations */
5515 old = parser_find_field(parser, var->name);
5517 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5518 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5527 parseerror(parser, "field `%s` already declared here: %s:%i",
5528 var->name, ast_ctx(old).file, ast_ctx(old).line);
5533 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5534 (old = parser_find_global(parser, var->name)))
5536 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5537 parseerror(parser, "field `%s` already declared here: %s:%i",
5538 var->name, ast_ctx(old).file, ast_ctx(old).line);
5545 /* deal with other globals */
5546 old = parser_find_global(parser, var->name);
5547 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5549 /* This is a function which had a prototype */
5550 if (!ast_istype(old, ast_value)) {
5551 parseerror(parser, "internal error: prototype is not an ast_value");
5555 proto = (ast_value*)old;
5556 proto->desc = var->desc;
5557 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5558 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5560 ast_ctx(proto).file, ast_ctx(proto).line);
5564 /* we need the new parameter-names */
5565 for (i = 0; i < vec_size(proto->expression.params); ++i)
5566 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5567 if (!parser_check_qualifiers(parser, var, proto)) {
5574 proto->expression.flags |= var->expression.flags;
5582 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5583 "global `%s` already declared here: %s:%i",
5584 var->name, ast_ctx(old).file, ast_ctx(old).line))
5589 proto = (ast_value*)old;
5590 if (!ast_istype(old, ast_value)) {
5591 parseerror(parser, "internal error: not an ast_value");
5596 if (!parser_check_qualifiers(parser, var, proto)) {
5601 proto->expression.flags |= var->expression.flags;
5605 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5606 (old = parser_find_field(parser, var->name)))
5608 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5609 parseerror(parser, "global `%s` already declared here: %s:%i",
5610 var->name, ast_ctx(old).file, ast_ctx(old).line);
5617 else /* it's not a global */
5619 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5620 if (old && !isparam) {
5621 parseerror(parser, "local `%s` already declared here: %s:%i",
5622 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5626 old = parser_find_local(parser, var->name, 0, &isparam);
5627 if (old && isparam) {
5628 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5629 "local `%s` is shadowing a parameter", var->name))
5631 parseerror(parser, "local `%s` already declared here: %s:%i",
5632 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5636 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5644 /* in a noref section we simply bump the usecount */
5645 if (noref || parser->noref)
5649 * Create the global/local, and deal with vector types.
5652 if (var->expression.vtype == TYPE_VECTOR)
5654 else if (var->expression.vtype == TYPE_FIELD &&
5655 var->expression.next->vtype == TYPE_VECTOR)
5659 if (!create_vector_members(var, me)) {
5666 /* deal with global variables, fields, functions */
5667 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5668 var->isfield = true;
5669 vec_push(parser->fields, (ast_expression*)var);
5670 util_htset(parser->htfields, var->name, var);
5672 for (i = 0; i < 3; ++i) {
5673 vec_push(parser->fields, (ast_expression*)me[i]);
5674 util_htset(parser->htfields, me[i]->name, me[i]);
5679 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5680 parser_addglobal(parser, var->name, (ast_expression*)var);
5682 for (i = 0; i < 3; ++i) {
5683 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5687 ast_expression *find = parser_find_global(parser, var->desc);
5690 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5694 if (var->expression.vtype != find->vtype) {
5698 ast_type_to_string(find, ty1, sizeof(ty1));
5699 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5701 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5708 * add alias to aliases table and to corrector
5709 * so corrections can apply for aliases as well.
5711 util_htset(parser->aliases, var->name, find);
5714 * add to corrector so corrections can work
5715 * even for aliases too.
5718 vec_last(parser->correct_variables),
5719 &vec_last(parser->correct_variables_score),
5723 /* generate aliases for vector components */
5727 util_asprintf(&buffer[0], "%s_x", var->desc);
5728 util_asprintf(&buffer[1], "%s_y", var->desc);
5729 util_asprintf(&buffer[2], "%s_z", var->desc);
5731 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5732 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5733 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5740 * add to corrector so corrections can work
5741 * even for aliases too.
5744 vec_last(parser->correct_variables),
5745 &vec_last(parser->correct_variables_score),
5749 vec_last(parser->correct_variables),
5750 &vec_last(parser->correct_variables_score),
5754 vec_last(parser->correct_variables),
5755 &vec_last(parser->correct_variables_score),
5763 /* a static adds itself to be generated like any other global
5764 * but is added to the local namespace instead
5766 char *defname = NULL;
5767 size_t prefix_len, ln;
5769 ln = strlen(parser->function->name);
5770 vec_append(defname, ln, parser->function->name);
5772 vec_append(defname, 2, "::");
5773 /* remember the length up to here */
5774 prefix_len = vec_size(defname);
5776 /* Add it to the local scope */
5777 util_htset(vec_last(parser->variables), var->name, (void*)var);
5781 vec_last(parser->correct_variables),
5782 &vec_last(parser->correct_variables_score),
5786 /* now rename the global */
5787 ln = strlen(var->name);
5788 vec_append(defname, ln, var->name);
5789 ast_value_set_name(var, defname);
5791 /* push it to the to-be-generated globals */
5792 vec_push(parser->globals, (ast_expression*)var);
5794 /* same game for the vector members */
5796 for (i = 0; i < 3; ++i) {
5797 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5801 vec_last(parser->correct_variables),
5802 &vec_last(parser->correct_variables_score),
5806 vec_shrinkto(defname, prefix_len);
5807 ln = strlen(me[i]->name);
5808 vec_append(defname, ln, me[i]->name);
5809 ast_member_set_name(me[i], defname);
5811 vec_push(parser->globals, (ast_expression*)me[i]);
5816 vec_push(localblock->locals, var);
5817 parser_addlocal(parser, var->name, (ast_expression*)var);
5819 for (i = 0; i < 3; ++i) {
5820 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5821 ast_block_collect(localblock, (ast_expression*)me[i]);
5827 me[0] = me[1] = me[2] = NULL;
5832 if (var->expression.vtype == TYPE_ARRAY) {
5833 if (var->expression.count != (size_t)-1) {
5834 if (!create_array_accessors(parser, var))
5838 else if (!localblock && !nofields &&
5839 var->expression.vtype == TYPE_FIELD &&
5840 var->expression.next->vtype == TYPE_ARRAY)
5843 ast_expression *telem;
5845 ast_value *array = (ast_value*)var->expression.next;
5847 if (!ast_istype(var->expression.next, ast_value)) {
5848 parseerror(parser, "internal error: field element type must be an ast_value");
5852 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5853 if (!parser_create_array_field_setter(parser, array, name))
5856 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5857 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5858 tfield->expression.next = telem;
5859 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5860 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5868 if (parser->tok == ';') {
5869 ast_delete(basetype);
5870 if (!parser_next(parser)) {
5871 parseerror(parser, "error after variable declaration");
5877 if (parser->tok == ',')
5881 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5884 parseerror(parser, "missing comma or semicolon while parsing variables");
5888 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5889 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5890 "initializing expression turns variable `%s` into a constant in this standard",
5897 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5898 if (parser->tok != '=') {
5899 if (!strcmp(parser_tokval(parser), "break")) {
5900 if (!parser_next(parser)) {
5901 parseerror(parser, "error parsing break definition");
5904 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5906 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5911 if (!parser_next(parser)) {
5912 parseerror(parser, "error parsing initializer");
5916 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5917 parseerror(parser, "expected '=' before function body in this standard");
5920 if (parser->tok == '#') {
5921 ast_function *func = NULL;
5922 ast_value *number = NULL;
5928 parseerror(parser, "cannot declare builtins within functions");
5931 if (var->expression.vtype != TYPE_FUNCTION) {
5932 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5935 if (!parser_next(parser)) {
5936 parseerror(parser, "expected builtin number");
5940 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5941 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5943 parseerror(parser, "builtin number expected");
5946 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5949 parseerror(parser, "builtin number must be a compile time constant");
5952 if (number->expression.vtype == TYPE_INTEGER)
5953 builtin_num = number->constval.vint;
5954 else if (number->expression.vtype == TYPE_FLOAT)
5955 builtin_num = number->constval.vfloat;
5958 parseerror(parser, "builtin number must be an integer constant");
5963 fractional = modff(builtin_num, &integral);
5964 if (builtin_num < 0 || fractional != 0) {
5965 parseerror(parser, "builtin number must be an integer greater than zero");
5969 /* we only want the integral part anyways */
5970 builtin_num = integral;
5971 } else if (parser->tok == TOKEN_INTCONST) {
5972 builtin_num = parser_token(parser)->constval.i;
5974 parseerror(parser, "builtin number must be a compile time constant");
5978 if (var->hasvalue) {
5979 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5980 "builtin `%s` has already been defined\n"
5981 " -> previous declaration here: %s:%i",
5982 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5986 func = ast_function_new(ast_ctx(var), var->name, var);
5988 parseerror(parser, "failed to allocate function for `%s`", var->name);
5991 vec_push(parser->functions, func);
5993 func->builtin = -builtin_num-1;
5996 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5997 ? (parser->tok != ',' && parser->tok != ';')
5998 : (!parser_next(parser)))
6000 parseerror(parser, "expected comma or semicolon");
6002 ast_function_delete(func);
6003 var->constval.vfunc = NULL;
6007 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
6010 /* Note that fteqcc and most others don't even *have*
6011 * local arrays, so this is not a high priority.
6013 parseerror(parser, "TODO: initializers for local arrays");
6017 var->hasvalue = true;
6018 if (!parse_array(parser, var))
6021 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
6024 parseerror(parser, "cannot declare functions within functions");
6029 ast_ctx(proto) = parser_ctx(parser);
6031 if (!parse_function_body(parser, var))
6033 ast_delete(basetype);
6034 for (i = 0; i < vec_size(parser->gotos); ++i)
6035 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
6036 vec_free(parser->gotos);
6037 vec_free(parser->labels);
6040 ast_expression *cexp;
6043 cexp = parse_expression_leave(parser, true, false, false);
6048 cval = (ast_value*)cexp;
6049 if (cval != parser->nil &&
6050 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
6053 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
6057 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
6058 qualifier != CV_VAR)
6060 var->cvq = CV_CONST;
6062 if (cval == parser->nil)
6063 var->expression.flags |= AST_FLAG_INITIALIZED;
6066 var->hasvalue = true;
6067 if (cval->expression.vtype == TYPE_STRING)
6068 var->constval.vstring = parser_strdup(cval->constval.vstring);
6069 else if (cval->expression.vtype == TYPE_FIELD)
6070 var->constval.vfield = cval;
6072 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
6078 shunt sy = { NULL, NULL, NULL, NULL };
6081 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
6082 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
6083 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
6084 if (!parser_sy_apply_operator(parser, &sy))
6087 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
6088 parseerror(parser, "internal error: leaked operands");
6089 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
6100 if (parser->tok == ',') {
6101 if (!parser_next(parser)) {
6102 parseerror(parser, "expected another variable");
6106 if (parser->tok != TOKEN_IDENT) {
6107 parseerror(parser, "expected another variable");
6110 var = ast_value_copy(basetype);
6112 ast_value_set_name(var, parser_tokval(parser));
6113 if (!parser_next(parser)) {
6114 parseerror(parser, "error parsing variable declaration");
6120 if (parser->tok != ';') {
6121 parseerror(parser, "missing semicolon after variables");
6125 if (!parser_next(parser)) {
6126 parseerror(parser, "parse error after variable declaration");
6130 ast_delete(basetype);
6134 if (cleanvar && var)
6136 ast_delete(basetype);
6140 ast_delete(basetype);
6141 if (cleanvar && var)
6143 if (me[0]) ast_member_delete(me[0]);
6144 if (me[1]) ast_member_delete(me[1]);
6145 if (me[2]) ast_member_delete(me[2]);
6149 static bool parser_global_statement(parser_t *parser)
6153 bool is_static = false;
6154 uint32_t qflags = 0;
6155 ast_value *istype = NULL;
6156 char *vstring = NULL;
6158 if (parser->tok == TOKEN_IDENT)
6159 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6161 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6163 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6165 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6167 if (cvq == CV_WRONG)
6169 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6171 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6173 return parse_enum(parser);
6175 else if (parser->tok == TOKEN_KEYWORD)
6177 if (!strcmp(parser_tokval(parser), "typedef")) {
6178 if (!parser_next(parser)) {
6179 parseerror(parser, "expected type definition after 'typedef'");
6182 return parse_typedef(parser);
6184 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6187 else if (parser->tok == '#')
6189 return parse_pragma(parser);
6191 else if (parser->tok == '$')
6193 if (!parser_next(parser)) {
6194 parseerror(parser, "parse error");
6200 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6206 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6208 return util_crc16(old, str, strlen(str));
6211 static void progdefs_crc_file(const char *str)
6213 /* write to progdefs.h here */
6217 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6219 old = progdefs_crc_sum(old, str);
6220 progdefs_crc_file(str);
6224 static void generate_checksum(parser_t *parser, ir_builder *ir)
6226 uint16_t crc = 0xFFFF;
6230 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6231 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6233 progdefs_crc_file("\tint\tpad;\n");
6234 progdefs_crc_file("\tint\tofs_return[3];\n");
6235 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6236 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6237 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6238 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6239 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6240 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6241 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6242 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6244 for (i = 0; i < parser->crc_globals; ++i) {
6245 if (!ast_istype(parser->globals[i], ast_value))
6247 value = (ast_value*)(parser->globals[i]);
6248 switch (value->expression.vtype) {
6249 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6250 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6251 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6252 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6254 crc = progdefs_crc_both(crc, "\tint\t");
6257 crc = progdefs_crc_both(crc, value->name);
6258 crc = progdefs_crc_both(crc, ";\n");
6260 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6261 for (i = 0; i < parser->crc_fields; ++i) {
6262 if (!ast_istype(parser->fields[i], ast_value))
6264 value = (ast_value*)(parser->fields[i]);
6265 switch (value->expression.next->vtype) {
6266 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6267 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6268 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6269 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6271 crc = progdefs_crc_both(crc, "\tint\t");
6274 crc = progdefs_crc_both(crc, value->name);
6275 crc = progdefs_crc_both(crc, ";\n");
6277 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6278 ir->code->crc = crc;
6281 parser_t *parser_create()
6284 lex_ctx_t empty_ctx;
6287 parser = (parser_t*)mem_a(sizeof(parser_t));
6291 memset(parser, 0, sizeof(*parser));
6293 for (i = 0; i < operator_count; ++i) {
6294 if (operators[i].id == opid1('=')) {
6295 parser->assign_op = operators+i;
6299 if (!parser->assign_op) {
6300 printf("internal error: initializing parser: failed to find assign operator\n");
6305 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6306 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6307 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6308 vec_push(parser->_blocktypedefs, 0);
6310 parser->aliases = util_htnew(PARSER_HT_SIZE);
6312 parser->ht_imm_string = util_htnew(512);
6313 parser->ht_imm_string_dotranslate = util_htnew(512);
6316 vec_push(parser->correct_variables, correct_trie_new());
6317 vec_push(parser->correct_variables_score, NULL);
6319 empty_ctx.file = "<internal>";
6321 empty_ctx.column = 0;
6322 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6323 parser->nil->cvq = CV_CONST;
6324 if (OPTS_FLAG(UNTYPED_NIL))
6325 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6327 parser->max_param_count = 1;
6329 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6330 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6331 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6333 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6334 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6335 parser->reserved_version->cvq = CV_CONST;
6336 parser->reserved_version->hasvalue = true;
6337 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6338 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6340 parser->reserved_version = NULL;
6346 static bool parser_compile(parser_t *parser)
6348 /* initial lexer/parser state */
6349 parser->lex->flags.noops = true;
6351 if (parser_next(parser))
6353 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6355 if (!parser_global_statement(parser)) {
6356 if (parser->tok == TOKEN_EOF)
6357 parseerror(parser, "unexpected end of file");
6358 else if (compile_errors)
6359 parseerror(parser, "there have been errors, bailing out");
6360 lex_close(parser->lex);
6366 parseerror(parser, "parse error");
6367 lex_close(parser->lex);
6372 lex_close(parser->lex);
6375 return !compile_errors;
6378 bool parser_compile_file(parser_t *parser, const char *filename)
6380 parser->lex = lex_open(filename);
6382 con_err("failed to open file \"%s\"\n", filename);
6385 return parser_compile(parser);
6388 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6390 parser->lex = lex_open_string(str, len, name);
6392 con_err("failed to create lexer for string \"%s\"\n", name);
6395 return parser_compile(parser);
6398 static void parser_remove_ast(parser_t *parser)
6401 if (parser->ast_cleaned)
6403 parser->ast_cleaned = true;
6404 for (i = 0; i < vec_size(parser->accessors); ++i) {
6405 ast_delete(parser->accessors[i]->constval.vfunc);
6406 parser->accessors[i]->constval.vfunc = NULL;
6407 ast_delete(parser->accessors[i]);
6409 for (i = 0; i < vec_size(parser->functions); ++i) {
6410 ast_delete(parser->functions[i]);
6412 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6413 ast_delete(parser->imm_vector[i]);
6415 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6416 ast_delete(parser->imm_string[i]);
6418 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6419 ast_delete(parser->imm_float[i]);
6421 for (i = 0; i < vec_size(parser->fields); ++i) {
6422 ast_delete(parser->fields[i]);
6424 for (i = 0; i < vec_size(parser->globals); ++i) {
6425 ast_delete(parser->globals[i]);
6427 vec_free(parser->accessors);
6428 vec_free(parser->functions);
6429 vec_free(parser->imm_vector);
6430 vec_free(parser->imm_string);
6431 util_htdel(parser->ht_imm_string_dotranslate);
6432 util_htdel(parser->ht_imm_string);
6433 vec_free(parser->imm_float);
6434 vec_free(parser->globals);
6435 vec_free(parser->fields);
6437 for (i = 0; i < vec_size(parser->variables); ++i)
6438 util_htdel(parser->variables[i]);
6439 vec_free(parser->variables);
6440 vec_free(parser->_blocklocals);
6441 vec_free(parser->_locals);
6444 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6445 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6447 vec_free(parser->correct_variables);
6448 vec_free(parser->correct_variables_score);
6450 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6451 ast_delete(parser->_typedefs[i]);
6452 vec_free(parser->_typedefs);
6453 for (i = 0; i < vec_size(parser->typedefs); ++i)
6454 util_htdel(parser->typedefs[i]);
6455 vec_free(parser->typedefs);
6456 vec_free(parser->_blocktypedefs);
6458 vec_free(parser->_block_ctx);
6460 vec_free(parser->labels);
6461 vec_free(parser->gotos);
6462 vec_free(parser->breaks);
6463 vec_free(parser->continues);
6465 ast_value_delete(parser->nil);
6467 ast_value_delete(parser->const_vec[0]);
6468 ast_value_delete(parser->const_vec[1]);
6469 ast_value_delete(parser->const_vec[2]);
6471 if (parser->reserved_version)
6472 ast_value_delete(parser->reserved_version);
6474 util_htdel(parser->aliases);
6475 intrin_intrinsics_destroy(parser);
6478 void parser_cleanup(parser_t *parser)
6480 parser_remove_ast(parser);
6484 bool parser_finish(parser_t *parser, const char *output)
6490 if (compile_errors) {
6491 con_out("*** there were compile errors\n");
6495 ir = ir_builder_new("gmqcc_out");
6497 con_out("failed to allocate builder\n");
6501 for (i = 0; i < vec_size(parser->fields); ++i) {
6504 if (!ast_istype(parser->fields[i], ast_value))
6506 field = (ast_value*)parser->fields[i];
6507 hasvalue = field->hasvalue;
6508 field->hasvalue = false;
6509 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6510 con_out("failed to generate field %s\n", field->name);
6511 ir_builder_delete(ir);
6516 ast_expression *subtype;
6517 field->hasvalue = true;
6518 subtype = field->expression.next;
6519 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6520 if (subtype->vtype == TYPE_FIELD)
6521 ifld->fieldtype = subtype->next->vtype;
6522 else if (subtype->vtype == TYPE_FUNCTION)
6523 ifld->outtype = subtype->next->vtype;
6524 (void)!ir_value_set_field(field->ir_v, ifld);
6527 for (i = 0; i < vec_size(parser->globals); ++i) {
6529 if (!ast_istype(parser->globals[i], ast_value))
6531 asvalue = (ast_value*)(parser->globals[i]);
6532 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6533 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6534 "unused global: `%s`", asvalue->name);
6536 if (!ast_global_codegen(asvalue, ir, false)) {
6537 con_out("failed to generate global %s\n", asvalue->name);
6538 ir_builder_delete(ir);
6542 /* Build function vararg accessor ast tree now before generating
6543 * immediates, because the accessors may add new immediates
6545 for (i = 0; i < vec_size(parser->functions); ++i) {
6546 ast_function *f = parser->functions[i];
6548 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6549 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6550 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6551 con_out("failed to generate vararg setter for %s\n", f->name);
6552 ir_builder_delete(ir);
6555 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6556 con_out("failed to generate vararg getter for %s\n", f->name);
6557 ir_builder_delete(ir);
6561 ast_delete(f->varargs);
6566 /* Now we can generate immediates */
6567 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6568 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6569 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6570 ir_builder_delete(ir);
6574 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6575 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6576 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6577 ir_builder_delete(ir);
6581 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6582 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6583 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6584 ir_builder_delete(ir);
6588 for (i = 0; i < vec_size(parser->globals); ++i) {
6590 if (!ast_istype(parser->globals[i], ast_value))
6592 asvalue = (ast_value*)(parser->globals[i]);
6593 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6595 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6596 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6597 "uninitialized constant: `%s`",
6599 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6600 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6601 "uninitialized global: `%s`",
6604 if (!ast_generate_accessors(asvalue, ir)) {
6605 ir_builder_delete(ir);
6609 for (i = 0; i < vec_size(parser->fields); ++i) {
6611 asvalue = (ast_value*)(parser->fields[i]->next);
6613 if (!ast_istype((ast_expression*)asvalue, ast_value))
6615 if (asvalue->expression.vtype != TYPE_ARRAY)
6617 if (!ast_generate_accessors(asvalue, ir)) {
6618 ir_builder_delete(ir);
6622 if (parser->reserved_version &&
6623 !ast_global_codegen(parser->reserved_version, ir, false))
6625 con_out("failed to generate reserved::version");
6626 ir_builder_delete(ir);
6629 for (i = 0; i < vec_size(parser->functions); ++i) {
6630 ast_function *f = parser->functions[i];
6631 if (!ast_function_codegen(f, ir)) {
6632 con_out("failed to generate function %s\n", f->name);
6633 ir_builder_delete(ir);
6638 generate_checksum(parser, ir);
6640 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6641 ir_builder_dump(ir, con_out);
6642 for (i = 0; i < vec_size(parser->functions); ++i) {
6643 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6644 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6645 ir_builder_delete(ir);
6649 parser_remove_ast(parser);
6651 if (compile_Werrors) {
6652 con_out("*** there were warnings treated as errors\n");
6653 compile_show_werrors();
6658 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6659 ir_builder_dump(ir, con_out);
6661 if (!ir_builder_generate(ir, output)) {
6662 con_out("*** failed to generate output file\n");
6663 ir_builder_delete(ir);
6667 ir_builder_delete(ir);