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 128
35 #define TYPEDEF_HT_SIZE 16
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;
53 /* must be deleted first, they reference immediates and values */
54 ast_value **accessors;
56 ast_value *imm_float_zero;
57 ast_value *imm_float_one;
58 ast_value *imm_float_neg_one;
60 ast_value *imm_vector_zero;
63 ast_value *reserved_version;
68 ast_function *function;
71 /* All the labels the function defined...
72 * Should they be in ast_function instead?
77 const char **continues;
79 /* A list of hashtables for each scope */
85 /* same as above but for the spelling corrector */
86 correct_trie_t **correct_variables;
87 size_t ***correct_variables_score; /* vector of vector of size_t* */
89 /* not to be used directly, we use the hash table */
90 ast_expression **_locals;
92 ast_value **_typedefs;
93 size_t *_blocktypedefs;
96 /* we store the '=' operator info */
97 const oper_info *assign_op;
100 ast_value *const_vec[3];
105 /* collected information */
106 size_t max_param_count;
109 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
111 static void parser_enterblock(parser_t *parser);
112 static bool parser_leaveblock(parser_t *parser);
113 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
114 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
115 static bool parse_typedef(parser_t *parser);
116 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);
117 static ast_block* parse_block(parser_t *parser);
118 static bool parse_block_into(parser_t *parser, ast_block *block);
119 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
120 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
121 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
122 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
123 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
124 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
125 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
127 static void parseerror(parser_t *parser, const char *fmt, ...)
131 vcompile_error(parser->lex->tok.ctx, fmt, ap);
135 /* returns true if it counts as an error */
136 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
141 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
146 /**********************************************************************
147 * some maths used for constant folding
150 vector vec3_add(vector a, vector b)
159 vector vec3_sub(vector a, vector b)
168 qcfloat vec3_mulvv(vector a, vector b)
170 return (a.x * b.x + a.y * b.y + a.z * b.z);
173 vector vec3_mulvf(vector a, float b)
182 /**********************************************************************
186 static bool parser_next(parser_t *parser)
188 /* lex_do kills the previous token */
189 parser->tok = lex_do(parser->lex);
190 if (parser->tok == TOKEN_EOF)
192 if (parser->tok >= TOKEN_ERROR) {
193 parseerror(parser, "lex error");
199 #define parser_tokval(p) ((p)->lex->tok.value)
200 #define parser_token(p) (&((p)->lex->tok))
201 #define parser_ctx(p) ((p)->lex->tok.ctx)
203 static ast_value* parser_const_float(parser_t *parser, double d)
208 for (i = 0; i < vec_size(parser->imm_float); ++i) {
209 const double compare = parser->imm_float[i]->constval.vfloat;
210 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
211 return parser->imm_float[i];
214 ctx = parser_ctx(parser);
216 memset(&ctx, 0, sizeof(ctx));
218 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
220 out->hasvalue = true;
222 out->constval.vfloat = d;
223 vec_push(parser->imm_float, out);
227 static ast_value* parser_const_float_0(parser_t *parser)
229 if (!parser->imm_float_zero)
230 parser->imm_float_zero = parser_const_float(parser, 0);
231 return parser->imm_float_zero;
234 static ast_value* parser_const_float_neg1(parser_t *parser) {
235 if (!parser->imm_float_neg_one)
236 parser->imm_float_neg_one = parser_const_float(parser, -1);
237 return parser->imm_float_neg_one;
240 static ast_value* parser_const_float_1(parser_t *parser)
242 if (!parser->imm_float_one)
243 parser->imm_float_one = parser_const_float(parser, 1);
244 return parser->imm_float_one;
247 static char *parser_strdup(const char *str)
250 /* actually dup empty strings */
251 char *out = (char*)mem_a(1);
255 return util_strdup(str);
258 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
260 size_t hash = util_hthash(parser->ht_imm_string, str);
262 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
263 if (dotranslate && out->name[0] == '#') {
265 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
266 ast_value_set_name(out, name);
267 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
272 for (i = 0; i < vec_size(parser->imm_string); ++i) {
273 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
274 return parser->imm_string[i];
279 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
280 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
281 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
283 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
285 out->hasvalue = true;
287 out->constval.vstring = parser_strdup(str);
288 vec_push(parser->imm_string, out);
289 util_htseth(parser->ht_imm_string, str, hash, out);
293 static ast_value* parser_const_vector(parser_t *parser, vector v)
297 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
298 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
299 return parser->imm_vector[i];
301 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
303 out->hasvalue = true;
305 out->constval.vvec = v;
306 vec_push(parser->imm_vector, out);
310 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
316 return parser_const_vector(parser, v);
319 static ast_value* parser_const_vector_0(parser_t *parser)
321 if (!parser->imm_vector_zero)
322 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
323 return parser->imm_vector_zero;
326 static ast_expression* parser_find_field(parser_t *parser, const char *name)
328 return ( ast_expression*)util_htget(parser->htfields, name);
331 static ast_expression* parser_find_label(parser_t *parser, const char *name)
334 for(i = 0; i < vec_size(parser->labels); i++)
335 if (!strcmp(parser->labels[i]->name, name))
336 return (ast_expression*)parser->labels[i];
340 static ast_expression* parser_find_global(parser_t *parser, const char *name)
342 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
345 return (ast_expression*)util_htget(parser->htglobals, name);
348 static ast_expression* parser_find_param(parser_t *parser, const char *name)
352 if (!parser->function)
354 fun = parser->function->vtype;
355 for (i = 0; i < vec_size(fun->expression.params); ++i) {
356 if (!strcmp(fun->expression.params[i]->name, name))
357 return (ast_expression*)(fun->expression.params[i]);
362 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
367 hash = util_hthash(parser->htglobals, name);
370 for (i = vec_size(parser->variables); i > upto;) {
372 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
376 return parser_find_param(parser, name);
379 static ast_expression* parser_find_var(parser_t *parser, const char *name)
383 v = parser_find_local(parser, name, 0, &dummy);
384 if (!v) v = parser_find_global(parser, name);
388 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
392 hash = util_hthash(parser->typedefs[0], name);
394 for (i = vec_size(parser->typedefs); i > upto;) {
396 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
402 /* include intrinsics */
407 size_t etype; /* 0 = expression, others are operators */
411 ast_block *block; /* for commas and function calls */
430 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
441 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
445 e.out = (ast_expression*)v;
452 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
454 e.etype = 1 + (op - operators);
463 static sy_elem syparen(lex_ctx ctx, size_t off) {
474 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
475 * so we need to rotate it to become ent.(foo[n]).
477 static bool rotate_entfield_array_index_nodes(ast_expression **out)
479 ast_array_index *index, *oldindex;
480 ast_entfield *entfield;
484 ast_expression *entity;
486 lex_ctx ctx = ast_ctx(*out);
488 if (!ast_istype(*out, ast_array_index))
490 index = (ast_array_index*)*out;
492 if (!ast_istype(index->array, ast_entfield))
494 entfield = (ast_entfield*)index->array;
496 if (!ast_istype(entfield->field, ast_value))
498 field = (ast_value*)entfield->field;
501 entity = entfield->entity;
505 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
506 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
507 *out = (ast_expression*)entfield;
509 oldindex->array = NULL;
510 oldindex->index = NULL;
511 ast_delete(oldindex);
516 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
518 switch (v->expression.vtype) {
520 return !!v->constval.vfloat;
522 return !!v->constval.vint;
524 if (OPTS_FLAG(CORRECT_LOGIC))
525 return v->constval.vvec.x &&
526 v->constval.vvec.y &&
529 return !!(v->constval.vvec.x);
531 if (!v->constval.vstring)
533 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
535 return !!v->constval.vstring[0];
537 compile_error(ctx, "internal error: immediate_is_true on invalid type");
538 return !!v->constval.vfunc;
542 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
546 ast_expression *out = NULL;
547 ast_expression *exprs[3];
548 ast_block *blocks[3];
549 ast_value *asvalue[3];
550 ast_binstore *asbinstore;
551 size_t i, assignop, addop, subop;
552 qcint generated_op = 0;
557 if (!vec_size(sy->ops)) {
558 parseerror(parser, "internal error: missing operator");
562 if (vec_last(sy->ops).isparen) {
563 parseerror(parser, "unmatched parenthesis");
567 op = &operators[vec_last(sy->ops).etype - 1];
568 ctx = vec_last(sy->ops).ctx;
570 if (vec_size(sy->out) < op->operands) {
571 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
572 op->op, (int)op->id);
576 vec_shrinkby(sy->ops, 1);
578 /* op(:?) has no input and no output */
582 vec_shrinkby(sy->out, op->operands);
583 for (i = 0; i < op->operands; ++i) {
584 exprs[i] = sy->out[vec_size(sy->out)+i].out;
585 blocks[i] = sy->out[vec_size(sy->out)+i].block;
586 asvalue[i] = (ast_value*)exprs[i];
588 if (exprs[i]->vtype == TYPE_NOEXPR &&
589 !(i != 0 && op->id == opid2('?',':')) &&
590 !(i == 1 && op->id == opid1('.')))
592 if (ast_istype(exprs[i], ast_label))
593 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
595 compile_error(ast_ctx(exprs[i]), "not an expression");
596 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
600 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
601 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
605 #define NotSameType(T) \
606 (exprs[0]->vtype != exprs[1]->vtype || \
607 exprs[0]->vtype != T)
608 #define CanConstFold1(A) \
609 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
610 (A)->vtype != TYPE_FUNCTION)
611 #define CanConstFold(A, B) \
612 (CanConstFold1(A) && CanConstFold1(B))
613 #define ConstV(i) (asvalue[(i)]->constval.vvec)
614 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
615 #define ConstS(i) (asvalue[(i)]->constval.vstring)
619 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
623 if (exprs[0]->vtype == TYPE_VECTOR &&
624 exprs[1]->vtype == TYPE_NOEXPR)
626 if (exprs[1] == (ast_expression*)parser->const_vec[0])
627 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
628 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
629 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
630 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
631 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
633 compile_error(ctx, "access to invalid vector component");
637 else if (exprs[0]->vtype == TYPE_ENTITY) {
638 if (exprs[1]->vtype != TYPE_FIELD) {
639 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
642 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
644 else if (exprs[0]->vtype == TYPE_VECTOR) {
645 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
649 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
655 if (exprs[0]->vtype != TYPE_ARRAY &&
656 !(exprs[0]->vtype == TYPE_FIELD &&
657 exprs[0]->next->vtype == TYPE_ARRAY))
659 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
660 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
663 if (exprs[1]->vtype != TYPE_FLOAT) {
664 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
665 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
668 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
669 if (rotate_entfield_array_index_nodes(&out))
672 /* This is not broken in fteqcc anymore */
673 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
674 /* this error doesn't need to make us bail out */
675 (void)!parsewarning(parser, WARN_EXTENSIONS,
676 "accessing array-field members of an entity without parenthesis\n"
677 " -> this is an extension from -std=gmqcc");
684 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
685 vec_push(sy->out, syexp(ctx, exprs[0]));
686 vec_push(sy->out, syexp(ctx, exprs[1]));
687 vec_last(sy->argc)++;
691 if (!ast_block_add_expr(blocks[0], exprs[1]))
694 blocks[0] = ast_block_new(ctx);
695 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
696 !ast_block_add_expr(blocks[0], exprs[1]))
701 ast_block_set_type(blocks[0], exprs[1]);
703 vec_push(sy->out, syblock(ctx, blocks[0]));
710 switch (exprs[0]->vtype) {
712 if (CanConstFold1(exprs[0]))
713 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
715 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
716 (ast_expression*)parser_const_float_0(parser),
720 if (CanConstFold1(exprs[0]))
721 out = (ast_expression*)parser_const_vector_f(parser,
722 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
724 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
725 (ast_expression*)parser_const_vector_0(parser),
729 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
730 type_name[exprs[0]->vtype]);
736 switch (exprs[0]->vtype) {
738 if (CanConstFold1(exprs[0]))
739 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
741 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
744 if (CanConstFold1(exprs[0]))
745 out = (ast_expression*)parser_const_float(parser,
746 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
748 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
751 if (CanConstFold1(exprs[0])) {
752 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
753 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
755 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
757 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
758 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
760 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
763 /* we don't constant-fold NOT for these types */
765 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
768 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
771 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
772 type_name[exprs[0]->vtype]);
778 if (exprs[0]->vtype != exprs[1]->vtype ||
779 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
781 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
782 type_name[exprs[0]->vtype],
783 type_name[exprs[1]->vtype]);
786 switch (exprs[0]->vtype) {
788 if (CanConstFold(exprs[0], exprs[1]))
790 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
793 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
799 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
802 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
803 type_name[exprs[0]->vtype],
804 type_name[exprs[1]->vtype]);
809 if (exprs[0]->vtype != exprs[1]->vtype ||
810 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
812 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
813 type_name[exprs[1]->vtype],
814 type_name[exprs[0]->vtype]);
817 switch (exprs[0]->vtype) {
819 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
825 if (CanConstFold(exprs[0], exprs[1]))
826 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
828 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
831 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
832 type_name[exprs[1]->vtype],
833 type_name[exprs[0]->vtype]);
838 if (exprs[0]->vtype != exprs[1]->vtype &&
839 !(exprs[0]->vtype == TYPE_VECTOR &&
840 exprs[1]->vtype == TYPE_FLOAT) &&
841 !(exprs[1]->vtype == TYPE_VECTOR &&
842 exprs[0]->vtype == TYPE_FLOAT)
845 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
846 type_name[exprs[1]->vtype],
847 type_name[exprs[0]->vtype]);
850 switch (exprs[0]->vtype) {
852 if (exprs[1]->vtype == TYPE_VECTOR)
854 if (CanConstFold(exprs[0], exprs[1]))
855 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
857 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
861 if (CanConstFold(exprs[0], exprs[1]))
862 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
864 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
868 if (exprs[1]->vtype == TYPE_FLOAT)
870 if (CanConstFold(exprs[0], exprs[1]))
871 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
873 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
877 if (CanConstFold(exprs[0], exprs[1]))
878 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
879 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
880 vector vec = ConstV(0);
881 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
882 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
883 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
884 out->node.keep = false;
885 ((ast_member*)out)->rvalue = true;
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
889 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
890 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
891 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
892 out->node.keep = false;
893 ((ast_member*)out)->rvalue = true;
895 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
897 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
898 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
899 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
900 out->node.keep = false;
901 ((ast_member*)out)->rvalue = true;
903 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
908 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
909 vector vec = ConstV(1);
910 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
911 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
912 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
913 out->node.keep = false;
914 ((ast_member*)out)->rvalue = true;
916 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
918 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
919 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
920 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
921 out->node.keep = false;
922 ((ast_member*)out)->rvalue = true;
924 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
926 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
927 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
928 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
929 out->node.keep = false;
930 ((ast_member*)out)->rvalue = true;
932 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
935 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
938 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
942 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
943 type_name[exprs[1]->vtype],
944 type_name[exprs[0]->vtype]);
949 if (exprs[1]->vtype != TYPE_FLOAT) {
950 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
951 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
952 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
955 if (exprs[0]->vtype == TYPE_FLOAT) {
956 if (CanConstFold(exprs[0], exprs[1]))
957 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
959 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
961 else if (exprs[0]->vtype == TYPE_VECTOR) {
962 if (CanConstFold(exprs[0], exprs[1]))
963 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
965 if (CanConstFold1(exprs[1])) {
966 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
968 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
969 (ast_expression*)parser_const_float_1(parser),
973 compile_error(ctx, "internal error: failed to generate division");
976 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
981 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
982 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
983 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
989 if (NotSameType(TYPE_FLOAT)) {
990 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
991 type_name[exprs[0]->vtype],
992 type_name[exprs[1]->vtype]);
995 if (CanConstFold(exprs[0], exprs[1])) {
996 out = (ast_expression*)parser_const_float(parser,
997 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
999 /* generate a call to __builtin_mod */
1000 ast_expression *mod = intrin_func(parser, "mod");
1001 ast_call *call = NULL;
1002 if (!mod) return false; /* can return null for missing floor */
1004 call = ast_call_new(parser_ctx(parser), mod);
1005 vec_push(call->params, exprs[0]);
1006 vec_push(call->params, exprs[1]);
1008 out = (ast_expression*)call;
1012 case opid2('%','='):
1013 compile_error(ctx, "%= is unimplemented");
1018 if (NotSameType(TYPE_FLOAT)) {
1019 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1020 type_name[exprs[0]->vtype],
1021 type_name[exprs[1]->vtype]);
1024 if (CanConstFold(exprs[0], exprs[1]))
1025 out = (ast_expression*)parser_const_float(parser,
1026 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1027 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1029 out = (ast_expression*)ast_binary_new(ctx,
1030 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1031 exprs[0], exprs[1]);
1035 * Okay lets designate what the hell is an acceptable use
1036 * of the ^ operator. In many vector processing units, XOR
1037 * is allowed to be used on vectors, but only if the first
1038 * operand is a vector, the second operand can be a float
1039 * or vector. It's never legal for the first operand to be
1040 * a float, and then the following operand to be a vector.
1041 * Further more, the only time it is legal to do XOR otherwise
1042 * is when both operand are floats. This nicely crafted if
1043 * statement catches them all.
1045 * In the event that the first operand is a vector, two
1046 * possible situations can arise, thus, each element of
1047 * vector A (operand A) is exclusive-ORed with the corresponding
1048 * element of vector B (operand B), If B is scalar, the
1049 * scalar value is first replicated for each element.
1051 * The QCVM itself lacks a BITXOR instruction. Thus emulating
1052 * the mathematics of it is required. The following equation
1053 * is used: (LHS | RHS) & ~(LHS & RHS). However, due to the
1054 * QCVM also lacking a BITNEG instruction, we need to emulate
1055 * ~FOO with -1 - FOO, the whole process becoming this nicely
1056 * crafted expression: (LHS | RHS) & (-1 - (LHS & RHS)).
1058 * When A is not scalar, this process is repeated for all
1059 * components of vector A with the value in operand B,
1060 * only if operand B is scalar. When A is not scalar, and B
1061 * is also not scalar, this process is repeated for all
1062 * components of the vector A with the components of vector B.
1063 * Finally when A is scalar and B is scalar, this process is
1064 * simply used once for A and B being LHS and RHS respectfully.
1066 * Yes the semantics are a bit strange (no pun intended).
1067 * But then again BITXOR is strange itself, consdering it's
1068 * commutative, assocative, and elements of the BITXOR operation
1069 * are their own inverse.
1071 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
1072 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
1073 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
1075 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1076 type_name[exprs[0]->vtype],
1077 type_name[exprs[1]->vtype]);
1082 * IF the first expression is float, the following will be too
1083 * since scalar ^ vector is not allowed.
1085 if (exprs[0]->vtype == TYPE_FLOAT) {
1086 if(CanConstFold(exprs[0], exprs[1])) {
1087 out = (ast_expression*)parser_const_float(parser, (float)((qcint)(ConstF(0)) ^ ((qcint)(ConstF(1)))));
1089 ast_binary *expr = ast_binary_new(
1092 (ast_expression*)parser_const_float_neg1(parser),
1093 (ast_expression*)ast_binary_new(
1100 expr->refs = AST_REF_NONE;
1102 out = (ast_expression*)
1106 (ast_expression*)ast_binary_new(
1112 (ast_expression*)expr
1117 * The first is a vector: vector is allowed to xor with vector and
1118 * with scalar, branch here for the second operand.
1120 if (exprs[1]->vtype == TYPE_VECTOR) {
1122 * Xor all the values of the vector components against the
1123 * vectors components in question.
1125 if (CanConstFold(exprs[0], exprs[1])) {
1126 out = (ast_expression*)parser_const_vector_f(
1128 (float)(((qcint)(ConstV(0).x)) ^ ((qcint)(ConstV(1).x))),
1129 (float)(((qcint)(ConstV(0).y)) ^ ((qcint)(ConstV(1).y))),
1130 (float)(((qcint)(ConstV(0).z)) ^ ((qcint)(ConstV(1).z)))
1133 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against vector");
1138 * Xor all the values of the vector components against the
1139 * scalar in question.
1141 if (CanConstFold(exprs[0], exprs[1])) {
1142 out = (ast_expression*)parser_const_vector_f(
1144 (float)(((qcint)(ConstV(0).x)) ^ ((qcint)(ConstF(1)))),
1145 (float)(((qcint)(ConstV(0).y)) ^ ((qcint)(ConstF(1)))),
1146 (float)(((qcint)(ConstV(0).z)) ^ ((qcint)(ConstF(1))))
1149 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against float");
1157 case opid2('<','<'):
1158 case opid2('>','>'):
1159 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1160 if (op->id == opid2('<','<'))
1161 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1163 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1166 case opid3('<','<','='):
1167 case opid3('>','>','='):
1168 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1171 case opid2('|','|'):
1172 generated_op += 1; /* INSTR_OR */
1173 case opid2('&','&'):
1174 generated_op += INSTR_AND;
1175 if (CanConstFold(exprs[0], exprs[1]))
1177 if (OPTS_FLAG(PERL_LOGIC)) {
1178 if (immediate_is_true(ctx, asvalue[0]))
1182 out = (ast_expression*)parser_const_float(parser,
1183 ( (generated_op == INSTR_OR)
1184 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1185 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1190 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1191 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1192 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1193 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1196 for (i = 0; i < 2; ++i) {
1197 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1198 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1200 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1202 exprs[i] = out; out = NULL;
1203 if (OPTS_FLAG(PERL_LOGIC)) {
1204 /* here we want to keep the right expressions' type */
1208 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1209 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1211 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1213 exprs[i] = out; out = NULL;
1214 if (OPTS_FLAG(PERL_LOGIC)) {
1215 /* here we want to keep the right expressions' type */
1220 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1224 case opid2('?',':'):
1225 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1226 compile_error(ctx, "mismatched parenthesis/ternary");
1230 if (!ast_compare_type(exprs[1], exprs[2])) {
1231 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1232 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1233 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1236 if (CanConstFold1(exprs[0]))
1237 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1239 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1242 case opid2('*', '*'):
1243 if (NotSameType(TYPE_FLOAT)) {
1244 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1245 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1246 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1252 if (CanConstFold(exprs[0], exprs[1])) {
1253 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1255 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1256 vec_push(gencall->params, exprs[0]);
1257 vec_push(gencall->params, exprs[1]);
1258 out = (ast_expression*)gencall;
1262 case opid3('<','=','>'): /* -1, 0, or 1 */
1263 if (NotSameType(TYPE_FLOAT)) {
1264 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1265 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1266 compile_error(ctx, "invalid types used in comparision: %s and %s",
1272 if (CanConstFold(exprs[0], exprs[1])) {
1273 if (ConstF(0) < ConstF(1))
1274 out = (ast_expression*)parser_const_float_neg1(parser);
1275 else if (ConstF(0) == ConstF(1))
1276 out = (ast_expression*)parser_const_float_0(parser);
1277 else if (ConstF(0) > ConstF(1))
1278 out = (ast_expression*)parser_const_float_1(parser);
1280 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1282 eq->refs = AST_REF_NONE;
1285 out = (ast_expression*)ast_ternary_new(ctx,
1286 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1288 (ast_expression*)parser_const_float_neg1(parser),
1291 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1293 (ast_expression*)parser_const_float_0(parser),
1296 (ast_expression*)parser_const_float_1(parser)
1306 generated_op += 1; /* INSTR_GT */
1308 generated_op += 1; /* INSTR_LT */
1309 case opid2('>', '='):
1310 generated_op += 1; /* INSTR_GE */
1311 case opid2('<', '='):
1312 generated_op += INSTR_LE;
1313 if (NotSameType(TYPE_FLOAT)) {
1314 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1315 type_name[exprs[0]->vtype],
1316 type_name[exprs[1]->vtype]);
1319 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1321 case opid2('!', '='):
1322 if (exprs[0]->vtype != exprs[1]->vtype) {
1323 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1324 type_name[exprs[0]->vtype],
1325 type_name[exprs[1]->vtype]);
1328 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1330 case opid2('=', '='):
1331 if (exprs[0]->vtype != exprs[1]->vtype) {
1332 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1333 type_name[exprs[0]->vtype],
1334 type_name[exprs[1]->vtype]);
1337 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1341 if (ast_istype(exprs[0], ast_entfield)) {
1342 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1343 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1344 exprs[0]->vtype == TYPE_FIELD &&
1345 exprs[0]->next->vtype == TYPE_VECTOR)
1347 assignop = type_storep_instr[TYPE_VECTOR];
1350 assignop = type_storep_instr[exprs[0]->vtype];
1351 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1353 ast_type_to_string(field->next, ty1, sizeof(ty1));
1354 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1355 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1356 field->next->vtype == TYPE_FUNCTION &&
1357 exprs[1]->vtype == TYPE_FUNCTION)
1359 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1360 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1363 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1368 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1369 exprs[0]->vtype == TYPE_FIELD &&
1370 exprs[0]->next->vtype == TYPE_VECTOR)
1372 assignop = type_store_instr[TYPE_VECTOR];
1375 assignop = type_store_instr[exprs[0]->vtype];
1378 if (assignop == VINSTR_END) {
1379 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1380 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1381 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1383 else if (!ast_compare_type(exprs[0], exprs[1]))
1385 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1386 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1387 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1388 exprs[0]->vtype == TYPE_FUNCTION &&
1389 exprs[1]->vtype == TYPE_FUNCTION)
1391 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1392 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1395 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1398 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1399 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1401 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1403 case opid3('+','+','P'):
1404 case opid3('-','-','P'):
1406 if (exprs[0]->vtype != TYPE_FLOAT) {
1407 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1408 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1411 if (op->id == opid3('+','+','P'))
1412 addop = INSTR_ADD_F;
1414 addop = INSTR_SUB_F;
1415 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1416 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1418 if (ast_istype(exprs[0], ast_entfield)) {
1419 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1421 (ast_expression*)parser_const_float_1(parser));
1423 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1425 (ast_expression*)parser_const_float_1(parser));
1428 case opid3('S','+','+'):
1429 case opid3('S','-','-'):
1431 if (exprs[0]->vtype != TYPE_FLOAT) {
1432 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1433 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1436 if (op->id == opid3('S','+','+')) {
1437 addop = INSTR_ADD_F;
1438 subop = INSTR_SUB_F;
1440 addop = INSTR_SUB_F;
1441 subop = INSTR_ADD_F;
1443 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1444 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1446 if (ast_istype(exprs[0], ast_entfield)) {
1447 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1449 (ast_expression*)parser_const_float_1(parser));
1451 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1453 (ast_expression*)parser_const_float_1(parser));
1457 out = (ast_expression*)ast_binary_new(ctx, subop,
1459 (ast_expression*)parser_const_float_1(parser));
1461 case opid2('+','='):
1462 case opid2('-','='):
1463 if (exprs[0]->vtype != exprs[1]->vtype ||
1464 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1466 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1467 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1468 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1472 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1473 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1475 if (ast_istype(exprs[0], ast_entfield))
1476 assignop = type_storep_instr[exprs[0]->vtype];
1478 assignop = type_store_instr[exprs[0]->vtype];
1479 switch (exprs[0]->vtype) {
1481 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1482 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1483 exprs[0], exprs[1]);
1486 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1487 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1488 exprs[0], exprs[1]);
1491 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1492 type_name[exprs[0]->vtype],
1493 type_name[exprs[1]->vtype]);
1497 case opid2('*','='):
1498 case opid2('/','='):
1499 if (exprs[1]->vtype != TYPE_FLOAT ||
1500 !(exprs[0]->vtype == TYPE_FLOAT ||
1501 exprs[0]->vtype == TYPE_VECTOR))
1503 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1504 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1505 compile_error(ctx, "invalid types used in expression: %s and %s",
1509 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1510 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1512 if (ast_istype(exprs[0], ast_entfield))
1513 assignop = type_storep_instr[exprs[0]->vtype];
1515 assignop = type_store_instr[exprs[0]->vtype];
1516 switch (exprs[0]->vtype) {
1518 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1519 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1520 exprs[0], exprs[1]);
1523 if (op->id == opid2('*','=')) {
1524 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1525 exprs[0], exprs[1]);
1527 /* there's no DIV_VF */
1528 if (CanConstFold1(exprs[1])) {
1529 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1531 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1532 (ast_expression*)parser_const_float_1(parser),
1536 compile_error(ctx, "internal error: failed to generate division");
1539 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1544 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1545 type_name[exprs[0]->vtype],
1546 type_name[exprs[1]->vtype]);
1550 case opid2('&','='):
1551 case opid2('|','='):
1552 if (NotSameType(TYPE_FLOAT)) {
1553 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1554 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1555 compile_error(ctx, "invalid types used in expression: %s and %s",
1559 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1560 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1562 if (ast_istype(exprs[0], ast_entfield))
1563 assignop = type_storep_instr[exprs[0]->vtype];
1565 assignop = type_store_instr[exprs[0]->vtype];
1566 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1567 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1568 exprs[0], exprs[1]);
1570 case opid3('&','~','='):
1571 /* This is like: a &= ~(b);
1572 * But QC has no bitwise-not, so we implement it as
1575 if (NotSameType(TYPE_FLOAT)) {
1576 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1577 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1578 compile_error(ctx, "invalid types used in expression: %s and %s",
1582 if (ast_istype(exprs[0], ast_entfield))
1583 assignop = type_storep_instr[exprs[0]->vtype];
1585 assignop = type_store_instr[exprs[0]->vtype];
1586 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1589 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1590 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1592 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1593 asbinstore->keep_dest = true;
1594 out = (ast_expression*)asbinstore;
1597 case opid2('~', 'P'):
1598 if (exprs[0]->vtype != TYPE_FLOAT) {
1599 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1600 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1604 if(CanConstFold1(exprs[0]))
1605 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1607 out = (ast_expression*)
1608 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1614 compile_error(ctx, "failed to apply operator %s", op->op);
1618 vec_push(sy->out, syexp(ctx, out));
1622 static bool parser_close_call(parser_t *parser, shunt *sy)
1624 /* was a function call */
1625 ast_expression *fun;
1626 ast_value *funval = NULL;
1630 size_t paramcount, i;
1632 fid = vec_last(sy->ops).off;
1633 vec_shrinkby(sy->ops, 1);
1635 /* out[fid] is the function
1636 * everything above is parameters...
1638 if (!vec_size(sy->argc)) {
1639 parseerror(parser, "internal error: no argument counter available");
1643 paramcount = vec_last(sy->argc);
1646 if (vec_size(sy->out) < fid) {
1647 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1648 (unsigned long)vec_size(sy->out),
1650 (unsigned long)paramcount);
1654 fun = sy->out[fid].out;
1656 if (fun == intrinsic_debug_typestring) {
1658 if (fid+2 != vec_size(sy->out) ||
1659 vec_last(sy->out).block)
1661 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1664 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1665 ast_unref(vec_last(sy->out).out);
1666 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1667 (ast_expression*)parser_const_string(parser, ty, false));
1668 vec_shrinkby(sy->out, 1);
1672 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1676 if (fid+1 < vec_size(sy->out))
1679 if (fid+1 + paramcount != vec_size(sy->out)) {
1680 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1681 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1685 for (i = 0; i < paramcount; ++i)
1686 vec_push(call->params, sy->out[fid+1 + i].out);
1687 vec_shrinkby(sy->out, paramcount);
1688 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1689 if (parser->max_param_count < paramcount)
1690 parser->max_param_count = paramcount;
1692 if (ast_istype(fun, ast_value)) {
1693 funval = (ast_value*)fun;
1694 if ((fun->flags & AST_FLAG_VARIADIC) &&
1695 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1697 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1701 /* overwrite fid, the function, with a call */
1702 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1704 if (fun->vtype != TYPE_FUNCTION) {
1705 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1710 parseerror(parser, "could not determine function return type");
1713 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1715 if (fun->flags & AST_FLAG_DEPRECATED) {
1717 return !parsewarning(parser, WARN_DEPRECATED,
1718 "call to function (which is marked deprecated)\n",
1719 "-> it has been declared here: %s:%i",
1720 ast_ctx(fun).file, ast_ctx(fun).line);
1723 return !parsewarning(parser, WARN_DEPRECATED,
1724 "call to `%s` (which is marked deprecated)\n"
1725 "-> `%s` declared here: %s:%i",
1726 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1728 return !parsewarning(parser, WARN_DEPRECATED,
1729 "call to `%s` (deprecated: %s)\n"
1730 "-> `%s` declared here: %s:%i",
1731 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1735 if (vec_size(fun->params) != paramcount &&
1736 !((fun->flags & AST_FLAG_VARIADIC) &&
1737 vec_size(fun->params) < paramcount))
1739 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1741 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1742 "too %s parameters for call to %s: expected %i, got %i\n"
1743 " -> `%s` has been declared here: %s:%i",
1744 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1745 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1747 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1748 "too %s parameters for function call: expected %i, got %i\n"
1749 " -> it has been declared here: %s:%i",
1750 fewmany, (int)vec_size(fun->params), (int)paramcount,
1751 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1758 static bool parser_close_paren(parser_t *parser, shunt *sy)
1760 if (!vec_size(sy->ops)) {
1761 parseerror(parser, "unmatched closing paren");
1765 while (vec_size(sy->ops)) {
1766 if (vec_last(sy->ops).isparen) {
1767 if (vec_last(sy->paren) == PAREN_FUNC) {
1769 if (!parser_close_call(parser, sy))
1773 if (vec_last(sy->paren) == PAREN_EXPR) {
1775 if (!vec_size(sy->out)) {
1776 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1777 vec_shrinkby(sy->ops, 1);
1780 vec_shrinkby(sy->ops, 1);
1783 if (vec_last(sy->paren) == PAREN_INDEX) {
1785 /* pop off the parenthesis */
1786 vec_shrinkby(sy->ops, 1);
1787 /* then apply the index operator */
1788 if (!parser_sy_apply_operator(parser, sy))
1792 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1793 vec_last(sy->paren) = PAREN_TERNARY2;
1794 /* pop off the parenthesis */
1795 vec_shrinkby(sy->ops, 1);
1798 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1801 if (!parser_sy_apply_operator(parser, sy))
1807 static void parser_reclassify_token(parser_t *parser)
1810 if (parser->tok >= TOKEN_START)
1812 for (i = 0; i < operator_count; ++i) {
1813 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1814 parser->tok = TOKEN_OPERATOR;
1820 static ast_expression* parse_vararg_do(parser_t *parser)
1822 ast_expression *idx, *out;
1824 ast_value *funtype = parser->function->vtype;
1825 lex_ctx ctx = parser_ctx(parser);
1827 if (!parser->function->varargs) {
1828 parseerror(parser, "function has no variable argument list");
1832 if (!parser_next(parser) || parser->tok != '(') {
1833 parseerror(parser, "expected parameter index and type in parenthesis");
1836 if (!parser_next(parser)) {
1837 parseerror(parser, "error parsing parameter index");
1841 idx = parse_expression_leave(parser, true, false, false);
1845 if (parser->tok != ',') {
1846 if (parser->tok != ')') {
1848 parseerror(parser, "expected comma after parameter index");
1851 /* vararg piping: ...(start) */
1852 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1856 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1858 parseerror(parser, "expected typename for vararg");
1862 typevar = parse_typename(parser, NULL, NULL);
1868 if (parser->tok != ')') {
1870 ast_delete(typevar);
1871 parseerror(parser, "expected closing paren");
1875 if (funtype->expression.varparam &&
1876 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1880 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1881 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1882 compile_error(ast_ctx(typevar),
1883 "function was declared to take varargs of type `%s`, requested type is: %s",
1887 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1888 ast_type_adopt(out, typevar);
1889 ast_delete(typevar);
1893 static ast_expression* parse_vararg(parser_t *parser)
1895 bool old_noops = parser->lex->flags.noops;
1897 ast_expression *out;
1899 parser->lex->flags.noops = true;
1900 out = parse_vararg_do(parser);
1902 parser->lex->flags.noops = old_noops;
1906 /* not to be exposed */
1907 extern bool ftepp_predef_exists(const char *name);
1909 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1911 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1912 parser->tok == TOKEN_IDENT &&
1913 !strcmp(parser_tokval(parser), "_"))
1915 /* a translatable string */
1918 parser->lex->flags.noops = true;
1919 if (!parser_next(parser) || parser->tok != '(') {
1920 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1923 parser->lex->flags.noops = false;
1924 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1925 parseerror(parser, "expected a constant string in translatable-string extension");
1928 val = parser_const_string(parser, parser_tokval(parser), true);
1931 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1933 if (!parser_next(parser) || parser->tok != ')') {
1934 parseerror(parser, "expected closing paren after translatable string");
1939 else if (parser->tok == TOKEN_DOTS)
1942 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1943 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1946 va = parse_vararg(parser);
1949 vec_push(sy->out, syexp(parser_ctx(parser), va));
1952 else if (parser->tok == TOKEN_FLOATCONST) {
1954 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1957 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1960 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1962 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1965 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1968 else if (parser->tok == TOKEN_STRINGCONST) {
1970 val = parser_const_string(parser, parser_tokval(parser), false);
1973 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1976 else if (parser->tok == TOKEN_VECTORCONST) {
1978 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1981 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1984 else if (parser->tok == TOKEN_IDENT)
1986 const char *ctoken = parser_tokval(parser);
1987 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1988 ast_expression *var;
1989 /* a_vector.{x,y,z} */
1990 if (!vec_size(sy->ops) ||
1991 !vec_last(sy->ops).etype ||
1992 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1993 (prev >= intrinsic_debug_typestring &&
1994 prev <= intrinsic_debug_typestring))
1996 /* When adding more intrinsics, fix the above condition */
1999 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
2001 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
2003 var = parser_find_var(parser, parser_tokval(parser));
2005 var = parser_find_field(parser, parser_tokval(parser));
2007 if (!var && with_labels) {
2008 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
2010 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
2011 var = (ast_expression*)lbl;
2012 vec_push(parser->labels, lbl);
2015 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
2016 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
2019 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
2020 var = (ast_expression*)intrinsic_debug_typestring;
2022 /* now we try for the real intrinsic hashtable. If the string
2023 * begins with __builtin, we simply skip past it, otherwise we
2024 * use the identifier as is.
2026 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
2027 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
2031 char *correct = NULL;
2035 * sometimes people use preprocessing predefs without enabling them
2036 * i've done this thousands of times already myself. Lets check for
2037 * it in the predef table. And diagnose it better :)
2039 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
2040 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
2045 * TODO: determine the best score for the identifier: be it
2046 * a variable, a field.
2048 * We should also consider adding correction tables for
2049 * other things as well.
2051 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
2053 correct_init(&corr);
2055 for (i = 0; i < vec_size(parser->correct_variables); i++) {
2056 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
2057 if (strcmp(correct, parser_tokval(parser))) {
2059 } else if (correct) {
2064 correct_free(&corr);
2067 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
2072 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
2078 if (ast_istype(var, ast_value)) {
2079 ((ast_value*)var)->uses++;
2081 else if (ast_istype(var, ast_member)) {
2082 ast_member *mem = (ast_member*)var;
2083 if (ast_istype(mem->owner, ast_value))
2084 ((ast_value*)(mem->owner))->uses++;
2087 vec_push(sy->out, syexp(parser_ctx(parser), var));
2090 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2094 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2096 ast_expression *expr = NULL;
2099 bool wantop = false;
2100 /* only warn once about an assignment in a truth value because the current code
2101 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2103 bool warn_truthvalue = true;
2105 /* count the parens because an if starts with one, so the
2106 * end of a condition is an unmatched closing paren
2110 memset(&sy, 0, sizeof(sy));
2112 parser->lex->flags.noops = false;
2114 parser_reclassify_token(parser);
2118 if (parser->tok == TOKEN_TYPENAME) {
2119 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
2123 if (parser->tok == TOKEN_OPERATOR)
2125 /* classify the operator */
2126 const oper_info *op;
2127 const oper_info *olast = NULL;
2129 for (o = 0; o < operator_count; ++o) {
2130 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2131 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2132 !strcmp(parser_tokval(parser), operators[o].op))
2137 if (o == operator_count) {
2138 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2141 /* found an operator */
2144 /* when declaring variables, a comma starts a new variable */
2145 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2146 /* fixup the token */
2151 /* a colon without a pervious question mark cannot be a ternary */
2152 if (!ternaries && op->id == opid2(':','?')) {
2157 if (op->id == opid1(',')) {
2158 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2159 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2163 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2164 olast = &operators[vec_last(sy.ops).etype-1];
2166 #define IsAssignOp(x) (\
2167 (x) == opid1('=') || \
2168 (x) == opid2('+','=') || \
2169 (x) == opid2('-','=') || \
2170 (x) == opid2('*','=') || \
2171 (x) == opid2('/','=') || \
2172 (x) == opid2('%','=') || \
2173 (x) == opid2('&','=') || \
2174 (x) == opid2('|','=') || \
2175 (x) == opid3('&','~','=') \
2177 if (warn_truthvalue) {
2178 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2179 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2180 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2183 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2184 warn_truthvalue = false;
2189 (op->prec < olast->prec) ||
2190 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2192 if (!parser_sy_apply_operator(parser, &sy))
2194 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2195 olast = &operators[vec_last(sy.ops).etype-1];
2200 if (op->id == opid1('(')) {
2202 size_t sycount = vec_size(sy.out);
2203 /* we expected an operator, this is the function-call operator */
2204 vec_push(sy.paren, PAREN_FUNC);
2205 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2206 vec_push(sy.argc, 0);
2208 vec_push(sy.paren, PAREN_EXPR);
2209 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2212 } else if (op->id == opid1('[')) {
2214 parseerror(parser, "unexpected array subscript");
2217 vec_push(sy.paren, PAREN_INDEX);
2218 /* push both the operator and the paren, this makes life easier */
2219 vec_push(sy.ops, syop(parser_ctx(parser), op));
2220 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2222 } else if (op->id == opid2('?',':')) {
2223 vec_push(sy.ops, syop(parser_ctx(parser), op));
2224 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2227 vec_push(sy.paren, PAREN_TERNARY1);
2228 } else if (op->id == opid2(':','?')) {
2229 if (!vec_size(sy.paren)) {
2230 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2233 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2234 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2237 if (!parser_close_paren(parser, &sy))
2239 vec_push(sy.ops, syop(parser_ctx(parser), op));
2243 vec_push(sy.ops, syop(parser_ctx(parser), op));
2244 wantop = !!(op->flags & OP_SUFFIX);
2247 else if (parser->tok == ')') {
2248 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2249 if (!parser_sy_apply_operator(parser, &sy))
2252 if (!vec_size(sy.paren))
2255 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2256 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2259 if (!parser_close_paren(parser, &sy))
2262 /* must be a function call without parameters */
2263 if (vec_last(sy.paren) != PAREN_FUNC) {
2264 parseerror(parser, "closing paren in invalid position");
2267 if (!parser_close_paren(parser, &sy))
2272 else if (parser->tok == '(') {
2273 parseerror(parser, "internal error: '(' should be classified as operator");
2276 else if (parser->tok == '[') {
2277 parseerror(parser, "internal error: '[' should be classified as operator");
2280 else if (parser->tok == ']') {
2281 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2282 if (!parser_sy_apply_operator(parser, &sy))
2285 if (!vec_size(sy.paren))
2287 if (vec_last(sy.paren) != PAREN_INDEX) {
2288 parseerror(parser, "mismatched parentheses, unexpected ']'");
2291 if (!parser_close_paren(parser, &sy))
2296 if (!parse_sya_operand(parser, &sy, with_labels))
2299 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2300 vec_last(sy.argc)++;
2305 /* in this case we might want to allow constant string concatenation */
2306 bool concatenated = false;
2307 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2308 ast_expression *lexpr = vec_last(sy.out).out;
2309 if (ast_istype(lexpr, ast_value)) {
2310 ast_value *last = (ast_value*)lexpr;
2311 if (last->isimm == true && last->cvq == CV_CONST &&
2312 last->hasvalue && last->expression.vtype == TYPE_STRING)
2314 char *newstr = NULL;
2315 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2316 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2318 concatenated = true;
2322 if (!concatenated) {
2323 parseerror(parser, "expected operator or end of statement");
2328 if (!parser_next(parser)) {
2331 if (parser->tok == ';' ||
2332 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2333 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2339 while (vec_size(sy.ops)) {
2340 if (!parser_sy_apply_operator(parser, &sy))
2344 parser->lex->flags.noops = true;
2345 if (vec_size(sy.out) != 1) {
2346 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2349 expr = sy.out[0].out;
2352 if (vec_size(sy.paren)) {
2353 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2361 parser->lex->flags.noops = true;
2362 for (i = 0; i < vec_size(sy.out); ++i) {
2364 ast_unref(sy.out[i].out);
2373 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2375 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2378 if (parser->tok != ';') {
2379 parseerror(parser, "semicolon expected after expression");
2383 if (!parser_next(parser)) {
2390 static void parser_enterblock(parser_t *parser)
2392 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2393 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2394 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2395 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2396 vec_push(parser->_block_ctx, parser_ctx(parser));
2399 vec_push(parser->correct_variables, correct_trie_new());
2400 vec_push(parser->correct_variables_score, NULL);
2403 static bool parser_leaveblock(parser_t *parser)
2406 size_t locals, typedefs;
2408 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2409 parseerror(parser, "internal error: parser_leaveblock with no block");
2413 util_htdel(vec_last(parser->variables));
2414 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2416 vec_pop(parser->variables);
2417 vec_pop(parser->correct_variables);
2418 vec_pop(parser->correct_variables_score);
2419 if (!vec_size(parser->_blocklocals)) {
2420 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2424 locals = vec_last(parser->_blocklocals);
2425 vec_pop(parser->_blocklocals);
2426 while (vec_size(parser->_locals) != locals) {
2427 ast_expression *e = vec_last(parser->_locals);
2428 ast_value *v = (ast_value*)e;
2429 vec_pop(parser->_locals);
2430 if (ast_istype(e, ast_value) && !v->uses) {
2431 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2436 typedefs = vec_last(parser->_blocktypedefs);
2437 while (vec_size(parser->_typedefs) != typedefs) {
2438 ast_delete(vec_last(parser->_typedefs));
2439 vec_pop(parser->_typedefs);
2441 util_htdel(vec_last(parser->typedefs));
2442 vec_pop(parser->typedefs);
2444 vec_pop(parser->_block_ctx);
2449 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2451 vec_push(parser->_locals, e);
2452 util_htset(vec_last(parser->variables), name, (void*)e);
2456 vec_last(parser->correct_variables),
2457 &vec_last(parser->correct_variables_score),
2462 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2464 vec_push(parser->globals, e);
2465 util_htset(parser->htglobals, name, e);
2469 parser->correct_variables[0],
2470 &parser->correct_variables_score[0],
2475 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2479 ast_expression *prev;
2481 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2483 ast_type_to_string(cond, ty, sizeof(ty));
2484 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2487 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2490 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2493 parseerror(parser, "internal error: failed to process condition");
2498 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2500 /* vector types need to be cast to true booleans */
2501 ast_binary *bin = (ast_binary*)cond;
2502 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2504 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2506 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2509 parseerror(parser, "internal error: failed to process condition");
2516 unary = (ast_unary*)cond;
2517 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2519 cond = unary->operand;
2520 unary->operand = NULL;
2523 unary = (ast_unary*)cond;
2527 parseerror(parser, "internal error: failed to process condition");
2529 if (ifnot) *_ifnot = !*_ifnot;
2533 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2536 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2539 lex_ctx ctx = parser_ctx(parser);
2541 (void)block; /* not touching */
2543 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected condition or 'not'");
2548 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2550 if (!parser_next(parser)) {
2551 parseerror(parser, "expected condition in parenthesis");
2555 if (parser->tok != '(') {
2556 parseerror(parser, "expected 'if' condition in parenthesis");
2559 /* parse into the expression */
2560 if (!parser_next(parser)) {
2561 parseerror(parser, "expected 'if' condition after opening paren");
2564 /* parse the condition */
2565 cond = parse_expression_leave(parser, false, true, false);
2569 if (parser->tok != ')') {
2570 parseerror(parser, "expected closing paren after 'if' condition");
2574 /* parse into the 'then' branch */
2575 if (!parser_next(parser)) {
2576 parseerror(parser, "expected statement for on-true branch of 'if'");
2580 if (!parse_statement_or_block(parser, &ontrue)) {
2585 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2586 /* check for an else */
2587 if (!strcmp(parser_tokval(parser), "else")) {
2588 /* parse into the 'else' branch */
2589 if (!parser_next(parser)) {
2590 parseerror(parser, "expected on-false branch after 'else'");
2595 if (!parse_statement_or_block(parser, &onfalse)) {
2602 cond = process_condition(parser, cond, &ifnot);
2604 if (ontrue) ast_delete(ontrue);
2605 if (onfalse) ast_delete(onfalse);
2610 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2612 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2613 *out = (ast_expression*)ifthen;
2617 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2618 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2623 /* skip the 'while' and get the body */
2624 if (!parser_next(parser)) {
2625 if (OPTS_FLAG(LOOP_LABELS))
2626 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2628 parseerror(parser, "expected 'while' condition in parenthesis");
2632 if (parser->tok == ':') {
2633 if (!OPTS_FLAG(LOOP_LABELS))
2634 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2635 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2636 parseerror(parser, "expected loop label");
2639 label = util_strdup(parser_tokval(parser));
2640 if (!parser_next(parser)) {
2642 parseerror(parser, "expected 'while' condition in parenthesis");
2647 if (parser->tok != '(') {
2648 parseerror(parser, "expected 'while' condition in parenthesis");
2652 vec_push(parser->breaks, label);
2653 vec_push(parser->continues, label);
2655 rv = parse_while_go(parser, block, out);
2658 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2659 parseerror(parser, "internal error: label stack corrupted");
2665 vec_pop(parser->breaks);
2666 vec_pop(parser->continues);
2671 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2674 ast_expression *cond, *ontrue;
2678 lex_ctx ctx = parser_ctx(parser);
2680 (void)block; /* not touching */
2682 /* parse into the expression */
2683 if (!parser_next(parser)) {
2684 parseerror(parser, "expected 'while' condition after opening paren");
2687 /* parse the condition */
2688 cond = parse_expression_leave(parser, false, true, false);
2692 if (parser->tok != ')') {
2693 parseerror(parser, "expected closing paren after 'while' condition");
2697 /* parse into the 'then' branch */
2698 if (!parser_next(parser)) {
2699 parseerror(parser, "expected while-loop body");
2703 if (!parse_statement_or_block(parser, &ontrue)) {
2708 cond = process_condition(parser, cond, &ifnot);
2713 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2714 *out = (ast_expression*)aloop;
2718 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2719 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2724 /* skip the 'do' and get the body */
2725 if (!parser_next(parser)) {
2726 if (OPTS_FLAG(LOOP_LABELS))
2727 parseerror(parser, "expected loop label or body");
2729 parseerror(parser, "expected loop body");
2733 if (parser->tok == ':') {
2734 if (!OPTS_FLAG(LOOP_LABELS))
2735 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2736 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2737 parseerror(parser, "expected loop label");
2740 label = util_strdup(parser_tokval(parser));
2741 if (!parser_next(parser)) {
2743 parseerror(parser, "expected loop body");
2748 vec_push(parser->breaks, label);
2749 vec_push(parser->continues, label);
2751 rv = parse_dowhile_go(parser, block, out);
2754 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2755 parseerror(parser, "internal error: label stack corrupted");
2761 vec_pop(parser->breaks);
2762 vec_pop(parser->continues);
2767 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2770 ast_expression *cond, *ontrue;
2774 lex_ctx ctx = parser_ctx(parser);
2776 (void)block; /* not touching */
2778 if (!parse_statement_or_block(parser, &ontrue))
2781 /* expect the "while" */
2782 if (parser->tok != TOKEN_KEYWORD ||
2783 strcmp(parser_tokval(parser), "while"))
2785 parseerror(parser, "expected 'while' and condition");
2790 /* skip the 'while' and check for opening paren */
2791 if (!parser_next(parser) || parser->tok != '(') {
2792 parseerror(parser, "expected 'while' condition in parenthesis");
2796 /* parse into the expression */
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "expected 'while' condition after opening paren");
2802 /* parse the condition */
2803 cond = parse_expression_leave(parser, false, true, false);
2807 if (parser->tok != ')') {
2808 parseerror(parser, "expected closing paren after 'while' condition");
2814 if (!parser_next(parser) || parser->tok != ';') {
2815 parseerror(parser, "expected semicolon after condition");
2821 if (!parser_next(parser)) {
2822 parseerror(parser, "parse error");
2828 cond = process_condition(parser, cond, &ifnot);
2833 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2834 *out = (ast_expression*)aloop;
2838 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2839 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2844 /* skip the 'for' and check for opening paren */
2845 if (!parser_next(parser)) {
2846 if (OPTS_FLAG(LOOP_LABELS))
2847 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2849 parseerror(parser, "expected 'for' expressions in parenthesis");
2853 if (parser->tok == ':') {
2854 if (!OPTS_FLAG(LOOP_LABELS))
2855 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2856 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2857 parseerror(parser, "expected loop label");
2860 label = util_strdup(parser_tokval(parser));
2861 if (!parser_next(parser)) {
2863 parseerror(parser, "expected 'for' expressions in parenthesis");
2868 if (parser->tok != '(') {
2869 parseerror(parser, "expected 'for' expressions in parenthesis");
2873 vec_push(parser->breaks, label);
2874 vec_push(parser->continues, label);
2876 rv = parse_for_go(parser, block, out);
2879 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2880 parseerror(parser, "internal error: label stack corrupted");
2886 vec_pop(parser->breaks);
2887 vec_pop(parser->continues);
2891 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2894 ast_expression *initexpr, *cond, *increment, *ontrue;
2899 lex_ctx ctx = parser_ctx(parser);
2901 parser_enterblock(parser);
2908 /* parse into the expression */
2909 if (!parser_next(parser)) {
2910 parseerror(parser, "expected 'for' initializer after opening paren");
2915 if (parser->tok == TOKEN_IDENT)
2916 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2918 if (typevar || parser->tok == TOKEN_TYPENAME) {
2920 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2921 if (parsewarning(parser, WARN_EXTENSIONS,
2922 "current standard does not allow variable declarations in for-loop initializers"))
2926 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2929 else if (parser->tok != ';')
2931 initexpr = parse_expression_leave(parser, false, false, false);
2936 /* move on to condition */
2937 if (parser->tok != ';') {
2938 parseerror(parser, "expected semicolon after for-loop initializer");
2941 if (!parser_next(parser)) {
2942 parseerror(parser, "expected for-loop condition");
2946 /* parse the condition */
2947 if (parser->tok != ';') {
2948 cond = parse_expression_leave(parser, false, true, false);
2953 /* move on to incrementor */
2954 if (parser->tok != ';') {
2955 parseerror(parser, "expected semicolon after for-loop initializer");
2958 if (!parser_next(parser)) {
2959 parseerror(parser, "expected for-loop condition");
2963 /* parse the incrementor */
2964 if (parser->tok != ')') {
2965 lex_ctx condctx = parser_ctx(parser);
2966 increment = parse_expression_leave(parser, false, false, false);
2969 if (!ast_side_effects(increment)) {
2970 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2976 if (parser->tok != ')') {
2977 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2980 /* parse into the 'then' branch */
2981 if (!parser_next(parser)) {
2982 parseerror(parser, "expected for-loop body");
2985 if (!parse_statement_or_block(parser, &ontrue))
2989 cond = process_condition(parser, cond, &ifnot);
2993 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2994 *out = (ast_expression*)aloop;
2996 if (!parser_leaveblock(parser)) {
3002 if (initexpr) ast_unref(initexpr);
3003 if (cond) ast_unref(cond);
3004 if (increment) ast_unref(increment);
3005 (void)!parser_leaveblock(parser);
3009 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
3011 ast_expression *exp = NULL;
3012 ast_expression *var = NULL;
3013 ast_return *ret = NULL;
3014 ast_value *retval = parser->function->return_value;
3015 ast_value *expected = parser->function->vtype;
3017 lex_ctx ctx = parser_ctx(parser);
3019 (void)block; /* not touching */
3021 if (!parser_next(parser)) {
3022 parseerror(parser, "expected return expression");
3026 /* return assignments */
3027 if (parser->tok == '=') {
3028 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
3029 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
3033 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
3035 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
3036 parseerror(parser, "invalid return type: `%s'", ty1);
3040 if (!parser_next(parser)) {
3041 parseerror(parser, "expected return assignment expression");
3045 if (!(exp = parse_expression_leave(parser, false, false, false)))
3048 /* prepare the return value */
3050 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
3051 ast_type_adopt(retval, expected->expression.next);
3052 parser->function->return_value = retval;
3055 if (!ast_compare_type(exp, (ast_expression*)retval)) {
3056 char ty1[1024], ty2[1024];
3057 ast_type_to_string(exp, ty1, sizeof(ty1));
3058 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
3059 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
3062 /* store to 'return' local variable */
3063 var = (ast_expression*)ast_store_new(
3065 type_store_instr[expected->expression.next->vtype],
3066 (ast_expression*)retval, exp);
3073 if (parser->tok != ';')
3074 parseerror(parser, "missing semicolon after return assignment");
3075 else if (!parser_next(parser))
3076 parseerror(parser, "parse error after return assignment");
3082 if (parser->tok != ';') {
3083 exp = parse_expression(parser, false, false);
3087 if (exp->vtype != TYPE_NIL &&
3088 exp->vtype != ((ast_expression*)expected)->next->vtype)
3090 parseerror(parser, "return with invalid expression");
3093 ret = ast_return_new(ctx, exp);
3099 if (!parser_next(parser))
3100 parseerror(parser, "parse error");
3102 if (!retval && expected->expression.next->vtype != TYPE_VOID)
3104 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3106 ret = ast_return_new(ctx, (ast_expression*)retval);
3108 *out = (ast_expression*)ret;
3112 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3115 unsigned int levels = 0;
3116 lex_ctx ctx = parser_ctx(parser);
3117 const char **loops = (is_continue ? parser->continues : parser->breaks);
3119 (void)block; /* not touching */
3120 if (!parser_next(parser)) {
3121 parseerror(parser, "expected semicolon or loop label");
3125 if (!vec_size(loops)) {
3127 parseerror(parser, "`continue` can only be used inside loops");
3129 parseerror(parser, "`break` can only be used inside loops or switches");
3132 if (parser->tok == TOKEN_IDENT) {
3133 if (!OPTS_FLAG(LOOP_LABELS))
3134 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3135 i = vec_size(loops);
3137 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3140 parseerror(parser, "no such loop to %s: `%s`",
3141 (is_continue ? "continue" : "break out of"),
3142 parser_tokval(parser));
3147 if (!parser_next(parser)) {
3148 parseerror(parser, "expected semicolon");
3153 if (parser->tok != ';') {
3154 parseerror(parser, "expected semicolon");
3158 if (!parser_next(parser))
3159 parseerror(parser, "parse error");
3161 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3165 /* returns true when it was a variable qualifier, false otherwise!
3166 * on error, cvq is set to CV_WRONG
3168 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3170 bool had_const = false;
3171 bool had_var = false;
3172 bool had_noref = false;
3173 bool had_attrib = false;
3174 bool had_static = false;
3179 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3181 /* parse an attribute */
3182 if (!parser_next(parser)) {
3183 parseerror(parser, "expected attribute after `[[`");
3187 if (!strcmp(parser_tokval(parser), "noreturn")) {
3188 flags |= AST_FLAG_NORETURN;
3189 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3190 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3195 else if (!strcmp(parser_tokval(parser), "noref")) {
3197 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3198 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3203 else if (!strcmp(parser_tokval(parser), "inline")) {
3204 flags |= AST_FLAG_INLINE;
3205 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3206 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3211 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3212 flags |= AST_FLAG_ALIAS;
3215 if (!parser_next(parser)) {
3216 parseerror(parser, "parse error in attribute");
3220 if (parser->tok == '(') {
3221 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3222 parseerror(parser, "`alias` attribute missing parameter");
3226 *message = util_strdup(parser_tokval(parser));
3228 if (!parser_next(parser)) {
3229 parseerror(parser, "parse error in attribute");
3233 if (parser->tok != ')') {
3234 parseerror(parser, "`alias` attribute expected `)` after parameter");
3238 if (!parser_next(parser)) {
3239 parseerror(parser, "parse error in attribute");
3244 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3245 parseerror(parser, "`alias` attribute expected `]]`");
3249 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3250 flags |= AST_FLAG_DEPRECATED;
3253 if (!parser_next(parser)) {
3254 parseerror(parser, "parse error in attribute");
3258 if (parser->tok == '(') {
3259 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3260 parseerror(parser, "`deprecated` attribute missing parameter");
3264 *message = util_strdup(parser_tokval(parser));
3266 if (!parser_next(parser)) {
3267 parseerror(parser, "parse error in attribute");
3271 if(parser->tok != ')') {
3272 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3276 if (!parser_next(parser)) {
3277 parseerror(parser, "parse error in attribute");
3282 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3283 parseerror(parser, "`deprecated` attribute expected `]]`");
3286 if (*message) mem_d(*message);
3294 /* Skip tokens until we hit a ]] */
3295 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3296 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3297 if (!parser_next(parser)) {
3298 parseerror(parser, "error inside attribute");
3305 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3307 else if (!strcmp(parser_tokval(parser), "const"))
3309 else if (!strcmp(parser_tokval(parser), "var"))
3311 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3313 else if (!strcmp(parser_tokval(parser), "noref"))
3315 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3320 if (!parser_next(parser))
3330 *is_static = had_static;
3334 parseerror(parser, "parse error after variable qualifier");
3339 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3340 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3345 /* skip the 'while' and get the body */
3346 if (!parser_next(parser)) {
3347 if (OPTS_FLAG(LOOP_LABELS))
3348 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3350 parseerror(parser, "expected 'switch' operand in parenthesis");
3354 if (parser->tok == ':') {
3355 if (!OPTS_FLAG(LOOP_LABELS))
3356 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3357 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3358 parseerror(parser, "expected loop label");
3361 label = util_strdup(parser_tokval(parser));
3362 if (!parser_next(parser)) {
3364 parseerror(parser, "expected 'switch' operand in parenthesis");
3369 if (parser->tok != '(') {
3370 parseerror(parser, "expected 'switch' operand in parenthesis");
3374 vec_push(parser->breaks, label);
3376 rv = parse_switch_go(parser, block, out);
3379 if (vec_last(parser->breaks) != label) {
3380 parseerror(parser, "internal error: label stack corrupted");
3386 vec_pop(parser->breaks);
3391 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3393 ast_expression *operand;
3396 ast_switch *switchnode;
3397 ast_switch_case swcase;
3400 bool noref, is_static;
3401 uint32_t qflags = 0;
3403 lex_ctx ctx = parser_ctx(parser);
3405 (void)block; /* not touching */
3408 /* parse into the expression */
3409 if (!parser_next(parser)) {
3410 parseerror(parser, "expected switch operand");
3413 /* parse the operand */
3414 operand = parse_expression_leave(parser, false, false, false);
3418 switchnode = ast_switch_new(ctx, operand);
3421 if (parser->tok != ')') {
3422 ast_delete(switchnode);
3423 parseerror(parser, "expected closing paren after 'switch' operand");
3427 /* parse over the opening paren */
3428 if (!parser_next(parser) || parser->tok != '{') {
3429 ast_delete(switchnode);
3430 parseerror(parser, "expected list of cases");
3434 if (!parser_next(parser)) {
3435 ast_delete(switchnode);
3436 parseerror(parser, "expected 'case' or 'default'");
3440 /* new block; allow some variables to be declared here */
3441 parser_enterblock(parser);
3444 if (parser->tok == TOKEN_IDENT)
3445 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3446 if (typevar || parser->tok == TOKEN_TYPENAME) {
3447 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3448 ast_delete(switchnode);
3453 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3455 if (cvq == CV_WRONG) {
3456 ast_delete(switchnode);
3459 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3460 ast_delete(switchnode);
3469 while (parser->tok != '}') {
3470 ast_block *caseblock;
3472 if (!strcmp(parser_tokval(parser), "case")) {
3473 if (!parser_next(parser)) {
3474 ast_delete(switchnode);
3475 parseerror(parser, "expected expression for case");
3478 swcase.value = parse_expression_leave(parser, false, false, false);
3479 if (!swcase.value) {
3480 ast_delete(switchnode);
3481 parseerror(parser, "expected expression for case");
3484 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3485 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3486 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3492 else if (!strcmp(parser_tokval(parser), "default")) {
3493 swcase.value = NULL;
3494 if (!parser_next(parser)) {
3495 ast_delete(switchnode);
3496 parseerror(parser, "expected colon");
3501 ast_delete(switchnode);
3502 parseerror(parser, "expected 'case' or 'default'");
3506 /* Now the colon and body */
3507 if (parser->tok != ':') {
3508 if (swcase.value) ast_unref(swcase.value);
3509 ast_delete(switchnode);
3510 parseerror(parser, "expected colon");
3514 if (!parser_next(parser)) {
3515 if (swcase.value) ast_unref(swcase.value);
3516 ast_delete(switchnode);
3517 parseerror(parser, "expected statements or case");
3520 caseblock = ast_block_new(parser_ctx(parser));
3522 if (swcase.value) ast_unref(swcase.value);
3523 ast_delete(switchnode);
3526 swcase.code = (ast_expression*)caseblock;
3527 vec_push(switchnode->cases, swcase);
3529 ast_expression *expr;
3530 if (parser->tok == '}')
3532 if (parser->tok == TOKEN_KEYWORD) {
3533 if (!strcmp(parser_tokval(parser), "case") ||
3534 !strcmp(parser_tokval(parser), "default"))
3539 if (!parse_statement(parser, caseblock, &expr, true)) {
3540 ast_delete(switchnode);
3545 if (!ast_block_add_expr(caseblock, expr)) {
3546 ast_delete(switchnode);
3552 parser_leaveblock(parser);
3555 if (parser->tok != '}') {
3556 ast_delete(switchnode);
3557 parseerror(parser, "expected closing paren of case list");
3560 if (!parser_next(parser)) {
3561 ast_delete(switchnode);
3562 parseerror(parser, "parse error after switch");
3565 *out = (ast_expression*)switchnode;
3569 /* parse computed goto sides */
3570 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3571 ast_expression *on_true;
3572 ast_expression *on_false;
3573 ast_expression *cond;
3578 if (ast_istype(*side, ast_ternary)) {
3579 ast_ternary *tern = (ast_ternary*)*side;
3580 on_true = parse_goto_computed(parser, &tern->on_true);
3581 on_false = parse_goto_computed(parser, &tern->on_false);
3583 if (!on_true || !on_false) {
3584 parseerror(parser, "expected label or expression in ternary");
3585 if (on_true) ast_unref(on_true);
3586 if (on_false) ast_unref(on_false);
3594 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3595 } else if (ast_istype(*side, ast_label)) {
3596 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3597 ast_goto_set_label(gt, ((ast_label*)*side));
3599 return (ast_expression*)gt;
3604 static bool parse_goto(parser_t *parser, ast_expression **out)
3606 ast_goto *gt = NULL;
3607 ast_expression *lbl;
3609 if (!parser_next(parser))
3612 if (parser->tok != TOKEN_IDENT) {
3613 ast_expression *expression;
3615 /* could be an expression i.e computed goto :-) */
3616 if (parser->tok != '(') {
3617 parseerror(parser, "expected label name after `goto`");
3621 /* failed to parse expression for goto */
3622 if (!(expression = parse_expression(parser, false, true)) ||
3623 !(*out = parse_goto_computed(parser, &expression))) {
3624 parseerror(parser, "invalid goto expression");
3625 ast_unref(expression);
3632 /* not computed goto */
3633 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3634 lbl = parser_find_label(parser, gt->name);
3636 if (!ast_istype(lbl, ast_label)) {
3637 parseerror(parser, "internal error: label is not an ast_label");
3641 ast_goto_set_label(gt, (ast_label*)lbl);
3644 vec_push(parser->gotos, gt);
3646 if (!parser_next(parser) || parser->tok != ';') {
3647 parseerror(parser, "semicolon expected after goto label");
3650 if (!parser_next(parser)) {
3651 parseerror(parser, "parse error after goto");
3655 *out = (ast_expression*)gt;
3659 static bool parse_skipwhite(parser_t *parser)
3662 if (!parser_next(parser))
3664 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3665 return parser->tok < TOKEN_ERROR;
3668 static bool parse_eol(parser_t *parser)
3670 if (!parse_skipwhite(parser))
3672 return parser->tok == TOKEN_EOL;
3675 static bool parse_pragma_do(parser_t *parser)
3677 if (!parser_next(parser) ||
3678 parser->tok != TOKEN_IDENT ||
3679 strcmp(parser_tokval(parser), "pragma"))
3681 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3684 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3685 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3689 if (!strcmp(parser_tokval(parser), "noref")) {
3690 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3691 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3694 parser->noref = !!parser_token(parser)->constval.i;
3695 if (!parse_eol(parser)) {
3696 parseerror(parser, "parse error after `noref` pragma");
3702 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3709 static bool parse_pragma(parser_t *parser)
3712 parser->lex->flags.preprocessing = true;
3713 parser->lex->flags.mergelines = true;
3714 rv = parse_pragma_do(parser);
3715 if (parser->tok != TOKEN_EOL) {
3716 parseerror(parser, "junk after pragma");
3719 parser->lex->flags.preprocessing = false;
3720 parser->lex->flags.mergelines = false;
3721 if (!parser_next(parser)) {
3722 parseerror(parser, "parse error after pragma");
3728 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3730 bool noref, is_static;
3732 uint32_t qflags = 0;
3733 ast_value *typevar = NULL;
3734 char *vstring = NULL;
3738 if (parser->tok == TOKEN_IDENT)
3739 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3741 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3743 /* local variable */
3745 parseerror(parser, "cannot declare a variable from here");
3748 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3749 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3752 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3756 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3758 if (cvq == CV_WRONG)
3760 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3762 else if (parser->tok == TOKEN_KEYWORD)
3764 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3769 if (!parser_next(parser)) {
3770 parseerror(parser, "parse error after __builtin_debug_printtype");
3774 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3776 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3777 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3778 if (!parser_next(parser)) {
3779 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3785 if (!parse_statement(parser, block, out, allow_cases))
3788 con_out("__builtin_debug_printtype: got no output node\n");
3791 ast_type_to_string(*out, ty, sizeof(ty));
3792 con_out("__builtin_debug_printtype: `%s`\n", ty);
3797 else if (!strcmp(parser_tokval(parser), "return"))
3799 return parse_return(parser, block, out);
3801 else if (!strcmp(parser_tokval(parser), "if"))
3803 return parse_if(parser, block, out);
3805 else if (!strcmp(parser_tokval(parser), "while"))
3807 return parse_while(parser, block, out);
3809 else if (!strcmp(parser_tokval(parser), "do"))
3811 return parse_dowhile(parser, block, out);
3813 else if (!strcmp(parser_tokval(parser), "for"))
3815 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3816 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3819 return parse_for(parser, block, out);
3821 else if (!strcmp(parser_tokval(parser), "break"))
3823 return parse_break_continue(parser, block, out, false);
3825 else if (!strcmp(parser_tokval(parser), "continue"))
3827 return parse_break_continue(parser, block, out, true);
3829 else if (!strcmp(parser_tokval(parser), "switch"))
3831 return parse_switch(parser, block, out);
3833 else if (!strcmp(parser_tokval(parser), "case") ||
3834 !strcmp(parser_tokval(parser), "default"))
3837 parseerror(parser, "unexpected 'case' label");
3842 else if (!strcmp(parser_tokval(parser), "goto"))
3844 return parse_goto(parser, out);
3846 else if (!strcmp(parser_tokval(parser), "typedef"))
3848 if (!parser_next(parser)) {
3849 parseerror(parser, "expected type definition after 'typedef'");
3852 return parse_typedef(parser);
3854 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3857 else if (parser->tok == '{')
3860 inner = parse_block(parser);
3863 *out = (ast_expression*)inner;
3866 else if (parser->tok == ':')
3870 if (!parser_next(parser)) {
3871 parseerror(parser, "expected label name");
3874 if (parser->tok != TOKEN_IDENT) {
3875 parseerror(parser, "label must be an identifier");
3878 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3880 if (!label->undefined) {
3881 parseerror(parser, "label `%s` already defined", label->name);
3884 label->undefined = false;
3887 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3888 vec_push(parser->labels, label);
3890 *out = (ast_expression*)label;
3891 if (!parser_next(parser)) {
3892 parseerror(parser, "parse error after label");
3895 for (i = 0; i < vec_size(parser->gotos); ++i) {
3896 if (!strcmp(parser->gotos[i]->name, label->name)) {
3897 ast_goto_set_label(parser->gotos[i], label);
3898 vec_remove(parser->gotos, i, 1);
3904 else if (parser->tok == ';')
3906 if (!parser_next(parser)) {
3907 parseerror(parser, "parse error after empty statement");
3914 lex_ctx ctx = parser_ctx(parser);
3915 ast_expression *exp = parse_expression(parser, false, false);
3919 if (!ast_side_effects(exp)) {
3920 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3927 static bool parse_enum(parser_t *parser)
3930 bool reverse = false;
3932 ast_value **values = NULL;
3933 ast_value *var = NULL;
3936 ast_expression *old;
3938 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3939 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3943 /* enumeration attributes (can add more later) */
3944 if (parser->tok == ':') {
3945 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3946 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3951 if (!strcmp(parser_tokval(parser), "flag")) {
3955 else if (!strcmp(parser_tokval(parser), "reverse")) {
3959 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3963 if (!parser_next(parser) || parser->tok != '{') {
3964 parseerror(parser, "expected `{` after enum attribute ");
3970 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3971 if (parser->tok == '}') {
3972 /* allow an empty enum */
3975 parseerror(parser, "expected identifier or `}`");
3979 old = parser_find_field(parser, parser_tokval(parser));
3981 old = parser_find_global(parser, parser_tokval(parser));
3983 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3984 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3988 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3989 vec_push(values, var);
3990 var->cvq = CV_CONST;
3991 var->hasvalue = true;
3993 /* for flagged enumerations increment in POTs of TWO */
3994 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3995 parser_addglobal(parser, var->name, (ast_expression*)var);
3997 if (!parser_next(parser)) {
3998 parseerror(parser, "expected `=`, `}` or comma after identifier");
4002 if (parser->tok == ',')
4004 if (parser->tok == '}')
4006 if (parser->tok != '=') {
4007 parseerror(parser, "expected `=`, `}` or comma after identifier");
4011 if (!parser_next(parser)) {
4012 parseerror(parser, "expected expression after `=`");
4016 /* We got a value! */
4017 old = parse_expression_leave(parser, true, false, false);
4018 asvalue = (ast_value*)old;
4019 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4020 compile_error(ast_ctx(var), "constant value or expression expected");
4023 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4025 if (parser->tok == '}')
4027 if (parser->tok != ',') {
4028 parseerror(parser, "expected `}` or comma after expression");
4033 /* patch them all (for reversed attribute) */
4036 for (i = 0; i < vec_size(values); i++)
4037 values[i]->constval.vfloat = vec_size(values) - i - 1;
4040 if (parser->tok != '}') {
4041 parseerror(parser, "internal error: breaking without `}`");
4045 if (!parser_next(parser) || parser->tok != ';') {
4046 parseerror(parser, "expected semicolon after enumeration");
4050 if (!parser_next(parser)) {
4051 parseerror(parser, "parse error after enumeration");
4063 static bool parse_block_into(parser_t *parser, ast_block *block)
4067 parser_enterblock(parser);
4069 if (!parser_next(parser)) { /* skip the '{' */
4070 parseerror(parser, "expected function body");
4074 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4076 ast_expression *expr = NULL;
4077 if (parser->tok == '}')
4080 if (!parse_statement(parser, block, &expr, false)) {
4081 /* parseerror(parser, "parse error"); */
4087 if (!ast_block_add_expr(block, expr)) {
4094 if (parser->tok != '}') {
4097 (void)parser_next(parser);
4101 if (!parser_leaveblock(parser))
4103 return retval && !!block;
4106 static ast_block* parse_block(parser_t *parser)
4109 block = ast_block_new(parser_ctx(parser));
4112 if (!parse_block_into(parser, block)) {
4113 ast_block_delete(block);
4119 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4121 if (parser->tok == '{') {
4122 *out = (ast_expression*)parse_block(parser);
4125 return parse_statement(parser, NULL, out, false);
4128 static bool create_vector_members(ast_value *var, ast_member **me)
4131 size_t len = strlen(var->name);
4133 for (i = 0; i < 3; ++i) {
4134 char *name = (char*)mem_a(len+3);
4135 memcpy(name, var->name, len);
4137 name[len+1] = 'x'+i;
4139 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4148 do { ast_member_delete(me[--i]); } while(i);
4152 static bool parse_function_body(parser_t *parser, ast_value *var)
4154 ast_block *block = NULL;
4159 ast_expression *framenum = NULL;
4160 ast_expression *nextthink = NULL;
4161 /* None of the following have to be deleted */
4162 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4163 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4164 bool has_frame_think;
4168 has_frame_think = false;
4169 old = parser->function;
4171 if (var->expression.flags & AST_FLAG_ALIAS) {
4172 parseerror(parser, "function aliases cannot have bodies");
4176 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4177 parseerror(parser, "gotos/labels leaking");
4181 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4182 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4183 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4189 if (parser->tok == '[') {
4190 /* got a frame definition: [ framenum, nextthink ]
4191 * this translates to:
4192 * self.frame = framenum;
4193 * self.nextthink = time + 0.1;
4194 * self.think = nextthink;
4198 fld_think = parser_find_field(parser, "think");
4199 fld_nextthink = parser_find_field(parser, "nextthink");
4200 fld_frame = parser_find_field(parser, "frame");
4201 if (!fld_think || !fld_nextthink || !fld_frame) {
4202 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4203 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4206 gbl_time = parser_find_global(parser, "time");
4207 gbl_self = parser_find_global(parser, "self");
4208 if (!gbl_time || !gbl_self) {
4209 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4210 parseerror(parser, "please declare the following globals: `time`, `self`");
4214 if (!parser_next(parser))
4217 framenum = parse_expression_leave(parser, true, false, false);
4219 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4222 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4223 ast_unref(framenum);
4224 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4228 if (parser->tok != ',') {
4229 ast_unref(framenum);
4230 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4231 parseerror(parser, "Got a %i\n", parser->tok);
4235 if (!parser_next(parser)) {
4236 ast_unref(framenum);
4240 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4242 /* qc allows the use of not-yet-declared functions here
4243 * - this automatically creates a prototype */
4244 ast_value *thinkfunc;
4245 ast_expression *functype = fld_think->next;
4247 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4248 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4249 ast_unref(framenum);
4250 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4253 ast_type_adopt(thinkfunc, functype);
4255 if (!parser_next(parser)) {
4256 ast_unref(framenum);
4257 ast_delete(thinkfunc);
4261 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4263 nextthink = (ast_expression*)thinkfunc;
4266 nextthink = parse_expression_leave(parser, true, false, false);
4268 ast_unref(framenum);
4269 parseerror(parser, "expected a think-function in [frame,think] notation");
4274 if (!ast_istype(nextthink, ast_value)) {
4275 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4279 if (retval && parser->tok != ']') {
4280 parseerror(parser, "expected closing `]` for [frame,think] notation");
4284 if (retval && !parser_next(parser)) {
4288 if (retval && parser->tok != '{') {
4289 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4294 ast_unref(nextthink);
4295 ast_unref(framenum);
4299 has_frame_think = true;
4302 block = ast_block_new(parser_ctx(parser));
4304 parseerror(parser, "failed to allocate block");
4305 if (has_frame_think) {
4306 ast_unref(nextthink);
4307 ast_unref(framenum);
4312 if (has_frame_think) {
4314 ast_expression *self_frame;
4315 ast_expression *self_nextthink;
4316 ast_expression *self_think;
4317 ast_expression *time_plus_1;
4318 ast_store *store_frame;
4319 ast_store *store_nextthink;
4320 ast_store *store_think;
4322 ctx = parser_ctx(parser);
4323 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4324 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4325 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4327 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4328 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4330 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4331 if (self_frame) ast_delete(self_frame);
4332 if (self_nextthink) ast_delete(self_nextthink);
4333 if (self_think) ast_delete(self_think);
4334 if (time_plus_1) ast_delete(time_plus_1);
4340 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4341 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4342 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4345 ast_delete(self_frame);
4348 if (!store_nextthink) {
4349 ast_delete(self_nextthink);
4353 ast_delete(self_think);
4357 if (store_frame) ast_delete(store_frame);
4358 if (store_nextthink) ast_delete(store_nextthink);
4359 if (store_think) ast_delete(store_think);
4362 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4363 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4364 !ast_block_add_expr(block, (ast_expression*)store_think))
4371 parseerror(parser, "failed to generate code for [frame,think]");
4372 ast_unref(nextthink);
4373 ast_unref(framenum);
4379 if (var->hasvalue) {
4380 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4381 ast_block_delete(block);
4385 func = ast_function_new(ast_ctx(var), var->name, var);
4387 parseerror(parser, "failed to allocate function for `%s`", var->name);
4388 ast_block_delete(block);
4391 vec_push(parser->functions, func);
4393 parser_enterblock(parser);
4395 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4397 ast_value *param = var->expression.params[parami];
4400 if (param->expression.vtype != TYPE_VECTOR &&
4401 (param->expression.vtype != TYPE_FIELD ||
4402 param->expression.next->vtype != TYPE_VECTOR))
4407 if (!create_vector_members(param, me)) {
4408 ast_block_delete(block);
4412 for (e = 0; e < 3; ++e) {
4413 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4414 ast_block_collect(block, (ast_expression*)me[e]);
4418 if (var->argcounter) {
4419 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4420 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4424 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4426 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4427 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4428 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4429 varargs->expression.count = 0;
4430 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4431 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4432 ast_delete(varargs);
4433 ast_block_delete(block);
4436 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4437 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4438 ast_delete(varargs);
4439 ast_block_delete(block);
4442 func->varargs = varargs;
4444 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4447 parser->function = func;
4448 if (!parse_block_into(parser, block)) {
4449 ast_block_delete(block);
4453 vec_push(func->blocks, block);
4456 parser->function = old;
4457 if (!parser_leaveblock(parser))
4459 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4460 parseerror(parser, "internal error: local scopes left");
4464 if (parser->tok == ';')
4465 return parser_next(parser);
4466 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4467 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4471 (void)!parser_leaveblock(parser);
4472 vec_pop(parser->functions);
4473 ast_function_delete(func);
4474 var->constval.vfunc = NULL;
4477 parser->function = old;
4481 static ast_expression *array_accessor_split(
4486 ast_expression *left,
4487 ast_expression *right
4493 lex_ctx ctx = ast_ctx(array);
4495 if (!left || !right) {
4496 if (left) ast_delete(left);
4497 if (right) ast_delete(right);
4501 cmp = ast_binary_new(ctx, INSTR_LT,
4502 (ast_expression*)index,
4503 (ast_expression*)parser_const_float(parser, middle));
4507 parseerror(parser, "internal error: failed to create comparison for array setter");
4511 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4513 ast_delete(cmp); /* will delete left and right */
4514 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4518 return (ast_expression*)ifthen;
4521 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4523 lex_ctx ctx = ast_ctx(array);
4525 if (from+1 == afterend) {
4526 /* set this value */
4529 ast_array_index *subscript;
4531 int assignop = type_store_instr[value->expression.vtype];
4533 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4534 assignop = INSTR_STORE_V;
4536 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4540 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4542 ast_delete(subscript);
4546 block = ast_block_new(ctx);
4552 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4557 ret = ast_return_new(ctx, NULL);
4563 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4568 return (ast_expression*)block;
4570 ast_expression *left, *right;
4571 size_t diff = afterend - from;
4572 size_t middle = from + diff/2;
4573 left = array_setter_node(parser, array, index, value, from, middle);
4574 right = array_setter_node(parser, array, index, value, middle, afterend);
4575 return array_accessor_split(parser, array, index, middle, left, right);
4579 static ast_expression *array_field_setter_node(
4588 lex_ctx ctx = ast_ctx(array);
4590 if (from+1 == afterend) {
4591 /* set this value */
4594 ast_entfield *entfield;
4595 ast_array_index *subscript;
4597 int assignop = type_storep_instr[value->expression.vtype];
4599 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4600 assignop = INSTR_STOREP_V;
4602 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4606 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4607 subscript->expression.vtype = TYPE_FIELD;
4609 entfield = ast_entfield_new_force(ctx,
4610 (ast_expression*)entity,
4611 (ast_expression*)subscript,
4612 (ast_expression*)subscript);
4614 ast_delete(subscript);
4618 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4620 ast_delete(entfield);
4624 block = ast_block_new(ctx);
4630 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4635 ret = ast_return_new(ctx, NULL);
4641 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4646 return (ast_expression*)block;
4648 ast_expression *left, *right;
4649 size_t diff = afterend - from;
4650 size_t middle = from + diff/2;
4651 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4652 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4653 return array_accessor_split(parser, array, index, middle, left, right);
4657 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4659 lex_ctx ctx = ast_ctx(array);
4661 if (from+1 == afterend) {
4663 ast_array_index *subscript;
4665 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4669 ret = ast_return_new(ctx, (ast_expression*)subscript);
4671 ast_delete(subscript);
4675 return (ast_expression*)ret;
4677 ast_expression *left, *right;
4678 size_t diff = afterend - from;
4679 size_t middle = from + diff/2;
4680 left = array_getter_node(parser, array, index, from, middle);
4681 right = array_getter_node(parser, array, index, middle, afterend);
4682 return array_accessor_split(parser, array, index, middle, left, right);
4686 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4688 ast_function *func = NULL;
4689 ast_value *fval = NULL;
4690 ast_block *body = NULL;
4692 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4694 parseerror(parser, "failed to create accessor function value");
4698 func = ast_function_new(ast_ctx(array), funcname, fval);
4701 parseerror(parser, "failed to create accessor function node");
4705 body = ast_block_new(ast_ctx(array));
4707 parseerror(parser, "failed to create block for array accessor");
4713 vec_push(func->blocks, body);
4716 vec_push(parser->accessors, fval);
4721 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4723 ast_value *index = NULL;
4724 ast_value *value = NULL;
4728 if (!ast_istype(array->expression.next, ast_value)) {
4729 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4733 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4735 func = fval->constval.vfunc;
4736 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4738 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4739 value = ast_value_copy((ast_value*)array->expression.next);
4741 if (!index || !value) {
4742 parseerror(parser, "failed to create locals for array accessor");
4745 (void)!ast_value_set_name(value, "value"); /* not important */
4746 vec_push(fval->expression.params, index);
4747 vec_push(fval->expression.params, value);
4749 array->setter = fval;
4752 if (index) ast_delete(index);
4753 if (value) ast_delete(value);
4759 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4761 ast_expression *root = NULL;
4762 root = array_setter_node(parser, array,
4763 array->setter->expression.params[0],
4764 array->setter->expression.params[1],
4765 0, array->expression.count);
4767 parseerror(parser, "failed to build accessor search tree");
4770 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4777 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4779 if (!parser_create_array_setter_proto(parser, array, funcname))
4781 return parser_create_array_setter_impl(parser, array);
4784 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4786 ast_expression *root = NULL;
4787 ast_value *entity = NULL;
4788 ast_value *index = NULL;
4789 ast_value *value = NULL;
4793 if (!ast_istype(array->expression.next, ast_value)) {
4794 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4798 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4800 func = fval->constval.vfunc;
4801 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4803 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4804 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4805 value = ast_value_copy((ast_value*)array->expression.next);
4806 if (!entity || !index || !value) {
4807 parseerror(parser, "failed to create locals for array accessor");
4810 (void)!ast_value_set_name(value, "value"); /* not important */
4811 vec_push(fval->expression.params, entity);
4812 vec_push(fval->expression.params, index);
4813 vec_push(fval->expression.params, value);
4815 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4817 parseerror(parser, "failed to build accessor search tree");
4821 array->setter = fval;
4822 return ast_block_add_expr(func->blocks[0], root);
4824 if (entity) ast_delete(entity);
4825 if (index) ast_delete(index);
4826 if (value) ast_delete(value);
4827 if (root) ast_delete(root);
4833 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4835 ast_value *index = NULL;
4839 /* NOTE: checking array->expression.next rather than elemtype since
4840 * for fields elemtype is a temporary fieldtype.
4842 if (!ast_istype(array->expression.next, ast_value)) {
4843 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4847 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4849 func = fval->constval.vfunc;
4850 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4852 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4855 parseerror(parser, "failed to create locals for array accessor");
4858 vec_push(fval->expression.params, index);
4860 array->getter = fval;
4863 if (index) ast_delete(index);
4869 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4871 ast_expression *root = NULL;
4873 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4875 parseerror(parser, "failed to build accessor search tree");
4878 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4885 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4887 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4889 return parser_create_array_getter_impl(parser, array);
4892 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4893 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4901 bool variadic = false;
4902 ast_value *varparam = NULL;
4903 char *argcounter = NULL;
4905 ctx = parser_ctx(parser);
4907 /* for the sake of less code we parse-in in this function */
4908 if (!parser_next(parser)) {
4910 parseerror(parser, "expected parameter list");
4916 /* parse variables until we hit a closing paren */
4917 while (parser->tok != ')') {
4919 /* there must be commas between them */
4920 if (parser->tok != ',') {
4921 parseerror(parser, "expected comma or end of parameter list");
4924 if (!parser_next(parser)) {
4925 parseerror(parser, "expected parameter");
4931 if (parser->tok == TOKEN_DOTS) {
4932 /* '...' indicates a varargs function */
4934 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4935 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4938 if (parser->tok == TOKEN_IDENT) {
4939 argcounter = util_strdup(parser_tokval(parser));
4940 if (!parser_next(parser) || parser->tok != ')') {
4941 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4948 /* for anything else just parse a typename */
4949 param = parse_typename(parser, NULL, NULL);
4952 vec_push(params, param);
4953 if (param->expression.vtype >= TYPE_VARIANT) {
4954 char tname[1024]; /* typename is reserved in C++ */
4955 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4956 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4959 /* type-restricted varargs */
4960 if (parser->tok == TOKEN_DOTS) {
4962 varparam = vec_last(params);
4964 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4965 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4968 if (parser->tok == TOKEN_IDENT) {
4969 argcounter = util_strdup(parser_tokval(parser));
4970 if (!parser_next(parser) || parser->tok != ')') {
4971 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4979 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4983 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4984 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4987 if (!parser_next(parser)) {
4988 parseerror(parser, "parse error after typename");
4992 /* now turn 'var' into a function type */
4993 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4994 fval->expression.next = (ast_expression*)var;
4996 fval->expression.flags |= AST_FLAG_VARIADIC;
4999 var->expression.params = params;
5000 var->expression.varparam = (ast_expression*)varparam;
5001 var->argcounter = argcounter;
5010 ast_delete(varparam);
5012 for (i = 0; i < vec_size(params); ++i)
5013 ast_delete(params[i]);
5018 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5020 ast_expression *cexp;
5021 ast_value *cval, *tmp;
5024 ctx = parser_ctx(parser);
5026 if (!parser_next(parser)) {
5028 parseerror(parser, "expected array-size");
5032 if (parser->tok != ']') {
5033 cexp = parse_expression_leave(parser, true, false, false);
5035 if (!cexp || !ast_istype(cexp, ast_value)) {
5039 parseerror(parser, "expected array-size as constant positive integer");
5042 cval = (ast_value*)cexp;
5049 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5050 tmp->expression.next = (ast_expression*)var;
5054 if (cval->expression.vtype == TYPE_INTEGER)
5055 tmp->expression.count = cval->constval.vint;
5056 else if (cval->expression.vtype == TYPE_FLOAT)
5057 tmp->expression.count = cval->constval.vfloat;
5061 parseerror(parser, "array-size must be a positive integer constant");
5067 var->expression.count = -1;
5068 var->expression.flags |= AST_FLAG_ARRAY_INIT;
5071 if (parser->tok != ']') {
5073 parseerror(parser, "expected ']' after array-size");
5076 if (!parser_next(parser)) {
5078 parseerror(parser, "error after parsing array size");
5084 /* Parse a complete typename.
5085 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5086 * but when parsing variables separated by comma
5087 * 'storebase' should point to where the base-type should be kept.
5088 * The base type makes up every bit of type information which comes *before* the
5091 * The following will be parsed in its entirety:
5093 * The 'basetype' in this case is 'void()'
5094 * and if there's a comma after it, say:
5096 * then the type-information 'void()' can be stored in 'storebase'
5098 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5100 ast_value *var, *tmp;
5103 const char *name = NULL;
5104 bool isfield = false;
5105 bool wasarray = false;
5106 size_t morefields = 0;
5108 ctx = parser_ctx(parser);
5110 /* types may start with a dot */
5111 if (parser->tok == '.') {
5113 /* if we parsed a dot we need a typename now */
5114 if (!parser_next(parser)) {
5115 parseerror(parser, "expected typename for field definition");
5119 /* Further dots are handled seperately because they won't be part of the
5122 while (parser->tok == '.') {
5124 if (!parser_next(parser)) {
5125 parseerror(parser, "expected typename for field definition");
5130 if (parser->tok == TOKEN_IDENT)
5131 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5132 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5133 parseerror(parser, "expected typename");
5137 /* generate the basic type value */
5138 if (cached_typedef) {
5139 var = ast_value_copy(cached_typedef);
5140 ast_value_set_name(var, "<type(from_def)>");
5142 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5144 for (; morefields; --morefields) {
5145 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5146 tmp->expression.next = (ast_expression*)var;
5150 /* do not yet turn into a field - remember:
5151 * .void() foo; is a field too
5152 * .void()() foo; is a function
5156 if (!parser_next(parser)) {
5158 parseerror(parser, "parse error after typename");
5162 /* an opening paren now starts the parameter-list of a function
5163 * this is where original-QC has parameter lists.
5164 * We allow a single parameter list here.
5165 * Much like fteqcc we don't allow `float()() x`
5167 if (parser->tok == '(') {
5168 var = parse_parameter_list(parser, var);
5173 /* store the base if requested */
5175 *storebase = ast_value_copy(var);
5177 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5178 tmp->expression.next = (ast_expression*)*storebase;
5183 /* there may be a name now */
5184 if (parser->tok == TOKEN_IDENT) {
5185 name = util_strdup(parser_tokval(parser));
5187 if (!parser_next(parser)) {
5190 parseerror(parser, "error after variable or field declaration");
5195 /* now this may be an array */
5196 if (parser->tok == '[') {
5198 var = parse_arraysize(parser, var);
5200 if (name) mem_d(name);
5205 /* This is the point where we can turn it into a field */
5207 /* turn it into a field if desired */
5208 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5209 tmp->expression.next = (ast_expression*)var;
5213 /* now there may be function parens again */
5214 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5215 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5216 if (parser->tok == '(' && wasarray)
5217 parseerror(parser, "arrays as part of a return type is not supported");
5218 while (parser->tok == '(') {
5219 var = parse_parameter_list(parser, var);
5221 if (name) mem_d(name);
5226 /* finally name it */
5228 if (!ast_value_set_name(var, name)) {
5231 parseerror(parser, "internal error: failed to set name");
5234 /* free the name, ast_value_set_name duplicates */
5241 static bool parse_typedef(parser_t *parser)
5243 ast_value *typevar, *oldtype;
5244 ast_expression *old;
5246 typevar = parse_typename(parser, NULL, NULL);
5251 if ( (old = parser_find_var(parser, typevar->name)) ) {
5252 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5253 " -> `%s` has been declared here: %s:%i",
5254 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5255 ast_delete(typevar);
5259 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5260 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5261 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5262 ast_delete(typevar);
5266 vec_push(parser->_typedefs, typevar);
5267 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5269 if (parser->tok != ';') {
5270 parseerror(parser, "expected semicolon after typedef");
5273 if (!parser_next(parser)) {
5274 parseerror(parser, "parse error after typedef");
5281 static const char *cvq_to_str(int cvq) {
5283 case CV_NONE: return "none";
5284 case CV_VAR: return "`var`";
5285 case CV_CONST: return "`const`";
5286 default: return "<INVALID>";
5290 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5293 if (proto->cvq != var->cvq) {
5294 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5295 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5296 parser->tok == '='))
5298 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5299 "`%s` declared with different qualifiers: %s\n"
5300 " -> previous declaration here: %s:%i uses %s",
5301 var->name, cvq_to_str(var->cvq),
5302 ast_ctx(proto).file, ast_ctx(proto).line,
5303 cvq_to_str(proto->cvq));
5306 av = (var ->expression.flags & AST_FLAG_NORETURN);
5307 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5309 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5310 "`%s` declared with different attributes%s\n"
5311 " -> previous declaration here: %s:%i",
5312 var->name, (av ? ": noreturn" : ""),
5313 ast_ctx(proto).file, ast_ctx(proto).line,
5314 (ao ? ": noreturn" : ""));
5319 static bool create_array_accessors(parser_t *parser, ast_value *var)
5322 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5323 if (!parser_create_array_setter(parser, var, name))
5325 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5326 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5331 static bool parse_array(parser_t *parser, ast_value *array)
5334 if (array->initlist) {
5335 parseerror(parser, "array already initialized elsewhere");
5338 if (!parser_next(parser)) {
5339 parseerror(parser, "parse error in array initializer");
5343 while (parser->tok != '}') {
5344 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5347 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5349 parseerror(parser, "initializing element must be a compile time constant");
5352 vec_push(array->initlist, v->constval);
5353 if (v->expression.vtype == TYPE_STRING) {
5354 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5358 if (parser->tok == '}')
5360 if (parser->tok != ',' || !parser_next(parser)) {
5361 parseerror(parser, "expected comma or '}' in element list");
5365 if (!parser_next(parser) || parser->tok != ';') {
5366 parseerror(parser, "expected semicolon after initializer, got %s");
5370 if (!parser_next(parser)) {
5371 parseerror(parser, "parse error after initializer");
5376 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5377 if (array->expression.count != (size_t)-1) {
5378 parseerror(parser, "array `%s' has already been initialized with %u elements",
5379 array->name, (unsigned)array->expression.count);
5381 array->expression.count = vec_size(array->initlist);
5382 if (!create_array_accessors(parser, array))
5388 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)
5392 ast_expression *old;
5396 ast_value *basetype = NULL;
5398 bool isparam = false;
5399 bool isvector = false;
5400 bool cleanvar = true;
5401 bool wasarray = false;
5403 ast_member *me[3] = { NULL, NULL, NULL };
5405 if (!localblock && is_static)
5406 parseerror(parser, "`static` qualifier is not supported in global scope");
5408 /* get the first complete variable */
5409 var = parse_typename(parser, &basetype, cached_typedef);
5412 ast_delete(basetype);
5420 /* Part 0: finish the type */
5421 if (parser->tok == '(') {
5422 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5423 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5424 var = parse_parameter_list(parser, var);
5430 /* we only allow 1-dimensional arrays */
5431 if (parser->tok == '[') {
5433 var = parse_arraysize(parser, var);
5439 if (parser->tok == '(' && wasarray) {
5440 parseerror(parser, "arrays as part of a return type is not supported");
5441 /* we'll still parse the type completely for now */
5443 /* for functions returning functions */
5444 while (parser->tok == '(') {
5445 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5446 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5447 var = parse_parameter_list(parser, var);
5454 var->cvq = qualifier;
5455 var->expression.flags |= qflags;
5458 * store the vstring back to var for alias and
5459 * deprecation messages.
5461 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5462 var->expression.flags & AST_FLAG_ALIAS)
5463 var->desc = vstring;
5466 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5467 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5468 * is then filled with the previous definition and the parameter-names replaced.
5470 if (!strcmp(var->name, "nil")) {
5471 if (OPTS_FLAG(UNTYPED_NIL)) {
5472 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5473 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5475 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5478 /* Deal with end_sys_ vars */
5480 if (!strcmp(var->name, "end_sys_globals")) {
5482 parser->crc_globals = vec_size(parser->globals);
5485 else if (!strcmp(var->name, "end_sys_fields")) {
5487 parser->crc_fields = vec_size(parser->fields);
5490 if (was_end && var->expression.vtype == TYPE_FIELD) {
5491 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5492 "global '%s' hint should not be a field",
5493 parser_tokval(parser)))
5500 if (!nofields && var->expression.vtype == TYPE_FIELD)
5502 /* deal with field declarations */
5503 old = parser_find_field(parser, var->name);
5505 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5506 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5515 parseerror(parser, "field `%s` already declared here: %s:%i",
5516 var->name, ast_ctx(old).file, ast_ctx(old).line);
5521 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5522 (old = parser_find_global(parser, var->name)))
5524 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5525 parseerror(parser, "field `%s` already declared here: %s:%i",
5526 var->name, ast_ctx(old).file, ast_ctx(old).line);
5533 /* deal with other globals */
5534 old = parser_find_global(parser, var->name);
5535 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5537 /* This is a function which had a prototype */
5538 if (!ast_istype(old, ast_value)) {
5539 parseerror(parser, "internal error: prototype is not an ast_value");
5543 proto = (ast_value*)old;
5544 proto->desc = var->desc;
5545 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5546 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5548 ast_ctx(proto).file, ast_ctx(proto).line);
5552 /* we need the new parameter-names */
5553 for (i = 0; i < vec_size(proto->expression.params); ++i)
5554 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5555 if (!parser_check_qualifiers(parser, var, proto)) {
5562 proto->expression.flags |= var->expression.flags;
5570 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5571 "global `%s` already declared here: %s:%i",
5572 var->name, ast_ctx(old).file, ast_ctx(old).line))
5577 proto = (ast_value*)old;
5578 if (!ast_istype(old, ast_value)) {
5579 parseerror(parser, "internal error: not an ast_value");
5584 if (!parser_check_qualifiers(parser, var, proto)) {
5589 proto->expression.flags |= var->expression.flags;
5593 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5594 (old = parser_find_field(parser, var->name)))
5596 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5597 parseerror(parser, "global `%s` already declared here: %s:%i",
5598 var->name, ast_ctx(old).file, ast_ctx(old).line);
5605 else /* it's not a global */
5607 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5608 if (old && !isparam) {
5609 parseerror(parser, "local `%s` already declared here: %s:%i",
5610 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5614 old = parser_find_local(parser, var->name, 0, &isparam);
5615 if (old && isparam) {
5616 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5617 "local `%s` is shadowing a parameter", var->name))
5619 parseerror(parser, "local `%s` already declared here: %s:%i",
5620 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5624 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5632 /* in a noref section we simply bump the usecount */
5633 if (noref || parser->noref)
5637 * Create the global/local, and deal with vector types.
5640 if (var->expression.vtype == TYPE_VECTOR)
5642 else if (var->expression.vtype == TYPE_FIELD &&
5643 var->expression.next->vtype == TYPE_VECTOR)
5647 if (!create_vector_members(var, me)) {
5654 /* deal with global variables, fields, functions */
5655 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5656 var->isfield = true;
5657 vec_push(parser->fields, (ast_expression*)var);
5658 util_htset(parser->htfields, var->name, var);
5660 for (i = 0; i < 3; ++i) {
5661 vec_push(parser->fields, (ast_expression*)me[i]);
5662 util_htset(parser->htfields, me[i]->name, me[i]);
5667 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5668 parser_addglobal(parser, var->name, (ast_expression*)var);
5670 for (i = 0; i < 3; ++i) {
5671 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5675 ast_expression *find = parser_find_global(parser, var->desc);
5678 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5682 if (var->expression.vtype != find->vtype) {
5686 ast_type_to_string(find, ty1, sizeof(ty1));
5687 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5689 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5696 * add alias to aliases table and to corrector
5697 * so corrections can apply for aliases as well.
5699 util_htset(parser->aliases, var->name, find);
5702 * add to corrector so corrections can work
5703 * even for aliases too.
5706 vec_last(parser->correct_variables),
5707 &vec_last(parser->correct_variables_score),
5711 /* generate aliases for vector components */
5715 util_asprintf(&buffer[0], "%s_x", var->desc);
5716 util_asprintf(&buffer[1], "%s_y", var->desc);
5717 util_asprintf(&buffer[2], "%s_z", var->desc);
5719 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5720 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5721 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5728 * add to corrector so corrections can work
5729 * even for aliases too.
5732 vec_last(parser->correct_variables),
5733 &vec_last(parser->correct_variables_score),
5737 vec_last(parser->correct_variables),
5738 &vec_last(parser->correct_variables_score),
5742 vec_last(parser->correct_variables),
5743 &vec_last(parser->correct_variables_score),
5751 /* a static adds itself to be generated like any other global
5752 * but is added to the local namespace instead
5754 char *defname = NULL;
5755 size_t prefix_len, ln;
5757 ln = strlen(parser->function->name);
5758 vec_append(defname, ln, parser->function->name);
5760 vec_append(defname, 2, "::");
5761 /* remember the length up to here */
5762 prefix_len = vec_size(defname);
5764 /* Add it to the local scope */
5765 util_htset(vec_last(parser->variables), var->name, (void*)var);
5769 vec_last(parser->correct_variables),
5770 &vec_last(parser->correct_variables_score),
5774 /* now rename the global */
5775 ln = strlen(var->name);
5776 vec_append(defname, ln, var->name);
5777 ast_value_set_name(var, defname);
5779 /* push it to the to-be-generated globals */
5780 vec_push(parser->globals, (ast_expression*)var);
5782 /* same game for the vector members */
5784 for (i = 0; i < 3; ++i) {
5785 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5789 vec_last(parser->correct_variables),
5790 &vec_last(parser->correct_variables_score),
5794 vec_shrinkto(defname, prefix_len);
5795 ln = strlen(me[i]->name);
5796 vec_append(defname, ln, me[i]->name);
5797 ast_member_set_name(me[i], defname);
5799 vec_push(parser->globals, (ast_expression*)me[i]);
5804 vec_push(localblock->locals, var);
5805 parser_addlocal(parser, var->name, (ast_expression*)var);
5807 for (i = 0; i < 3; ++i) {
5808 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5809 ast_block_collect(localblock, (ast_expression*)me[i]);
5815 me[0] = me[1] = me[2] = NULL;
5820 if (var->expression.vtype == TYPE_ARRAY) {
5821 if (var->expression.count != (size_t)-1) {
5822 if (!create_array_accessors(parser, var))
5826 else if (!localblock && !nofields &&
5827 var->expression.vtype == TYPE_FIELD &&
5828 var->expression.next->vtype == TYPE_ARRAY)
5831 ast_expression *telem;
5833 ast_value *array = (ast_value*)var->expression.next;
5835 if (!ast_istype(var->expression.next, ast_value)) {
5836 parseerror(parser, "internal error: field element type must be an ast_value");
5840 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5841 if (!parser_create_array_field_setter(parser, array, name))
5844 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5845 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5846 tfield->expression.next = telem;
5847 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5848 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5856 if (parser->tok == ';') {
5857 ast_delete(basetype);
5858 if (!parser_next(parser)) {
5859 parseerror(parser, "error after variable declaration");
5865 if (parser->tok == ',')
5869 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5872 parseerror(parser, "missing comma or semicolon while parsing variables");
5876 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5877 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5878 "initializing expression turns variable `%s` into a constant in this standard",
5885 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5886 if (parser->tok != '=') {
5887 if (!strcmp(parser_tokval(parser), "break")) {
5888 if (!parser_next(parser)) {
5889 parseerror(parser, "error parsing break definition");
5892 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5894 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5899 if (!parser_next(parser)) {
5900 parseerror(parser, "error parsing initializer");
5904 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5905 parseerror(parser, "expected '=' before function body in this standard");
5908 if (parser->tok == '#') {
5909 ast_function *func = NULL;
5910 ast_value *number = NULL;
5916 parseerror(parser, "cannot declare builtins within functions");
5919 if (var->expression.vtype != TYPE_FUNCTION) {
5920 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5923 if (!parser_next(parser)) {
5924 parseerror(parser, "expected builtin number");
5928 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5929 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5931 parseerror(parser, "builtin number expected");
5934 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5937 parseerror(parser, "builtin number must be a compile time constant");
5940 if (number->expression.vtype == TYPE_INTEGER)
5941 builtin_num = number->constval.vint;
5942 else if (number->expression.vtype == TYPE_FLOAT)
5943 builtin_num = number->constval.vfloat;
5946 parseerror(parser, "builtin number must be an integer constant");
5951 fractional = modff(builtin_num, &integral);
5952 if (builtin_num < 0 || fractional != 0) {
5953 parseerror(parser, "builtin number must be an integer greater than zero");
5957 /* we only want the integral part anyways */
5958 builtin_num = integral;
5959 } else if (parser->tok == TOKEN_INTCONST) {
5960 builtin_num = parser_token(parser)->constval.i;
5962 parseerror(parser, "builtin number must be a compile time constant");
5966 if (var->hasvalue) {
5967 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5968 "builtin `%s` has already been defined\n"
5969 " -> previous declaration here: %s:%i",
5970 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5974 func = ast_function_new(ast_ctx(var), var->name, var);
5976 parseerror(parser, "failed to allocate function for `%s`", var->name);
5979 vec_push(parser->functions, func);
5981 func->builtin = -builtin_num-1;
5984 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5985 ? (parser->tok != ',' && parser->tok != ';')
5986 : (!parser_next(parser)))
5988 parseerror(parser, "expected comma or semicolon");
5990 ast_function_delete(func);
5991 var->constval.vfunc = NULL;
5995 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5998 /* Note that fteqcc and most others don't even *have*
5999 * local arrays, so this is not a high priority.
6001 parseerror(parser, "TODO: initializers for local arrays");
6005 var->hasvalue = true;
6006 if (!parse_array(parser, var))
6009 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
6012 parseerror(parser, "cannot declare functions within functions");
6017 ast_ctx(proto) = parser_ctx(parser);
6019 if (!parse_function_body(parser, var))
6021 ast_delete(basetype);
6022 for (i = 0; i < vec_size(parser->gotos); ++i)
6023 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
6024 vec_free(parser->gotos);
6025 vec_free(parser->labels);
6028 ast_expression *cexp;
6031 cexp = parse_expression_leave(parser, true, false, false);
6036 cval = (ast_value*)cexp;
6037 if (cval != parser->nil &&
6038 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
6041 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
6045 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
6046 qualifier != CV_VAR)
6048 var->cvq = CV_CONST;
6050 if (cval == parser->nil)
6051 var->expression.flags |= AST_FLAG_INITIALIZED;
6054 var->hasvalue = true;
6055 if (cval->expression.vtype == TYPE_STRING)
6056 var->constval.vstring = parser_strdup(cval->constval.vstring);
6057 else if (cval->expression.vtype == TYPE_FIELD)
6058 var->constval.vfield = cval;
6060 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
6066 shunt sy = { NULL, NULL, NULL, NULL };
6069 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
6070 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
6071 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
6072 if (!parser_sy_apply_operator(parser, &sy))
6075 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
6076 parseerror(parser, "internal error: leaked operands");
6077 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
6088 if (parser->tok == ',') {
6089 if (!parser_next(parser)) {
6090 parseerror(parser, "expected another variable");
6094 if (parser->tok != TOKEN_IDENT) {
6095 parseerror(parser, "expected another variable");
6098 var = ast_value_copy(basetype);
6100 ast_value_set_name(var, parser_tokval(parser));
6101 if (!parser_next(parser)) {
6102 parseerror(parser, "error parsing variable declaration");
6108 if (parser->tok != ';') {
6109 parseerror(parser, "missing semicolon after variables");
6113 if (!parser_next(parser)) {
6114 parseerror(parser, "parse error after variable declaration");
6118 ast_delete(basetype);
6122 if (cleanvar && var)
6124 ast_delete(basetype);
6128 ast_delete(basetype);
6129 if (cleanvar && var)
6131 if (me[0]) ast_member_delete(me[0]);
6132 if (me[1]) ast_member_delete(me[1]);
6133 if (me[2]) ast_member_delete(me[2]);
6137 static bool parser_global_statement(parser_t *parser)
6141 bool is_static = false;
6142 uint32_t qflags = 0;
6143 ast_value *istype = NULL;
6144 char *vstring = NULL;
6146 if (parser->tok == TOKEN_IDENT)
6147 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6149 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6151 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6153 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6155 if (cvq == CV_WRONG)
6157 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6159 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6161 return parse_enum(parser);
6163 else if (parser->tok == TOKEN_KEYWORD)
6165 if (!strcmp(parser_tokval(parser), "typedef")) {
6166 if (!parser_next(parser)) {
6167 parseerror(parser, "expected type definition after 'typedef'");
6170 return parse_typedef(parser);
6172 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6175 else if (parser->tok == '#')
6177 return parse_pragma(parser);
6179 else if (parser->tok == '$')
6181 if (!parser_next(parser)) {
6182 parseerror(parser, "parse error");
6188 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6194 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6196 return util_crc16(old, str, strlen(str));
6199 static void progdefs_crc_file(const char *str)
6201 /* write to progdefs.h here */
6205 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6207 old = progdefs_crc_sum(old, str);
6208 progdefs_crc_file(str);
6212 static void generate_checksum(parser_t *parser, ir_builder *ir)
6214 uint16_t crc = 0xFFFF;
6218 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6219 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6221 progdefs_crc_file("\tint\tpad;\n");
6222 progdefs_crc_file("\tint\tofs_return[3];\n");
6223 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6224 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6225 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6226 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6227 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6228 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6229 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6230 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6232 for (i = 0; i < parser->crc_globals; ++i) {
6233 if (!ast_istype(parser->globals[i], ast_value))
6235 value = (ast_value*)(parser->globals[i]);
6236 switch (value->expression.vtype) {
6237 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6238 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6239 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6240 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6242 crc = progdefs_crc_both(crc, "\tint\t");
6245 crc = progdefs_crc_both(crc, value->name);
6246 crc = progdefs_crc_both(crc, ";\n");
6248 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6249 for (i = 0; i < parser->crc_fields; ++i) {
6250 if (!ast_istype(parser->fields[i], ast_value))
6252 value = (ast_value*)(parser->fields[i]);
6253 switch (value->expression.next->vtype) {
6254 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6255 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6256 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6257 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6259 crc = progdefs_crc_both(crc, "\tint\t");
6262 crc = progdefs_crc_both(crc, value->name);
6263 crc = progdefs_crc_both(crc, ";\n");
6265 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6266 ir->code->crc = crc;
6269 parser_t *parser_create()
6275 parser = (parser_t*)mem_a(sizeof(parser_t));
6279 memset(parser, 0, sizeof(*parser));
6281 for (i = 0; i < operator_count; ++i) {
6282 if (operators[i].id == opid1('=')) {
6283 parser->assign_op = operators+i;
6287 if (!parser->assign_op) {
6288 printf("internal error: initializing parser: failed to find assign operator\n");
6293 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6294 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6295 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6296 vec_push(parser->_blocktypedefs, 0);
6298 parser->aliases = util_htnew(PARSER_HT_SIZE);
6300 parser->ht_imm_string = util_htnew(512);
6303 vec_push(parser->correct_variables, correct_trie_new());
6304 vec_push(parser->correct_variables_score, NULL);
6306 empty_ctx.file = "<internal>";
6308 empty_ctx.column = 0;
6309 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6310 parser->nil->cvq = CV_CONST;
6311 if (OPTS_FLAG(UNTYPED_NIL))
6312 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6314 parser->max_param_count = 1;
6316 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6317 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6318 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6320 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6321 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6322 parser->reserved_version->cvq = CV_CONST;
6323 parser->reserved_version->hasvalue = true;
6324 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6325 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6327 parser->reserved_version = NULL;
6333 static bool parser_compile(parser_t *parser)
6335 /* initial lexer/parser state */
6336 parser->lex->flags.noops = true;
6338 if (parser_next(parser))
6340 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6342 if (!parser_global_statement(parser)) {
6343 if (parser->tok == TOKEN_EOF)
6344 parseerror(parser, "unexpected end of file");
6345 else if (compile_errors)
6346 parseerror(parser, "there have been errors, bailing out");
6347 lex_close(parser->lex);
6353 parseerror(parser, "parse error");
6354 lex_close(parser->lex);
6359 lex_close(parser->lex);
6362 return !compile_errors;
6365 bool parser_compile_file(parser_t *parser, const char *filename)
6367 parser->lex = lex_open(filename);
6369 con_err("failed to open file \"%s\"\n", filename);
6372 return parser_compile(parser);
6375 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6377 parser->lex = lex_open_string(str, len, name);
6379 con_err("failed to create lexer for string \"%s\"\n", name);
6382 return parser_compile(parser);
6385 static void parser_remove_ast(parser_t *parser)
6388 if (parser->ast_cleaned)
6390 parser->ast_cleaned = true;
6391 for (i = 0; i < vec_size(parser->accessors); ++i) {
6392 ast_delete(parser->accessors[i]->constval.vfunc);
6393 parser->accessors[i]->constval.vfunc = NULL;
6394 ast_delete(parser->accessors[i]);
6396 for (i = 0; i < vec_size(parser->functions); ++i) {
6397 ast_delete(parser->functions[i]);
6399 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6400 ast_delete(parser->imm_vector[i]);
6402 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6403 ast_delete(parser->imm_string[i]);
6405 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6406 ast_delete(parser->imm_float[i]);
6408 for (i = 0; i < vec_size(parser->fields); ++i) {
6409 ast_delete(parser->fields[i]);
6411 for (i = 0; i < vec_size(parser->globals); ++i) {
6412 ast_delete(parser->globals[i]);
6414 vec_free(parser->accessors);
6415 vec_free(parser->functions);
6416 vec_free(parser->imm_vector);
6417 vec_free(parser->imm_string);
6418 util_htdel(parser->ht_imm_string);
6419 vec_free(parser->imm_float);
6420 vec_free(parser->globals);
6421 vec_free(parser->fields);
6423 for (i = 0; i < vec_size(parser->variables); ++i)
6424 util_htdel(parser->variables[i]);
6425 vec_free(parser->variables);
6426 vec_free(parser->_blocklocals);
6427 vec_free(parser->_locals);
6430 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6431 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6433 vec_free(parser->correct_variables);
6434 vec_free(parser->correct_variables_score);
6436 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6437 ast_delete(parser->_typedefs[i]);
6438 vec_free(parser->_typedefs);
6439 for (i = 0; i < vec_size(parser->typedefs); ++i)
6440 util_htdel(parser->typedefs[i]);
6441 vec_free(parser->typedefs);
6442 vec_free(parser->_blocktypedefs);
6444 vec_free(parser->_block_ctx);
6446 vec_free(parser->labels);
6447 vec_free(parser->gotos);
6448 vec_free(parser->breaks);
6449 vec_free(parser->continues);
6451 ast_value_delete(parser->nil);
6453 ast_value_delete(parser->const_vec[0]);
6454 ast_value_delete(parser->const_vec[1]);
6455 ast_value_delete(parser->const_vec[2]);
6457 if (parser->reserved_version)
6458 ast_value_delete(parser->reserved_version);
6460 util_htdel(parser->aliases);
6461 intrin_intrinsics_destroy(parser);
6464 void parser_cleanup(parser_t *parser)
6466 parser_remove_ast(parser);
6470 bool parser_finish(parser_t *parser, const char *output)
6476 if (compile_errors) {
6477 con_out("*** there were compile errors\n");
6481 ir = ir_builder_new("gmqcc_out");
6483 con_out("failed to allocate builder\n");
6487 for (i = 0; i < vec_size(parser->fields); ++i) {
6490 if (!ast_istype(parser->fields[i], ast_value))
6492 field = (ast_value*)parser->fields[i];
6493 hasvalue = field->hasvalue;
6494 field->hasvalue = false;
6495 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6496 con_out("failed to generate field %s\n", field->name);
6497 ir_builder_delete(ir);
6502 ast_expression *subtype;
6503 field->hasvalue = true;
6504 subtype = field->expression.next;
6505 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6506 if (subtype->vtype == TYPE_FIELD)
6507 ifld->fieldtype = subtype->next->vtype;
6508 else if (subtype->vtype == TYPE_FUNCTION)
6509 ifld->outtype = subtype->next->vtype;
6510 (void)!ir_value_set_field(field->ir_v, ifld);
6513 for (i = 0; i < vec_size(parser->globals); ++i) {
6515 if (!ast_istype(parser->globals[i], ast_value))
6517 asvalue = (ast_value*)(parser->globals[i]);
6518 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6519 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6520 "unused global: `%s`", asvalue->name);
6522 if (!ast_global_codegen(asvalue, ir, false)) {
6523 con_out("failed to generate global %s\n", asvalue->name);
6524 ir_builder_delete(ir);
6528 /* Build function vararg accessor ast tree now before generating
6529 * immediates, because the accessors may add new immediates
6531 for (i = 0; i < vec_size(parser->functions); ++i) {
6532 ast_function *f = parser->functions[i];
6534 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6535 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6536 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6537 con_out("failed to generate vararg setter for %s\n", f->name);
6538 ir_builder_delete(ir);
6541 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6542 con_out("failed to generate vararg getter for %s\n", f->name);
6543 ir_builder_delete(ir);
6547 ast_delete(f->varargs);
6552 /* Now we can generate immediates */
6553 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6554 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6555 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6556 ir_builder_delete(ir);
6560 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6561 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6562 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6563 ir_builder_delete(ir);
6567 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6568 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6569 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6570 ir_builder_delete(ir);
6574 for (i = 0; i < vec_size(parser->globals); ++i) {
6576 if (!ast_istype(parser->globals[i], ast_value))
6578 asvalue = (ast_value*)(parser->globals[i]);
6579 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6581 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6582 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6583 "uninitialized constant: `%s`",
6585 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6586 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6587 "uninitialized global: `%s`",
6590 if (!ast_generate_accessors(asvalue, ir)) {
6591 ir_builder_delete(ir);
6595 for (i = 0; i < vec_size(parser->fields); ++i) {
6597 asvalue = (ast_value*)(parser->fields[i]->next);
6599 if (!ast_istype((ast_expression*)asvalue, ast_value))
6601 if (asvalue->expression.vtype != TYPE_ARRAY)
6603 if (!ast_generate_accessors(asvalue, ir)) {
6604 ir_builder_delete(ir);
6608 if (parser->reserved_version &&
6609 !ast_global_codegen(parser->reserved_version, ir, false))
6611 con_out("failed to generate reserved::version");
6612 ir_builder_delete(ir);
6615 for (i = 0; i < vec_size(parser->functions); ++i) {
6616 ast_function *f = parser->functions[i];
6617 if (!ast_function_codegen(f, ir)) {
6618 con_out("failed to generate function %s\n", f->name);
6619 ir_builder_delete(ir);
6624 generate_checksum(parser, ir);
6626 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6627 ir_builder_dump(ir, con_out);
6628 for (i = 0; i < vec_size(parser->functions); ++i) {
6629 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6630 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6631 ir_builder_delete(ir);
6635 parser_remove_ast(parser);
6637 if (compile_Werrors) {
6638 con_out("*** there were warnings treated as errors\n");
6639 compile_show_werrors();
6644 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6645 ir_builder_dump(ir, con_out);
6647 if (!ir_builder_generate(ir, output)) {
6648 con_out("*** failed to generate output file\n");
6649 ir_builder_delete(ir);
6653 ir_builder_delete(ir);