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;
112 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
114 static void parser_enterblock(parser_t *parser);
115 static bool parser_leaveblock(parser_t *parser);
116 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
117 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
118 static bool parse_typedef(parser_t *parser);
119 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);
120 static ast_block* parse_block(parser_t *parser);
121 static bool parse_block_into(parser_t *parser, ast_block *block);
122 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
123 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
124 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
125 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
126 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
127 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
128 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
130 static void parseerror(parser_t *parser, const char *fmt, ...)
134 vcompile_error(parser->lex->tok.ctx, fmt, ap);
138 /* returns true if it counts as an error */
139 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
144 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
149 /**********************************************************************
150 * some maths used for constant folding
153 vector vec3_add(vector a, vector b)
162 vector vec3_sub(vector a, vector b)
171 qcfloat vec3_mulvv(vector a, vector b)
173 return (a.x * b.x + a.y * b.y + a.z * b.z);
176 vector vec3_mulvf(vector a, float b)
185 /**********************************************************************
189 static bool parser_next(parser_t *parser)
191 /* lex_do kills the previous token */
192 parser->tok = lex_do(parser->lex);
193 if (parser->tok == TOKEN_EOF)
195 if (parser->tok >= TOKEN_ERROR) {
196 parseerror(parser, "lex error");
202 #define parser_tokval(p) ((p)->lex->tok.value)
203 #define parser_token(p) (&((p)->lex->tok))
204 #define parser_ctx(p) ((p)->lex->tok.ctx)
206 static ast_value* parser_const_float(parser_t *parser, double d)
211 for (i = 0; i < vec_size(parser->imm_float); ++i) {
212 const double compare = parser->imm_float[i]->constval.vfloat;
213 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
214 return parser->imm_float[i];
217 ctx = parser_ctx(parser);
219 memset(&ctx, 0, sizeof(ctx));
221 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
223 out->hasvalue = true;
225 out->constval.vfloat = d;
226 vec_push(parser->imm_float, out);
230 static ast_value* parser_const_float_0(parser_t *parser)
232 if (!parser->imm_float_zero)
233 parser->imm_float_zero = parser_const_float(parser, 0);
234 return parser->imm_float_zero;
237 static ast_value* parser_const_float_neg1(parser_t *parser) {
238 if (!parser->imm_float_neg_one)
239 parser->imm_float_neg_one = parser_const_float(parser, -1);
240 return parser->imm_float_neg_one;
243 static ast_value* parser_const_float_1(parser_t *parser)
245 if (!parser->imm_float_one)
246 parser->imm_float_one = parser_const_float(parser, 1);
247 return parser->imm_float_one;
250 static char *parser_strdup(const char *str)
253 /* actually dup empty strings */
254 char *out = (char*)mem_a(1);
258 return util_strdup(str);
261 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
263 size_t hash = util_hthash(parser->ht_imm_string, str);
265 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
266 if (dotranslate && out->name[0] == '#') {
268 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
269 ast_value_set_name(out, name);
270 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
275 for (i = 0; i < vec_size(parser->imm_string); ++i) {
276 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
277 return parser->imm_string[i];
282 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
283 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
284 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
286 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
288 out->hasvalue = true;
290 out->constval.vstring = parser_strdup(str);
291 vec_push(parser->imm_string, out);
292 util_htseth(parser->ht_imm_string, str, hash, out);
296 static ast_value* parser_const_vector(parser_t *parser, vector v)
300 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
301 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
302 return parser->imm_vector[i];
304 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
306 out->hasvalue = true;
308 out->constval.vvec = v;
309 vec_push(parser->imm_vector, out);
313 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
319 return parser_const_vector(parser, v);
322 static ast_value* parser_const_vector_0(parser_t *parser)
324 if (!parser->imm_vector_zero)
325 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
326 return parser->imm_vector_zero;
329 static ast_expression* parser_find_field(parser_t *parser, const char *name)
331 return ( ast_expression*)util_htget(parser->htfields, name);
334 static ast_expression* parser_find_label(parser_t *parser, const char *name)
337 for(i = 0; i < vec_size(parser->labels); i++)
338 if (!strcmp(parser->labels[i]->name, name))
339 return (ast_expression*)parser->labels[i];
343 static ast_expression* parser_find_global(parser_t *parser, const char *name)
345 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
348 return (ast_expression*)util_htget(parser->htglobals, name);
351 static ast_expression* parser_find_param(parser_t *parser, const char *name)
355 if (!parser->function)
357 fun = parser->function->vtype;
358 for (i = 0; i < vec_size(fun->expression.params); ++i) {
359 if (!strcmp(fun->expression.params[i]->name, name))
360 return (ast_expression*)(fun->expression.params[i]);
365 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
370 hash = util_hthash(parser->htglobals, name);
373 for (i = vec_size(parser->variables); i > upto;) {
375 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
379 return parser_find_param(parser, name);
382 static ast_expression* parser_find_var(parser_t *parser, const char *name)
386 v = parser_find_local(parser, name, 0, &dummy);
387 if (!v) v = parser_find_global(parser, name);
391 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
395 hash = util_hthash(parser->typedefs[0], name);
397 for (i = vec_size(parser->typedefs); i > upto;) {
399 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
405 /* include intrinsics */
410 size_t etype; /* 0 = expression, others are operators */
414 ast_block *block; /* for commas and function calls */
433 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
444 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
448 e.out = (ast_expression*)v;
455 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
457 e.etype = 1 + (op - operators);
466 static sy_elem syparen(lex_ctx ctx, size_t off) {
477 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
478 * so we need to rotate it to become ent.(foo[n]).
480 static bool rotate_entfield_array_index_nodes(ast_expression **out)
482 ast_array_index *index, *oldindex;
483 ast_entfield *entfield;
487 ast_expression *entity;
489 lex_ctx ctx = ast_ctx(*out);
491 if (!ast_istype(*out, ast_array_index))
493 index = (ast_array_index*)*out;
495 if (!ast_istype(index->array, ast_entfield))
497 entfield = (ast_entfield*)index->array;
499 if (!ast_istype(entfield->field, ast_value))
501 field = (ast_value*)entfield->field;
504 entity = entfield->entity;
508 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
509 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
510 *out = (ast_expression*)entfield;
512 oldindex->array = NULL;
513 oldindex->index = NULL;
514 ast_delete(oldindex);
519 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
521 switch (v->expression.vtype) {
523 return !!v->constval.vfloat;
525 return !!v->constval.vint;
527 if (OPTS_FLAG(CORRECT_LOGIC))
528 return v->constval.vvec.x &&
529 v->constval.vvec.y &&
532 return !!(v->constval.vvec.x);
534 if (!v->constval.vstring)
536 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
538 return !!v->constval.vstring[0];
540 compile_error(ctx, "internal error: immediate_is_true on invalid type");
541 return !!v->constval.vfunc;
545 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
549 ast_expression *out = NULL;
550 ast_expression *exprs[3];
551 ast_block *blocks[3];
552 ast_value *asvalue[3];
553 ast_binstore *asbinstore;
554 size_t i, assignop, addop, subop;
555 qcint generated_op = 0;
560 if (!vec_size(sy->ops)) {
561 parseerror(parser, "internal error: missing operator");
565 if (vec_last(sy->ops).isparen) {
566 parseerror(parser, "unmatched parenthesis");
570 op = &operators[vec_last(sy->ops).etype - 1];
571 ctx = vec_last(sy->ops).ctx;
573 if (vec_size(sy->out) < op->operands) {
574 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
575 op->op, (int)op->id);
579 vec_shrinkby(sy->ops, 1);
581 /* op(:?) has no input and no output */
585 vec_shrinkby(sy->out, op->operands);
586 for (i = 0; i < op->operands; ++i) {
587 exprs[i] = sy->out[vec_size(sy->out)+i].out;
588 blocks[i] = sy->out[vec_size(sy->out)+i].block;
589 asvalue[i] = (ast_value*)exprs[i];
591 if (exprs[i]->vtype == TYPE_NOEXPR &&
592 !(i != 0 && op->id == opid2('?',':')) &&
593 !(i == 1 && op->id == opid1('.')))
595 if (ast_istype(exprs[i], ast_label))
596 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
598 compile_error(ast_ctx(exprs[i]), "not an expression");
599 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
603 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
604 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
608 #define NotSameType(T) \
609 (exprs[0]->vtype != exprs[1]->vtype || \
610 exprs[0]->vtype != T)
611 #define CanConstFold1(A) \
612 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
613 (A)->vtype != TYPE_FUNCTION)
614 #define CanConstFold(A, B) \
615 (CanConstFold1(A) && CanConstFold1(B))
616 #define ConstV(i) (asvalue[(i)]->constval.vvec)
617 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
618 #define ConstS(i) (asvalue[(i)]->constval.vstring)
622 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
626 if (exprs[0]->vtype == TYPE_VECTOR &&
627 exprs[1]->vtype == TYPE_NOEXPR)
629 if (exprs[1] == (ast_expression*)parser->const_vec[0])
630 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
631 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
632 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
633 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
634 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
636 compile_error(ctx, "access to invalid vector component");
640 else if (exprs[0]->vtype == TYPE_ENTITY) {
641 if (exprs[1]->vtype != TYPE_FIELD) {
642 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
645 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
647 else if (exprs[0]->vtype == TYPE_VECTOR) {
648 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
652 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
658 if (exprs[0]->vtype != TYPE_ARRAY &&
659 !(exprs[0]->vtype == TYPE_FIELD &&
660 exprs[0]->next->vtype == TYPE_ARRAY))
662 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
663 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
666 if (exprs[1]->vtype != TYPE_FLOAT) {
667 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
668 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
671 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
672 if (rotate_entfield_array_index_nodes(&out))
675 /* This is not broken in fteqcc anymore */
676 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
677 /* this error doesn't need to make us bail out */
678 (void)!parsewarning(parser, WARN_EXTENSIONS,
679 "accessing array-field members of an entity without parenthesis\n"
680 " -> this is an extension from -std=gmqcc");
687 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
688 vec_push(sy->out, syexp(ctx, exprs[0]));
689 vec_push(sy->out, syexp(ctx, exprs[1]));
690 vec_last(sy->argc)++;
694 if (!ast_block_add_expr(blocks[0], exprs[1]))
697 blocks[0] = ast_block_new(ctx);
698 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
699 !ast_block_add_expr(blocks[0], exprs[1]))
704 ast_block_set_type(blocks[0], exprs[1]);
706 vec_push(sy->out, syblock(ctx, blocks[0]));
713 switch (exprs[0]->vtype) {
715 if (CanConstFold1(exprs[0]))
716 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
718 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
719 (ast_expression*)parser_const_float_0(parser),
723 if (CanConstFold1(exprs[0]))
724 out = (ast_expression*)parser_const_vector_f(parser,
725 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
727 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
728 (ast_expression*)parser_const_vector_0(parser),
732 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
733 type_name[exprs[0]->vtype]);
739 switch (exprs[0]->vtype) {
741 if (CanConstFold1(exprs[0]))
742 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
744 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
747 if (CanConstFold1(exprs[0]))
748 out = (ast_expression*)parser_const_float(parser,
749 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
751 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
754 if (CanConstFold1(exprs[0])) {
755 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
756 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
758 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
760 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
761 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
763 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
766 /* we don't constant-fold NOT for these types */
768 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
771 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
774 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
775 type_name[exprs[0]->vtype]);
781 if (exprs[0]->vtype != exprs[1]->vtype ||
782 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
784 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
785 type_name[exprs[0]->vtype],
786 type_name[exprs[1]->vtype]);
789 switch (exprs[0]->vtype) {
791 if (CanConstFold(exprs[0], exprs[1]))
793 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
796 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
799 if (CanConstFold(exprs[0], exprs[1]))
800 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
802 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
805 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
806 type_name[exprs[0]->vtype],
807 type_name[exprs[1]->vtype]);
812 if (exprs[0]->vtype != exprs[1]->vtype ||
813 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
815 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
816 type_name[exprs[1]->vtype],
817 type_name[exprs[0]->vtype]);
820 switch (exprs[0]->vtype) {
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
825 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
828 if (CanConstFold(exprs[0], exprs[1]))
829 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
831 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
834 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
835 type_name[exprs[1]->vtype],
836 type_name[exprs[0]->vtype]);
841 if (exprs[0]->vtype != exprs[1]->vtype &&
842 !(exprs[0]->vtype == TYPE_VECTOR &&
843 exprs[1]->vtype == TYPE_FLOAT) &&
844 !(exprs[1]->vtype == TYPE_VECTOR &&
845 exprs[0]->vtype == TYPE_FLOAT)
848 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
849 type_name[exprs[1]->vtype],
850 type_name[exprs[0]->vtype]);
853 switch (exprs[0]->vtype) {
855 if (exprs[1]->vtype == TYPE_VECTOR)
857 if (CanConstFold(exprs[0], exprs[1]))
858 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
860 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
864 if (CanConstFold(exprs[0], exprs[1]))
865 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
867 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
871 if (exprs[1]->vtype == TYPE_FLOAT)
873 if (CanConstFold(exprs[0], exprs[1]))
874 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
876 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
880 if (CanConstFold(exprs[0], exprs[1]))
881 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
882 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
883 vector vec = ConstV(0);
884 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
885 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
886 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
887 out->node.keep = false;
888 ((ast_member*)out)->rvalue = true;
890 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
892 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
893 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
894 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
895 out->node.keep = false;
896 ((ast_member*)out)->rvalue = true;
898 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
900 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
901 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
902 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
903 out->node.keep = false;
904 ((ast_member*)out)->rvalue = true;
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
909 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
911 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
912 vector vec = ConstV(1);
913 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
914 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
915 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
916 out->node.keep = false;
917 ((ast_member*)out)->rvalue = true;
919 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
921 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
922 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
923 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
924 out->node.keep = false;
925 ((ast_member*)out)->rvalue = true;
927 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
929 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
930 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
931 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
932 out->node.keep = false;
933 ((ast_member*)out)->rvalue = true;
935 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
938 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
941 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
945 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
946 type_name[exprs[1]->vtype],
947 type_name[exprs[0]->vtype]);
952 if (exprs[1]->vtype != TYPE_FLOAT) {
953 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
954 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
955 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
958 if (exprs[0]->vtype == TYPE_FLOAT) {
959 if (CanConstFold(exprs[0], exprs[1]))
960 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
962 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
964 else if (exprs[0]->vtype == TYPE_VECTOR) {
965 if (CanConstFold(exprs[0], exprs[1]))
966 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
968 if (CanConstFold1(exprs[1])) {
969 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
971 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
972 (ast_expression*)parser_const_float_1(parser),
976 compile_error(ctx, "internal error: failed to generate division");
979 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
984 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
985 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
986 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
992 if (NotSameType(TYPE_FLOAT)) {
993 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
994 type_name[exprs[0]->vtype],
995 type_name[exprs[1]->vtype]);
998 if (CanConstFold(exprs[0], exprs[1])) {
999 out = (ast_expression*)parser_const_float(parser,
1000 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
1002 /* generate a call to __builtin_mod */
1003 ast_expression *mod = intrin_func(parser, "mod");
1004 ast_call *call = NULL;
1005 if (!mod) return false; /* can return null for missing floor */
1007 call = ast_call_new(parser_ctx(parser), mod);
1008 vec_push(call->params, exprs[0]);
1009 vec_push(call->params, exprs[1]);
1011 out = (ast_expression*)call;
1015 case opid2('%','='):
1016 compile_error(ctx, "%= is unimplemented");
1021 if (NotSameType(TYPE_FLOAT)) {
1022 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1023 type_name[exprs[0]->vtype],
1024 type_name[exprs[1]->vtype]);
1027 if (CanConstFold(exprs[0], exprs[1]))
1028 out = (ast_expression*)parser_const_float(parser,
1029 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1030 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1032 out = (ast_expression*)ast_binary_new(ctx,
1033 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1034 exprs[0], exprs[1]);
1038 * ^ can be implemented as:
1039 * (LHS | RHS) & ~(LHS & RHS)
1040 * to implement ~ we need to use -1-X, as you can see the
1041 * whole process ends up becoming:
1042 * (LHS | RHS) & (-1 - (LHS & RHS))
1044 #define TRY_TYPE(I) \
1045 if (exprs[(I)]->vtype != TYPE_FLOAT) { \
1046 ast_type_to_string(exprs[(I)], ty1, sizeof(ty1)); \
1048 ast_ctx(exprs[(I)]), \
1049 "invalid type `%s` for bit-xor in %s", \
1052 ? "left-hand-side of expression" \
1053 : "right-hand-side of expression" \
1061 if(CanConstFold(exprs[0], exprs[1])) {
1062 out = (ast_expression*)parser_const_float(parser, (float)((qcint)(ConstF(0)) ^ ((qcint)(ConstF(1)))));
1064 out = (ast_expression*)
1068 (ast_expression*)ast_binary_new(
1074 (ast_expression*)ast_binary_new(
1077 (ast_expression*)parser_const_float_neg1(parser),
1078 (ast_expression*)ast_binary_new(
1089 case opid2('<','<'):
1090 case opid2('>','>'):
1091 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1092 if (op->id == opid2('<','<'))
1093 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1095 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1098 case opid3('<','<','='):
1099 case opid3('>','>','='):
1100 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1103 case opid2('|','|'):
1104 generated_op += 1; /* INSTR_OR */
1105 case opid2('&','&'):
1106 generated_op += INSTR_AND;
1107 if (CanConstFold(exprs[0], exprs[1]))
1109 if (OPTS_FLAG(PERL_LOGIC)) {
1110 if (immediate_is_true(ctx, asvalue[0]))
1114 out = (ast_expression*)parser_const_float(parser,
1115 ( (generated_op == INSTR_OR)
1116 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1117 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1122 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1123 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1124 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1125 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1128 for (i = 0; i < 2; ++i) {
1129 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1130 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1132 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1134 exprs[i] = out; out = NULL;
1135 if (OPTS_FLAG(PERL_LOGIC)) {
1136 /* here we want to keep the right expressions' type */
1140 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1141 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1143 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1145 exprs[i] = out; out = NULL;
1146 if (OPTS_FLAG(PERL_LOGIC)) {
1147 /* here we want to keep the right expressions' type */
1152 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1156 case opid2('?',':'):
1157 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1158 compile_error(ctx, "mismatched parenthesis/ternary");
1162 if (!ast_compare_type(exprs[1], exprs[2])) {
1163 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1164 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1165 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1168 if (CanConstFold1(exprs[0]))
1169 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1171 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1174 case opid2('*', '*'):
1175 if (NotSameType(TYPE_FLOAT)) {
1176 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1177 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1178 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1184 if (CanConstFold(exprs[0], exprs[1])) {
1185 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1187 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1188 vec_push(gencall->params, exprs[0]);
1189 vec_push(gencall->params, exprs[1]);
1190 out = (ast_expression*)gencall;
1194 case opid3('<','=','>'): /* -1, 0, or 1 */
1195 if (NotSameType(TYPE_FLOAT)) {
1196 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1197 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1198 compile_error(ctx, "invalid types used in comparision: %s and %s",
1204 if (CanConstFold(exprs[0], exprs[1])) {
1205 if (ConstF(0) < ConstF(1))
1206 out = (ast_expression*)parser_const_float_neg1(parser);
1207 else if (ConstF(0) == ConstF(1))
1208 out = (ast_expression*)parser_const_float_0(parser);
1209 else if (ConstF(0) > ConstF(1))
1210 out = (ast_expression*)parser_const_float_1(parser);
1212 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1214 eq->refs = (ast_binary_ref)false; /* references nothing */
1217 out = (ast_expression*)ast_ternary_new(ctx,
1218 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1220 (ast_expression*)parser_const_float_neg1(parser),
1223 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1225 (ast_expression*)parser_const_float_0(parser),
1228 (ast_expression*)parser_const_float_1(parser)
1238 generated_op += 1; /* INSTR_GT */
1240 generated_op += 1; /* INSTR_LT */
1241 case opid2('>', '='):
1242 generated_op += 1; /* INSTR_GE */
1243 case opid2('<', '='):
1244 generated_op += INSTR_LE;
1245 if (NotSameType(TYPE_FLOAT)) {
1246 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1247 type_name[exprs[0]->vtype],
1248 type_name[exprs[1]->vtype]);
1251 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1253 case opid2('!', '='):
1254 if (exprs[0]->vtype != exprs[1]->vtype) {
1255 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1256 type_name[exprs[0]->vtype],
1257 type_name[exprs[1]->vtype]);
1260 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1262 case opid2('=', '='):
1263 if (exprs[0]->vtype != exprs[1]->vtype) {
1264 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1265 type_name[exprs[0]->vtype],
1266 type_name[exprs[1]->vtype]);
1269 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1273 if (ast_istype(exprs[0], ast_entfield)) {
1274 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1275 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1276 exprs[0]->vtype == TYPE_FIELD &&
1277 exprs[0]->next->vtype == TYPE_VECTOR)
1279 assignop = type_storep_instr[TYPE_VECTOR];
1282 assignop = type_storep_instr[exprs[0]->vtype];
1283 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1285 ast_type_to_string(field->next, ty1, sizeof(ty1));
1286 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1287 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1288 field->next->vtype == TYPE_FUNCTION &&
1289 exprs[1]->vtype == TYPE_FUNCTION)
1291 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1292 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1295 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1300 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1301 exprs[0]->vtype == TYPE_FIELD &&
1302 exprs[0]->next->vtype == TYPE_VECTOR)
1304 assignop = type_store_instr[TYPE_VECTOR];
1307 assignop = type_store_instr[exprs[0]->vtype];
1310 if (assignop == VINSTR_END) {
1311 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1312 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1313 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1315 else if (!ast_compare_type(exprs[0], exprs[1]))
1317 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1318 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1319 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1320 exprs[0]->vtype == TYPE_FUNCTION &&
1321 exprs[1]->vtype == TYPE_FUNCTION)
1323 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1324 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1327 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1330 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1331 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1333 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1335 case opid3('+','+','P'):
1336 case opid3('-','-','P'):
1338 if (exprs[0]->vtype != TYPE_FLOAT) {
1339 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1340 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1343 if (op->id == opid3('+','+','P'))
1344 addop = INSTR_ADD_F;
1346 addop = INSTR_SUB_F;
1347 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1348 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1350 if (ast_istype(exprs[0], ast_entfield)) {
1351 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1353 (ast_expression*)parser_const_float_1(parser));
1355 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1357 (ast_expression*)parser_const_float_1(parser));
1360 case opid3('S','+','+'):
1361 case opid3('S','-','-'):
1363 if (exprs[0]->vtype != TYPE_FLOAT) {
1364 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1365 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1368 if (op->id == opid3('S','+','+')) {
1369 addop = INSTR_ADD_F;
1370 subop = INSTR_SUB_F;
1372 addop = INSTR_SUB_F;
1373 subop = INSTR_ADD_F;
1375 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1376 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1378 if (ast_istype(exprs[0], ast_entfield)) {
1379 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1381 (ast_expression*)parser_const_float_1(parser));
1383 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1385 (ast_expression*)parser_const_float_1(parser));
1389 out = (ast_expression*)ast_binary_new(ctx, subop,
1391 (ast_expression*)parser_const_float_1(parser));
1393 case opid2('+','='):
1394 case opid2('-','='):
1395 if (exprs[0]->vtype != exprs[1]->vtype ||
1396 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1398 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1399 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1400 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1404 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1405 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1407 if (ast_istype(exprs[0], ast_entfield))
1408 assignop = type_storep_instr[exprs[0]->vtype];
1410 assignop = type_store_instr[exprs[0]->vtype];
1411 switch (exprs[0]->vtype) {
1413 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1414 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1415 exprs[0], exprs[1]);
1418 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1419 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1420 exprs[0], exprs[1]);
1423 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1424 type_name[exprs[0]->vtype],
1425 type_name[exprs[1]->vtype]);
1429 case opid2('*','='):
1430 case opid2('/','='):
1431 if (exprs[1]->vtype != TYPE_FLOAT ||
1432 !(exprs[0]->vtype == TYPE_FLOAT ||
1433 exprs[0]->vtype == TYPE_VECTOR))
1435 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1436 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1437 compile_error(ctx, "invalid types used in expression: %s and %s",
1441 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1442 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1444 if (ast_istype(exprs[0], ast_entfield))
1445 assignop = type_storep_instr[exprs[0]->vtype];
1447 assignop = type_store_instr[exprs[0]->vtype];
1448 switch (exprs[0]->vtype) {
1450 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1451 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1452 exprs[0], exprs[1]);
1455 if (op->id == opid2('*','=')) {
1456 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1457 exprs[0], exprs[1]);
1459 /* there's no DIV_VF */
1460 if (CanConstFold1(exprs[1])) {
1461 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1463 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1464 (ast_expression*)parser_const_float_1(parser),
1468 compile_error(ctx, "internal error: failed to generate division");
1471 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1476 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1477 type_name[exprs[0]->vtype],
1478 type_name[exprs[1]->vtype]);
1482 case opid2('&','='):
1483 case opid2('|','='):
1484 if (NotSameType(TYPE_FLOAT)) {
1485 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1486 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1487 compile_error(ctx, "invalid types used in expression: %s and %s",
1491 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1492 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1494 if (ast_istype(exprs[0], ast_entfield))
1495 assignop = type_storep_instr[exprs[0]->vtype];
1497 assignop = type_store_instr[exprs[0]->vtype];
1498 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1499 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1500 exprs[0], exprs[1]);
1502 case opid3('&','~','='):
1503 /* This is like: a &= ~(b);
1504 * But QC has no bitwise-not, so we implement it as
1507 if (NotSameType(TYPE_FLOAT)) {
1508 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1509 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1510 compile_error(ctx, "invalid types used in expression: %s and %s",
1514 if (ast_istype(exprs[0], ast_entfield))
1515 assignop = type_storep_instr[exprs[0]->vtype];
1517 assignop = type_store_instr[exprs[0]->vtype];
1518 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1521 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1522 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1524 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1525 asbinstore->keep_dest = true;
1526 out = (ast_expression*)asbinstore;
1529 case opid2('~', 'P'):
1530 if (exprs[0]->vtype != TYPE_FLOAT) {
1531 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1532 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1536 if(CanConstFold1(exprs[0]))
1537 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1539 out = (ast_expression*)
1540 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1546 compile_error(ctx, "failed to apply operator %s", op->op);
1550 vec_push(sy->out, syexp(ctx, out));
1554 static bool parser_close_call(parser_t *parser, shunt *sy)
1556 /* was a function call */
1557 ast_expression *fun;
1558 ast_value *funval = NULL;
1562 size_t paramcount, i;
1564 fid = vec_last(sy->ops).off;
1565 vec_shrinkby(sy->ops, 1);
1567 /* out[fid] is the function
1568 * everything above is parameters...
1570 if (!vec_size(sy->argc)) {
1571 parseerror(parser, "internal error: no argument counter available");
1575 paramcount = vec_last(sy->argc);
1578 if (vec_size(sy->out) < fid) {
1579 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1580 (unsigned long)vec_size(sy->out),
1582 (unsigned long)paramcount);
1586 fun = sy->out[fid].out;
1588 if (fun == intrinsic_debug_typestring) {
1590 if (fid+2 != vec_size(sy->out) ||
1591 vec_last(sy->out).block)
1593 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1596 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1597 ast_unref(vec_last(sy->out).out);
1598 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1599 (ast_expression*)parser_const_string(parser, ty, false));
1600 vec_shrinkby(sy->out, 1);
1604 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1608 if (fid+1 < vec_size(sy->out))
1611 if (fid+1 + paramcount != vec_size(sy->out)) {
1612 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1613 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1617 for (i = 0; i < paramcount; ++i)
1618 vec_push(call->params, sy->out[fid+1 + i].out);
1619 vec_shrinkby(sy->out, paramcount);
1620 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1621 if (parser->max_param_count < paramcount)
1622 parser->max_param_count = paramcount;
1624 if (ast_istype(fun, ast_value)) {
1625 funval = (ast_value*)fun;
1626 if ((fun->flags & AST_FLAG_VARIADIC) &&
1627 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1629 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1633 /* overwrite fid, the function, with a call */
1634 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1636 if (fun->vtype != TYPE_FUNCTION) {
1637 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1642 parseerror(parser, "could not determine function return type");
1645 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1647 if (fun->flags & AST_FLAG_DEPRECATED) {
1649 return !parsewarning(parser, WARN_DEPRECATED,
1650 "call to function (which is marked deprecated)\n",
1651 "-> it has been declared here: %s:%i",
1652 ast_ctx(fun).file, ast_ctx(fun).line);
1655 return !parsewarning(parser, WARN_DEPRECATED,
1656 "call to `%s` (which is marked deprecated)\n"
1657 "-> `%s` declared here: %s:%i",
1658 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1660 return !parsewarning(parser, WARN_DEPRECATED,
1661 "call to `%s` (deprecated: %s)\n"
1662 "-> `%s` declared here: %s:%i",
1663 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1667 if (vec_size(fun->params) != paramcount &&
1668 !((fun->flags & AST_FLAG_VARIADIC) &&
1669 vec_size(fun->params) < paramcount))
1671 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1673 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1674 "too %s parameters for call to %s: expected %i, got %i\n"
1675 " -> `%s` has been declared here: %s:%i",
1676 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1677 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1679 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1680 "too %s parameters for function call: expected %i, got %i\n"
1681 " -> it has been declared here: %s:%i",
1682 fewmany, (int)vec_size(fun->params), (int)paramcount,
1683 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1690 static bool parser_close_paren(parser_t *parser, shunt *sy)
1692 if (!vec_size(sy->ops)) {
1693 parseerror(parser, "unmatched closing paren");
1697 while (vec_size(sy->ops)) {
1698 if (vec_last(sy->ops).isparen) {
1699 if (vec_last(sy->paren) == PAREN_FUNC) {
1701 if (!parser_close_call(parser, sy))
1705 if (vec_last(sy->paren) == PAREN_EXPR) {
1707 if (!vec_size(sy->out)) {
1708 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1709 vec_shrinkby(sy->ops, 1);
1712 vec_shrinkby(sy->ops, 1);
1715 if (vec_last(sy->paren) == PAREN_INDEX) {
1717 /* pop off the parenthesis */
1718 vec_shrinkby(sy->ops, 1);
1719 /* then apply the index operator */
1720 if (!parser_sy_apply_operator(parser, sy))
1724 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1725 vec_last(sy->paren) = PAREN_TERNARY2;
1726 /* pop off the parenthesis */
1727 vec_shrinkby(sy->ops, 1);
1730 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1733 if (!parser_sy_apply_operator(parser, sy))
1739 static void parser_reclassify_token(parser_t *parser)
1742 for (i = 0; i < operator_count; ++i) {
1743 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1744 parser->tok = TOKEN_OPERATOR;
1750 static ast_expression* parse_vararg_do(parser_t *parser)
1752 ast_expression *idx, *out;
1754 ast_value *funtype = parser->function->vtype;
1755 lex_ctx ctx = parser_ctx(parser);
1757 if (!parser->function->varargs) {
1758 parseerror(parser, "function has no variable argument list");
1762 if (!parser_next(parser) || parser->tok != '(') {
1763 parseerror(parser, "expected parameter index and type in parenthesis");
1766 if (!parser_next(parser)) {
1767 parseerror(parser, "error parsing parameter index");
1771 idx = parse_expression_leave(parser, true, false, false);
1775 if (parser->tok != ',') {
1776 if (parser->tok != ')') {
1778 parseerror(parser, "expected comma after parameter index");
1781 /* vararg piping: ...(start) */
1782 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1786 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1788 parseerror(parser, "expected typename for vararg");
1792 typevar = parse_typename(parser, NULL, NULL);
1798 if (parser->tok != ')') {
1800 ast_delete(typevar);
1801 parseerror(parser, "expected closing paren");
1805 if (funtype->expression.varparam &&
1806 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1810 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1811 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1812 compile_error(ast_ctx(typevar),
1813 "function was declared to take varargs of type `%s`, requested type is: %s",
1817 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1818 ast_type_adopt(out, typevar);
1819 ast_delete(typevar);
1823 static ast_expression* parse_vararg(parser_t *parser)
1825 bool old_noops = parser->lex->flags.noops;
1827 ast_expression *out;
1829 parser->lex->flags.noops = true;
1830 out = parse_vararg_do(parser);
1832 parser->lex->flags.noops = old_noops;
1836 /* not to be exposed */
1837 extern bool ftepp_predef_exists(const char *name);
1839 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1841 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1842 parser->tok == TOKEN_IDENT &&
1843 !strcmp(parser_tokval(parser), "_"))
1845 /* a translatable string */
1848 parser->lex->flags.noops = true;
1849 if (!parser_next(parser) || parser->tok != '(') {
1850 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1853 parser->lex->flags.noops = false;
1854 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1855 parseerror(parser, "expected a constant string in translatable-string extension");
1858 val = parser_const_string(parser, parser_tokval(parser), true);
1861 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1863 if (!parser_next(parser) || parser->tok != ')') {
1864 parseerror(parser, "expected closing paren after translatable string");
1869 else if (parser->tok == TOKEN_DOTS)
1872 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1873 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1876 va = parse_vararg(parser);
1879 vec_push(sy->out, syexp(parser_ctx(parser), va));
1882 else if (parser->tok == TOKEN_FLOATCONST) {
1884 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1887 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1890 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1892 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1895 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1898 else if (parser->tok == TOKEN_STRINGCONST) {
1900 val = parser_const_string(parser, parser_tokval(parser), false);
1903 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1906 else if (parser->tok == TOKEN_VECTORCONST) {
1908 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1911 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1914 else if (parser->tok == TOKEN_IDENT)
1916 const char *ctoken = parser_tokval(parser);
1917 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1918 ast_expression *var;
1919 /* a_vector.{x,y,z} */
1920 if (!vec_size(sy->ops) ||
1921 !vec_last(sy->ops).etype ||
1922 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1923 (prev >= intrinsic_debug_typestring &&
1924 prev <= intrinsic_debug_typestring))
1926 /* When adding more intrinsics, fix the above condition */
1929 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1931 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1933 var = parser_find_var(parser, parser_tokval(parser));
1935 var = parser_find_field(parser, parser_tokval(parser));
1937 if (!var && with_labels) {
1938 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1940 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1941 var = (ast_expression*)lbl;
1942 vec_push(parser->labels, lbl);
1945 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1946 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1949 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1950 var = (ast_expression*)intrinsic_debug_typestring;
1952 /* now we try for the real intrinsic hashtable. If the string
1953 * begins with __builtin, we simply skip past it, otherwise we
1954 * use the identifier as is.
1956 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1957 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1961 char *correct = NULL;
1965 * sometimes people use preprocessing predefs without enabling them
1966 * i've done this thousands of times already myself. Lets check for
1967 * it in the predef table. And diagnose it better :)
1969 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1970 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1975 * TODO: determine the best score for the identifier: be it
1976 * a variable, a field.
1978 * We should also consider adding correction tables for
1979 * other things as well.
1981 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1983 correct_init(&corr);
1985 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1986 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1987 if (strcmp(correct, parser_tokval(parser))) {
1989 } else if (correct) {
1994 correct_free(&corr);
1997 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
2002 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
2008 if (ast_istype(var, ast_value)) {
2009 ((ast_value*)var)->uses++;
2011 else if (ast_istype(var, ast_member)) {
2012 ast_member *mem = (ast_member*)var;
2013 if (ast_istype(mem->owner, ast_value))
2014 ((ast_value*)(mem->owner))->uses++;
2017 vec_push(sy->out, syexp(parser_ctx(parser), var));
2020 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2024 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2026 ast_expression *expr = NULL;
2029 bool wantop = false;
2030 /* only warn once about an assignment in a truth value because the current code
2031 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2033 bool warn_truthvalue = true;
2035 /* count the parens because an if starts with one, so the
2036 * end of a condition is an unmatched closing paren
2040 memset(&sy, 0, sizeof(sy));
2042 parser->lex->flags.noops = false;
2044 parser_reclassify_token(parser);
2048 if (parser->tok == TOKEN_TYPENAME) {
2049 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
2053 if (parser->tok == TOKEN_OPERATOR)
2055 /* classify the operator */
2056 const oper_info *op;
2057 const oper_info *olast = NULL;
2059 for (o = 0; o < operator_count; ++o) {
2060 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2061 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2062 !strcmp(parser_tokval(parser), operators[o].op))
2067 if (o == operator_count) {
2068 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2071 /* found an operator */
2074 /* when declaring variables, a comma starts a new variable */
2075 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2076 /* fixup the token */
2081 /* a colon without a pervious question mark cannot be a ternary */
2082 if (!ternaries && op->id == opid2(':','?')) {
2087 if (op->id == opid1(',')) {
2088 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2089 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2093 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2094 olast = &operators[vec_last(sy.ops).etype-1];
2096 #define IsAssignOp(x) (\
2097 (x) == opid1('=') || \
2098 (x) == opid2('+','=') || \
2099 (x) == opid2('-','=') || \
2100 (x) == opid2('*','=') || \
2101 (x) == opid2('/','=') || \
2102 (x) == opid2('%','=') || \
2103 (x) == opid2('&','=') || \
2104 (x) == opid2('|','=') || \
2105 (x) == opid3('&','~','=') \
2107 if (warn_truthvalue) {
2108 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2109 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2110 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2113 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2114 warn_truthvalue = false;
2119 (op->prec < olast->prec) ||
2120 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2122 if (!parser_sy_apply_operator(parser, &sy))
2124 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2125 olast = &operators[vec_last(sy.ops).etype-1];
2130 if (op->id == opid1('(')) {
2132 size_t sycount = vec_size(sy.out);
2133 /* we expected an operator, this is the function-call operator */
2134 vec_push(sy.paren, PAREN_FUNC);
2135 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2136 vec_push(sy.argc, 0);
2138 vec_push(sy.paren, PAREN_EXPR);
2139 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2142 } else if (op->id == opid1('[')) {
2144 parseerror(parser, "unexpected array subscript");
2147 vec_push(sy.paren, PAREN_INDEX);
2148 /* push both the operator and the paren, this makes life easier */
2149 vec_push(sy.ops, syop(parser_ctx(parser), op));
2150 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2152 } else if (op->id == opid2('?',':')) {
2153 vec_push(sy.ops, syop(parser_ctx(parser), op));
2154 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2157 vec_push(sy.paren, PAREN_TERNARY1);
2158 } else if (op->id == opid2(':','?')) {
2159 if (!vec_size(sy.paren)) {
2160 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2163 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2164 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2167 if (!parser_close_paren(parser, &sy))
2169 vec_push(sy.ops, syop(parser_ctx(parser), op));
2173 vec_push(sy.ops, syop(parser_ctx(parser), op));
2174 wantop = !!(op->flags & OP_SUFFIX);
2177 else if (parser->tok == ')') {
2178 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2179 if (!parser_sy_apply_operator(parser, &sy))
2182 if (!vec_size(sy.paren))
2185 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2186 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2189 if (!parser_close_paren(parser, &sy))
2192 /* must be a function call without parameters */
2193 if (vec_last(sy.paren) != PAREN_FUNC) {
2194 parseerror(parser, "closing paren in invalid position");
2197 if (!parser_close_paren(parser, &sy))
2202 else if (parser->tok == '(') {
2203 parseerror(parser, "internal error: '(' should be classified as operator");
2206 else if (parser->tok == '[') {
2207 parseerror(parser, "internal error: '[' should be classified as operator");
2210 else if (parser->tok == ']') {
2211 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2212 if (!parser_sy_apply_operator(parser, &sy))
2215 if (!vec_size(sy.paren))
2217 if (vec_last(sy.paren) != PAREN_INDEX) {
2218 parseerror(parser, "mismatched parentheses, unexpected ']'");
2221 if (!parser_close_paren(parser, &sy))
2226 if (!parse_sya_operand(parser, &sy, with_labels))
2229 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2230 vec_last(sy.argc)++;
2235 /* in this case we might want to allow constant string concatenation */
2236 bool concatenated = false;
2237 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2238 ast_expression *lexpr = vec_last(sy.out).out;
2239 if (ast_istype(lexpr, ast_value)) {
2240 ast_value *last = (ast_value*)lexpr;
2241 if (last->isimm == true && last->cvq == CV_CONST &&
2242 last->hasvalue && last->expression.vtype == TYPE_STRING)
2244 char *newstr = NULL;
2245 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2246 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2248 concatenated = true;
2252 if (!concatenated) {
2253 parseerror(parser, "expected operator or end of statement");
2258 if (!parser_next(parser)) {
2261 if (parser->tok == ';' ||
2262 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2263 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2269 while (vec_size(sy.ops)) {
2270 if (!parser_sy_apply_operator(parser, &sy))
2274 parser->lex->flags.noops = true;
2275 if (vec_size(sy.out) != 1) {
2276 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2279 expr = sy.out[0].out;
2282 if (vec_size(sy.paren)) {
2283 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2291 parser->lex->flags.noops = true;
2292 for (i = 0; i < vec_size(sy.out); ++i) {
2294 ast_unref(sy.out[i].out);
2303 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2305 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2308 if (parser->tok != ';') {
2309 parseerror(parser, "semicolon expected after expression");
2313 if (!parser_next(parser)) {
2320 static void parser_enterblock(parser_t *parser)
2322 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2323 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2324 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2325 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2326 vec_push(parser->_block_ctx, parser_ctx(parser));
2329 vec_push(parser->correct_variables, correct_trie_new());
2330 vec_push(parser->correct_variables_score, NULL);
2333 static bool parser_leaveblock(parser_t *parser)
2336 size_t locals, typedefs;
2338 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2339 parseerror(parser, "internal error: parser_leaveblock with no block");
2343 util_htdel(vec_last(parser->variables));
2344 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2346 vec_pop(parser->variables);
2347 vec_pop(parser->correct_variables);
2348 vec_pop(parser->correct_variables_score);
2349 if (!vec_size(parser->_blocklocals)) {
2350 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2354 locals = vec_last(parser->_blocklocals);
2355 vec_pop(parser->_blocklocals);
2356 while (vec_size(parser->_locals) != locals) {
2357 ast_expression *e = vec_last(parser->_locals);
2358 ast_value *v = (ast_value*)e;
2359 vec_pop(parser->_locals);
2360 if (ast_istype(e, ast_value) && !v->uses) {
2361 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2366 typedefs = vec_last(parser->_blocktypedefs);
2367 while (vec_size(parser->_typedefs) != typedefs) {
2368 ast_delete(vec_last(parser->_typedefs));
2369 vec_pop(parser->_typedefs);
2371 util_htdel(vec_last(parser->typedefs));
2372 vec_pop(parser->typedefs);
2374 vec_pop(parser->_block_ctx);
2379 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2381 vec_push(parser->_locals, e);
2382 util_htset(vec_last(parser->variables), name, (void*)e);
2386 vec_last(parser->correct_variables),
2387 &vec_last(parser->correct_variables_score),
2392 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2394 vec_push(parser->globals, e);
2395 util_htset(parser->htglobals, name, e);
2399 parser->correct_variables[0],
2400 &parser->correct_variables_score[0],
2405 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2409 ast_expression *prev;
2411 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2413 ast_type_to_string(cond, ty, sizeof(ty));
2414 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2417 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2420 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2423 parseerror(parser, "internal error: failed to process condition");
2428 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2430 /* vector types need to be cast to true booleans */
2431 ast_binary *bin = (ast_binary*)cond;
2432 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2434 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2436 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2439 parseerror(parser, "internal error: failed to process condition");
2446 unary = (ast_unary*)cond;
2447 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2449 cond = unary->operand;
2450 unary->operand = NULL;
2453 unary = (ast_unary*)cond;
2457 parseerror(parser, "internal error: failed to process condition");
2459 if (ifnot) *_ifnot = !*_ifnot;
2463 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2466 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2469 lex_ctx ctx = parser_ctx(parser);
2471 (void)block; /* not touching */
2473 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2474 if (!parser_next(parser)) {
2475 parseerror(parser, "expected condition or 'not'");
2478 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2480 if (!parser_next(parser)) {
2481 parseerror(parser, "expected condition in parenthesis");
2485 if (parser->tok != '(') {
2486 parseerror(parser, "expected 'if' condition in parenthesis");
2489 /* parse into the expression */
2490 if (!parser_next(parser)) {
2491 parseerror(parser, "expected 'if' condition after opening paren");
2494 /* parse the condition */
2495 cond = parse_expression_leave(parser, false, true, false);
2499 if (parser->tok != ')') {
2500 parseerror(parser, "expected closing paren after 'if' condition");
2504 /* parse into the 'then' branch */
2505 if (!parser_next(parser)) {
2506 parseerror(parser, "expected statement for on-true branch of 'if'");
2510 if (!parse_statement_or_block(parser, &ontrue)) {
2515 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2516 /* check for an else */
2517 if (!strcmp(parser_tokval(parser), "else")) {
2518 /* parse into the 'else' branch */
2519 if (!parser_next(parser)) {
2520 parseerror(parser, "expected on-false branch after 'else'");
2525 if (!parse_statement_or_block(parser, &onfalse)) {
2532 cond = process_condition(parser, cond, &ifnot);
2534 if (ontrue) ast_delete(ontrue);
2535 if (onfalse) ast_delete(onfalse);
2540 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2542 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2543 *out = (ast_expression*)ifthen;
2547 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2548 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2553 /* skip the 'while' and get the body */
2554 if (!parser_next(parser)) {
2555 if (OPTS_FLAG(LOOP_LABELS))
2556 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2558 parseerror(parser, "expected 'while' condition in parenthesis");
2562 if (parser->tok == ':') {
2563 if (!OPTS_FLAG(LOOP_LABELS))
2564 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2565 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2566 parseerror(parser, "expected loop label");
2569 label = util_strdup(parser_tokval(parser));
2570 if (!parser_next(parser)) {
2572 parseerror(parser, "expected 'while' condition in parenthesis");
2577 if (parser->tok != '(') {
2578 parseerror(parser, "expected 'while' condition in parenthesis");
2582 vec_push(parser->breaks, label);
2583 vec_push(parser->continues, label);
2585 rv = parse_while_go(parser, block, out);
2588 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2589 parseerror(parser, "internal error: label stack corrupted");
2595 vec_pop(parser->breaks);
2596 vec_pop(parser->continues);
2601 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2604 ast_expression *cond, *ontrue;
2608 lex_ctx ctx = parser_ctx(parser);
2610 (void)block; /* not touching */
2612 /* parse into the expression */
2613 if (!parser_next(parser)) {
2614 parseerror(parser, "expected 'while' condition after opening paren");
2617 /* parse the condition */
2618 cond = parse_expression_leave(parser, false, true, false);
2622 if (parser->tok != ')') {
2623 parseerror(parser, "expected closing paren after 'while' condition");
2627 /* parse into the 'then' branch */
2628 if (!parser_next(parser)) {
2629 parseerror(parser, "expected while-loop body");
2633 if (!parse_statement_or_block(parser, &ontrue)) {
2638 cond = process_condition(parser, cond, &ifnot);
2643 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2644 *out = (ast_expression*)aloop;
2648 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2649 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2654 /* skip the 'do' and get the body */
2655 if (!parser_next(parser)) {
2656 if (OPTS_FLAG(LOOP_LABELS))
2657 parseerror(parser, "expected loop label or body");
2659 parseerror(parser, "expected loop body");
2663 if (parser->tok == ':') {
2664 if (!OPTS_FLAG(LOOP_LABELS))
2665 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2666 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2667 parseerror(parser, "expected loop label");
2670 label = util_strdup(parser_tokval(parser));
2671 if (!parser_next(parser)) {
2673 parseerror(parser, "expected loop body");
2678 vec_push(parser->breaks, label);
2679 vec_push(parser->continues, label);
2681 rv = parse_dowhile_go(parser, block, out);
2684 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2685 parseerror(parser, "internal error: label stack corrupted");
2691 vec_pop(parser->breaks);
2692 vec_pop(parser->continues);
2697 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2700 ast_expression *cond, *ontrue;
2704 lex_ctx ctx = parser_ctx(parser);
2706 (void)block; /* not touching */
2708 if (!parse_statement_or_block(parser, &ontrue))
2711 /* expect the "while" */
2712 if (parser->tok != TOKEN_KEYWORD ||
2713 strcmp(parser_tokval(parser), "while"))
2715 parseerror(parser, "expected 'while' and condition");
2720 /* skip the 'while' and check for opening paren */
2721 if (!parser_next(parser) || parser->tok != '(') {
2722 parseerror(parser, "expected 'while' condition in parenthesis");
2726 /* parse into the expression */
2727 if (!parser_next(parser)) {
2728 parseerror(parser, "expected 'while' condition after opening paren");
2732 /* parse the condition */
2733 cond = parse_expression_leave(parser, false, true, false);
2737 if (parser->tok != ')') {
2738 parseerror(parser, "expected closing paren after 'while' condition");
2744 if (!parser_next(parser) || parser->tok != ';') {
2745 parseerror(parser, "expected semicolon after condition");
2751 if (!parser_next(parser)) {
2752 parseerror(parser, "parse error");
2758 cond = process_condition(parser, cond, &ifnot);
2763 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2764 *out = (ast_expression*)aloop;
2768 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2769 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2774 /* skip the 'for' and check for opening paren */
2775 if (!parser_next(parser)) {
2776 if (OPTS_FLAG(LOOP_LABELS))
2777 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2779 parseerror(parser, "expected 'for' expressions in parenthesis");
2783 if (parser->tok == ':') {
2784 if (!OPTS_FLAG(LOOP_LABELS))
2785 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2786 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2787 parseerror(parser, "expected loop label");
2790 label = util_strdup(parser_tokval(parser));
2791 if (!parser_next(parser)) {
2793 parseerror(parser, "expected 'for' expressions in parenthesis");
2798 if (parser->tok != '(') {
2799 parseerror(parser, "expected 'for' expressions in parenthesis");
2803 vec_push(parser->breaks, label);
2804 vec_push(parser->continues, label);
2806 rv = parse_for_go(parser, block, out);
2809 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2810 parseerror(parser, "internal error: label stack corrupted");
2816 vec_pop(parser->breaks);
2817 vec_pop(parser->continues);
2821 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2824 ast_expression *initexpr, *cond, *increment, *ontrue;
2829 lex_ctx ctx = parser_ctx(parser);
2831 parser_enterblock(parser);
2838 /* parse into the expression */
2839 if (!parser_next(parser)) {
2840 parseerror(parser, "expected 'for' initializer after opening paren");
2845 if (parser->tok == TOKEN_IDENT)
2846 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2848 if (typevar || parser->tok == TOKEN_TYPENAME) {
2850 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2851 if (parsewarning(parser, WARN_EXTENSIONS,
2852 "current standard does not allow variable declarations in for-loop initializers"))
2856 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2859 else if (parser->tok != ';')
2861 initexpr = parse_expression_leave(parser, false, false, false);
2866 /* move on to condition */
2867 if (parser->tok != ';') {
2868 parseerror(parser, "expected semicolon after for-loop initializer");
2871 if (!parser_next(parser)) {
2872 parseerror(parser, "expected for-loop condition");
2876 /* parse the condition */
2877 if (parser->tok != ';') {
2878 cond = parse_expression_leave(parser, false, true, false);
2883 /* move on to incrementor */
2884 if (parser->tok != ';') {
2885 parseerror(parser, "expected semicolon after for-loop initializer");
2888 if (!parser_next(parser)) {
2889 parseerror(parser, "expected for-loop condition");
2893 /* parse the incrementor */
2894 if (parser->tok != ')') {
2895 lex_ctx condctx = parser_ctx(parser);
2896 increment = parse_expression_leave(parser, false, false, false);
2899 if (!ast_side_effects(increment)) {
2900 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2906 if (parser->tok != ')') {
2907 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2910 /* parse into the 'then' branch */
2911 if (!parser_next(parser)) {
2912 parseerror(parser, "expected for-loop body");
2915 if (!parse_statement_or_block(parser, &ontrue))
2919 cond = process_condition(parser, cond, &ifnot);
2923 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2924 *out = (ast_expression*)aloop;
2926 if (!parser_leaveblock(parser)) {
2932 if (initexpr) ast_unref(initexpr);
2933 if (cond) ast_unref(cond);
2934 if (increment) ast_unref(increment);
2935 (void)!parser_leaveblock(parser);
2939 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2941 ast_expression *exp = NULL;
2942 ast_expression *var = NULL;
2943 ast_return *ret = NULL;
2944 ast_value *retval = parser->function->return_value;
2945 ast_value *expected = parser->function->vtype;
2947 lex_ctx ctx = parser_ctx(parser);
2949 (void)block; /* not touching */
2951 if (!parser_next(parser)) {
2952 parseerror(parser, "expected return expression");
2956 /* return assignments */
2957 if (parser->tok == '=') {
2958 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2959 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2963 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2965 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2966 parseerror(parser, "invalid return type: `%s'", ty1);
2970 if (!parser_next(parser)) {
2971 parseerror(parser, "expected return assignment expression");
2975 if (!(exp = parse_expression_leave(parser, false, false, false)))
2978 /* prepare the return value */
2980 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2981 ast_type_adopt(retval, expected->expression.next);
2982 parser->function->return_value = retval;
2985 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2986 char ty1[1024], ty2[1024];
2987 ast_type_to_string(exp, ty1, sizeof(ty1));
2988 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2989 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2992 /* store to 'return' local variable */
2993 var = (ast_expression*)ast_store_new(
2995 type_store_instr[expected->expression.next->vtype],
2996 (ast_expression*)retval, exp);
3003 if (parser->tok != ';')
3004 parseerror(parser, "missing semicolon after return assignment");
3005 else if (!parser_next(parser))
3006 parseerror(parser, "parse error after return assignment");
3012 if (parser->tok != ';') {
3013 exp = parse_expression(parser, false, false);
3017 if (exp->vtype != TYPE_NIL &&
3018 exp->vtype != ((ast_expression*)expected)->next->vtype)
3020 parseerror(parser, "return with invalid expression");
3023 ret = ast_return_new(ctx, exp);
3029 if (!parser_next(parser))
3030 parseerror(parser, "parse error");
3032 if (!retval && expected->expression.next->vtype != TYPE_VOID)
3034 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3036 ret = ast_return_new(ctx, (ast_expression*)retval);
3038 *out = (ast_expression*)ret;
3042 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3045 unsigned int levels = 0;
3046 lex_ctx ctx = parser_ctx(parser);
3047 const char **loops = (is_continue ? parser->continues : parser->breaks);
3049 (void)block; /* not touching */
3050 if (!parser_next(parser)) {
3051 parseerror(parser, "expected semicolon or loop label");
3055 if (!vec_size(loops)) {
3057 parseerror(parser, "`continue` can only be used inside loops");
3059 parseerror(parser, "`break` can only be used inside loops or switches");
3062 if (parser->tok == TOKEN_IDENT) {
3063 if (!OPTS_FLAG(LOOP_LABELS))
3064 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3065 i = vec_size(loops);
3067 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3070 parseerror(parser, "no such loop to %s: `%s`",
3071 (is_continue ? "continue" : "break out of"),
3072 parser_tokval(parser));
3077 if (!parser_next(parser)) {
3078 parseerror(parser, "expected semicolon");
3083 if (parser->tok != ';') {
3084 parseerror(parser, "expected semicolon");
3088 if (!parser_next(parser))
3089 parseerror(parser, "parse error");
3091 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3095 /* returns true when it was a variable qualifier, false otherwise!
3096 * on error, cvq is set to CV_WRONG
3098 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3100 bool had_const = false;
3101 bool had_var = false;
3102 bool had_noref = false;
3103 bool had_attrib = false;
3104 bool had_static = false;
3109 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3111 /* parse an attribute */
3112 if (!parser_next(parser)) {
3113 parseerror(parser, "expected attribute after `[[`");
3117 if (!strcmp(parser_tokval(parser), "noreturn")) {
3118 flags |= AST_FLAG_NORETURN;
3119 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3120 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3125 else if (!strcmp(parser_tokval(parser), "noref")) {
3127 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3128 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3133 else if (!strcmp(parser_tokval(parser), "inline")) {
3134 flags |= AST_FLAG_INLINE;
3135 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3136 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3141 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3142 flags |= AST_FLAG_ALIAS;
3145 if (!parser_next(parser)) {
3146 parseerror(parser, "parse error in attribute");
3150 if (parser->tok == '(') {
3151 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3152 parseerror(parser, "`alias` attribute missing parameter");
3156 *message = util_strdup(parser_tokval(parser));
3158 if (!parser_next(parser)) {
3159 parseerror(parser, "parse error in attribute");
3163 if (parser->tok != ')') {
3164 parseerror(parser, "`alias` attribute expected `)` after parameter");
3168 if (!parser_next(parser)) {
3169 parseerror(parser, "parse error in attribute");
3174 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3175 parseerror(parser, "`alias` attribute expected `]]`");
3179 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3180 flags |= AST_FLAG_DEPRECATED;
3183 if (!parser_next(parser)) {
3184 parseerror(parser, "parse error in attribute");
3188 if (parser->tok == '(') {
3189 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3190 parseerror(parser, "`deprecated` attribute missing parameter");
3194 *message = util_strdup(parser_tokval(parser));
3196 if (!parser_next(parser)) {
3197 parseerror(parser, "parse error in attribute");
3201 if(parser->tok != ')') {
3202 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3206 if (!parser_next(parser)) {
3207 parseerror(parser, "parse error in attribute");
3212 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3213 parseerror(parser, "`deprecated` attribute expected `]]`");
3216 if (*message) mem_d(*message);
3224 /* Skip tokens until we hit a ]] */
3225 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3226 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3227 if (!parser_next(parser)) {
3228 parseerror(parser, "error inside attribute");
3235 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3237 else if (!strcmp(parser_tokval(parser), "const"))
3239 else if (!strcmp(parser_tokval(parser), "var"))
3241 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3243 else if (!strcmp(parser_tokval(parser), "noref"))
3245 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3250 if (!parser_next(parser))
3260 *is_static = had_static;
3264 parseerror(parser, "parse error after variable qualifier");
3269 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3270 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3275 /* skip the 'while' and get the body */
3276 if (!parser_next(parser)) {
3277 if (OPTS_FLAG(LOOP_LABELS))
3278 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3280 parseerror(parser, "expected 'switch' operand in parenthesis");
3284 if (parser->tok == ':') {
3285 if (!OPTS_FLAG(LOOP_LABELS))
3286 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3287 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3288 parseerror(parser, "expected loop label");
3291 label = util_strdup(parser_tokval(parser));
3292 if (!parser_next(parser)) {
3294 parseerror(parser, "expected 'switch' operand in parenthesis");
3299 if (parser->tok != '(') {
3300 parseerror(parser, "expected 'switch' operand in parenthesis");
3304 vec_push(parser->breaks, label);
3306 rv = parse_switch_go(parser, block, out);
3309 if (vec_last(parser->breaks) != label) {
3310 parseerror(parser, "internal error: label stack corrupted");
3316 vec_pop(parser->breaks);
3321 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3323 ast_expression *operand;
3326 ast_switch *switchnode;
3327 ast_switch_case swcase;
3330 bool noref, is_static;
3331 uint32_t qflags = 0;
3333 lex_ctx ctx = parser_ctx(parser);
3335 (void)block; /* not touching */
3338 /* parse into the expression */
3339 if (!parser_next(parser)) {
3340 parseerror(parser, "expected switch operand");
3343 /* parse the operand */
3344 operand = parse_expression_leave(parser, false, false, false);
3348 switchnode = ast_switch_new(ctx, operand);
3351 if (parser->tok != ')') {
3352 ast_delete(switchnode);
3353 parseerror(parser, "expected closing paren after 'switch' operand");
3357 /* parse over the opening paren */
3358 if (!parser_next(parser) || parser->tok != '{') {
3359 ast_delete(switchnode);
3360 parseerror(parser, "expected list of cases");
3364 if (!parser_next(parser)) {
3365 ast_delete(switchnode);
3366 parseerror(parser, "expected 'case' or 'default'");
3370 /* new block; allow some variables to be declared here */
3371 parser_enterblock(parser);
3374 if (parser->tok == TOKEN_IDENT)
3375 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3376 if (typevar || parser->tok == TOKEN_TYPENAME) {
3377 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3378 ast_delete(switchnode);
3383 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3385 if (cvq == CV_WRONG) {
3386 ast_delete(switchnode);
3389 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3390 ast_delete(switchnode);
3399 while (parser->tok != '}') {
3400 ast_block *caseblock;
3402 if (!strcmp(parser_tokval(parser), "case")) {
3403 if (!parser_next(parser)) {
3404 ast_delete(switchnode);
3405 parseerror(parser, "expected expression for case");
3408 swcase.value = parse_expression_leave(parser, false, false, false);
3409 if (!swcase.value) {
3410 ast_delete(switchnode);
3411 parseerror(parser, "expected expression for case");
3414 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3415 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3416 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3422 else if (!strcmp(parser_tokval(parser), "default")) {
3423 swcase.value = NULL;
3424 if (!parser_next(parser)) {
3425 ast_delete(switchnode);
3426 parseerror(parser, "expected colon");
3431 ast_delete(switchnode);
3432 parseerror(parser, "expected 'case' or 'default'");
3436 /* Now the colon and body */
3437 if (parser->tok != ':') {
3438 if (swcase.value) ast_unref(swcase.value);
3439 ast_delete(switchnode);
3440 parseerror(parser, "expected colon");
3444 if (!parser_next(parser)) {
3445 if (swcase.value) ast_unref(swcase.value);
3446 ast_delete(switchnode);
3447 parseerror(parser, "expected statements or case");
3450 caseblock = ast_block_new(parser_ctx(parser));
3452 if (swcase.value) ast_unref(swcase.value);
3453 ast_delete(switchnode);
3456 swcase.code = (ast_expression*)caseblock;
3457 vec_push(switchnode->cases, swcase);
3459 ast_expression *expr;
3460 if (parser->tok == '}')
3462 if (parser->tok == TOKEN_KEYWORD) {
3463 if (!strcmp(parser_tokval(parser), "case") ||
3464 !strcmp(parser_tokval(parser), "default"))
3469 if (!parse_statement(parser, caseblock, &expr, true)) {
3470 ast_delete(switchnode);
3475 if (!ast_block_add_expr(caseblock, expr)) {
3476 ast_delete(switchnode);
3482 parser_leaveblock(parser);
3485 if (parser->tok != '}') {
3486 ast_delete(switchnode);
3487 parseerror(parser, "expected closing paren of case list");
3490 if (!parser_next(parser)) {
3491 ast_delete(switchnode);
3492 parseerror(parser, "parse error after switch");
3495 *out = (ast_expression*)switchnode;
3499 /* parse computed goto sides */
3500 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3501 ast_expression *on_true;
3502 ast_expression *on_false;
3503 ast_expression *cond;
3508 if (ast_istype(*side, ast_ternary)) {
3509 ast_ternary *tern = (ast_ternary*)*side;
3510 on_true = parse_goto_computed(parser, &tern->on_true);
3511 on_false = parse_goto_computed(parser, &tern->on_false);
3513 if (!on_true || !on_false) {
3514 parseerror(parser, "expected label or expression in ternary");
3515 if (on_true) ast_unref(on_true);
3516 if (on_false) ast_unref(on_false);
3524 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3525 } else if (ast_istype(*side, ast_label)) {
3526 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3527 ast_goto_set_label(gt, ((ast_label*)*side));
3529 return (ast_expression*)gt;
3534 static bool parse_goto(parser_t *parser, ast_expression **out)
3536 ast_goto *gt = NULL;
3537 ast_expression *lbl;
3539 if (!parser_next(parser))
3542 if (parser->tok != TOKEN_IDENT) {
3543 ast_expression *expression;
3545 /* could be an expression i.e computed goto :-) */
3546 if (parser->tok != '(') {
3547 parseerror(parser, "expected label name after `goto`");
3551 /* failed to parse expression for goto */
3552 if (!(expression = parse_expression(parser, false, true)) ||
3553 !(*out = parse_goto_computed(parser, &expression))) {
3554 parseerror(parser, "invalid goto expression");
3555 ast_unref(expression);
3562 /* not computed goto */
3563 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3564 lbl = parser_find_label(parser, gt->name);
3566 if (!ast_istype(lbl, ast_label)) {
3567 parseerror(parser, "internal error: label is not an ast_label");
3571 ast_goto_set_label(gt, (ast_label*)lbl);
3574 vec_push(parser->gotos, gt);
3576 if (!parser_next(parser) || parser->tok != ';') {
3577 parseerror(parser, "semicolon expected after goto label");
3580 if (!parser_next(parser)) {
3581 parseerror(parser, "parse error after goto");
3585 *out = (ast_expression*)gt;
3589 static bool parse_skipwhite(parser_t *parser)
3592 if (!parser_next(parser))
3594 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3595 return parser->tok < TOKEN_ERROR;
3598 static bool parse_eol(parser_t *parser)
3600 if (!parse_skipwhite(parser))
3602 return parser->tok == TOKEN_EOL;
3605 static bool parse_pragma_do(parser_t *parser)
3607 if (!parser_next(parser) ||
3608 parser->tok != TOKEN_IDENT ||
3609 strcmp(parser_tokval(parser), "pragma"))
3611 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3614 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3615 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3619 if (!strcmp(parser_tokval(parser), "noref")) {
3620 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3621 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3624 parser->noref = !!parser_token(parser)->constval.i;
3625 if (!parse_eol(parser)) {
3626 parseerror(parser, "parse error after `noref` pragma");
3632 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3639 static bool parse_pragma(parser_t *parser)
3642 parser->lex->flags.preprocessing = true;
3643 parser->lex->flags.mergelines = true;
3644 rv = parse_pragma_do(parser);
3645 if (parser->tok != TOKEN_EOL) {
3646 parseerror(parser, "junk after pragma");
3649 parser->lex->flags.preprocessing = false;
3650 parser->lex->flags.mergelines = false;
3651 if (!parser_next(parser)) {
3652 parseerror(parser, "parse error after pragma");
3658 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3660 bool noref, is_static;
3662 uint32_t qflags = 0;
3663 ast_value *typevar = NULL;
3664 char *vstring = NULL;
3668 if (parser->tok == TOKEN_IDENT)
3669 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3671 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3673 /* local variable */
3675 parseerror(parser, "cannot declare a variable from here");
3678 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3679 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3682 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3686 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3688 if (cvq == CV_WRONG)
3690 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3692 else if (parser->tok == TOKEN_KEYWORD)
3694 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3699 if (!parser_next(parser)) {
3700 parseerror(parser, "parse error after __builtin_debug_printtype");
3704 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3706 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3707 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3708 if (!parser_next(parser)) {
3709 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3715 if (!parse_statement(parser, block, out, allow_cases))
3718 con_out("__builtin_debug_printtype: got no output node\n");
3721 ast_type_to_string(*out, ty, sizeof(ty));
3722 con_out("__builtin_debug_printtype: `%s`\n", ty);
3727 else if (!strcmp(parser_tokval(parser), "return"))
3729 return parse_return(parser, block, out);
3731 else if (!strcmp(parser_tokval(parser), "if"))
3733 return parse_if(parser, block, out);
3735 else if (!strcmp(parser_tokval(parser), "while"))
3737 return parse_while(parser, block, out);
3739 else if (!strcmp(parser_tokval(parser), "do"))
3741 return parse_dowhile(parser, block, out);
3743 else if (!strcmp(parser_tokval(parser), "for"))
3745 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3746 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3749 return parse_for(parser, block, out);
3751 else if (!strcmp(parser_tokval(parser), "break"))
3753 return parse_break_continue(parser, block, out, false);
3755 else if (!strcmp(parser_tokval(parser), "continue"))
3757 return parse_break_continue(parser, block, out, true);
3759 else if (!strcmp(parser_tokval(parser), "switch"))
3761 return parse_switch(parser, block, out);
3763 else if (!strcmp(parser_tokval(parser), "case") ||
3764 !strcmp(parser_tokval(parser), "default"))
3767 parseerror(parser, "unexpected 'case' label");
3772 else if (!strcmp(parser_tokval(parser), "goto"))
3774 return parse_goto(parser, out);
3776 else if (!strcmp(parser_tokval(parser), "typedef"))
3778 if (!parser_next(parser)) {
3779 parseerror(parser, "expected type definition after 'typedef'");
3782 return parse_typedef(parser);
3784 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3787 else if (parser->tok == '{')
3790 inner = parse_block(parser);
3793 *out = (ast_expression*)inner;
3796 else if (parser->tok == ':')
3800 if (!parser_next(parser)) {
3801 parseerror(parser, "expected label name");
3804 if (parser->tok != TOKEN_IDENT) {
3805 parseerror(parser, "label must be an identifier");
3808 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3810 if (!label->undefined) {
3811 parseerror(parser, "label `%s` already defined", label->name);
3814 label->undefined = false;
3817 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3818 vec_push(parser->labels, label);
3820 *out = (ast_expression*)label;
3821 if (!parser_next(parser)) {
3822 parseerror(parser, "parse error after label");
3825 for (i = 0; i < vec_size(parser->gotos); ++i) {
3826 if (!strcmp(parser->gotos[i]->name, label->name)) {
3827 ast_goto_set_label(parser->gotos[i], label);
3828 vec_remove(parser->gotos, i, 1);
3834 else if (parser->tok == ';')
3836 if (!parser_next(parser)) {
3837 parseerror(parser, "parse error after empty statement");
3844 lex_ctx ctx = parser_ctx(parser);
3845 ast_expression *exp = parse_expression(parser, false, false);
3849 if (!ast_side_effects(exp)) {
3850 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3857 static bool parse_enum(parser_t *parser)
3860 bool reverse = false;
3862 ast_value **values = NULL;
3863 ast_value *var = NULL;
3866 ast_expression *old;
3868 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3869 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3873 /* enumeration attributes (can add more later) */
3874 if (parser->tok == ':') {
3875 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3876 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3881 if (!strcmp(parser_tokval(parser), "flag")) {
3885 else if (!strcmp(parser_tokval(parser), "reverse")) {
3889 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3893 if (!parser_next(parser) || parser->tok != '{') {
3894 parseerror(parser, "expected `{` after enum attribute ");
3900 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3901 if (parser->tok == '}') {
3902 /* allow an empty enum */
3905 parseerror(parser, "expected identifier or `}`");
3909 old = parser_find_field(parser, parser_tokval(parser));
3911 old = parser_find_global(parser, parser_tokval(parser));
3913 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3914 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3918 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3919 vec_push(values, var);
3920 var->cvq = CV_CONST;
3921 var->hasvalue = true;
3923 /* for flagged enumerations increment in POTs of TWO */
3924 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3925 parser_addglobal(parser, var->name, (ast_expression*)var);
3927 if (!parser_next(parser)) {
3928 parseerror(parser, "expected `=`, `}` or comma after identifier");
3932 if (parser->tok == ',')
3934 if (parser->tok == '}')
3936 if (parser->tok != '=') {
3937 parseerror(parser, "expected `=`, `}` or comma after identifier");
3941 if (!parser_next(parser)) {
3942 parseerror(parser, "expected expression after `=`");
3946 /* We got a value! */
3947 old = parse_expression_leave(parser, true, false, false);
3948 asvalue = (ast_value*)old;
3949 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3950 compile_error(ast_ctx(var), "constant value or expression expected");
3953 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3955 if (parser->tok == '}')
3957 if (parser->tok != ',') {
3958 parseerror(parser, "expected `}` or comma after expression");
3963 /* patch them all (for reversed attribute) */
3966 for (i = 0; i < vec_size(values); i++)
3967 values[i]->constval.vfloat = vec_size(values) - i - 1;
3970 if (parser->tok != '}') {
3971 parseerror(parser, "internal error: breaking without `}`");
3975 if (!parser_next(parser) || parser->tok != ';') {
3976 parseerror(parser, "expected semicolon after enumeration");
3980 if (!parser_next(parser)) {
3981 parseerror(parser, "parse error after enumeration");
3993 static bool parse_block_into(parser_t *parser, ast_block *block)
3997 parser_enterblock(parser);
3999 if (!parser_next(parser)) { /* skip the '{' */
4000 parseerror(parser, "expected function body");
4004 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4006 ast_expression *expr = NULL;
4007 if (parser->tok == '}')
4010 if (!parse_statement(parser, block, &expr, false)) {
4011 /* parseerror(parser, "parse error"); */
4017 if (!ast_block_add_expr(block, expr)) {
4024 if (parser->tok != '}') {
4027 (void)parser_next(parser);
4031 if (!parser_leaveblock(parser))
4033 return retval && !!block;
4036 static ast_block* parse_block(parser_t *parser)
4039 block = ast_block_new(parser_ctx(parser));
4042 if (!parse_block_into(parser, block)) {
4043 ast_block_delete(block);
4049 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4051 if (parser->tok == '{') {
4052 *out = (ast_expression*)parse_block(parser);
4055 return parse_statement(parser, NULL, out, false);
4058 static bool create_vector_members(ast_value *var, ast_member **me)
4061 size_t len = strlen(var->name);
4063 for (i = 0; i < 3; ++i) {
4064 char *name = (char*)mem_a(len+3);
4065 memcpy(name, var->name, len);
4067 name[len+1] = 'x'+i;
4069 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4078 do { ast_member_delete(me[--i]); } while(i);
4082 static bool parse_function_body(parser_t *parser, ast_value *var)
4084 ast_block *block = NULL;
4089 ast_expression *framenum = NULL;
4090 ast_expression *nextthink = NULL;
4091 /* None of the following have to be deleted */
4092 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4093 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4094 bool has_frame_think;
4098 has_frame_think = false;
4099 old = parser->function;
4101 if (var->expression.flags & AST_FLAG_ALIAS) {
4102 parseerror(parser, "function aliases cannot have bodies");
4106 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4107 parseerror(parser, "gotos/labels leaking");
4111 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4112 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4113 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4119 if (parser->tok == '[') {
4120 /* got a frame definition: [ framenum, nextthink ]
4121 * this translates to:
4122 * self.frame = framenum;
4123 * self.nextthink = time + 0.1;
4124 * self.think = nextthink;
4128 fld_think = parser_find_field(parser, "think");
4129 fld_nextthink = parser_find_field(parser, "nextthink");
4130 fld_frame = parser_find_field(parser, "frame");
4131 if (!fld_think || !fld_nextthink || !fld_frame) {
4132 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4133 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4136 gbl_time = parser_find_global(parser, "time");
4137 gbl_self = parser_find_global(parser, "self");
4138 if (!gbl_time || !gbl_self) {
4139 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4140 parseerror(parser, "please declare the following globals: `time`, `self`");
4144 if (!parser_next(parser))
4147 framenum = parse_expression_leave(parser, true, false, false);
4149 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4152 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4153 ast_unref(framenum);
4154 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4158 if (parser->tok != ',') {
4159 ast_unref(framenum);
4160 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4161 parseerror(parser, "Got a %i\n", parser->tok);
4165 if (!parser_next(parser)) {
4166 ast_unref(framenum);
4170 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4172 /* qc allows the use of not-yet-declared functions here
4173 * - this automatically creates a prototype */
4174 ast_value *thinkfunc;
4175 ast_expression *functype = fld_think->next;
4177 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4178 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4179 ast_unref(framenum);
4180 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4183 ast_type_adopt(thinkfunc, functype);
4185 if (!parser_next(parser)) {
4186 ast_unref(framenum);
4187 ast_delete(thinkfunc);
4191 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4193 nextthink = (ast_expression*)thinkfunc;
4196 nextthink = parse_expression_leave(parser, true, false, false);
4198 ast_unref(framenum);
4199 parseerror(parser, "expected a think-function in [frame,think] notation");
4204 if (!ast_istype(nextthink, ast_value)) {
4205 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4209 if (retval && parser->tok != ']') {
4210 parseerror(parser, "expected closing `]` for [frame,think] notation");
4214 if (retval && !parser_next(parser)) {
4218 if (retval && parser->tok != '{') {
4219 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4224 ast_unref(nextthink);
4225 ast_unref(framenum);
4229 has_frame_think = true;
4232 block = ast_block_new(parser_ctx(parser));
4234 parseerror(parser, "failed to allocate block");
4235 if (has_frame_think) {
4236 ast_unref(nextthink);
4237 ast_unref(framenum);
4242 if (has_frame_think) {
4244 ast_expression *self_frame;
4245 ast_expression *self_nextthink;
4246 ast_expression *self_think;
4247 ast_expression *time_plus_1;
4248 ast_store *store_frame;
4249 ast_store *store_nextthink;
4250 ast_store *store_think;
4252 ctx = parser_ctx(parser);
4253 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4254 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4255 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4257 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4258 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4260 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4261 if (self_frame) ast_delete(self_frame);
4262 if (self_nextthink) ast_delete(self_nextthink);
4263 if (self_think) ast_delete(self_think);
4264 if (time_plus_1) ast_delete(time_plus_1);
4270 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4271 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4272 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4275 ast_delete(self_frame);
4278 if (!store_nextthink) {
4279 ast_delete(self_nextthink);
4283 ast_delete(self_think);
4287 if (store_frame) ast_delete(store_frame);
4288 if (store_nextthink) ast_delete(store_nextthink);
4289 if (store_think) ast_delete(store_think);
4292 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4293 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4294 !ast_block_add_expr(block, (ast_expression*)store_think))
4301 parseerror(parser, "failed to generate code for [frame,think]");
4302 ast_unref(nextthink);
4303 ast_unref(framenum);
4309 if (var->hasvalue) {
4310 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4311 ast_block_delete(block);
4315 func = ast_function_new(ast_ctx(var), var->name, var);
4317 parseerror(parser, "failed to allocate function for `%s`", var->name);
4318 ast_block_delete(block);
4321 vec_push(parser->functions, func);
4323 parser_enterblock(parser);
4325 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4327 ast_value *param = var->expression.params[parami];
4330 if (param->expression.vtype != TYPE_VECTOR &&
4331 (param->expression.vtype != TYPE_FIELD ||
4332 param->expression.next->vtype != TYPE_VECTOR))
4337 if (!create_vector_members(param, me)) {
4338 ast_block_delete(block);
4342 for (e = 0; e < 3; ++e) {
4343 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4344 ast_block_collect(block, (ast_expression*)me[e]);
4348 if (var->argcounter) {
4349 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4350 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4354 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4356 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4357 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4358 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4359 varargs->expression.count = 0;
4360 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4361 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4362 ast_delete(varargs);
4363 ast_block_delete(block);
4366 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4367 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4368 ast_delete(varargs);
4369 ast_block_delete(block);
4372 func->varargs = varargs;
4374 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4377 parser->function = func;
4378 if (!parse_block_into(parser, block)) {
4379 ast_block_delete(block);
4383 vec_push(func->blocks, block);
4386 parser->function = old;
4387 if (!parser_leaveblock(parser))
4389 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4390 parseerror(parser, "internal error: local scopes left");
4394 if (parser->tok == ';')
4395 return parser_next(parser);
4396 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4397 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4401 (void)!parser_leaveblock(parser);
4402 vec_pop(parser->functions);
4403 ast_function_delete(func);
4404 var->constval.vfunc = NULL;
4407 parser->function = old;
4411 static ast_expression *array_accessor_split(
4416 ast_expression *left,
4417 ast_expression *right
4423 lex_ctx ctx = ast_ctx(array);
4425 if (!left || !right) {
4426 if (left) ast_delete(left);
4427 if (right) ast_delete(right);
4431 cmp = ast_binary_new(ctx, INSTR_LT,
4432 (ast_expression*)index,
4433 (ast_expression*)parser_const_float(parser, middle));
4437 parseerror(parser, "internal error: failed to create comparison for array setter");
4441 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4443 ast_delete(cmp); /* will delete left and right */
4444 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4448 return (ast_expression*)ifthen;
4451 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4453 lex_ctx ctx = ast_ctx(array);
4455 if (from+1 == afterend) {
4456 /* set this value */
4459 ast_array_index *subscript;
4461 int assignop = type_store_instr[value->expression.vtype];
4463 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4464 assignop = INSTR_STORE_V;
4466 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4470 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4472 ast_delete(subscript);
4476 block = ast_block_new(ctx);
4482 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4487 ret = ast_return_new(ctx, NULL);
4493 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4498 return (ast_expression*)block;
4500 ast_expression *left, *right;
4501 size_t diff = afterend - from;
4502 size_t middle = from + diff/2;
4503 left = array_setter_node(parser, array, index, value, from, middle);
4504 right = array_setter_node(parser, array, index, value, middle, afterend);
4505 return array_accessor_split(parser, array, index, middle, left, right);
4509 static ast_expression *array_field_setter_node(
4518 lex_ctx ctx = ast_ctx(array);
4520 if (from+1 == afterend) {
4521 /* set this value */
4524 ast_entfield *entfield;
4525 ast_array_index *subscript;
4527 int assignop = type_storep_instr[value->expression.vtype];
4529 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4530 assignop = INSTR_STOREP_V;
4532 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4536 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4537 subscript->expression.vtype = TYPE_FIELD;
4539 entfield = ast_entfield_new_force(ctx,
4540 (ast_expression*)entity,
4541 (ast_expression*)subscript,
4542 (ast_expression*)subscript);
4544 ast_delete(subscript);
4548 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4550 ast_delete(entfield);
4554 block = ast_block_new(ctx);
4560 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4565 ret = ast_return_new(ctx, NULL);
4571 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4576 return (ast_expression*)block;
4578 ast_expression *left, *right;
4579 size_t diff = afterend - from;
4580 size_t middle = from + diff/2;
4581 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4582 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4583 return array_accessor_split(parser, array, index, middle, left, right);
4587 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4589 lex_ctx ctx = ast_ctx(array);
4591 if (from+1 == afterend) {
4593 ast_array_index *subscript;
4595 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4599 ret = ast_return_new(ctx, (ast_expression*)subscript);
4601 ast_delete(subscript);
4605 return (ast_expression*)ret;
4607 ast_expression *left, *right;
4608 size_t diff = afterend - from;
4609 size_t middle = from + diff/2;
4610 left = array_getter_node(parser, array, index, from, middle);
4611 right = array_getter_node(parser, array, index, middle, afterend);
4612 return array_accessor_split(parser, array, index, middle, left, right);
4616 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4618 ast_function *func = NULL;
4619 ast_value *fval = NULL;
4620 ast_block *body = NULL;
4622 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4624 parseerror(parser, "failed to create accessor function value");
4628 func = ast_function_new(ast_ctx(array), funcname, fval);
4631 parseerror(parser, "failed to create accessor function node");
4635 body = ast_block_new(ast_ctx(array));
4637 parseerror(parser, "failed to create block for array accessor");
4643 vec_push(func->blocks, body);
4646 vec_push(parser->accessors, fval);
4651 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4653 ast_value *index = NULL;
4654 ast_value *value = NULL;
4658 if (!ast_istype(array->expression.next, ast_value)) {
4659 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4663 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4665 func = fval->constval.vfunc;
4666 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4668 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4669 value = ast_value_copy((ast_value*)array->expression.next);
4671 if (!index || !value) {
4672 parseerror(parser, "failed to create locals for array accessor");
4675 (void)!ast_value_set_name(value, "value"); /* not important */
4676 vec_push(fval->expression.params, index);
4677 vec_push(fval->expression.params, value);
4679 array->setter = fval;
4682 if (index) ast_delete(index);
4683 if (value) ast_delete(value);
4689 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4691 ast_expression *root = NULL;
4692 root = array_setter_node(parser, array,
4693 array->setter->expression.params[0],
4694 array->setter->expression.params[1],
4695 0, array->expression.count);
4697 parseerror(parser, "failed to build accessor search tree");
4700 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4707 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4709 if (!parser_create_array_setter_proto(parser, array, funcname))
4711 return parser_create_array_setter_impl(parser, array);
4714 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4716 ast_expression *root = NULL;
4717 ast_value *entity = NULL;
4718 ast_value *index = NULL;
4719 ast_value *value = NULL;
4723 if (!ast_istype(array->expression.next, ast_value)) {
4724 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4728 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4730 func = fval->constval.vfunc;
4731 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4733 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4734 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4735 value = ast_value_copy((ast_value*)array->expression.next);
4736 if (!entity || !index || !value) {
4737 parseerror(parser, "failed to create locals for array accessor");
4740 (void)!ast_value_set_name(value, "value"); /* not important */
4741 vec_push(fval->expression.params, entity);
4742 vec_push(fval->expression.params, index);
4743 vec_push(fval->expression.params, value);
4745 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4747 parseerror(parser, "failed to build accessor search tree");
4751 array->setter = fval;
4752 return ast_block_add_expr(func->blocks[0], root);
4754 if (entity) ast_delete(entity);
4755 if (index) ast_delete(index);
4756 if (value) ast_delete(value);
4757 if (root) ast_delete(root);
4763 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4765 ast_value *index = NULL;
4769 /* NOTE: checking array->expression.next rather than elemtype since
4770 * for fields elemtype is a temporary fieldtype.
4772 if (!ast_istype(array->expression.next, ast_value)) {
4773 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4777 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4779 func = fval->constval.vfunc;
4780 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4782 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4785 parseerror(parser, "failed to create locals for array accessor");
4788 vec_push(fval->expression.params, index);
4790 array->getter = fval;
4793 if (index) ast_delete(index);
4799 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4801 ast_expression *root = NULL;
4803 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4805 parseerror(parser, "failed to build accessor search tree");
4808 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4815 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4817 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4819 return parser_create_array_getter_impl(parser, array);
4822 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4823 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4831 bool variadic = false;
4832 ast_value *varparam = NULL;
4833 char *argcounter = NULL;
4835 ctx = parser_ctx(parser);
4837 /* for the sake of less code we parse-in in this function */
4838 if (!parser_next(parser)) {
4840 parseerror(parser, "expected parameter list");
4846 /* parse variables until we hit a closing paren */
4847 while (parser->tok != ')') {
4849 /* there must be commas between them */
4850 if (parser->tok != ',') {
4851 parseerror(parser, "expected comma or end of parameter list");
4854 if (!parser_next(parser)) {
4855 parseerror(parser, "expected parameter");
4861 if (parser->tok == TOKEN_DOTS) {
4862 /* '...' indicates a varargs function */
4864 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4865 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4868 if (parser->tok == TOKEN_IDENT) {
4869 argcounter = util_strdup(parser_tokval(parser));
4870 if (!parser_next(parser) || parser->tok != ')') {
4871 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4878 /* for anything else just parse a typename */
4879 param = parse_typename(parser, NULL, NULL);
4882 vec_push(params, param);
4883 if (param->expression.vtype >= TYPE_VARIANT) {
4884 char tname[1024]; /* typename is reserved in C++ */
4885 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4886 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4889 /* type-restricted varargs */
4890 if (parser->tok == TOKEN_DOTS) {
4892 varparam = vec_last(params);
4894 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4895 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4898 if (parser->tok == TOKEN_IDENT) {
4899 argcounter = util_strdup(parser_tokval(parser));
4900 if (!parser_next(parser) || parser->tok != ')') {
4901 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4909 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4913 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4914 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4917 if (!parser_next(parser)) {
4918 parseerror(parser, "parse error after typename");
4922 /* now turn 'var' into a function type */
4923 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4924 fval->expression.next = (ast_expression*)var;
4926 fval->expression.flags |= AST_FLAG_VARIADIC;
4929 var->expression.params = params;
4930 var->expression.varparam = (ast_expression*)varparam;
4931 var->argcounter = argcounter;
4940 ast_delete(varparam);
4942 for (i = 0; i < vec_size(params); ++i)
4943 ast_delete(params[i]);
4948 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4950 ast_expression *cexp;
4951 ast_value *cval, *tmp;
4954 ctx = parser_ctx(parser);
4956 if (!parser_next(parser)) {
4958 parseerror(parser, "expected array-size");
4962 if (parser->tok != ']') {
4963 cexp = parse_expression_leave(parser, true, false, false);
4965 if (!cexp || !ast_istype(cexp, ast_value)) {
4969 parseerror(parser, "expected array-size as constant positive integer");
4972 cval = (ast_value*)cexp;
4979 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4980 tmp->expression.next = (ast_expression*)var;
4984 if (cval->expression.vtype == TYPE_INTEGER)
4985 tmp->expression.count = cval->constval.vint;
4986 else if (cval->expression.vtype == TYPE_FLOAT)
4987 tmp->expression.count = cval->constval.vfloat;
4991 parseerror(parser, "array-size must be a positive integer constant");
4997 var->expression.count = -1;
4998 var->expression.flags |= AST_FLAG_ARRAY_INIT;
5001 if (parser->tok != ']') {
5003 parseerror(parser, "expected ']' after array-size");
5006 if (!parser_next(parser)) {
5008 parseerror(parser, "error after parsing array size");
5014 /* Parse a complete typename.
5015 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5016 * but when parsing variables separated by comma
5017 * 'storebase' should point to where the base-type should be kept.
5018 * The base type makes up every bit of type information which comes *before* the
5021 * The following will be parsed in its entirety:
5023 * The 'basetype' in this case is 'void()'
5024 * and if there's a comma after it, say:
5026 * then the type-information 'void()' can be stored in 'storebase'
5028 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5030 ast_value *var, *tmp;
5033 const char *name = NULL;
5034 bool isfield = false;
5035 bool wasarray = false;
5036 size_t morefields = 0;
5038 ctx = parser_ctx(parser);
5040 /* types may start with a dot */
5041 if (parser->tok == '.') {
5043 /* if we parsed a dot we need a typename now */
5044 if (!parser_next(parser)) {
5045 parseerror(parser, "expected typename for field definition");
5049 /* Further dots are handled seperately because they won't be part of the
5052 while (parser->tok == '.') {
5054 if (!parser_next(parser)) {
5055 parseerror(parser, "expected typename for field definition");
5060 if (parser->tok == TOKEN_IDENT)
5061 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5062 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5063 parseerror(parser, "expected typename");
5067 /* generate the basic type value */
5068 if (cached_typedef) {
5069 var = ast_value_copy(cached_typedef);
5070 ast_value_set_name(var, "<type(from_def)>");
5072 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5074 for (; morefields; --morefields) {
5075 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5076 tmp->expression.next = (ast_expression*)var;
5080 /* do not yet turn into a field - remember:
5081 * .void() foo; is a field too
5082 * .void()() foo; is a function
5086 if (!parser_next(parser)) {
5088 parseerror(parser, "parse error after typename");
5092 /* an opening paren now starts the parameter-list of a function
5093 * this is where original-QC has parameter lists.
5094 * We allow a single parameter list here.
5095 * Much like fteqcc we don't allow `float()() x`
5097 if (parser->tok == '(') {
5098 var = parse_parameter_list(parser, var);
5103 /* store the base if requested */
5105 *storebase = ast_value_copy(var);
5107 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5108 tmp->expression.next = (ast_expression*)*storebase;
5113 /* there may be a name now */
5114 if (parser->tok == TOKEN_IDENT) {
5115 name = util_strdup(parser_tokval(parser));
5117 if (!parser_next(parser)) {
5120 parseerror(parser, "error after variable or field declaration");
5125 /* now this may be an array */
5126 if (parser->tok == '[') {
5128 var = parse_arraysize(parser, var);
5130 if (name) mem_d(name);
5135 /* This is the point where we can turn it into a field */
5137 /* turn it into a field if desired */
5138 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5139 tmp->expression.next = (ast_expression*)var;
5143 /* now there may be function parens again */
5144 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5145 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5146 if (parser->tok == '(' && wasarray)
5147 parseerror(parser, "arrays as part of a return type is not supported");
5148 while (parser->tok == '(') {
5149 var = parse_parameter_list(parser, var);
5151 if (name) mem_d(name);
5156 /* finally name it */
5158 if (!ast_value_set_name(var, name)) {
5161 parseerror(parser, "internal error: failed to set name");
5164 /* free the name, ast_value_set_name duplicates */
5171 static bool parse_typedef(parser_t *parser)
5173 ast_value *typevar, *oldtype;
5174 ast_expression *old;
5176 typevar = parse_typename(parser, NULL, NULL);
5181 if ( (old = parser_find_var(parser, typevar->name)) ) {
5182 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5183 " -> `%s` has been declared here: %s:%i",
5184 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5185 ast_delete(typevar);
5189 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5190 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5191 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5192 ast_delete(typevar);
5196 vec_push(parser->_typedefs, typevar);
5197 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5199 if (parser->tok != ';') {
5200 parseerror(parser, "expected semicolon after typedef");
5203 if (!parser_next(parser)) {
5204 parseerror(parser, "parse error after typedef");
5211 static const char *cvq_to_str(int cvq) {
5213 case CV_NONE: return "none";
5214 case CV_VAR: return "`var`";
5215 case CV_CONST: return "`const`";
5216 default: return "<INVALID>";
5220 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5223 if (proto->cvq != var->cvq) {
5224 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5225 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5226 parser->tok == '='))
5228 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5229 "`%s` declared with different qualifiers: %s\n"
5230 " -> previous declaration here: %s:%i uses %s",
5231 var->name, cvq_to_str(var->cvq),
5232 ast_ctx(proto).file, ast_ctx(proto).line,
5233 cvq_to_str(proto->cvq));
5236 av = (var ->expression.flags & AST_FLAG_NORETURN);
5237 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5239 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5240 "`%s` declared with different attributes%s\n"
5241 " -> previous declaration here: %s:%i",
5242 var->name, (av ? ": noreturn" : ""),
5243 ast_ctx(proto).file, ast_ctx(proto).line,
5244 (ao ? ": noreturn" : ""));
5249 static bool create_array_accessors(parser_t *parser, ast_value *var)
5252 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5253 if (!parser_create_array_setter(parser, var, name))
5255 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5256 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5261 static bool parse_array(parser_t *parser, ast_value *array)
5264 if (array->initlist) {
5265 parseerror(parser, "array already initialized elsewhere");
5268 if (!parser_next(parser)) {
5269 parseerror(parser, "parse error in array initializer");
5273 while (parser->tok != '}') {
5274 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5277 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5279 parseerror(parser, "initializing element must be a compile time constant");
5282 vec_push(array->initlist, v->constval);
5283 if (v->expression.vtype == TYPE_STRING) {
5284 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5288 if (parser->tok == '}')
5290 if (parser->tok != ',' || !parser_next(parser)) {
5291 parseerror(parser, "expected comma or '}' in element list");
5295 if (!parser_next(parser) || parser->tok != ';') {
5296 parseerror(parser, "expected semicolon after initializer, got %s");
5300 if (!parser_next(parser)) {
5301 parseerror(parser, "parse error after initializer");
5306 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5307 if (array->expression.count != (size_t)-1) {
5308 parseerror(parser, "array `%s' has already been initialized with %u elements",
5309 array->name, (unsigned)array->expression.count);
5311 array->expression.count = vec_size(array->initlist);
5312 if (!create_array_accessors(parser, array))
5318 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)
5322 ast_expression *old;
5326 ast_value *basetype = NULL;
5328 bool isparam = false;
5329 bool isvector = false;
5330 bool cleanvar = true;
5331 bool wasarray = false;
5333 ast_member *me[3] = { NULL, NULL, NULL };
5335 if (!localblock && is_static)
5336 parseerror(parser, "`static` qualifier is not supported in global scope");
5338 /* get the first complete variable */
5339 var = parse_typename(parser, &basetype, cached_typedef);
5342 ast_delete(basetype);
5350 /* Part 0: finish the type */
5351 if (parser->tok == '(') {
5352 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5353 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5354 var = parse_parameter_list(parser, var);
5360 /* we only allow 1-dimensional arrays */
5361 if (parser->tok == '[') {
5363 var = parse_arraysize(parser, var);
5369 if (parser->tok == '(' && wasarray) {
5370 parseerror(parser, "arrays as part of a return type is not supported");
5371 /* we'll still parse the type completely for now */
5373 /* for functions returning functions */
5374 while (parser->tok == '(') {
5375 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5376 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5377 var = parse_parameter_list(parser, var);
5384 var->cvq = qualifier;
5385 var->expression.flags |= qflags;
5388 * store the vstring back to var for alias and
5389 * deprecation messages.
5391 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5392 var->expression.flags & AST_FLAG_ALIAS)
5393 var->desc = vstring;
5396 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5397 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5398 * is then filled with the previous definition and the parameter-names replaced.
5400 if (!strcmp(var->name, "nil")) {
5401 if (OPTS_FLAG(UNTYPED_NIL)) {
5402 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5403 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5405 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5408 /* Deal with end_sys_ vars */
5410 if (!strcmp(var->name, "end_sys_globals")) {
5412 parser->crc_globals = vec_size(parser->globals);
5415 else if (!strcmp(var->name, "end_sys_fields")) {
5417 parser->crc_fields = vec_size(parser->fields);
5420 if (was_end && var->expression.vtype == TYPE_FIELD) {
5421 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5422 "global '%s' hint should not be a field",
5423 parser_tokval(parser)))
5430 if (!nofields && var->expression.vtype == TYPE_FIELD)
5432 /* deal with field declarations */
5433 old = parser_find_field(parser, var->name);
5435 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5436 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5445 parseerror(parser, "field `%s` already declared here: %s:%i",
5446 var->name, ast_ctx(old).file, ast_ctx(old).line);
5451 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5452 (old = parser_find_global(parser, var->name)))
5454 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5455 parseerror(parser, "field `%s` already declared here: %s:%i",
5456 var->name, ast_ctx(old).file, ast_ctx(old).line);
5463 /* deal with other globals */
5464 old = parser_find_global(parser, var->name);
5465 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5467 /* This is a function which had a prototype */
5468 if (!ast_istype(old, ast_value)) {
5469 parseerror(parser, "internal error: prototype is not an ast_value");
5473 proto = (ast_value*)old;
5474 proto->desc = var->desc;
5475 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5476 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5478 ast_ctx(proto).file, ast_ctx(proto).line);
5482 /* we need the new parameter-names */
5483 for (i = 0; i < vec_size(proto->expression.params); ++i)
5484 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5485 if (!parser_check_qualifiers(parser, var, proto)) {
5492 proto->expression.flags |= var->expression.flags;
5500 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5501 "global `%s` already declared here: %s:%i",
5502 var->name, ast_ctx(old).file, ast_ctx(old).line))
5507 proto = (ast_value*)old;
5508 if (!ast_istype(old, ast_value)) {
5509 parseerror(parser, "internal error: not an ast_value");
5514 if (!parser_check_qualifiers(parser, var, proto)) {
5519 proto->expression.flags |= var->expression.flags;
5523 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5524 (old = parser_find_field(parser, var->name)))
5526 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5527 parseerror(parser, "global `%s` already declared here: %s:%i",
5528 var->name, ast_ctx(old).file, ast_ctx(old).line);
5535 else /* it's not a global */
5537 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5538 if (old && !isparam) {
5539 parseerror(parser, "local `%s` already declared here: %s:%i",
5540 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5544 old = parser_find_local(parser, var->name, 0, &isparam);
5545 if (old && isparam) {
5546 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5547 "local `%s` is shadowing a parameter", var->name))
5549 parseerror(parser, "local `%s` already declared here: %s:%i",
5550 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5554 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5562 /* in a noref section we simply bump the usecount */
5563 if (noref || parser->noref)
5567 * Create the global/local, and deal with vector types.
5570 if (var->expression.vtype == TYPE_VECTOR)
5572 else if (var->expression.vtype == TYPE_FIELD &&
5573 var->expression.next->vtype == TYPE_VECTOR)
5577 if (!create_vector_members(var, me)) {
5584 /* deal with global variables, fields, functions */
5585 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5586 var->isfield = true;
5587 vec_push(parser->fields, (ast_expression*)var);
5588 util_htset(parser->htfields, var->name, var);
5590 for (i = 0; i < 3; ++i) {
5591 vec_push(parser->fields, (ast_expression*)me[i]);
5592 util_htset(parser->htfields, me[i]->name, me[i]);
5597 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5598 parser_addglobal(parser, var->name, (ast_expression*)var);
5600 for (i = 0; i < 3; ++i) {
5601 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5605 ast_expression *find = parser_find_global(parser, var->desc);
5608 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5612 if (var->expression.vtype != find->vtype) {
5616 ast_type_to_string(find, ty1, sizeof(ty1));
5617 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5619 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5626 * add alias to aliases table and to corrector
5627 * so corrections can apply for aliases as well.
5629 util_htset(parser->aliases, var->name, find);
5632 * add to corrector so corrections can work
5633 * even for aliases too.
5636 vec_last(parser->correct_variables),
5637 &vec_last(parser->correct_variables_score),
5641 /* generate aliases for vector components */
5645 util_asprintf(&buffer[0], "%s_x", var->desc);
5646 util_asprintf(&buffer[1], "%s_y", var->desc);
5647 util_asprintf(&buffer[2], "%s_z", var->desc);
5649 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5650 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5651 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5658 * add to corrector so corrections can work
5659 * even for aliases too.
5662 vec_last(parser->correct_variables),
5663 &vec_last(parser->correct_variables_score),
5667 vec_last(parser->correct_variables),
5668 &vec_last(parser->correct_variables_score),
5672 vec_last(parser->correct_variables),
5673 &vec_last(parser->correct_variables_score),
5681 /* a static adds itself to be generated like any other global
5682 * but is added to the local namespace instead
5684 char *defname = NULL;
5685 size_t prefix_len, ln;
5687 ln = strlen(parser->function->name);
5688 vec_append(defname, ln, parser->function->name);
5690 vec_append(defname, 2, "::");
5691 /* remember the length up to here */
5692 prefix_len = vec_size(defname);
5694 /* Add it to the local scope */
5695 util_htset(vec_last(parser->variables), var->name, (void*)var);
5699 vec_last(parser->correct_variables),
5700 &vec_last(parser->correct_variables_score),
5704 /* now rename the global */
5705 ln = strlen(var->name);
5706 vec_append(defname, ln, var->name);
5707 ast_value_set_name(var, defname);
5709 /* push it to the to-be-generated globals */
5710 vec_push(parser->globals, (ast_expression*)var);
5712 /* same game for the vector members */
5714 for (i = 0; i < 3; ++i) {
5715 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5719 vec_last(parser->correct_variables),
5720 &vec_last(parser->correct_variables_score),
5724 vec_shrinkto(defname, prefix_len);
5725 ln = strlen(me[i]->name);
5726 vec_append(defname, ln, me[i]->name);
5727 ast_member_set_name(me[i], defname);
5729 vec_push(parser->globals, (ast_expression*)me[i]);
5734 vec_push(localblock->locals, var);
5735 parser_addlocal(parser, var->name, (ast_expression*)var);
5737 for (i = 0; i < 3; ++i) {
5738 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5739 ast_block_collect(localblock, (ast_expression*)me[i]);
5745 me[0] = me[1] = me[2] = NULL;
5750 if (var->expression.vtype == TYPE_ARRAY) {
5751 if (var->expression.count != (size_t)-1) {
5752 if (!create_array_accessors(parser, var))
5756 else if (!localblock && !nofields &&
5757 var->expression.vtype == TYPE_FIELD &&
5758 var->expression.next->vtype == TYPE_ARRAY)
5761 ast_expression *telem;
5763 ast_value *array = (ast_value*)var->expression.next;
5765 if (!ast_istype(var->expression.next, ast_value)) {
5766 parseerror(parser, "internal error: field element type must be an ast_value");
5770 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5771 if (!parser_create_array_field_setter(parser, array, name))
5774 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5775 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5776 tfield->expression.next = telem;
5777 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5778 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5786 if (parser->tok == ';') {
5787 ast_delete(basetype);
5788 if (!parser_next(parser)) {
5789 parseerror(parser, "error after variable declaration");
5795 if (parser->tok == ',')
5799 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5802 parseerror(parser, "missing comma or semicolon while parsing variables");
5806 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5807 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5808 "initializing expression turns variable `%s` into a constant in this standard",
5815 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5816 if (parser->tok != '=') {
5817 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5821 if (!parser_next(parser)) {
5822 parseerror(parser, "error parsing initializer");
5826 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5827 parseerror(parser, "expected '=' before function body in this standard");
5830 if (parser->tok == '#') {
5831 ast_function *func = NULL;
5832 ast_value *number = NULL;
5838 parseerror(parser, "cannot declare builtins within functions");
5841 if (var->expression.vtype != TYPE_FUNCTION) {
5842 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5845 if (!parser_next(parser)) {
5846 parseerror(parser, "expected builtin number");
5850 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5851 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5853 parseerror(parser, "builtin number expected");
5856 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5859 parseerror(parser, "builtin number must be a compile time constant");
5862 if (number->expression.vtype == TYPE_INTEGER)
5863 builtin_num = number->constval.vint;
5864 else if (number->expression.vtype == TYPE_FLOAT)
5865 builtin_num = number->constval.vfloat;
5868 parseerror(parser, "builtin number must be an integer constant");
5873 fractional = modff(builtin_num, &integral);
5874 if (builtin_num < 0 || fractional != 0) {
5875 parseerror(parser, "builtin number must be an integer greater than zero");
5879 /* we only want the integral part anyways */
5880 builtin_num = integral;
5881 } else if (parser->tok == TOKEN_INTCONST) {
5882 builtin_num = parser_token(parser)->constval.i;
5884 parseerror(parser, "builtin number must be a compile time constant");
5888 if (var->hasvalue) {
5889 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5890 "builtin `%s` has already been defined\n"
5891 " -> previous declaration here: %s:%i",
5892 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5896 func = ast_function_new(ast_ctx(var), var->name, var);
5898 parseerror(parser, "failed to allocate function for `%s`", var->name);
5901 vec_push(parser->functions, func);
5903 func->builtin = -builtin_num-1;
5906 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5907 ? (parser->tok != ',' && parser->tok != ';')
5908 : (!parser_next(parser)))
5910 parseerror(parser, "expected comma or semicolon");
5912 ast_function_delete(func);
5913 var->constval.vfunc = NULL;
5917 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5920 /* Note that fteqcc and most others don't even *have*
5921 * local arrays, so this is not a high priority.
5923 parseerror(parser, "TODO: initializers for local arrays");
5927 var->hasvalue = true;
5928 if (!parse_array(parser, var))
5931 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5934 parseerror(parser, "cannot declare functions within functions");
5939 ast_ctx(proto) = parser_ctx(parser);
5941 if (!parse_function_body(parser, var))
5943 ast_delete(basetype);
5944 for (i = 0; i < vec_size(parser->gotos); ++i)
5945 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5946 vec_free(parser->gotos);
5947 vec_free(parser->labels);
5950 ast_expression *cexp;
5953 cexp = parse_expression_leave(parser, true, false, false);
5958 cval = (ast_value*)cexp;
5959 if (cval != parser->nil &&
5960 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5963 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5967 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5968 qualifier != CV_VAR)
5970 var->cvq = CV_CONST;
5972 if (cval == parser->nil)
5973 var->expression.flags |= AST_FLAG_INITIALIZED;
5976 var->hasvalue = true;
5977 if (cval->expression.vtype == TYPE_STRING)
5978 var->constval.vstring = parser_strdup(cval->constval.vstring);
5979 else if (cval->expression.vtype == TYPE_FIELD)
5980 var->constval.vfield = cval;
5982 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5988 shunt sy = { NULL, NULL, NULL, NULL };
5991 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5992 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5993 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5994 if (!parser_sy_apply_operator(parser, &sy))
5997 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5998 parseerror(parser, "internal error: leaked operands");
5999 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
6010 if (parser->tok == ',') {
6011 if (!parser_next(parser)) {
6012 parseerror(parser, "expected another variable");
6016 if (parser->tok != TOKEN_IDENT) {
6017 parseerror(parser, "expected another variable");
6020 var = ast_value_copy(basetype);
6022 ast_value_set_name(var, parser_tokval(parser));
6023 if (!parser_next(parser)) {
6024 parseerror(parser, "error parsing variable declaration");
6030 if (parser->tok != ';') {
6031 parseerror(parser, "missing semicolon after variables");
6035 if (!parser_next(parser)) {
6036 parseerror(parser, "parse error after variable declaration");
6040 ast_delete(basetype);
6044 if (cleanvar && var)
6046 ast_delete(basetype);
6050 ast_delete(basetype);
6051 if (cleanvar && var)
6053 if (me[0]) ast_member_delete(me[0]);
6054 if (me[1]) ast_member_delete(me[1]);
6055 if (me[2]) ast_member_delete(me[2]);
6059 static bool parser_global_statement(parser_t *parser)
6063 bool is_static = false;
6064 uint32_t qflags = 0;
6065 ast_value *istype = NULL;
6066 char *vstring = NULL;
6068 if (parser->tok == TOKEN_IDENT)
6069 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6071 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6073 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6075 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6077 if (cvq == CV_WRONG)
6079 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6081 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6083 return parse_enum(parser);
6085 else if (parser->tok == TOKEN_KEYWORD)
6087 if (!strcmp(parser_tokval(parser), "typedef")) {
6088 if (!parser_next(parser)) {
6089 parseerror(parser, "expected type definition after 'typedef'");
6092 return parse_typedef(parser);
6094 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6097 else if (parser->tok == '#')
6099 return parse_pragma(parser);
6101 else if (parser->tok == '$')
6103 if (!parser_next(parser)) {
6104 parseerror(parser, "parse error");
6110 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6116 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6118 return util_crc16(old, str, strlen(str));
6121 static void progdefs_crc_file(const char *str)
6123 /* write to progdefs.h here */
6127 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6129 old = progdefs_crc_sum(old, str);
6130 progdefs_crc_file(str);
6134 static void generate_checksum(parser_t *parser)
6136 uint16_t crc = 0xFFFF;
6140 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6141 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6143 progdefs_crc_file("\tint\tpad;\n");
6144 progdefs_crc_file("\tint\tofs_return[3];\n");
6145 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6146 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6147 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6148 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6149 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6150 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6151 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6152 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6154 for (i = 0; i < parser->crc_globals; ++i) {
6155 if (!ast_istype(parser->globals[i], ast_value))
6157 value = (ast_value*)(parser->globals[i]);
6158 switch (value->expression.vtype) {
6159 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6160 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6161 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6162 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6164 crc = progdefs_crc_both(crc, "\tint\t");
6167 crc = progdefs_crc_both(crc, value->name);
6168 crc = progdefs_crc_both(crc, ";\n");
6170 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6171 for (i = 0; i < parser->crc_fields; ++i) {
6172 if (!ast_istype(parser->fields[i], ast_value))
6174 value = (ast_value*)(parser->fields[i]);
6175 switch (value->expression.next->vtype) {
6176 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6177 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6178 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6179 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6181 crc = progdefs_crc_both(crc, "\tint\t");
6184 crc = progdefs_crc_both(crc, value->name);
6185 crc = progdefs_crc_both(crc, ";\n");
6187 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6189 parser->code->crc = crc;
6192 parser_t *parser_create()
6198 parser = (parser_t*)mem_a(sizeof(parser_t));
6202 memset(parser, 0, sizeof(*parser));
6204 if (!(parser->code = code_init())) {
6209 for (i = 0; i < operator_count; ++i) {
6210 if (operators[i].id == opid1('=')) {
6211 parser->assign_op = operators+i;
6215 if (!parser->assign_op) {
6216 printf("internal error: initializing parser: failed to find assign operator\n");
6221 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6222 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6223 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6224 vec_push(parser->_blocktypedefs, 0);
6226 parser->aliases = util_htnew(PARSER_HT_SIZE);
6228 parser->ht_imm_string = util_htnew(512);
6231 vec_push(parser->correct_variables, correct_trie_new());
6232 vec_push(parser->correct_variables_score, NULL);
6234 empty_ctx.file = "<internal>";
6236 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6237 parser->nil->cvq = CV_CONST;
6238 if (OPTS_FLAG(UNTYPED_NIL))
6239 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6241 parser->max_param_count = 1;
6243 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6244 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6245 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6247 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6248 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6249 parser->reserved_version->cvq = CV_CONST;
6250 parser->reserved_version->hasvalue = true;
6251 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6252 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6254 parser->reserved_version = NULL;
6260 static bool parser_compile(parser_t *parser)
6262 /* initial lexer/parser state */
6263 parser->lex->flags.noops = true;
6265 if (parser_next(parser))
6267 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6269 if (!parser_global_statement(parser)) {
6270 if (parser->tok == TOKEN_EOF)
6271 parseerror(parser, "unexpected end of file");
6272 else if (compile_errors)
6273 parseerror(parser, "there have been errors, bailing out");
6274 lex_close(parser->lex);
6280 parseerror(parser, "parse error");
6281 lex_close(parser->lex);
6286 lex_close(parser->lex);
6289 return !compile_errors;
6292 bool parser_compile_file(parser_t *parser, const char *filename)
6294 parser->lex = lex_open(filename);
6296 con_err("failed to open file \"%s\"\n", filename);
6299 return parser_compile(parser);
6302 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6304 parser->lex = lex_open_string(str, len, name);
6306 con_err("failed to create lexer for string \"%s\"\n", name);
6309 return parser_compile(parser);
6312 static void parser_remove_ast(parser_t *parser)
6315 if (parser->ast_cleaned)
6317 parser->ast_cleaned = true;
6318 for (i = 0; i < vec_size(parser->accessors); ++i) {
6319 ast_delete(parser->accessors[i]->constval.vfunc);
6320 parser->accessors[i]->constval.vfunc = NULL;
6321 ast_delete(parser->accessors[i]);
6323 for (i = 0; i < vec_size(parser->functions); ++i) {
6324 ast_delete(parser->functions[i]);
6326 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6327 ast_delete(parser->imm_vector[i]);
6329 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6330 ast_delete(parser->imm_string[i]);
6332 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6333 ast_delete(parser->imm_float[i]);
6335 for (i = 0; i < vec_size(parser->fields); ++i) {
6336 ast_delete(parser->fields[i]);
6338 for (i = 0; i < vec_size(parser->globals); ++i) {
6339 ast_delete(parser->globals[i]);
6341 vec_free(parser->accessors);
6342 vec_free(parser->functions);
6343 vec_free(parser->imm_vector);
6344 vec_free(parser->imm_string);
6345 util_htdel(parser->ht_imm_string);
6346 vec_free(parser->imm_float);
6347 vec_free(parser->globals);
6348 vec_free(parser->fields);
6350 for (i = 0; i < vec_size(parser->variables); ++i)
6351 util_htdel(parser->variables[i]);
6352 vec_free(parser->variables);
6353 vec_free(parser->_blocklocals);
6354 vec_free(parser->_locals);
6357 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6358 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6360 vec_free(parser->correct_variables);
6361 vec_free(parser->correct_variables_score);
6364 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6365 ast_delete(parser->_typedefs[i]);
6366 vec_free(parser->_typedefs);
6367 for (i = 0; i < vec_size(parser->typedefs); ++i)
6368 util_htdel(parser->typedefs[i]);
6369 vec_free(parser->typedefs);
6370 vec_free(parser->_blocktypedefs);
6372 vec_free(parser->_block_ctx);
6374 vec_free(parser->labels);
6375 vec_free(parser->gotos);
6376 vec_free(parser->breaks);
6377 vec_free(parser->continues);
6379 ast_value_delete(parser->nil);
6381 ast_value_delete(parser->const_vec[0]);
6382 ast_value_delete(parser->const_vec[1]);
6383 ast_value_delete(parser->const_vec[2]);
6385 util_htdel(parser->aliases);
6386 intrin_intrinsics_destroy(parser);
6389 void parser_cleanup(parser_t *parser)
6391 parser_remove_ast(parser);
6392 code_cleanup(parser->code);
6397 bool parser_finish(parser_t *parser, const char *output)
6403 if (compile_errors) {
6404 con_out("*** there were compile errors\n");
6408 ir = ir_builder_new("gmqcc_out");
6410 con_out("failed to allocate builder\n");
6414 for (i = 0; i < vec_size(parser->fields); ++i) {
6417 if (!ast_istype(parser->fields[i], ast_value))
6419 field = (ast_value*)parser->fields[i];
6420 hasvalue = field->hasvalue;
6421 field->hasvalue = false;
6422 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6423 con_out("failed to generate field %s\n", field->name);
6424 ir_builder_delete(ir);
6429 ast_expression *subtype;
6430 field->hasvalue = true;
6431 subtype = field->expression.next;
6432 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6433 if (subtype->vtype == TYPE_FIELD)
6434 ifld->fieldtype = subtype->next->vtype;
6435 else if (subtype->vtype == TYPE_FUNCTION)
6436 ifld->outtype = subtype->next->vtype;
6437 (void)!ir_value_set_field(field->ir_v, ifld);
6440 for (i = 0; i < vec_size(parser->globals); ++i) {
6442 if (!ast_istype(parser->globals[i], ast_value))
6444 asvalue = (ast_value*)(parser->globals[i]);
6445 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6446 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6447 "unused global: `%s`", asvalue->name);
6449 if (!ast_global_codegen(asvalue, ir, false)) {
6450 con_out("failed to generate global %s\n", asvalue->name);
6451 ir_builder_delete(ir);
6455 /* Build function vararg accessor ast tree now before generating
6456 * immediates, because the accessors may add new immediates
6458 for (i = 0; i < vec_size(parser->functions); ++i) {
6459 ast_function *f = parser->functions[i];
6461 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6462 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6463 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6464 con_out("failed to generate vararg setter for %s\n", f->name);
6465 ir_builder_delete(ir);
6468 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6469 con_out("failed to generate vararg getter for %s\n", f->name);
6470 ir_builder_delete(ir);
6474 ast_delete(f->varargs);
6479 /* Now we can generate immediates */
6480 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6481 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6482 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6483 ir_builder_delete(ir);
6487 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6488 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6489 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6490 ir_builder_delete(ir);
6494 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6495 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6496 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6497 ir_builder_delete(ir);
6501 for (i = 0; i < vec_size(parser->globals); ++i) {
6503 if (!ast_istype(parser->globals[i], ast_value))
6505 asvalue = (ast_value*)(parser->globals[i]);
6506 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6508 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6509 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6510 "uninitialized constant: `%s`",
6512 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6513 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6514 "uninitialized global: `%s`",
6517 if (!ast_generate_accessors(asvalue, ir)) {
6518 ir_builder_delete(ir);
6522 for (i = 0; i < vec_size(parser->fields); ++i) {
6524 asvalue = (ast_value*)(parser->fields[i]->next);
6526 if (!ast_istype((ast_expression*)asvalue, ast_value))
6528 if (asvalue->expression.vtype != TYPE_ARRAY)
6530 if (!ast_generate_accessors(asvalue, ir)) {
6531 ir_builder_delete(ir);
6535 if (parser->reserved_version &&
6536 !ast_global_codegen(parser->reserved_version, ir, false))
6538 con_out("failed to generate reserved::version");
6539 ir_builder_delete(ir);
6542 for (i = 0; i < vec_size(parser->functions); ++i) {
6543 ast_function *f = parser->functions[i];
6544 if (!ast_function_codegen(f, ir)) {
6545 con_out("failed to generate function %s\n", f->name);
6546 ir_builder_delete(ir);
6551 generate_checksum(parser);
6552 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6553 ir_builder_dump(ir, con_out);
6554 for (i = 0; i < vec_size(parser->functions); ++i) {
6555 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6556 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6557 ir_builder_delete(ir);
6561 parser_remove_ast(parser);
6563 if (compile_Werrors) {
6564 con_out("*** there were warnings treated as errors\n");
6565 compile_show_werrors();
6570 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6571 ir_builder_dump(ir, con_out);
6573 if (!ir_builder_generate(parser->code, ir, output)) {
6574 con_out("*** failed to generate output file\n");
6575 ir_builder_delete(ir);
6579 ir_builder_delete(ir);