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
32 /* beginning of locals */
33 #define PARSER_HT_LOCALS 2
35 #define PARSER_HT_SIZE 128
36 #define TYPEDEF_HT_SIZE 16
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_float_neg_one;
57 ast_value *imm_vector_zero;
60 ast_value *reserved_version;
65 ast_function *function;
68 /* All the labels the function defined...
69 * Should they be in ast_function instead?
74 const char **continues;
76 /* A list of hashtables for each scope */
82 /* same as above but for the spelling corrector */
83 correct_trie_t **correct_variables;
84 size_t ***correct_variables_score; /* vector of vector of size_t* */
86 /* not to be used directly, we use the hash table */
87 ast_expression **_locals;
89 ast_value **_typedefs;
90 size_t *_blocktypedefs;
93 /* we store the '=' operator info */
94 const oper_info *assign_op;
97 ast_value *const_vec[3];
102 /* collected information */
103 size_t max_param_count;
106 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
108 static void parser_enterblock(parser_t *parser);
109 static bool parser_leaveblock(parser_t *parser);
110 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
111 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
112 static bool parse_typedef(parser_t *parser);
113 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);
114 static ast_block* parse_block(parser_t *parser);
115 static bool parse_block_into(parser_t *parser, ast_block *block);
116 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
117 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
118 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
119 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
120 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
121 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
122 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
124 static ast_expression *parser_builtin_pow(parser_t *);
125 static ast_expression *parser_builtin_exp(parser_t *);
126 static ast_expression *parser_builtin_mod(parser_t *);
128 static void parseerror(parser_t *parser, const char *fmt, ...)
132 vcompile_error(parser->lex->tok.ctx, fmt, ap);
136 /* returns true if it counts as an error */
137 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
142 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
147 /**********************************************************************
148 * some maths used for constant folding
151 vector vec3_add(vector a, vector b)
160 vector vec3_sub(vector a, vector b)
169 qcfloat vec3_mulvv(vector a, vector b)
171 return (a.x * b.x + a.y * b.y + a.z * b.z);
174 vector vec3_mulvf(vector a, float b)
183 /**********************************************************************
187 bool parser_next(parser_t *parser)
189 /* lex_do kills the previous token */
190 parser->tok = lex_do(parser->lex);
191 if (parser->tok == TOKEN_EOF)
193 if (parser->tok >= TOKEN_ERROR) {
194 parseerror(parser, "lex error");
200 #define parser_tokval(p) ((p)->lex->tok.value)
201 #define parser_token(p) (&((p)->lex->tok))
202 #define parser_ctx(p) ((p)->lex->tok.ctx)
204 static ast_value* parser_const_float(parser_t *parser, double d)
209 for (i = 0; i < vec_size(parser->imm_float); ++i) {
210 const double compare = parser->imm_float[i]->constval.vfloat;
211 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
212 return parser->imm_float[i];
215 ctx = parser_ctx(parser);
217 memset(&ctx, 0, sizeof(ctx));
219 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
221 out->hasvalue = true;
222 out->constval.vfloat = d;
223 vec_push(parser->imm_float, out);
227 static ast_value* parser_const_float_0(parser_t *parser)
229 if (!parser->imm_float_zero)
230 parser->imm_float_zero = parser_const_float(parser, 0);
231 return parser->imm_float_zero;
234 static ast_value* parser_const_float_neg1(parser_t *parser) {
235 if (!parser->imm_float_neg_one)
236 parser->imm_float_neg_one = parser_const_float(parser, -1);
237 return parser->imm_float_neg_one;
240 static ast_value* parser_const_float_1(parser_t *parser)
242 if (!parser->imm_float_one)
243 parser->imm_float_one = parser_const_float(parser, 1);
244 return parser->imm_float_one;
247 static char *parser_strdup(const char *str)
250 /* actually dup empty strings */
251 char *out = (char*)mem_a(1);
255 return util_strdup(str);
258 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
262 for (i = 0; i < vec_size(parser->imm_string); ++i) {
263 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
264 return parser->imm_string[i];
268 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
269 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
271 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
273 out->hasvalue = true;
274 out->constval.vstring = parser_strdup(str);
275 vec_push(parser->imm_string, out);
279 static ast_value* parser_const_vector(parser_t *parser, vector v)
283 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
284 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
285 return parser->imm_vector[i];
287 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
289 out->hasvalue = true;
290 out->constval.vvec = v;
291 vec_push(parser->imm_vector, out);
295 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
301 return parser_const_vector(parser, v);
304 static ast_value* parser_const_vector_0(parser_t *parser)
306 if (!parser->imm_vector_zero)
307 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
308 return parser->imm_vector_zero;
311 static ast_expression* parser_find_field(parser_t *parser, const char *name)
313 return ( ast_expression*)util_htget(parser->htfields, name);
316 static ast_expression* parser_find_label(parser_t *parser, const char *name)
319 for(i = 0; i < vec_size(parser->labels); i++)
320 if (!strcmp(parser->labels[i]->name, name))
321 return (ast_expression*)parser->labels[i];
325 static ast_expression* parser_find_global(parser_t *parser, const char *name)
327 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
330 return (ast_expression*)util_htget(parser->htglobals, name);
333 static ast_expression* parser_find_param(parser_t *parser, const char *name)
337 if (!parser->function)
339 fun = parser->function->vtype;
340 for (i = 0; i < vec_size(fun->expression.params); ++i) {
341 if (!strcmp(fun->expression.params[i]->name, name))
342 return (ast_expression*)(fun->expression.params[i]);
347 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
352 hash = util_hthash(parser->htglobals, name);
355 for (i = vec_size(parser->variables); i > upto;) {
357 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
361 return parser_find_param(parser, name);
364 static ast_expression* parser_find_var(parser_t *parser, const char *name)
368 v = parser_find_local(parser, name, 0, &dummy);
369 if (!v) v = parser_find_global(parser, name);
373 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
377 hash = util_hthash(parser->typedefs[0], name);
379 for (i = vec_size(parser->typedefs); i > upto;) {
381 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
389 size_t etype; /* 0 = expression, others are operators */
393 ast_block *block; /* for commas and function calls */
412 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
423 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
427 e.out = (ast_expression*)v;
434 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
436 e.etype = 1 + (op - operators);
445 static sy_elem syparen(lex_ctx ctx, size_t off) {
456 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
457 * so we need to rotate it to become ent.(foo[n]).
459 static bool rotate_entfield_array_index_nodes(ast_expression **out)
461 ast_array_index *index, *oldindex;
462 ast_entfield *entfield;
466 ast_expression *entity;
468 lex_ctx ctx = ast_ctx(*out);
470 if (!ast_istype(*out, ast_array_index))
472 index = (ast_array_index*)*out;
474 if (!ast_istype(index->array, ast_entfield))
476 entfield = (ast_entfield*)index->array;
478 if (!ast_istype(entfield->field, ast_value))
480 field = (ast_value*)entfield->field;
483 entity = entfield->entity;
487 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
488 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
489 *out = (ast_expression*)entfield;
491 oldindex->array = NULL;
492 oldindex->index = NULL;
493 ast_delete(oldindex);
498 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
500 switch (v->expression.vtype) {
502 return !!v->constval.vfloat;
504 return !!v->constval.vint;
506 if (OPTS_FLAG(CORRECT_LOGIC))
507 return v->constval.vvec.x &&
508 v->constval.vvec.y &&
511 return !!(v->constval.vvec.x);
513 if (!v->constval.vstring)
515 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
517 return !!v->constval.vstring[0];
519 compile_error(ctx, "internal error: immediate_is_true on invalid type");
520 return !!v->constval.vfunc;
524 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
528 ast_expression *out = NULL;
529 ast_expression *exprs[3];
530 ast_block *blocks[3];
531 ast_value *asvalue[3];
532 ast_binstore *asbinstore;
533 size_t i, assignop, addop, subop;
534 qcint generated_op = 0;
539 if (!vec_size(sy->ops)) {
540 parseerror(parser, "internal error: missing operator");
544 if (vec_last(sy->ops).isparen) {
545 parseerror(parser, "unmatched parenthesis");
549 op = &operators[vec_last(sy->ops).etype - 1];
550 ctx = vec_last(sy->ops).ctx;
552 if (vec_size(sy->out) < op->operands) {
553 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
554 op->op, (int)op->id);
558 vec_shrinkby(sy->ops, 1);
560 /* op(:?) has no input and no output */
564 vec_shrinkby(sy->out, op->operands);
565 for (i = 0; i < op->operands; ++i) {
566 exprs[i] = sy->out[vec_size(sy->out)+i].out;
567 blocks[i] = sy->out[vec_size(sy->out)+i].block;
568 asvalue[i] = (ast_value*)exprs[i];
570 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
571 !(i != 0 && op->id == opid2('?',':')) &&
572 !(i == 1 && op->id == opid1('.')))
574 if (ast_istype(exprs[i], ast_label))
575 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
577 compile_error(ast_ctx(exprs[i]), "not an expression");
578 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
582 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
583 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
587 #define NotSameType(T) \
588 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
589 exprs[0]->expression.vtype != T)
590 #define CanConstFold1(A) \
591 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
592 (A)->expression.vtype != TYPE_FUNCTION)
593 #define CanConstFold(A, B) \
594 (CanConstFold1(A) && CanConstFold1(B))
595 #define ConstV(i) (asvalue[(i)]->constval.vvec)
596 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
597 #define ConstS(i) (asvalue[(i)]->constval.vstring)
601 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
605 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
606 exprs[1]->expression.vtype == TYPE_NOEXPR)
608 if (exprs[1] == (ast_expression*)parser->const_vec[0])
609 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
610 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
611 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
612 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
613 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
615 compile_error(ctx, "access to invalid vector component");
619 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
620 if (exprs[1]->expression.vtype != TYPE_FIELD) {
621 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
624 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
626 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
627 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
631 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
637 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
638 !(exprs[0]->expression.vtype == TYPE_FIELD &&
639 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
641 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
642 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
645 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
646 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
647 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
650 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
651 if (rotate_entfield_array_index_nodes(&out))
654 /* This is not broken in fteqcc anymore */
655 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
656 /* this error doesn't need to make us bail out */
657 (void)!parsewarning(parser, WARN_EXTENSIONS,
658 "accessing array-field members of an entity without parenthesis\n"
659 " -> this is an extension from -std=gmqcc");
666 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
667 vec_push(sy->out, syexp(ctx, exprs[0]));
668 vec_push(sy->out, syexp(ctx, exprs[1]));
669 vec_last(sy->argc)++;
673 if (!ast_block_add_expr(blocks[0], exprs[1]))
676 blocks[0] = ast_block_new(ctx);
677 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
678 !ast_block_add_expr(blocks[0], exprs[1]))
683 ast_block_set_type(blocks[0], exprs[1]);
685 vec_push(sy->out, syblock(ctx, blocks[0]));
692 switch (exprs[0]->expression.vtype) {
694 if (CanConstFold1(exprs[0]))
695 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
697 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
698 (ast_expression*)parser_const_float_0(parser),
702 if (CanConstFold1(exprs[0]))
703 out = (ast_expression*)parser_const_vector_f(parser,
704 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
706 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
707 (ast_expression*)parser_const_vector_0(parser),
711 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
712 type_name[exprs[0]->expression.vtype]);
718 switch (exprs[0]->expression.vtype) {
720 if (CanConstFold1(exprs[0]))
721 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
723 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
726 if (CanConstFold1(exprs[0]))
727 out = (ast_expression*)parser_const_float(parser,
728 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
730 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
733 if (CanConstFold1(exprs[0])) {
734 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
735 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
737 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
739 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
740 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
742 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
745 /* we don't constant-fold NOT for these types */
747 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
750 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
753 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
754 type_name[exprs[0]->expression.vtype]);
760 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
761 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
763 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
764 type_name[exprs[0]->expression.vtype],
765 type_name[exprs[1]->expression.vtype]);
768 switch (exprs[0]->expression.vtype) {
770 if (CanConstFold(exprs[0], exprs[1]))
772 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
775 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
778 if (CanConstFold(exprs[0], exprs[1]))
779 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
781 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
784 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
785 type_name[exprs[0]->expression.vtype],
786 type_name[exprs[1]->expression.vtype]);
791 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
792 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
794 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
795 type_name[exprs[1]->expression.vtype],
796 type_name[exprs[0]->expression.vtype]);
799 switch (exprs[0]->expression.vtype) {
801 if (CanConstFold(exprs[0], exprs[1]))
802 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
804 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
807 if (CanConstFold(exprs[0], exprs[1]))
808 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
810 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
813 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
814 type_name[exprs[1]->expression.vtype],
815 type_name[exprs[0]->expression.vtype]);
820 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
821 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
822 exprs[1]->expression.vtype == TYPE_FLOAT) &&
823 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
824 exprs[0]->expression.vtype == TYPE_FLOAT)
827 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
828 type_name[exprs[1]->expression.vtype],
829 type_name[exprs[0]->expression.vtype]);
832 switch (exprs[0]->expression.vtype) {
834 if (exprs[1]->expression.vtype == TYPE_VECTOR)
836 if (CanConstFold(exprs[0], exprs[1]))
837 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
839 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
843 if (CanConstFold(exprs[0], exprs[1]))
844 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
846 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
850 if (exprs[1]->expression.vtype == TYPE_FLOAT)
852 if (CanConstFold(exprs[0], exprs[1]))
853 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
855 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
859 if (CanConstFold(exprs[0], exprs[1]))
860 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
861 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
862 vector vec = ConstV(0);
863 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
864 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
865 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
866 out->expression.node.keep = false;
867 ((ast_member*)out)->rvalue = true;
869 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
871 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
872 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
873 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
874 out->expression.node.keep = false;
875 ((ast_member*)out)->rvalue = true;
877 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
879 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
880 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
881 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
882 out->expression.node.keep = false;
883 ((ast_member*)out)->rvalue = true;
885 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
888 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
890 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
891 vector vec = ConstV(1);
892 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
893 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
894 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
895 out->expression.node.keep = false;
896 ((ast_member*)out)->rvalue = true;
898 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
900 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
901 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
902 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
903 out->expression.node.keep = false;
904 ((ast_member*)out)->rvalue = true;
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
908 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
909 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
910 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
911 out->expression.node.keep = false;
912 ((ast_member*)out)->rvalue = true;
914 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
917 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
920 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
924 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
925 type_name[exprs[1]->expression.vtype],
926 type_name[exprs[0]->expression.vtype]);
931 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
932 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
933 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
934 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
937 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
938 if (CanConstFold(exprs[0], exprs[1]))
939 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
941 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
943 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
944 if (CanConstFold(exprs[0], exprs[1]))
945 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
947 if (CanConstFold1(exprs[1])) {
948 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
950 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
951 (ast_expression*)parser_const_float_1(parser),
955 compile_error(ctx, "internal error: failed to generate division");
958 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
963 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
964 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
965 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
971 if (NotSameType(TYPE_FLOAT)) {
972 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
973 type_name[exprs[0]->expression.vtype],
974 type_name[exprs[1]->expression.vtype]);
977 if (CanConstFold(exprs[0], exprs[1])) {
978 out = (ast_expression*)parser_const_float(parser,
979 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
981 /* generate a call to __builtin_mod */
982 ast_expression *mod = parser_builtin_mod(parser);
983 ast_call *call = NULL;
984 if (!mod) return false; /* can return null for missing floor */
986 call = ast_call_new(parser_ctx(parser), mod);
987 vec_push(call->params, exprs[0]);
988 vec_push(call->params, exprs[1]);
990 out = (ast_expression*)call;
995 compile_error(ctx, "%= is unimplemented");
1000 if (NotSameType(TYPE_FLOAT)) {
1001 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1002 type_name[exprs[0]->expression.vtype],
1003 type_name[exprs[1]->expression.vtype]);
1006 if (CanConstFold(exprs[0], exprs[1]))
1007 out = (ast_expression*)parser_const_float(parser,
1008 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1009 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1011 out = (ast_expression*)ast_binary_new(ctx,
1012 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1013 exprs[0], exprs[1]);
1016 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1019 case opid2('<','<'):
1020 case opid2('>','>'):
1021 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1022 if (op->id == opid2('<','<'))
1023 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1025 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1028 case opid3('<','<','='):
1029 case opid3('>','>','='):
1030 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1033 case opid2('|','|'):
1034 generated_op += 1; /* INSTR_OR */
1035 case opid2('&','&'):
1036 generated_op += INSTR_AND;
1037 if (CanConstFold(exprs[0], exprs[1]))
1039 if (OPTS_FLAG(PERL_LOGIC)) {
1040 if (immediate_is_true(ctx, asvalue[0]))
1044 out = (ast_expression*)parser_const_float(parser,
1045 ( (generated_op == INSTR_OR)
1046 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1047 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1052 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1053 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1054 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1055 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1058 for (i = 0; i < 2; ++i) {
1059 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1060 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1062 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1064 exprs[i] = out; out = NULL;
1065 if (OPTS_FLAG(PERL_LOGIC)) {
1066 /* here we want to keep the right expressions' type */
1070 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1071 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1073 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1075 exprs[i] = out; out = NULL;
1076 if (OPTS_FLAG(PERL_LOGIC)) {
1077 /* here we want to keep the right expressions' type */
1082 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1086 case opid2('?',':'):
1087 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1088 compile_error(ctx, "mismatched parenthesis/ternary");
1092 if (!ast_compare_type(exprs[1], exprs[2])) {
1093 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1094 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1095 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1098 if (CanConstFold1(exprs[0]))
1099 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1101 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1104 case opid2('*', '*'):
1105 if (NotSameType(TYPE_FLOAT)) {
1106 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1107 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1108 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1114 if (CanConstFold(exprs[0], exprs[1])) {
1115 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1117 ast_call *gencall = ast_call_new(parser_ctx(parser), parser_builtin_pow(parser));
1118 vec_push(gencall->params, exprs[0]);
1119 vec_push(gencall->params, exprs[1]);
1120 out = (ast_expression*)gencall;
1124 case opid3('<','=','>'): /* -1, 0, or 1 */
1125 if (NotSameType(TYPE_FLOAT)) {
1126 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128 compile_error(ctx, "invalid types used in comparision: %s and %s",
1134 if (CanConstFold(exprs[0], exprs[1])) {
1135 if (ConstF(0) < ConstF(1))
1136 out = (ast_expression*)parser_const_float_neg1(parser);
1137 else if (ConstF(0) == ConstF(1))
1138 out = (ast_expression*)parser_const_float_0(parser);
1139 else if (ConstF(0) > ConstF(1))
1140 out = (ast_expression*)parser_const_float_1(parser);
1142 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1144 eq->refs = (ast_binary_ref)false; /* references nothing */
1147 out = (ast_expression*)ast_ternary_new(ctx,
1148 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1150 (ast_expression*)parser_const_float_neg1(parser),
1153 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1155 (ast_expression*)parser_const_float_0(parser),
1158 (ast_expression*)parser_const_float_1(parser)
1168 generated_op += 1; /* INSTR_GT */
1170 generated_op += 1; /* INSTR_LT */
1171 case opid2('>', '='):
1172 generated_op += 1; /* INSTR_GE */
1173 case opid2('<', '='):
1174 generated_op += INSTR_LE;
1175 if (NotSameType(TYPE_FLOAT)) {
1176 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1177 type_name[exprs[0]->expression.vtype],
1178 type_name[exprs[1]->expression.vtype]);
1181 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1183 case opid2('!', '='):
1184 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1185 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1186 type_name[exprs[0]->expression.vtype],
1187 type_name[exprs[1]->expression.vtype]);
1190 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1192 case opid2('=', '='):
1193 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1194 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1195 type_name[exprs[0]->expression.vtype],
1196 type_name[exprs[1]->expression.vtype]);
1199 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1203 if (ast_istype(exprs[0], ast_entfield)) {
1204 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1205 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1206 exprs[0]->expression.vtype == TYPE_FIELD &&
1207 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1209 assignop = type_storep_instr[TYPE_VECTOR];
1212 assignop = type_storep_instr[exprs[0]->expression.vtype];
1213 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1215 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1216 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1217 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1218 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1219 exprs[1]->expression.vtype == TYPE_FUNCTION)
1221 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1222 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1225 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1230 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1231 exprs[0]->expression.vtype == TYPE_FIELD &&
1232 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1234 assignop = type_store_instr[TYPE_VECTOR];
1237 assignop = type_store_instr[exprs[0]->expression.vtype];
1240 if (assignop == VINSTR_END) {
1241 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1242 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1243 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1245 else if (!ast_compare_type(exprs[0], exprs[1]))
1247 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1248 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1249 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1250 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1251 exprs[1]->expression.vtype == TYPE_FUNCTION)
1253 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1254 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1257 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1260 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1261 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1263 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1265 case opid3('+','+','P'):
1266 case opid3('-','-','P'):
1268 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1269 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1270 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1273 if (op->id == opid3('+','+','P'))
1274 addop = INSTR_ADD_F;
1276 addop = INSTR_SUB_F;
1277 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1278 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1280 if (ast_istype(exprs[0], ast_entfield)) {
1281 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1283 (ast_expression*)parser_const_float_1(parser));
1285 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1287 (ast_expression*)parser_const_float_1(parser));
1290 case opid3('S','+','+'):
1291 case opid3('S','-','-'):
1293 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1294 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1295 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1298 if (op->id == opid3('S','+','+')) {
1299 addop = INSTR_ADD_F;
1300 subop = INSTR_SUB_F;
1302 addop = INSTR_SUB_F;
1303 subop = INSTR_ADD_F;
1305 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1306 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1308 if (ast_istype(exprs[0], ast_entfield)) {
1309 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1311 (ast_expression*)parser_const_float_1(parser));
1313 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1315 (ast_expression*)parser_const_float_1(parser));
1319 out = (ast_expression*)ast_binary_new(ctx, subop,
1321 (ast_expression*)parser_const_float_1(parser));
1323 case opid2('+','='):
1324 case opid2('-','='):
1325 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1326 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1328 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1329 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1330 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1334 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1335 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1337 if (ast_istype(exprs[0], ast_entfield))
1338 assignop = type_storep_instr[exprs[0]->expression.vtype];
1340 assignop = type_store_instr[exprs[0]->expression.vtype];
1341 switch (exprs[0]->expression.vtype) {
1343 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1344 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1345 exprs[0], exprs[1]);
1348 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1349 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1350 exprs[0], exprs[1]);
1353 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1354 type_name[exprs[0]->expression.vtype],
1355 type_name[exprs[1]->expression.vtype]);
1359 case opid2('*','='):
1360 case opid2('/','='):
1361 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1362 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1363 exprs[0]->expression.vtype == TYPE_VECTOR))
1365 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1366 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1367 compile_error(ctx, "invalid types used in expression: %s and %s",
1371 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1372 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1374 if (ast_istype(exprs[0], ast_entfield))
1375 assignop = type_storep_instr[exprs[0]->expression.vtype];
1377 assignop = type_store_instr[exprs[0]->expression.vtype];
1378 switch (exprs[0]->expression.vtype) {
1380 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1381 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1382 exprs[0], exprs[1]);
1385 if (op->id == opid2('*','=')) {
1386 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1387 exprs[0], exprs[1]);
1389 /* there's no DIV_VF */
1390 if (CanConstFold1(exprs[1])) {
1391 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1393 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1394 (ast_expression*)parser_const_float_1(parser),
1398 compile_error(ctx, "internal error: failed to generate division");
1401 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1406 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1407 type_name[exprs[0]->expression.vtype],
1408 type_name[exprs[1]->expression.vtype]);
1412 case opid2('&','='):
1413 case opid2('|','='):
1414 if (NotSameType(TYPE_FLOAT)) {
1415 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1416 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1417 compile_error(ctx, "invalid types used in expression: %s and %s",
1421 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1422 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1424 if (ast_istype(exprs[0], ast_entfield))
1425 assignop = type_storep_instr[exprs[0]->expression.vtype];
1427 assignop = type_store_instr[exprs[0]->expression.vtype];
1428 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1429 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1430 exprs[0], exprs[1]);
1432 case opid3('&','~','='):
1433 /* This is like: a &= ~(b);
1434 * But QC has no bitwise-not, so we implement it as
1437 if (NotSameType(TYPE_FLOAT)) {
1438 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1439 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1440 compile_error(ctx, "invalid types used in expression: %s and %s",
1444 if (ast_istype(exprs[0], ast_entfield))
1445 assignop = type_storep_instr[exprs[0]->expression.vtype];
1447 assignop = type_store_instr[exprs[0]->expression.vtype];
1448 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1451 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1452 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1454 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1455 asbinstore->keep_dest = true;
1456 out = (ast_expression*)asbinstore;
1459 case opid2('~', 'P'):
1460 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1461 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1462 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1466 if(CanConstFold1(exprs[0]))
1467 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1469 out = (ast_expression*)
1470 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1476 compile_error(ctx, "failed to apply operator %s", op->op);
1480 vec_push(sy->out, syexp(ctx, out));
1484 static bool parser_close_call(parser_t *parser, shunt *sy)
1486 /* was a function call */
1487 ast_expression *fun;
1488 ast_value *funval = NULL;
1492 size_t paramcount, i;
1494 fid = vec_last(sy->ops).off;
1495 vec_shrinkby(sy->ops, 1);
1497 /* out[fid] is the function
1498 * everything above is parameters...
1500 if (!vec_size(sy->argc)) {
1501 parseerror(parser, "internal error: no argument counter available");
1505 paramcount = vec_last(sy->argc);
1508 if (vec_size(sy->out) < fid) {
1509 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1510 (unsigned long)vec_size(sy->out),
1512 (unsigned long)paramcount);
1516 fun = sy->out[fid].out;
1518 if (fun == intrinsic_debug_typestring) {
1520 if (fid+2 != vec_size(sy->out) ||
1521 vec_last(sy->out).block)
1523 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1526 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1527 ast_unref(vec_last(sy->out).out);
1528 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1529 (ast_expression*)parser_const_string(parser, ty, false));
1530 vec_shrinkby(sy->out, 1);
1534 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1538 if (fid+1 < vec_size(sy->out))
1541 if (fid+1 + paramcount != vec_size(sy->out)) {
1542 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1543 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1547 for (i = 0; i < paramcount; ++i)
1548 vec_push(call->params, sy->out[fid+1 + i].out);
1549 vec_shrinkby(sy->out, paramcount);
1550 (void)!ast_call_check_types(call);
1551 if (parser->max_param_count < paramcount)
1552 parser->max_param_count = paramcount;
1554 if (ast_istype(fun, ast_value)) {
1555 funval = (ast_value*)fun;
1556 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1557 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1559 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1563 /* overwrite fid, the function, with a call */
1564 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1566 if (fun->expression.vtype != TYPE_FUNCTION) {
1567 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1571 if (!fun->expression.next) {
1572 parseerror(parser, "could not determine function return type");
1575 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1577 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1579 return !parsewarning(parser, WARN_DEPRECATED,
1580 "call to function (which is marked deprecated)\n",
1581 "-> it has been declared here: %s:%i",
1582 ast_ctx(fun).file, ast_ctx(fun).line);
1585 return !parsewarning(parser, WARN_DEPRECATED,
1586 "call to `%s` (which is marked deprecated)\n"
1587 "-> `%s` declared here: %s:%i",
1588 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1590 return !parsewarning(parser, WARN_DEPRECATED,
1591 "call to `%s` (deprecated: %s)\n"
1592 "-> `%s` declared here: %s:%i",
1593 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1597 if (vec_size(fun->expression.params) != paramcount &&
1598 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1599 vec_size(fun->expression.params) < paramcount))
1601 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1603 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1604 "too %s parameters for call to %s: expected %i, got %i\n"
1605 " -> `%s` has been declared here: %s:%i",
1606 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1607 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1609 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1610 "too %s parameters for function call: expected %i, got %i\n"
1611 " -> it has been declared here: %s:%i",
1612 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1613 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1620 static bool parser_close_paren(parser_t *parser, shunt *sy)
1622 if (!vec_size(sy->ops)) {
1623 parseerror(parser, "unmatched closing paren");
1627 while (vec_size(sy->ops)) {
1628 if (vec_last(sy->ops).isparen) {
1629 if (vec_last(sy->paren) == PAREN_FUNC) {
1631 if (!parser_close_call(parser, sy))
1635 if (vec_last(sy->paren) == PAREN_EXPR) {
1637 if (!vec_size(sy->out)) {
1638 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1639 vec_shrinkby(sy->ops, 1);
1642 vec_shrinkby(sy->ops, 1);
1645 if (vec_last(sy->paren) == PAREN_INDEX) {
1647 /* pop off the parenthesis */
1648 vec_shrinkby(sy->ops, 1);
1649 /* then apply the index operator */
1650 if (!parser_sy_apply_operator(parser, sy))
1654 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1655 vec_last(sy->paren) = PAREN_TERNARY2;
1656 /* pop off the parenthesis */
1657 vec_shrinkby(sy->ops, 1);
1660 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1663 if (!parser_sy_apply_operator(parser, sy))
1669 static void parser_reclassify_token(parser_t *parser)
1672 for (i = 0; i < operator_count; ++i) {
1673 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1674 parser->tok = TOKEN_OPERATOR;
1680 static ast_expression* parse_vararg_do(parser_t *parser)
1682 ast_expression *idx, *out;
1684 ast_value *funtype = parser->function->vtype;
1686 lex_ctx ctx = parser_ctx(parser);
1688 if (!parser_next(parser) || parser->tok != '(') {
1689 parseerror(parser, "expected parameter index and type in parenthesis");
1692 if (!parser_next(parser)) {
1693 parseerror(parser, "error parsing parameter index");
1697 idx = parse_expression_leave(parser, true, false, false);
1701 if (parser->tok != ',') {
1703 parseerror(parser, "expected comma after parameter index");
1707 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1709 parseerror(parser, "expected typename for vararg");
1713 typevar = parse_typename(parser, NULL, NULL);
1719 if (parser->tok != ')') {
1721 ast_delete(typevar);
1722 parseerror(parser, "expected closing paren");
1727 if (!parser_next(parser)) {
1729 ast_delete(typevar);
1730 parseerror(parser, "parse error after vararg");
1735 if (!parser->function->varargs) {
1737 ast_delete(typevar);
1738 parseerror(parser, "function has no variable argument list");
1742 if (funtype->expression.varparam &&
1743 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1747 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1748 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1749 compile_error(ast_ctx(typevar),
1750 "function was declared to take varargs of type `%s`, requested type is: %s",
1754 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1755 ast_type_adopt(out, typevar);
1756 ast_delete(typevar);
1760 static ast_expression* parse_vararg(parser_t *parser)
1762 bool old_noops = parser->lex->flags.noops;
1764 ast_expression *out;
1766 parser->lex->flags.noops = true;
1767 out = parse_vararg_do(parser);
1769 parser->lex->flags.noops = old_noops;
1773 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1775 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1776 parser->tok == TOKEN_IDENT &&
1777 !strcmp(parser_tokval(parser), "_"))
1779 /* a translatable string */
1782 parser->lex->flags.noops = true;
1783 if (!parser_next(parser) || parser->tok != '(') {
1784 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1787 parser->lex->flags.noops = false;
1788 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1789 parseerror(parser, "expected a constant string in translatable-string extension");
1792 val = parser_const_string(parser, parser_tokval(parser), true);
1795 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1797 if (!parser_next(parser) || parser->tok != ')') {
1798 parseerror(parser, "expected closing paren after translatable string");
1803 else if (parser->tok == TOKEN_DOTS)
1806 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1807 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1810 va = parse_vararg(parser);
1813 vec_push(sy->out, syexp(parser_ctx(parser), va));
1816 else if (parser->tok == TOKEN_FLOATCONST) {
1818 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1821 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1824 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1826 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1829 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1832 else if (parser->tok == TOKEN_STRINGCONST) {
1834 val = parser_const_string(parser, parser_tokval(parser), false);
1837 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1840 else if (parser->tok == TOKEN_VECTORCONST) {
1842 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1845 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1848 else if (parser->tok == TOKEN_IDENT)
1850 const char *ctoken = parser_tokval(parser);
1851 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1852 ast_expression *var;
1853 /* a_vector.{x,y,z} */
1854 if (!vec_size(sy->ops) ||
1855 !vec_last(sy->ops).etype ||
1856 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1857 (prev >= intrinsic_debug_typestring &&
1858 prev <= intrinsic_debug_typestring))
1860 /* When adding more intrinsics, fix the above condition */
1863 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1865 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1867 var = parser_find_var(parser, parser_tokval(parser));
1869 var = parser_find_field(parser, parser_tokval(parser));
1871 if (!var && with_labels) {
1872 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1874 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1875 var = (ast_expression*)lbl;
1876 vec_push(parser->labels, lbl);
1881 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1882 var = (ast_expression*)intrinsic_debug_typestring;
1884 if (!strcmp(parser_tokval(parser), "__builtin_pow"))
1885 var = parser_builtin_pow(parser);
1886 if (!strcmp(parser_tokval(parser), "__builtin_exp"))
1887 var = parser_builtin_exp(parser);
1888 if (!strcmp(parser_tokval(parser), "__builtin_mod"))
1889 var = parser_builtin_mod(parser);
1892 char *correct = NULL;
1896 * sometimes people use preprocessing predefs without enabling them
1897 * i've done this thousands of times already myself. Lets check for
1898 * it in the predef table. And diagnose it better :)
1900 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1901 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1902 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1903 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1910 * TODO: determine the best score for the identifier: be it
1911 * a variable, a field.
1913 * We should also consider adding correction tables for
1914 * other things as well.
1916 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1918 correct_init(&corr);
1920 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1921 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1922 if (strcmp(correct, parser_tokval(parser))) {
1924 } else if (correct) {
1929 correct_free(&corr);
1932 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1937 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1943 if (ast_istype(var, ast_value)) {
1944 ((ast_value*)var)->uses++;
1946 else if (ast_istype(var, ast_member)) {
1947 ast_member *mem = (ast_member*)var;
1948 if (ast_istype(mem->owner, ast_value))
1949 ((ast_value*)(mem->owner))->uses++;
1952 vec_push(sy->out, syexp(parser_ctx(parser), var));
1955 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1959 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1961 ast_expression *expr = NULL;
1964 bool wantop = false;
1965 /* only warn once about an assignment in a truth value because the current code
1966 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1968 bool warn_truthvalue = true;
1970 /* count the parens because an if starts with one, so the
1971 * end of a condition is an unmatched closing paren
1975 memset(&sy, 0, sizeof(sy));
1977 parser->lex->flags.noops = false;
1979 parser_reclassify_token(parser);
1983 if (parser->tok == TOKEN_TYPENAME) {
1984 parseerror(parser, "unexpected typename");
1988 if (parser->tok == TOKEN_OPERATOR)
1990 /* classify the operator */
1991 const oper_info *op;
1992 const oper_info *olast = NULL;
1994 for (o = 0; o < operator_count; ++o) {
1995 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1996 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1997 !strcmp(parser_tokval(parser), operators[o].op))
2002 if (o == operator_count) {
2003 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2006 /* found an operator */
2009 /* when declaring variables, a comma starts a new variable */
2010 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2011 /* fixup the token */
2016 /* a colon without a pervious question mark cannot be a ternary */
2017 if (!ternaries && op->id == opid2(':','?')) {
2022 if (op->id == opid1(',')) {
2023 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2024 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2028 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2029 olast = &operators[vec_last(sy.ops).etype-1];
2031 #define IsAssignOp(x) (\
2032 (x) == opid1('=') || \
2033 (x) == opid2('+','=') || \
2034 (x) == opid2('-','=') || \
2035 (x) == opid2('*','=') || \
2036 (x) == opid2('/','=') || \
2037 (x) == opid2('%','=') || \
2038 (x) == opid2('&','=') || \
2039 (x) == opid2('|','=') || \
2040 (x) == opid3('&','~','=') \
2042 if (warn_truthvalue) {
2043 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2044 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2045 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2048 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2049 warn_truthvalue = false;
2054 (op->prec < olast->prec) ||
2055 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2057 if (!parser_sy_apply_operator(parser, &sy))
2059 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2060 olast = &operators[vec_last(sy.ops).etype-1];
2065 if (op->id == opid1('(')) {
2067 size_t sycount = vec_size(sy.out);
2068 /* we expected an operator, this is the function-call operator */
2069 vec_push(sy.paren, PAREN_FUNC);
2070 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2071 vec_push(sy.argc, 0);
2073 vec_push(sy.paren, PAREN_EXPR);
2074 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2077 } else if (op->id == opid1('[')) {
2079 parseerror(parser, "unexpected array subscript");
2082 vec_push(sy.paren, PAREN_INDEX);
2083 /* push both the operator and the paren, this makes life easier */
2084 vec_push(sy.ops, syop(parser_ctx(parser), op));
2085 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2087 } else if (op->id == opid2('?',':')) {
2088 vec_push(sy.ops, syop(parser_ctx(parser), op));
2089 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2092 vec_push(sy.paren, PAREN_TERNARY1);
2093 } else if (op->id == opid2(':','?')) {
2094 if (!vec_size(sy.paren)) {
2095 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2098 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2099 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2102 if (!parser_close_paren(parser, &sy))
2104 vec_push(sy.ops, syop(parser_ctx(parser), op));
2108 vec_push(sy.ops, syop(parser_ctx(parser), op));
2109 wantop = !!(op->flags & OP_SUFFIX);
2112 else if (parser->tok == ')') {
2113 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2114 if (!parser_sy_apply_operator(parser, &sy))
2117 if (!vec_size(sy.paren))
2120 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2121 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2124 if (!parser_close_paren(parser, &sy))
2127 /* must be a function call without parameters */
2128 if (vec_last(sy.paren) != PAREN_FUNC) {
2129 parseerror(parser, "closing paren in invalid position");
2132 if (!parser_close_paren(parser, &sy))
2137 else if (parser->tok == '(') {
2138 parseerror(parser, "internal error: '(' should be classified as operator");
2141 else if (parser->tok == '[') {
2142 parseerror(parser, "internal error: '[' should be classified as operator");
2145 else if (parser->tok == ']') {
2146 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2147 if (!parser_sy_apply_operator(parser, &sy))
2150 if (!vec_size(sy.paren))
2152 if (vec_last(sy.paren) != PAREN_INDEX) {
2153 parseerror(parser, "mismatched parentheses, unexpected ']'");
2156 if (!parser_close_paren(parser, &sy))
2161 if (!parse_sya_operand(parser, &sy, with_labels))
2164 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2165 vec_last(sy.argc)++;
2170 parseerror(parser, "expected operator or end of statement");
2174 if (!parser_next(parser)) {
2177 if (parser->tok == ';' ||
2178 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2179 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2185 while (vec_size(sy.ops)) {
2186 if (!parser_sy_apply_operator(parser, &sy))
2190 parser->lex->flags.noops = true;
2191 if (!vec_size(sy.out)) {
2192 parseerror(parser, "empty expression");
2195 expr = sy.out[0].out;
2198 if (vec_size(sy.paren)) {
2199 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2207 parser->lex->flags.noops = true;
2208 for (i = 0; i < vec_size(sy.out); ++i) {
2210 ast_unref(sy.out[i].out);
2219 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2221 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2224 if (parser->tok != ';') {
2225 parseerror(parser, "semicolon expected after expression");
2229 if (!parser_next(parser)) {
2236 static void parser_enterblock(parser_t *parser)
2238 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2239 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2240 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2241 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2242 vec_push(parser->_block_ctx, parser_ctx(parser));
2245 vec_push(parser->correct_variables, correct_trie_new());
2246 vec_push(parser->correct_variables_score, NULL);
2249 static bool parser_leaveblock(parser_t *parser)
2252 size_t locals, typedefs;
2254 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2255 parseerror(parser, "internal error: parser_leaveblock with no block");
2259 util_htdel(vec_last(parser->variables));
2260 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2262 vec_pop(parser->variables);
2263 vec_pop(parser->correct_variables);
2264 vec_pop(parser->correct_variables_score);
2265 if (!vec_size(parser->_blocklocals)) {
2266 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2270 locals = vec_last(parser->_blocklocals);
2271 vec_pop(parser->_blocklocals);
2272 while (vec_size(parser->_locals) != locals) {
2273 ast_expression *e = vec_last(parser->_locals);
2274 ast_value *v = (ast_value*)e;
2275 vec_pop(parser->_locals);
2276 if (ast_istype(e, ast_value) && !v->uses) {
2277 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2282 typedefs = vec_last(parser->_blocktypedefs);
2283 while (vec_size(parser->_typedefs) != typedefs) {
2284 ast_delete(vec_last(parser->_typedefs));
2285 vec_pop(parser->_typedefs);
2287 util_htdel(vec_last(parser->typedefs));
2288 vec_pop(parser->typedefs);
2290 vec_pop(parser->_block_ctx);
2295 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2297 vec_push(parser->_locals, e);
2298 util_htset(vec_last(parser->variables), name, (void*)e);
2302 vec_last(parser->correct_variables),
2303 &vec_last(parser->correct_variables_score),
2308 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2310 vec_push(parser->globals, e);
2311 util_htset(parser->htglobals, name, e);
2315 parser->correct_variables[0],
2316 &parser->correct_variables_score[0],
2321 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2325 ast_expression *prev;
2327 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2329 ast_type_to_string(cond, ty, sizeof(ty));
2330 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2333 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2336 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2339 parseerror(parser, "internal error: failed to process condition");
2344 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2346 /* vector types need to be cast to true booleans */
2347 ast_binary *bin = (ast_binary*)cond;
2348 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2350 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2352 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2355 parseerror(parser, "internal error: failed to process condition");
2362 unary = (ast_unary*)cond;
2363 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2365 cond = unary->operand;
2366 unary->operand = NULL;
2369 unary = (ast_unary*)cond;
2373 parseerror(parser, "internal error: failed to process condition");
2375 if (ifnot) *_ifnot = !*_ifnot;
2379 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2382 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2385 lex_ctx ctx = parser_ctx(parser);
2387 (void)block; /* not touching */
2389 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2390 if (!parser_next(parser)) {
2391 parseerror(parser, "expected condition or 'not'");
2394 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2396 if (!parser_next(parser)) {
2397 parseerror(parser, "expected condition in parenthesis");
2401 if (parser->tok != '(') {
2402 parseerror(parser, "expected 'if' condition in parenthesis");
2405 /* parse into the expression */
2406 if (!parser_next(parser)) {
2407 parseerror(parser, "expected 'if' condition after opening paren");
2410 /* parse the condition */
2411 cond = parse_expression_leave(parser, false, true, false);
2415 if (parser->tok != ')') {
2416 parseerror(parser, "expected closing paren after 'if' condition");
2420 /* parse into the 'then' branch */
2421 if (!parser_next(parser)) {
2422 parseerror(parser, "expected statement for on-true branch of 'if'");
2426 if (!parse_statement_or_block(parser, &ontrue)) {
2431 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2432 /* check for an else */
2433 if (!strcmp(parser_tokval(parser), "else")) {
2434 /* parse into the 'else' branch */
2435 if (!parser_next(parser)) {
2436 parseerror(parser, "expected on-false branch after 'else'");
2441 if (!parse_statement_or_block(parser, &onfalse)) {
2448 cond = process_condition(parser, cond, &ifnot);
2450 if (ontrue) ast_delete(ontrue);
2451 if (onfalse) ast_delete(onfalse);
2456 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2458 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2459 *out = (ast_expression*)ifthen;
2463 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2464 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2469 /* skip the 'while' and get the body */
2470 if (!parser_next(parser)) {
2471 if (OPTS_FLAG(LOOP_LABELS))
2472 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2474 parseerror(parser, "expected 'while' condition in parenthesis");
2478 if (parser->tok == ':') {
2479 if (!OPTS_FLAG(LOOP_LABELS))
2480 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2481 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2482 parseerror(parser, "expected loop label");
2485 label = util_strdup(parser_tokval(parser));
2486 if (!parser_next(parser)) {
2488 parseerror(parser, "expected 'while' condition in parenthesis");
2493 if (parser->tok != '(') {
2494 parseerror(parser, "expected 'while' condition in parenthesis");
2498 vec_push(parser->breaks, label);
2499 vec_push(parser->continues, label);
2501 rv = parse_while_go(parser, block, out);
2504 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2505 parseerror(parser, "internal error: label stack corrupted");
2511 vec_pop(parser->breaks);
2512 vec_pop(parser->continues);
2517 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2520 ast_expression *cond, *ontrue;
2524 lex_ctx ctx = parser_ctx(parser);
2526 (void)block; /* not touching */
2528 /* parse into the expression */
2529 if (!parser_next(parser)) {
2530 parseerror(parser, "expected 'while' condition after opening paren");
2533 /* parse the condition */
2534 cond = parse_expression_leave(parser, false, true, false);
2538 if (parser->tok != ')') {
2539 parseerror(parser, "expected closing paren after 'while' condition");
2543 /* parse into the 'then' branch */
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected while-loop body");
2549 if (!parse_statement_or_block(parser, &ontrue)) {
2554 cond = process_condition(parser, cond, &ifnot);
2559 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2560 *out = (ast_expression*)aloop;
2564 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2565 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2570 /* skip the 'do' and get the body */
2571 if (!parser_next(parser)) {
2572 if (OPTS_FLAG(LOOP_LABELS))
2573 parseerror(parser, "expected loop label or body");
2575 parseerror(parser, "expected loop body");
2579 if (parser->tok == ':') {
2580 if (!OPTS_FLAG(LOOP_LABELS))
2581 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2582 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2583 parseerror(parser, "expected loop label");
2586 label = util_strdup(parser_tokval(parser));
2587 if (!parser_next(parser)) {
2589 parseerror(parser, "expected loop body");
2594 vec_push(parser->breaks, label);
2595 vec_push(parser->continues, label);
2597 rv = parse_dowhile_go(parser, block, out);
2600 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2601 parseerror(parser, "internal error: label stack corrupted");
2607 vec_pop(parser->breaks);
2608 vec_pop(parser->continues);
2613 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2616 ast_expression *cond, *ontrue;
2620 lex_ctx ctx = parser_ctx(parser);
2622 (void)block; /* not touching */
2624 if (!parse_statement_or_block(parser, &ontrue))
2627 /* expect the "while" */
2628 if (parser->tok != TOKEN_KEYWORD ||
2629 strcmp(parser_tokval(parser), "while"))
2631 parseerror(parser, "expected 'while' and condition");
2636 /* skip the 'while' and check for opening paren */
2637 if (!parser_next(parser) || parser->tok != '(') {
2638 parseerror(parser, "expected 'while' condition in parenthesis");
2642 /* parse into the expression */
2643 if (!parser_next(parser)) {
2644 parseerror(parser, "expected 'while' condition after opening paren");
2648 /* parse the condition */
2649 cond = parse_expression_leave(parser, false, true, false);
2653 if (parser->tok != ')') {
2654 parseerror(parser, "expected closing paren after 'while' condition");
2660 if (!parser_next(parser) || parser->tok != ';') {
2661 parseerror(parser, "expected semicolon after condition");
2667 if (!parser_next(parser)) {
2668 parseerror(parser, "parse error");
2674 cond = process_condition(parser, cond, &ifnot);
2679 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2680 *out = (ast_expression*)aloop;
2684 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2685 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2690 /* skip the 'for' and check for opening paren */
2691 if (!parser_next(parser)) {
2692 if (OPTS_FLAG(LOOP_LABELS))
2693 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2695 parseerror(parser, "expected 'for' expressions in parenthesis");
2699 if (parser->tok == ':') {
2700 if (!OPTS_FLAG(LOOP_LABELS))
2701 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2702 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2703 parseerror(parser, "expected loop label");
2706 label = util_strdup(parser_tokval(parser));
2707 if (!parser_next(parser)) {
2709 parseerror(parser, "expected 'for' expressions in parenthesis");
2714 if (parser->tok != '(') {
2715 parseerror(parser, "expected 'for' expressions in parenthesis");
2719 vec_push(parser->breaks, label);
2720 vec_push(parser->continues, label);
2722 rv = parse_for_go(parser, block, out);
2725 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2726 parseerror(parser, "internal error: label stack corrupted");
2732 vec_pop(parser->breaks);
2733 vec_pop(parser->continues);
2737 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2740 ast_expression *initexpr, *cond, *increment, *ontrue;
2746 lex_ctx ctx = parser_ctx(parser);
2748 parser_enterblock(parser);
2755 /* parse into the expression */
2756 if (!parser_next(parser)) {
2757 parseerror(parser, "expected 'for' initializer after opening paren");
2762 if (parser->tok == TOKEN_IDENT)
2763 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2765 if (typevar || parser->tok == TOKEN_TYPENAME) {
2767 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2768 if (parsewarning(parser, WARN_EXTENSIONS,
2769 "current standard does not allow variable declarations in for-loop initializers"))
2773 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2776 else if (parser->tok != ';')
2778 initexpr = parse_expression_leave(parser, false, false, false);
2783 /* move on to condition */
2784 if (parser->tok != ';') {
2785 parseerror(parser, "expected semicolon after for-loop initializer");
2788 if (!parser_next(parser)) {
2789 parseerror(parser, "expected for-loop condition");
2793 /* parse the condition */
2794 if (parser->tok != ';') {
2795 cond = parse_expression_leave(parser, false, true, false);
2800 /* move on to incrementor */
2801 if (parser->tok != ';') {
2802 parseerror(parser, "expected semicolon after for-loop initializer");
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "expected for-loop condition");
2810 /* parse the incrementor */
2811 if (parser->tok != ')') {
2812 lex_ctx condctx = parser_ctx(parser);
2813 increment = parse_expression_leave(parser, false, false, false);
2816 if (!ast_side_effects(increment)) {
2817 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2823 if (parser->tok != ')') {
2824 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2827 /* parse into the 'then' branch */
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "expected for-loop body");
2832 if (!parse_statement_or_block(parser, &ontrue))
2836 cond = process_condition(parser, cond, &ifnot);
2840 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2841 *out = (ast_expression*)aloop;
2843 if (!parser_leaveblock(parser))
2847 if (initexpr) ast_delete(initexpr);
2848 if (cond) ast_delete(cond);
2849 if (increment) ast_delete(increment);
2850 (void)!parser_leaveblock(parser);
2854 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2856 ast_expression *exp = NULL;
2857 ast_return *ret = NULL;
2858 ast_value *expected = parser->function->vtype;
2860 lex_ctx ctx = parser_ctx(parser);
2862 (void)block; /* not touching */
2864 if (!parser_next(parser)) {
2865 parseerror(parser, "expected return expression");
2869 if (parser->tok != ';') {
2870 exp = parse_expression(parser, false, false);
2874 if (exp->expression.vtype != TYPE_NIL &&
2875 exp->expression.vtype != expected->expression.next->expression.vtype)
2877 parseerror(parser, "return with invalid expression");
2880 ret = ast_return_new(ctx, exp);
2886 if (!parser_next(parser))
2887 parseerror(parser, "parse error");
2888 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2889 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2891 ret = ast_return_new(ctx, NULL);
2893 *out = (ast_expression*)ret;
2897 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2900 unsigned int levels = 0;
2901 lex_ctx ctx = parser_ctx(parser);
2902 const char **loops = (is_continue ? parser->continues : parser->breaks);
2904 (void)block; /* not touching */
2905 if (!parser_next(parser)) {
2906 parseerror(parser, "expected semicolon or loop label");
2910 if (!vec_size(loops)) {
2912 parseerror(parser, "`continue` can only be used inside loops");
2914 parseerror(parser, "`break` can only be used inside loops or switches");
2917 if (parser->tok == TOKEN_IDENT) {
2918 if (!OPTS_FLAG(LOOP_LABELS))
2919 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2920 i = vec_size(loops);
2922 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2925 parseerror(parser, "no such loop to %s: `%s`",
2926 (is_continue ? "continue" : "break out of"),
2927 parser_tokval(parser));
2932 if (!parser_next(parser)) {
2933 parseerror(parser, "expected semicolon");
2938 if (parser->tok != ';') {
2939 parseerror(parser, "expected semicolon");
2943 if (!parser_next(parser))
2944 parseerror(parser, "parse error");
2946 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2950 /* returns true when it was a variable qualifier, false otherwise!
2951 * on error, cvq is set to CV_WRONG
2953 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2955 bool had_const = false;
2956 bool had_var = false;
2957 bool had_noref = false;
2958 bool had_attrib = false;
2959 bool had_static = false;
2964 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2966 /* parse an attribute */
2967 if (!parser_next(parser)) {
2968 parseerror(parser, "expected attribute after `[[`");
2972 if (!strcmp(parser_tokval(parser), "noreturn")) {
2973 flags |= AST_FLAG_NORETURN;
2974 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2975 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2980 else if (!strcmp(parser_tokval(parser), "noref")) {
2982 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2983 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2988 else if (!strcmp(parser_tokval(parser), "inline")) {
2989 flags |= AST_FLAG_INLINE;
2990 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2991 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2996 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2997 flags |= AST_FLAG_ALIAS;
3000 if (!parser_next(parser)) {
3001 parseerror(parser, "parse error in attribute");
3005 if (parser->tok == '(') {
3006 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3007 parseerror(parser, "`alias` attribute missing parameter");
3011 *message = util_strdup(parser_tokval(parser));
3013 if (!parser_next(parser)) {
3014 parseerror(parser, "parse error in attribute");
3018 if (parser->tok != ')') {
3019 parseerror(parser, "`alias` attribute expected `)` after parameter");
3023 if (!parser_next(parser)) {
3024 parseerror(parser, "parse error in attribute");
3029 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3030 parseerror(parser, "`alias` attribute expected `]]`");
3034 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3035 flags |= AST_FLAG_DEPRECATED;
3038 if (!parser_next(parser)) {
3039 parseerror(parser, "parse error in attribute");
3043 if (parser->tok == '(') {
3044 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3045 parseerror(parser, "`deprecated` attribute missing parameter");
3049 *message = util_strdup(parser_tokval(parser));
3051 if (!parser_next(parser)) {
3052 parseerror(parser, "parse error in attribute");
3056 if(parser->tok != ')') {
3057 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3061 if (!parser_next(parser)) {
3062 parseerror(parser, "parse error in attribute");
3067 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3068 parseerror(parser, "`deprecated` attribute expected `]]`");
3071 if (*message) mem_d(*message);
3079 /* Skip tokens until we hit a ]] */
3080 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3081 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3082 if (!parser_next(parser)) {
3083 parseerror(parser, "error inside attribute");
3090 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3092 else if (!strcmp(parser_tokval(parser), "const"))
3094 else if (!strcmp(parser_tokval(parser), "var"))
3096 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3098 else if (!strcmp(parser_tokval(parser), "noref"))
3100 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3105 if (!parser_next(parser))
3115 *is_static = had_static;
3119 parseerror(parser, "parse error after variable qualifier");
3124 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3125 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3130 /* skip the 'while' and get the body */
3131 if (!parser_next(parser)) {
3132 if (OPTS_FLAG(LOOP_LABELS))
3133 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3135 parseerror(parser, "expected 'switch' operand in parenthesis");
3139 if (parser->tok == ':') {
3140 if (!OPTS_FLAG(LOOP_LABELS))
3141 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3142 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3143 parseerror(parser, "expected loop label");
3146 label = util_strdup(parser_tokval(parser));
3147 if (!parser_next(parser)) {
3149 parseerror(parser, "expected 'switch' operand in parenthesis");
3154 if (parser->tok != '(') {
3155 parseerror(parser, "expected 'switch' operand in parenthesis");
3159 vec_push(parser->breaks, label);
3161 rv = parse_switch_go(parser, block, out);
3164 if (vec_last(parser->breaks) != label) {
3165 parseerror(parser, "internal error: label stack corrupted");
3171 vec_pop(parser->breaks);
3176 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3178 ast_expression *operand;
3181 ast_switch *switchnode;
3182 ast_switch_case swcase;
3185 bool noref, is_static;
3186 uint32_t qflags = 0;
3188 lex_ctx ctx = parser_ctx(parser);
3190 (void)block; /* not touching */
3193 /* parse into the expression */
3194 if (!parser_next(parser)) {
3195 parseerror(parser, "expected switch operand");
3198 /* parse the operand */
3199 operand = parse_expression_leave(parser, false, false, false);
3203 switchnode = ast_switch_new(ctx, operand);
3206 if (parser->tok != ')') {
3207 ast_delete(switchnode);
3208 parseerror(parser, "expected closing paren after 'switch' operand");
3212 /* parse over the opening paren */
3213 if (!parser_next(parser) || parser->tok != '{') {
3214 ast_delete(switchnode);
3215 parseerror(parser, "expected list of cases");
3219 if (!parser_next(parser)) {
3220 ast_delete(switchnode);
3221 parseerror(parser, "expected 'case' or 'default'");
3225 /* new block; allow some variables to be declared here */
3226 parser_enterblock(parser);
3229 if (parser->tok == TOKEN_IDENT)
3230 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3231 if (typevar || parser->tok == TOKEN_TYPENAME) {
3232 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3233 ast_delete(switchnode);
3238 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3240 if (cvq == CV_WRONG) {
3241 ast_delete(switchnode);
3244 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3245 ast_delete(switchnode);
3254 while (parser->tok != '}') {
3255 ast_block *caseblock;
3257 if (!strcmp(parser_tokval(parser), "case")) {
3258 if (!parser_next(parser)) {
3259 ast_delete(switchnode);
3260 parseerror(parser, "expected expression for case");
3263 swcase.value = parse_expression_leave(parser, false, false, false);
3264 if (!swcase.value) {
3265 ast_delete(switchnode);
3266 parseerror(parser, "expected expression for case");
3269 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3270 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3271 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3277 else if (!strcmp(parser_tokval(parser), "default")) {
3278 swcase.value = NULL;
3279 if (!parser_next(parser)) {
3280 ast_delete(switchnode);
3281 parseerror(parser, "expected colon");
3286 ast_delete(switchnode);
3287 parseerror(parser, "expected 'case' or 'default'");
3291 /* Now the colon and body */
3292 if (parser->tok != ':') {
3293 if (swcase.value) ast_unref(swcase.value);
3294 ast_delete(switchnode);
3295 parseerror(parser, "expected colon");
3299 if (!parser_next(parser)) {
3300 if (swcase.value) ast_unref(swcase.value);
3301 ast_delete(switchnode);
3302 parseerror(parser, "expected statements or case");
3305 caseblock = ast_block_new(parser_ctx(parser));
3307 if (swcase.value) ast_unref(swcase.value);
3308 ast_delete(switchnode);
3311 swcase.code = (ast_expression*)caseblock;
3312 vec_push(switchnode->cases, swcase);
3314 ast_expression *expr;
3315 if (parser->tok == '}')
3317 if (parser->tok == TOKEN_KEYWORD) {
3318 if (!strcmp(parser_tokval(parser), "case") ||
3319 !strcmp(parser_tokval(parser), "default"))
3324 if (!parse_statement(parser, caseblock, &expr, true)) {
3325 ast_delete(switchnode);
3330 if (!ast_block_add_expr(caseblock, expr)) {
3331 ast_delete(switchnode);
3337 parser_leaveblock(parser);
3340 if (parser->tok != '}') {
3341 ast_delete(switchnode);
3342 parseerror(parser, "expected closing paren of case list");
3345 if (!parser_next(parser)) {
3346 ast_delete(switchnode);
3347 parseerror(parser, "parse error after switch");
3350 *out = (ast_expression*)switchnode;
3354 ast_expression *parser_builtin_pow(parser_t *parser) {
3356 * float __builtin_pow(float x, float y) {
3357 * float value = 1.0f;
3369 static ast_function *pow_func = NULL;
3370 static ast_value *pow_func_val = NULL;
3372 ast_value *pow_arguments[2];
3373 ast_value *pow_value = ast_value_new (parser_ctx(parser), "value", TYPE_FLOAT);
3374 ast_block *pow_body = ast_block_new (parser_ctx(parser));
3375 ast_block *pow_loop_body = ast_block_new (parser_ctx(parser));
3376 ast_block *pow_loop_nest_body = ast_block_new (parser_ctx(parser));
3377 ast_loop *pow_loop = NULL;
3378 ast_loop *pow_loop_nest = NULL;
3380 pow_arguments[0] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3381 pow_arguments[1] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3382 pow_func_val = ast_value_new (parser_ctx(parser), "__builtin_pow", TYPE_FUNCTION);
3383 pow_func_val->expression.next = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
3385 vec_push(pow_func_val->expression.params, pow_arguments[0]);
3386 vec_push(pow_func_val->expression.params, pow_arguments[1]);
3388 pow_func = ast_function_new(parser_ctx(parser), "__builtin_pow", pow_func_val);
3391 vec_push(pow_body->locals, pow_value);
3393 vec_push(pow_body->exprs,
3394 (ast_expression*)ast_store_new(
3397 (ast_expression*)pow_value,
3398 (ast_expression*)parser_const_float_1(parser)
3403 vec_push(pow_loop_nest_body->exprs,
3404 (ast_expression*)ast_binstore_new(
3408 (ast_expression*)pow_arguments[1],
3409 (ast_expression*)parser_const_float(parser, 0.25f)
3412 vec_push(pow_loop_nest_body->exprs,
3413 (ast_expression*)ast_binstore_new(
3417 (ast_expression*)pow_arguments[0],
3418 (ast_expression*)pow_arguments[0]
3422 /* while (!(y&1)) */
3423 pow_loop_nest = ast_loop_new (
3426 (ast_expression*)ast_binary_new(
3429 (ast_expression*)pow_arguments[1],
3430 (ast_expression*)parser_const_float_1(parser)
3436 (ast_expression*)pow_loop_nest_body
3439 vec_push(pow_loop_body->exprs, (ast_expression*)pow_loop_nest);
3440 vec_push(pow_loop_body->exprs,
3441 (ast_expression*)ast_binstore_new(
3445 (ast_expression*)pow_arguments[1],
3446 (ast_expression*)parser_const_float_1(parser)
3449 vec_push(pow_loop_body->exprs,
3450 (ast_expression*)ast_binstore_new(
3454 (ast_expression*)pow_value,
3455 (ast_expression*)pow_arguments[0]
3459 /* while (y > 0) { */
3460 pow_loop = ast_loop_new(
3463 (ast_expression*)ast_binary_new(
3466 (ast_expression*)pow_arguments[1],
3467 (ast_expression*)parser_const_float_0(parser)
3473 (ast_expression*)pow_loop_body
3476 vec_push(pow_body->exprs, (ast_expression*)pow_loop);
3478 vec_push(pow_body->exprs,
3479 (ast_expression*)ast_return_new(
3481 (ast_expression*)pow_value
3485 vec_push(pow_func->blocks, pow_body);
3486 vec_push(parser->globals, (ast_expression*)pow_func_val);
3487 vec_push(parser->functions, pow_func);
3490 return (ast_expression*)pow_func_val;
3494 #define M_E 2.71828182845905
3496 static ast_expression *parser_builtin_exp(parser_t *parser) {
3498 * float __builtin_exp(float x) {
3499 * return __builtin_exp(E, x);
3502 static ast_value *exp_func_val = NULL;
3504 if (!exp_func_val) {
3505 ast_function *exp_func = NULL;
3506 ast_value *arg = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3507 ast_block *exp_body = ast_block_new (parser_ctx(parser));
3508 ast_call *exp_call = ast_call_new (parser_ctx(parser), parser_builtin_pow(parser));
3509 exp_func_val = ast_value_new (parser_ctx(parser), "__builtin_exp", TYPE_FUNCTION);
3510 exp_func_val->expression.next = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
3511 exp_func = ast_function_new(parser_ctx(parser), "__builtin_exp", exp_func_val);
3513 vec_push(exp_call->params, (ast_expression*)parser_const_float(parser, M_E));
3514 vec_push(exp_call->params, (ast_expression*)arg);
3516 vec_push(exp_body->exprs,
3517 (ast_expression*)ast_return_new(
3519 (ast_expression*)exp_call
3523 vec_push(exp_func_val->expression.params, arg);
3524 vec_push(exp_func->blocks, exp_body);
3526 vec_push(parser->functions, exp_func);
3527 vec_push(parser->globals, (ast_expression*)exp_func_val);
3530 return (ast_expression*)exp_func_val;
3533 static ast_expression *parser_builtin_mod(parser_t *parser) {
3535 * float __builtin_mod(float x, float y) {
3536 * return x - y * floor(x / y);
3539 static ast_value *mod_func_val = NULL;
3540 static ast_expression *mod_floor = NULL;
3543 if (!(mod_floor = parser_find_global(parser, "floor"))) {
3545 "internal error: no suitable definition found for `floor`"
3546 "(required for `%%` operator and `__builtin_mod` intrinsic)"
3552 if (!mod_func_val) {
3553 ast_value *mod_args[2];
3554 ast_function *mod_func = NULL;
3555 ast_block *mod_body = ast_block_new (parser_ctx(parser));
3556 ast_call *mod_call = ast_call_new (parser_ctx(parser), mod_floor);
3557 mod_func_val = ast_value_new (parser_ctx(parser), "__builtin_mod", TYPE_FUNCTION);
3558 mod_func_val->expression.next = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
3559 mod_func = ast_function_new(parser_ctx(parser), "__builtin_mod", mod_func_val);
3560 mod_args[0] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3561 mod_args[1] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3564 vec_push(mod_call->params,
3565 (ast_expression*)ast_binary_new(
3568 (ast_expression*)mod_args[0],
3569 (ast_expression*)mod_args[1]
3573 vec_push(mod_body->exprs,
3574 (ast_expression*)ast_return_new(
3576 (ast_expression*)ast_binary_new(
3579 (ast_expression*)mod_args[0],
3580 (ast_expression*)ast_binary_new(
3583 (ast_expression*)mod_args[1],
3584 (ast_expression*)mod_call
3590 vec_push(mod_func_val->expression.params, mod_args[0]);
3591 vec_push(mod_func_val->expression.params, mod_args[1]);
3593 vec_push(mod_func->blocks, mod_body);
3595 vec_push(parser->functions, mod_func);
3596 vec_push(parser->globals, (ast_expression*)mod_func_val);
3599 return (ast_expression*)mod_func_val;
3602 /* parse computed goto sides */
3603 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3604 ast_expression *on_true;
3605 ast_expression *on_false;
3606 ast_expression *cond;
3611 if (ast_istype(*side, ast_ternary)) {
3612 ast_ternary *tern = (ast_ternary*)*side;
3613 on_true = parse_goto_computed(parser, &tern->on_true);
3614 on_false = parse_goto_computed(parser, &tern->on_false);
3616 if (!on_true || !on_false) {
3617 parseerror(parser, "expected label or expression in ternary");
3618 if (on_true) ast_unref(on_true);
3619 if (on_false) ast_unref(on_false);
3627 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3628 } else if (ast_istype(*side, ast_label)) {
3629 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3630 ast_goto_set_label(gt, ((ast_label*)*side));
3632 return (ast_expression*)gt;
3637 static bool parse_goto(parser_t *parser, ast_expression **out)
3639 ast_goto *gt = NULL;
3640 ast_expression *lbl;
3642 if (!parser_next(parser))
3645 if (parser->tok != TOKEN_IDENT) {
3646 ast_expression *expression;
3648 /* could be an expression i.e computed goto :-) */
3649 if (parser->tok != '(') {
3650 parseerror(parser, "expected label name after `goto`");
3654 /* failed to parse expression for goto */
3655 if (!(expression = parse_expression(parser, false, true)) ||
3656 !(*out = parse_goto_computed(parser, &expression))) {
3657 parseerror(parser, "invalid goto expression");
3658 ast_unref(expression);
3665 /* not computed goto */
3666 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3667 lbl = parser_find_label(parser, gt->name);
3669 if (!ast_istype(lbl, ast_label)) {
3670 parseerror(parser, "internal error: label is not an ast_label");
3674 ast_goto_set_label(gt, (ast_label*)lbl);
3677 vec_push(parser->gotos, gt);
3679 if (!parser_next(parser) || parser->tok != ';') {
3680 parseerror(parser, "semicolon expected after goto label");
3683 if (!parser_next(parser)) {
3684 parseerror(parser, "parse error after goto");
3688 *out = (ast_expression*)gt;
3692 static bool parse_skipwhite(parser_t *parser)
3695 if (!parser_next(parser))
3697 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3698 return parser->tok < TOKEN_ERROR;
3701 static bool parse_eol(parser_t *parser)
3703 if (!parse_skipwhite(parser))
3705 return parser->tok == TOKEN_EOL;
3708 static bool parse_pragma_do(parser_t *parser)
3710 if (!parser_next(parser) ||
3711 parser->tok != TOKEN_IDENT ||
3712 strcmp(parser_tokval(parser), "pragma"))
3714 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3717 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3718 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3722 if (!strcmp(parser_tokval(parser), "noref")) {
3723 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3724 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3727 parser->noref = !!parser_token(parser)->constval.i;
3728 if (!parse_eol(parser)) {
3729 parseerror(parser, "parse error after `noref` pragma");
3735 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3742 static bool parse_pragma(parser_t *parser)
3745 parser->lex->flags.preprocessing = true;
3746 parser->lex->flags.mergelines = true;
3747 rv = parse_pragma_do(parser);
3748 if (parser->tok != TOKEN_EOL) {
3749 parseerror(parser, "junk after pragma");
3752 parser->lex->flags.preprocessing = false;
3753 parser->lex->flags.mergelines = false;
3754 if (!parser_next(parser)) {
3755 parseerror(parser, "parse error after pragma");
3761 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3763 bool noref, is_static;
3765 uint32_t qflags = 0;
3766 ast_value *typevar = NULL;
3767 char *vstring = NULL;
3771 if (parser->tok == TOKEN_IDENT)
3772 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3774 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3776 /* local variable */
3778 parseerror(parser, "cannot declare a variable from here");
3781 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3782 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3785 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3789 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3791 if (cvq == CV_WRONG)
3793 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3795 else if (parser->tok == TOKEN_KEYWORD)
3797 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3802 if (!parser_next(parser)) {
3803 parseerror(parser, "parse error after __builtin_debug_printtype");
3807 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3809 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3810 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3811 if (!parser_next(parser)) {
3812 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3818 if (!parse_statement(parser, block, out, allow_cases))
3821 con_out("__builtin_debug_printtype: got no output node\n");
3824 ast_type_to_string(*out, ty, sizeof(ty));
3825 con_out("__builtin_debug_printtype: `%s`\n", ty);
3830 else if (!strcmp(parser_tokval(parser), "return"))
3832 return parse_return(parser, block, out);
3834 else if (!strcmp(parser_tokval(parser), "if"))
3836 return parse_if(parser, block, out);
3838 else if (!strcmp(parser_tokval(parser), "while"))
3840 return parse_while(parser, block, out);
3842 else if (!strcmp(parser_tokval(parser), "do"))
3844 return parse_dowhile(parser, block, out);
3846 else if (!strcmp(parser_tokval(parser), "for"))
3848 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3849 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3852 return parse_for(parser, block, out);
3854 else if (!strcmp(parser_tokval(parser), "break"))
3856 return parse_break_continue(parser, block, out, false);
3858 else if (!strcmp(parser_tokval(parser), "continue"))
3860 return parse_break_continue(parser, block, out, true);
3862 else if (!strcmp(parser_tokval(parser), "switch"))
3864 return parse_switch(parser, block, out);
3866 else if (!strcmp(parser_tokval(parser), "case") ||
3867 !strcmp(parser_tokval(parser), "default"))
3870 parseerror(parser, "unexpected 'case' label");
3875 else if (!strcmp(parser_tokval(parser), "goto"))
3877 return parse_goto(parser, out);
3879 else if (!strcmp(parser_tokval(parser), "typedef"))
3881 if (!parser_next(parser)) {
3882 parseerror(parser, "expected type definition after 'typedef'");
3885 return parse_typedef(parser);
3887 parseerror(parser, "Unexpected keyword");
3890 else if (parser->tok == '{')
3893 inner = parse_block(parser);
3896 *out = (ast_expression*)inner;
3899 else if (parser->tok == ':')
3903 if (!parser_next(parser)) {
3904 parseerror(parser, "expected label name");
3907 if (parser->tok != TOKEN_IDENT) {
3908 parseerror(parser, "label must be an identifier");
3911 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3913 if (!label->undefined) {
3914 parseerror(parser, "label `%s` already defined", label->name);
3917 label->undefined = false;
3920 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3921 vec_push(parser->labels, label);
3923 *out = (ast_expression*)label;
3924 if (!parser_next(parser)) {
3925 parseerror(parser, "parse error after label");
3928 for (i = 0; i < vec_size(parser->gotos); ++i) {
3929 if (!strcmp(parser->gotos[i]->name, label->name)) {
3930 ast_goto_set_label(parser->gotos[i], label);
3931 vec_remove(parser->gotos, i, 1);
3937 else if (parser->tok == ';')
3939 if (!parser_next(parser)) {
3940 parseerror(parser, "parse error after empty statement");
3947 lex_ctx ctx = parser_ctx(parser);
3948 ast_expression *exp = parse_expression(parser, false, false);
3952 if (!ast_side_effects(exp)) {
3953 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3960 static bool parse_enum(parser_t *parser)
3963 bool reverse = false;
3965 ast_value **values = NULL;
3966 ast_value *var = NULL;
3969 ast_expression *old;
3971 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3972 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3976 /* enumeration attributes (can add more later) */
3977 if (parser->tok == ':') {
3978 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3979 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3984 if (!strcmp(parser_tokval(parser), "flag")) {
3988 else if (!strcmp(parser_tokval(parser), "reverse")) {
3992 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3996 if (!parser_next(parser) || parser->tok != '{') {
3997 parseerror(parser, "expected `{` after enum attribute ");
4003 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
4004 if (parser->tok == '}') {
4005 /* allow an empty enum */
4008 parseerror(parser, "expected identifier or `}`");
4012 old = parser_find_field(parser, parser_tokval(parser));
4014 old = parser_find_global(parser, parser_tokval(parser));
4016 parseerror(parser, "value `%s` has already been declared here: %s:%i",
4017 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
4021 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
4022 vec_push(values, var);
4023 var->cvq = CV_CONST;
4024 var->hasvalue = true;
4026 /* for flagged enumerations increment in POTs of TWO */
4027 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
4028 parser_addglobal(parser, var->name, (ast_expression*)var);
4030 if (!parser_next(parser)) {
4031 parseerror(parser, "expected `=`, `}` or comma after identifier");
4035 if (parser->tok == ',')
4037 if (parser->tok == '}')
4039 if (parser->tok != '=') {
4040 parseerror(parser, "expected `=`, `}` or comma after identifier");
4044 if (!parser_next(parser)) {
4045 parseerror(parser, "expected expression after `=`");
4049 /* We got a value! */
4050 old = parse_expression_leave(parser, true, false, false);
4051 asvalue = (ast_value*)old;
4052 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4053 compile_error(ast_ctx(var), "constant value or expression expected");
4056 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4058 if (parser->tok == '}')
4060 if (parser->tok != ',') {
4061 parseerror(parser, "expected `}` or comma after expression");
4066 /* patch them all (for reversed attribute) */
4069 for (i = 0; i < vec_size(values); i++)
4070 values[i]->constval.vfloat = vec_size(values) - i - 1;
4073 if (parser->tok != '}') {
4074 parseerror(parser, "internal error: breaking without `}`");
4078 if (!parser_next(parser) || parser->tok != ';') {
4079 parseerror(parser, "expected semicolon after enumeration");
4083 if (!parser_next(parser)) {
4084 parseerror(parser, "parse error after enumeration");
4096 static bool parse_block_into(parser_t *parser, ast_block *block)
4100 parser_enterblock(parser);
4102 if (!parser_next(parser)) { /* skip the '{' */
4103 parseerror(parser, "expected function body");
4107 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4109 ast_expression *expr = NULL;
4110 if (parser->tok == '}')
4113 if (!parse_statement(parser, block, &expr, false)) {
4114 /* parseerror(parser, "parse error"); */
4120 if (!ast_block_add_expr(block, expr)) {
4127 if (parser->tok != '}') {
4130 (void)parser_next(parser);
4134 if (!parser_leaveblock(parser))
4136 return retval && !!block;
4139 static ast_block* parse_block(parser_t *parser)
4142 block = ast_block_new(parser_ctx(parser));
4145 if (!parse_block_into(parser, block)) {
4146 ast_block_delete(block);
4152 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4154 if (parser->tok == '{') {
4155 *out = (ast_expression*)parse_block(parser);
4158 return parse_statement(parser, NULL, out, false);
4161 static bool create_vector_members(ast_value *var, ast_member **me)
4164 size_t len = strlen(var->name);
4166 for (i = 0; i < 3; ++i) {
4167 char *name = (char*)mem_a(len+3);
4168 memcpy(name, var->name, len);
4170 name[len+1] = 'x'+i;
4172 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4181 do { ast_member_delete(me[--i]); } while(i);
4185 static bool parse_function_body(parser_t *parser, ast_value *var)
4187 ast_block *block = NULL;
4192 ast_expression *framenum = NULL;
4193 ast_expression *nextthink = NULL;
4194 /* None of the following have to be deleted */
4195 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4196 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4197 bool has_frame_think;
4201 has_frame_think = false;
4202 old = parser->function;
4204 if (var->expression.flags & AST_FLAG_ALIAS) {
4205 parseerror(parser, "function aliases cannot have bodies");
4209 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4210 parseerror(parser, "gotos/labels leaking");
4214 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4215 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4216 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4222 if (parser->tok == '[') {
4223 /* got a frame definition: [ framenum, nextthink ]
4224 * this translates to:
4225 * self.frame = framenum;
4226 * self.nextthink = time + 0.1;
4227 * self.think = nextthink;
4231 fld_think = parser_find_field(parser, "think");
4232 fld_nextthink = parser_find_field(parser, "nextthink");
4233 fld_frame = parser_find_field(parser, "frame");
4234 if (!fld_think || !fld_nextthink || !fld_frame) {
4235 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4236 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4239 gbl_time = parser_find_global(parser, "time");
4240 gbl_self = parser_find_global(parser, "self");
4241 if (!gbl_time || !gbl_self) {
4242 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4243 parseerror(parser, "please declare the following globals: `time`, `self`");
4247 if (!parser_next(parser))
4250 framenum = parse_expression_leave(parser, true, false, false);
4252 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4255 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4256 ast_unref(framenum);
4257 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4261 if (parser->tok != ',') {
4262 ast_unref(framenum);
4263 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4264 parseerror(parser, "Got a %i\n", parser->tok);
4268 if (!parser_next(parser)) {
4269 ast_unref(framenum);
4273 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4275 /* qc allows the use of not-yet-declared functions here
4276 * - this automatically creates a prototype */
4277 ast_value *thinkfunc;
4278 ast_expression *functype = fld_think->expression.next;
4280 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4281 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4282 ast_unref(framenum);
4283 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4286 ast_type_adopt(thinkfunc, functype);
4288 if (!parser_next(parser)) {
4289 ast_unref(framenum);
4290 ast_delete(thinkfunc);
4294 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4296 nextthink = (ast_expression*)thinkfunc;
4299 nextthink = parse_expression_leave(parser, true, false, false);
4301 ast_unref(framenum);
4302 parseerror(parser, "expected a think-function in [frame,think] notation");
4307 if (!ast_istype(nextthink, ast_value)) {
4308 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4312 if (retval && parser->tok != ']') {
4313 parseerror(parser, "expected closing `]` for [frame,think] notation");
4317 if (retval && !parser_next(parser)) {
4321 if (retval && parser->tok != '{') {
4322 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4327 ast_unref(nextthink);
4328 ast_unref(framenum);
4332 has_frame_think = true;
4335 block = ast_block_new(parser_ctx(parser));
4337 parseerror(parser, "failed to allocate block");
4338 if (has_frame_think) {
4339 ast_unref(nextthink);
4340 ast_unref(framenum);
4345 if (has_frame_think) {
4347 ast_expression *self_frame;
4348 ast_expression *self_nextthink;
4349 ast_expression *self_think;
4350 ast_expression *time_plus_1;
4351 ast_store *store_frame;
4352 ast_store *store_nextthink;
4353 ast_store *store_think;
4355 ctx = parser_ctx(parser);
4356 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4357 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4358 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4360 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4361 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4363 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4364 if (self_frame) ast_delete(self_frame);
4365 if (self_nextthink) ast_delete(self_nextthink);
4366 if (self_think) ast_delete(self_think);
4367 if (time_plus_1) ast_delete(time_plus_1);
4373 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4374 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4375 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4378 ast_delete(self_frame);
4381 if (!store_nextthink) {
4382 ast_delete(self_nextthink);
4386 ast_delete(self_think);
4390 if (store_frame) ast_delete(store_frame);
4391 if (store_nextthink) ast_delete(store_nextthink);
4392 if (store_think) ast_delete(store_think);
4395 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4396 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4397 !ast_block_add_expr(block, (ast_expression*)store_think))
4404 parseerror(parser, "failed to generate code for [frame,think]");
4405 ast_unref(nextthink);
4406 ast_unref(framenum);
4412 if (var->hasvalue) {
4413 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4414 ast_block_delete(block);
4418 func = ast_function_new(ast_ctx(var), var->name, var);
4420 parseerror(parser, "failed to allocate function for `%s`", var->name);
4421 ast_block_delete(block);
4424 vec_push(parser->functions, func);
4426 parser_enterblock(parser);
4428 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4430 ast_value *param = var->expression.params[parami];
4433 if (param->expression.vtype != TYPE_VECTOR &&
4434 (param->expression.vtype != TYPE_FIELD ||
4435 param->expression.next->expression.vtype != TYPE_VECTOR))
4440 if (!create_vector_members(param, me)) {
4441 ast_block_delete(block);
4445 for (e = 0; e < 3; ++e) {
4446 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4447 ast_block_collect(block, (ast_expression*)me[e]);
4451 if (var->argcounter) {
4452 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4453 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4457 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4459 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4460 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4461 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4462 varargs->expression.count = 0;
4463 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4464 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4465 ast_delete(varargs);
4466 ast_block_delete(block);
4469 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4470 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4471 ast_delete(varargs);
4472 ast_block_delete(block);
4475 func->varargs = varargs;
4477 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4480 parser->function = func;
4481 if (!parse_block_into(parser, block)) {
4482 ast_block_delete(block);
4486 vec_push(func->blocks, block);
4488 parser->function = old;
4489 if (!parser_leaveblock(parser))
4491 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4492 parseerror(parser, "internal error: local scopes left");
4496 if (parser->tok == ';')
4497 return parser_next(parser);
4498 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4499 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4503 (void)!parser_leaveblock(parser);
4504 vec_pop(parser->functions);
4505 ast_function_delete(func);
4506 var->constval.vfunc = NULL;
4509 parser->function = old;
4513 static ast_expression *array_accessor_split(
4518 ast_expression *left,
4519 ast_expression *right
4525 lex_ctx ctx = ast_ctx(array);
4527 if (!left || !right) {
4528 if (left) ast_delete(left);
4529 if (right) ast_delete(right);
4533 cmp = ast_binary_new(ctx, INSTR_LT,
4534 (ast_expression*)index,
4535 (ast_expression*)parser_const_float(parser, middle));
4539 parseerror(parser, "internal error: failed to create comparison for array setter");
4543 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4545 ast_delete(cmp); /* will delete left and right */
4546 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4550 return (ast_expression*)ifthen;
4553 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4555 lex_ctx ctx = ast_ctx(array);
4557 if (from+1 == afterend) {
4558 /* set this value */
4561 ast_array_index *subscript;
4563 int assignop = type_store_instr[value->expression.vtype];
4565 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4566 assignop = INSTR_STORE_V;
4568 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4572 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4574 ast_delete(subscript);
4578 block = ast_block_new(ctx);
4584 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4589 ret = ast_return_new(ctx, NULL);
4595 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4600 return (ast_expression*)block;
4602 ast_expression *left, *right;
4603 size_t diff = afterend - from;
4604 size_t middle = from + diff/2;
4605 left = array_setter_node(parser, array, index, value, from, middle);
4606 right = array_setter_node(parser, array, index, value, middle, afterend);
4607 return array_accessor_split(parser, array, index, middle, left, right);
4611 static ast_expression *array_field_setter_node(
4620 lex_ctx ctx = ast_ctx(array);
4622 if (from+1 == afterend) {
4623 /* set this value */
4626 ast_entfield *entfield;
4627 ast_array_index *subscript;
4629 int assignop = type_storep_instr[value->expression.vtype];
4631 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4632 assignop = INSTR_STOREP_V;
4634 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4638 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4639 subscript->expression.vtype = TYPE_FIELD;
4641 entfield = ast_entfield_new_force(ctx,
4642 (ast_expression*)entity,
4643 (ast_expression*)subscript,
4644 (ast_expression*)subscript);
4646 ast_delete(subscript);
4650 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4652 ast_delete(entfield);
4656 block = ast_block_new(ctx);
4662 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4667 ret = ast_return_new(ctx, NULL);
4673 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4678 return (ast_expression*)block;
4680 ast_expression *left, *right;
4681 size_t diff = afterend - from;
4682 size_t middle = from + diff/2;
4683 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4684 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4685 return array_accessor_split(parser, array, index, middle, left, right);
4689 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4691 lex_ctx ctx = ast_ctx(array);
4693 if (from+1 == afterend) {
4695 ast_array_index *subscript;
4697 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4701 ret = ast_return_new(ctx, (ast_expression*)subscript);
4703 ast_delete(subscript);
4707 return (ast_expression*)ret;
4709 ast_expression *left, *right;
4710 size_t diff = afterend - from;
4711 size_t middle = from + diff/2;
4712 left = array_getter_node(parser, array, index, from, middle);
4713 right = array_getter_node(parser, array, index, middle, afterend);
4714 return array_accessor_split(parser, array, index, middle, left, right);
4718 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4720 ast_function *func = NULL;
4721 ast_value *fval = NULL;
4722 ast_block *body = NULL;
4724 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4726 parseerror(parser, "failed to create accessor function value");
4730 func = ast_function_new(ast_ctx(array), funcname, fval);
4733 parseerror(parser, "failed to create accessor function node");
4737 body = ast_block_new(ast_ctx(array));
4739 parseerror(parser, "failed to create block for array accessor");
4745 vec_push(func->blocks, body);
4748 vec_push(parser->accessors, fval);
4753 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4755 ast_value *index = NULL;
4756 ast_value *value = NULL;
4760 if (!ast_istype(array->expression.next, ast_value)) {
4761 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4765 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4767 func = fval->constval.vfunc;
4768 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4770 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4771 value = ast_value_copy((ast_value*)array->expression.next);
4773 if (!index || !value) {
4774 parseerror(parser, "failed to create locals for array accessor");
4777 (void)!ast_value_set_name(value, "value"); /* not important */
4778 vec_push(fval->expression.params, index);
4779 vec_push(fval->expression.params, value);
4781 array->setter = fval;
4784 if (index) ast_delete(index);
4785 if (value) ast_delete(value);
4791 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4793 ast_expression *root = NULL;
4794 root = array_setter_node(parser, array,
4795 array->setter->expression.params[0],
4796 array->setter->expression.params[1],
4797 0, array->expression.count);
4799 parseerror(parser, "failed to build accessor search tree");
4802 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4809 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4811 if (!parser_create_array_setter_proto(parser, array, funcname))
4813 return parser_create_array_setter_impl(parser, array);
4816 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4818 ast_expression *root = NULL;
4819 ast_value *entity = NULL;
4820 ast_value *index = NULL;
4821 ast_value *value = NULL;
4825 if (!ast_istype(array->expression.next, ast_value)) {
4826 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4830 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4832 func = fval->constval.vfunc;
4833 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4835 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4836 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4837 value = ast_value_copy((ast_value*)array->expression.next);
4838 if (!entity || !index || !value) {
4839 parseerror(parser, "failed to create locals for array accessor");
4842 (void)!ast_value_set_name(value, "value"); /* not important */
4843 vec_push(fval->expression.params, entity);
4844 vec_push(fval->expression.params, index);
4845 vec_push(fval->expression.params, value);
4847 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4849 parseerror(parser, "failed to build accessor search tree");
4853 array->setter = fval;
4854 return ast_block_add_expr(func->blocks[0], root);
4856 if (entity) ast_delete(entity);
4857 if (index) ast_delete(index);
4858 if (value) ast_delete(value);
4859 if (root) ast_delete(root);
4865 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4867 ast_value *index = NULL;
4871 /* NOTE: checking array->expression.next rather than elemtype since
4872 * for fields elemtype is a temporary fieldtype.
4874 if (!ast_istype(array->expression.next, ast_value)) {
4875 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4879 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4881 func = fval->constval.vfunc;
4882 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4884 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4887 parseerror(parser, "failed to create locals for array accessor");
4890 vec_push(fval->expression.params, index);
4892 array->getter = fval;
4895 if (index) ast_delete(index);
4901 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4903 ast_expression *root = NULL;
4905 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4907 parseerror(parser, "failed to build accessor search tree");
4910 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4917 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4919 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4921 return parser_create_array_getter_impl(parser, array);
4924 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4925 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4933 bool variadic = false;
4934 ast_value *varparam = NULL;
4935 char *argcounter = NULL;
4937 ctx = parser_ctx(parser);
4939 /* for the sake of less code we parse-in in this function */
4940 if (!parser_next(parser)) {
4941 parseerror(parser, "expected parameter list");
4947 /* parse variables until we hit a closing paren */
4948 while (parser->tok != ')') {
4950 /* there must be commas between them */
4951 if (parser->tok != ',') {
4952 parseerror(parser, "expected comma or end of parameter list");
4955 if (!parser_next(parser)) {
4956 parseerror(parser, "expected parameter");
4962 if (parser->tok == TOKEN_DOTS) {
4963 /* '...' indicates a varargs function */
4965 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4966 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4969 if (parser->tok == TOKEN_IDENT) {
4970 argcounter = util_strdup(parser_tokval(parser));
4971 if (!parser_next(parser) || parser->tok != ')') {
4972 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4979 /* for anything else just parse a typename */
4980 param = parse_typename(parser, NULL, NULL);
4983 vec_push(params, param);
4984 if (param->expression.vtype >= TYPE_VARIANT) {
4985 char tname[1024]; /* typename is reserved in C++ */
4986 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4987 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4990 /* type-restricted varargs */
4991 if (parser->tok == TOKEN_DOTS) {
4993 varparam = vec_last(params);
4995 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4996 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4999 if (parser->tok == TOKEN_IDENT) {
5000 argcounter = util_strdup(parser_tokval(parser));
5001 if (!parser_next(parser) || parser->tok != ')') {
5002 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
5010 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
5014 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5015 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
5018 if (!parser_next(parser)) {
5019 parseerror(parser, "parse error after typename");
5023 /* now turn 'var' into a function type */
5024 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
5025 fval->expression.next = (ast_expression*)var;
5027 fval->expression.flags |= AST_FLAG_VARIADIC;
5030 var->expression.params = params;
5031 var->expression.varparam = (ast_expression*)varparam;
5032 var->argcounter = argcounter;
5041 for (i = 0; i < vec_size(params); ++i)
5042 ast_delete(params[i]);
5047 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5049 ast_expression *cexp;
5050 ast_value *cval, *tmp;
5053 ctx = parser_ctx(parser);
5055 if (!parser_next(parser)) {
5057 parseerror(parser, "expected array-size");
5061 cexp = parse_expression_leave(parser, true, false, false);
5063 if (!cexp || !ast_istype(cexp, ast_value)) {
5067 parseerror(parser, "expected array-size as constant positive integer");
5070 cval = (ast_value*)cexp;
5072 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5073 tmp->expression.next = (ast_expression*)var;
5076 if (cval->expression.vtype == TYPE_INTEGER)
5077 tmp->expression.count = cval->constval.vint;
5078 else if (cval->expression.vtype == TYPE_FLOAT)
5079 tmp->expression.count = cval->constval.vfloat;
5083 parseerror(parser, "array-size must be a positive integer constant");
5088 if (parser->tok != ']') {
5090 parseerror(parser, "expected ']' after array-size");
5093 if (!parser_next(parser)) {
5095 parseerror(parser, "error after parsing array size");
5101 /* Parse a complete typename.
5102 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5103 * but when parsing variables separated by comma
5104 * 'storebase' should point to where the base-type should be kept.
5105 * The base type makes up every bit of type information which comes *before* the
5108 * The following will be parsed in its entirety:
5110 * The 'basetype' in this case is 'void()'
5111 * and if there's a comma after it, say:
5113 * then the type-information 'void()' can be stored in 'storebase'
5115 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5117 ast_value *var, *tmp;
5120 const char *name = NULL;
5121 bool isfield = false;
5122 bool wasarray = false;
5123 size_t morefields = 0;
5125 ctx = parser_ctx(parser);
5127 /* types may start with a dot */
5128 if (parser->tok == '.') {
5130 /* if we parsed a dot we need a typename now */
5131 if (!parser_next(parser)) {
5132 parseerror(parser, "expected typename for field definition");
5136 /* Further dots are handled seperately because they won't be part of the
5139 while (parser->tok == '.') {
5141 if (!parser_next(parser)) {
5142 parseerror(parser, "expected typename for field definition");
5147 if (parser->tok == TOKEN_IDENT)
5148 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5149 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5150 parseerror(parser, "expected typename");
5154 /* generate the basic type value */
5155 if (cached_typedef) {
5156 var = ast_value_copy(cached_typedef);
5157 ast_value_set_name(var, "<type(from_def)>");
5159 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5161 for (; morefields; --morefields) {
5162 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5163 tmp->expression.next = (ast_expression*)var;
5167 /* do not yet turn into a field - remember:
5168 * .void() foo; is a field too
5169 * .void()() foo; is a function
5173 if (!parser_next(parser)) {
5175 parseerror(parser, "parse error after typename");
5179 /* an opening paren now starts the parameter-list of a function
5180 * this is where original-QC has parameter lists.
5181 * We allow a single parameter list here.
5182 * Much like fteqcc we don't allow `float()() x`
5184 if (parser->tok == '(') {
5185 var = parse_parameter_list(parser, var);
5190 /* store the base if requested */
5192 *storebase = ast_value_copy(var);
5194 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5195 tmp->expression.next = (ast_expression*)*storebase;
5200 /* there may be a name now */
5201 if (parser->tok == TOKEN_IDENT) {
5202 name = util_strdup(parser_tokval(parser));
5204 if (!parser_next(parser)) {
5206 parseerror(parser, "error after variable or field declaration");
5211 /* now this may be an array */
5212 if (parser->tok == '[') {
5214 var = parse_arraysize(parser, var);
5219 /* This is the point where we can turn it into a field */
5221 /* turn it into a field if desired */
5222 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5223 tmp->expression.next = (ast_expression*)var;
5227 /* now there may be function parens again */
5228 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5229 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5230 if (parser->tok == '(' && wasarray)
5231 parseerror(parser, "arrays as part of a return type is not supported");
5232 while (parser->tok == '(') {
5233 var = parse_parameter_list(parser, var);
5241 /* finally name it */
5243 if (!ast_value_set_name(var, name)) {
5245 parseerror(parser, "internal error: failed to set name");
5248 /* free the name, ast_value_set_name duplicates */
5255 static bool parse_typedef(parser_t *parser)
5257 ast_value *typevar, *oldtype;
5258 ast_expression *old;
5260 typevar = parse_typename(parser, NULL, NULL);
5265 if ( (old = parser_find_var(parser, typevar->name)) ) {
5266 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5267 " -> `%s` has been declared here: %s:%i",
5268 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5269 ast_delete(typevar);
5273 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5274 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5275 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5276 ast_delete(typevar);
5280 vec_push(parser->_typedefs, typevar);
5281 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5283 if (parser->tok != ';') {
5284 parseerror(parser, "expected semicolon after typedef");
5287 if (!parser_next(parser)) {
5288 parseerror(parser, "parse error after typedef");
5295 static const char *cvq_to_str(int cvq) {
5297 case CV_NONE: return "none";
5298 case CV_VAR: return "`var`";
5299 case CV_CONST: return "`const`";
5300 default: return "<INVALID>";
5304 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5307 if (proto->cvq != var->cvq) {
5308 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5309 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5310 parser->tok == '='))
5312 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5313 "`%s` declared with different qualifiers: %s\n"
5314 " -> previous declaration here: %s:%i uses %s",
5315 var->name, cvq_to_str(var->cvq),
5316 ast_ctx(proto).file, ast_ctx(proto).line,
5317 cvq_to_str(proto->cvq));
5320 av = (var ->expression.flags & AST_FLAG_NORETURN);
5321 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5323 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5324 "`%s` declared with different attributes%s\n"
5325 " -> previous declaration here: %s:%i",
5326 var->name, (av ? ": noreturn" : ""),
5327 ast_ctx(proto).file, ast_ctx(proto).line,
5328 (ao ? ": noreturn" : ""));
5333 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)
5337 ast_expression *old;
5341 ast_value *basetype = NULL;
5343 bool isparam = false;
5344 bool isvector = false;
5345 bool cleanvar = true;
5346 bool wasarray = false;
5350 if (!localblock && is_static)
5351 parseerror(parser, "`static` qualifier is not supported in global scope");
5353 /* get the first complete variable */
5354 var = parse_typename(parser, &basetype, cached_typedef);
5357 ast_delete(basetype);
5365 /* Part 0: finish the type */
5366 if (parser->tok == '(') {
5367 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5368 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5369 var = parse_parameter_list(parser, var);
5375 /* we only allow 1-dimensional arrays */
5376 if (parser->tok == '[') {
5378 var = parse_arraysize(parser, var);
5384 if (parser->tok == '(' && wasarray) {
5385 parseerror(parser, "arrays as part of a return type is not supported");
5386 /* we'll still parse the type completely for now */
5388 /* for functions returning functions */
5389 while (parser->tok == '(') {
5390 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5391 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5392 var = parse_parameter_list(parser, var);
5399 var->cvq = qualifier;
5400 var->expression.flags |= qflags;
5403 * store the vstring back to var for alias and
5404 * deprecation messages.
5406 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5407 var->expression.flags & AST_FLAG_ALIAS)
5408 var->desc = vstring;
5411 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5412 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5413 * is then filled with the previous definition and the parameter-names replaced.
5415 if (!strcmp(var->name, "nil")) {
5416 if (OPTS_FLAG(UNTYPED_NIL)) {
5417 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5418 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5420 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5423 /* Deal with end_sys_ vars */
5425 if (!strcmp(var->name, "end_sys_globals")) {
5427 parser->crc_globals = vec_size(parser->globals);
5430 else if (!strcmp(var->name, "end_sys_fields")) {
5432 parser->crc_fields = vec_size(parser->fields);
5435 if (was_end && var->expression.vtype == TYPE_FIELD) {
5436 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5437 "global '%s' hint should not be a field",
5438 parser_tokval(parser)))
5445 if (!nofields && var->expression.vtype == TYPE_FIELD)
5447 /* deal with field declarations */
5448 old = parser_find_field(parser, var->name);
5450 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5451 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5460 parseerror(parser, "field `%s` already declared here: %s:%i",
5461 var->name, ast_ctx(old).file, ast_ctx(old).line);
5466 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5467 (old = parser_find_global(parser, var->name)))
5469 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5470 parseerror(parser, "field `%s` already declared here: %s:%i",
5471 var->name, ast_ctx(old).file, ast_ctx(old).line);
5478 /* deal with other globals */
5479 old = parser_find_global(parser, var->name);
5480 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5482 /* This is a function which had a prototype */
5483 if (!ast_istype(old, ast_value)) {
5484 parseerror(parser, "internal error: prototype is not an ast_value");
5488 proto = (ast_value*)old;
5489 proto->desc = var->desc;
5490 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5491 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5493 ast_ctx(proto).file, ast_ctx(proto).line);
5497 /* we need the new parameter-names */
5498 for (i = 0; i < vec_size(proto->expression.params); ++i)
5499 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5500 if (!parser_check_qualifiers(parser, var, proto)) {
5507 proto->expression.flags |= var->expression.flags;
5515 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5516 "global `%s` already declared here: %s:%i",
5517 var->name, ast_ctx(old).file, ast_ctx(old).line))
5522 proto = (ast_value*)old;
5523 if (!ast_istype(old, ast_value)) {
5524 parseerror(parser, "internal error: not an ast_value");
5529 if (!parser_check_qualifiers(parser, var, proto)) {
5534 proto->expression.flags |= var->expression.flags;
5538 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5539 (old = parser_find_field(parser, var->name)))
5541 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5542 parseerror(parser, "global `%s` already declared here: %s:%i",
5543 var->name, ast_ctx(old).file, ast_ctx(old).line);
5550 else /* it's not a global */
5552 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5553 if (old && !isparam) {
5554 parseerror(parser, "local `%s` already declared here: %s:%i",
5555 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5559 old = parser_find_local(parser, var->name, 0, &isparam);
5560 if (old && isparam) {
5561 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5562 "local `%s` is shadowing a parameter", var->name))
5564 parseerror(parser, "local `%s` already declared here: %s:%i",
5565 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5569 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5577 /* in a noref section we simply bump the usecount */
5578 if (noref || parser->noref)
5582 * Create the global/local, and deal with vector types.
5585 if (var->expression.vtype == TYPE_VECTOR)
5587 else if (var->expression.vtype == TYPE_FIELD &&
5588 var->expression.next->expression.vtype == TYPE_VECTOR)
5592 if (!create_vector_members(var, me)) {
5599 /* deal with global variables, fields, functions */
5600 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5601 var->isfield = true;
5602 vec_push(parser->fields, (ast_expression*)var);
5603 util_htset(parser->htfields, var->name, var);
5605 for (i = 0; i < 3; ++i) {
5606 vec_push(parser->fields, (ast_expression*)me[i]);
5607 util_htset(parser->htfields, me[i]->name, me[i]);
5612 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5613 parser_addglobal(parser, var->name, (ast_expression*)var);
5615 for (i = 0; i < 3; ++i) {
5616 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5620 ast_expression *find = parser_find_global(parser, var->desc);
5623 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5627 if (var->expression.vtype != find->expression.vtype) {
5631 ast_type_to_string(find, ty1, sizeof(ty1));
5632 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5634 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5641 * add alias to aliases table and to corrector
5642 * so corrections can apply for aliases as well.
5644 util_htset(parser->aliases, var->name, find);
5647 * add to corrector so corrections can work
5648 * even for aliases too.
5651 vec_last(parser->correct_variables),
5652 &vec_last(parser->correct_variables_score),
5656 /* generate aliases for vector components */
5660 util_asprintf(&buffer[0], "%s_x", var->desc);
5661 util_asprintf(&buffer[1], "%s_y", var->desc);
5662 util_asprintf(&buffer[2], "%s_z", var->desc);
5664 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5665 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5666 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5673 * add to corrector so corrections can work
5674 * even for aliases too.
5677 vec_last(parser->correct_variables),
5678 &vec_last(parser->correct_variables_score),
5682 vec_last(parser->correct_variables),
5683 &vec_last(parser->correct_variables_score),
5687 vec_last(parser->correct_variables),
5688 &vec_last(parser->correct_variables_score),
5696 /* a static adds itself to be generated like any other global
5697 * but is added to the local namespace instead
5699 char *defname = NULL;
5700 size_t prefix_len, ln;
5702 ln = strlen(parser->function->name);
5703 vec_append(defname, ln, parser->function->name);
5705 vec_append(defname, 2, "::");
5706 /* remember the length up to here */
5707 prefix_len = vec_size(defname);
5709 /* Add it to the local scope */
5710 util_htset(vec_last(parser->variables), var->name, (void*)var);
5714 vec_last(parser->correct_variables),
5715 &vec_last(parser->correct_variables_score),
5719 /* now rename the global */
5720 ln = strlen(var->name);
5721 vec_append(defname, ln, var->name);
5722 ast_value_set_name(var, defname);
5724 /* push it to the to-be-generated globals */
5725 vec_push(parser->globals, (ast_expression*)var);
5727 /* same game for the vector members */
5729 for (i = 0; i < 3; ++i) {
5730 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5734 vec_last(parser->correct_variables),
5735 &vec_last(parser->correct_variables_score),
5739 vec_shrinkto(defname, prefix_len);
5740 ln = strlen(me[i]->name);
5741 vec_append(defname, ln, me[i]->name);
5742 ast_member_set_name(me[i], defname);
5744 vec_push(parser->globals, (ast_expression*)me[i]);
5749 vec_push(localblock->locals, var);
5750 parser_addlocal(parser, var->name, (ast_expression*)var);
5752 for (i = 0; i < 3; ++i) {
5753 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5754 ast_block_collect(localblock, (ast_expression*)me[i]);
5760 me[0] = me[1] = me[2] = NULL;
5765 if (var->expression.vtype == TYPE_ARRAY) {
5767 snprintf(name, sizeof(name), "%s##SET", var->name);
5768 if (!parser_create_array_setter(parser, var, name))
5770 snprintf(name, sizeof(name), "%s##GET", var->name);
5771 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5774 else if (!localblock && !nofields &&
5775 var->expression.vtype == TYPE_FIELD &&
5776 var->expression.next->expression.vtype == TYPE_ARRAY)
5779 ast_expression *telem;
5781 ast_value *array = (ast_value*)var->expression.next;
5783 if (!ast_istype(var->expression.next, ast_value)) {
5784 parseerror(parser, "internal error: field element type must be an ast_value");
5788 snprintf(name, sizeof(name), "%s##SETF", var->name);
5789 if (!parser_create_array_field_setter(parser, array, name))
5792 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5793 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5794 tfield->expression.next = telem;
5795 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5796 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5804 if (parser->tok == ';') {
5805 ast_delete(basetype);
5806 if (!parser_next(parser)) {
5807 parseerror(parser, "error after variable declaration");
5813 if (parser->tok == ',')
5817 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5820 parseerror(parser, "missing comma or semicolon while parsing variables");
5824 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5825 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5826 "initializing expression turns variable `%s` into a constant in this standard",
5833 if (parser->tok != '{') {
5834 if (parser->tok != '=') {
5835 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5839 if (!parser_next(parser)) {
5840 parseerror(parser, "error parsing initializer");
5844 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5845 parseerror(parser, "expected '=' before function body in this standard");
5848 if (parser->tok == '#') {
5849 ast_function *func = NULL;
5852 parseerror(parser, "cannot declare builtins within functions");
5855 if (var->expression.vtype != TYPE_FUNCTION) {
5856 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5859 if (!parser_next(parser)) {
5860 parseerror(parser, "expected builtin number");
5863 if (parser->tok != TOKEN_INTCONST) {
5864 parseerror(parser, "builtin number must be an integer constant");
5867 if (parser_token(parser)->constval.i < 0) {
5868 parseerror(parser, "builtin number must be an integer greater than zero");
5872 if (var->hasvalue) {
5873 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5874 "builtin `%s` has already been defined\n"
5875 " -> previous declaration here: %s:%i",
5876 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5880 func = ast_function_new(ast_ctx(var), var->name, var);
5882 parseerror(parser, "failed to allocate function for `%s`", var->name);
5885 vec_push(parser->functions, func);
5887 func->builtin = -parser_token(parser)->constval.i-1;
5890 if (!parser_next(parser)) {
5891 parseerror(parser, "expected comma or semicolon");
5893 ast_function_delete(func);
5894 var->constval.vfunc = NULL;
5898 else if (parser->tok == '{' || parser->tok == '[')
5901 parseerror(parser, "cannot declare functions within functions");
5906 ast_ctx(proto) = parser_ctx(parser);
5908 if (!parse_function_body(parser, var))
5910 ast_delete(basetype);
5911 for (i = 0; i < vec_size(parser->gotos); ++i)
5912 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5913 vec_free(parser->gotos);
5914 vec_free(parser->labels);
5917 ast_expression *cexp;
5920 cexp = parse_expression_leave(parser, true, false, false);
5925 cval = (ast_value*)cexp;
5926 if (cval != parser->nil &&
5927 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5930 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5934 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5935 qualifier != CV_VAR)
5937 var->cvq = CV_CONST;
5939 if (cval == parser->nil)
5940 var->expression.flags |= AST_FLAG_INITIALIZED;
5943 var->hasvalue = true;
5944 if (cval->expression.vtype == TYPE_STRING)
5945 var->constval.vstring = parser_strdup(cval->constval.vstring);
5946 else if (cval->expression.vtype == TYPE_FIELD)
5947 var->constval.vfield = cval;
5949 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5955 shunt sy = { NULL, NULL, NULL, NULL };
5958 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5959 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5960 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5961 if (!parser_sy_apply_operator(parser, &sy))
5964 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5965 parseerror(parser, "internal error: leaked operands");
5966 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5976 if (parser->tok == ',') {
5977 if (!parser_next(parser)) {
5978 parseerror(parser, "expected another variable");
5982 if (parser->tok != TOKEN_IDENT) {
5983 parseerror(parser, "expected another variable");
5986 var = ast_value_copy(basetype);
5988 ast_value_set_name(var, parser_tokval(parser));
5989 if (!parser_next(parser)) {
5990 parseerror(parser, "error parsing variable declaration");
5996 if (parser->tok != ';') {
5997 parseerror(parser, "missing semicolon after variables");
6001 if (!parser_next(parser)) {
6002 parseerror(parser, "parse error after variable declaration");
6006 ast_delete(basetype);
6010 if (cleanvar && var)
6012 ast_delete(basetype);
6016 ast_delete(basetype);
6017 if (cleanvar && var)
6019 if (me[0]) ast_member_delete(me[0]);
6020 if (me[1]) ast_member_delete(me[1]);
6021 if (me[2]) ast_member_delete(me[2]);
6025 static bool parser_global_statement(parser_t *parser)
6029 bool is_static = false;
6030 uint32_t qflags = 0;
6031 ast_value *istype = NULL;
6032 char *vstring = NULL;
6034 if (parser->tok == TOKEN_IDENT)
6035 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6037 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6039 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6041 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6043 if (cvq == CV_WRONG)
6045 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6047 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6049 return parse_enum(parser);
6051 else if (parser->tok == TOKEN_KEYWORD)
6053 if (!strcmp(parser_tokval(parser), "typedef")) {
6054 if (!parser_next(parser)) {
6055 parseerror(parser, "expected type definition after 'typedef'");
6058 return parse_typedef(parser);
6060 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6063 else if (parser->tok == '#')
6065 return parse_pragma(parser);
6067 else if (parser->tok == '$')
6069 if (!parser_next(parser)) {
6070 parseerror(parser, "parse error");
6076 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6082 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6084 return util_crc16(old, str, strlen(str));
6087 static void progdefs_crc_file(const char *str)
6089 /* write to progdefs.h here */
6093 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6095 old = progdefs_crc_sum(old, str);
6096 progdefs_crc_file(str);
6100 static void generate_checksum(parser_t *parser)
6102 uint16_t crc = 0xFFFF;
6106 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6107 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6109 progdefs_crc_file("\tint\tpad;\n");
6110 progdefs_crc_file("\tint\tofs_return[3];\n");
6111 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6112 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6113 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6114 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6115 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6116 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6117 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6118 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6120 for (i = 0; i < parser->crc_globals; ++i) {
6121 if (!ast_istype(parser->globals[i], ast_value))
6123 value = (ast_value*)(parser->globals[i]);
6124 switch (value->expression.vtype) {
6125 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6126 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6127 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6128 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6130 crc = progdefs_crc_both(crc, "\tint\t");
6133 crc = progdefs_crc_both(crc, value->name);
6134 crc = progdefs_crc_both(crc, ";\n");
6136 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6137 for (i = 0; i < parser->crc_fields; ++i) {
6138 if (!ast_istype(parser->fields[i], ast_value))
6140 value = (ast_value*)(parser->fields[i]);
6141 switch (value->expression.next->expression.vtype) {
6142 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6143 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6144 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6145 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6147 crc = progdefs_crc_both(crc, "\tint\t");
6150 crc = progdefs_crc_both(crc, value->name);
6151 crc = progdefs_crc_both(crc, ";\n");
6153 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6158 static parser_t *parser;
6165 parser = (parser_t*)mem_a(sizeof(parser_t));
6169 memset(parser, 0, sizeof(*parser));
6171 for (i = 0; i < operator_count; ++i) {
6172 if (operators[i].id == opid1('=')) {
6173 parser->assign_op = operators+i;
6177 if (!parser->assign_op) {
6178 printf("internal error: initializing parser: failed to find assign operator\n");
6183 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6184 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6185 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6186 vec_push(parser->_blocktypedefs, 0);
6188 parser->aliases = util_htnew(PARSER_HT_SIZE);
6191 vec_push(parser->correct_variables, correct_trie_new());
6192 vec_push(parser->correct_variables_score, NULL);
6194 empty_ctx.file = "<internal>";
6196 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6197 parser->nil->cvq = CV_CONST;
6198 if (OPTS_FLAG(UNTYPED_NIL))
6199 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6201 parser->max_param_count = 1;
6203 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6204 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6205 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6207 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6208 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6209 parser->reserved_version->cvq = CV_CONST;
6210 parser->reserved_version->hasvalue = true;
6211 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6212 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6214 parser->reserved_version = NULL;
6219 bool parser_compile()
6221 /* initial lexer/parser state */
6222 parser->lex->flags.noops = true;
6224 if (parser_next(parser))
6226 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6228 if (!parser_global_statement(parser)) {
6229 if (parser->tok == TOKEN_EOF)
6230 parseerror(parser, "unexpected eof");
6231 else if (compile_errors)
6232 parseerror(parser, "there have been errors, bailing out");
6233 lex_close(parser->lex);
6239 parseerror(parser, "parse error");
6240 lex_close(parser->lex);
6245 lex_close(parser->lex);
6248 return !compile_errors;
6251 bool parser_compile_file(const char *filename)
6253 parser->lex = lex_open(filename);
6255 con_err("failed to open file \"%s\"\n", filename);
6258 return parser_compile();
6261 bool parser_compile_string(const char *name, const char *str, size_t len)
6263 parser->lex = lex_open_string(str, len, name);
6265 con_err("failed to create lexer for string \"%s\"\n", name);
6268 return parser_compile();
6271 void parser_cleanup()
6274 for (i = 0; i < vec_size(parser->accessors); ++i) {
6275 ast_delete(parser->accessors[i]->constval.vfunc);
6276 parser->accessors[i]->constval.vfunc = NULL;
6277 ast_delete(parser->accessors[i]);
6279 for (i = 0; i < vec_size(parser->functions); ++i) {
6280 ast_delete(parser->functions[i]);
6282 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6283 ast_delete(parser->imm_vector[i]);
6285 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6286 ast_delete(parser->imm_string[i]);
6288 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6289 ast_delete(parser->imm_float[i]);
6291 for (i = 0; i < vec_size(parser->fields); ++i) {
6292 ast_delete(parser->fields[i]);
6294 for (i = 0; i < vec_size(parser->globals); ++i) {
6295 ast_delete(parser->globals[i]);
6297 vec_free(parser->accessors);
6298 vec_free(parser->functions);
6299 vec_free(parser->imm_vector);
6300 vec_free(parser->imm_string);
6301 vec_free(parser->imm_float);
6302 vec_free(parser->globals);
6303 vec_free(parser->fields);
6305 for (i = 0; i < vec_size(parser->variables); ++i)
6306 util_htdel(parser->variables[i]);
6307 vec_free(parser->variables);
6308 vec_free(parser->_blocklocals);
6309 vec_free(parser->_locals);
6312 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6313 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6315 vec_free(parser->correct_variables);
6316 vec_free(parser->correct_variables_score);
6319 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6320 ast_delete(parser->_typedefs[i]);
6321 vec_free(parser->_typedefs);
6322 for (i = 0; i < vec_size(parser->typedefs); ++i)
6323 util_htdel(parser->typedefs[i]);
6324 vec_free(parser->typedefs);
6325 vec_free(parser->_blocktypedefs);
6327 vec_free(parser->_block_ctx);
6329 vec_free(parser->labels);
6330 vec_free(parser->gotos);
6331 vec_free(parser->breaks);
6332 vec_free(parser->continues);
6334 ast_value_delete(parser->nil);
6336 ast_value_delete(parser->const_vec[0]);
6337 ast_value_delete(parser->const_vec[1]);
6338 ast_value_delete(parser->const_vec[2]);
6340 util_htdel(parser->aliases);
6345 bool parser_finish(const char *output)
6351 if (compile_errors) {
6352 con_out("*** there were compile errors\n");
6356 ir = ir_builder_new("gmqcc_out");
6358 con_out("failed to allocate builder\n");
6362 for (i = 0; i < vec_size(parser->fields); ++i) {
6365 if (!ast_istype(parser->fields[i], ast_value))
6367 field = (ast_value*)parser->fields[i];
6368 hasvalue = field->hasvalue;
6369 field->hasvalue = false;
6370 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6371 con_out("failed to generate field %s\n", field->name);
6372 ir_builder_delete(ir);
6377 ast_expression *subtype;
6378 field->hasvalue = true;
6379 subtype = field->expression.next;
6380 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6381 if (subtype->expression.vtype == TYPE_FIELD)
6382 ifld->fieldtype = subtype->expression.next->expression.vtype;
6383 else if (subtype->expression.vtype == TYPE_FUNCTION)
6384 ifld->outtype = subtype->expression.next->expression.vtype;
6385 (void)!ir_value_set_field(field->ir_v, ifld);
6388 for (i = 0; i < vec_size(parser->globals); ++i) {
6390 if (!ast_istype(parser->globals[i], ast_value))
6392 asvalue = (ast_value*)(parser->globals[i]);
6393 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6394 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6395 "unused global: `%s`", asvalue->name);
6397 if (!ast_global_codegen(asvalue, ir, false)) {
6398 con_out("failed to generate global %s\n", asvalue->name);
6399 ir_builder_delete(ir);
6403 /* Build function vararg accessor ast tree now before generating
6404 * immediates, because the accessors may add new immediates
6406 for (i = 0; i < vec_size(parser->functions); ++i) {
6407 ast_function *f = parser->functions[i];
6409 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6410 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6411 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6412 con_out("failed to generate vararg setter for %s\n", f->name);
6413 ir_builder_delete(ir);
6416 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6417 con_out("failed to generate vararg getter for %s\n", f->name);
6418 ir_builder_delete(ir);
6422 ast_delete(f->varargs);
6427 /* Now we can generate immediates */
6428 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6429 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6430 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6431 ir_builder_delete(ir);
6435 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6436 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6437 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6438 ir_builder_delete(ir);
6442 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6443 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6444 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6445 ir_builder_delete(ir);
6449 for (i = 0; i < vec_size(parser->globals); ++i) {
6451 if (!ast_istype(parser->globals[i], ast_value))
6453 asvalue = (ast_value*)(parser->globals[i]);
6454 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6456 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6457 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6458 "uninitialized constant: `%s`",
6460 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6461 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6462 "uninitialized global: `%s`",
6465 if (!ast_generate_accessors(asvalue, ir)) {
6466 ir_builder_delete(ir);
6470 for (i = 0; i < vec_size(parser->fields); ++i) {
6472 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6474 if (!ast_istype((ast_expression*)asvalue, ast_value))
6476 if (asvalue->expression.vtype != TYPE_ARRAY)
6478 if (!ast_generate_accessors(asvalue, ir)) {
6479 ir_builder_delete(ir);
6483 if (parser->reserved_version &&
6484 !ast_global_codegen(parser->reserved_version, ir, false))
6486 con_out("failed to generate reserved::version");
6487 ir_builder_delete(ir);
6490 for (i = 0; i < vec_size(parser->functions); ++i) {
6491 ast_function *f = parser->functions[i];
6492 if (!ast_function_codegen(f, ir)) {
6493 con_out("failed to generate function %s\n", f->name);
6494 ir_builder_delete(ir);
6498 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6499 ir_builder_dump(ir, con_out);
6500 for (i = 0; i < vec_size(parser->functions); ++i) {
6501 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6502 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6503 ir_builder_delete(ir);
6508 if (compile_Werrors) {
6509 con_out("*** there were warnings treated as errors\n");
6510 compile_show_werrors();
6515 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6516 ir_builder_dump(ir, con_out);
6518 generate_checksum(parser);
6520 if (!ir_builder_generate(ir, output)) {
6521 con_out("*** failed to generate output file\n");
6522 ir_builder_delete(ir);
6527 ir_builder_delete(ir);