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)
3964 ast_value **values = NULL;
3965 ast_value *var = NULL;
3968 ast_expression *old;
3970 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3971 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3975 /* enumeration attributes (can add more later) */
3976 if (parser->tok == ':') {
3977 if (!parser_next(parser) || parser->tok != TOKEN_IDENT || strcmp(parser_tokval(parser), "flag")) {
3978 parseerror(parser, "expected `flag` after enumeration attribute ':'");
3982 if (!parser_next(parser) || parser->tok != '{') {
3983 parseerror(parser, "expected `{` after enum attribute `flag`");
3987 /* flagged enumeration start from 1 */
3993 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3994 if (parser->tok == '}') {
3995 /* allow an empty enum */
3998 parseerror(parser, "expected identifier or `}`");
4002 old = parser_find_field(parser, parser_tokval(parser));
4004 old = parser_find_global(parser, parser_tokval(parser));
4006 parseerror(parser, "value `%s` has already been declared here: %s:%i",
4007 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
4011 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
4012 vec_push(values, var);
4013 var->cvq = CV_CONST;
4014 var->hasvalue = true;
4016 /* for flagged enumerations increment in POTs of TWO */
4017 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
4019 parser_addglobal(parser, var->name, (ast_expression*)var);
4021 if (!parser_next(parser)) {
4022 parseerror(parser, "expected `=`, `}` or comma after identifier");
4026 if (parser->tok == ',')
4028 if (parser->tok == '}')
4030 if (parser->tok != '=') {
4031 parseerror(parser, "expected `=`, `}` or comma after identifier");
4035 if (!parser_next(parser)) {
4036 parseerror(parser, "expected expression after `=`");
4040 /* We got a value! */
4041 old = parse_expression_leave(parser, true, false, false);
4042 asvalue = (ast_value*)old;
4043 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4044 compile_error(ast_ctx(var), "constant value or expression expected");
4047 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4049 if (parser->tok == '}')
4051 if (parser->tok != ',') {
4052 parseerror(parser, "expected `}` or comma after expression");
4057 if (parser->tok != '}') {
4058 parseerror(parser, "internal error: breaking without `}`");
4062 if (!parser_next(parser) || parser->tok != ';') {
4063 parseerror(parser, "expected semicolon after enumeration");
4067 if (!parser_next(parser)) {
4068 parseerror(parser, "parse error after enumeration");
4080 static bool parse_block_into(parser_t *parser, ast_block *block)
4084 parser_enterblock(parser);
4086 if (!parser_next(parser)) { /* skip the '{' */
4087 parseerror(parser, "expected function body");
4091 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4093 ast_expression *expr = NULL;
4094 if (parser->tok == '}')
4097 if (!parse_statement(parser, block, &expr, false)) {
4098 /* parseerror(parser, "parse error"); */
4104 if (!ast_block_add_expr(block, expr)) {
4111 if (parser->tok != '}') {
4114 (void)parser_next(parser);
4118 if (!parser_leaveblock(parser))
4120 return retval && !!block;
4123 static ast_block* parse_block(parser_t *parser)
4126 block = ast_block_new(parser_ctx(parser));
4129 if (!parse_block_into(parser, block)) {
4130 ast_block_delete(block);
4136 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4138 if (parser->tok == '{') {
4139 *out = (ast_expression*)parse_block(parser);
4142 return parse_statement(parser, NULL, out, false);
4145 static bool create_vector_members(ast_value *var, ast_member **me)
4148 size_t len = strlen(var->name);
4150 for (i = 0; i < 3; ++i) {
4151 char *name = (char*)mem_a(len+3);
4152 memcpy(name, var->name, len);
4154 name[len+1] = 'x'+i;
4156 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4165 do { ast_member_delete(me[--i]); } while(i);
4169 static bool parse_function_body(parser_t *parser, ast_value *var)
4171 ast_block *block = NULL;
4176 ast_expression *framenum = NULL;
4177 ast_expression *nextthink = NULL;
4178 /* None of the following have to be deleted */
4179 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4180 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4181 bool has_frame_think;
4185 has_frame_think = false;
4186 old = parser->function;
4188 if (var->expression.flags & AST_FLAG_ALIAS) {
4189 parseerror(parser, "function aliases cannot have bodies");
4193 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4194 parseerror(parser, "gotos/labels leaking");
4198 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4199 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4200 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4206 if (parser->tok == '[') {
4207 /* got a frame definition: [ framenum, nextthink ]
4208 * this translates to:
4209 * self.frame = framenum;
4210 * self.nextthink = time + 0.1;
4211 * self.think = nextthink;
4215 fld_think = parser_find_field(parser, "think");
4216 fld_nextthink = parser_find_field(parser, "nextthink");
4217 fld_frame = parser_find_field(parser, "frame");
4218 if (!fld_think || !fld_nextthink || !fld_frame) {
4219 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4220 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4223 gbl_time = parser_find_global(parser, "time");
4224 gbl_self = parser_find_global(parser, "self");
4225 if (!gbl_time || !gbl_self) {
4226 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4227 parseerror(parser, "please declare the following globals: `time`, `self`");
4231 if (!parser_next(parser))
4234 framenum = parse_expression_leave(parser, true, false, false);
4236 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4239 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4240 ast_unref(framenum);
4241 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4245 if (parser->tok != ',') {
4246 ast_unref(framenum);
4247 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4248 parseerror(parser, "Got a %i\n", parser->tok);
4252 if (!parser_next(parser)) {
4253 ast_unref(framenum);
4257 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4259 /* qc allows the use of not-yet-declared functions here
4260 * - this automatically creates a prototype */
4261 ast_value *thinkfunc;
4262 ast_expression *functype = fld_think->expression.next;
4264 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4265 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4266 ast_unref(framenum);
4267 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4270 ast_type_adopt(thinkfunc, functype);
4272 if (!parser_next(parser)) {
4273 ast_unref(framenum);
4274 ast_delete(thinkfunc);
4278 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4280 nextthink = (ast_expression*)thinkfunc;
4283 nextthink = parse_expression_leave(parser, true, false, false);
4285 ast_unref(framenum);
4286 parseerror(parser, "expected a think-function in [frame,think] notation");
4291 if (!ast_istype(nextthink, ast_value)) {
4292 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4296 if (retval && parser->tok != ']') {
4297 parseerror(parser, "expected closing `]` for [frame,think] notation");
4301 if (retval && !parser_next(parser)) {
4305 if (retval && parser->tok != '{') {
4306 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4311 ast_unref(nextthink);
4312 ast_unref(framenum);
4316 has_frame_think = true;
4319 block = ast_block_new(parser_ctx(parser));
4321 parseerror(parser, "failed to allocate block");
4322 if (has_frame_think) {
4323 ast_unref(nextthink);
4324 ast_unref(framenum);
4329 if (has_frame_think) {
4331 ast_expression *self_frame;
4332 ast_expression *self_nextthink;
4333 ast_expression *self_think;
4334 ast_expression *time_plus_1;
4335 ast_store *store_frame;
4336 ast_store *store_nextthink;
4337 ast_store *store_think;
4339 ctx = parser_ctx(parser);
4340 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4341 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4342 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4344 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4345 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4347 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4348 if (self_frame) ast_delete(self_frame);
4349 if (self_nextthink) ast_delete(self_nextthink);
4350 if (self_think) ast_delete(self_think);
4351 if (time_plus_1) ast_delete(time_plus_1);
4357 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4358 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4359 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4362 ast_delete(self_frame);
4365 if (!store_nextthink) {
4366 ast_delete(self_nextthink);
4370 ast_delete(self_think);
4374 if (store_frame) ast_delete(store_frame);
4375 if (store_nextthink) ast_delete(store_nextthink);
4376 if (store_think) ast_delete(store_think);
4379 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4380 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4381 !ast_block_add_expr(block, (ast_expression*)store_think))
4388 parseerror(parser, "failed to generate code for [frame,think]");
4389 ast_unref(nextthink);
4390 ast_unref(framenum);
4396 if (var->hasvalue) {
4397 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4398 ast_block_delete(block);
4402 func = ast_function_new(ast_ctx(var), var->name, var);
4404 parseerror(parser, "failed to allocate function for `%s`", var->name);
4405 ast_block_delete(block);
4408 vec_push(parser->functions, func);
4410 parser_enterblock(parser);
4412 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4414 ast_value *param = var->expression.params[parami];
4417 if (param->expression.vtype != TYPE_VECTOR &&
4418 (param->expression.vtype != TYPE_FIELD ||
4419 param->expression.next->expression.vtype != TYPE_VECTOR))
4424 if (!create_vector_members(param, me)) {
4425 ast_block_delete(block);
4429 for (e = 0; e < 3; ++e) {
4430 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4431 ast_block_collect(block, (ast_expression*)me[e]);
4435 if (var->argcounter) {
4436 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4437 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4441 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4443 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4444 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4445 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4446 varargs->expression.count = 0;
4447 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4448 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4449 ast_delete(varargs);
4450 ast_block_delete(block);
4453 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4454 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4455 ast_delete(varargs);
4456 ast_block_delete(block);
4459 func->varargs = varargs;
4461 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4464 parser->function = func;
4465 if (!parse_block_into(parser, block)) {
4466 ast_block_delete(block);
4470 vec_push(func->blocks, block);
4472 parser->function = old;
4473 if (!parser_leaveblock(parser))
4475 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4476 parseerror(parser, "internal error: local scopes left");
4480 if (parser->tok == ';')
4481 return parser_next(parser);
4482 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4483 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4487 (void)!parser_leaveblock(parser);
4488 vec_pop(parser->functions);
4489 ast_function_delete(func);
4490 var->constval.vfunc = NULL;
4493 parser->function = old;
4497 static ast_expression *array_accessor_split(
4502 ast_expression *left,
4503 ast_expression *right
4509 lex_ctx ctx = ast_ctx(array);
4511 if (!left || !right) {
4512 if (left) ast_delete(left);
4513 if (right) ast_delete(right);
4517 cmp = ast_binary_new(ctx, INSTR_LT,
4518 (ast_expression*)index,
4519 (ast_expression*)parser_const_float(parser, middle));
4523 parseerror(parser, "internal error: failed to create comparison for array setter");
4527 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4529 ast_delete(cmp); /* will delete left and right */
4530 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4534 return (ast_expression*)ifthen;
4537 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4539 lex_ctx ctx = ast_ctx(array);
4541 if (from+1 == afterend) {
4542 /* set this value */
4545 ast_array_index *subscript;
4547 int assignop = type_store_instr[value->expression.vtype];
4549 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4550 assignop = INSTR_STORE_V;
4552 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4556 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4558 ast_delete(subscript);
4562 block = ast_block_new(ctx);
4568 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4573 ret = ast_return_new(ctx, NULL);
4579 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4584 return (ast_expression*)block;
4586 ast_expression *left, *right;
4587 size_t diff = afterend - from;
4588 size_t middle = from + diff/2;
4589 left = array_setter_node(parser, array, index, value, from, middle);
4590 right = array_setter_node(parser, array, index, value, middle, afterend);
4591 return array_accessor_split(parser, array, index, middle, left, right);
4595 static ast_expression *array_field_setter_node(
4604 lex_ctx ctx = ast_ctx(array);
4606 if (from+1 == afterend) {
4607 /* set this value */
4610 ast_entfield *entfield;
4611 ast_array_index *subscript;
4613 int assignop = type_storep_instr[value->expression.vtype];
4615 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4616 assignop = INSTR_STOREP_V;
4618 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4622 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4623 subscript->expression.vtype = TYPE_FIELD;
4625 entfield = ast_entfield_new_force(ctx,
4626 (ast_expression*)entity,
4627 (ast_expression*)subscript,
4628 (ast_expression*)subscript);
4630 ast_delete(subscript);
4634 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4636 ast_delete(entfield);
4640 block = ast_block_new(ctx);
4646 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4651 ret = ast_return_new(ctx, NULL);
4657 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4662 return (ast_expression*)block;
4664 ast_expression *left, *right;
4665 size_t diff = afterend - from;
4666 size_t middle = from + diff/2;
4667 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4668 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4669 return array_accessor_split(parser, array, index, middle, left, right);
4673 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4675 lex_ctx ctx = ast_ctx(array);
4677 if (from+1 == afterend) {
4679 ast_array_index *subscript;
4681 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4685 ret = ast_return_new(ctx, (ast_expression*)subscript);
4687 ast_delete(subscript);
4691 return (ast_expression*)ret;
4693 ast_expression *left, *right;
4694 size_t diff = afterend - from;
4695 size_t middle = from + diff/2;
4696 left = array_getter_node(parser, array, index, from, middle);
4697 right = array_getter_node(parser, array, index, middle, afterend);
4698 return array_accessor_split(parser, array, index, middle, left, right);
4702 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4704 ast_function *func = NULL;
4705 ast_value *fval = NULL;
4706 ast_block *body = NULL;
4708 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4710 parseerror(parser, "failed to create accessor function value");
4714 func = ast_function_new(ast_ctx(array), funcname, fval);
4717 parseerror(parser, "failed to create accessor function node");
4721 body = ast_block_new(ast_ctx(array));
4723 parseerror(parser, "failed to create block for array accessor");
4729 vec_push(func->blocks, body);
4732 vec_push(parser->accessors, fval);
4737 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4739 ast_value *index = NULL;
4740 ast_value *value = NULL;
4744 if (!ast_istype(array->expression.next, ast_value)) {
4745 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4749 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4751 func = fval->constval.vfunc;
4752 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4754 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4755 value = ast_value_copy((ast_value*)array->expression.next);
4757 if (!index || !value) {
4758 parseerror(parser, "failed to create locals for array accessor");
4761 (void)!ast_value_set_name(value, "value"); /* not important */
4762 vec_push(fval->expression.params, index);
4763 vec_push(fval->expression.params, value);
4765 array->setter = fval;
4768 if (index) ast_delete(index);
4769 if (value) ast_delete(value);
4775 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4777 ast_expression *root = NULL;
4778 root = array_setter_node(parser, array,
4779 array->setter->expression.params[0],
4780 array->setter->expression.params[1],
4781 0, array->expression.count);
4783 parseerror(parser, "failed to build accessor search tree");
4786 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4793 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4795 if (!parser_create_array_setter_proto(parser, array, funcname))
4797 return parser_create_array_setter_impl(parser, array);
4800 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4802 ast_expression *root = NULL;
4803 ast_value *entity = NULL;
4804 ast_value *index = NULL;
4805 ast_value *value = NULL;
4809 if (!ast_istype(array->expression.next, ast_value)) {
4810 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4814 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4816 func = fval->constval.vfunc;
4817 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4819 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4820 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4821 value = ast_value_copy((ast_value*)array->expression.next);
4822 if (!entity || !index || !value) {
4823 parseerror(parser, "failed to create locals for array accessor");
4826 (void)!ast_value_set_name(value, "value"); /* not important */
4827 vec_push(fval->expression.params, entity);
4828 vec_push(fval->expression.params, index);
4829 vec_push(fval->expression.params, value);
4831 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4833 parseerror(parser, "failed to build accessor search tree");
4837 array->setter = fval;
4838 return ast_block_add_expr(func->blocks[0], root);
4840 if (entity) ast_delete(entity);
4841 if (index) ast_delete(index);
4842 if (value) ast_delete(value);
4843 if (root) ast_delete(root);
4849 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4851 ast_value *index = NULL;
4855 /* NOTE: checking array->expression.next rather than elemtype since
4856 * for fields elemtype is a temporary fieldtype.
4858 if (!ast_istype(array->expression.next, ast_value)) {
4859 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4863 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4865 func = fval->constval.vfunc;
4866 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4868 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4871 parseerror(parser, "failed to create locals for array accessor");
4874 vec_push(fval->expression.params, index);
4876 array->getter = fval;
4879 if (index) ast_delete(index);
4885 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4887 ast_expression *root = NULL;
4889 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4891 parseerror(parser, "failed to build accessor search tree");
4894 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4901 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4903 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4905 return parser_create_array_getter_impl(parser, array);
4908 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4909 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4917 bool variadic = false;
4918 ast_value *varparam = NULL;
4919 char *argcounter = NULL;
4921 ctx = parser_ctx(parser);
4923 /* for the sake of less code we parse-in in this function */
4924 if (!parser_next(parser)) {
4925 parseerror(parser, "expected parameter list");
4931 /* parse variables until we hit a closing paren */
4932 while (parser->tok != ')') {
4934 /* there must be commas between them */
4935 if (parser->tok != ',') {
4936 parseerror(parser, "expected comma or end of parameter list");
4939 if (!parser_next(parser)) {
4940 parseerror(parser, "expected parameter");
4946 if (parser->tok == TOKEN_DOTS) {
4947 /* '...' indicates a varargs function */
4949 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4950 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4953 if (parser->tok == TOKEN_IDENT) {
4954 argcounter = util_strdup(parser_tokval(parser));
4955 if (!parser_next(parser) || parser->tok != ')') {
4956 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4963 /* for anything else just parse a typename */
4964 param = parse_typename(parser, NULL, NULL);
4967 vec_push(params, param);
4968 if (param->expression.vtype >= TYPE_VARIANT) {
4969 char tname[1024]; /* typename is reserved in C++ */
4970 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4971 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4974 /* type-restricted varargs */
4975 if (parser->tok == TOKEN_DOTS) {
4977 varparam = vec_last(params);
4979 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4980 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4983 if (parser->tok == TOKEN_IDENT) {
4984 argcounter = util_strdup(parser_tokval(parser));
4985 if (!parser_next(parser) || parser->tok != ')') {
4986 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4994 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4998 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4999 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
5002 if (!parser_next(parser)) {
5003 parseerror(parser, "parse error after typename");
5007 /* now turn 'var' into a function type */
5008 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
5009 fval->expression.next = (ast_expression*)var;
5011 fval->expression.flags |= AST_FLAG_VARIADIC;
5014 var->expression.params = params;
5015 var->expression.varparam = (ast_expression*)varparam;
5016 var->argcounter = argcounter;
5025 for (i = 0; i < vec_size(params); ++i)
5026 ast_delete(params[i]);
5031 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5033 ast_expression *cexp;
5034 ast_value *cval, *tmp;
5037 ctx = parser_ctx(parser);
5039 if (!parser_next(parser)) {
5041 parseerror(parser, "expected array-size");
5045 cexp = parse_expression_leave(parser, true, false, false);
5047 if (!cexp || !ast_istype(cexp, ast_value)) {
5051 parseerror(parser, "expected array-size as constant positive integer");
5054 cval = (ast_value*)cexp;
5056 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5057 tmp->expression.next = (ast_expression*)var;
5060 if (cval->expression.vtype == TYPE_INTEGER)
5061 tmp->expression.count = cval->constval.vint;
5062 else if (cval->expression.vtype == TYPE_FLOAT)
5063 tmp->expression.count = cval->constval.vfloat;
5067 parseerror(parser, "array-size must be a positive integer constant");
5072 if (parser->tok != ']') {
5074 parseerror(parser, "expected ']' after array-size");
5077 if (!parser_next(parser)) {
5079 parseerror(parser, "error after parsing array size");
5085 /* Parse a complete typename.
5086 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5087 * but when parsing variables separated by comma
5088 * 'storebase' should point to where the base-type should be kept.
5089 * The base type makes up every bit of type information which comes *before* the
5092 * The following will be parsed in its entirety:
5094 * The 'basetype' in this case is 'void()'
5095 * and if there's a comma after it, say:
5097 * then the type-information 'void()' can be stored in 'storebase'
5099 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5101 ast_value *var, *tmp;
5104 const char *name = NULL;
5105 bool isfield = false;
5106 bool wasarray = false;
5107 size_t morefields = 0;
5109 ctx = parser_ctx(parser);
5111 /* types may start with a dot */
5112 if (parser->tok == '.') {
5114 /* if we parsed a dot we need a typename now */
5115 if (!parser_next(parser)) {
5116 parseerror(parser, "expected typename for field definition");
5120 /* Further dots are handled seperately because they won't be part of the
5123 while (parser->tok == '.') {
5125 if (!parser_next(parser)) {
5126 parseerror(parser, "expected typename for field definition");
5131 if (parser->tok == TOKEN_IDENT)
5132 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5133 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5134 parseerror(parser, "expected typename");
5138 /* generate the basic type value */
5139 if (cached_typedef) {
5140 var = ast_value_copy(cached_typedef);
5141 ast_value_set_name(var, "<type(from_def)>");
5143 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5145 for (; morefields; --morefields) {
5146 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5147 tmp->expression.next = (ast_expression*)var;
5151 /* do not yet turn into a field - remember:
5152 * .void() foo; is a field too
5153 * .void()() foo; is a function
5157 if (!parser_next(parser)) {
5159 parseerror(parser, "parse error after typename");
5163 /* an opening paren now starts the parameter-list of a function
5164 * this is where original-QC has parameter lists.
5165 * We allow a single parameter list here.
5166 * Much like fteqcc we don't allow `float()() x`
5168 if (parser->tok == '(') {
5169 var = parse_parameter_list(parser, var);
5174 /* store the base if requested */
5176 *storebase = ast_value_copy(var);
5178 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5179 tmp->expression.next = (ast_expression*)*storebase;
5184 /* there may be a name now */
5185 if (parser->tok == TOKEN_IDENT) {
5186 name = util_strdup(parser_tokval(parser));
5188 if (!parser_next(parser)) {
5190 parseerror(parser, "error after variable or field declaration");
5195 /* now this may be an array */
5196 if (parser->tok == '[') {
5198 var = parse_arraysize(parser, var);
5203 /* This is the point where we can turn it into a field */
5205 /* turn it into a field if desired */
5206 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5207 tmp->expression.next = (ast_expression*)var;
5211 /* now there may be function parens again */
5212 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5213 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5214 if (parser->tok == '(' && wasarray)
5215 parseerror(parser, "arrays as part of a return type is not supported");
5216 while (parser->tok == '(') {
5217 var = parse_parameter_list(parser, var);
5225 /* finally name it */
5227 if (!ast_value_set_name(var, name)) {
5229 parseerror(parser, "internal error: failed to set name");
5232 /* free the name, ast_value_set_name duplicates */
5239 static bool parse_typedef(parser_t *parser)
5241 ast_value *typevar, *oldtype;
5242 ast_expression *old;
5244 typevar = parse_typename(parser, NULL, NULL);
5249 if ( (old = parser_find_var(parser, typevar->name)) ) {
5250 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5251 " -> `%s` has been declared here: %s:%i",
5252 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5253 ast_delete(typevar);
5257 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5258 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5259 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5260 ast_delete(typevar);
5264 vec_push(parser->_typedefs, typevar);
5265 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5267 if (parser->tok != ';') {
5268 parseerror(parser, "expected semicolon after typedef");
5271 if (!parser_next(parser)) {
5272 parseerror(parser, "parse error after typedef");
5279 static const char *cvq_to_str(int cvq) {
5281 case CV_NONE: return "none";
5282 case CV_VAR: return "`var`";
5283 case CV_CONST: return "`const`";
5284 default: return "<INVALID>";
5288 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5291 if (proto->cvq != var->cvq) {
5292 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5293 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5294 parser->tok == '='))
5296 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5297 "`%s` declared with different qualifiers: %s\n"
5298 " -> previous declaration here: %s:%i uses %s",
5299 var->name, cvq_to_str(var->cvq),
5300 ast_ctx(proto).file, ast_ctx(proto).line,
5301 cvq_to_str(proto->cvq));
5304 av = (var ->expression.flags & AST_FLAG_NORETURN);
5305 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5307 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5308 "`%s` declared with different attributes%s\n"
5309 " -> previous declaration here: %s:%i",
5310 var->name, (av ? ": noreturn" : ""),
5311 ast_ctx(proto).file, ast_ctx(proto).line,
5312 (ao ? ": noreturn" : ""));
5317 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)
5321 ast_expression *old;
5325 ast_value *basetype = NULL;
5327 bool isparam = false;
5328 bool isvector = false;
5329 bool cleanvar = true;
5330 bool wasarray = false;
5334 if (!localblock && is_static)
5335 parseerror(parser, "`static` qualifier is not supported in global scope");
5337 /* get the first complete variable */
5338 var = parse_typename(parser, &basetype, cached_typedef);
5341 ast_delete(basetype);
5349 /* Part 0: finish the type */
5350 if (parser->tok == '(') {
5351 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5352 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5353 var = parse_parameter_list(parser, var);
5359 /* we only allow 1-dimensional arrays */
5360 if (parser->tok == '[') {
5362 var = parse_arraysize(parser, var);
5368 if (parser->tok == '(' && wasarray) {
5369 parseerror(parser, "arrays as part of a return type is not supported");
5370 /* we'll still parse the type completely for now */
5372 /* for functions returning functions */
5373 while (parser->tok == '(') {
5374 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5375 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5376 var = parse_parameter_list(parser, var);
5383 var->cvq = qualifier;
5384 var->expression.flags |= qflags;
5387 * store the vstring back to var for alias and
5388 * deprecation messages.
5390 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5391 var->expression.flags & AST_FLAG_ALIAS)
5392 var->desc = vstring;
5395 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5396 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5397 * is then filled with the previous definition and the parameter-names replaced.
5399 if (!strcmp(var->name, "nil")) {
5400 if (OPTS_FLAG(UNTYPED_NIL)) {
5401 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5402 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5404 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5407 /* Deal with end_sys_ vars */
5409 if (!strcmp(var->name, "end_sys_globals")) {
5411 parser->crc_globals = vec_size(parser->globals);
5414 else if (!strcmp(var->name, "end_sys_fields")) {
5416 parser->crc_fields = vec_size(parser->fields);
5419 if (was_end && var->expression.vtype == TYPE_FIELD) {
5420 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5421 "global '%s' hint should not be a field",
5422 parser_tokval(parser)))
5429 if (!nofields && var->expression.vtype == TYPE_FIELD)
5431 /* deal with field declarations */
5432 old = parser_find_field(parser, var->name);
5434 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5435 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5444 parseerror(parser, "field `%s` already declared here: %s:%i",
5445 var->name, ast_ctx(old).file, ast_ctx(old).line);
5450 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5451 (old = parser_find_global(parser, var->name)))
5453 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5454 parseerror(parser, "field `%s` already declared here: %s:%i",
5455 var->name, ast_ctx(old).file, ast_ctx(old).line);
5462 /* deal with other globals */
5463 old = parser_find_global(parser, var->name);
5464 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5466 /* This is a function which had a prototype */
5467 if (!ast_istype(old, ast_value)) {
5468 parseerror(parser, "internal error: prototype is not an ast_value");
5472 proto = (ast_value*)old;
5473 proto->desc = var->desc;
5474 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5475 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5477 ast_ctx(proto).file, ast_ctx(proto).line);
5481 /* we need the new parameter-names */
5482 for (i = 0; i < vec_size(proto->expression.params); ++i)
5483 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5484 if (!parser_check_qualifiers(parser, var, proto)) {
5491 proto->expression.flags |= var->expression.flags;
5499 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5500 "global `%s` already declared here: %s:%i",
5501 var->name, ast_ctx(old).file, ast_ctx(old).line))
5506 proto = (ast_value*)old;
5507 if (!ast_istype(old, ast_value)) {
5508 parseerror(parser, "internal error: not an ast_value");
5513 if (!parser_check_qualifiers(parser, var, proto)) {
5518 proto->expression.flags |= var->expression.flags;
5522 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5523 (old = parser_find_field(parser, var->name)))
5525 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5526 parseerror(parser, "global `%s` already declared here: %s:%i",
5527 var->name, ast_ctx(old).file, ast_ctx(old).line);
5534 else /* it's not a global */
5536 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5537 if (old && !isparam) {
5538 parseerror(parser, "local `%s` already declared here: %s:%i",
5539 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5543 old = parser_find_local(parser, var->name, 0, &isparam);
5544 if (old && isparam) {
5545 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5546 "local `%s` is shadowing a parameter", var->name))
5548 parseerror(parser, "local `%s` already declared here: %s:%i",
5549 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5553 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5561 /* in a noref section we simply bump the usecount */
5562 if (noref || parser->noref)
5566 * Create the global/local, and deal with vector types.
5569 if (var->expression.vtype == TYPE_VECTOR)
5571 else if (var->expression.vtype == TYPE_FIELD &&
5572 var->expression.next->expression.vtype == TYPE_VECTOR)
5576 if (!create_vector_members(var, me)) {
5583 /* deal with global variables, fields, functions */
5584 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5585 var->isfield = true;
5586 vec_push(parser->fields, (ast_expression*)var);
5587 util_htset(parser->htfields, var->name, var);
5589 for (i = 0; i < 3; ++i) {
5590 vec_push(parser->fields, (ast_expression*)me[i]);
5591 util_htset(parser->htfields, me[i]->name, me[i]);
5596 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5597 parser_addglobal(parser, var->name, (ast_expression*)var);
5599 for (i = 0; i < 3; ++i) {
5600 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5604 ast_expression *find = parser_find_global(parser, var->desc);
5607 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5611 if (var->expression.vtype != find->expression.vtype) {
5615 ast_type_to_string(find, ty1, sizeof(ty1));
5616 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5618 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5625 * add alias to aliases table and to corrector
5626 * so corrections can apply for aliases as well.
5628 util_htset(parser->aliases, var->name, find);
5631 * add to corrector so corrections can work
5632 * even for aliases too.
5635 vec_last(parser->correct_variables),
5636 &vec_last(parser->correct_variables_score),
5640 /* generate aliases for vector components */
5644 util_asprintf(&buffer[0], "%s_x", var->desc);
5645 util_asprintf(&buffer[1], "%s_y", var->desc);
5646 util_asprintf(&buffer[2], "%s_z", var->desc);
5648 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5649 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5650 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5657 * add to corrector so corrections can work
5658 * even for aliases too.
5661 vec_last(parser->correct_variables),
5662 &vec_last(parser->correct_variables_score),
5666 vec_last(parser->correct_variables),
5667 &vec_last(parser->correct_variables_score),
5671 vec_last(parser->correct_variables),
5672 &vec_last(parser->correct_variables_score),
5680 /* a static adds itself to be generated like any other global
5681 * but is added to the local namespace instead
5683 char *defname = NULL;
5684 size_t prefix_len, ln;
5686 ln = strlen(parser->function->name);
5687 vec_append(defname, ln, parser->function->name);
5689 vec_append(defname, 2, "::");
5690 /* remember the length up to here */
5691 prefix_len = vec_size(defname);
5693 /* Add it to the local scope */
5694 util_htset(vec_last(parser->variables), var->name, (void*)var);
5698 vec_last(parser->correct_variables),
5699 &vec_last(parser->correct_variables_score),
5703 /* now rename the global */
5704 ln = strlen(var->name);
5705 vec_append(defname, ln, var->name);
5706 ast_value_set_name(var, defname);
5708 /* push it to the to-be-generated globals */
5709 vec_push(parser->globals, (ast_expression*)var);
5711 /* same game for the vector members */
5713 for (i = 0; i < 3; ++i) {
5714 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5718 vec_last(parser->correct_variables),
5719 &vec_last(parser->correct_variables_score),
5723 vec_shrinkto(defname, prefix_len);
5724 ln = strlen(me[i]->name);
5725 vec_append(defname, ln, me[i]->name);
5726 ast_member_set_name(me[i], defname);
5728 vec_push(parser->globals, (ast_expression*)me[i]);
5733 vec_push(localblock->locals, var);
5734 parser_addlocal(parser, var->name, (ast_expression*)var);
5736 for (i = 0; i < 3; ++i) {
5737 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5738 ast_block_collect(localblock, (ast_expression*)me[i]);
5744 me[0] = me[1] = me[2] = NULL;
5749 if (var->expression.vtype == TYPE_ARRAY) {
5751 snprintf(name, sizeof(name), "%s##SET", var->name);
5752 if (!parser_create_array_setter(parser, var, name))
5754 snprintf(name, sizeof(name), "%s##GET", var->name);
5755 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5758 else if (!localblock && !nofields &&
5759 var->expression.vtype == TYPE_FIELD &&
5760 var->expression.next->expression.vtype == TYPE_ARRAY)
5763 ast_expression *telem;
5765 ast_value *array = (ast_value*)var->expression.next;
5767 if (!ast_istype(var->expression.next, ast_value)) {
5768 parseerror(parser, "internal error: field element type must be an ast_value");
5772 snprintf(name, sizeof(name), "%s##SETF", var->name);
5773 if (!parser_create_array_field_setter(parser, array, name))
5776 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5777 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5778 tfield->expression.next = telem;
5779 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5780 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5788 if (parser->tok == ';') {
5789 ast_delete(basetype);
5790 if (!parser_next(parser)) {
5791 parseerror(parser, "error after variable declaration");
5797 if (parser->tok == ',')
5801 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5804 parseerror(parser, "missing comma or semicolon while parsing variables");
5808 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5809 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5810 "initializing expression turns variable `%s` into a constant in this standard",
5817 if (parser->tok != '{') {
5818 if (parser->tok != '=') {
5819 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5823 if (!parser_next(parser)) {
5824 parseerror(parser, "error parsing initializer");
5828 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5829 parseerror(parser, "expected '=' before function body in this standard");
5832 if (parser->tok == '#') {
5833 ast_function *func = NULL;
5836 parseerror(parser, "cannot declare builtins within functions");
5839 if (var->expression.vtype != TYPE_FUNCTION) {
5840 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5843 if (!parser_next(parser)) {
5844 parseerror(parser, "expected builtin number");
5847 if (parser->tok != TOKEN_INTCONST) {
5848 parseerror(parser, "builtin number must be an integer constant");
5851 if (parser_token(parser)->constval.i < 0) {
5852 parseerror(parser, "builtin number must be an integer greater than zero");
5856 if (var->hasvalue) {
5857 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5858 "builtin `%s` has already been defined\n"
5859 " -> previous declaration here: %s:%i",
5860 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5864 func = ast_function_new(ast_ctx(var), var->name, var);
5866 parseerror(parser, "failed to allocate function for `%s`", var->name);
5869 vec_push(parser->functions, func);
5871 func->builtin = -parser_token(parser)->constval.i-1;
5874 if (!parser_next(parser)) {
5875 parseerror(parser, "expected comma or semicolon");
5877 ast_function_delete(func);
5878 var->constval.vfunc = NULL;
5882 else if (parser->tok == '{' || parser->tok == '[')
5885 parseerror(parser, "cannot declare functions within functions");
5890 ast_ctx(proto) = parser_ctx(parser);
5892 if (!parse_function_body(parser, var))
5894 ast_delete(basetype);
5895 for (i = 0; i < vec_size(parser->gotos); ++i)
5896 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5897 vec_free(parser->gotos);
5898 vec_free(parser->labels);
5901 ast_expression *cexp;
5904 cexp = parse_expression_leave(parser, true, false, false);
5909 cval = (ast_value*)cexp;
5910 if (cval != parser->nil &&
5911 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5914 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5918 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5919 qualifier != CV_VAR)
5921 var->cvq = CV_CONST;
5923 if (cval == parser->nil)
5924 var->expression.flags |= AST_FLAG_INITIALIZED;
5927 var->hasvalue = true;
5928 if (cval->expression.vtype == TYPE_STRING)
5929 var->constval.vstring = parser_strdup(cval->constval.vstring);
5930 else if (cval->expression.vtype == TYPE_FIELD)
5931 var->constval.vfield = cval;
5933 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5939 shunt sy = { NULL, NULL, NULL, NULL };
5942 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5943 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5944 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5945 if (!parser_sy_apply_operator(parser, &sy))
5948 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5949 parseerror(parser, "internal error: leaked operands");
5950 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5960 if (parser->tok == ',') {
5961 if (!parser_next(parser)) {
5962 parseerror(parser, "expected another variable");
5966 if (parser->tok != TOKEN_IDENT) {
5967 parseerror(parser, "expected another variable");
5970 var = ast_value_copy(basetype);
5972 ast_value_set_name(var, parser_tokval(parser));
5973 if (!parser_next(parser)) {
5974 parseerror(parser, "error parsing variable declaration");
5980 if (parser->tok != ';') {
5981 parseerror(parser, "missing semicolon after variables");
5985 if (!parser_next(parser)) {
5986 parseerror(parser, "parse error after variable declaration");
5990 ast_delete(basetype);
5994 if (cleanvar && var)
5996 ast_delete(basetype);
6000 ast_delete(basetype);
6001 if (cleanvar && var)
6003 if (me[0]) ast_member_delete(me[0]);
6004 if (me[1]) ast_member_delete(me[1]);
6005 if (me[2]) ast_member_delete(me[2]);
6009 static bool parser_global_statement(parser_t *parser)
6013 bool is_static = false;
6014 uint32_t qflags = 0;
6015 ast_value *istype = NULL;
6016 char *vstring = NULL;
6018 if (parser->tok == TOKEN_IDENT)
6019 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6021 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6023 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6025 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6027 if (cvq == CV_WRONG)
6029 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6031 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6033 return parse_enum(parser);
6035 else if (parser->tok == TOKEN_KEYWORD)
6037 if (!strcmp(parser_tokval(parser), "typedef")) {
6038 if (!parser_next(parser)) {
6039 parseerror(parser, "expected type definition after 'typedef'");
6042 return parse_typedef(parser);
6044 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6047 else if (parser->tok == '#')
6049 return parse_pragma(parser);
6051 else if (parser->tok == '$')
6053 if (!parser_next(parser)) {
6054 parseerror(parser, "parse error");
6060 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6066 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6068 return util_crc16(old, str, strlen(str));
6071 static void progdefs_crc_file(const char *str)
6073 /* write to progdefs.h here */
6077 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6079 old = progdefs_crc_sum(old, str);
6080 progdefs_crc_file(str);
6084 static void generate_checksum(parser_t *parser)
6086 uint16_t crc = 0xFFFF;
6090 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6091 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6093 progdefs_crc_file("\tint\tpad;\n");
6094 progdefs_crc_file("\tint\tofs_return[3];\n");
6095 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6096 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6097 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6098 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6099 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6100 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6101 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6102 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6104 for (i = 0; i < parser->crc_globals; ++i) {
6105 if (!ast_istype(parser->globals[i], ast_value))
6107 value = (ast_value*)(parser->globals[i]);
6108 switch (value->expression.vtype) {
6109 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6110 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6111 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6112 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6114 crc = progdefs_crc_both(crc, "\tint\t");
6117 crc = progdefs_crc_both(crc, value->name);
6118 crc = progdefs_crc_both(crc, ";\n");
6120 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6121 for (i = 0; i < parser->crc_fields; ++i) {
6122 if (!ast_istype(parser->fields[i], ast_value))
6124 value = (ast_value*)(parser->fields[i]);
6125 switch (value->expression.next->expression.vtype) {
6126 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6127 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6128 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6129 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6131 crc = progdefs_crc_both(crc, "\tint\t");
6134 crc = progdefs_crc_both(crc, value->name);
6135 crc = progdefs_crc_both(crc, ";\n");
6137 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6142 static parser_t *parser;
6149 parser = (parser_t*)mem_a(sizeof(parser_t));
6153 memset(parser, 0, sizeof(*parser));
6155 for (i = 0; i < operator_count; ++i) {
6156 if (operators[i].id == opid1('=')) {
6157 parser->assign_op = operators+i;
6161 if (!parser->assign_op) {
6162 printf("internal error: initializing parser: failed to find assign operator\n");
6167 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6168 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6169 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6170 vec_push(parser->_blocktypedefs, 0);
6172 parser->aliases = util_htnew(PARSER_HT_SIZE);
6175 vec_push(parser->correct_variables, correct_trie_new());
6176 vec_push(parser->correct_variables_score, NULL);
6178 empty_ctx.file = "<internal>";
6180 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6181 parser->nil->cvq = CV_CONST;
6182 if (OPTS_FLAG(UNTYPED_NIL))
6183 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6185 parser->max_param_count = 1;
6187 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6188 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6189 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6191 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6192 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6193 parser->reserved_version->cvq = CV_CONST;
6194 parser->reserved_version->hasvalue = true;
6195 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6196 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6198 parser->reserved_version = NULL;
6203 bool parser_compile()
6205 /* initial lexer/parser state */
6206 parser->lex->flags.noops = true;
6208 if (parser_next(parser))
6210 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6212 if (!parser_global_statement(parser)) {
6213 if (parser->tok == TOKEN_EOF)
6214 parseerror(parser, "unexpected eof");
6215 else if (compile_errors)
6216 parseerror(parser, "there have been errors, bailing out");
6217 lex_close(parser->lex);
6223 parseerror(parser, "parse error");
6224 lex_close(parser->lex);
6229 lex_close(parser->lex);
6232 return !compile_errors;
6235 bool parser_compile_file(const char *filename)
6237 parser->lex = lex_open(filename);
6239 con_err("failed to open file \"%s\"\n", filename);
6242 return parser_compile();
6245 bool parser_compile_string(const char *name, const char *str, size_t len)
6247 parser->lex = lex_open_string(str, len, name);
6249 con_err("failed to create lexer for string \"%s\"\n", name);
6252 return parser_compile();
6255 void parser_cleanup()
6258 for (i = 0; i < vec_size(parser->accessors); ++i) {
6259 ast_delete(parser->accessors[i]->constval.vfunc);
6260 parser->accessors[i]->constval.vfunc = NULL;
6261 ast_delete(parser->accessors[i]);
6263 for (i = 0; i < vec_size(parser->functions); ++i) {
6264 ast_delete(parser->functions[i]);
6266 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6267 ast_delete(parser->imm_vector[i]);
6269 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6270 ast_delete(parser->imm_string[i]);
6272 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6273 ast_delete(parser->imm_float[i]);
6275 for (i = 0; i < vec_size(parser->fields); ++i) {
6276 ast_delete(parser->fields[i]);
6278 for (i = 0; i < vec_size(parser->globals); ++i) {
6279 ast_delete(parser->globals[i]);
6281 vec_free(parser->accessors);
6282 vec_free(parser->functions);
6283 vec_free(parser->imm_vector);
6284 vec_free(parser->imm_string);
6285 vec_free(parser->imm_float);
6286 vec_free(parser->globals);
6287 vec_free(parser->fields);
6289 for (i = 0; i < vec_size(parser->variables); ++i)
6290 util_htdel(parser->variables[i]);
6291 vec_free(parser->variables);
6292 vec_free(parser->_blocklocals);
6293 vec_free(parser->_locals);
6296 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6297 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6299 vec_free(parser->correct_variables);
6300 vec_free(parser->correct_variables_score);
6303 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6304 ast_delete(parser->_typedefs[i]);
6305 vec_free(parser->_typedefs);
6306 for (i = 0; i < vec_size(parser->typedefs); ++i)
6307 util_htdel(parser->typedefs[i]);
6308 vec_free(parser->typedefs);
6309 vec_free(parser->_blocktypedefs);
6311 vec_free(parser->_block_ctx);
6313 vec_free(parser->labels);
6314 vec_free(parser->gotos);
6315 vec_free(parser->breaks);
6316 vec_free(parser->continues);
6318 ast_value_delete(parser->nil);
6320 ast_value_delete(parser->const_vec[0]);
6321 ast_value_delete(parser->const_vec[1]);
6322 ast_value_delete(parser->const_vec[2]);
6324 util_htdel(parser->aliases);
6329 bool parser_finish(const char *output)
6335 if (compile_errors) {
6336 con_out("*** there were compile errors\n");
6340 ir = ir_builder_new("gmqcc_out");
6342 con_out("failed to allocate builder\n");
6346 for (i = 0; i < vec_size(parser->fields); ++i) {
6349 if (!ast_istype(parser->fields[i], ast_value))
6351 field = (ast_value*)parser->fields[i];
6352 hasvalue = field->hasvalue;
6353 field->hasvalue = false;
6354 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6355 con_out("failed to generate field %s\n", field->name);
6356 ir_builder_delete(ir);
6361 ast_expression *subtype;
6362 field->hasvalue = true;
6363 subtype = field->expression.next;
6364 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6365 if (subtype->expression.vtype == TYPE_FIELD)
6366 ifld->fieldtype = subtype->expression.next->expression.vtype;
6367 else if (subtype->expression.vtype == TYPE_FUNCTION)
6368 ifld->outtype = subtype->expression.next->expression.vtype;
6369 (void)!ir_value_set_field(field->ir_v, ifld);
6372 for (i = 0; i < vec_size(parser->globals); ++i) {
6374 if (!ast_istype(parser->globals[i], ast_value))
6376 asvalue = (ast_value*)(parser->globals[i]);
6377 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6378 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6379 "unused global: `%s`", asvalue->name);
6381 if (!ast_global_codegen(asvalue, ir, false)) {
6382 con_out("failed to generate global %s\n", asvalue->name);
6383 ir_builder_delete(ir);
6387 /* Build function vararg accessor ast tree now before generating
6388 * immediates, because the accessors may add new immediates
6390 for (i = 0; i < vec_size(parser->functions); ++i) {
6391 ast_function *f = parser->functions[i];
6393 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6394 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6395 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6396 con_out("failed to generate vararg setter for %s\n", f->name);
6397 ir_builder_delete(ir);
6400 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6401 con_out("failed to generate vararg getter for %s\n", f->name);
6402 ir_builder_delete(ir);
6406 ast_delete(f->varargs);
6411 /* Now we can generate immediates */
6412 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6413 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6414 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6415 ir_builder_delete(ir);
6419 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6420 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6421 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6422 ir_builder_delete(ir);
6426 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6427 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6428 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6429 ir_builder_delete(ir);
6433 for (i = 0; i < vec_size(parser->globals); ++i) {
6435 if (!ast_istype(parser->globals[i], ast_value))
6437 asvalue = (ast_value*)(parser->globals[i]);
6438 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6440 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6441 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6442 "uninitialized constant: `%s`",
6444 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6445 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6446 "uninitialized global: `%s`",
6449 if (!ast_generate_accessors(asvalue, ir)) {
6450 ir_builder_delete(ir);
6454 for (i = 0; i < vec_size(parser->fields); ++i) {
6456 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6458 if (!ast_istype((ast_expression*)asvalue, ast_value))
6460 if (asvalue->expression.vtype != TYPE_ARRAY)
6462 if (!ast_generate_accessors(asvalue, ir)) {
6463 ir_builder_delete(ir);
6467 if (parser->reserved_version &&
6468 !ast_global_codegen(parser->reserved_version, ir, false))
6470 con_out("failed to generate reserved::version");
6471 ir_builder_delete(ir);
6474 for (i = 0; i < vec_size(parser->functions); ++i) {
6475 ast_function *f = parser->functions[i];
6476 if (!ast_function_codegen(f, ir)) {
6477 con_out("failed to generate function %s\n", f->name);
6478 ir_builder_delete(ir);
6482 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6483 ir_builder_dump(ir, con_out);
6484 for (i = 0; i < vec_size(parser->functions); ++i) {
6485 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6486 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6487 ir_builder_delete(ir);
6492 if (compile_Werrors) {
6493 con_out("*** there were warnings treated as errors\n");
6494 compile_show_werrors();
6499 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6500 ir_builder_dump(ir, con_out);
6502 generate_checksum(parser);
6504 if (!ir_builder_generate(ir, output)) {
6505 con_out("*** failed to generate output file\n");
6506 ir_builder_delete(ir);
6511 ir_builder_delete(ir);