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]);
1037 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1040 case opid2('<','<'):
1041 case opid2('>','>'):
1042 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1043 if (op->id == opid2('<','<'))
1044 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1046 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1049 case opid3('<','<','='):
1050 case opid3('>','>','='):
1051 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1054 case opid2('|','|'):
1055 generated_op += 1; /* INSTR_OR */
1056 case opid2('&','&'):
1057 generated_op += INSTR_AND;
1058 if (CanConstFold(exprs[0], exprs[1]))
1060 if (OPTS_FLAG(PERL_LOGIC)) {
1061 if (immediate_is_true(ctx, asvalue[0]))
1065 out = (ast_expression*)parser_const_float(parser,
1066 ( (generated_op == INSTR_OR)
1067 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1068 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1073 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1074 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1075 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1076 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1079 for (i = 0; i < 2; ++i) {
1080 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1081 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1083 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1085 exprs[i] = out; out = NULL;
1086 if (OPTS_FLAG(PERL_LOGIC)) {
1087 /* here we want to keep the right expressions' type */
1091 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1092 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1094 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1096 exprs[i] = out; out = NULL;
1097 if (OPTS_FLAG(PERL_LOGIC)) {
1098 /* here we want to keep the right expressions' type */
1103 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1107 case opid2('?',':'):
1108 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1109 compile_error(ctx, "mismatched parenthesis/ternary");
1113 if (!ast_compare_type(exprs[1], exprs[2])) {
1114 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1115 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1116 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1119 if (CanConstFold1(exprs[0]))
1120 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1122 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1125 case opid2('*', '*'):
1126 if (NotSameType(TYPE_FLOAT)) {
1127 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1128 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1129 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1135 if (CanConstFold(exprs[0], exprs[1])) {
1136 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1138 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1139 vec_push(gencall->params, exprs[0]);
1140 vec_push(gencall->params, exprs[1]);
1141 out = (ast_expression*)gencall;
1145 case opid3('<','=','>'): /* -1, 0, or 1 */
1146 if (NotSameType(TYPE_FLOAT)) {
1147 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1148 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1149 compile_error(ctx, "invalid types used in comparision: %s and %s",
1155 if (CanConstFold(exprs[0], exprs[1])) {
1156 if (ConstF(0) < ConstF(1))
1157 out = (ast_expression*)parser_const_float_neg1(parser);
1158 else if (ConstF(0) == ConstF(1))
1159 out = (ast_expression*)parser_const_float_0(parser);
1160 else if (ConstF(0) > ConstF(1))
1161 out = (ast_expression*)parser_const_float_1(parser);
1163 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1165 eq->refs = (ast_binary_ref)false; /* references nothing */
1168 out = (ast_expression*)ast_ternary_new(ctx,
1169 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1171 (ast_expression*)parser_const_float_neg1(parser),
1174 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1176 (ast_expression*)parser_const_float_0(parser),
1179 (ast_expression*)parser_const_float_1(parser)
1189 generated_op += 1; /* INSTR_GT */
1191 generated_op += 1; /* INSTR_LT */
1192 case opid2('>', '='):
1193 generated_op += 1; /* INSTR_GE */
1194 case opid2('<', '='):
1195 generated_op += INSTR_LE;
1196 if (NotSameType(TYPE_FLOAT)) {
1197 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1198 type_name[exprs[0]->vtype],
1199 type_name[exprs[1]->vtype]);
1202 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1204 case opid2('!', '='):
1205 if (exprs[0]->vtype != exprs[1]->vtype) {
1206 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1207 type_name[exprs[0]->vtype],
1208 type_name[exprs[1]->vtype]);
1211 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1213 case opid2('=', '='):
1214 if (exprs[0]->vtype != exprs[1]->vtype) {
1215 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1216 type_name[exprs[0]->vtype],
1217 type_name[exprs[1]->vtype]);
1220 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1224 if (ast_istype(exprs[0], ast_entfield)) {
1225 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1226 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1227 exprs[0]->vtype == TYPE_FIELD &&
1228 exprs[0]->next->vtype == TYPE_VECTOR)
1230 assignop = type_storep_instr[TYPE_VECTOR];
1233 assignop = type_storep_instr[exprs[0]->vtype];
1234 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1236 ast_type_to_string(field->next, ty1, sizeof(ty1));
1237 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1238 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1239 field->next->vtype == TYPE_FUNCTION &&
1240 exprs[1]->vtype == TYPE_FUNCTION)
1242 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1243 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1246 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1251 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1252 exprs[0]->vtype == TYPE_FIELD &&
1253 exprs[0]->next->vtype == TYPE_VECTOR)
1255 assignop = type_store_instr[TYPE_VECTOR];
1258 assignop = type_store_instr[exprs[0]->vtype];
1261 if (assignop == VINSTR_END) {
1262 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1263 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1264 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1266 else if (!ast_compare_type(exprs[0], exprs[1]))
1268 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1269 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1270 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1271 exprs[0]->vtype == TYPE_FUNCTION &&
1272 exprs[1]->vtype == TYPE_FUNCTION)
1274 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1275 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1278 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1281 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1282 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1284 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1286 case opid3('+','+','P'):
1287 case opid3('-','-','P'):
1289 if (exprs[0]->vtype != TYPE_FLOAT) {
1290 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1291 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1294 if (op->id == opid3('+','+','P'))
1295 addop = INSTR_ADD_F;
1297 addop = INSTR_SUB_F;
1298 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1299 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1301 if (ast_istype(exprs[0], ast_entfield)) {
1302 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1304 (ast_expression*)parser_const_float_1(parser));
1306 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1308 (ast_expression*)parser_const_float_1(parser));
1311 case opid3('S','+','+'):
1312 case opid3('S','-','-'):
1314 if (exprs[0]->vtype != TYPE_FLOAT) {
1315 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1316 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1319 if (op->id == opid3('S','+','+')) {
1320 addop = INSTR_ADD_F;
1321 subop = INSTR_SUB_F;
1323 addop = INSTR_SUB_F;
1324 subop = INSTR_ADD_F;
1326 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1327 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1329 if (ast_istype(exprs[0], ast_entfield)) {
1330 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1332 (ast_expression*)parser_const_float_1(parser));
1334 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1336 (ast_expression*)parser_const_float_1(parser));
1340 out = (ast_expression*)ast_binary_new(ctx, subop,
1342 (ast_expression*)parser_const_float_1(parser));
1344 case opid2('+','='):
1345 case opid2('-','='):
1346 if (exprs[0]->vtype != exprs[1]->vtype ||
1347 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1349 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1350 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1351 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1355 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1356 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1358 if (ast_istype(exprs[0], ast_entfield))
1359 assignop = type_storep_instr[exprs[0]->vtype];
1361 assignop = type_store_instr[exprs[0]->vtype];
1362 switch (exprs[0]->vtype) {
1364 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1365 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1366 exprs[0], exprs[1]);
1369 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1370 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1371 exprs[0], exprs[1]);
1374 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1375 type_name[exprs[0]->vtype],
1376 type_name[exprs[1]->vtype]);
1380 case opid2('*','='):
1381 case opid2('/','='):
1382 if (exprs[1]->vtype != TYPE_FLOAT ||
1383 !(exprs[0]->vtype == TYPE_FLOAT ||
1384 exprs[0]->vtype == TYPE_VECTOR))
1386 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1387 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1388 compile_error(ctx, "invalid types used in expression: %s and %s",
1392 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1393 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1395 if (ast_istype(exprs[0], ast_entfield))
1396 assignop = type_storep_instr[exprs[0]->vtype];
1398 assignop = type_store_instr[exprs[0]->vtype];
1399 switch (exprs[0]->vtype) {
1401 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1402 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1403 exprs[0], exprs[1]);
1406 if (op->id == opid2('*','=')) {
1407 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1408 exprs[0], exprs[1]);
1410 /* there's no DIV_VF */
1411 if (CanConstFold1(exprs[1])) {
1412 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1414 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1415 (ast_expression*)parser_const_float_1(parser),
1419 compile_error(ctx, "internal error: failed to generate division");
1422 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1427 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1428 type_name[exprs[0]->vtype],
1429 type_name[exprs[1]->vtype]);
1433 case opid2('&','='):
1434 case opid2('|','='):
1435 if (NotSameType(TYPE_FLOAT)) {
1436 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1437 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1438 compile_error(ctx, "invalid types used in expression: %s and %s",
1442 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1443 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1445 if (ast_istype(exprs[0], ast_entfield))
1446 assignop = type_storep_instr[exprs[0]->vtype];
1448 assignop = type_store_instr[exprs[0]->vtype];
1449 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1450 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1451 exprs[0], exprs[1]);
1453 case opid3('&','~','='):
1454 /* This is like: a &= ~(b);
1455 * But QC has no bitwise-not, so we implement it as
1458 if (NotSameType(TYPE_FLOAT)) {
1459 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1460 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1461 compile_error(ctx, "invalid types used in expression: %s and %s",
1465 if (ast_istype(exprs[0], ast_entfield))
1466 assignop = type_storep_instr[exprs[0]->vtype];
1468 assignop = type_store_instr[exprs[0]->vtype];
1469 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1472 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1473 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1475 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1476 asbinstore->keep_dest = true;
1477 out = (ast_expression*)asbinstore;
1480 case opid2('~', 'P'):
1481 if (exprs[0]->vtype != TYPE_FLOAT) {
1482 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1483 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1487 if(CanConstFold1(exprs[0]))
1488 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1490 out = (ast_expression*)
1491 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1497 compile_error(ctx, "failed to apply operator %s", op->op);
1501 vec_push(sy->out, syexp(ctx, out));
1505 static bool parser_close_call(parser_t *parser, shunt *sy)
1507 /* was a function call */
1508 ast_expression *fun;
1509 ast_value *funval = NULL;
1513 size_t paramcount, i;
1515 fid = vec_last(sy->ops).off;
1516 vec_shrinkby(sy->ops, 1);
1518 /* out[fid] is the function
1519 * everything above is parameters...
1521 if (!vec_size(sy->argc)) {
1522 parseerror(parser, "internal error: no argument counter available");
1526 paramcount = vec_last(sy->argc);
1529 if (vec_size(sy->out) < fid) {
1530 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1531 (unsigned long)vec_size(sy->out),
1533 (unsigned long)paramcount);
1537 fun = sy->out[fid].out;
1539 if (fun == intrinsic_debug_typestring) {
1541 if (fid+2 != vec_size(sy->out) ||
1542 vec_last(sy->out).block)
1544 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1547 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1548 ast_unref(vec_last(sy->out).out);
1549 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1550 (ast_expression*)parser_const_string(parser, ty, false));
1551 vec_shrinkby(sy->out, 1);
1555 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1559 if (fid+1 < vec_size(sy->out))
1562 if (fid+1 + paramcount != vec_size(sy->out)) {
1563 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1564 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1568 for (i = 0; i < paramcount; ++i)
1569 vec_push(call->params, sy->out[fid+1 + i].out);
1570 vec_shrinkby(sy->out, paramcount);
1571 (void)!ast_call_check_types(call);
1572 if (parser->max_param_count < paramcount)
1573 parser->max_param_count = paramcount;
1575 if (ast_istype(fun, ast_value)) {
1576 funval = (ast_value*)fun;
1577 if ((fun->flags & AST_FLAG_VARIADIC) &&
1578 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1580 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1584 /* overwrite fid, the function, with a call */
1585 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1587 if (fun->vtype != TYPE_FUNCTION) {
1588 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1593 parseerror(parser, "could not determine function return type");
1596 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1598 if (fun->flags & AST_FLAG_DEPRECATED) {
1600 return !parsewarning(parser, WARN_DEPRECATED,
1601 "call to function (which is marked deprecated)\n",
1602 "-> it has been declared here: %s:%i",
1603 ast_ctx(fun).file, ast_ctx(fun).line);
1606 return !parsewarning(parser, WARN_DEPRECATED,
1607 "call to `%s` (which is marked deprecated)\n"
1608 "-> `%s` declared here: %s:%i",
1609 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1611 return !parsewarning(parser, WARN_DEPRECATED,
1612 "call to `%s` (deprecated: %s)\n"
1613 "-> `%s` declared here: %s:%i",
1614 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1618 if (vec_size(fun->params) != paramcount &&
1619 !((fun->flags & AST_FLAG_VARIADIC) &&
1620 vec_size(fun->params) < paramcount))
1622 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1624 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1625 "too %s parameters for call to %s: expected %i, got %i\n"
1626 " -> `%s` has been declared here: %s:%i",
1627 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1628 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1630 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1631 "too %s parameters for function call: expected %i, got %i\n"
1632 " -> it has been declared here: %s:%i",
1633 fewmany, (int)vec_size(fun->params), (int)paramcount,
1634 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1641 static bool parser_close_paren(parser_t *parser, shunt *sy)
1643 if (!vec_size(sy->ops)) {
1644 parseerror(parser, "unmatched closing paren");
1648 while (vec_size(sy->ops)) {
1649 if (vec_last(sy->ops).isparen) {
1650 if (vec_last(sy->paren) == PAREN_FUNC) {
1652 if (!parser_close_call(parser, sy))
1656 if (vec_last(sy->paren) == PAREN_EXPR) {
1658 if (!vec_size(sy->out)) {
1659 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1660 vec_shrinkby(sy->ops, 1);
1663 vec_shrinkby(sy->ops, 1);
1666 if (vec_last(sy->paren) == PAREN_INDEX) {
1668 /* pop off the parenthesis */
1669 vec_shrinkby(sy->ops, 1);
1670 /* then apply the index operator */
1671 if (!parser_sy_apply_operator(parser, sy))
1675 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1676 vec_last(sy->paren) = PAREN_TERNARY2;
1677 /* pop off the parenthesis */
1678 vec_shrinkby(sy->ops, 1);
1681 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1684 if (!parser_sy_apply_operator(parser, sy))
1690 static void parser_reclassify_token(parser_t *parser)
1693 for (i = 0; i < operator_count; ++i) {
1694 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1695 parser->tok = TOKEN_OPERATOR;
1701 static ast_expression* parse_vararg_do(parser_t *parser)
1703 ast_expression *idx, *out;
1705 ast_value *funtype = parser->function->vtype;
1707 lex_ctx ctx = parser_ctx(parser);
1709 if (!parser_next(parser) || parser->tok != '(') {
1710 parseerror(parser, "expected parameter index and type in parenthesis");
1713 if (!parser_next(parser)) {
1714 parseerror(parser, "error parsing parameter index");
1718 idx = parse_expression_leave(parser, true, false, false);
1722 if (parser->tok != ',') {
1724 parseerror(parser, "expected comma after parameter index");
1728 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1730 parseerror(parser, "expected typename for vararg");
1734 typevar = parse_typename(parser, NULL, NULL);
1740 if (parser->tok != ')') {
1742 ast_delete(typevar);
1743 parseerror(parser, "expected closing paren");
1748 if (!parser_next(parser)) {
1750 ast_delete(typevar);
1751 parseerror(parser, "parse error after vararg");
1756 if (!parser->function->varargs) {
1758 ast_delete(typevar);
1759 parseerror(parser, "function has no variable argument list");
1763 if (funtype->expression.varparam &&
1764 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1768 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1769 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1770 compile_error(ast_ctx(typevar),
1771 "function was declared to take varargs of type `%s`, requested type is: %s",
1775 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1776 ast_type_adopt(out, typevar);
1777 ast_delete(typevar);
1781 static ast_expression* parse_vararg(parser_t *parser)
1783 bool old_noops = parser->lex->flags.noops;
1785 ast_expression *out;
1787 parser->lex->flags.noops = true;
1788 out = parse_vararg_do(parser);
1790 parser->lex->flags.noops = old_noops;
1794 /* not to be exposed */
1795 extern bool ftepp_predef_exists(const char *name);
1797 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1799 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1800 parser->tok == TOKEN_IDENT &&
1801 !strcmp(parser_tokval(parser), "_"))
1803 /* a translatable string */
1806 parser->lex->flags.noops = true;
1807 if (!parser_next(parser) || parser->tok != '(') {
1808 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1811 parser->lex->flags.noops = false;
1812 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1813 parseerror(parser, "expected a constant string in translatable-string extension");
1816 val = parser_const_string(parser, parser_tokval(parser), true);
1819 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1821 if (!parser_next(parser) || parser->tok != ')') {
1822 parseerror(parser, "expected closing paren after translatable string");
1827 else if (parser->tok == TOKEN_DOTS)
1830 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1831 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1834 va = parse_vararg(parser);
1837 vec_push(sy->out, syexp(parser_ctx(parser), va));
1840 else if (parser->tok == TOKEN_FLOATCONST) {
1842 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1845 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1848 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1850 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1853 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1856 else if (parser->tok == TOKEN_STRINGCONST) {
1858 val = parser_const_string(parser, parser_tokval(parser), false);
1861 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1864 else if (parser->tok == TOKEN_VECTORCONST) {
1866 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1869 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1872 else if (parser->tok == TOKEN_IDENT)
1874 const char *ctoken = parser_tokval(parser);
1875 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1876 ast_expression *var;
1877 /* a_vector.{x,y,z} */
1878 if (!vec_size(sy->ops) ||
1879 !vec_last(sy->ops).etype ||
1880 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1881 (prev >= intrinsic_debug_typestring &&
1882 prev <= intrinsic_debug_typestring))
1884 /* When adding more intrinsics, fix the above condition */
1887 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1889 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1891 var = parser_find_var(parser, parser_tokval(parser));
1893 var = parser_find_field(parser, parser_tokval(parser));
1895 if (!var && with_labels) {
1896 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1898 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1899 var = (ast_expression*)lbl;
1900 vec_push(parser->labels, lbl);
1903 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1904 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1907 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1908 var = (ast_expression*)intrinsic_debug_typestring;
1910 /* now we try for the real intrinsic hashtable. If the string
1911 * begins with __builtin, we simply skip past it, otherwise we
1912 * use the identifier as is.
1914 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1915 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1919 char *correct = NULL;
1923 * sometimes people use preprocessing predefs without enabling them
1924 * i've done this thousands of times already myself. Lets check for
1925 * it in the predef table. And diagnose it better :)
1927 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1928 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1933 * TODO: determine the best score for the identifier: be it
1934 * a variable, a field.
1936 * We should also consider adding correction tables for
1937 * other things as well.
1939 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1941 correct_init(&corr);
1943 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1944 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1945 if (strcmp(correct, parser_tokval(parser))) {
1947 } else if (correct) {
1952 correct_free(&corr);
1955 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1960 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1966 if (ast_istype(var, ast_value)) {
1967 ((ast_value*)var)->uses++;
1969 else if (ast_istype(var, ast_member)) {
1970 ast_member *mem = (ast_member*)var;
1971 if (ast_istype(mem->owner, ast_value))
1972 ((ast_value*)(mem->owner))->uses++;
1975 vec_push(sy->out, syexp(parser_ctx(parser), var));
1978 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1982 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1984 ast_expression *expr = NULL;
1987 bool wantop = false;
1988 /* only warn once about an assignment in a truth value because the current code
1989 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1991 bool warn_truthvalue = true;
1993 /* count the parens because an if starts with one, so the
1994 * end of a condition is an unmatched closing paren
1998 memset(&sy, 0, sizeof(sy));
2000 parser->lex->flags.noops = false;
2002 parser_reclassify_token(parser);
2006 if (parser->tok == TOKEN_TYPENAME) {
2007 parseerror(parser, "unexpected typename");
2011 if (parser->tok == TOKEN_OPERATOR)
2013 /* classify the operator */
2014 const oper_info *op;
2015 const oper_info *olast = NULL;
2017 for (o = 0; o < operator_count; ++o) {
2018 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2019 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2020 !strcmp(parser_tokval(parser), operators[o].op))
2025 if (o == operator_count) {
2026 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2029 /* found an operator */
2032 /* when declaring variables, a comma starts a new variable */
2033 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2034 /* fixup the token */
2039 /* a colon without a pervious question mark cannot be a ternary */
2040 if (!ternaries && op->id == opid2(':','?')) {
2045 if (op->id == opid1(',')) {
2046 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2047 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2051 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2052 olast = &operators[vec_last(sy.ops).etype-1];
2054 #define IsAssignOp(x) (\
2055 (x) == opid1('=') || \
2056 (x) == opid2('+','=') || \
2057 (x) == opid2('-','=') || \
2058 (x) == opid2('*','=') || \
2059 (x) == opid2('/','=') || \
2060 (x) == opid2('%','=') || \
2061 (x) == opid2('&','=') || \
2062 (x) == opid2('|','=') || \
2063 (x) == opid3('&','~','=') \
2065 if (warn_truthvalue) {
2066 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2067 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2068 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2071 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2072 warn_truthvalue = false;
2077 (op->prec < olast->prec) ||
2078 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2080 if (!parser_sy_apply_operator(parser, &sy))
2082 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2083 olast = &operators[vec_last(sy.ops).etype-1];
2088 if (op->id == opid1('(')) {
2090 size_t sycount = vec_size(sy.out);
2091 /* we expected an operator, this is the function-call operator */
2092 vec_push(sy.paren, PAREN_FUNC);
2093 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2094 vec_push(sy.argc, 0);
2096 vec_push(sy.paren, PAREN_EXPR);
2097 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2100 } else if (op->id == opid1('[')) {
2102 parseerror(parser, "unexpected array subscript");
2105 vec_push(sy.paren, PAREN_INDEX);
2106 /* push both the operator and the paren, this makes life easier */
2107 vec_push(sy.ops, syop(parser_ctx(parser), op));
2108 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2110 } else if (op->id == opid2('?',':')) {
2111 vec_push(sy.ops, syop(parser_ctx(parser), op));
2112 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2115 vec_push(sy.paren, PAREN_TERNARY1);
2116 } else if (op->id == opid2(':','?')) {
2117 if (!vec_size(sy.paren)) {
2118 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2121 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2122 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2125 if (!parser_close_paren(parser, &sy))
2127 vec_push(sy.ops, syop(parser_ctx(parser), op));
2131 vec_push(sy.ops, syop(parser_ctx(parser), op));
2132 wantop = !!(op->flags & OP_SUFFIX);
2135 else if (parser->tok == ')') {
2136 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2137 if (!parser_sy_apply_operator(parser, &sy))
2140 if (!vec_size(sy.paren))
2143 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2144 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2147 if (!parser_close_paren(parser, &sy))
2150 /* must be a function call without parameters */
2151 if (vec_last(sy.paren) != PAREN_FUNC) {
2152 parseerror(parser, "closing paren in invalid position");
2155 if (!parser_close_paren(parser, &sy))
2160 else if (parser->tok == '(') {
2161 parseerror(parser, "internal error: '(' should be classified as operator");
2164 else if (parser->tok == '[') {
2165 parseerror(parser, "internal error: '[' should be classified as operator");
2168 else if (parser->tok == ']') {
2169 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2170 if (!parser_sy_apply_operator(parser, &sy))
2173 if (!vec_size(sy.paren))
2175 if (vec_last(sy.paren) != PAREN_INDEX) {
2176 parseerror(parser, "mismatched parentheses, unexpected ']'");
2179 if (!parser_close_paren(parser, &sy))
2184 if (!parse_sya_operand(parser, &sy, with_labels))
2187 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2188 vec_last(sy.argc)++;
2193 /* in this case we might want to allow constant string concatenation */
2194 bool concatenated = false;
2195 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2196 ast_expression *lexpr = vec_last(sy.out).out;
2197 if (ast_istype(lexpr, ast_value)) {
2198 ast_value *last = (ast_value*)lexpr;
2199 if (last->isimm == true && last->cvq == CV_CONST &&
2200 last->hasvalue && last->expression.vtype == TYPE_STRING)
2202 char *newstr = NULL;
2203 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2204 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2206 concatenated = true;
2210 if (!concatenated) {
2211 parseerror(parser, "expected operator or end of statement");
2216 if (!parser_next(parser)) {
2219 if (parser->tok == ';' ||
2220 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2221 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2227 while (vec_size(sy.ops)) {
2228 if (!parser_sy_apply_operator(parser, &sy))
2232 parser->lex->flags.noops = true;
2233 if (vec_size(sy.out) != 1) {
2234 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2237 expr = sy.out[0].out;
2240 if (vec_size(sy.paren)) {
2241 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2249 parser->lex->flags.noops = true;
2250 for (i = 0; i < vec_size(sy.out); ++i) {
2252 ast_unref(sy.out[i].out);
2261 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2263 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2266 if (parser->tok != ';') {
2267 parseerror(parser, "semicolon expected after expression");
2271 if (!parser_next(parser)) {
2278 static void parser_enterblock(parser_t *parser)
2280 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2281 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2282 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2283 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2284 vec_push(parser->_block_ctx, parser_ctx(parser));
2287 vec_push(parser->correct_variables, correct_trie_new());
2288 vec_push(parser->correct_variables_score, NULL);
2291 static bool parser_leaveblock(parser_t *parser)
2294 size_t locals, typedefs;
2296 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2297 parseerror(parser, "internal error: parser_leaveblock with no block");
2301 util_htdel(vec_last(parser->variables));
2302 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2304 vec_pop(parser->variables);
2305 vec_pop(parser->correct_variables);
2306 vec_pop(parser->correct_variables_score);
2307 if (!vec_size(parser->_blocklocals)) {
2308 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2312 locals = vec_last(parser->_blocklocals);
2313 vec_pop(parser->_blocklocals);
2314 while (vec_size(parser->_locals) != locals) {
2315 ast_expression *e = vec_last(parser->_locals);
2316 ast_value *v = (ast_value*)e;
2317 vec_pop(parser->_locals);
2318 if (ast_istype(e, ast_value) && !v->uses) {
2319 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2324 typedefs = vec_last(parser->_blocktypedefs);
2325 while (vec_size(parser->_typedefs) != typedefs) {
2326 ast_delete(vec_last(parser->_typedefs));
2327 vec_pop(parser->_typedefs);
2329 util_htdel(vec_last(parser->typedefs));
2330 vec_pop(parser->typedefs);
2332 vec_pop(parser->_block_ctx);
2337 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2339 vec_push(parser->_locals, e);
2340 util_htset(vec_last(parser->variables), name, (void*)e);
2344 vec_last(parser->correct_variables),
2345 &vec_last(parser->correct_variables_score),
2350 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2352 vec_push(parser->globals, e);
2353 util_htset(parser->htglobals, name, e);
2357 parser->correct_variables[0],
2358 &parser->correct_variables_score[0],
2363 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2367 ast_expression *prev;
2369 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2371 ast_type_to_string(cond, ty, sizeof(ty));
2372 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2375 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2378 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2381 parseerror(parser, "internal error: failed to process condition");
2386 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2388 /* vector types need to be cast to true booleans */
2389 ast_binary *bin = (ast_binary*)cond;
2390 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2392 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2394 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2397 parseerror(parser, "internal error: failed to process condition");
2404 unary = (ast_unary*)cond;
2405 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2407 cond = unary->operand;
2408 unary->operand = NULL;
2411 unary = (ast_unary*)cond;
2415 parseerror(parser, "internal error: failed to process condition");
2417 if (ifnot) *_ifnot = !*_ifnot;
2421 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2424 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2427 lex_ctx ctx = parser_ctx(parser);
2429 (void)block; /* not touching */
2431 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2432 if (!parser_next(parser)) {
2433 parseerror(parser, "expected condition or 'not'");
2436 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2438 if (!parser_next(parser)) {
2439 parseerror(parser, "expected condition in parenthesis");
2443 if (parser->tok != '(') {
2444 parseerror(parser, "expected 'if' condition in parenthesis");
2447 /* parse into the expression */
2448 if (!parser_next(parser)) {
2449 parseerror(parser, "expected 'if' condition after opening paren");
2452 /* parse the condition */
2453 cond = parse_expression_leave(parser, false, true, false);
2457 if (parser->tok != ')') {
2458 parseerror(parser, "expected closing paren after 'if' condition");
2462 /* parse into the 'then' branch */
2463 if (!parser_next(parser)) {
2464 parseerror(parser, "expected statement for on-true branch of 'if'");
2468 if (!parse_statement_or_block(parser, &ontrue)) {
2473 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2474 /* check for an else */
2475 if (!strcmp(parser_tokval(parser), "else")) {
2476 /* parse into the 'else' branch */
2477 if (!parser_next(parser)) {
2478 parseerror(parser, "expected on-false branch after 'else'");
2483 if (!parse_statement_or_block(parser, &onfalse)) {
2490 cond = process_condition(parser, cond, &ifnot);
2492 if (ontrue) ast_delete(ontrue);
2493 if (onfalse) ast_delete(onfalse);
2498 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2500 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2501 *out = (ast_expression*)ifthen;
2505 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2506 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2511 /* skip the 'while' and get the body */
2512 if (!parser_next(parser)) {
2513 if (OPTS_FLAG(LOOP_LABELS))
2514 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2516 parseerror(parser, "expected 'while' condition in parenthesis");
2520 if (parser->tok == ':') {
2521 if (!OPTS_FLAG(LOOP_LABELS))
2522 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2523 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2524 parseerror(parser, "expected loop label");
2527 label = util_strdup(parser_tokval(parser));
2528 if (!parser_next(parser)) {
2530 parseerror(parser, "expected 'while' condition in parenthesis");
2535 if (parser->tok != '(') {
2536 parseerror(parser, "expected 'while' condition in parenthesis");
2540 vec_push(parser->breaks, label);
2541 vec_push(parser->continues, label);
2543 rv = parse_while_go(parser, block, out);
2546 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2547 parseerror(parser, "internal error: label stack corrupted");
2553 vec_pop(parser->breaks);
2554 vec_pop(parser->continues);
2559 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2562 ast_expression *cond, *ontrue;
2566 lex_ctx ctx = parser_ctx(parser);
2568 (void)block; /* not touching */
2570 /* parse into the expression */
2571 if (!parser_next(parser)) {
2572 parseerror(parser, "expected 'while' condition after opening paren");
2575 /* parse the condition */
2576 cond = parse_expression_leave(parser, false, true, false);
2580 if (parser->tok != ')') {
2581 parseerror(parser, "expected closing paren after 'while' condition");
2585 /* parse into the 'then' branch */
2586 if (!parser_next(parser)) {
2587 parseerror(parser, "expected while-loop body");
2591 if (!parse_statement_or_block(parser, &ontrue)) {
2596 cond = process_condition(parser, cond, &ifnot);
2601 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2602 *out = (ast_expression*)aloop;
2606 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2607 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2612 /* skip the 'do' and get the body */
2613 if (!parser_next(parser)) {
2614 if (OPTS_FLAG(LOOP_LABELS))
2615 parseerror(parser, "expected loop label or body");
2617 parseerror(parser, "expected loop body");
2621 if (parser->tok == ':') {
2622 if (!OPTS_FLAG(LOOP_LABELS))
2623 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2624 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2625 parseerror(parser, "expected loop label");
2628 label = util_strdup(parser_tokval(parser));
2629 if (!parser_next(parser)) {
2631 parseerror(parser, "expected loop body");
2636 vec_push(parser->breaks, label);
2637 vec_push(parser->continues, label);
2639 rv = parse_dowhile_go(parser, block, out);
2642 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2643 parseerror(parser, "internal error: label stack corrupted");
2649 vec_pop(parser->breaks);
2650 vec_pop(parser->continues);
2655 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2658 ast_expression *cond, *ontrue;
2662 lex_ctx ctx = parser_ctx(parser);
2664 (void)block; /* not touching */
2666 if (!parse_statement_or_block(parser, &ontrue))
2669 /* expect the "while" */
2670 if (parser->tok != TOKEN_KEYWORD ||
2671 strcmp(parser_tokval(parser), "while"))
2673 parseerror(parser, "expected 'while' and condition");
2678 /* skip the 'while' and check for opening paren */
2679 if (!parser_next(parser) || parser->tok != '(') {
2680 parseerror(parser, "expected 'while' condition in parenthesis");
2684 /* parse into the expression */
2685 if (!parser_next(parser)) {
2686 parseerror(parser, "expected 'while' condition after opening paren");
2690 /* parse the condition */
2691 cond = parse_expression_leave(parser, false, true, false);
2695 if (parser->tok != ')') {
2696 parseerror(parser, "expected closing paren after 'while' condition");
2702 if (!parser_next(parser) || parser->tok != ';') {
2703 parseerror(parser, "expected semicolon after condition");
2709 if (!parser_next(parser)) {
2710 parseerror(parser, "parse error");
2716 cond = process_condition(parser, cond, &ifnot);
2721 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2722 *out = (ast_expression*)aloop;
2726 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2727 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2732 /* skip the 'for' and check for opening paren */
2733 if (!parser_next(parser)) {
2734 if (OPTS_FLAG(LOOP_LABELS))
2735 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2737 parseerror(parser, "expected 'for' expressions in parenthesis");
2741 if (parser->tok == ':') {
2742 if (!OPTS_FLAG(LOOP_LABELS))
2743 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2744 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2745 parseerror(parser, "expected loop label");
2748 label = util_strdup(parser_tokval(parser));
2749 if (!parser_next(parser)) {
2751 parseerror(parser, "expected 'for' expressions in parenthesis");
2756 if (parser->tok != '(') {
2757 parseerror(parser, "expected 'for' expressions in parenthesis");
2761 vec_push(parser->breaks, label);
2762 vec_push(parser->continues, label);
2764 rv = parse_for_go(parser, block, out);
2767 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2768 parseerror(parser, "internal error: label stack corrupted");
2774 vec_pop(parser->breaks);
2775 vec_pop(parser->continues);
2779 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2782 ast_expression *initexpr, *cond, *increment, *ontrue;
2787 lex_ctx ctx = parser_ctx(parser);
2789 parser_enterblock(parser);
2796 /* parse into the expression */
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "expected 'for' initializer after opening paren");
2803 if (parser->tok == TOKEN_IDENT)
2804 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2806 if (typevar || parser->tok == TOKEN_TYPENAME) {
2808 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2809 if (parsewarning(parser, WARN_EXTENSIONS,
2810 "current standard does not allow variable declarations in for-loop initializers"))
2814 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2817 else if (parser->tok != ';')
2819 initexpr = parse_expression_leave(parser, false, false, false);
2824 /* move on to condition */
2825 if (parser->tok != ';') {
2826 parseerror(parser, "expected semicolon after for-loop initializer");
2829 if (!parser_next(parser)) {
2830 parseerror(parser, "expected for-loop condition");
2834 /* parse the condition */
2835 if (parser->tok != ';') {
2836 cond = parse_expression_leave(parser, false, true, false);
2841 /* move on to incrementor */
2842 if (parser->tok != ';') {
2843 parseerror(parser, "expected semicolon after for-loop initializer");
2846 if (!parser_next(parser)) {
2847 parseerror(parser, "expected for-loop condition");
2851 /* parse the incrementor */
2852 if (parser->tok != ')') {
2853 lex_ctx condctx = parser_ctx(parser);
2854 increment = parse_expression_leave(parser, false, false, false);
2857 if (!ast_side_effects(increment)) {
2858 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2864 if (parser->tok != ')') {
2865 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2868 /* parse into the 'then' branch */
2869 if (!parser_next(parser)) {
2870 parseerror(parser, "expected for-loop body");
2873 if (!parse_statement_or_block(parser, &ontrue))
2877 cond = process_condition(parser, cond, &ifnot);
2881 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2882 *out = (ast_expression*)aloop;
2884 if (!parser_leaveblock(parser)) {
2890 if (initexpr) ast_unref(initexpr);
2891 if (cond) ast_unref(cond);
2892 if (increment) ast_unref(increment);
2893 (void)!parser_leaveblock(parser);
2897 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2899 ast_expression *exp = NULL;
2900 ast_expression *var = NULL;
2901 ast_return *ret = NULL;
2902 ast_value *retval = parser->function->return_value;
2903 ast_value *expected = parser->function->vtype;
2905 lex_ctx ctx = parser_ctx(parser);
2907 (void)block; /* not touching */
2909 if (!parser_next(parser)) {
2910 parseerror(parser, "expected return expression");
2914 /* return assignments */
2915 if (parser->tok == '=') {
2916 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2917 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2921 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2923 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2924 parseerror(parser, "invalid return type: `%s'", ty1);
2928 if (!parser_next(parser)) {
2929 parseerror(parser, "expected return assignment expression");
2933 if (!(exp = parse_expression_leave(parser, false, false, false)))
2936 /* prepare the return value */
2938 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2939 ast_type_adopt(retval, expected->expression.next);
2940 parser->function->return_value = retval;
2943 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2944 char ty1[1024], ty2[1024];
2945 ast_type_to_string(exp, ty1, sizeof(ty1));
2946 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2947 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2950 /* store to 'return' local variable */
2951 var = (ast_expression*)ast_store_new(
2953 type_store_instr[expected->expression.next->vtype],
2954 (ast_expression*)retval, exp);
2961 if (parser->tok != ';')
2962 parseerror(parser, "missing semicolon after return assignment");
2963 else if (!parser_next(parser))
2964 parseerror(parser, "parse error after return assignment");
2970 if (parser->tok != ';') {
2971 exp = parse_expression(parser, false, false);
2975 if (exp->vtype != TYPE_NIL &&
2976 exp->vtype != ((ast_expression*)expected)->next->vtype)
2978 parseerror(parser, "return with invalid expression");
2981 ret = ast_return_new(ctx, exp);
2987 if (!parser_next(parser))
2988 parseerror(parser, "parse error");
2990 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2992 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2994 ret = ast_return_new(ctx, (ast_expression*)retval);
2996 *out = (ast_expression*)ret;
3000 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3003 unsigned int levels = 0;
3004 lex_ctx ctx = parser_ctx(parser);
3005 const char **loops = (is_continue ? parser->continues : parser->breaks);
3007 (void)block; /* not touching */
3008 if (!parser_next(parser)) {
3009 parseerror(parser, "expected semicolon or loop label");
3013 if (!vec_size(loops)) {
3015 parseerror(parser, "`continue` can only be used inside loops");
3017 parseerror(parser, "`break` can only be used inside loops or switches");
3020 if (parser->tok == TOKEN_IDENT) {
3021 if (!OPTS_FLAG(LOOP_LABELS))
3022 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3023 i = vec_size(loops);
3025 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3028 parseerror(parser, "no such loop to %s: `%s`",
3029 (is_continue ? "continue" : "break out of"),
3030 parser_tokval(parser));
3035 if (!parser_next(parser)) {
3036 parseerror(parser, "expected semicolon");
3041 if (parser->tok != ';') {
3042 parseerror(parser, "expected semicolon");
3046 if (!parser_next(parser))
3047 parseerror(parser, "parse error");
3049 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3053 /* returns true when it was a variable qualifier, false otherwise!
3054 * on error, cvq is set to CV_WRONG
3056 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3058 bool had_const = false;
3059 bool had_var = false;
3060 bool had_noref = false;
3061 bool had_attrib = false;
3062 bool had_static = false;
3067 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3069 /* parse an attribute */
3070 if (!parser_next(parser)) {
3071 parseerror(parser, "expected attribute after `[[`");
3075 if (!strcmp(parser_tokval(parser), "noreturn")) {
3076 flags |= AST_FLAG_NORETURN;
3077 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3078 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3083 else if (!strcmp(parser_tokval(parser), "noref")) {
3085 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3086 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3091 else if (!strcmp(parser_tokval(parser), "inline")) {
3092 flags |= AST_FLAG_INLINE;
3093 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3094 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3099 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3100 flags |= AST_FLAG_ALIAS;
3103 if (!parser_next(parser)) {
3104 parseerror(parser, "parse error in attribute");
3108 if (parser->tok == '(') {
3109 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3110 parseerror(parser, "`alias` attribute missing parameter");
3114 *message = util_strdup(parser_tokval(parser));
3116 if (!parser_next(parser)) {
3117 parseerror(parser, "parse error in attribute");
3121 if (parser->tok != ')') {
3122 parseerror(parser, "`alias` attribute expected `)` after parameter");
3126 if (!parser_next(parser)) {
3127 parseerror(parser, "parse error in attribute");
3132 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3133 parseerror(parser, "`alias` attribute expected `]]`");
3137 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3138 flags |= AST_FLAG_DEPRECATED;
3141 if (!parser_next(parser)) {
3142 parseerror(parser, "parse error in attribute");
3146 if (parser->tok == '(') {
3147 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3148 parseerror(parser, "`deprecated` attribute missing parameter");
3152 *message = util_strdup(parser_tokval(parser));
3154 if (!parser_next(parser)) {
3155 parseerror(parser, "parse error in attribute");
3159 if(parser->tok != ')') {
3160 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3164 if (!parser_next(parser)) {
3165 parseerror(parser, "parse error in attribute");
3170 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3171 parseerror(parser, "`deprecated` attribute expected `]]`");
3174 if (*message) mem_d(*message);
3182 /* Skip tokens until we hit a ]] */
3183 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3184 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3185 if (!parser_next(parser)) {
3186 parseerror(parser, "error inside attribute");
3193 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3195 else if (!strcmp(parser_tokval(parser), "const"))
3197 else if (!strcmp(parser_tokval(parser), "var"))
3199 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3201 else if (!strcmp(parser_tokval(parser), "noref"))
3203 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3208 if (!parser_next(parser))
3218 *is_static = had_static;
3222 parseerror(parser, "parse error after variable qualifier");
3227 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3228 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3233 /* skip the 'while' and get the body */
3234 if (!parser_next(parser)) {
3235 if (OPTS_FLAG(LOOP_LABELS))
3236 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3238 parseerror(parser, "expected 'switch' operand in parenthesis");
3242 if (parser->tok == ':') {
3243 if (!OPTS_FLAG(LOOP_LABELS))
3244 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3245 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3246 parseerror(parser, "expected loop label");
3249 label = util_strdup(parser_tokval(parser));
3250 if (!parser_next(parser)) {
3252 parseerror(parser, "expected 'switch' operand in parenthesis");
3257 if (parser->tok != '(') {
3258 parseerror(parser, "expected 'switch' operand in parenthesis");
3262 vec_push(parser->breaks, label);
3264 rv = parse_switch_go(parser, block, out);
3267 if (vec_last(parser->breaks) != label) {
3268 parseerror(parser, "internal error: label stack corrupted");
3274 vec_pop(parser->breaks);
3279 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3281 ast_expression *operand;
3284 ast_switch *switchnode;
3285 ast_switch_case swcase;
3288 bool noref, is_static;
3289 uint32_t qflags = 0;
3291 lex_ctx ctx = parser_ctx(parser);
3293 (void)block; /* not touching */
3296 /* parse into the expression */
3297 if (!parser_next(parser)) {
3298 parseerror(parser, "expected switch operand");
3301 /* parse the operand */
3302 operand = parse_expression_leave(parser, false, false, false);
3306 switchnode = ast_switch_new(ctx, operand);
3309 if (parser->tok != ')') {
3310 ast_delete(switchnode);
3311 parseerror(parser, "expected closing paren after 'switch' operand");
3315 /* parse over the opening paren */
3316 if (!parser_next(parser) || parser->tok != '{') {
3317 ast_delete(switchnode);
3318 parseerror(parser, "expected list of cases");
3322 if (!parser_next(parser)) {
3323 ast_delete(switchnode);
3324 parseerror(parser, "expected 'case' or 'default'");
3328 /* new block; allow some variables to be declared here */
3329 parser_enterblock(parser);
3332 if (parser->tok == TOKEN_IDENT)
3333 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3334 if (typevar || parser->tok == TOKEN_TYPENAME) {
3335 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3336 ast_delete(switchnode);
3341 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3343 if (cvq == CV_WRONG) {
3344 ast_delete(switchnode);
3347 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3348 ast_delete(switchnode);
3357 while (parser->tok != '}') {
3358 ast_block *caseblock;
3360 if (!strcmp(parser_tokval(parser), "case")) {
3361 if (!parser_next(parser)) {
3362 ast_delete(switchnode);
3363 parseerror(parser, "expected expression for case");
3366 swcase.value = parse_expression_leave(parser, false, false, false);
3367 if (!swcase.value) {
3368 ast_delete(switchnode);
3369 parseerror(parser, "expected expression for case");
3372 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3373 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3374 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3380 else if (!strcmp(parser_tokval(parser), "default")) {
3381 swcase.value = NULL;
3382 if (!parser_next(parser)) {
3383 ast_delete(switchnode);
3384 parseerror(parser, "expected colon");
3389 ast_delete(switchnode);
3390 parseerror(parser, "expected 'case' or 'default'");
3394 /* Now the colon and body */
3395 if (parser->tok != ':') {
3396 if (swcase.value) ast_unref(swcase.value);
3397 ast_delete(switchnode);
3398 parseerror(parser, "expected colon");
3402 if (!parser_next(parser)) {
3403 if (swcase.value) ast_unref(swcase.value);
3404 ast_delete(switchnode);
3405 parseerror(parser, "expected statements or case");
3408 caseblock = ast_block_new(parser_ctx(parser));
3410 if (swcase.value) ast_unref(swcase.value);
3411 ast_delete(switchnode);
3414 swcase.code = (ast_expression*)caseblock;
3415 vec_push(switchnode->cases, swcase);
3417 ast_expression *expr;
3418 if (parser->tok == '}')
3420 if (parser->tok == TOKEN_KEYWORD) {
3421 if (!strcmp(parser_tokval(parser), "case") ||
3422 !strcmp(parser_tokval(parser), "default"))
3427 if (!parse_statement(parser, caseblock, &expr, true)) {
3428 ast_delete(switchnode);
3433 if (!ast_block_add_expr(caseblock, expr)) {
3434 ast_delete(switchnode);
3440 parser_leaveblock(parser);
3443 if (parser->tok != '}') {
3444 ast_delete(switchnode);
3445 parseerror(parser, "expected closing paren of case list");
3448 if (!parser_next(parser)) {
3449 ast_delete(switchnode);
3450 parseerror(parser, "parse error after switch");
3453 *out = (ast_expression*)switchnode;
3457 /* parse computed goto sides */
3458 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3459 ast_expression *on_true;
3460 ast_expression *on_false;
3461 ast_expression *cond;
3466 if (ast_istype(*side, ast_ternary)) {
3467 ast_ternary *tern = (ast_ternary*)*side;
3468 on_true = parse_goto_computed(parser, &tern->on_true);
3469 on_false = parse_goto_computed(parser, &tern->on_false);
3471 if (!on_true || !on_false) {
3472 parseerror(parser, "expected label or expression in ternary");
3473 if (on_true) ast_unref(on_true);
3474 if (on_false) ast_unref(on_false);
3482 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3483 } else if (ast_istype(*side, ast_label)) {
3484 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3485 ast_goto_set_label(gt, ((ast_label*)*side));
3487 return (ast_expression*)gt;
3492 static bool parse_goto(parser_t *parser, ast_expression **out)
3494 ast_goto *gt = NULL;
3495 ast_expression *lbl;
3497 if (!parser_next(parser))
3500 if (parser->tok != TOKEN_IDENT) {
3501 ast_expression *expression;
3503 /* could be an expression i.e computed goto :-) */
3504 if (parser->tok != '(') {
3505 parseerror(parser, "expected label name after `goto`");
3509 /* failed to parse expression for goto */
3510 if (!(expression = parse_expression(parser, false, true)) ||
3511 !(*out = parse_goto_computed(parser, &expression))) {
3512 parseerror(parser, "invalid goto expression");
3513 ast_unref(expression);
3520 /* not computed goto */
3521 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3522 lbl = parser_find_label(parser, gt->name);
3524 if (!ast_istype(lbl, ast_label)) {
3525 parseerror(parser, "internal error: label is not an ast_label");
3529 ast_goto_set_label(gt, (ast_label*)lbl);
3532 vec_push(parser->gotos, gt);
3534 if (!parser_next(parser) || parser->tok != ';') {
3535 parseerror(parser, "semicolon expected after goto label");
3538 if (!parser_next(parser)) {
3539 parseerror(parser, "parse error after goto");
3543 *out = (ast_expression*)gt;
3547 static bool parse_skipwhite(parser_t *parser)
3550 if (!parser_next(parser))
3552 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3553 return parser->tok < TOKEN_ERROR;
3556 static bool parse_eol(parser_t *parser)
3558 if (!parse_skipwhite(parser))
3560 return parser->tok == TOKEN_EOL;
3563 static bool parse_pragma_do(parser_t *parser)
3565 if (!parser_next(parser) ||
3566 parser->tok != TOKEN_IDENT ||
3567 strcmp(parser_tokval(parser), "pragma"))
3569 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3572 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3573 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3577 if (!strcmp(parser_tokval(parser), "noref")) {
3578 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3579 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3582 parser->noref = !!parser_token(parser)->constval.i;
3583 if (!parse_eol(parser)) {
3584 parseerror(parser, "parse error after `noref` pragma");
3590 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3597 static bool parse_pragma(parser_t *parser)
3600 parser->lex->flags.preprocessing = true;
3601 parser->lex->flags.mergelines = true;
3602 rv = parse_pragma_do(parser);
3603 if (parser->tok != TOKEN_EOL) {
3604 parseerror(parser, "junk after pragma");
3607 parser->lex->flags.preprocessing = false;
3608 parser->lex->flags.mergelines = false;
3609 if (!parser_next(parser)) {
3610 parseerror(parser, "parse error after pragma");
3616 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3618 bool noref, is_static;
3620 uint32_t qflags = 0;
3621 ast_value *typevar = NULL;
3622 char *vstring = NULL;
3626 if (parser->tok == TOKEN_IDENT)
3627 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3629 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3631 /* local variable */
3633 parseerror(parser, "cannot declare a variable from here");
3636 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3637 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3640 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3644 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3646 if (cvq == CV_WRONG)
3648 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3650 else if (parser->tok == TOKEN_KEYWORD)
3652 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3657 if (!parser_next(parser)) {
3658 parseerror(parser, "parse error after __builtin_debug_printtype");
3662 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3664 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3665 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3666 if (!parser_next(parser)) {
3667 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3673 if (!parse_statement(parser, block, out, allow_cases))
3676 con_out("__builtin_debug_printtype: got no output node\n");
3679 ast_type_to_string(*out, ty, sizeof(ty));
3680 con_out("__builtin_debug_printtype: `%s`\n", ty);
3685 else if (!strcmp(parser_tokval(parser), "return"))
3687 return parse_return(parser, block, out);
3689 else if (!strcmp(parser_tokval(parser), "if"))
3691 return parse_if(parser, block, out);
3693 else if (!strcmp(parser_tokval(parser), "while"))
3695 return parse_while(parser, block, out);
3697 else if (!strcmp(parser_tokval(parser), "do"))
3699 return parse_dowhile(parser, block, out);
3701 else if (!strcmp(parser_tokval(parser), "for"))
3703 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3704 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3707 return parse_for(parser, block, out);
3709 else if (!strcmp(parser_tokval(parser), "break"))
3711 return parse_break_continue(parser, block, out, false);
3713 else if (!strcmp(parser_tokval(parser), "continue"))
3715 return parse_break_continue(parser, block, out, true);
3717 else if (!strcmp(parser_tokval(parser), "switch"))
3719 return parse_switch(parser, block, out);
3721 else if (!strcmp(parser_tokval(parser), "case") ||
3722 !strcmp(parser_tokval(parser), "default"))
3725 parseerror(parser, "unexpected 'case' label");
3730 else if (!strcmp(parser_tokval(parser), "goto"))
3732 return parse_goto(parser, out);
3734 else if (!strcmp(parser_tokval(parser), "typedef"))
3736 if (!parser_next(parser)) {
3737 parseerror(parser, "expected type definition after 'typedef'");
3740 return parse_typedef(parser);
3742 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3745 else if (parser->tok == '{')
3748 inner = parse_block(parser);
3751 *out = (ast_expression*)inner;
3754 else if (parser->tok == ':')
3758 if (!parser_next(parser)) {
3759 parseerror(parser, "expected label name");
3762 if (parser->tok != TOKEN_IDENT) {
3763 parseerror(parser, "label must be an identifier");
3766 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3768 if (!label->undefined) {
3769 parseerror(parser, "label `%s` already defined", label->name);
3772 label->undefined = false;
3775 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3776 vec_push(parser->labels, label);
3778 *out = (ast_expression*)label;
3779 if (!parser_next(parser)) {
3780 parseerror(parser, "parse error after label");
3783 for (i = 0; i < vec_size(parser->gotos); ++i) {
3784 if (!strcmp(parser->gotos[i]->name, label->name)) {
3785 ast_goto_set_label(parser->gotos[i], label);
3786 vec_remove(parser->gotos, i, 1);
3792 else if (parser->tok == ';')
3794 if (!parser_next(parser)) {
3795 parseerror(parser, "parse error after empty statement");
3802 lex_ctx ctx = parser_ctx(parser);
3803 ast_expression *exp = parse_expression(parser, false, false);
3807 if (!ast_side_effects(exp)) {
3808 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3815 static bool parse_enum(parser_t *parser)
3818 bool reverse = false;
3820 ast_value **values = NULL;
3821 ast_value *var = NULL;
3824 ast_expression *old;
3826 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3827 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3831 /* enumeration attributes (can add more later) */
3832 if (parser->tok == ':') {
3833 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3834 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3839 if (!strcmp(parser_tokval(parser), "flag")) {
3843 else if (!strcmp(parser_tokval(parser), "reverse")) {
3847 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3851 if (!parser_next(parser) || parser->tok != '{') {
3852 parseerror(parser, "expected `{` after enum attribute ");
3858 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3859 if (parser->tok == '}') {
3860 /* allow an empty enum */
3863 parseerror(parser, "expected identifier or `}`");
3867 old = parser_find_field(parser, parser_tokval(parser));
3869 old = parser_find_global(parser, parser_tokval(parser));
3871 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3872 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3876 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3877 vec_push(values, var);
3878 var->cvq = CV_CONST;
3879 var->hasvalue = true;
3881 /* for flagged enumerations increment in POTs of TWO */
3882 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3883 parser_addglobal(parser, var->name, (ast_expression*)var);
3885 if (!parser_next(parser)) {
3886 parseerror(parser, "expected `=`, `}` or comma after identifier");
3890 if (parser->tok == ',')
3892 if (parser->tok == '}')
3894 if (parser->tok != '=') {
3895 parseerror(parser, "expected `=`, `}` or comma after identifier");
3899 if (!parser_next(parser)) {
3900 parseerror(parser, "expected expression after `=`");
3904 /* We got a value! */
3905 old = parse_expression_leave(parser, true, false, false);
3906 asvalue = (ast_value*)old;
3907 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3908 compile_error(ast_ctx(var), "constant value or expression expected");
3911 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3913 if (parser->tok == '}')
3915 if (parser->tok != ',') {
3916 parseerror(parser, "expected `}` or comma after expression");
3921 /* patch them all (for reversed attribute) */
3924 for (i = 0; i < vec_size(values); i++)
3925 values[i]->constval.vfloat = vec_size(values) - i - 1;
3928 if (parser->tok != '}') {
3929 parseerror(parser, "internal error: breaking without `}`");
3933 if (!parser_next(parser) || parser->tok != ';') {
3934 parseerror(parser, "expected semicolon after enumeration");
3938 if (!parser_next(parser)) {
3939 parseerror(parser, "parse error after enumeration");
3951 static bool parse_block_into(parser_t *parser, ast_block *block)
3955 parser_enterblock(parser);
3957 if (!parser_next(parser)) { /* skip the '{' */
3958 parseerror(parser, "expected function body");
3962 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3964 ast_expression *expr = NULL;
3965 if (parser->tok == '}')
3968 if (!parse_statement(parser, block, &expr, false)) {
3969 /* parseerror(parser, "parse error"); */
3975 if (!ast_block_add_expr(block, expr)) {
3982 if (parser->tok != '}') {
3985 (void)parser_next(parser);
3989 if (!parser_leaveblock(parser))
3991 return retval && !!block;
3994 static ast_block* parse_block(parser_t *parser)
3997 block = ast_block_new(parser_ctx(parser));
4000 if (!parse_block_into(parser, block)) {
4001 ast_block_delete(block);
4007 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4009 if (parser->tok == '{') {
4010 *out = (ast_expression*)parse_block(parser);
4013 return parse_statement(parser, NULL, out, false);
4016 static bool create_vector_members(ast_value *var, ast_member **me)
4019 size_t len = strlen(var->name);
4021 for (i = 0; i < 3; ++i) {
4022 char *name = (char*)mem_a(len+3);
4023 memcpy(name, var->name, len);
4025 name[len+1] = 'x'+i;
4027 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4036 do { ast_member_delete(me[--i]); } while(i);
4040 static bool parse_function_body(parser_t *parser, ast_value *var)
4042 ast_block *block = NULL;
4047 ast_expression *framenum = NULL;
4048 ast_expression *nextthink = NULL;
4049 /* None of the following have to be deleted */
4050 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4051 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4052 bool has_frame_think;
4056 has_frame_think = false;
4057 old = parser->function;
4059 if (var->expression.flags & AST_FLAG_ALIAS) {
4060 parseerror(parser, "function aliases cannot have bodies");
4064 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4065 parseerror(parser, "gotos/labels leaking");
4069 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4070 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4071 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4077 if (parser->tok == '[') {
4078 /* got a frame definition: [ framenum, nextthink ]
4079 * this translates to:
4080 * self.frame = framenum;
4081 * self.nextthink = time + 0.1;
4082 * self.think = nextthink;
4086 fld_think = parser_find_field(parser, "think");
4087 fld_nextthink = parser_find_field(parser, "nextthink");
4088 fld_frame = parser_find_field(parser, "frame");
4089 if (!fld_think || !fld_nextthink || !fld_frame) {
4090 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4091 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4094 gbl_time = parser_find_global(parser, "time");
4095 gbl_self = parser_find_global(parser, "self");
4096 if (!gbl_time || !gbl_self) {
4097 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4098 parseerror(parser, "please declare the following globals: `time`, `self`");
4102 if (!parser_next(parser))
4105 framenum = parse_expression_leave(parser, true, false, false);
4107 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4110 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4111 ast_unref(framenum);
4112 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4116 if (parser->tok != ',') {
4117 ast_unref(framenum);
4118 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4119 parseerror(parser, "Got a %i\n", parser->tok);
4123 if (!parser_next(parser)) {
4124 ast_unref(framenum);
4128 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4130 /* qc allows the use of not-yet-declared functions here
4131 * - this automatically creates a prototype */
4132 ast_value *thinkfunc;
4133 ast_expression *functype = fld_think->next;
4135 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4136 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4137 ast_unref(framenum);
4138 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4141 ast_type_adopt(thinkfunc, functype);
4143 if (!parser_next(parser)) {
4144 ast_unref(framenum);
4145 ast_delete(thinkfunc);
4149 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4151 nextthink = (ast_expression*)thinkfunc;
4154 nextthink = parse_expression_leave(parser, true, false, false);
4156 ast_unref(framenum);
4157 parseerror(parser, "expected a think-function in [frame,think] notation");
4162 if (!ast_istype(nextthink, ast_value)) {
4163 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4167 if (retval && parser->tok != ']') {
4168 parseerror(parser, "expected closing `]` for [frame,think] notation");
4172 if (retval && !parser_next(parser)) {
4176 if (retval && parser->tok != '{') {
4177 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4182 ast_unref(nextthink);
4183 ast_unref(framenum);
4187 has_frame_think = true;
4190 block = ast_block_new(parser_ctx(parser));
4192 parseerror(parser, "failed to allocate block");
4193 if (has_frame_think) {
4194 ast_unref(nextthink);
4195 ast_unref(framenum);
4200 if (has_frame_think) {
4202 ast_expression *self_frame;
4203 ast_expression *self_nextthink;
4204 ast_expression *self_think;
4205 ast_expression *time_plus_1;
4206 ast_store *store_frame;
4207 ast_store *store_nextthink;
4208 ast_store *store_think;
4210 ctx = parser_ctx(parser);
4211 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4212 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4213 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4215 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4216 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4218 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4219 if (self_frame) ast_delete(self_frame);
4220 if (self_nextthink) ast_delete(self_nextthink);
4221 if (self_think) ast_delete(self_think);
4222 if (time_plus_1) ast_delete(time_plus_1);
4228 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4229 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4230 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4233 ast_delete(self_frame);
4236 if (!store_nextthink) {
4237 ast_delete(self_nextthink);
4241 ast_delete(self_think);
4245 if (store_frame) ast_delete(store_frame);
4246 if (store_nextthink) ast_delete(store_nextthink);
4247 if (store_think) ast_delete(store_think);
4250 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4251 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4252 !ast_block_add_expr(block, (ast_expression*)store_think))
4259 parseerror(parser, "failed to generate code for [frame,think]");
4260 ast_unref(nextthink);
4261 ast_unref(framenum);
4267 if (var->hasvalue) {
4268 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4269 ast_block_delete(block);
4273 func = ast_function_new(ast_ctx(var), var->name, var);
4275 parseerror(parser, "failed to allocate function for `%s`", var->name);
4276 ast_block_delete(block);
4279 vec_push(parser->functions, func);
4281 parser_enterblock(parser);
4283 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4285 ast_value *param = var->expression.params[parami];
4288 if (param->expression.vtype != TYPE_VECTOR &&
4289 (param->expression.vtype != TYPE_FIELD ||
4290 param->expression.next->vtype != TYPE_VECTOR))
4295 if (!create_vector_members(param, me)) {
4296 ast_block_delete(block);
4300 for (e = 0; e < 3; ++e) {
4301 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4302 ast_block_collect(block, (ast_expression*)me[e]);
4306 if (var->argcounter) {
4307 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4308 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4312 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4314 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4315 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4316 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4317 varargs->expression.count = 0;
4318 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4319 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4320 ast_delete(varargs);
4321 ast_block_delete(block);
4324 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4325 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4326 ast_delete(varargs);
4327 ast_block_delete(block);
4330 func->varargs = varargs;
4332 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4335 parser->function = func;
4336 if (!parse_block_into(parser, block)) {
4337 ast_block_delete(block);
4341 vec_push(func->blocks, block);
4344 parser->function = old;
4345 if (!parser_leaveblock(parser))
4347 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4348 parseerror(parser, "internal error: local scopes left");
4352 if (parser->tok == ';')
4353 return parser_next(parser);
4354 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4355 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4359 (void)!parser_leaveblock(parser);
4360 vec_pop(parser->functions);
4361 ast_function_delete(func);
4362 var->constval.vfunc = NULL;
4365 parser->function = old;
4369 static ast_expression *array_accessor_split(
4374 ast_expression *left,
4375 ast_expression *right
4381 lex_ctx ctx = ast_ctx(array);
4383 if (!left || !right) {
4384 if (left) ast_delete(left);
4385 if (right) ast_delete(right);
4389 cmp = ast_binary_new(ctx, INSTR_LT,
4390 (ast_expression*)index,
4391 (ast_expression*)parser_const_float(parser, middle));
4395 parseerror(parser, "internal error: failed to create comparison for array setter");
4399 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4401 ast_delete(cmp); /* will delete left and right */
4402 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4406 return (ast_expression*)ifthen;
4409 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4411 lex_ctx ctx = ast_ctx(array);
4413 if (from+1 == afterend) {
4414 /* set this value */
4417 ast_array_index *subscript;
4419 int assignop = type_store_instr[value->expression.vtype];
4421 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4422 assignop = INSTR_STORE_V;
4424 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4428 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4430 ast_delete(subscript);
4434 block = ast_block_new(ctx);
4440 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4445 ret = ast_return_new(ctx, NULL);
4451 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4456 return (ast_expression*)block;
4458 ast_expression *left, *right;
4459 size_t diff = afterend - from;
4460 size_t middle = from + diff/2;
4461 left = array_setter_node(parser, array, index, value, from, middle);
4462 right = array_setter_node(parser, array, index, value, middle, afterend);
4463 return array_accessor_split(parser, array, index, middle, left, right);
4467 static ast_expression *array_field_setter_node(
4476 lex_ctx ctx = ast_ctx(array);
4478 if (from+1 == afterend) {
4479 /* set this value */
4482 ast_entfield *entfield;
4483 ast_array_index *subscript;
4485 int assignop = type_storep_instr[value->expression.vtype];
4487 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4488 assignop = INSTR_STOREP_V;
4490 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4494 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4495 subscript->expression.vtype = TYPE_FIELD;
4497 entfield = ast_entfield_new_force(ctx,
4498 (ast_expression*)entity,
4499 (ast_expression*)subscript,
4500 (ast_expression*)subscript);
4502 ast_delete(subscript);
4506 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4508 ast_delete(entfield);
4512 block = ast_block_new(ctx);
4518 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4523 ret = ast_return_new(ctx, NULL);
4529 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4534 return (ast_expression*)block;
4536 ast_expression *left, *right;
4537 size_t diff = afterend - from;
4538 size_t middle = from + diff/2;
4539 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4540 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4541 return array_accessor_split(parser, array, index, middle, left, right);
4545 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4547 lex_ctx ctx = ast_ctx(array);
4549 if (from+1 == afterend) {
4551 ast_array_index *subscript;
4553 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4557 ret = ast_return_new(ctx, (ast_expression*)subscript);
4559 ast_delete(subscript);
4563 return (ast_expression*)ret;
4565 ast_expression *left, *right;
4566 size_t diff = afterend - from;
4567 size_t middle = from + diff/2;
4568 left = array_getter_node(parser, array, index, from, middle);
4569 right = array_getter_node(parser, array, index, middle, afterend);
4570 return array_accessor_split(parser, array, index, middle, left, right);
4574 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4576 ast_function *func = NULL;
4577 ast_value *fval = NULL;
4578 ast_block *body = NULL;
4580 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4582 parseerror(parser, "failed to create accessor function value");
4586 func = ast_function_new(ast_ctx(array), funcname, fval);
4589 parseerror(parser, "failed to create accessor function node");
4593 body = ast_block_new(ast_ctx(array));
4595 parseerror(parser, "failed to create block for array accessor");
4601 vec_push(func->blocks, body);
4604 vec_push(parser->accessors, fval);
4609 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4611 ast_value *index = NULL;
4612 ast_value *value = NULL;
4616 if (!ast_istype(array->expression.next, ast_value)) {
4617 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4621 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4623 func = fval->constval.vfunc;
4624 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4626 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4627 value = ast_value_copy((ast_value*)array->expression.next);
4629 if (!index || !value) {
4630 parseerror(parser, "failed to create locals for array accessor");
4633 (void)!ast_value_set_name(value, "value"); /* not important */
4634 vec_push(fval->expression.params, index);
4635 vec_push(fval->expression.params, value);
4637 array->setter = fval;
4640 if (index) ast_delete(index);
4641 if (value) ast_delete(value);
4647 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4649 ast_expression *root = NULL;
4650 root = array_setter_node(parser, array,
4651 array->setter->expression.params[0],
4652 array->setter->expression.params[1],
4653 0, array->expression.count);
4655 parseerror(parser, "failed to build accessor search tree");
4658 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4665 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4667 if (!parser_create_array_setter_proto(parser, array, funcname))
4669 return parser_create_array_setter_impl(parser, array);
4672 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4674 ast_expression *root = NULL;
4675 ast_value *entity = NULL;
4676 ast_value *index = NULL;
4677 ast_value *value = NULL;
4681 if (!ast_istype(array->expression.next, ast_value)) {
4682 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4686 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4688 func = fval->constval.vfunc;
4689 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4691 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4692 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4693 value = ast_value_copy((ast_value*)array->expression.next);
4694 if (!entity || !index || !value) {
4695 parseerror(parser, "failed to create locals for array accessor");
4698 (void)!ast_value_set_name(value, "value"); /* not important */
4699 vec_push(fval->expression.params, entity);
4700 vec_push(fval->expression.params, index);
4701 vec_push(fval->expression.params, value);
4703 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4705 parseerror(parser, "failed to build accessor search tree");
4709 array->setter = fval;
4710 return ast_block_add_expr(func->blocks[0], root);
4712 if (entity) ast_delete(entity);
4713 if (index) ast_delete(index);
4714 if (value) ast_delete(value);
4715 if (root) ast_delete(root);
4721 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4723 ast_value *index = NULL;
4727 /* NOTE: checking array->expression.next rather than elemtype since
4728 * for fields elemtype is a temporary fieldtype.
4730 if (!ast_istype(array->expression.next, ast_value)) {
4731 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4735 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4737 func = fval->constval.vfunc;
4738 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4740 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4743 parseerror(parser, "failed to create locals for array accessor");
4746 vec_push(fval->expression.params, index);
4748 array->getter = fval;
4751 if (index) ast_delete(index);
4757 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4759 ast_expression *root = NULL;
4761 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4763 parseerror(parser, "failed to build accessor search tree");
4766 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4773 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4775 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4777 return parser_create_array_getter_impl(parser, array);
4780 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4781 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4789 bool variadic = false;
4790 ast_value *varparam = NULL;
4791 char *argcounter = NULL;
4793 ctx = parser_ctx(parser);
4795 /* for the sake of less code we parse-in in this function */
4796 if (!parser_next(parser)) {
4798 parseerror(parser, "expected parameter list");
4804 /* parse variables until we hit a closing paren */
4805 while (parser->tok != ')') {
4807 /* there must be commas between them */
4808 if (parser->tok != ',') {
4809 parseerror(parser, "expected comma or end of parameter list");
4812 if (!parser_next(parser)) {
4813 parseerror(parser, "expected parameter");
4819 if (parser->tok == TOKEN_DOTS) {
4820 /* '...' indicates a varargs function */
4822 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4823 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4826 if (parser->tok == TOKEN_IDENT) {
4827 argcounter = util_strdup(parser_tokval(parser));
4828 if (!parser_next(parser) || parser->tok != ')') {
4829 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4836 /* for anything else just parse a typename */
4837 param = parse_typename(parser, NULL, NULL);
4840 vec_push(params, param);
4841 if (param->expression.vtype >= TYPE_VARIANT) {
4842 char tname[1024]; /* typename is reserved in C++ */
4843 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4844 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4847 /* type-restricted varargs */
4848 if (parser->tok == TOKEN_DOTS) {
4850 varparam = vec_last(params);
4852 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4853 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4856 if (parser->tok == TOKEN_IDENT) {
4857 argcounter = util_strdup(parser_tokval(parser));
4858 if (!parser_next(parser) || parser->tok != ')') {
4859 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4867 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4871 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4872 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4875 if (!parser_next(parser)) {
4876 parseerror(parser, "parse error after typename");
4880 /* now turn 'var' into a function type */
4881 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4882 fval->expression.next = (ast_expression*)var;
4884 fval->expression.flags |= AST_FLAG_VARIADIC;
4887 var->expression.params = params;
4888 var->expression.varparam = (ast_expression*)varparam;
4889 var->argcounter = argcounter;
4898 ast_delete(varparam);
4900 for (i = 0; i < vec_size(params); ++i)
4901 ast_delete(params[i]);
4906 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4908 ast_expression *cexp;
4909 ast_value *cval, *tmp;
4912 ctx = parser_ctx(parser);
4914 if (!parser_next(parser)) {
4916 parseerror(parser, "expected array-size");
4920 if (parser->tok != ']') {
4921 cexp = parse_expression_leave(parser, true, false, false);
4923 if (!cexp || !ast_istype(cexp, ast_value)) {
4927 parseerror(parser, "expected array-size as constant positive integer");
4930 cval = (ast_value*)cexp;
4937 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4938 tmp->expression.next = (ast_expression*)var;
4942 if (cval->expression.vtype == TYPE_INTEGER)
4943 tmp->expression.count = cval->constval.vint;
4944 else if (cval->expression.vtype == TYPE_FLOAT)
4945 tmp->expression.count = cval->constval.vfloat;
4949 parseerror(parser, "array-size must be a positive integer constant");
4955 var->expression.count = -1;
4956 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4959 if (parser->tok != ']') {
4961 parseerror(parser, "expected ']' after array-size");
4964 if (!parser_next(parser)) {
4966 parseerror(parser, "error after parsing array size");
4972 /* Parse a complete typename.
4973 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4974 * but when parsing variables separated by comma
4975 * 'storebase' should point to where the base-type should be kept.
4976 * The base type makes up every bit of type information which comes *before* the
4979 * The following will be parsed in its entirety:
4981 * The 'basetype' in this case is 'void()'
4982 * and if there's a comma after it, say:
4984 * then the type-information 'void()' can be stored in 'storebase'
4986 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4988 ast_value *var, *tmp;
4991 const char *name = NULL;
4992 bool isfield = false;
4993 bool wasarray = false;
4994 size_t morefields = 0;
4996 ctx = parser_ctx(parser);
4998 /* types may start with a dot */
4999 if (parser->tok == '.') {
5001 /* if we parsed a dot we need a typename now */
5002 if (!parser_next(parser)) {
5003 parseerror(parser, "expected typename for field definition");
5007 /* Further dots are handled seperately because they won't be part of the
5010 while (parser->tok == '.') {
5012 if (!parser_next(parser)) {
5013 parseerror(parser, "expected typename for field definition");
5018 if (parser->tok == TOKEN_IDENT)
5019 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5020 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5021 parseerror(parser, "expected typename");
5025 /* generate the basic type value */
5026 if (cached_typedef) {
5027 var = ast_value_copy(cached_typedef);
5028 ast_value_set_name(var, "<type(from_def)>");
5030 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5032 for (; morefields; --morefields) {
5033 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5034 tmp->expression.next = (ast_expression*)var;
5038 /* do not yet turn into a field - remember:
5039 * .void() foo; is a field too
5040 * .void()() foo; is a function
5044 if (!parser_next(parser)) {
5046 parseerror(parser, "parse error after typename");
5050 /* an opening paren now starts the parameter-list of a function
5051 * this is where original-QC has parameter lists.
5052 * We allow a single parameter list here.
5053 * Much like fteqcc we don't allow `float()() x`
5055 if (parser->tok == '(') {
5056 var = parse_parameter_list(parser, var);
5061 /* store the base if requested */
5063 *storebase = ast_value_copy(var);
5065 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5066 tmp->expression.next = (ast_expression*)*storebase;
5071 /* there may be a name now */
5072 if (parser->tok == TOKEN_IDENT) {
5073 name = util_strdup(parser_tokval(parser));
5075 if (!parser_next(parser)) {
5078 parseerror(parser, "error after variable or field declaration");
5083 /* now this may be an array */
5084 if (parser->tok == '[') {
5086 var = parse_arraysize(parser, var);
5088 if (name) mem_d(name);
5093 /* This is the point where we can turn it into a field */
5095 /* turn it into a field if desired */
5096 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5097 tmp->expression.next = (ast_expression*)var;
5101 /* now there may be function parens again */
5102 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5103 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5104 if (parser->tok == '(' && wasarray)
5105 parseerror(parser, "arrays as part of a return type is not supported");
5106 while (parser->tok == '(') {
5107 var = parse_parameter_list(parser, var);
5109 if (name) mem_d(name);
5114 /* finally name it */
5116 if (!ast_value_set_name(var, name)) {
5119 parseerror(parser, "internal error: failed to set name");
5122 /* free the name, ast_value_set_name duplicates */
5129 static bool parse_typedef(parser_t *parser)
5131 ast_value *typevar, *oldtype;
5132 ast_expression *old;
5134 typevar = parse_typename(parser, NULL, NULL);
5139 if ( (old = parser_find_var(parser, typevar->name)) ) {
5140 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5141 " -> `%s` has been declared here: %s:%i",
5142 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5143 ast_delete(typevar);
5147 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5148 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5149 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5150 ast_delete(typevar);
5154 vec_push(parser->_typedefs, typevar);
5155 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5157 if (parser->tok != ';') {
5158 parseerror(parser, "expected semicolon after typedef");
5161 if (!parser_next(parser)) {
5162 parseerror(parser, "parse error after typedef");
5169 static const char *cvq_to_str(int cvq) {
5171 case CV_NONE: return "none";
5172 case CV_VAR: return "`var`";
5173 case CV_CONST: return "`const`";
5174 default: return "<INVALID>";
5178 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5181 if (proto->cvq != var->cvq) {
5182 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5183 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5184 parser->tok == '='))
5186 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5187 "`%s` declared with different qualifiers: %s\n"
5188 " -> previous declaration here: %s:%i uses %s",
5189 var->name, cvq_to_str(var->cvq),
5190 ast_ctx(proto).file, ast_ctx(proto).line,
5191 cvq_to_str(proto->cvq));
5194 av = (var ->expression.flags & AST_FLAG_NORETURN);
5195 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5197 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5198 "`%s` declared with different attributes%s\n"
5199 " -> previous declaration here: %s:%i",
5200 var->name, (av ? ": noreturn" : ""),
5201 ast_ctx(proto).file, ast_ctx(proto).line,
5202 (ao ? ": noreturn" : ""));
5207 static bool create_array_accessors(parser_t *parser, ast_value *var)
5210 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5211 if (!parser_create_array_setter(parser, var, name))
5213 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5214 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5219 static bool parse_array(parser_t *parser, ast_value *array)
5222 if (array->initlist) {
5223 parseerror(parser, "array already initialized elsewhere");
5226 if (!parser_next(parser)) {
5227 parseerror(parser, "parse error in array initializer");
5231 while (parser->tok != '}') {
5232 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5235 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5237 parseerror(parser, "initializing element must be a compile time constant");
5240 vec_push(array->initlist, v->constval);
5241 if (v->expression.vtype == TYPE_STRING) {
5242 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5246 if (parser->tok == '}')
5248 if (parser->tok != ',' || !parser_next(parser)) {
5249 parseerror(parser, "expected comma or '}' in element list");
5253 if (!parser_next(parser) || parser->tok != ';') {
5254 parseerror(parser, "expected semicolon after initializer, got %s");
5258 if (!parser_next(parser)) {
5259 parseerror(parser, "parse error after initializer");
5264 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5265 if (array->expression.count != (size_t)-1) {
5266 parseerror(parser, "array `%s' has already been initialized with %u elements",
5267 array->name, (unsigned)array->expression.count);
5269 array->expression.count = vec_size(array->initlist);
5270 if (!create_array_accessors(parser, array))
5276 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)
5280 ast_expression *old;
5284 ast_value *basetype = NULL;
5286 bool isparam = false;
5287 bool isvector = false;
5288 bool cleanvar = true;
5289 bool wasarray = false;
5291 ast_member *me[3] = { NULL, NULL, NULL };
5293 if (!localblock && is_static)
5294 parseerror(parser, "`static` qualifier is not supported in global scope");
5296 /* get the first complete variable */
5297 var = parse_typename(parser, &basetype, cached_typedef);
5300 ast_delete(basetype);
5308 /* Part 0: finish the type */
5309 if (parser->tok == '(') {
5310 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5311 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5312 var = parse_parameter_list(parser, var);
5318 /* we only allow 1-dimensional arrays */
5319 if (parser->tok == '[') {
5321 var = parse_arraysize(parser, var);
5327 if (parser->tok == '(' && wasarray) {
5328 parseerror(parser, "arrays as part of a return type is not supported");
5329 /* we'll still parse the type completely for now */
5331 /* for functions returning functions */
5332 while (parser->tok == '(') {
5333 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5334 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5335 var = parse_parameter_list(parser, var);
5342 var->cvq = qualifier;
5343 var->expression.flags |= qflags;
5346 * store the vstring back to var for alias and
5347 * deprecation messages.
5349 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5350 var->expression.flags & AST_FLAG_ALIAS)
5351 var->desc = vstring;
5354 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5355 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5356 * is then filled with the previous definition and the parameter-names replaced.
5358 if (!strcmp(var->name, "nil")) {
5359 if (OPTS_FLAG(UNTYPED_NIL)) {
5360 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5361 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5363 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5366 /* Deal with end_sys_ vars */
5368 if (!strcmp(var->name, "end_sys_globals")) {
5370 parser->crc_globals = vec_size(parser->globals);
5373 else if (!strcmp(var->name, "end_sys_fields")) {
5375 parser->crc_fields = vec_size(parser->fields);
5378 if (was_end && var->expression.vtype == TYPE_FIELD) {
5379 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5380 "global '%s' hint should not be a field",
5381 parser_tokval(parser)))
5388 if (!nofields && var->expression.vtype == TYPE_FIELD)
5390 /* deal with field declarations */
5391 old = parser_find_field(parser, var->name);
5393 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5394 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5403 parseerror(parser, "field `%s` already declared here: %s:%i",
5404 var->name, ast_ctx(old).file, ast_ctx(old).line);
5409 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5410 (old = parser_find_global(parser, var->name)))
5412 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5413 parseerror(parser, "field `%s` already declared here: %s:%i",
5414 var->name, ast_ctx(old).file, ast_ctx(old).line);
5421 /* deal with other globals */
5422 old = parser_find_global(parser, var->name);
5423 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5425 /* This is a function which had a prototype */
5426 if (!ast_istype(old, ast_value)) {
5427 parseerror(parser, "internal error: prototype is not an ast_value");
5431 proto = (ast_value*)old;
5432 proto->desc = var->desc;
5433 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5434 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5436 ast_ctx(proto).file, ast_ctx(proto).line);
5440 /* we need the new parameter-names */
5441 for (i = 0; i < vec_size(proto->expression.params); ++i)
5442 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5443 if (!parser_check_qualifiers(parser, var, proto)) {
5450 proto->expression.flags |= var->expression.flags;
5458 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5459 "global `%s` already declared here: %s:%i",
5460 var->name, ast_ctx(old).file, ast_ctx(old).line))
5465 proto = (ast_value*)old;
5466 if (!ast_istype(old, ast_value)) {
5467 parseerror(parser, "internal error: not an ast_value");
5472 if (!parser_check_qualifiers(parser, var, proto)) {
5477 proto->expression.flags |= var->expression.flags;
5481 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5482 (old = parser_find_field(parser, var->name)))
5484 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5485 parseerror(parser, "global `%s` already declared here: %s:%i",
5486 var->name, ast_ctx(old).file, ast_ctx(old).line);
5493 else /* it's not a global */
5495 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5496 if (old && !isparam) {
5497 parseerror(parser, "local `%s` already declared here: %s:%i",
5498 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5502 old = parser_find_local(parser, var->name, 0, &isparam);
5503 if (old && isparam) {
5504 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5505 "local `%s` is shadowing a parameter", var->name))
5507 parseerror(parser, "local `%s` already declared here: %s:%i",
5508 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5512 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5520 /* in a noref section we simply bump the usecount */
5521 if (noref || parser->noref)
5525 * Create the global/local, and deal with vector types.
5528 if (var->expression.vtype == TYPE_VECTOR)
5530 else if (var->expression.vtype == TYPE_FIELD &&
5531 var->expression.next->vtype == TYPE_VECTOR)
5535 if (!create_vector_members(var, me)) {
5542 /* deal with global variables, fields, functions */
5543 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5544 var->isfield = true;
5545 vec_push(parser->fields, (ast_expression*)var);
5546 util_htset(parser->htfields, var->name, var);
5548 for (i = 0; i < 3; ++i) {
5549 vec_push(parser->fields, (ast_expression*)me[i]);
5550 util_htset(parser->htfields, me[i]->name, me[i]);
5555 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5556 parser_addglobal(parser, var->name, (ast_expression*)var);
5558 for (i = 0; i < 3; ++i) {
5559 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5563 ast_expression *find = parser_find_global(parser, var->desc);
5566 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5570 if (var->expression.vtype != find->vtype) {
5574 ast_type_to_string(find, ty1, sizeof(ty1));
5575 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5577 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5584 * add alias to aliases table and to corrector
5585 * so corrections can apply for aliases as well.
5587 util_htset(parser->aliases, var->name, find);
5590 * add to corrector so corrections can work
5591 * even for aliases too.
5594 vec_last(parser->correct_variables),
5595 &vec_last(parser->correct_variables_score),
5599 /* generate aliases for vector components */
5603 util_asprintf(&buffer[0], "%s_x", var->desc);
5604 util_asprintf(&buffer[1], "%s_y", var->desc);
5605 util_asprintf(&buffer[2], "%s_z", var->desc);
5607 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5608 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5609 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5616 * add to corrector so corrections can work
5617 * even for aliases too.
5620 vec_last(parser->correct_variables),
5621 &vec_last(parser->correct_variables_score),
5625 vec_last(parser->correct_variables),
5626 &vec_last(parser->correct_variables_score),
5630 vec_last(parser->correct_variables),
5631 &vec_last(parser->correct_variables_score),
5639 /* a static adds itself to be generated like any other global
5640 * but is added to the local namespace instead
5642 char *defname = NULL;
5643 size_t prefix_len, ln;
5645 ln = strlen(parser->function->name);
5646 vec_append(defname, ln, parser->function->name);
5648 vec_append(defname, 2, "::");
5649 /* remember the length up to here */
5650 prefix_len = vec_size(defname);
5652 /* Add it to the local scope */
5653 util_htset(vec_last(parser->variables), var->name, (void*)var);
5657 vec_last(parser->correct_variables),
5658 &vec_last(parser->correct_variables_score),
5662 /* now rename the global */
5663 ln = strlen(var->name);
5664 vec_append(defname, ln, var->name);
5665 ast_value_set_name(var, defname);
5667 /* push it to the to-be-generated globals */
5668 vec_push(parser->globals, (ast_expression*)var);
5670 /* same game for the vector members */
5672 for (i = 0; i < 3; ++i) {
5673 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5677 vec_last(parser->correct_variables),
5678 &vec_last(parser->correct_variables_score),
5682 vec_shrinkto(defname, prefix_len);
5683 ln = strlen(me[i]->name);
5684 vec_append(defname, ln, me[i]->name);
5685 ast_member_set_name(me[i], defname);
5687 vec_push(parser->globals, (ast_expression*)me[i]);
5692 vec_push(localblock->locals, var);
5693 parser_addlocal(parser, var->name, (ast_expression*)var);
5695 for (i = 0; i < 3; ++i) {
5696 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5697 ast_block_collect(localblock, (ast_expression*)me[i]);
5703 me[0] = me[1] = me[2] = NULL;
5708 if (var->expression.vtype == TYPE_ARRAY) {
5709 if (var->expression.count != (size_t)-1) {
5710 if (!create_array_accessors(parser, var))
5714 else if (!localblock && !nofields &&
5715 var->expression.vtype == TYPE_FIELD &&
5716 var->expression.next->vtype == TYPE_ARRAY)
5719 ast_expression *telem;
5721 ast_value *array = (ast_value*)var->expression.next;
5723 if (!ast_istype(var->expression.next, ast_value)) {
5724 parseerror(parser, "internal error: field element type must be an ast_value");
5728 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5729 if (!parser_create_array_field_setter(parser, array, name))
5732 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5733 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5734 tfield->expression.next = telem;
5735 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5736 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5744 if (parser->tok == ';') {
5745 ast_delete(basetype);
5746 if (!parser_next(parser)) {
5747 parseerror(parser, "error after variable declaration");
5753 if (parser->tok == ',')
5757 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5760 parseerror(parser, "missing comma or semicolon while parsing variables");
5764 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5765 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5766 "initializing expression turns variable `%s` into a constant in this standard",
5773 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5774 if (parser->tok != '=') {
5775 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5779 if (!parser_next(parser)) {
5780 parseerror(parser, "error parsing initializer");
5784 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5785 parseerror(parser, "expected '=' before function body in this standard");
5788 if (parser->tok == '#') {
5789 ast_function *func = NULL;
5790 ast_value *number = NULL;
5796 parseerror(parser, "cannot declare builtins within functions");
5799 if (var->expression.vtype != TYPE_FUNCTION) {
5800 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5803 if (!parser_next(parser)) {
5804 parseerror(parser, "expected builtin number");
5808 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5809 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5811 parseerror(parser, "builtin number expected");
5814 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5817 parseerror(parser, "builtin number must be a compile time constant");
5820 if (number->expression.vtype == TYPE_INTEGER)
5821 builtin_num = number->constval.vint;
5822 else if (number->expression.vtype == TYPE_FLOAT)
5823 builtin_num = number->constval.vfloat;
5826 parseerror(parser, "builtin number must be an integer constant");
5831 fractional = modff(builtin_num, &integral);
5832 if (builtin_num < 0 || fractional != 0) {
5833 parseerror(parser, "builtin number must be an integer greater than zero");
5837 /* we only want the integral part anyways */
5838 builtin_num = integral;
5839 } else if (parser->tok == TOKEN_INTCONST) {
5840 builtin_num = parser_token(parser)->constval.i;
5842 parseerror(parser, "builtin number must be a compile time constant");
5846 if (var->hasvalue) {
5847 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5848 "builtin `%s` has already been defined\n"
5849 " -> previous declaration here: %s:%i",
5850 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5854 func = ast_function_new(ast_ctx(var), var->name, var);
5856 parseerror(parser, "failed to allocate function for `%s`", var->name);
5859 vec_push(parser->functions, func);
5861 func->builtin = -builtin_num-1;
5864 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5865 ? (parser->tok != ',' && parser->tok != ';')
5866 : (!parser_next(parser)))
5868 parseerror(parser, "expected comma or semicolon");
5870 ast_function_delete(func);
5871 var->constval.vfunc = NULL;
5875 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5878 /* Note that fteqcc and most others don't even *have*
5879 * local arrays, so this is not a high priority.
5881 parseerror(parser, "TODO: initializers for local arrays");
5885 var->hasvalue = true;
5886 if (!parse_array(parser, var))
5889 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5892 parseerror(parser, "cannot declare functions within functions");
5897 ast_ctx(proto) = parser_ctx(parser);
5899 if (!parse_function_body(parser, var))
5901 ast_delete(basetype);
5902 for (i = 0; i < vec_size(parser->gotos); ++i)
5903 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5904 vec_free(parser->gotos);
5905 vec_free(parser->labels);
5908 ast_expression *cexp;
5911 cexp = parse_expression_leave(parser, true, false, false);
5916 cval = (ast_value*)cexp;
5917 if (cval != parser->nil &&
5918 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5921 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5925 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5926 qualifier != CV_VAR)
5928 var->cvq = CV_CONST;
5930 if (cval == parser->nil)
5931 var->expression.flags |= AST_FLAG_INITIALIZED;
5934 var->hasvalue = true;
5935 if (cval->expression.vtype == TYPE_STRING)
5936 var->constval.vstring = parser_strdup(cval->constval.vstring);
5937 else if (cval->expression.vtype == TYPE_FIELD)
5938 var->constval.vfield = cval;
5940 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5946 shunt sy = { NULL, NULL, NULL, NULL };
5949 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5950 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5951 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5952 if (!parser_sy_apply_operator(parser, &sy))
5955 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5956 parseerror(parser, "internal error: leaked operands");
5957 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5968 if (parser->tok == ',') {
5969 if (!parser_next(parser)) {
5970 parseerror(parser, "expected another variable");
5974 if (parser->tok != TOKEN_IDENT) {
5975 parseerror(parser, "expected another variable");
5978 var = ast_value_copy(basetype);
5980 ast_value_set_name(var, parser_tokval(parser));
5981 if (!parser_next(parser)) {
5982 parseerror(parser, "error parsing variable declaration");
5988 if (parser->tok != ';') {
5989 parseerror(parser, "missing semicolon after variables");
5993 if (!parser_next(parser)) {
5994 parseerror(parser, "parse error after variable declaration");
5998 ast_delete(basetype);
6002 if (cleanvar && var)
6004 ast_delete(basetype);
6008 ast_delete(basetype);
6009 if (cleanvar && var)
6011 if (me[0]) ast_member_delete(me[0]);
6012 if (me[1]) ast_member_delete(me[1]);
6013 if (me[2]) ast_member_delete(me[2]);
6017 static bool parser_global_statement(parser_t *parser)
6021 bool is_static = false;
6022 uint32_t qflags = 0;
6023 ast_value *istype = NULL;
6024 char *vstring = NULL;
6026 if (parser->tok == TOKEN_IDENT)
6027 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6029 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6031 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6033 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6035 if (cvq == CV_WRONG)
6037 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6039 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6041 return parse_enum(parser);
6043 else if (parser->tok == TOKEN_KEYWORD)
6045 if (!strcmp(parser_tokval(parser), "typedef")) {
6046 if (!parser_next(parser)) {
6047 parseerror(parser, "expected type definition after 'typedef'");
6050 return parse_typedef(parser);
6052 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6055 else if (parser->tok == '#')
6057 return parse_pragma(parser);
6059 else if (parser->tok == '$')
6061 if (!parser_next(parser)) {
6062 parseerror(parser, "parse error");
6068 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6074 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6076 return util_crc16(old, str, strlen(str));
6079 static void progdefs_crc_file(const char *str)
6081 /* write to progdefs.h here */
6085 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6087 old = progdefs_crc_sum(old, str);
6088 progdefs_crc_file(str);
6092 static void generate_checksum(parser_t *parser)
6094 uint16_t crc = 0xFFFF;
6098 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6099 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6101 progdefs_crc_file("\tint\tpad;\n");
6102 progdefs_crc_file("\tint\tofs_return[3];\n");
6103 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6104 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6105 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6106 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6107 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6108 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6109 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6110 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6112 for (i = 0; i < parser->crc_globals; ++i) {
6113 if (!ast_istype(parser->globals[i], ast_value))
6115 value = (ast_value*)(parser->globals[i]);
6116 switch (value->expression.vtype) {
6117 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6118 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6119 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6120 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6122 crc = progdefs_crc_both(crc, "\tint\t");
6125 crc = progdefs_crc_both(crc, value->name);
6126 crc = progdefs_crc_both(crc, ";\n");
6128 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6129 for (i = 0; i < parser->crc_fields; ++i) {
6130 if (!ast_istype(parser->fields[i], ast_value))
6132 value = (ast_value*)(parser->fields[i]);
6133 switch (value->expression.next->vtype) {
6134 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6135 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6136 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6137 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6139 crc = progdefs_crc_both(crc, "\tint\t");
6142 crc = progdefs_crc_both(crc, value->name);
6143 crc = progdefs_crc_both(crc, ";\n");
6145 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6147 parser->code->crc = crc;
6150 parser_t *parser_create()
6156 parser = (parser_t*)mem_a(sizeof(parser_t));
6160 memset(parser, 0, sizeof(*parser));
6162 if (!(parser->code = code_init())) {
6167 for (i = 0; i < operator_count; ++i) {
6168 if (operators[i].id == opid1('=')) {
6169 parser->assign_op = operators+i;
6173 if (!parser->assign_op) {
6174 printf("internal error: initializing parser: failed to find assign operator\n");
6179 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6180 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6181 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6182 vec_push(parser->_blocktypedefs, 0);
6184 parser->aliases = util_htnew(PARSER_HT_SIZE);
6186 parser->ht_imm_string = util_htnew(512);
6189 vec_push(parser->correct_variables, correct_trie_new());
6190 vec_push(parser->correct_variables_score, NULL);
6192 empty_ctx.file = "<internal>";
6194 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6195 parser->nil->cvq = CV_CONST;
6196 if (OPTS_FLAG(UNTYPED_NIL))
6197 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6199 parser->max_param_count = 1;
6201 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6202 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6203 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6205 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6206 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6207 parser->reserved_version->cvq = CV_CONST;
6208 parser->reserved_version->hasvalue = true;
6209 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6210 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6212 parser->reserved_version = NULL;
6218 static bool parser_compile(parser_t *parser)
6220 /* initial lexer/parser state */
6221 parser->lex->flags.noops = true;
6223 if (parser_next(parser))
6225 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6227 if (!parser_global_statement(parser)) {
6228 if (parser->tok == TOKEN_EOF)
6229 parseerror(parser, "unexpected eof");
6230 else if (compile_errors)
6231 parseerror(parser, "there have been errors, bailing out");
6232 lex_close(parser->lex);
6238 parseerror(parser, "parse error");
6239 lex_close(parser->lex);
6244 lex_close(parser->lex);
6247 return !compile_errors;
6250 bool parser_compile_file(parser_t *parser, const char *filename)
6252 parser->lex = lex_open(filename);
6254 con_err("failed to open file \"%s\"\n", filename);
6257 return parser_compile(parser);
6260 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6262 parser->lex = lex_open_string(str, len, name);
6264 con_err("failed to create lexer for string \"%s\"\n", name);
6267 return parser_compile(parser);
6270 static void parser_remove_ast(parser_t *parser)
6273 if (parser->ast_cleaned)
6275 parser->ast_cleaned = true;
6276 for (i = 0; i < vec_size(parser->accessors); ++i) {
6277 ast_delete(parser->accessors[i]->constval.vfunc);
6278 parser->accessors[i]->constval.vfunc = NULL;
6279 ast_delete(parser->accessors[i]);
6281 for (i = 0; i < vec_size(parser->functions); ++i) {
6282 ast_delete(parser->functions[i]);
6284 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6285 ast_delete(parser->imm_vector[i]);
6287 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6288 ast_delete(parser->imm_string[i]);
6290 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6291 ast_delete(parser->imm_float[i]);
6293 for (i = 0; i < vec_size(parser->fields); ++i) {
6294 ast_delete(parser->fields[i]);
6296 for (i = 0; i < vec_size(parser->globals); ++i) {
6297 ast_delete(parser->globals[i]);
6299 vec_free(parser->accessors);
6300 vec_free(parser->functions);
6301 vec_free(parser->imm_vector);
6302 vec_free(parser->imm_string);
6303 util_htdel(parser->ht_imm_string);
6304 vec_free(parser->imm_float);
6305 vec_free(parser->globals);
6306 vec_free(parser->fields);
6308 for (i = 0; i < vec_size(parser->variables); ++i)
6309 util_htdel(parser->variables[i]);
6310 vec_free(parser->variables);
6311 vec_free(parser->_blocklocals);
6312 vec_free(parser->_locals);
6315 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6316 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6318 vec_free(parser->correct_variables);
6319 vec_free(parser->correct_variables_score);
6322 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6323 ast_delete(parser->_typedefs[i]);
6324 vec_free(parser->_typedefs);
6325 for (i = 0; i < vec_size(parser->typedefs); ++i)
6326 util_htdel(parser->typedefs[i]);
6327 vec_free(parser->typedefs);
6328 vec_free(parser->_blocktypedefs);
6330 vec_free(parser->_block_ctx);
6332 vec_free(parser->labels);
6333 vec_free(parser->gotos);
6334 vec_free(parser->breaks);
6335 vec_free(parser->continues);
6337 ast_value_delete(parser->nil);
6339 ast_value_delete(parser->const_vec[0]);
6340 ast_value_delete(parser->const_vec[1]);
6341 ast_value_delete(parser->const_vec[2]);
6343 util_htdel(parser->aliases);
6344 intrin_intrinsics_destroy(parser);
6347 void parser_cleanup(parser_t *parser)
6349 parser_remove_ast(parser);
6350 code_cleanup(parser->code);
6355 bool parser_finish(parser_t *parser, const char *output)
6361 if (compile_errors) {
6362 con_out("*** there were compile errors\n");
6366 ir = ir_builder_new("gmqcc_out");
6368 con_out("failed to allocate builder\n");
6372 for (i = 0; i < vec_size(parser->fields); ++i) {
6375 if (!ast_istype(parser->fields[i], ast_value))
6377 field = (ast_value*)parser->fields[i];
6378 hasvalue = field->hasvalue;
6379 field->hasvalue = false;
6380 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6381 con_out("failed to generate field %s\n", field->name);
6382 ir_builder_delete(ir);
6387 ast_expression *subtype;
6388 field->hasvalue = true;
6389 subtype = field->expression.next;
6390 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6391 if (subtype->vtype == TYPE_FIELD)
6392 ifld->fieldtype = subtype->next->vtype;
6393 else if (subtype->vtype == TYPE_FUNCTION)
6394 ifld->outtype = subtype->next->vtype;
6395 (void)!ir_value_set_field(field->ir_v, ifld);
6398 for (i = 0; i < vec_size(parser->globals); ++i) {
6400 if (!ast_istype(parser->globals[i], ast_value))
6402 asvalue = (ast_value*)(parser->globals[i]);
6403 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6404 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6405 "unused global: `%s`", asvalue->name);
6407 if (!ast_global_codegen(asvalue, ir, false)) {
6408 con_out("failed to generate global %s\n", asvalue->name);
6409 ir_builder_delete(ir);
6413 /* Build function vararg accessor ast tree now before generating
6414 * immediates, because the accessors may add new immediates
6416 for (i = 0; i < vec_size(parser->functions); ++i) {
6417 ast_function *f = parser->functions[i];
6419 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6420 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6421 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6422 con_out("failed to generate vararg setter for %s\n", f->name);
6423 ir_builder_delete(ir);
6426 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6427 con_out("failed to generate vararg getter for %s\n", f->name);
6428 ir_builder_delete(ir);
6432 ast_delete(f->varargs);
6437 /* Now we can generate immediates */
6438 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6439 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6440 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6441 ir_builder_delete(ir);
6445 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6446 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6447 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6448 ir_builder_delete(ir);
6452 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6453 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6454 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6455 ir_builder_delete(ir);
6459 for (i = 0; i < vec_size(parser->globals); ++i) {
6461 if (!ast_istype(parser->globals[i], ast_value))
6463 asvalue = (ast_value*)(parser->globals[i]);
6464 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6466 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6467 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6468 "uninitialized constant: `%s`",
6470 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6471 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6472 "uninitialized global: `%s`",
6475 if (!ast_generate_accessors(asvalue, ir)) {
6476 ir_builder_delete(ir);
6480 for (i = 0; i < vec_size(parser->fields); ++i) {
6482 asvalue = (ast_value*)(parser->fields[i]->next);
6484 if (!ast_istype((ast_expression*)asvalue, ast_value))
6486 if (asvalue->expression.vtype != TYPE_ARRAY)
6488 if (!ast_generate_accessors(asvalue, ir)) {
6489 ir_builder_delete(ir);
6493 if (parser->reserved_version &&
6494 !ast_global_codegen(parser->reserved_version, ir, false))
6496 con_out("failed to generate reserved::version");
6497 ir_builder_delete(ir);
6500 for (i = 0; i < vec_size(parser->functions); ++i) {
6501 ast_function *f = parser->functions[i];
6502 if (!ast_function_codegen(f, ir)) {
6503 con_out("failed to generate function %s\n", f->name);
6504 ir_builder_delete(ir);
6509 generate_checksum(parser);
6510 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6511 ir_builder_dump(ir, con_out);
6512 for (i = 0; i < vec_size(parser->functions); ++i) {
6513 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6514 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6515 ir_builder_delete(ir);
6519 parser_remove_ast(parser);
6521 if (compile_Werrors) {
6522 con_out("*** there were warnings treated as errors\n");
6523 compile_show_werrors();
6528 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6529 ir_builder_dump(ir, con_out);
6531 if (!ir_builder_generate(parser->code, ir, output)) {
6532 con_out("*** failed to generate output file\n");
6533 ir_builder_delete(ir);
6537 ir_builder_delete(ir);