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"))) {
3544 parseerror(parser, "internal error: no suitable definition found for `floor` (required for % and __builtin_mod)");
3549 if (!mod_func_val) {
3550 ast_value *mod_args[2];
3551 ast_function *mod_func = NULL;
3552 ast_block *mod_body = ast_block_new (parser_ctx(parser));
3553 ast_call *mod_call = ast_call_new (parser_ctx(parser), mod_floor);
3554 mod_func_val = ast_value_new (parser_ctx(parser), "__builtin_mod", TYPE_FUNCTION);
3555 mod_func_val->expression.next = (ast_expression*)ast_value_new(parser_ctx(parser), "<float>", TYPE_FLOAT);
3556 mod_func = ast_function_new(parser_ctx(parser), "__builtin_mod", mod_func_val);
3557 mod_args[0] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3558 mod_args[1] = ast_value_new (parser_ctx(parser), "x", TYPE_FLOAT);
3561 vec_push(mod_call->params,
3562 (ast_expression*)ast_binary_new(
3565 (ast_expression*)mod_args[0],
3566 (ast_expression*)mod_args[1]
3570 vec_push(mod_body->exprs,
3571 (ast_expression*)ast_return_new(
3573 (ast_expression*)ast_binary_new(
3576 (ast_expression*)mod_args[0],
3577 (ast_expression*)ast_binary_new(
3580 (ast_expression*)mod_args[1],
3581 (ast_expression*)mod_call
3587 vec_push(mod_func_val->expression.params, mod_args[0]);
3588 vec_push(mod_func_val->expression.params, mod_args[1]);
3590 vec_push(mod_func->blocks, mod_body);
3592 vec_push(parser->functions, mod_func);
3593 vec_push(parser->globals, (ast_expression*)mod_func_val);
3596 return (ast_expression*)mod_func_val;
3599 /* parse computed goto sides */
3600 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3601 ast_expression *on_true;
3602 ast_expression *on_false;
3603 ast_expression *cond;
3608 if (ast_istype(*side, ast_ternary)) {
3609 ast_ternary *tern = (ast_ternary*)*side;
3610 on_true = parse_goto_computed(parser, &tern->on_true);
3611 on_false = parse_goto_computed(parser, &tern->on_false);
3613 if (!on_true || !on_false) {
3614 parseerror(parser, "expected label or expression in ternary");
3615 if (on_true) ast_unref(on_true);
3616 if (on_false) ast_unref(on_false);
3624 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3625 } else if (ast_istype(*side, ast_label)) {
3626 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3627 ast_goto_set_label(gt, ((ast_label*)*side));
3629 return (ast_expression*)gt;
3634 static bool parse_goto(parser_t *parser, ast_expression **out)
3636 ast_goto *gt = NULL;
3637 ast_expression *lbl;
3639 if (!parser_next(parser))
3642 if (parser->tok != TOKEN_IDENT) {
3643 ast_expression *expression;
3645 /* could be an expression i.e computed goto :-) */
3646 if (parser->tok != '(') {
3647 parseerror(parser, "expected label name after `goto`");
3651 /* failed to parse expression for goto */
3652 if (!(expression = parse_expression(parser, false, true)) ||
3653 !(*out = parse_goto_computed(parser, &expression))) {
3654 parseerror(parser, "invalid goto expression");
3655 ast_unref(expression);
3662 /* not computed goto */
3663 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3664 lbl = parser_find_label(parser, gt->name);
3666 if (!ast_istype(lbl, ast_label)) {
3667 parseerror(parser, "internal error: label is not an ast_label");
3671 ast_goto_set_label(gt, (ast_label*)lbl);
3674 vec_push(parser->gotos, gt);
3676 if (!parser_next(parser) || parser->tok != ';') {
3677 parseerror(parser, "semicolon expected after goto label");
3680 if (!parser_next(parser)) {
3681 parseerror(parser, "parse error after goto");
3685 *out = (ast_expression*)gt;
3689 static bool parse_skipwhite(parser_t *parser)
3692 if (!parser_next(parser))
3694 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3695 return parser->tok < TOKEN_ERROR;
3698 static bool parse_eol(parser_t *parser)
3700 if (!parse_skipwhite(parser))
3702 return parser->tok == TOKEN_EOL;
3705 static bool parse_pragma_do(parser_t *parser)
3707 if (!parser_next(parser) ||
3708 parser->tok != TOKEN_IDENT ||
3709 strcmp(parser_tokval(parser), "pragma"))
3711 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3714 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3715 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3719 if (!strcmp(parser_tokval(parser), "noref")) {
3720 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3721 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3724 parser->noref = !!parser_token(parser)->constval.i;
3725 if (!parse_eol(parser)) {
3726 parseerror(parser, "parse error after `noref` pragma");
3732 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3739 static bool parse_pragma(parser_t *parser)
3742 parser->lex->flags.preprocessing = true;
3743 parser->lex->flags.mergelines = true;
3744 rv = parse_pragma_do(parser);
3745 if (parser->tok != TOKEN_EOL) {
3746 parseerror(parser, "junk after pragma");
3749 parser->lex->flags.preprocessing = false;
3750 parser->lex->flags.mergelines = false;
3751 if (!parser_next(parser)) {
3752 parseerror(parser, "parse error after pragma");
3758 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3760 bool noref, is_static;
3762 uint32_t qflags = 0;
3763 ast_value *typevar = NULL;
3764 char *vstring = NULL;
3768 if (parser->tok == TOKEN_IDENT)
3769 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3771 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3773 /* local variable */
3775 parseerror(parser, "cannot declare a variable from here");
3778 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3779 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3782 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3786 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3788 if (cvq == CV_WRONG)
3790 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3792 else if (parser->tok == TOKEN_KEYWORD)
3794 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3799 if (!parser_next(parser)) {
3800 parseerror(parser, "parse error after __builtin_debug_printtype");
3804 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3806 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3807 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3808 if (!parser_next(parser)) {
3809 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3815 if (!parse_statement(parser, block, out, allow_cases))
3818 con_out("__builtin_debug_printtype: got no output node\n");
3821 ast_type_to_string(*out, ty, sizeof(ty));
3822 con_out("__builtin_debug_printtype: `%s`\n", ty);
3827 else if (!strcmp(parser_tokval(parser), "return"))
3829 return parse_return(parser, block, out);
3831 else if (!strcmp(parser_tokval(parser), "if"))
3833 return parse_if(parser, block, out);
3835 else if (!strcmp(parser_tokval(parser), "while"))
3837 return parse_while(parser, block, out);
3839 else if (!strcmp(parser_tokval(parser), "do"))
3841 return parse_dowhile(parser, block, out);
3843 else if (!strcmp(parser_tokval(parser), "for"))
3845 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3846 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3849 return parse_for(parser, block, out);
3851 else if (!strcmp(parser_tokval(parser), "break"))
3853 return parse_break_continue(parser, block, out, false);
3855 else if (!strcmp(parser_tokval(parser), "continue"))
3857 return parse_break_continue(parser, block, out, true);
3859 else if (!strcmp(parser_tokval(parser), "switch"))
3861 return parse_switch(parser, block, out);
3863 else if (!strcmp(parser_tokval(parser), "case") ||
3864 !strcmp(parser_tokval(parser), "default"))
3867 parseerror(parser, "unexpected 'case' label");
3872 else if (!strcmp(parser_tokval(parser), "goto"))
3874 return parse_goto(parser, out);
3876 else if (!strcmp(parser_tokval(parser), "typedef"))
3878 if (!parser_next(parser)) {
3879 parseerror(parser, "expected type definition after 'typedef'");
3882 return parse_typedef(parser);
3884 parseerror(parser, "Unexpected keyword");
3887 else if (parser->tok == '{')
3890 inner = parse_block(parser);
3893 *out = (ast_expression*)inner;
3896 else if (parser->tok == ':')
3900 if (!parser_next(parser)) {
3901 parseerror(parser, "expected label name");
3904 if (parser->tok != TOKEN_IDENT) {
3905 parseerror(parser, "label must be an identifier");
3908 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3910 if (!label->undefined) {
3911 parseerror(parser, "label `%s` already defined", label->name);
3914 label->undefined = false;
3917 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3918 vec_push(parser->labels, label);
3920 *out = (ast_expression*)label;
3921 if (!parser_next(parser)) {
3922 parseerror(parser, "parse error after label");
3925 for (i = 0; i < vec_size(parser->gotos); ++i) {
3926 if (!strcmp(parser->gotos[i]->name, label->name)) {
3927 ast_goto_set_label(parser->gotos[i], label);
3928 vec_remove(parser->gotos, i, 1);
3934 else if (parser->tok == ';')
3936 if (!parser_next(parser)) {
3937 parseerror(parser, "parse error after empty statement");
3944 lex_ctx ctx = parser_ctx(parser);
3945 ast_expression *exp = parse_expression(parser, false, false);
3949 if (!ast_side_effects(exp)) {
3950 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3957 static bool parse_enum(parser_t *parser)
3961 ast_value **values = NULL;
3962 ast_value *var = NULL;
3965 ast_expression *old;
3967 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3968 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3972 /* enumeration attributes (can add more later) */
3973 if (parser->tok == ':') {
3974 if (!parser_next(parser) || parser->tok != TOKEN_IDENT || strcmp(parser_tokval(parser), "flag")) {
3975 parseerror(parser, "expected `flag` after enumeration attribute ':'");
3979 if (!parser_next(parser) || parser->tok != '{') {
3980 parseerror(parser, "expected `{` after enum attribute `flag`");
3984 /* flagged enumeration start from 1 */
3990 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3991 if (parser->tok == '}') {
3992 /* allow an empty enum */
3995 parseerror(parser, "expected identifier or `}`");
3999 old = parser_find_field(parser, parser_tokval(parser));
4001 old = parser_find_global(parser, parser_tokval(parser));
4003 parseerror(parser, "value `%s` has already been declared here: %s:%i",
4004 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
4008 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
4009 vec_push(values, var);
4010 var->cvq = CV_CONST;
4011 var->hasvalue = true;
4013 /* for flagged enumerations increment in POTs of TWO */
4014 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
4016 parser_addglobal(parser, var->name, (ast_expression*)var);
4018 if (!parser_next(parser)) {
4019 parseerror(parser, "expected `=`, `}` or comma after identifier");
4023 if (parser->tok == ',')
4025 if (parser->tok == '}')
4027 if (parser->tok != '=') {
4028 parseerror(parser, "expected `=`, `}` or comma after identifier");
4032 if (!parser_next(parser)) {
4033 parseerror(parser, "expected expression after `=`");
4037 /* We got a value! */
4038 old = parse_expression_leave(parser, true, false, false);
4039 asvalue = (ast_value*)old;
4040 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
4041 compile_error(ast_ctx(var), "constant value or expression expected");
4044 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
4046 if (parser->tok == '}')
4048 if (parser->tok != ',') {
4049 parseerror(parser, "expected `}` or comma after expression");
4054 if (parser->tok != '}') {
4055 parseerror(parser, "internal error: breaking without `}`");
4059 if (!parser_next(parser) || parser->tok != ';') {
4060 parseerror(parser, "expected semicolon after enumeration");
4064 if (!parser_next(parser)) {
4065 parseerror(parser, "parse error after enumeration");
4077 static bool parse_block_into(parser_t *parser, ast_block *block)
4081 parser_enterblock(parser);
4083 if (!parser_next(parser)) { /* skip the '{' */
4084 parseerror(parser, "expected function body");
4088 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4090 ast_expression *expr = NULL;
4091 if (parser->tok == '}')
4094 if (!parse_statement(parser, block, &expr, false)) {
4095 /* parseerror(parser, "parse error"); */
4101 if (!ast_block_add_expr(block, expr)) {
4108 if (parser->tok != '}') {
4111 (void)parser_next(parser);
4115 if (!parser_leaveblock(parser))
4117 return retval && !!block;
4120 static ast_block* parse_block(parser_t *parser)
4123 block = ast_block_new(parser_ctx(parser));
4126 if (!parse_block_into(parser, block)) {
4127 ast_block_delete(block);
4133 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4135 if (parser->tok == '{') {
4136 *out = (ast_expression*)parse_block(parser);
4139 return parse_statement(parser, NULL, out, false);
4142 static bool create_vector_members(ast_value *var, ast_member **me)
4145 size_t len = strlen(var->name);
4147 for (i = 0; i < 3; ++i) {
4148 char *name = (char*)mem_a(len+3);
4149 memcpy(name, var->name, len);
4151 name[len+1] = 'x'+i;
4153 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4162 do { ast_member_delete(me[--i]); } while(i);
4166 static bool parse_function_body(parser_t *parser, ast_value *var)
4168 ast_block *block = NULL;
4173 ast_expression *framenum = NULL;
4174 ast_expression *nextthink = NULL;
4175 /* None of the following have to be deleted */
4176 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4177 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4178 bool has_frame_think;
4182 has_frame_think = false;
4183 old = parser->function;
4185 if (var->expression.flags & AST_FLAG_ALIAS) {
4186 parseerror(parser, "function aliases cannot have bodies");
4190 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4191 parseerror(parser, "gotos/labels leaking");
4195 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4196 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4197 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4203 if (parser->tok == '[') {
4204 /* got a frame definition: [ framenum, nextthink ]
4205 * this translates to:
4206 * self.frame = framenum;
4207 * self.nextthink = time + 0.1;
4208 * self.think = nextthink;
4212 fld_think = parser_find_field(parser, "think");
4213 fld_nextthink = parser_find_field(parser, "nextthink");
4214 fld_frame = parser_find_field(parser, "frame");
4215 if (!fld_think || !fld_nextthink || !fld_frame) {
4216 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4217 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4220 gbl_time = parser_find_global(parser, "time");
4221 gbl_self = parser_find_global(parser, "self");
4222 if (!gbl_time || !gbl_self) {
4223 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4224 parseerror(parser, "please declare the following globals: `time`, `self`");
4228 if (!parser_next(parser))
4231 framenum = parse_expression_leave(parser, true, false, false);
4233 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4236 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4237 ast_unref(framenum);
4238 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4242 if (parser->tok != ',') {
4243 ast_unref(framenum);
4244 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4245 parseerror(parser, "Got a %i\n", parser->tok);
4249 if (!parser_next(parser)) {
4250 ast_unref(framenum);
4254 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4256 /* qc allows the use of not-yet-declared functions here
4257 * - this automatically creates a prototype */
4258 ast_value *thinkfunc;
4259 ast_expression *functype = fld_think->expression.next;
4261 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4262 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4263 ast_unref(framenum);
4264 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4267 ast_type_adopt(thinkfunc, functype);
4269 if (!parser_next(parser)) {
4270 ast_unref(framenum);
4271 ast_delete(thinkfunc);
4275 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4277 nextthink = (ast_expression*)thinkfunc;
4280 nextthink = parse_expression_leave(parser, true, false, false);
4282 ast_unref(framenum);
4283 parseerror(parser, "expected a think-function in [frame,think] notation");
4288 if (!ast_istype(nextthink, ast_value)) {
4289 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4293 if (retval && parser->tok != ']') {
4294 parseerror(parser, "expected closing `]` for [frame,think] notation");
4298 if (retval && !parser_next(parser)) {
4302 if (retval && parser->tok != '{') {
4303 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4308 ast_unref(nextthink);
4309 ast_unref(framenum);
4313 has_frame_think = true;
4316 block = ast_block_new(parser_ctx(parser));
4318 parseerror(parser, "failed to allocate block");
4319 if (has_frame_think) {
4320 ast_unref(nextthink);
4321 ast_unref(framenum);
4326 if (has_frame_think) {
4328 ast_expression *self_frame;
4329 ast_expression *self_nextthink;
4330 ast_expression *self_think;
4331 ast_expression *time_plus_1;
4332 ast_store *store_frame;
4333 ast_store *store_nextthink;
4334 ast_store *store_think;
4336 ctx = parser_ctx(parser);
4337 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4338 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4339 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4341 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4342 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4344 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4345 if (self_frame) ast_delete(self_frame);
4346 if (self_nextthink) ast_delete(self_nextthink);
4347 if (self_think) ast_delete(self_think);
4348 if (time_plus_1) ast_delete(time_plus_1);
4354 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4355 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4356 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4359 ast_delete(self_frame);
4362 if (!store_nextthink) {
4363 ast_delete(self_nextthink);
4367 ast_delete(self_think);
4371 if (store_frame) ast_delete(store_frame);
4372 if (store_nextthink) ast_delete(store_nextthink);
4373 if (store_think) ast_delete(store_think);
4376 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4377 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4378 !ast_block_add_expr(block, (ast_expression*)store_think))
4385 parseerror(parser, "failed to generate code for [frame,think]");
4386 ast_unref(nextthink);
4387 ast_unref(framenum);
4393 if (var->hasvalue) {
4394 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4395 ast_block_delete(block);
4399 func = ast_function_new(ast_ctx(var), var->name, var);
4401 parseerror(parser, "failed to allocate function for `%s`", var->name);
4402 ast_block_delete(block);
4405 vec_push(parser->functions, func);
4407 parser_enterblock(parser);
4409 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4411 ast_value *param = var->expression.params[parami];
4414 if (param->expression.vtype != TYPE_VECTOR &&
4415 (param->expression.vtype != TYPE_FIELD ||
4416 param->expression.next->expression.vtype != TYPE_VECTOR))
4421 if (!create_vector_members(param, me)) {
4422 ast_block_delete(block);
4426 for (e = 0; e < 3; ++e) {
4427 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4428 ast_block_collect(block, (ast_expression*)me[e]);
4432 if (var->argcounter) {
4433 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4434 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4438 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4440 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4441 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4442 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4443 varargs->expression.count = 0;
4444 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4445 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4446 ast_delete(varargs);
4447 ast_block_delete(block);
4450 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4451 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4452 ast_delete(varargs);
4453 ast_block_delete(block);
4456 func->varargs = varargs;
4458 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4461 parser->function = func;
4462 if (!parse_block_into(parser, block)) {
4463 ast_block_delete(block);
4467 vec_push(func->blocks, block);
4469 parser->function = old;
4470 if (!parser_leaveblock(parser))
4472 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4473 parseerror(parser, "internal error: local scopes left");
4477 if (parser->tok == ';')
4478 return parser_next(parser);
4479 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4480 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4484 (void)!parser_leaveblock(parser);
4485 vec_pop(parser->functions);
4486 ast_function_delete(func);
4487 var->constval.vfunc = NULL;
4490 parser->function = old;
4494 static ast_expression *array_accessor_split(
4499 ast_expression *left,
4500 ast_expression *right
4506 lex_ctx ctx = ast_ctx(array);
4508 if (!left || !right) {
4509 if (left) ast_delete(left);
4510 if (right) ast_delete(right);
4514 cmp = ast_binary_new(ctx, INSTR_LT,
4515 (ast_expression*)index,
4516 (ast_expression*)parser_const_float(parser, middle));
4520 parseerror(parser, "internal error: failed to create comparison for array setter");
4524 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4526 ast_delete(cmp); /* will delete left and right */
4527 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4531 return (ast_expression*)ifthen;
4534 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4536 lex_ctx ctx = ast_ctx(array);
4538 if (from+1 == afterend) {
4539 /* set this value */
4542 ast_array_index *subscript;
4544 int assignop = type_store_instr[value->expression.vtype];
4546 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4547 assignop = INSTR_STORE_V;
4549 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4553 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4555 ast_delete(subscript);
4559 block = ast_block_new(ctx);
4565 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4570 ret = ast_return_new(ctx, NULL);
4576 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4581 return (ast_expression*)block;
4583 ast_expression *left, *right;
4584 size_t diff = afterend - from;
4585 size_t middle = from + diff/2;
4586 left = array_setter_node(parser, array, index, value, from, middle);
4587 right = array_setter_node(parser, array, index, value, middle, afterend);
4588 return array_accessor_split(parser, array, index, middle, left, right);
4592 static ast_expression *array_field_setter_node(
4601 lex_ctx ctx = ast_ctx(array);
4603 if (from+1 == afterend) {
4604 /* set this value */
4607 ast_entfield *entfield;
4608 ast_array_index *subscript;
4610 int assignop = type_storep_instr[value->expression.vtype];
4612 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4613 assignop = INSTR_STOREP_V;
4615 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4619 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4620 subscript->expression.vtype = TYPE_FIELD;
4622 entfield = ast_entfield_new_force(ctx,
4623 (ast_expression*)entity,
4624 (ast_expression*)subscript,
4625 (ast_expression*)subscript);
4627 ast_delete(subscript);
4631 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4633 ast_delete(entfield);
4637 block = ast_block_new(ctx);
4643 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4648 ret = ast_return_new(ctx, NULL);
4654 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4659 return (ast_expression*)block;
4661 ast_expression *left, *right;
4662 size_t diff = afterend - from;
4663 size_t middle = from + diff/2;
4664 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4665 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4666 return array_accessor_split(parser, array, index, middle, left, right);
4670 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4672 lex_ctx ctx = ast_ctx(array);
4674 if (from+1 == afterend) {
4676 ast_array_index *subscript;
4678 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4682 ret = ast_return_new(ctx, (ast_expression*)subscript);
4684 ast_delete(subscript);
4688 return (ast_expression*)ret;
4690 ast_expression *left, *right;
4691 size_t diff = afterend - from;
4692 size_t middle = from + diff/2;
4693 left = array_getter_node(parser, array, index, from, middle);
4694 right = array_getter_node(parser, array, index, middle, afterend);
4695 return array_accessor_split(parser, array, index, middle, left, right);
4699 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4701 ast_function *func = NULL;
4702 ast_value *fval = NULL;
4703 ast_block *body = NULL;
4705 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4707 parseerror(parser, "failed to create accessor function value");
4711 func = ast_function_new(ast_ctx(array), funcname, fval);
4714 parseerror(parser, "failed to create accessor function node");
4718 body = ast_block_new(ast_ctx(array));
4720 parseerror(parser, "failed to create block for array accessor");
4726 vec_push(func->blocks, body);
4729 vec_push(parser->accessors, fval);
4734 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4736 ast_value *index = NULL;
4737 ast_value *value = NULL;
4741 if (!ast_istype(array->expression.next, ast_value)) {
4742 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4746 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4748 func = fval->constval.vfunc;
4749 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4751 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4752 value = ast_value_copy((ast_value*)array->expression.next);
4754 if (!index || !value) {
4755 parseerror(parser, "failed to create locals for array accessor");
4758 (void)!ast_value_set_name(value, "value"); /* not important */
4759 vec_push(fval->expression.params, index);
4760 vec_push(fval->expression.params, value);
4762 array->setter = fval;
4765 if (index) ast_delete(index);
4766 if (value) ast_delete(value);
4772 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4774 ast_expression *root = NULL;
4775 root = array_setter_node(parser, array,
4776 array->setter->expression.params[0],
4777 array->setter->expression.params[1],
4778 0, array->expression.count);
4780 parseerror(parser, "failed to build accessor search tree");
4783 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4790 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4792 if (!parser_create_array_setter_proto(parser, array, funcname))
4794 return parser_create_array_setter_impl(parser, array);
4797 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4799 ast_expression *root = NULL;
4800 ast_value *entity = NULL;
4801 ast_value *index = NULL;
4802 ast_value *value = NULL;
4806 if (!ast_istype(array->expression.next, ast_value)) {
4807 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4811 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4813 func = fval->constval.vfunc;
4814 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4816 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4817 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4818 value = ast_value_copy((ast_value*)array->expression.next);
4819 if (!entity || !index || !value) {
4820 parseerror(parser, "failed to create locals for array accessor");
4823 (void)!ast_value_set_name(value, "value"); /* not important */
4824 vec_push(fval->expression.params, entity);
4825 vec_push(fval->expression.params, index);
4826 vec_push(fval->expression.params, value);
4828 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4830 parseerror(parser, "failed to build accessor search tree");
4834 array->setter = fval;
4835 return ast_block_add_expr(func->blocks[0], root);
4837 if (entity) ast_delete(entity);
4838 if (index) ast_delete(index);
4839 if (value) ast_delete(value);
4840 if (root) ast_delete(root);
4846 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4848 ast_value *index = NULL;
4852 /* NOTE: checking array->expression.next rather than elemtype since
4853 * for fields elemtype is a temporary fieldtype.
4855 if (!ast_istype(array->expression.next, ast_value)) {
4856 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4860 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4862 func = fval->constval.vfunc;
4863 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4865 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4868 parseerror(parser, "failed to create locals for array accessor");
4871 vec_push(fval->expression.params, index);
4873 array->getter = fval;
4876 if (index) ast_delete(index);
4882 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4884 ast_expression *root = NULL;
4886 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4888 parseerror(parser, "failed to build accessor search tree");
4891 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4898 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4900 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4902 return parser_create_array_getter_impl(parser, array);
4905 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4906 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4914 bool variadic = false;
4915 ast_value *varparam = NULL;
4916 char *argcounter = NULL;
4918 ctx = parser_ctx(parser);
4920 /* for the sake of less code we parse-in in this function */
4921 if (!parser_next(parser)) {
4922 parseerror(parser, "expected parameter list");
4928 /* parse variables until we hit a closing paren */
4929 while (parser->tok != ')') {
4931 /* there must be commas between them */
4932 if (parser->tok != ',') {
4933 parseerror(parser, "expected comma or end of parameter list");
4936 if (!parser_next(parser)) {
4937 parseerror(parser, "expected parameter");
4943 if (parser->tok == TOKEN_DOTS) {
4944 /* '...' indicates a varargs function */
4946 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4947 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4950 if (parser->tok == TOKEN_IDENT) {
4951 argcounter = util_strdup(parser_tokval(parser));
4952 if (!parser_next(parser) || parser->tok != ')') {
4953 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4960 /* for anything else just parse a typename */
4961 param = parse_typename(parser, NULL, NULL);
4964 vec_push(params, param);
4965 if (param->expression.vtype >= TYPE_VARIANT) {
4966 char tname[1024]; /* typename is reserved in C++ */
4967 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4968 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4971 /* type-restricted varargs */
4972 if (parser->tok == TOKEN_DOTS) {
4974 varparam = vec_last(params);
4976 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4977 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4980 if (parser->tok == TOKEN_IDENT) {
4981 argcounter = util_strdup(parser_tokval(parser));
4982 if (!parser_next(parser) || parser->tok != ')') {
4983 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4991 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4995 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4996 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4999 if (!parser_next(parser)) {
5000 parseerror(parser, "parse error after typename");
5004 /* now turn 'var' into a function type */
5005 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
5006 fval->expression.next = (ast_expression*)var;
5008 fval->expression.flags |= AST_FLAG_VARIADIC;
5011 var->expression.params = params;
5012 var->expression.varparam = (ast_expression*)varparam;
5013 var->argcounter = argcounter;
5022 for (i = 0; i < vec_size(params); ++i)
5023 ast_delete(params[i]);
5028 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
5030 ast_expression *cexp;
5031 ast_value *cval, *tmp;
5034 ctx = parser_ctx(parser);
5036 if (!parser_next(parser)) {
5038 parseerror(parser, "expected array-size");
5042 cexp = parse_expression_leave(parser, true, false, false);
5044 if (!cexp || !ast_istype(cexp, ast_value)) {
5048 parseerror(parser, "expected array-size as constant positive integer");
5051 cval = (ast_value*)cexp;
5053 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
5054 tmp->expression.next = (ast_expression*)var;
5057 if (cval->expression.vtype == TYPE_INTEGER)
5058 tmp->expression.count = cval->constval.vint;
5059 else if (cval->expression.vtype == TYPE_FLOAT)
5060 tmp->expression.count = cval->constval.vfloat;
5064 parseerror(parser, "array-size must be a positive integer constant");
5069 if (parser->tok != ']') {
5071 parseerror(parser, "expected ']' after array-size");
5074 if (!parser_next(parser)) {
5076 parseerror(parser, "error after parsing array size");
5082 /* Parse a complete typename.
5083 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5084 * but when parsing variables separated by comma
5085 * 'storebase' should point to where the base-type should be kept.
5086 * The base type makes up every bit of type information which comes *before* the
5089 * The following will be parsed in its entirety:
5091 * The 'basetype' in this case is 'void()'
5092 * and if there's a comma after it, say:
5094 * then the type-information 'void()' can be stored in 'storebase'
5096 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5098 ast_value *var, *tmp;
5101 const char *name = NULL;
5102 bool isfield = false;
5103 bool wasarray = false;
5104 size_t morefields = 0;
5106 ctx = parser_ctx(parser);
5108 /* types may start with a dot */
5109 if (parser->tok == '.') {
5111 /* if we parsed a dot we need a typename now */
5112 if (!parser_next(parser)) {
5113 parseerror(parser, "expected typename for field definition");
5117 /* Further dots are handled seperately because they won't be part of the
5120 while (parser->tok == '.') {
5122 if (!parser_next(parser)) {
5123 parseerror(parser, "expected typename for field definition");
5128 if (parser->tok == TOKEN_IDENT)
5129 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5130 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5131 parseerror(parser, "expected typename");
5135 /* generate the basic type value */
5136 if (cached_typedef) {
5137 var = ast_value_copy(cached_typedef);
5138 ast_value_set_name(var, "<type(from_def)>");
5140 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5142 for (; morefields; --morefields) {
5143 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5144 tmp->expression.next = (ast_expression*)var;
5148 /* do not yet turn into a field - remember:
5149 * .void() foo; is a field too
5150 * .void()() foo; is a function
5154 if (!parser_next(parser)) {
5156 parseerror(parser, "parse error after typename");
5160 /* an opening paren now starts the parameter-list of a function
5161 * this is where original-QC has parameter lists.
5162 * We allow a single parameter list here.
5163 * Much like fteqcc we don't allow `float()() x`
5165 if (parser->tok == '(') {
5166 var = parse_parameter_list(parser, var);
5171 /* store the base if requested */
5173 *storebase = ast_value_copy(var);
5175 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5176 tmp->expression.next = (ast_expression*)*storebase;
5181 /* there may be a name now */
5182 if (parser->tok == TOKEN_IDENT) {
5183 name = util_strdup(parser_tokval(parser));
5185 if (!parser_next(parser)) {
5187 parseerror(parser, "error after variable or field declaration");
5192 /* now this may be an array */
5193 if (parser->tok == '[') {
5195 var = parse_arraysize(parser, var);
5200 /* This is the point where we can turn it into a field */
5202 /* turn it into a field if desired */
5203 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5204 tmp->expression.next = (ast_expression*)var;
5208 /* now there may be function parens again */
5209 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5210 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5211 if (parser->tok == '(' && wasarray)
5212 parseerror(parser, "arrays as part of a return type is not supported");
5213 while (parser->tok == '(') {
5214 var = parse_parameter_list(parser, var);
5222 /* finally name it */
5224 if (!ast_value_set_name(var, name)) {
5226 parseerror(parser, "internal error: failed to set name");
5229 /* free the name, ast_value_set_name duplicates */
5236 static bool parse_typedef(parser_t *parser)
5238 ast_value *typevar, *oldtype;
5239 ast_expression *old;
5241 typevar = parse_typename(parser, NULL, NULL);
5246 if ( (old = parser_find_var(parser, typevar->name)) ) {
5247 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5248 " -> `%s` has been declared here: %s:%i",
5249 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5250 ast_delete(typevar);
5254 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5255 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5256 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5257 ast_delete(typevar);
5261 vec_push(parser->_typedefs, typevar);
5262 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5264 if (parser->tok != ';') {
5265 parseerror(parser, "expected semicolon after typedef");
5268 if (!parser_next(parser)) {
5269 parseerror(parser, "parse error after typedef");
5276 static const char *cvq_to_str(int cvq) {
5278 case CV_NONE: return "none";
5279 case CV_VAR: return "`var`";
5280 case CV_CONST: return "`const`";
5281 default: return "<INVALID>";
5285 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5288 if (proto->cvq != var->cvq) {
5289 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5290 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5291 parser->tok == '='))
5293 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5294 "`%s` declared with different qualifiers: %s\n"
5295 " -> previous declaration here: %s:%i uses %s",
5296 var->name, cvq_to_str(var->cvq),
5297 ast_ctx(proto).file, ast_ctx(proto).line,
5298 cvq_to_str(proto->cvq));
5301 av = (var ->expression.flags & AST_FLAG_NORETURN);
5302 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5304 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5305 "`%s` declared with different attributes%s\n"
5306 " -> previous declaration here: %s:%i",
5307 var->name, (av ? ": noreturn" : ""),
5308 ast_ctx(proto).file, ast_ctx(proto).line,
5309 (ao ? ": noreturn" : ""));
5314 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)
5318 ast_expression *old;
5322 ast_value *basetype = NULL;
5324 bool isparam = false;
5325 bool isvector = false;
5326 bool cleanvar = true;
5327 bool wasarray = false;
5331 if (!localblock && is_static)
5332 parseerror(parser, "`static` qualifier is not supported in global scope");
5334 /* get the first complete variable */
5335 var = parse_typename(parser, &basetype, cached_typedef);
5338 ast_delete(basetype);
5346 /* Part 0: finish the type */
5347 if (parser->tok == '(') {
5348 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5349 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5350 var = parse_parameter_list(parser, var);
5356 /* we only allow 1-dimensional arrays */
5357 if (parser->tok == '[') {
5359 var = parse_arraysize(parser, var);
5365 if (parser->tok == '(' && wasarray) {
5366 parseerror(parser, "arrays as part of a return type is not supported");
5367 /* we'll still parse the type completely for now */
5369 /* for functions returning functions */
5370 while (parser->tok == '(') {
5371 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5372 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5373 var = parse_parameter_list(parser, var);
5380 var->cvq = qualifier;
5381 var->expression.flags |= qflags;
5384 * store the vstring back to var for alias and
5385 * deprecation messages.
5387 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5388 var->expression.flags & AST_FLAG_ALIAS)
5389 var->desc = vstring;
5392 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5393 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5394 * is then filled with the previous definition and the parameter-names replaced.
5396 if (!strcmp(var->name, "nil")) {
5397 if (OPTS_FLAG(UNTYPED_NIL)) {
5398 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5399 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5401 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5404 /* Deal with end_sys_ vars */
5406 if (!strcmp(var->name, "end_sys_globals")) {
5408 parser->crc_globals = vec_size(parser->globals);
5411 else if (!strcmp(var->name, "end_sys_fields")) {
5413 parser->crc_fields = vec_size(parser->fields);
5416 if (was_end && var->expression.vtype == TYPE_FIELD) {
5417 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5418 "global '%s' hint should not be a field",
5419 parser_tokval(parser)))
5426 if (!nofields && var->expression.vtype == TYPE_FIELD)
5428 /* deal with field declarations */
5429 old = parser_find_field(parser, var->name);
5431 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5432 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5441 parseerror(parser, "field `%s` already declared here: %s:%i",
5442 var->name, ast_ctx(old).file, ast_ctx(old).line);
5447 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5448 (old = parser_find_global(parser, var->name)))
5450 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5451 parseerror(parser, "field `%s` already declared here: %s:%i",
5452 var->name, ast_ctx(old).file, ast_ctx(old).line);
5459 /* deal with other globals */
5460 old = parser_find_global(parser, var->name);
5461 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5463 /* This is a function which had a prototype */
5464 if (!ast_istype(old, ast_value)) {
5465 parseerror(parser, "internal error: prototype is not an ast_value");
5469 proto = (ast_value*)old;
5470 proto->desc = var->desc;
5471 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5472 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5474 ast_ctx(proto).file, ast_ctx(proto).line);
5478 /* we need the new parameter-names */
5479 for (i = 0; i < vec_size(proto->expression.params); ++i)
5480 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5481 if (!parser_check_qualifiers(parser, var, proto)) {
5488 proto->expression.flags |= var->expression.flags;
5496 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5497 "global `%s` already declared here: %s:%i",
5498 var->name, ast_ctx(old).file, ast_ctx(old).line))
5503 proto = (ast_value*)old;
5504 if (!ast_istype(old, ast_value)) {
5505 parseerror(parser, "internal error: not an ast_value");
5510 if (!parser_check_qualifiers(parser, var, proto)) {
5515 proto->expression.flags |= var->expression.flags;
5519 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5520 (old = parser_find_field(parser, var->name)))
5522 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5523 parseerror(parser, "global `%s` already declared here: %s:%i",
5524 var->name, ast_ctx(old).file, ast_ctx(old).line);
5531 else /* it's not a global */
5533 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5534 if (old && !isparam) {
5535 parseerror(parser, "local `%s` already declared here: %s:%i",
5536 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5540 old = parser_find_local(parser, var->name, 0, &isparam);
5541 if (old && isparam) {
5542 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5543 "local `%s` is shadowing a parameter", var->name))
5545 parseerror(parser, "local `%s` already declared here: %s:%i",
5546 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5550 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5558 /* in a noref section we simply bump the usecount */
5559 if (noref || parser->noref)
5563 * Create the global/local, and deal with vector types.
5566 if (var->expression.vtype == TYPE_VECTOR)
5568 else if (var->expression.vtype == TYPE_FIELD &&
5569 var->expression.next->expression.vtype == TYPE_VECTOR)
5573 if (!create_vector_members(var, me)) {
5580 /* deal with global variables, fields, functions */
5581 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5582 var->isfield = true;
5583 vec_push(parser->fields, (ast_expression*)var);
5584 util_htset(parser->htfields, var->name, var);
5586 for (i = 0; i < 3; ++i) {
5587 vec_push(parser->fields, (ast_expression*)me[i]);
5588 util_htset(parser->htfields, me[i]->name, me[i]);
5593 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5594 parser_addglobal(parser, var->name, (ast_expression*)var);
5596 for (i = 0; i < 3; ++i) {
5597 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5601 ast_expression *find = parser_find_global(parser, var->desc);
5604 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5608 if (var->expression.vtype != find->expression.vtype) {
5612 ast_type_to_string(find, ty1, sizeof(ty1));
5613 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5615 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5622 * add alias to aliases table and to corrector
5623 * so corrections can apply for aliases as well.
5625 util_htset(parser->aliases, var->name, find);
5628 * add to corrector so corrections can work
5629 * even for aliases too.
5632 vec_last(parser->correct_variables),
5633 &vec_last(parser->correct_variables_score),
5637 /* generate aliases for vector components */
5641 util_asprintf(&buffer[0], "%s_x", var->desc);
5642 util_asprintf(&buffer[1], "%s_y", var->desc);
5643 util_asprintf(&buffer[2], "%s_z", var->desc);
5645 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5646 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5647 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5654 * add to corrector so corrections can work
5655 * even for aliases too.
5658 vec_last(parser->correct_variables),
5659 &vec_last(parser->correct_variables_score),
5663 vec_last(parser->correct_variables),
5664 &vec_last(parser->correct_variables_score),
5668 vec_last(parser->correct_variables),
5669 &vec_last(parser->correct_variables_score),
5677 /* a static adds itself to be generated like any other global
5678 * but is added to the local namespace instead
5680 char *defname = NULL;
5681 size_t prefix_len, ln;
5683 ln = strlen(parser->function->name);
5684 vec_append(defname, ln, parser->function->name);
5686 vec_append(defname, 2, "::");
5687 /* remember the length up to here */
5688 prefix_len = vec_size(defname);
5690 /* Add it to the local scope */
5691 util_htset(vec_last(parser->variables), var->name, (void*)var);
5695 vec_last(parser->correct_variables),
5696 &vec_last(parser->correct_variables_score),
5700 /* now rename the global */
5701 ln = strlen(var->name);
5702 vec_append(defname, ln, var->name);
5703 ast_value_set_name(var, defname);
5705 /* push it to the to-be-generated globals */
5706 vec_push(parser->globals, (ast_expression*)var);
5708 /* same game for the vector members */
5710 for (i = 0; i < 3; ++i) {
5711 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5715 vec_last(parser->correct_variables),
5716 &vec_last(parser->correct_variables_score),
5720 vec_shrinkto(defname, prefix_len);
5721 ln = strlen(me[i]->name);
5722 vec_append(defname, ln, me[i]->name);
5723 ast_member_set_name(me[i], defname);
5725 vec_push(parser->globals, (ast_expression*)me[i]);
5730 vec_push(localblock->locals, var);
5731 parser_addlocal(parser, var->name, (ast_expression*)var);
5733 for (i = 0; i < 3; ++i) {
5734 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5735 ast_block_collect(localblock, (ast_expression*)me[i]);
5741 me[0] = me[1] = me[2] = NULL;
5746 if (var->expression.vtype == TYPE_ARRAY) {
5748 snprintf(name, sizeof(name), "%s##SET", var->name);
5749 if (!parser_create_array_setter(parser, var, name))
5751 snprintf(name, sizeof(name), "%s##GET", var->name);
5752 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5755 else if (!localblock && !nofields &&
5756 var->expression.vtype == TYPE_FIELD &&
5757 var->expression.next->expression.vtype == TYPE_ARRAY)
5760 ast_expression *telem;
5762 ast_value *array = (ast_value*)var->expression.next;
5764 if (!ast_istype(var->expression.next, ast_value)) {
5765 parseerror(parser, "internal error: field element type must be an ast_value");
5769 snprintf(name, sizeof(name), "%s##SETF", var->name);
5770 if (!parser_create_array_field_setter(parser, array, name))
5773 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5774 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5775 tfield->expression.next = telem;
5776 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5777 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5785 if (parser->tok == ';') {
5786 ast_delete(basetype);
5787 if (!parser_next(parser)) {
5788 parseerror(parser, "error after variable declaration");
5794 if (parser->tok == ',')
5798 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5801 parseerror(parser, "missing comma or semicolon while parsing variables");
5805 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5806 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5807 "initializing expression turns variable `%s` into a constant in this standard",
5814 if (parser->tok != '{') {
5815 if (parser->tok != '=') {
5816 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5820 if (!parser_next(parser)) {
5821 parseerror(parser, "error parsing initializer");
5825 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5826 parseerror(parser, "expected '=' before function body in this standard");
5829 if (parser->tok == '#') {
5830 ast_function *func = NULL;
5833 parseerror(parser, "cannot declare builtins within functions");
5836 if (var->expression.vtype != TYPE_FUNCTION) {
5837 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5840 if (!parser_next(parser)) {
5841 parseerror(parser, "expected builtin number");
5844 if (parser->tok != TOKEN_INTCONST) {
5845 parseerror(parser, "builtin number must be an integer constant");
5848 if (parser_token(parser)->constval.i < 0) {
5849 parseerror(parser, "builtin number must be an integer greater than zero");
5853 if (var->hasvalue) {
5854 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5855 "builtin `%s` has already been defined\n"
5856 " -> previous declaration here: %s:%i",
5857 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5861 func = ast_function_new(ast_ctx(var), var->name, var);
5863 parseerror(parser, "failed to allocate function for `%s`", var->name);
5866 vec_push(parser->functions, func);
5868 func->builtin = -parser_token(parser)->constval.i-1;
5871 if (!parser_next(parser)) {
5872 parseerror(parser, "expected comma or semicolon");
5874 ast_function_delete(func);
5875 var->constval.vfunc = NULL;
5879 else if (parser->tok == '{' || parser->tok == '[')
5882 parseerror(parser, "cannot declare functions within functions");
5887 ast_ctx(proto) = parser_ctx(parser);
5889 if (!parse_function_body(parser, var))
5891 ast_delete(basetype);
5892 for (i = 0; i < vec_size(parser->gotos); ++i)
5893 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5894 vec_free(parser->gotos);
5895 vec_free(parser->labels);
5898 ast_expression *cexp;
5901 cexp = parse_expression_leave(parser, true, false, false);
5906 cval = (ast_value*)cexp;
5907 if (cval != parser->nil &&
5908 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5911 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5915 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5916 qualifier != CV_VAR)
5918 var->cvq = CV_CONST;
5920 if (cval == parser->nil)
5921 var->expression.flags |= AST_FLAG_INITIALIZED;
5924 var->hasvalue = true;
5925 if (cval->expression.vtype == TYPE_STRING)
5926 var->constval.vstring = parser_strdup(cval->constval.vstring);
5927 else if (cval->expression.vtype == TYPE_FIELD)
5928 var->constval.vfield = cval;
5930 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5936 shunt sy = { NULL, NULL, NULL, NULL };
5939 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5940 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5941 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5942 if (!parser_sy_apply_operator(parser, &sy))
5945 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5946 parseerror(parser, "internal error: leaked operands");
5947 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5957 if (parser->tok == ',') {
5958 if (!parser_next(parser)) {
5959 parseerror(parser, "expected another variable");
5963 if (parser->tok != TOKEN_IDENT) {
5964 parseerror(parser, "expected another variable");
5967 var = ast_value_copy(basetype);
5969 ast_value_set_name(var, parser_tokval(parser));
5970 if (!parser_next(parser)) {
5971 parseerror(parser, "error parsing variable declaration");
5977 if (parser->tok != ';') {
5978 parseerror(parser, "missing semicolon after variables");
5982 if (!parser_next(parser)) {
5983 parseerror(parser, "parse error after variable declaration");
5987 ast_delete(basetype);
5991 if (cleanvar && var)
5993 ast_delete(basetype);
5997 ast_delete(basetype);
5998 if (cleanvar && var)
6000 if (me[0]) ast_member_delete(me[0]);
6001 if (me[1]) ast_member_delete(me[1]);
6002 if (me[2]) ast_member_delete(me[2]);
6006 static bool parser_global_statement(parser_t *parser)
6010 bool is_static = false;
6011 uint32_t qflags = 0;
6012 ast_value *istype = NULL;
6013 char *vstring = NULL;
6015 if (parser->tok == TOKEN_IDENT)
6016 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6018 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6020 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6022 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6024 if (cvq == CV_WRONG)
6026 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6028 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6030 return parse_enum(parser);
6032 else if (parser->tok == TOKEN_KEYWORD)
6034 if (!strcmp(parser_tokval(parser), "typedef")) {
6035 if (!parser_next(parser)) {
6036 parseerror(parser, "expected type definition after 'typedef'");
6039 return parse_typedef(parser);
6041 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6044 else if (parser->tok == '#')
6046 return parse_pragma(parser);
6048 else if (parser->tok == '$')
6050 if (!parser_next(parser)) {
6051 parseerror(parser, "parse error");
6057 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6063 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6065 return util_crc16(old, str, strlen(str));
6068 static void progdefs_crc_file(const char *str)
6070 /* write to progdefs.h here */
6074 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6076 old = progdefs_crc_sum(old, str);
6077 progdefs_crc_file(str);
6081 static void generate_checksum(parser_t *parser)
6083 uint16_t crc = 0xFFFF;
6087 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6088 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6090 progdefs_crc_file("\tint\tpad;\n");
6091 progdefs_crc_file("\tint\tofs_return[3];\n");
6092 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6093 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6094 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6095 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6096 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6097 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6098 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6099 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6101 for (i = 0; i < parser->crc_globals; ++i) {
6102 if (!ast_istype(parser->globals[i], ast_value))
6104 value = (ast_value*)(parser->globals[i]);
6105 switch (value->expression.vtype) {
6106 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6107 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6108 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6109 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6111 crc = progdefs_crc_both(crc, "\tint\t");
6114 crc = progdefs_crc_both(crc, value->name);
6115 crc = progdefs_crc_both(crc, ";\n");
6117 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6118 for (i = 0; i < parser->crc_fields; ++i) {
6119 if (!ast_istype(parser->fields[i], ast_value))
6121 value = (ast_value*)(parser->fields[i]);
6122 switch (value->expression.next->expression.vtype) {
6123 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6124 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6125 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6126 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6128 crc = progdefs_crc_both(crc, "\tint\t");
6131 crc = progdefs_crc_both(crc, value->name);
6132 crc = progdefs_crc_both(crc, ";\n");
6134 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6139 static parser_t *parser;
6146 parser = (parser_t*)mem_a(sizeof(parser_t));
6150 memset(parser, 0, sizeof(*parser));
6152 for (i = 0; i < operator_count; ++i) {
6153 if (operators[i].id == opid1('=')) {
6154 parser->assign_op = operators+i;
6158 if (!parser->assign_op) {
6159 printf("internal error: initializing parser: failed to find assign operator\n");
6164 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6165 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6166 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6167 vec_push(parser->_blocktypedefs, 0);
6169 parser->aliases = util_htnew(PARSER_HT_SIZE);
6172 vec_push(parser->correct_variables, correct_trie_new());
6173 vec_push(parser->correct_variables_score, NULL);
6175 empty_ctx.file = "<internal>";
6177 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6178 parser->nil->cvq = CV_CONST;
6179 if (OPTS_FLAG(UNTYPED_NIL))
6180 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6182 parser->max_param_count = 1;
6184 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6185 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6186 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6188 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6189 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6190 parser->reserved_version->cvq = CV_CONST;
6191 parser->reserved_version->hasvalue = true;
6192 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6193 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6195 parser->reserved_version = NULL;
6200 bool parser_compile()
6202 /* initial lexer/parser state */
6203 parser->lex->flags.noops = true;
6205 if (parser_next(parser))
6207 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6209 if (!parser_global_statement(parser)) {
6210 if (parser->tok == TOKEN_EOF)
6211 parseerror(parser, "unexpected eof");
6212 else if (compile_errors)
6213 parseerror(parser, "there have been errors, bailing out");
6214 lex_close(parser->lex);
6220 parseerror(parser, "parse error");
6221 lex_close(parser->lex);
6226 lex_close(parser->lex);
6229 return !compile_errors;
6232 bool parser_compile_file(const char *filename)
6234 parser->lex = lex_open(filename);
6236 con_err("failed to open file \"%s\"\n", filename);
6239 return parser_compile();
6242 bool parser_compile_string(const char *name, const char *str, size_t len)
6244 parser->lex = lex_open_string(str, len, name);
6246 con_err("failed to create lexer for string \"%s\"\n", name);
6249 return parser_compile();
6252 void parser_cleanup()
6255 for (i = 0; i < vec_size(parser->accessors); ++i) {
6256 ast_delete(parser->accessors[i]->constval.vfunc);
6257 parser->accessors[i]->constval.vfunc = NULL;
6258 ast_delete(parser->accessors[i]);
6260 for (i = 0; i < vec_size(parser->functions); ++i) {
6261 ast_delete(parser->functions[i]);
6263 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6264 ast_delete(parser->imm_vector[i]);
6266 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6267 ast_delete(parser->imm_string[i]);
6269 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6270 ast_delete(parser->imm_float[i]);
6272 for (i = 0; i < vec_size(parser->fields); ++i) {
6273 ast_delete(parser->fields[i]);
6275 for (i = 0; i < vec_size(parser->globals); ++i) {
6276 ast_delete(parser->globals[i]);
6278 vec_free(parser->accessors);
6279 vec_free(parser->functions);
6280 vec_free(parser->imm_vector);
6281 vec_free(parser->imm_string);
6282 vec_free(parser->imm_float);
6283 vec_free(parser->globals);
6284 vec_free(parser->fields);
6286 for (i = 0; i < vec_size(parser->variables); ++i)
6287 util_htdel(parser->variables[i]);
6288 vec_free(parser->variables);
6289 vec_free(parser->_blocklocals);
6290 vec_free(parser->_locals);
6293 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6294 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6296 vec_free(parser->correct_variables);
6297 vec_free(parser->correct_variables_score);
6300 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6301 ast_delete(parser->_typedefs[i]);
6302 vec_free(parser->_typedefs);
6303 for (i = 0; i < vec_size(parser->typedefs); ++i)
6304 util_htdel(parser->typedefs[i]);
6305 vec_free(parser->typedefs);
6306 vec_free(parser->_blocktypedefs);
6308 vec_free(parser->_block_ctx);
6310 vec_free(parser->labels);
6311 vec_free(parser->gotos);
6312 vec_free(parser->breaks);
6313 vec_free(parser->continues);
6315 ast_value_delete(parser->nil);
6317 ast_value_delete(parser->const_vec[0]);
6318 ast_value_delete(parser->const_vec[1]);
6319 ast_value_delete(parser->const_vec[2]);
6321 util_htdel(parser->aliases);
6326 bool parser_finish(const char *output)
6332 if (compile_errors) {
6333 con_out("*** there were compile errors\n");
6337 ir = ir_builder_new("gmqcc_out");
6339 con_out("failed to allocate builder\n");
6343 for (i = 0; i < vec_size(parser->fields); ++i) {
6346 if (!ast_istype(parser->fields[i], ast_value))
6348 field = (ast_value*)parser->fields[i];
6349 hasvalue = field->hasvalue;
6350 field->hasvalue = false;
6351 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6352 con_out("failed to generate field %s\n", field->name);
6353 ir_builder_delete(ir);
6358 ast_expression *subtype;
6359 field->hasvalue = true;
6360 subtype = field->expression.next;
6361 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6362 if (subtype->expression.vtype == TYPE_FIELD)
6363 ifld->fieldtype = subtype->expression.next->expression.vtype;
6364 else if (subtype->expression.vtype == TYPE_FUNCTION)
6365 ifld->outtype = subtype->expression.next->expression.vtype;
6366 (void)!ir_value_set_field(field->ir_v, ifld);
6369 for (i = 0; i < vec_size(parser->globals); ++i) {
6371 if (!ast_istype(parser->globals[i], ast_value))
6373 asvalue = (ast_value*)(parser->globals[i]);
6374 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6375 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6376 "unused global: `%s`", asvalue->name);
6378 if (!ast_global_codegen(asvalue, ir, false)) {
6379 con_out("failed to generate global %s\n", asvalue->name);
6380 ir_builder_delete(ir);
6384 /* Build function vararg accessor ast tree now before generating
6385 * immediates, because the accessors may add new immediates
6387 for (i = 0; i < vec_size(parser->functions); ++i) {
6388 ast_function *f = parser->functions[i];
6390 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6391 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6392 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6393 con_out("failed to generate vararg setter for %s\n", f->name);
6394 ir_builder_delete(ir);
6397 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6398 con_out("failed to generate vararg getter for %s\n", f->name);
6399 ir_builder_delete(ir);
6403 ast_delete(f->varargs);
6408 /* Now we can generate immediates */
6409 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6410 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6411 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6412 ir_builder_delete(ir);
6416 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6417 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6418 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6419 ir_builder_delete(ir);
6423 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6424 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6425 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6426 ir_builder_delete(ir);
6430 for (i = 0; i < vec_size(parser->globals); ++i) {
6432 if (!ast_istype(parser->globals[i], ast_value))
6434 asvalue = (ast_value*)(parser->globals[i]);
6435 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6437 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6438 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6439 "uninitialized constant: `%s`",
6441 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6442 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6443 "uninitialized global: `%s`",
6446 if (!ast_generate_accessors(asvalue, ir)) {
6447 ir_builder_delete(ir);
6451 for (i = 0; i < vec_size(parser->fields); ++i) {
6453 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6455 if (!ast_istype((ast_expression*)asvalue, ast_value))
6457 if (asvalue->expression.vtype != TYPE_ARRAY)
6459 if (!ast_generate_accessors(asvalue, ir)) {
6460 ir_builder_delete(ir);
6464 if (parser->reserved_version &&
6465 !ast_global_codegen(parser->reserved_version, ir, false))
6467 con_out("failed to generate reserved::version");
6468 ir_builder_delete(ir);
6471 for (i = 0; i < vec_size(parser->functions); ++i) {
6472 ast_function *f = parser->functions[i];
6473 if (!ast_function_codegen(f, ir)) {
6474 con_out("failed to generate function %s\n", f->name);
6475 ir_builder_delete(ir);
6479 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6480 ir_builder_dump(ir, con_out);
6481 for (i = 0; i < vec_size(parser->functions); ++i) {
6482 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6483 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6484 ir_builder_delete(ir);
6489 if (compile_Werrors) {
6490 con_out("*** there were warnings treated as errors\n");
6491 compile_show_werrors();
6496 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6497 ir_builder_dump(ir, con_out);
6499 generate_checksum(parser);
6501 if (!ir_builder_generate(ir, output)) {
6502 con_out("*** failed to generate output file\n");
6503 ir_builder_delete(ir);
6508 ir_builder_delete(ir);