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;
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 vector vec3_add(vector a, vector b)
160 vector vec3_sub(vector a, vector b)
169 qcfloat vec3_mulvv(vector a, vector b)
171 return (a.x * b.x + a.y * b.y + a.z * b.z);
174 vector vec3_mulvf(vector 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, vector 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 ctx, ast_expression *v) {
442 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
446 e.out = (ast_expression*)v;
453 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
455 e.etype = 1 + (op - operators);
464 static sy_elem syparen(lex_ctx 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 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 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 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 vector 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 vector 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)ConstF(0)) % ((qcint)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)ConstF(0)) | ((qcint)ConstF(1)) ) :
1028 (float)( ((qcint)ConstF(0)) & ((qcint)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)(ConstF(0)) ^ ((qcint)(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)(ConstV(0).x)) ^ ((qcint)(ConstV(1).x))),
1130 (float)(((qcint)(ConstV(0).y)) ^ ((qcint)(ConstV(1).y))),
1131 (float)(((qcint)(ConstV(0).z)) ^ ((qcint)(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)(ConstV(0).x)) ^ ((qcint)(ConstF(1)))),
1146 (float)(((qcint)(ConstV(0).y)) ^ ((qcint)(ConstF(1)))),
1147 (float)(((qcint)(ConstV(0).z)) ^ ((qcint)(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 = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1331 case opid2('=', '='):
1332 if (exprs[0]->vtype != exprs[1]->vtype) {
1333 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1334 type_name[exprs[0]->vtype],
1335 type_name[exprs[1]->vtype]);
1338 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1342 if (ast_istype(exprs[0], ast_entfield)) {
1343 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1344 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1345 exprs[0]->vtype == TYPE_FIELD &&
1346 exprs[0]->next->vtype == TYPE_VECTOR)
1348 assignop = type_storep_instr[TYPE_VECTOR];
1351 assignop = type_storep_instr[exprs[0]->vtype];
1352 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1354 ast_type_to_string(field->next, ty1, sizeof(ty1));
1355 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1356 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1357 field->next->vtype == TYPE_FUNCTION &&
1358 exprs[1]->vtype == TYPE_FUNCTION)
1360 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1361 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1364 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1369 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1370 exprs[0]->vtype == TYPE_FIELD &&
1371 exprs[0]->next->vtype == TYPE_VECTOR)
1373 assignop = type_store_instr[TYPE_VECTOR];
1376 assignop = type_store_instr[exprs[0]->vtype];
1379 if (assignop == VINSTR_END) {
1380 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1381 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1382 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1384 else if (!ast_compare_type(exprs[0], exprs[1]))
1386 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1387 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1388 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1389 exprs[0]->vtype == TYPE_FUNCTION &&
1390 exprs[1]->vtype == TYPE_FUNCTION)
1392 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1393 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1396 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1399 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1400 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1402 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1404 case opid3('+','+','P'):
1405 case opid3('-','-','P'):
1407 if (exprs[0]->vtype != TYPE_FLOAT) {
1408 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1409 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1412 if (op->id == opid3('+','+','P'))
1413 addop = INSTR_ADD_F;
1415 addop = INSTR_SUB_F;
1416 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1417 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1419 if (ast_istype(exprs[0], ast_entfield)) {
1420 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1422 (ast_expression*)parser_const_float_1(parser));
1424 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1426 (ast_expression*)parser_const_float_1(parser));
1429 case opid3('S','+','+'):
1430 case opid3('S','-','-'):
1432 if (exprs[0]->vtype != TYPE_FLOAT) {
1433 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1434 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1437 if (op->id == opid3('S','+','+')) {
1438 addop = INSTR_ADD_F;
1439 subop = INSTR_SUB_F;
1441 addop = INSTR_SUB_F;
1442 subop = INSTR_ADD_F;
1444 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1445 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1447 if (ast_istype(exprs[0], ast_entfield)) {
1448 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1450 (ast_expression*)parser_const_float_1(parser));
1452 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1454 (ast_expression*)parser_const_float_1(parser));
1458 out = (ast_expression*)ast_binary_new(ctx, subop,
1460 (ast_expression*)parser_const_float_1(parser));
1462 case opid2('+','='):
1463 case opid2('-','='):
1464 if (exprs[0]->vtype != exprs[1]->vtype ||
1465 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1467 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1468 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1469 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1473 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1474 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1476 if (ast_istype(exprs[0], ast_entfield))
1477 assignop = type_storep_instr[exprs[0]->vtype];
1479 assignop = type_store_instr[exprs[0]->vtype];
1480 switch (exprs[0]->vtype) {
1482 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1483 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1484 exprs[0], exprs[1]);
1487 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1488 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1489 exprs[0], exprs[1]);
1492 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1493 type_name[exprs[0]->vtype],
1494 type_name[exprs[1]->vtype]);
1498 case opid2('*','='):
1499 case opid2('/','='):
1500 if (exprs[1]->vtype != TYPE_FLOAT ||
1501 !(exprs[0]->vtype == TYPE_FLOAT ||
1502 exprs[0]->vtype == TYPE_VECTOR))
1504 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1505 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1506 compile_error(ctx, "invalid types used in expression: %s and %s",
1510 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1511 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1513 if (ast_istype(exprs[0], ast_entfield))
1514 assignop = type_storep_instr[exprs[0]->vtype];
1516 assignop = type_store_instr[exprs[0]->vtype];
1517 switch (exprs[0]->vtype) {
1519 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1520 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1521 exprs[0], exprs[1]);
1524 if (op->id == opid2('*','=')) {
1525 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1526 exprs[0], exprs[1]);
1528 /* there's no DIV_VF */
1529 if (CanConstFold1(exprs[1])) {
1530 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1532 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1533 (ast_expression*)parser_const_float_1(parser),
1537 compile_error(ctx, "internal error: failed to generate division");
1540 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1545 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1546 type_name[exprs[0]->vtype],
1547 type_name[exprs[1]->vtype]);
1551 case opid2('&','='):
1552 case opid2('|','='):
1553 if (NotSameType(TYPE_FLOAT)) {
1554 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1555 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1556 compile_error(ctx, "invalid types used in expression: %s and %s",
1560 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1561 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1563 if (ast_istype(exprs[0], ast_entfield))
1564 assignop = type_storep_instr[exprs[0]->vtype];
1566 assignop = type_store_instr[exprs[0]->vtype];
1567 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1568 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1569 exprs[0], exprs[1]);
1571 case opid3('&','~','='):
1572 /* This is like: a &= ~(b);
1573 * But QC has no bitwise-not, so we implement it as
1576 if (NotSameType(TYPE_FLOAT)) {
1577 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1578 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1579 compile_error(ctx, "invalid types used in expression: %s and %s",
1583 if (ast_istype(exprs[0], ast_entfield))
1584 assignop = type_storep_instr[exprs[0]->vtype];
1586 assignop = type_store_instr[exprs[0]->vtype];
1587 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1590 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1591 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1593 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1594 asbinstore->keep_dest = true;
1595 out = (ast_expression*)asbinstore;
1598 case opid2('~', 'P'):
1599 if (exprs[0]->vtype != TYPE_FLOAT) {
1600 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1601 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1605 if(CanConstFold1(exprs[0]))
1606 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1608 out = (ast_expression*)
1609 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1615 compile_error(ctx, "failed to apply operator %s", op->op);
1619 vec_push(sy->out, syexp(ctx, out));
1623 static bool parser_close_call(parser_t *parser, shunt *sy)
1625 /* was a function call */
1626 ast_expression *fun;
1627 ast_value *funval = NULL;
1631 size_t paramcount, i;
1633 fid = vec_last(sy->ops).off;
1634 vec_shrinkby(sy->ops, 1);
1636 /* out[fid] is the function
1637 * everything above is parameters...
1639 if (!vec_size(sy->argc)) {
1640 parseerror(parser, "internal error: no argument counter available");
1644 paramcount = vec_last(sy->argc);
1647 if (vec_size(sy->out) < fid) {
1648 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1649 (unsigned long)vec_size(sy->out),
1651 (unsigned long)paramcount);
1655 fun = sy->out[fid].out;
1657 if (fun == intrinsic_debug_typestring) {
1659 if (fid+2 != vec_size(sy->out) ||
1660 vec_last(sy->out).block)
1662 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1665 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1666 ast_unref(vec_last(sy->out).out);
1667 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1668 (ast_expression*)parser_const_string(parser, ty, false));
1669 vec_shrinkby(sy->out, 1);
1673 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1677 if (fid+1 < vec_size(sy->out))
1680 if (fid+1 + paramcount != vec_size(sy->out)) {
1681 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1682 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1686 for (i = 0; i < paramcount; ++i)
1687 vec_push(call->params, sy->out[fid+1 + i].out);
1688 vec_shrinkby(sy->out, paramcount);
1689 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1690 if (parser->max_param_count < paramcount)
1691 parser->max_param_count = paramcount;
1693 if (ast_istype(fun, ast_value)) {
1694 funval = (ast_value*)fun;
1695 if ((fun->flags & AST_FLAG_VARIADIC) &&
1696 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1698 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1702 /* overwrite fid, the function, with a call */
1703 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1705 if (fun->vtype != TYPE_FUNCTION) {
1706 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1711 parseerror(parser, "could not determine function return type");
1714 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1716 if (fun->flags & AST_FLAG_DEPRECATED) {
1718 return !parsewarning(parser, WARN_DEPRECATED,
1719 "call to function (which is marked deprecated)\n",
1720 "-> it has been declared here: %s:%i",
1721 ast_ctx(fun).file, ast_ctx(fun).line);
1724 return !parsewarning(parser, WARN_DEPRECATED,
1725 "call to `%s` (which is marked deprecated)\n"
1726 "-> `%s` declared here: %s:%i",
1727 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1729 return !parsewarning(parser, WARN_DEPRECATED,
1730 "call to `%s` (deprecated: %s)\n"
1731 "-> `%s` declared here: %s:%i",
1732 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1736 if (vec_size(fun->params) != paramcount &&
1737 !((fun->flags & AST_FLAG_VARIADIC) &&
1738 vec_size(fun->params) < paramcount))
1740 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1742 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1743 "too %s parameters for call to %s: expected %i, got %i\n"
1744 " -> `%s` has been declared here: %s:%i",
1745 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1746 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1748 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1749 "too %s parameters for function call: expected %i, got %i\n"
1750 " -> it has been declared here: %s:%i",
1751 fewmany, (int)vec_size(fun->params), (int)paramcount,
1752 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1759 static bool parser_close_paren(parser_t *parser, shunt *sy)
1761 if (!vec_size(sy->ops)) {
1762 parseerror(parser, "unmatched closing paren");
1766 while (vec_size(sy->ops)) {
1767 if (vec_last(sy->ops).isparen) {
1768 if (vec_last(sy->paren) == PAREN_FUNC) {
1770 if (!parser_close_call(parser, sy))
1774 if (vec_last(sy->paren) == PAREN_EXPR) {
1776 if (!vec_size(sy->out)) {
1777 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1778 vec_shrinkby(sy->ops, 1);
1781 vec_shrinkby(sy->ops, 1);
1784 if (vec_last(sy->paren) == PAREN_INDEX) {
1786 /* pop off the parenthesis */
1787 vec_shrinkby(sy->ops, 1);
1788 /* then apply the index operator */
1789 if (!parser_sy_apply_operator(parser, sy))
1793 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1794 vec_last(sy->paren) = PAREN_TERNARY2;
1795 /* pop off the parenthesis */
1796 vec_shrinkby(sy->ops, 1);
1799 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1802 if (!parser_sy_apply_operator(parser, sy))
1808 static void parser_reclassify_token(parser_t *parser)
1811 if (parser->tok >= TOKEN_START)
1813 for (i = 0; i < operator_count; ++i) {
1814 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1815 parser->tok = TOKEN_OPERATOR;
1821 static ast_expression* parse_vararg_do(parser_t *parser)
1823 ast_expression *idx, *out;
1825 ast_value *funtype = parser->function->vtype;
1826 lex_ctx ctx = parser_ctx(parser);
1828 if (!parser->function->varargs) {
1829 parseerror(parser, "function has no variable argument list");
1833 if (!parser_next(parser) || parser->tok != '(') {
1834 parseerror(parser, "expected parameter index and type in parenthesis");
1837 if (!parser_next(parser)) {
1838 parseerror(parser, "error parsing parameter index");
1842 idx = parse_expression_leave(parser, true, false, false);
1846 if (parser->tok != ',') {
1847 if (parser->tok != ')') {
1849 parseerror(parser, "expected comma after parameter index");
1852 /* vararg piping: ...(start) */
1853 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1857 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1859 parseerror(parser, "expected typename for vararg");
1863 typevar = parse_typename(parser, NULL, NULL);
1869 if (parser->tok != ')') {
1871 ast_delete(typevar);
1872 parseerror(parser, "expected closing paren");
1876 if (funtype->expression.varparam &&
1877 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1881 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1882 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1883 compile_error(ast_ctx(typevar),
1884 "function was declared to take varargs of type `%s`, requested type is: %s",
1888 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1889 ast_type_adopt(out, typevar);
1890 ast_delete(typevar);
1894 static ast_expression* parse_vararg(parser_t *parser)
1896 bool old_noops = parser->lex->flags.noops;
1898 ast_expression *out;
1900 parser->lex->flags.noops = true;
1901 out = parse_vararg_do(parser);
1903 parser->lex->flags.noops = old_noops;
1907 /* not to be exposed */
1908 extern bool ftepp_predef_exists(const char *name);
1910 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1912 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1913 parser->tok == TOKEN_IDENT &&
1914 !strcmp(parser_tokval(parser), "_"))
1916 /* a translatable string */
1919 parser->lex->flags.noops = true;
1920 if (!parser_next(parser) || parser->tok != '(') {
1921 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1924 parser->lex->flags.noops = false;
1925 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1926 parseerror(parser, "expected a constant string in translatable-string extension");
1929 val = parser_const_string(parser, parser_tokval(parser), true);
1932 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1934 if (!parser_next(parser) || parser->tok != ')') {
1935 parseerror(parser, "expected closing paren after translatable string");
1940 else if (parser->tok == TOKEN_DOTS)
1943 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1944 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1947 va = parse_vararg(parser);
1950 vec_push(sy->out, syexp(parser_ctx(parser), va));
1953 else if (parser->tok == TOKEN_FLOATCONST) {
1955 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1958 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1961 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1963 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1966 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1969 else if (parser->tok == TOKEN_STRINGCONST) {
1971 val = parser_const_string(parser, parser_tokval(parser), false);
1974 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1977 else if (parser->tok == TOKEN_VECTORCONST) {
1979 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1982 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1985 else if (parser->tok == TOKEN_IDENT)
1987 const char *ctoken = parser_tokval(parser);
1988 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1989 ast_expression *var;
1990 /* a_vector.{x,y,z} */
1991 if (!vec_size(sy->ops) ||
1992 !vec_last(sy->ops).etype ||
1993 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1994 (prev >= intrinsic_debug_typestring &&
1995 prev <= intrinsic_debug_typestring))
1997 /* When adding more intrinsics, fix the above condition */
2000 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
2002 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
2004 var = parser_find_var(parser, parser_tokval(parser));
2006 var = parser_find_field(parser, parser_tokval(parser));
2008 if (!var && with_labels) {
2009 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
2011 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
2012 var = (ast_expression*)lbl;
2013 vec_push(parser->labels, lbl);
2016 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
2017 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
2020 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
2021 var = (ast_expression*)intrinsic_debug_typestring;
2023 /* now we try for the real intrinsic hashtable. If the string
2024 * begins with __builtin, we simply skip past it, otherwise we
2025 * use the identifier as is.
2027 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
2028 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
2032 char *correct = NULL;
2036 * sometimes people use preprocessing predefs without enabling them
2037 * i've done this thousands of times already myself. Lets check for
2038 * it in the predef table. And diagnose it better :)
2040 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
2041 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
2046 * TODO: determine the best score for the identifier: be it
2047 * a variable, a field.
2049 * We should also consider adding correction tables for
2050 * other things as well.
2052 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
2054 correct_init(&corr);
2056 for (i = 0; i < vec_size(parser->correct_variables); i++) {
2057 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
2058 if (strcmp(correct, parser_tokval(parser))) {
2065 correct_free(&corr);
2068 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
2073 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
2079 if (ast_istype(var, ast_value)) {
2080 ((ast_value*)var)->uses++;
2082 else if (ast_istype(var, ast_member)) {
2083 ast_member *mem = (ast_member*)var;
2084 if (ast_istype(mem->owner, ast_value))
2085 ((ast_value*)(mem->owner))->uses++;
2088 vec_push(sy->out, syexp(parser_ctx(parser), var));
2091 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2095 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2097 ast_expression *expr = NULL;
2100 bool wantop = false;
2101 /* only warn once about an assignment in a truth value because the current code
2102 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2104 bool warn_truthvalue = true;
2106 /* count the parens because an if starts with one, so the
2107 * end of a condition is an unmatched closing paren
2111 memset(&sy, 0, sizeof(sy));
2113 parser->lex->flags.noops = false;
2115 parser_reclassify_token(parser);
2119 if (parser->tok == TOKEN_TYPENAME) {
2120 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
2124 if (parser->tok == TOKEN_OPERATOR)
2126 /* classify the operator */
2127 const oper_info *op;
2128 const oper_info *olast = NULL;
2130 for (o = 0; o < operator_count; ++o) {
2131 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2132 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2133 !strcmp(parser_tokval(parser), operators[o].op))
2138 if (o == operator_count) {
2139 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2142 /* found an operator */
2145 /* when declaring variables, a comma starts a new variable */
2146 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2147 /* fixup the token */
2152 /* a colon without a pervious question mark cannot be a ternary */
2153 if (!ternaries && op->id == opid2(':','?')) {
2158 if (op->id == opid1(',')) {
2159 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2160 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2164 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2165 olast = &operators[vec_last(sy.ops).etype-1];
2167 #define IsAssignOp(x) (\
2168 (x) == opid1('=') || \
2169 (x) == opid2('+','=') || \
2170 (x) == opid2('-','=') || \
2171 (x) == opid2('*','=') || \
2172 (x) == opid2('/','=') || \
2173 (x) == opid2('%','=') || \
2174 (x) == opid2('&','=') || \
2175 (x) == opid2('|','=') || \
2176 (x) == opid3('&','~','=') \
2178 if (warn_truthvalue) {
2179 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2180 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2181 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2184 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2185 warn_truthvalue = false;
2190 (op->prec < olast->prec) ||
2191 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2193 if (!parser_sy_apply_operator(parser, &sy))
2195 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2196 olast = &operators[vec_last(sy.ops).etype-1];
2201 if (op->id == opid1('(')) {
2203 size_t sycount = vec_size(sy.out);
2204 /* we expected an operator, this is the function-call operator */
2205 vec_push(sy.paren, PAREN_FUNC);
2206 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2207 vec_push(sy.argc, 0);
2209 vec_push(sy.paren, PAREN_EXPR);
2210 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2213 } else if (op->id == opid1('[')) {
2215 parseerror(parser, "unexpected array subscript");
2218 vec_push(sy.paren, PAREN_INDEX);
2219 /* push both the operator and the paren, this makes life easier */
2220 vec_push(sy.ops, syop(parser_ctx(parser), op));
2221 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2223 } else if (op->id == opid2('?',':')) {
2224 vec_push(sy.ops, syop(parser_ctx(parser), op));
2225 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2228 vec_push(sy.paren, PAREN_TERNARY1);
2229 } else if (op->id == opid2(':','?')) {
2230 if (!vec_size(sy.paren)) {
2231 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2234 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2235 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2238 if (!parser_close_paren(parser, &sy))
2240 vec_push(sy.ops, syop(parser_ctx(parser), op));
2244 vec_push(sy.ops, syop(parser_ctx(parser), op));
2245 wantop = !!(op->flags & OP_SUFFIX);
2248 else if (parser->tok == ')') {
2249 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2250 if (!parser_sy_apply_operator(parser, &sy))
2253 if (!vec_size(sy.paren))
2256 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2257 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2260 if (!parser_close_paren(parser, &sy))
2263 /* must be a function call without parameters */
2264 if (vec_last(sy.paren) != PAREN_FUNC) {
2265 parseerror(parser, "closing paren in invalid position");
2268 if (!parser_close_paren(parser, &sy))
2273 else if (parser->tok == '(') {
2274 parseerror(parser, "internal error: '(' should be classified as operator");
2277 else if (parser->tok == '[') {
2278 parseerror(parser, "internal error: '[' should be classified as operator");
2281 else if (parser->tok == ']') {
2282 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2283 if (!parser_sy_apply_operator(parser, &sy))
2286 if (!vec_size(sy.paren))
2288 if (vec_last(sy.paren) != PAREN_INDEX) {
2289 parseerror(parser, "mismatched parentheses, unexpected ']'");
2292 if (!parser_close_paren(parser, &sy))
2297 if (!parse_sya_operand(parser, &sy, with_labels))
2300 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2301 vec_last(sy.argc)++;
2306 /* in this case we might want to allow constant string concatenation */
2307 bool concatenated = false;
2308 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2309 ast_expression *lexpr = vec_last(sy.out).out;
2310 if (ast_istype(lexpr, ast_value)) {
2311 ast_value *last = (ast_value*)lexpr;
2312 if (last->isimm == true && last->cvq == CV_CONST &&
2313 last->hasvalue && last->expression.vtype == TYPE_STRING)
2315 char *newstr = NULL;
2316 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2317 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2319 concatenated = true;
2323 if (!concatenated) {
2324 parseerror(parser, "expected operator or end of statement");
2329 if (!parser_next(parser)) {
2332 if (parser->tok == ';' ||
2333 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2334 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2340 while (vec_size(sy.ops)) {
2341 if (!parser_sy_apply_operator(parser, &sy))
2345 parser->lex->flags.noops = true;
2346 if (vec_size(sy.out) != 1) {
2347 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2350 expr = sy.out[0].out;
2353 if (vec_size(sy.paren)) {
2354 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2362 parser->lex->flags.noops = true;
2363 for (i = 0; i < vec_size(sy.out); ++i) {
2365 ast_unref(sy.out[i].out);
2374 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2376 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2379 if (parser->tok != ';') {
2380 parseerror(parser, "semicolon expected after expression");
2384 if (!parser_next(parser)) {
2391 static void parser_enterblock(parser_t *parser)
2393 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2394 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2395 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2396 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2397 vec_push(parser->_block_ctx, parser_ctx(parser));
2400 vec_push(parser->correct_variables, correct_trie_new());
2401 vec_push(parser->correct_variables_score, NULL);
2404 static bool parser_leaveblock(parser_t *parser)
2407 size_t locals, typedefs;
2409 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2410 parseerror(parser, "internal error: parser_leaveblock with no block");
2414 util_htdel(vec_last(parser->variables));
2415 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2417 vec_pop(parser->variables);
2418 vec_pop(parser->correct_variables);
2419 vec_pop(parser->correct_variables_score);
2420 if (!vec_size(parser->_blocklocals)) {
2421 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2425 locals = vec_last(parser->_blocklocals);
2426 vec_pop(parser->_blocklocals);
2427 while (vec_size(parser->_locals) != locals) {
2428 ast_expression *e = vec_last(parser->_locals);
2429 ast_value *v = (ast_value*)e;
2430 vec_pop(parser->_locals);
2431 if (ast_istype(e, ast_value) && !v->uses) {
2432 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2437 typedefs = vec_last(parser->_blocktypedefs);
2438 while (vec_size(parser->_typedefs) != typedefs) {
2439 ast_delete(vec_last(parser->_typedefs));
2440 vec_pop(parser->_typedefs);
2442 util_htdel(vec_last(parser->typedefs));
2443 vec_pop(parser->typedefs);
2445 vec_pop(parser->_block_ctx);
2450 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2452 vec_push(parser->_locals, e);
2453 util_htset(vec_last(parser->variables), name, (void*)e);
2457 vec_last(parser->correct_variables),
2458 &vec_last(parser->correct_variables_score),
2463 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2465 vec_push(parser->globals, e);
2466 util_htset(parser->htglobals, name, e);
2470 parser->correct_variables[0],
2471 &parser->correct_variables_score[0],
2476 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2480 ast_expression *prev;
2482 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2484 ast_type_to_string(cond, ty, sizeof(ty));
2485 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2488 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2491 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2494 parseerror(parser, "internal error: failed to process condition");
2499 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2501 /* vector types need to be cast to true booleans */
2502 ast_binary *bin = (ast_binary*)cond;
2503 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2505 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2507 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2510 parseerror(parser, "internal error: failed to process condition");
2517 unary = (ast_unary*)cond;
2518 /* ast_istype dereferences cond, should test here for safety */
2519 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2521 cond = unary->operand;
2522 unary->operand = NULL;
2525 unary = (ast_unary*)cond;
2529 parseerror(parser, "internal error: failed to process condition");
2531 if (ifnot) *_ifnot = !*_ifnot;
2535 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2538 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2541 lex_ctx ctx = parser_ctx(parser);
2543 (void)block; /* not touching */
2545 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2546 if (!parser_next(parser)) {
2547 parseerror(parser, "expected condition or 'not'");
2550 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2552 if (!parser_next(parser)) {
2553 parseerror(parser, "expected condition in parenthesis");
2557 if (parser->tok != '(') {
2558 parseerror(parser, "expected 'if' condition in parenthesis");
2561 /* parse into the expression */
2562 if (!parser_next(parser)) {
2563 parseerror(parser, "expected 'if' condition after opening paren");
2566 /* parse the condition */
2567 cond = parse_expression_leave(parser, false, true, false);
2571 if (parser->tok != ')') {
2572 parseerror(parser, "expected closing paren after 'if' condition");
2576 /* parse into the 'then' branch */
2577 if (!parser_next(parser)) {
2578 parseerror(parser, "expected statement for on-true branch of 'if'");
2582 if (!parse_statement_or_block(parser, &ontrue)) {
2587 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2588 /* check for an else */
2589 if (!strcmp(parser_tokval(parser), "else")) {
2590 /* parse into the 'else' branch */
2591 if (!parser_next(parser)) {
2592 parseerror(parser, "expected on-false branch after 'else'");
2597 if (!parse_statement_or_block(parser, &onfalse)) {
2604 cond = process_condition(parser, cond, &ifnot);
2606 if (ontrue) ast_delete(ontrue);
2607 if (onfalse) ast_delete(onfalse);
2612 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2614 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2615 *out = (ast_expression*)ifthen;
2619 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2620 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2625 /* skip the 'while' and get the body */
2626 if (!parser_next(parser)) {
2627 if (OPTS_FLAG(LOOP_LABELS))
2628 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2630 parseerror(parser, "expected 'while' condition in parenthesis");
2634 if (parser->tok == ':') {
2635 if (!OPTS_FLAG(LOOP_LABELS))
2636 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2637 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2638 parseerror(parser, "expected loop label");
2641 label = util_strdup(parser_tokval(parser));
2642 if (!parser_next(parser)) {
2644 parseerror(parser, "expected 'while' condition in parenthesis");
2649 if (parser->tok != '(') {
2650 parseerror(parser, "expected 'while' condition in parenthesis");
2654 vec_push(parser->breaks, label);
2655 vec_push(parser->continues, label);
2657 rv = parse_while_go(parser, block, out);
2660 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2661 parseerror(parser, "internal error: label stack corrupted");
2667 vec_pop(parser->breaks);
2668 vec_pop(parser->continues);
2673 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2676 ast_expression *cond, *ontrue;
2680 lex_ctx ctx = parser_ctx(parser);
2682 (void)block; /* not touching */
2684 /* parse into the expression */
2685 if (!parser_next(parser)) {
2686 parseerror(parser, "expected 'while' condition after opening paren");
2689 /* parse the condition */
2690 cond = parse_expression_leave(parser, false, true, false);
2694 if (parser->tok != ')') {
2695 parseerror(parser, "expected closing paren after 'while' condition");
2699 /* parse into the 'then' branch */
2700 if (!parser_next(parser)) {
2701 parseerror(parser, "expected while-loop body");
2705 if (!parse_statement_or_block(parser, &ontrue)) {
2710 cond = process_condition(parser, cond, &ifnot);
2715 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2716 *out = (ast_expression*)aloop;
2720 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2721 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2726 /* skip the 'do' and get the body */
2727 if (!parser_next(parser)) {
2728 if (OPTS_FLAG(LOOP_LABELS))
2729 parseerror(parser, "expected loop label or body");
2731 parseerror(parser, "expected loop body");
2735 if (parser->tok == ':') {
2736 if (!OPTS_FLAG(LOOP_LABELS))
2737 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2738 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2739 parseerror(parser, "expected loop label");
2742 label = util_strdup(parser_tokval(parser));
2743 if (!parser_next(parser)) {
2745 parseerror(parser, "expected loop body");
2750 vec_push(parser->breaks, label);
2751 vec_push(parser->continues, label);
2753 rv = parse_dowhile_go(parser, block, out);
2756 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2757 parseerror(parser, "internal error: label stack corrupted");
2760 * Test for NULL otherwise ast_delete dereferences null pointer
2768 vec_pop(parser->breaks);
2769 vec_pop(parser->continues);
2774 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2777 ast_expression *cond, *ontrue;
2781 lex_ctx ctx = parser_ctx(parser);
2783 (void)block; /* not touching */
2785 if (!parse_statement_or_block(parser, &ontrue))
2788 /* expect the "while" */
2789 if (parser->tok != TOKEN_KEYWORD ||
2790 strcmp(parser_tokval(parser), "while"))
2792 parseerror(parser, "expected 'while' and condition");
2797 /* skip the 'while' and check for opening paren */
2798 if (!parser_next(parser) || parser->tok != '(') {
2799 parseerror(parser, "expected 'while' condition in parenthesis");
2803 /* parse into the expression */
2804 if (!parser_next(parser)) {
2805 parseerror(parser, "expected 'while' condition after opening paren");
2809 /* parse the condition */
2810 cond = parse_expression_leave(parser, false, true, false);
2814 if (parser->tok != ')') {
2815 parseerror(parser, "expected closing paren after 'while' condition");
2821 if (!parser_next(parser) || parser->tok != ';') {
2822 parseerror(parser, "expected semicolon after condition");
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "parse error");
2835 cond = process_condition(parser, cond, &ifnot);
2840 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2841 *out = (ast_expression*)aloop;
2845 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2846 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2851 /* skip the 'for' and check for opening paren */
2852 if (!parser_next(parser)) {
2853 if (OPTS_FLAG(LOOP_LABELS))
2854 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2856 parseerror(parser, "expected 'for' expressions in parenthesis");
2860 if (parser->tok == ':') {
2861 if (!OPTS_FLAG(LOOP_LABELS))
2862 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2863 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2864 parseerror(parser, "expected loop label");
2867 label = util_strdup(parser_tokval(parser));
2868 if (!parser_next(parser)) {
2870 parseerror(parser, "expected 'for' expressions in parenthesis");
2875 if (parser->tok != '(') {
2876 parseerror(parser, "expected 'for' expressions in parenthesis");
2880 vec_push(parser->breaks, label);
2881 vec_push(parser->continues, label);
2883 rv = parse_for_go(parser, block, out);
2886 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2887 parseerror(parser, "internal error: label stack corrupted");
2893 vec_pop(parser->breaks);
2894 vec_pop(parser->continues);
2898 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2901 ast_expression *initexpr, *cond, *increment, *ontrue;
2906 lex_ctx ctx = parser_ctx(parser);
2908 parser_enterblock(parser);
2915 /* parse into the expression */
2916 if (!parser_next(parser)) {
2917 parseerror(parser, "expected 'for' initializer after opening paren");
2922 if (parser->tok == TOKEN_IDENT)
2923 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2925 if (typevar || parser->tok == TOKEN_TYPENAME) {
2927 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2928 if (parsewarning(parser, WARN_EXTENSIONS,
2929 "current standard does not allow variable declarations in for-loop initializers"))
2933 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2936 else if (parser->tok != ';')
2938 initexpr = parse_expression_leave(parser, false, false, false);
2943 /* move on to condition */
2944 if (parser->tok != ';') {
2945 parseerror(parser, "expected semicolon after for-loop initializer");
2948 if (!parser_next(parser)) {
2949 parseerror(parser, "expected for-loop condition");
2953 /* parse the condition */
2954 if (parser->tok != ';') {
2955 cond = parse_expression_leave(parser, false, true, false);
2960 /* move on to incrementor */
2961 if (parser->tok != ';') {
2962 parseerror(parser, "expected semicolon after for-loop initializer");
2965 if (!parser_next(parser)) {
2966 parseerror(parser, "expected for-loop condition");
2970 /* parse the incrementor */
2971 if (parser->tok != ')') {
2972 lex_ctx condctx = parser_ctx(parser);
2973 increment = parse_expression_leave(parser, false, false, false);
2976 if (!ast_side_effects(increment)) {
2977 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2983 if (parser->tok != ')') {
2984 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2987 /* parse into the 'then' branch */
2988 if (!parser_next(parser)) {
2989 parseerror(parser, "expected for-loop body");
2992 if (!parse_statement_or_block(parser, &ontrue))
2996 cond = process_condition(parser, cond, &ifnot);
3000 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
3001 *out = (ast_expression*)aloop;
3003 if (!parser_leaveblock(parser)) {
3009 if (initexpr) ast_unref(initexpr);
3010 if (cond) ast_unref(cond);
3011 if (increment) ast_unref(increment);
3012 (void)!parser_leaveblock(parser);
3016 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
3018 ast_expression *exp = NULL;
3019 ast_expression *var = NULL;
3020 ast_return *ret = NULL;
3021 ast_value *retval = parser->function->return_value;
3022 ast_value *expected = parser->function->vtype;
3024 lex_ctx ctx = parser_ctx(parser);
3026 (void)block; /* not touching */
3028 if (!parser_next(parser)) {
3029 parseerror(parser, "expected return expression");
3033 /* return assignments */
3034 if (parser->tok == '=') {
3035 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
3036 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
3040 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
3042 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
3043 parseerror(parser, "invalid return type: `%s'", ty1);
3047 if (!parser_next(parser)) {
3048 parseerror(parser, "expected return assignment expression");
3052 if (!(exp = parse_expression_leave(parser, false, false, false)))
3055 /* prepare the return value */
3057 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
3058 ast_type_adopt(retval, expected->expression.next);
3059 parser->function->return_value = retval;
3062 if (!ast_compare_type(exp, (ast_expression*)retval)) {
3063 char ty1[1024], ty2[1024];
3064 ast_type_to_string(exp, ty1, sizeof(ty1));
3065 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
3066 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
3069 /* store to 'return' local variable */
3070 var = (ast_expression*)ast_store_new(
3072 type_store_instr[expected->expression.next->vtype],
3073 (ast_expression*)retval, exp);
3080 if (parser->tok != ';')
3081 parseerror(parser, "missing semicolon after return assignment");
3082 else if (!parser_next(parser))
3083 parseerror(parser, "parse error after return assignment");
3089 if (parser->tok != ';') {
3090 exp = parse_expression(parser, false, false);
3094 if (exp->vtype != TYPE_NIL &&
3095 exp->vtype != ((ast_expression*)expected)->next->vtype)
3097 parseerror(parser, "return with invalid expression");
3100 ret = ast_return_new(ctx, exp);
3106 if (!parser_next(parser))
3107 parseerror(parser, "parse error");
3109 if (!retval && expected->expression.next->vtype != TYPE_VOID)
3111 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3113 ret = ast_return_new(ctx, (ast_expression*)retval);
3115 *out = (ast_expression*)ret;
3119 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3122 unsigned int levels = 0;
3123 lex_ctx ctx = parser_ctx(parser);
3124 const char **loops = (is_continue ? parser->continues : parser->breaks);
3126 (void)block; /* not touching */
3127 if (!parser_next(parser)) {
3128 parseerror(parser, "expected semicolon or loop label");
3132 if (!vec_size(loops)) {
3134 parseerror(parser, "`continue` can only be used inside loops");
3136 parseerror(parser, "`break` can only be used inside loops or switches");
3139 if (parser->tok == TOKEN_IDENT) {
3140 if (!OPTS_FLAG(LOOP_LABELS))
3141 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3142 i = vec_size(loops);
3144 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3147 parseerror(parser, "no such loop to %s: `%s`",
3148 (is_continue ? "continue" : "break out of"),
3149 parser_tokval(parser));
3154 if (!parser_next(parser)) {
3155 parseerror(parser, "expected semicolon");
3160 if (parser->tok != ';') {
3161 parseerror(parser, "expected semicolon");
3165 if (!parser_next(parser))
3166 parseerror(parser, "parse error");
3168 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3172 /* returns true when it was a variable qualifier, false otherwise!
3173 * on error, cvq is set to CV_WRONG
3175 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3177 bool had_const = false;
3178 bool had_var = false;
3179 bool had_noref = false;
3180 bool had_attrib = false;
3181 bool had_static = false;
3186 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3188 /* parse an attribute */
3189 if (!parser_next(parser)) {
3190 parseerror(parser, "expected attribute after `[[`");
3194 if (!strcmp(parser_tokval(parser), "noreturn")) {
3195 flags |= AST_FLAG_NORETURN;
3196 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3197 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3202 else if (!strcmp(parser_tokval(parser), "noref")) {
3204 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3205 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3210 else if (!strcmp(parser_tokval(parser), "inline")) {
3211 flags |= AST_FLAG_INLINE;
3212 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3213 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3218 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3219 flags |= AST_FLAG_ALIAS;
3222 if (!parser_next(parser)) {
3223 parseerror(parser, "parse error in attribute");
3227 if (parser->tok == '(') {
3228 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3229 parseerror(parser, "`alias` attribute missing parameter");
3233 *message = util_strdup(parser_tokval(parser));
3235 if (!parser_next(parser)) {
3236 parseerror(parser, "parse error in attribute");
3240 if (parser->tok != ')') {
3241 parseerror(parser, "`alias` attribute expected `)` after parameter");
3245 if (!parser_next(parser)) {
3246 parseerror(parser, "parse error in attribute");
3251 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3252 parseerror(parser, "`alias` attribute expected `]]`");
3256 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3257 flags |= AST_FLAG_DEPRECATED;
3260 if (!parser_next(parser)) {
3261 parseerror(parser, "parse error in attribute");
3265 if (parser->tok == '(') {
3266 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3267 parseerror(parser, "`deprecated` attribute missing parameter");
3271 *message = util_strdup(parser_tokval(parser));
3273 if (!parser_next(parser)) {
3274 parseerror(parser, "parse error in attribute");
3278 if(parser->tok != ')') {
3279 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3283 if (!parser_next(parser)) {
3284 parseerror(parser, "parse error in attribute");
3289 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3290 parseerror(parser, "`deprecated` attribute expected `]]`");
3293 if (*message) mem_d(*message);
3301 /* Skip tokens until we hit a ]] */
3302 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3303 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3304 if (!parser_next(parser)) {
3305 parseerror(parser, "error inside attribute");
3312 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3314 else if (!strcmp(parser_tokval(parser), "const"))
3316 else if (!strcmp(parser_tokval(parser), "var"))
3318 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3320 else if (!strcmp(parser_tokval(parser), "noref"))
3322 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3327 if (!parser_next(parser))
3337 *is_static = had_static;
3341 parseerror(parser, "parse error after variable qualifier");
3346 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3347 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3352 /* skip the 'while' and get the body */
3353 if (!parser_next(parser)) {
3354 if (OPTS_FLAG(LOOP_LABELS))
3355 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3357 parseerror(parser, "expected 'switch' operand in parenthesis");
3361 if (parser->tok == ':') {
3362 if (!OPTS_FLAG(LOOP_LABELS))
3363 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3364 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3365 parseerror(parser, "expected loop label");
3368 label = util_strdup(parser_tokval(parser));
3369 if (!parser_next(parser)) {
3371 parseerror(parser, "expected 'switch' operand in parenthesis");
3376 if (parser->tok != '(') {
3377 parseerror(parser, "expected 'switch' operand in parenthesis");
3381 vec_push(parser->breaks, label);
3383 rv = parse_switch_go(parser, block, out);
3386 if (vec_last(parser->breaks) != label) {
3387 parseerror(parser, "internal error: label stack corrupted");
3393 vec_pop(parser->breaks);
3398 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3400 ast_expression *operand;
3403 ast_switch *switchnode;
3404 ast_switch_case swcase;
3407 bool noref, is_static;
3408 uint32_t qflags = 0;
3410 lex_ctx ctx = parser_ctx(parser);
3412 (void)block; /* not touching */
3415 /* parse into the expression */
3416 if (!parser_next(parser)) {
3417 parseerror(parser, "expected switch operand");
3420 /* parse the operand */
3421 operand = parse_expression_leave(parser, false, false, false);
3425 switchnode = ast_switch_new(ctx, operand);
3428 if (parser->tok != ')') {
3429 ast_delete(switchnode);
3430 parseerror(parser, "expected closing paren after 'switch' operand");
3434 /* parse over the opening paren */
3435 if (!parser_next(parser) || parser->tok != '{') {
3436 ast_delete(switchnode);
3437 parseerror(parser, "expected list of cases");
3441 if (!parser_next(parser)) {
3442 ast_delete(switchnode);
3443 parseerror(parser, "expected 'case' or 'default'");
3447 /* new block; allow some variables to be declared here */
3448 parser_enterblock(parser);
3451 if (parser->tok == TOKEN_IDENT)
3452 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3453 if (typevar || parser->tok == TOKEN_TYPENAME) {
3454 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3455 ast_delete(switchnode);
3460 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3462 if (cvq == CV_WRONG) {
3463 ast_delete(switchnode);
3466 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3467 ast_delete(switchnode);
3476 while (parser->tok != '}') {
3477 ast_block *caseblock;
3479 if (!strcmp(parser_tokval(parser), "case")) {
3480 if (!parser_next(parser)) {
3481 ast_delete(switchnode);
3482 parseerror(parser, "expected expression for case");
3485 swcase.value = parse_expression_leave(parser, false, false, false);
3486 if (!swcase.value) {
3487 ast_delete(switchnode);
3488 parseerror(parser, "expected expression for case");
3491 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3492 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3493 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3499 else if (!strcmp(parser_tokval(parser), "default")) {
3500 swcase.value = NULL;
3501 if (!parser_next(parser)) {
3502 ast_delete(switchnode);
3503 parseerror(parser, "expected colon");
3508 ast_delete(switchnode);
3509 parseerror(parser, "expected 'case' or 'default'");
3513 /* Now the colon and body */
3514 if (parser->tok != ':') {
3515 if (swcase.value) ast_unref(swcase.value);
3516 ast_delete(switchnode);
3517 parseerror(parser, "expected colon");
3521 if (!parser_next(parser)) {
3522 if (swcase.value) ast_unref(swcase.value);
3523 ast_delete(switchnode);
3524 parseerror(parser, "expected statements or case");
3527 caseblock = ast_block_new(parser_ctx(parser));
3529 if (swcase.value) ast_unref(swcase.value);
3530 ast_delete(switchnode);
3533 swcase.code = (ast_expression*)caseblock;
3534 vec_push(switchnode->cases, swcase);
3536 ast_expression *expr;
3537 if (parser->tok == '}')
3539 if (parser->tok == TOKEN_KEYWORD) {
3540 if (!strcmp(parser_tokval(parser), "case") ||
3541 !strcmp(parser_tokval(parser), "default"))
3546 if (!parse_statement(parser, caseblock, &expr, true)) {
3547 ast_delete(switchnode);
3552 if (!ast_block_add_expr(caseblock, expr)) {
3553 ast_delete(switchnode);
3559 parser_leaveblock(parser);
3562 if (parser->tok != '}') {
3563 ast_delete(switchnode);
3564 parseerror(parser, "expected closing paren of case list");
3567 if (!parser_next(parser)) {
3568 ast_delete(switchnode);
3569 parseerror(parser, "parse error after switch");
3572 *out = (ast_expression*)switchnode;
3576 /* parse computed goto sides */
3577 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3578 ast_expression *on_true;
3579 ast_expression *on_false;
3580 ast_expression *cond;
3585 if (ast_istype(*side, ast_ternary)) {
3586 ast_ternary *tern = (ast_ternary*)*side;
3587 on_true = parse_goto_computed(parser, &tern->on_true);
3588 on_false = parse_goto_computed(parser, &tern->on_false);
3590 if (!on_true || !on_false) {
3591 parseerror(parser, "expected label or expression in ternary");
3592 if (on_true) ast_unref(on_true);
3593 if (on_false) ast_unref(on_false);
3601 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3602 } else if (ast_istype(*side, ast_label)) {
3603 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3604 ast_goto_set_label(gt, ((ast_label*)*side));
3606 return (ast_expression*)gt;
3611 static bool parse_goto(parser_t *parser, ast_expression **out)
3613 ast_goto *gt = NULL;
3614 ast_expression *lbl;
3616 if (!parser_next(parser))
3619 if (parser->tok != TOKEN_IDENT) {
3620 ast_expression *expression;
3622 /* could be an expression i.e computed goto :-) */
3623 if (parser->tok != '(') {
3624 parseerror(parser, "expected label name after `goto`");
3628 /* failed to parse expression for goto */
3629 if (!(expression = parse_expression(parser, false, true)) ||
3630 !(*out = parse_goto_computed(parser, &expression))) {
3631 parseerror(parser, "invalid goto expression");
3633 ast_unref(expression);
3640 /* not computed goto */
3641 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3642 lbl = parser_find_label(parser, gt->name);
3644 if (!ast_istype(lbl, ast_label)) {
3645 parseerror(parser, "internal error: label is not an ast_label");
3649 ast_goto_set_label(gt, (ast_label*)lbl);
3652 vec_push(parser->gotos, gt);
3654 if (!parser_next(parser) || parser->tok != ';') {
3655 parseerror(parser, "semicolon expected after goto label");
3658 if (!parser_next(parser)) {
3659 parseerror(parser, "parse error after goto");
3663 *out = (ast_expression*)gt;
3667 static bool parse_skipwhite(parser_t *parser)
3670 if (!parser_next(parser))
3672 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3673 return parser->tok < TOKEN_ERROR;
3676 static bool parse_eol(parser_t *parser)
3678 if (!parse_skipwhite(parser))
3680 return parser->tok == TOKEN_EOL;
3683 static bool parse_pragma_do(parser_t *parser)
3685 if (!parser_next(parser) ||
3686 parser->tok != TOKEN_IDENT ||
3687 strcmp(parser_tokval(parser), "pragma"))
3689 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3692 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3693 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3697 if (!strcmp(parser_tokval(parser), "noref")) {
3698 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3699 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3702 parser->noref = !!parser_token(parser)->constval.i;
3703 if (!parse_eol(parser)) {
3704 parseerror(parser, "parse error after `noref` pragma");
3710 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3717 static bool parse_pragma(parser_t *parser)
3720 parser->lex->flags.preprocessing = true;
3721 parser->lex->flags.mergelines = true;
3722 rv = parse_pragma_do(parser);
3723 if (parser->tok != TOKEN_EOL) {
3724 parseerror(parser, "junk after pragma");
3727 parser->lex->flags.preprocessing = false;
3728 parser->lex->flags.mergelines = false;
3729 if (!parser_next(parser)) {
3730 parseerror(parser, "parse error after pragma");
3736 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3738 bool noref, is_static;
3740 uint32_t qflags = 0;
3741 ast_value *typevar = NULL;
3742 char *vstring = NULL;
3746 if (parser->tok == TOKEN_IDENT)
3747 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3749 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3751 /* local variable */
3753 parseerror(parser, "cannot declare a variable from here");
3756 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3757 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3760 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3764 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3766 if (cvq == CV_WRONG)
3768 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3770 else if (parser->tok == TOKEN_KEYWORD)
3772 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3777 if (!parser_next(parser)) {
3778 parseerror(parser, "parse error after __builtin_debug_printtype");
3782 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3784 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3785 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3786 if (!parser_next(parser)) {
3787 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3793 if (!parse_statement(parser, block, out, allow_cases))
3796 con_out("__builtin_debug_printtype: got no output node\n");
3799 ast_type_to_string(*out, ty, sizeof(ty));
3800 con_out("__builtin_debug_printtype: `%s`\n", ty);
3805 else if (!strcmp(parser_tokval(parser), "return"))
3807 return parse_return(parser, block, out);
3809 else if (!strcmp(parser_tokval(parser), "if"))
3811 return parse_if(parser, block, out);
3813 else if (!strcmp(parser_tokval(parser), "while"))
3815 return parse_while(parser, block, out);
3817 else if (!strcmp(parser_tokval(parser), "do"))
3819 return parse_dowhile(parser, block, out);
3821 else if (!strcmp(parser_tokval(parser), "for"))
3823 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3824 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3827 return parse_for(parser, block, out);
3829 else if (!strcmp(parser_tokval(parser), "break"))
3831 return parse_break_continue(parser, block, out, false);
3833 else if (!strcmp(parser_tokval(parser), "continue"))
3835 return parse_break_continue(parser, block, out, true);
3837 else if (!strcmp(parser_tokval(parser), "switch"))
3839 return parse_switch(parser, block, out);
3841 else if (!strcmp(parser_tokval(parser), "case") ||
3842 !strcmp(parser_tokval(parser), "default"))
3845 parseerror(parser, "unexpected 'case' label");
3850 else if (!strcmp(parser_tokval(parser), "goto"))
3852 return parse_goto(parser, out);
3854 else if (!strcmp(parser_tokval(parser), "typedef"))
3856 if (!parser_next(parser)) {
3857 parseerror(parser, "expected type definition after 'typedef'");
3860 return parse_typedef(parser);
3862 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3865 else if (parser->tok == '{')
3868 inner = parse_block(parser);
3871 *out = (ast_expression*)inner;
3874 else if (parser->tok == ':')
3878 if (!parser_next(parser)) {
3879 parseerror(parser, "expected label name");
3882 if (parser->tok != TOKEN_IDENT) {
3883 parseerror(parser, "label must be an identifier");
3886 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3888 if (!label->undefined) {
3889 parseerror(parser, "label `%s` already defined", label->name);
3892 label->undefined = false;
3895 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3896 vec_push(parser->labels, label);
3898 *out = (ast_expression*)label;
3899 if (!parser_next(parser)) {
3900 parseerror(parser, "parse error after label");
3903 for (i = 0; i < vec_size(parser->gotos); ++i) {
3904 if (!strcmp(parser->gotos[i]->name, label->name)) {
3905 ast_goto_set_label(parser->gotos[i], label);
3906 vec_remove(parser->gotos, i, 1);
3912 else if (parser->tok == ';')
3914 if (!parser_next(parser)) {
3915 parseerror(parser, "parse error after empty statement");
3922 lex_ctx ctx = parser_ctx(parser);
3923 ast_expression *exp = parse_expression(parser, false, false);
3927 if (!ast_side_effects(exp)) {
3928 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3935 static bool parse_enum(parser_t *parser)
3938 bool reverse = false;
3940 ast_value **values = NULL;
3941 ast_value *var = NULL;
3944 ast_expression *old;
3946 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3947 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3951 /* enumeration attributes (can add more later) */
3952 if (parser->tok == ':') {
3953 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3954 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3959 if (!strcmp(parser_tokval(parser), "flag")) {
3963 else if (!strcmp(parser_tokval(parser), "reverse")) {
3967 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3971 if (!parser_next(parser) || parser->tok != '{') {
3972 parseerror(parser, "expected `{` after enum attribute ");
3978 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3979 if (parser->tok == '}') {
3980 /* allow an empty enum */
3983 parseerror(parser, "expected identifier or `}`");
3987 old = parser_find_field(parser, parser_tokval(parser));
3989 old = parser_find_global(parser, parser_tokval(parser));
3991 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3992 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3996 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3997 vec_push(values, var);
3998 var->cvq = CV_CONST;
3999 var->hasvalue = true;
4001 /* for flagged enumerations increment in POTs of TWO */
4002 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
4003 parser_addglobal(parser, var->name, (ast_expression*)var);
4005 if (!parser_next(parser)) {
4006 parseerror(parser, "expected `=`, `}` or comma after identifier");
4010 if (parser->tok == ',')
4012 if (parser->tok == '}')
4014 if (parser->tok != '=') {
4015 parseerror(parser, "expected `=`, `}` or comma after identifier");
4019 if (!parser_next(parser)) {
4020 parseerror(parser, "expected expression after `=`");
4024 /* We got a value! */
4025 old = parse_expression_leave(parser, true, false, false);
4026 asvalue = (ast_value*)old;
4027 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4028 compile_error(ast_ctx(var), "constant value or expression expected");
4031 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4033 if (parser->tok == '}')
4035 if (parser->tok != ',') {
4036 parseerror(parser, "expected `}` or comma after expression");
4041 /* patch them all (for reversed attribute) */
4044 for (i = 0; i < vec_size(values); i++)
4045 values[i]->constval.vfloat = vec_size(values) - i - 1;
4048 if (parser->tok != '}') {
4049 parseerror(parser, "internal error: breaking without `}`");
4053 if (!parser_next(parser) || parser->tok != ';') {
4054 parseerror(parser, "expected semicolon after enumeration");
4058 if (!parser_next(parser)) {
4059 parseerror(parser, "parse error after enumeration");
4071 static bool parse_block_into(parser_t *parser, ast_block *block)
4075 parser_enterblock(parser);
4077 if (!parser_next(parser)) { /* skip the '{' */
4078 parseerror(parser, "expected function body");
4082 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4084 ast_expression *expr = NULL;
4085 if (parser->tok == '}')
4088 if (!parse_statement(parser, block, &expr, false)) {
4089 /* parseerror(parser, "parse error"); */
4095 if (!ast_block_add_expr(block, expr)) {
4102 if (parser->tok != '}') {
4105 (void)parser_next(parser);
4109 if (!parser_leaveblock(parser))
4111 return retval && !!block;
4114 static ast_block* parse_block(parser_t *parser)
4117 block = ast_block_new(parser_ctx(parser));
4120 if (!parse_block_into(parser, block)) {
4121 ast_block_delete(block);
4127 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4129 if (parser->tok == '{') {
4130 *out = (ast_expression*)parse_block(parser);
4133 return parse_statement(parser, NULL, out, false);
4136 static bool create_vector_members(ast_value *var, ast_member **me)
4139 size_t len = strlen(var->name);
4141 for (i = 0; i < 3; ++i) {
4142 char *name = (char*)mem_a(len+3);
4143 memcpy(name, var->name, len);
4145 name[len+1] = 'x'+i;
4147 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4156 do { ast_member_delete(me[--i]); } while(i);
4160 static bool parse_function_body(parser_t *parser, ast_value *var)
4162 ast_block *block = NULL;
4167 ast_expression *framenum = NULL;
4168 ast_expression *nextthink = NULL;
4169 /* None of the following have to be deleted */
4170 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4171 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4172 bool has_frame_think;
4176 has_frame_think = false;
4177 old = parser->function;
4179 if (var->expression.flags & AST_FLAG_ALIAS) {
4180 parseerror(parser, "function aliases cannot have bodies");
4184 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4185 parseerror(parser, "gotos/labels leaking");
4189 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4190 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4191 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4197 if (parser->tok == '[') {
4198 /* got a frame definition: [ framenum, nextthink ]
4199 * this translates to:
4200 * self.frame = framenum;
4201 * self.nextthink = time + 0.1;
4202 * self.think = nextthink;
4206 fld_think = parser_find_field(parser, "think");
4207 fld_nextthink = parser_find_field(parser, "nextthink");
4208 fld_frame = parser_find_field(parser, "frame");
4209 if (!fld_think || !fld_nextthink || !fld_frame) {
4210 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4211 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4214 gbl_time = parser_find_global(parser, "time");
4215 gbl_self = parser_find_global(parser, "self");
4216 if (!gbl_time || !gbl_self) {
4217 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4218 parseerror(parser, "please declare the following globals: `time`, `self`");
4222 if (!parser_next(parser))
4225 framenum = parse_expression_leave(parser, true, false, false);
4227 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4230 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4231 ast_unref(framenum);
4232 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4236 if (parser->tok != ',') {
4237 ast_unref(framenum);
4238 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4239 parseerror(parser, "Got a %i\n", parser->tok);
4243 if (!parser_next(parser)) {
4244 ast_unref(framenum);
4248 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4250 /* qc allows the use of not-yet-declared functions here
4251 * - this automatically creates a prototype */
4252 ast_value *thinkfunc;
4253 ast_expression *functype = fld_think->next;
4255 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4256 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4257 ast_unref(framenum);
4258 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4261 ast_type_adopt(thinkfunc, functype);
4263 if (!parser_next(parser)) {
4264 ast_unref(framenum);
4265 ast_delete(thinkfunc);
4269 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4271 nextthink = (ast_expression*)thinkfunc;
4274 nextthink = parse_expression_leave(parser, true, false, false);
4276 ast_unref(framenum);
4277 parseerror(parser, "expected a think-function in [frame,think] notation");
4282 if (!ast_istype(nextthink, ast_value)) {
4283 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4287 if (retval && parser->tok != ']') {
4288 parseerror(parser, "expected closing `]` for [frame,think] notation");
4292 if (retval && !parser_next(parser)) {
4296 if (retval && parser->tok != '{') {
4297 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4302 ast_unref(nextthink);
4303 ast_unref(framenum);
4307 has_frame_think = true;
4310 block = ast_block_new(parser_ctx(parser));
4312 parseerror(parser, "failed to allocate block");
4313 if (has_frame_think) {
4314 ast_unref(nextthink);
4315 ast_unref(framenum);
4320 if (has_frame_think) {
4322 ast_expression *self_frame;
4323 ast_expression *self_nextthink;
4324 ast_expression *self_think;
4325 ast_expression *time_plus_1;
4326 ast_store *store_frame;
4327 ast_store *store_nextthink;
4328 ast_store *store_think;
4330 ctx = parser_ctx(parser);
4331 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4332 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4333 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4335 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4336 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4338 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4339 if (self_frame) ast_delete(self_frame);
4340 if (self_nextthink) ast_delete(self_nextthink);
4341 if (self_think) ast_delete(self_think);
4342 if (time_plus_1) ast_delete(time_plus_1);
4348 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4349 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4350 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4353 ast_delete(self_frame);
4356 if (!store_nextthink) {
4357 ast_delete(self_nextthink);
4361 ast_delete(self_think);
4365 if (store_frame) ast_delete(store_frame);
4366 if (store_nextthink) ast_delete(store_nextthink);
4367 if (store_think) ast_delete(store_think);
4370 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4371 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4372 !ast_block_add_expr(block, (ast_expression*)store_think))
4379 parseerror(parser, "failed to generate code for [frame,think]");
4380 ast_unref(nextthink);
4381 ast_unref(framenum);
4387 if (var->hasvalue) {
4388 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4389 ast_block_delete(block);
4393 func = ast_function_new(ast_ctx(var), var->name, var);
4395 parseerror(parser, "failed to allocate function for `%s`", var->name);
4396 ast_block_delete(block);
4399 vec_push(parser->functions, func);
4401 parser_enterblock(parser);
4403 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4405 ast_value *param = var->expression.params[parami];
4408 if (param->expression.vtype != TYPE_VECTOR &&
4409 (param->expression.vtype != TYPE_FIELD ||
4410 param->expression.next->vtype != TYPE_VECTOR))
4415 if (!create_vector_members(param, me)) {
4416 ast_block_delete(block);
4420 for (e = 0; e < 3; ++e) {
4421 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4422 ast_block_collect(block, (ast_expression*)me[e]);
4426 if (var->argcounter) {
4427 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4428 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4432 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4434 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4435 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4436 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4437 varargs->expression.count = 0;
4438 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4439 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4440 ast_delete(varargs);
4441 ast_block_delete(block);
4444 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4445 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4446 ast_delete(varargs);
4447 ast_block_delete(block);
4450 func->varargs = varargs;
4452 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4455 parser->function = func;
4456 if (!parse_block_into(parser, block)) {
4457 ast_block_delete(block);
4461 vec_push(func->blocks, block);
4464 parser->function = old;
4465 if (!parser_leaveblock(parser))
4467 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4468 parseerror(parser, "internal error: local scopes left");
4472 if (parser->tok == ';')
4473 return parser_next(parser);
4474 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4475 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4479 (void)!parser_leaveblock(parser);
4480 vec_pop(parser->functions);
4481 ast_function_delete(func);
4482 var->constval.vfunc = NULL;
4485 parser->function = old;
4489 static ast_expression *array_accessor_split(
4494 ast_expression *left,
4495 ast_expression *right
4501 lex_ctx ctx = ast_ctx(array);
4503 if (!left || !right) {
4504 if (left) ast_delete(left);
4505 if (right) ast_delete(right);
4509 cmp = ast_binary_new(ctx, INSTR_LT,
4510 (ast_expression*)index,
4511 (ast_expression*)parser_const_float(parser, middle));
4515 parseerror(parser, "internal error: failed to create comparison for array setter");
4519 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4521 ast_delete(cmp); /* will delete left and right */
4522 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4526 return (ast_expression*)ifthen;
4529 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4531 lex_ctx ctx = ast_ctx(array);
4533 if (from+1 == afterend) {
4534 /* set this value */
4537 ast_array_index *subscript;
4539 int assignop = type_store_instr[value->expression.vtype];
4541 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4542 assignop = INSTR_STORE_V;
4544 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4548 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4550 ast_delete(subscript);
4554 block = ast_block_new(ctx);
4560 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4565 ret = ast_return_new(ctx, NULL);
4571 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4576 return (ast_expression*)block;
4578 ast_expression *left, *right;
4579 size_t diff = afterend - from;
4580 size_t middle = from + diff/2;
4581 left = array_setter_node(parser, array, index, value, from, middle);
4582 right = array_setter_node(parser, array, index, value, middle, afterend);
4583 return array_accessor_split(parser, array, index, middle, left, right);
4587 static ast_expression *array_field_setter_node(
4596 lex_ctx ctx = ast_ctx(array);
4598 if (from+1 == afterend) {
4599 /* set this value */
4602 ast_entfield *entfield;
4603 ast_array_index *subscript;
4605 int assignop = type_storep_instr[value->expression.vtype];
4607 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4608 assignop = INSTR_STOREP_V;
4610 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4614 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4615 subscript->expression.vtype = TYPE_FIELD;
4617 entfield = ast_entfield_new_force(ctx,
4618 (ast_expression*)entity,
4619 (ast_expression*)subscript,
4620 (ast_expression*)subscript);
4622 ast_delete(subscript);
4626 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4628 ast_delete(entfield);
4632 block = ast_block_new(ctx);
4638 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4643 ret = ast_return_new(ctx, NULL);
4649 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4654 return (ast_expression*)block;
4656 ast_expression *left, *right;
4657 size_t diff = afterend - from;
4658 size_t middle = from + diff/2;
4659 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4660 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4661 return array_accessor_split(parser, array, index, middle, left, right);
4665 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4667 lex_ctx ctx = ast_ctx(array);
4669 if (from+1 == afterend) {
4671 ast_array_index *subscript;
4673 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4677 ret = ast_return_new(ctx, (ast_expression*)subscript);
4679 ast_delete(subscript);
4683 return (ast_expression*)ret;
4685 ast_expression *left, *right;
4686 size_t diff = afterend - from;
4687 size_t middle = from + diff/2;
4688 left = array_getter_node(parser, array, index, from, middle);
4689 right = array_getter_node(parser, array, index, middle, afterend);
4690 return array_accessor_split(parser, array, index, middle, left, right);
4694 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4696 ast_function *func = NULL;
4697 ast_value *fval = NULL;
4698 ast_block *body = NULL;
4700 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4702 parseerror(parser, "failed to create accessor function value");
4706 func = ast_function_new(ast_ctx(array), funcname, fval);
4709 parseerror(parser, "failed to create accessor function node");
4713 body = ast_block_new(ast_ctx(array));
4715 parseerror(parser, "failed to create block for array accessor");
4721 vec_push(func->blocks, body);
4724 vec_push(parser->accessors, fval);
4729 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4731 ast_value *index = NULL;
4732 ast_value *value = NULL;
4736 if (!ast_istype(array->expression.next, ast_value)) {
4737 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4741 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4743 func = fval->constval.vfunc;
4744 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4746 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4747 value = ast_value_copy((ast_value*)array->expression.next);
4749 if (!index || !value) {
4750 parseerror(parser, "failed to create locals for array accessor");
4753 (void)!ast_value_set_name(value, "value"); /* not important */
4754 vec_push(fval->expression.params, index);
4755 vec_push(fval->expression.params, value);
4757 array->setter = fval;
4760 if (index) ast_delete(index);
4761 if (value) ast_delete(value);
4767 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4769 ast_expression *root = NULL;
4770 root = array_setter_node(parser, array,
4771 array->setter->expression.params[0],
4772 array->setter->expression.params[1],
4773 0, array->expression.count);
4775 parseerror(parser, "failed to build accessor search tree");
4778 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4785 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4787 if (!parser_create_array_setter_proto(parser, array, funcname))
4789 return parser_create_array_setter_impl(parser, array);
4792 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4794 ast_expression *root = NULL;
4795 ast_value *entity = NULL;
4796 ast_value *index = NULL;
4797 ast_value *value = NULL;
4801 if (!ast_istype(array->expression.next, ast_value)) {
4802 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4806 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4808 func = fval->constval.vfunc;
4809 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4811 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4812 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4813 value = ast_value_copy((ast_value*)array->expression.next);
4814 if (!entity || !index || !value) {
4815 parseerror(parser, "failed to create locals for array accessor");
4818 (void)!ast_value_set_name(value, "value"); /* not important */
4819 vec_push(fval->expression.params, entity);
4820 vec_push(fval->expression.params, index);
4821 vec_push(fval->expression.params, value);
4823 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4825 parseerror(parser, "failed to build accessor search tree");
4829 array->setter = fval;
4830 return ast_block_add_expr(func->blocks[0], root);
4832 if (entity) ast_delete(entity);
4833 if (index) ast_delete(index);
4834 if (value) ast_delete(value);
4835 if (root) ast_delete(root);
4841 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4843 ast_value *index = NULL;
4847 /* NOTE: checking array->expression.next rather than elemtype since
4848 * for fields elemtype is a temporary fieldtype.
4850 if (!ast_istype(array->expression.next, ast_value)) {
4851 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4855 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4857 func = fval->constval.vfunc;
4858 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4860 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4863 parseerror(parser, "failed to create locals for array accessor");
4866 vec_push(fval->expression.params, index);
4868 array->getter = fval;
4871 if (index) ast_delete(index);
4877 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4879 ast_expression *root = NULL;
4881 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4883 parseerror(parser, "failed to build accessor search tree");
4886 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4893 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4895 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4897 return parser_create_array_getter_impl(parser, array);
4900 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4901 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4909 bool variadic = false;
4910 ast_value *varparam = NULL;
4911 char *argcounter = NULL;
4913 ctx = parser_ctx(parser);
4915 /* for the sake of less code we parse-in in this function */
4916 if (!parser_next(parser)) {
4918 parseerror(parser, "expected parameter list");
4924 /* parse variables until we hit a closing paren */
4925 while (parser->tok != ')') {
4927 /* there must be commas between them */
4928 if (parser->tok != ',') {
4929 parseerror(parser, "expected comma or end of parameter list");
4932 if (!parser_next(parser)) {
4933 parseerror(parser, "expected parameter");
4939 if (parser->tok == TOKEN_DOTS) {
4940 /* '...' indicates a varargs function */
4942 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4943 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4946 if (parser->tok == TOKEN_IDENT) {
4947 argcounter = util_strdup(parser_tokval(parser));
4948 if (!parser_next(parser) || parser->tok != ')') {
4949 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4956 /* for anything else just parse a typename */
4957 param = parse_typename(parser, NULL, NULL);
4960 vec_push(params, param);
4961 if (param->expression.vtype >= TYPE_VARIANT) {
4962 char tname[1024]; /* typename is reserved in C++ */
4963 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4964 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4967 /* type-restricted varargs */
4968 if (parser->tok == TOKEN_DOTS) {
4970 varparam = vec_last(params);
4972 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4973 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4976 if (parser->tok == TOKEN_IDENT) {
4977 argcounter = util_strdup(parser_tokval(parser));
4978 if (!parser_next(parser) || parser->tok != ')') {
4979 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4987 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4991 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4992 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4995 if (!parser_next(parser)) {
4996 parseerror(parser, "parse error after typename");
5000 /* now turn 'var' into a function type */
5001 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
5002 fval->expression.next = (ast_expression*)var;
5004 fval->expression.flags |= AST_FLAG_VARIADIC;
5007 var->expression.params = params;
5008 var->expression.varparam = (ast_expression*)varparam;
5009 var->argcounter = argcounter;
5018 ast_delete(varparam);
5020 for (i = 0; i < vec_size(params); ++i)
5021 ast_delete(params[i]);
5026 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5028 ast_expression *cexp;
5029 ast_value *cval, *tmp;
5032 ctx = parser_ctx(parser);
5034 if (!parser_next(parser)) {
5036 parseerror(parser, "expected array-size");
5040 if (parser->tok != ']') {
5041 cexp = parse_expression_leave(parser, true, false, false);
5043 if (!cexp || !ast_istype(cexp, ast_value)) {
5047 parseerror(parser, "expected array-size as constant positive integer");
5050 cval = (ast_value*)cexp;
5057 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5058 tmp->expression.next = (ast_expression*)var;
5062 if (cval->expression.vtype == TYPE_INTEGER)
5063 tmp->expression.count = cval->constval.vint;
5064 else if (cval->expression.vtype == TYPE_FLOAT)
5065 tmp->expression.count = cval->constval.vfloat;
5069 parseerror(parser, "array-size must be a positive integer constant");
5075 var->expression.count = -1;
5076 var->expression.flags |= AST_FLAG_ARRAY_INIT;
5079 if (parser->tok != ']') {
5081 parseerror(parser, "expected ']' after array-size");
5084 if (!parser_next(parser)) {
5086 parseerror(parser, "error after parsing array size");
5092 /* Parse a complete typename.
5093 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5094 * but when parsing variables separated by comma
5095 * 'storebase' should point to where the base-type should be kept.
5096 * The base type makes up every bit of type information which comes *before* the
5099 * The following will be parsed in its entirety:
5101 * The 'basetype' in this case is 'void()'
5102 * and if there's a comma after it, say:
5104 * then the type-information 'void()' can be stored in 'storebase'
5106 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5108 ast_value *var, *tmp;
5111 const char *name = NULL;
5112 bool isfield = false;
5113 bool wasarray = false;
5114 size_t morefields = 0;
5116 ctx = parser_ctx(parser);
5118 /* types may start with a dot */
5119 if (parser->tok == '.') {
5121 /* if we parsed a dot we need a typename now */
5122 if (!parser_next(parser)) {
5123 parseerror(parser, "expected typename for field definition");
5127 /* Further dots are handled seperately because they won't be part of the
5130 while (parser->tok == '.') {
5132 if (!parser_next(parser)) {
5133 parseerror(parser, "expected typename for field definition");
5138 if (parser->tok == TOKEN_IDENT)
5139 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5140 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5141 parseerror(parser, "expected typename");
5145 /* generate the basic type value */
5146 if (cached_typedef) {
5147 var = ast_value_copy(cached_typedef);
5148 ast_value_set_name(var, "<type(from_def)>");
5150 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5152 for (; morefields; --morefields) {
5153 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5154 tmp->expression.next = (ast_expression*)var;
5158 /* do not yet turn into a field - remember:
5159 * .void() foo; is a field too
5160 * .void()() foo; is a function
5164 if (!parser_next(parser)) {
5166 parseerror(parser, "parse error after typename");
5170 /* an opening paren now starts the parameter-list of a function
5171 * this is where original-QC has parameter lists.
5172 * We allow a single parameter list here.
5173 * Much like fteqcc we don't allow `float()() x`
5175 if (parser->tok == '(') {
5176 var = parse_parameter_list(parser, var);
5181 /* store the base if requested */
5183 *storebase = ast_value_copy(var);
5185 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5186 tmp->expression.next = (ast_expression*)*storebase;
5191 /* there may be a name now */
5192 if (parser->tok == TOKEN_IDENT) {
5193 name = util_strdup(parser_tokval(parser));
5195 if (!parser_next(parser)) {
5198 parseerror(parser, "error after variable or field declaration");
5203 /* now this may be an array */
5204 if (parser->tok == '[') {
5206 var = parse_arraysize(parser, var);
5208 if (name) mem_d(name);
5213 /* This is the point where we can turn it into a field */
5215 /* turn it into a field if desired */
5216 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5217 tmp->expression.next = (ast_expression*)var;
5221 /* now there may be function parens again */
5222 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5223 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5224 if (parser->tok == '(' && wasarray)
5225 parseerror(parser, "arrays as part of a return type is not supported");
5226 while (parser->tok == '(') {
5227 var = parse_parameter_list(parser, var);
5229 if (name) mem_d(name);
5234 /* finally name it */
5236 if (!ast_value_set_name(var, name)) {
5239 parseerror(parser, "internal error: failed to set name");
5242 /* free the name, ast_value_set_name duplicates */
5249 static bool parse_typedef(parser_t *parser)
5251 ast_value *typevar, *oldtype;
5252 ast_expression *old;
5254 typevar = parse_typename(parser, NULL, NULL);
5259 if ( (old = parser_find_var(parser, typevar->name)) ) {
5260 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5261 " -> `%s` has been declared here: %s:%i",
5262 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5263 ast_delete(typevar);
5267 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5268 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5269 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5270 ast_delete(typevar);
5274 vec_push(parser->_typedefs, typevar);
5275 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5277 if (parser->tok != ';') {
5278 parseerror(parser, "expected semicolon after typedef");
5281 if (!parser_next(parser)) {
5282 parseerror(parser, "parse error after typedef");
5289 static const char *cvq_to_str(int cvq) {
5291 case CV_NONE: return "none";
5292 case CV_VAR: return "`var`";
5293 case CV_CONST: return "`const`";
5294 default: return "<INVALID>";
5298 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5301 if (proto->cvq != var->cvq) {
5302 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5303 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5304 parser->tok == '='))
5306 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5307 "`%s` declared with different qualifiers: %s\n"
5308 " -> previous declaration here: %s:%i uses %s",
5309 var->name, cvq_to_str(var->cvq),
5310 ast_ctx(proto).file, ast_ctx(proto).line,
5311 cvq_to_str(proto->cvq));
5314 av = (var ->expression.flags & AST_FLAG_NORETURN);
5315 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5317 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5318 "`%s` declared with different attributes%s\n"
5319 " -> previous declaration here: %s:%i",
5320 var->name, (av ? ": noreturn" : ""),
5321 ast_ctx(proto).file, ast_ctx(proto).line,
5322 (ao ? ": noreturn" : ""));
5327 static bool create_array_accessors(parser_t *parser, ast_value *var)
5330 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5331 if (!parser_create_array_setter(parser, var, name))
5333 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5334 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5339 static bool parse_array(parser_t *parser, ast_value *array)
5342 if (array->initlist) {
5343 parseerror(parser, "array already initialized elsewhere");
5346 if (!parser_next(parser)) {
5347 parseerror(parser, "parse error in array initializer");
5351 while (parser->tok != '}') {
5352 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5355 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5357 parseerror(parser, "initializing element must be a compile time constant");
5360 vec_push(array->initlist, v->constval);
5361 if (v->expression.vtype == TYPE_STRING) {
5362 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5366 if (parser->tok == '}')
5368 if (parser->tok != ',' || !parser_next(parser)) {
5369 parseerror(parser, "expected comma or '}' in element list");
5373 if (!parser_next(parser) || parser->tok != ';') {
5374 parseerror(parser, "expected semicolon after initializer, got %s");
5378 if (!parser_next(parser)) {
5379 parseerror(parser, "parse error after initializer");
5384 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5385 if (array->expression.count != (size_t)-1) {
5386 parseerror(parser, "array `%s' has already been initialized with %u elements",
5387 array->name, (unsigned)array->expression.count);
5389 array->expression.count = vec_size(array->initlist);
5390 if (!create_array_accessors(parser, array))
5396 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)
5400 ast_expression *old;
5404 ast_value *basetype = NULL;
5406 bool isparam = false;
5407 bool isvector = false;
5408 bool cleanvar = true;
5409 bool wasarray = false;
5411 ast_member *me[3] = { NULL, NULL, NULL };
5413 if (!localblock && is_static)
5414 parseerror(parser, "`static` qualifier is not supported in global scope");
5416 /* get the first complete variable */
5417 var = parse_typename(parser, &basetype, cached_typedef);
5420 ast_delete(basetype);
5428 /* Part 0: finish the type */
5429 if (parser->tok == '(') {
5430 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5431 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5432 var = parse_parameter_list(parser, var);
5438 /* we only allow 1-dimensional arrays */
5439 if (parser->tok == '[') {
5441 var = parse_arraysize(parser, var);
5447 if (parser->tok == '(' && wasarray) {
5448 parseerror(parser, "arrays as part of a return type is not supported");
5449 /* we'll still parse the type completely for now */
5451 /* for functions returning functions */
5452 while (parser->tok == '(') {
5453 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5454 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5455 var = parse_parameter_list(parser, var);
5462 var->cvq = qualifier;
5463 var->expression.flags |= qflags;
5466 * store the vstring back to var for alias and
5467 * deprecation messages.
5469 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5470 var->expression.flags & AST_FLAG_ALIAS)
5471 var->desc = vstring;
5474 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5475 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5476 * is then filled with the previous definition and the parameter-names replaced.
5478 if (!strcmp(var->name, "nil")) {
5479 if (OPTS_FLAG(UNTYPED_NIL)) {
5480 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5481 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5483 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5486 /* Deal with end_sys_ vars */
5488 if (!strcmp(var->name, "end_sys_globals")) {
5490 parser->crc_globals = vec_size(parser->globals);
5493 else if (!strcmp(var->name, "end_sys_fields")) {
5495 parser->crc_fields = vec_size(parser->fields);
5498 if (was_end && var->expression.vtype == TYPE_FIELD) {
5499 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5500 "global '%s' hint should not be a field",
5501 parser_tokval(parser)))
5508 if (!nofields && var->expression.vtype == TYPE_FIELD)
5510 /* deal with field declarations */
5511 old = parser_find_field(parser, var->name);
5513 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5514 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5523 parseerror(parser, "field `%s` already declared here: %s:%i",
5524 var->name, ast_ctx(old).file, ast_ctx(old).line);
5529 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5530 (old = parser_find_global(parser, var->name)))
5532 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5533 parseerror(parser, "field `%s` already declared here: %s:%i",
5534 var->name, ast_ctx(old).file, ast_ctx(old).line);
5541 /* deal with other globals */
5542 old = parser_find_global(parser, var->name);
5543 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5545 /* This is a function which had a prototype */
5546 if (!ast_istype(old, ast_value)) {
5547 parseerror(parser, "internal error: prototype is not an ast_value");
5551 proto = (ast_value*)old;
5552 proto->desc = var->desc;
5553 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5554 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5556 ast_ctx(proto).file, ast_ctx(proto).line);
5560 /* we need the new parameter-names */
5561 for (i = 0; i < vec_size(proto->expression.params); ++i)
5562 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5563 if (!parser_check_qualifiers(parser, var, proto)) {
5570 proto->expression.flags |= var->expression.flags;
5578 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5579 "global `%s` already declared here: %s:%i",
5580 var->name, ast_ctx(old).file, ast_ctx(old).line))
5585 proto = (ast_value*)old;
5586 if (!ast_istype(old, ast_value)) {
5587 parseerror(parser, "internal error: not an ast_value");
5592 if (!parser_check_qualifiers(parser, var, proto)) {
5597 proto->expression.flags |= var->expression.flags;
5601 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5602 (old = parser_find_field(parser, var->name)))
5604 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5605 parseerror(parser, "global `%s` already declared here: %s:%i",
5606 var->name, ast_ctx(old).file, ast_ctx(old).line);
5613 else /* it's not a global */
5615 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5616 if (old && !isparam) {
5617 parseerror(parser, "local `%s` already declared here: %s:%i",
5618 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5622 old = parser_find_local(parser, var->name, 0, &isparam);
5623 if (old && isparam) {
5624 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5625 "local `%s` is shadowing a parameter", var->name))
5627 parseerror(parser, "local `%s` already declared here: %s:%i",
5628 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5632 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5640 /* in a noref section we simply bump the usecount */
5641 if (noref || parser->noref)
5645 * Create the global/local, and deal with vector types.
5648 if (var->expression.vtype == TYPE_VECTOR)
5650 else if (var->expression.vtype == TYPE_FIELD &&
5651 var->expression.next->vtype == TYPE_VECTOR)
5655 if (!create_vector_members(var, me)) {
5662 /* deal with global variables, fields, functions */
5663 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5664 var->isfield = true;
5665 vec_push(parser->fields, (ast_expression*)var);
5666 util_htset(parser->htfields, var->name, var);
5668 for (i = 0; i < 3; ++i) {
5669 vec_push(parser->fields, (ast_expression*)me[i]);
5670 util_htset(parser->htfields, me[i]->name, me[i]);
5675 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5676 parser_addglobal(parser, var->name, (ast_expression*)var);
5678 for (i = 0; i < 3; ++i) {
5679 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5683 ast_expression *find = parser_find_global(parser, var->desc);
5686 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5690 if (var->expression.vtype != find->vtype) {
5694 ast_type_to_string(find, ty1, sizeof(ty1));
5695 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5697 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5704 * add alias to aliases table and to corrector
5705 * so corrections can apply for aliases as well.
5707 util_htset(parser->aliases, var->name, find);
5710 * add to corrector so corrections can work
5711 * even for aliases too.
5714 vec_last(parser->correct_variables),
5715 &vec_last(parser->correct_variables_score),
5719 /* generate aliases for vector components */
5723 util_asprintf(&buffer[0], "%s_x", var->desc);
5724 util_asprintf(&buffer[1], "%s_y", var->desc);
5725 util_asprintf(&buffer[2], "%s_z", var->desc);
5727 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5728 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5729 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5736 * add to corrector so corrections can work
5737 * even for aliases too.
5740 vec_last(parser->correct_variables),
5741 &vec_last(parser->correct_variables_score),
5745 vec_last(parser->correct_variables),
5746 &vec_last(parser->correct_variables_score),
5750 vec_last(parser->correct_variables),
5751 &vec_last(parser->correct_variables_score),
5759 /* a static adds itself to be generated like any other global
5760 * but is added to the local namespace instead
5762 char *defname = NULL;
5763 size_t prefix_len, ln;
5765 ln = strlen(parser->function->name);
5766 vec_append(defname, ln, parser->function->name);
5768 vec_append(defname, 2, "::");
5769 /* remember the length up to here */
5770 prefix_len = vec_size(defname);
5772 /* Add it to the local scope */
5773 util_htset(vec_last(parser->variables), var->name, (void*)var);
5777 vec_last(parser->correct_variables),
5778 &vec_last(parser->correct_variables_score),
5782 /* now rename the global */
5783 ln = strlen(var->name);
5784 vec_append(defname, ln, var->name);
5785 ast_value_set_name(var, defname);
5787 /* push it to the to-be-generated globals */
5788 vec_push(parser->globals, (ast_expression*)var);
5790 /* same game for the vector members */
5792 for (i = 0; i < 3; ++i) {
5793 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5797 vec_last(parser->correct_variables),
5798 &vec_last(parser->correct_variables_score),
5802 vec_shrinkto(defname, prefix_len);
5803 ln = strlen(me[i]->name);
5804 vec_append(defname, ln, me[i]->name);
5805 ast_member_set_name(me[i], defname);
5807 vec_push(parser->globals, (ast_expression*)me[i]);
5812 vec_push(localblock->locals, var);
5813 parser_addlocal(parser, var->name, (ast_expression*)var);
5815 for (i = 0; i < 3; ++i) {
5816 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5817 ast_block_collect(localblock, (ast_expression*)me[i]);
5823 me[0] = me[1] = me[2] = NULL;
5828 if (var->expression.vtype == TYPE_ARRAY) {
5829 if (var->expression.count != (size_t)-1) {
5830 if (!create_array_accessors(parser, var))
5834 else if (!localblock && !nofields &&
5835 var->expression.vtype == TYPE_FIELD &&
5836 var->expression.next->vtype == TYPE_ARRAY)
5839 ast_expression *telem;
5841 ast_value *array = (ast_value*)var->expression.next;
5843 if (!ast_istype(var->expression.next, ast_value)) {
5844 parseerror(parser, "internal error: field element type must be an ast_value");
5848 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5849 if (!parser_create_array_field_setter(parser, array, name))
5852 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5853 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5854 tfield->expression.next = telem;
5855 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5856 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5864 if (parser->tok == ';') {
5865 ast_delete(basetype);
5866 if (!parser_next(parser)) {
5867 parseerror(parser, "error after variable declaration");
5873 if (parser->tok == ',')
5877 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5880 parseerror(parser, "missing comma or semicolon while parsing variables");
5884 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5885 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5886 "initializing expression turns variable `%s` into a constant in this standard",
5893 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5894 if (parser->tok != '=') {
5895 if (!strcmp(parser_tokval(parser), "break")) {
5896 if (!parser_next(parser)) {
5897 parseerror(parser, "error parsing break definition");
5900 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5902 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5907 if (!parser_next(parser)) {
5908 parseerror(parser, "error parsing initializer");
5912 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5913 parseerror(parser, "expected '=' before function body in this standard");
5916 if (parser->tok == '#') {
5917 ast_function *func = NULL;
5918 ast_value *number = NULL;
5924 parseerror(parser, "cannot declare builtins within functions");
5927 if (var->expression.vtype != TYPE_FUNCTION) {
5928 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5931 if (!parser_next(parser)) {
5932 parseerror(parser, "expected builtin number");
5936 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5937 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5939 parseerror(parser, "builtin number expected");
5942 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5945 parseerror(parser, "builtin number must be a compile time constant");
5948 if (number->expression.vtype == TYPE_INTEGER)
5949 builtin_num = number->constval.vint;
5950 else if (number->expression.vtype == TYPE_FLOAT)
5951 builtin_num = number->constval.vfloat;
5954 parseerror(parser, "builtin number must be an integer constant");
5959 fractional = modff(builtin_num, &integral);
5960 if (builtin_num < 0 || fractional != 0) {
5961 parseerror(parser, "builtin number must be an integer greater than zero");
5965 /* we only want the integral part anyways */
5966 builtin_num = integral;
5967 } else if (parser->tok == TOKEN_INTCONST) {
5968 builtin_num = parser_token(parser)->constval.i;
5970 parseerror(parser, "builtin number must be a compile time constant");
5974 if (var->hasvalue) {
5975 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5976 "builtin `%s` has already been defined\n"
5977 " -> previous declaration here: %s:%i",
5978 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5982 func = ast_function_new(ast_ctx(var), var->name, var);
5984 parseerror(parser, "failed to allocate function for `%s`", var->name);
5987 vec_push(parser->functions, func);
5989 func->builtin = -builtin_num-1;
5992 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5993 ? (parser->tok != ',' && parser->tok != ';')
5994 : (!parser_next(parser)))
5996 parseerror(parser, "expected comma or semicolon");
5998 ast_function_delete(func);
5999 var->constval.vfunc = NULL;
6003 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
6006 /* Note that fteqcc and most others don't even *have*
6007 * local arrays, so this is not a high priority.
6009 parseerror(parser, "TODO: initializers for local arrays");
6013 var->hasvalue = true;
6014 if (!parse_array(parser, var))
6017 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
6020 parseerror(parser, "cannot declare functions within functions");
6025 ast_ctx(proto) = parser_ctx(parser);
6027 if (!parse_function_body(parser, var))
6029 ast_delete(basetype);
6030 for (i = 0; i < vec_size(parser->gotos); ++i)
6031 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
6032 vec_free(parser->gotos);
6033 vec_free(parser->labels);
6036 ast_expression *cexp;
6039 cexp = parse_expression_leave(parser, true, false, false);
6044 cval = (ast_value*)cexp;
6045 if (cval != parser->nil &&
6046 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
6049 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
6053 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
6054 qualifier != CV_VAR)
6056 var->cvq = CV_CONST;
6058 if (cval == parser->nil)
6059 var->expression.flags |= AST_FLAG_INITIALIZED;
6062 var->hasvalue = true;
6063 if (cval->expression.vtype == TYPE_STRING)
6064 var->constval.vstring = parser_strdup(cval->constval.vstring);
6065 else if (cval->expression.vtype == TYPE_FIELD)
6066 var->constval.vfield = cval;
6068 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
6074 shunt sy = { NULL, NULL, NULL, NULL };
6077 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
6078 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
6079 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
6080 if (!parser_sy_apply_operator(parser, &sy))
6083 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
6084 parseerror(parser, "internal error: leaked operands");
6085 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
6096 if (parser->tok == ',') {
6097 if (!parser_next(parser)) {
6098 parseerror(parser, "expected another variable");
6102 if (parser->tok != TOKEN_IDENT) {
6103 parseerror(parser, "expected another variable");
6106 var = ast_value_copy(basetype);
6108 ast_value_set_name(var, parser_tokval(parser));
6109 if (!parser_next(parser)) {
6110 parseerror(parser, "error parsing variable declaration");
6116 if (parser->tok != ';') {
6117 parseerror(parser, "missing semicolon after variables");
6121 if (!parser_next(parser)) {
6122 parseerror(parser, "parse error after variable declaration");
6126 ast_delete(basetype);
6130 if (cleanvar && var)
6132 ast_delete(basetype);
6136 ast_delete(basetype);
6137 if (cleanvar && var)
6139 if (me[0]) ast_member_delete(me[0]);
6140 if (me[1]) ast_member_delete(me[1]);
6141 if (me[2]) ast_member_delete(me[2]);
6145 static bool parser_global_statement(parser_t *parser)
6149 bool is_static = false;
6150 uint32_t qflags = 0;
6151 ast_value *istype = NULL;
6152 char *vstring = NULL;
6154 if (parser->tok == TOKEN_IDENT)
6155 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6157 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6159 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6161 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6163 if (cvq == CV_WRONG)
6165 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6167 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6169 return parse_enum(parser);
6171 else if (parser->tok == TOKEN_KEYWORD)
6173 if (!strcmp(parser_tokval(parser), "typedef")) {
6174 if (!parser_next(parser)) {
6175 parseerror(parser, "expected type definition after 'typedef'");
6178 return parse_typedef(parser);
6180 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6183 else if (parser->tok == '#')
6185 return parse_pragma(parser);
6187 else if (parser->tok == '$')
6189 if (!parser_next(parser)) {
6190 parseerror(parser, "parse error");
6196 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6202 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6204 return util_crc16(old, str, strlen(str));
6207 static void progdefs_crc_file(const char *str)
6209 /* write to progdefs.h here */
6213 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6215 old = progdefs_crc_sum(old, str);
6216 progdefs_crc_file(str);
6220 static void generate_checksum(parser_t *parser, ir_builder *ir)
6222 uint16_t crc = 0xFFFF;
6226 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6227 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6229 progdefs_crc_file("\tint\tpad;\n");
6230 progdefs_crc_file("\tint\tofs_return[3];\n");
6231 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6232 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6233 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6234 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6235 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6236 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6237 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6238 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6240 for (i = 0; i < parser->crc_globals; ++i) {
6241 if (!ast_istype(parser->globals[i], ast_value))
6243 value = (ast_value*)(parser->globals[i]);
6244 switch (value->expression.vtype) {
6245 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6246 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6247 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6248 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6250 crc = progdefs_crc_both(crc, "\tint\t");
6253 crc = progdefs_crc_both(crc, value->name);
6254 crc = progdefs_crc_both(crc, ";\n");
6256 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6257 for (i = 0; i < parser->crc_fields; ++i) {
6258 if (!ast_istype(parser->fields[i], ast_value))
6260 value = (ast_value*)(parser->fields[i]);
6261 switch (value->expression.next->vtype) {
6262 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6263 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6264 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6265 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6267 crc = progdefs_crc_both(crc, "\tint\t");
6270 crc = progdefs_crc_both(crc, value->name);
6271 crc = progdefs_crc_both(crc, ";\n");
6273 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6274 ir->code->crc = crc;
6277 parser_t *parser_create()
6283 parser = (parser_t*)mem_a(sizeof(parser_t));
6287 memset(parser, 0, sizeof(*parser));
6289 for (i = 0; i < operator_count; ++i) {
6290 if (operators[i].id == opid1('=')) {
6291 parser->assign_op = operators+i;
6295 if (!parser->assign_op) {
6296 printf("internal error: initializing parser: failed to find assign operator\n");
6301 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6302 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6303 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6304 vec_push(parser->_blocktypedefs, 0);
6306 parser->aliases = util_htnew(PARSER_HT_SIZE);
6308 parser->ht_imm_string = util_htnew(512);
6309 parser->ht_imm_string_dotranslate = util_htnew(512);
6312 vec_push(parser->correct_variables, correct_trie_new());
6313 vec_push(parser->correct_variables_score, NULL);
6315 empty_ctx.file = "<internal>";
6317 empty_ctx.column = 0;
6318 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6319 parser->nil->cvq = CV_CONST;
6320 if (OPTS_FLAG(UNTYPED_NIL))
6321 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6323 parser->max_param_count = 1;
6325 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6326 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6327 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6329 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6330 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6331 parser->reserved_version->cvq = CV_CONST;
6332 parser->reserved_version->hasvalue = true;
6333 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6334 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6336 parser->reserved_version = NULL;
6342 static bool parser_compile(parser_t *parser)
6344 /* initial lexer/parser state */
6345 parser->lex->flags.noops = true;
6347 if (parser_next(parser))
6349 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6351 if (!parser_global_statement(parser)) {
6352 if (parser->tok == TOKEN_EOF)
6353 parseerror(parser, "unexpected end of file");
6354 else if (compile_errors)
6355 parseerror(parser, "there have been errors, bailing out");
6356 lex_close(parser->lex);
6362 parseerror(parser, "parse error");
6363 lex_close(parser->lex);
6368 lex_close(parser->lex);
6371 return !compile_errors;
6374 bool parser_compile_file(parser_t *parser, const char *filename)
6376 parser->lex = lex_open(filename);
6378 con_err("failed to open file \"%s\"\n", filename);
6381 return parser_compile(parser);
6384 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6386 parser->lex = lex_open_string(str, len, name);
6388 con_err("failed to create lexer for string \"%s\"\n", name);
6391 return parser_compile(parser);
6394 static void parser_remove_ast(parser_t *parser)
6397 if (parser->ast_cleaned)
6399 parser->ast_cleaned = true;
6400 for (i = 0; i < vec_size(parser->accessors); ++i) {
6401 ast_delete(parser->accessors[i]->constval.vfunc);
6402 parser->accessors[i]->constval.vfunc = NULL;
6403 ast_delete(parser->accessors[i]);
6405 for (i = 0; i < vec_size(parser->functions); ++i) {
6406 ast_delete(parser->functions[i]);
6408 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6409 ast_delete(parser->imm_vector[i]);
6411 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6412 ast_delete(parser->imm_string[i]);
6414 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6415 ast_delete(parser->imm_float[i]);
6417 for (i = 0; i < vec_size(parser->fields); ++i) {
6418 ast_delete(parser->fields[i]);
6420 for (i = 0; i < vec_size(parser->globals); ++i) {
6421 ast_delete(parser->globals[i]);
6423 vec_free(parser->accessors);
6424 vec_free(parser->functions);
6425 vec_free(parser->imm_vector);
6426 vec_free(parser->imm_string);
6427 util_htdel(parser->ht_imm_string_dotranslate);
6428 util_htdel(parser->ht_imm_string);
6429 vec_free(parser->imm_float);
6430 vec_free(parser->globals);
6431 vec_free(parser->fields);
6433 for (i = 0; i < vec_size(parser->variables); ++i)
6434 util_htdel(parser->variables[i]);
6435 vec_free(parser->variables);
6436 vec_free(parser->_blocklocals);
6437 vec_free(parser->_locals);
6440 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6441 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6443 vec_free(parser->correct_variables);
6444 vec_free(parser->correct_variables_score);
6446 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6447 ast_delete(parser->_typedefs[i]);
6448 vec_free(parser->_typedefs);
6449 for (i = 0; i < vec_size(parser->typedefs); ++i)
6450 util_htdel(parser->typedefs[i]);
6451 vec_free(parser->typedefs);
6452 vec_free(parser->_blocktypedefs);
6454 vec_free(parser->_block_ctx);
6456 vec_free(parser->labels);
6457 vec_free(parser->gotos);
6458 vec_free(parser->breaks);
6459 vec_free(parser->continues);
6461 ast_value_delete(parser->nil);
6463 ast_value_delete(parser->const_vec[0]);
6464 ast_value_delete(parser->const_vec[1]);
6465 ast_value_delete(parser->const_vec[2]);
6467 if (parser->reserved_version)
6468 ast_value_delete(parser->reserved_version);
6470 util_htdel(parser->aliases);
6471 intrin_intrinsics_destroy(parser);
6474 void parser_cleanup(parser_t *parser)
6476 parser_remove_ast(parser);
6480 bool parser_finish(parser_t *parser, const char *output)
6486 if (compile_errors) {
6487 con_out("*** there were compile errors\n");
6491 ir = ir_builder_new("gmqcc_out");
6493 con_out("failed to allocate builder\n");
6497 for (i = 0; i < vec_size(parser->fields); ++i) {
6500 if (!ast_istype(parser->fields[i], ast_value))
6502 field = (ast_value*)parser->fields[i];
6503 hasvalue = field->hasvalue;
6504 field->hasvalue = false;
6505 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6506 con_out("failed to generate field %s\n", field->name);
6507 ir_builder_delete(ir);
6512 ast_expression *subtype;
6513 field->hasvalue = true;
6514 subtype = field->expression.next;
6515 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6516 if (subtype->vtype == TYPE_FIELD)
6517 ifld->fieldtype = subtype->next->vtype;
6518 else if (subtype->vtype == TYPE_FUNCTION)
6519 ifld->outtype = subtype->next->vtype;
6520 (void)!ir_value_set_field(field->ir_v, ifld);
6523 for (i = 0; i < vec_size(parser->globals); ++i) {
6525 if (!ast_istype(parser->globals[i], ast_value))
6527 asvalue = (ast_value*)(parser->globals[i]);
6528 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6529 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6530 "unused global: `%s`", asvalue->name);
6532 if (!ast_global_codegen(asvalue, ir, false)) {
6533 con_out("failed to generate global %s\n", asvalue->name);
6534 ir_builder_delete(ir);
6538 /* Build function vararg accessor ast tree now before generating
6539 * immediates, because the accessors may add new immediates
6541 for (i = 0; i < vec_size(parser->functions); ++i) {
6542 ast_function *f = parser->functions[i];
6544 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6545 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6546 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6547 con_out("failed to generate vararg setter for %s\n", f->name);
6548 ir_builder_delete(ir);
6551 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6552 con_out("failed to generate vararg getter for %s\n", f->name);
6553 ir_builder_delete(ir);
6557 ast_delete(f->varargs);
6562 /* Now we can generate immediates */
6563 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6564 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6565 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6566 ir_builder_delete(ir);
6570 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6571 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6572 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6573 ir_builder_delete(ir);
6577 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6578 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6579 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6580 ir_builder_delete(ir);
6584 for (i = 0; i < vec_size(parser->globals); ++i) {
6586 if (!ast_istype(parser->globals[i], ast_value))
6588 asvalue = (ast_value*)(parser->globals[i]);
6589 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6591 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6592 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6593 "uninitialized constant: `%s`",
6595 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6596 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6597 "uninitialized global: `%s`",
6600 if (!ast_generate_accessors(asvalue, ir)) {
6601 ir_builder_delete(ir);
6605 for (i = 0; i < vec_size(parser->fields); ++i) {
6607 asvalue = (ast_value*)(parser->fields[i]->next);
6609 if (!ast_istype((ast_expression*)asvalue, ast_value))
6611 if (asvalue->expression.vtype != TYPE_ARRAY)
6613 if (!ast_generate_accessors(asvalue, ir)) {
6614 ir_builder_delete(ir);
6618 if (parser->reserved_version &&
6619 !ast_global_codegen(parser->reserved_version, ir, false))
6621 con_out("failed to generate reserved::version");
6622 ir_builder_delete(ir);
6625 for (i = 0; i < vec_size(parser->functions); ++i) {
6626 ast_function *f = parser->functions[i];
6627 if (!ast_function_codegen(f, ir)) {
6628 con_out("failed to generate function %s\n", f->name);
6629 ir_builder_delete(ir);
6634 generate_checksum(parser, ir);
6636 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6637 ir_builder_dump(ir, con_out);
6638 for (i = 0; i < vec_size(parser->functions); ++i) {
6639 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6640 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6641 ir_builder_delete(ir);
6645 parser_remove_ast(parser);
6647 if (compile_Werrors) {
6648 con_out("*** there were warnings treated as errors\n");
6649 compile_show_werrors();
6654 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6655 ir_builder_dump(ir, con_out);
6657 if (!ir_builder_generate(ir, output)) {
6658 con_out("*** failed to generate output file\n");
6659 ir_builder_delete(ir);
6663 ir_builder_delete(ir);