2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 128
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
56 ast_value *reserved_version;
61 ast_function *function;
63 /* All the labels the function defined...
64 * Should they be in ast_function instead?
69 const char **continues;
71 /* A list of hashtables for each scope */
77 /* same as above but for the spelling corrector */
78 correct_trie_t **correct_variables;
79 size_t ***correct_variables_score; /* vector of vector of size_t* */
81 /* not to be used directly, we use the hash table */
82 ast_expression **_locals;
84 ast_value **_typedefs;
85 size_t *_blocktypedefs;
88 /* we store the '=' operator info */
89 const oper_info *assign_op;
92 ast_value *const_vec[3];
97 /* collected information */
98 size_t max_param_count;
101 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
103 static void parser_enterblock(parser_t *parser);
104 static bool parser_leaveblock(parser_t *parser);
105 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
106 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
107 static bool parse_typedef(parser_t *parser);
108 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);
109 static ast_block* parse_block(parser_t *parser);
110 static bool parse_block_into(parser_t *parser, ast_block *block);
111 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
112 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
113 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
114 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
115 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
116 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
117 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
119 static void parseerror(parser_t *parser, const char *fmt, ...)
123 vcompile_error(parser->lex->tok.ctx, fmt, ap);
127 /* returns true if it counts as an error */
128 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
133 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
138 /**********************************************************************
139 * some maths used for constant folding
142 vector vec3_add(vector a, vector b)
151 vector vec3_sub(vector a, vector b)
160 qcfloat vec3_mulvv(vector a, vector b)
162 return (a.x * b.x + a.y * b.y + a.z * b.z);
165 vector vec3_mulvf(vector a, float b)
174 /**********************************************************************
178 bool parser_next(parser_t *parser)
180 /* lex_do kills the previous token */
181 parser->tok = lex_do(parser->lex);
182 if (parser->tok == TOKEN_EOF)
184 if (parser->tok >= TOKEN_ERROR) {
185 parseerror(parser, "lex error");
191 #define parser_tokval(p) ((p)->lex->tok.value)
192 #define parser_token(p) (&((p)->lex->tok))
193 #define parser_ctx(p) ((p)->lex->tok.ctx)
195 static ast_value* parser_const_float(parser_t *parser, double d)
200 for (i = 0; i < vec_size(parser->imm_float); ++i) {
201 const double compare = parser->imm_float[i]->constval.vfloat;
202 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
203 return parser->imm_float[i];
206 ctx = parser_ctx(parser);
208 memset(&ctx, 0, sizeof(ctx));
210 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
212 out->hasvalue = true;
213 out->constval.vfloat = d;
214 vec_push(parser->imm_float, out);
218 static ast_value* parser_const_float_0(parser_t *parser)
220 if (!parser->imm_float_zero)
221 parser->imm_float_zero = parser_const_float(parser, 0);
222 return parser->imm_float_zero;
225 static ast_value* parser_const_float_1(parser_t *parser)
227 if (!parser->imm_float_one)
228 parser->imm_float_one = parser_const_float(parser, 1);
229 return parser->imm_float_one;
232 static char *parser_strdup(const char *str)
235 /* actually dup empty strings */
236 char *out = (char*)mem_a(1);
240 return util_strdup(str);
243 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
247 for (i = 0; i < vec_size(parser->imm_string); ++i) {
248 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
249 return parser->imm_string[i];
253 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
254 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
256 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
258 out->hasvalue = true;
259 out->constval.vstring = parser_strdup(str);
260 vec_push(parser->imm_string, out);
264 static ast_value* parser_const_vector(parser_t *parser, vector v)
268 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
269 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
270 return parser->imm_vector[i];
272 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
274 out->hasvalue = true;
275 out->constval.vvec = v;
276 vec_push(parser->imm_vector, out);
280 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
286 return parser_const_vector(parser, v);
289 static ast_value* parser_const_vector_0(parser_t *parser)
291 if (!parser->imm_vector_zero)
292 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
293 return parser->imm_vector_zero;
296 static ast_expression* parser_find_field(parser_t *parser, const char *name)
298 return ( ast_expression*)util_htget(parser->htfields, name);
301 static ast_expression* parser_find_label(parser_t *parser, const char *name)
304 for(i = 0; i < vec_size(parser->labels); i++)
305 if (!strcmp(parser->labels[i]->name, name))
306 return (ast_expression*)parser->labels[i];
310 static ast_expression* parser_find_global(parser_t *parser, const char *name)
312 return (ast_expression*)util_htget(parser->htglobals, name);
315 static ast_expression* parser_find_param(parser_t *parser, const char *name)
319 if (!parser->function)
321 fun = parser->function->vtype;
322 for (i = 0; i < vec_size(fun->expression.params); ++i) {
323 if (!strcmp(fun->expression.params[i]->name, name))
324 return (ast_expression*)(fun->expression.params[i]);
329 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
334 hash = util_hthash(parser->htglobals, name);
337 for (i = vec_size(parser->variables); i > upto;) {
339 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
343 return parser_find_param(parser, name);
346 static ast_expression* parser_find_var(parser_t *parser, const char *name)
350 v = parser_find_local(parser, name, 0, &dummy);
351 if (!v) v = parser_find_global(parser, name);
355 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
359 hash = util_hthash(parser->typedefs[0], name);
361 for (i = vec_size(parser->typedefs); i > upto;) {
363 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
371 size_t etype; /* 0 = expression, others are operators */
375 ast_block *block; /* for commas and function calls */
394 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
405 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
409 e.out = (ast_expression*)v;
416 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
418 e.etype = 1 + (op - operators);
427 static sy_elem syparen(lex_ctx ctx, size_t off) {
438 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
439 * so we need to rotate it to become ent.(foo[n]).
441 static bool rotate_entfield_array_index_nodes(ast_expression **out)
443 ast_array_index *index;
444 ast_entfield *entfield;
448 ast_expression *entity;
450 lex_ctx ctx = ast_ctx(*out);
452 if (!ast_istype(*out, ast_array_index))
454 index = (ast_array_index*)*out;
456 if (!ast_istype(index->array, ast_entfield))
458 entfield = (ast_entfield*)index->array;
460 if (!ast_istype(entfield->field, ast_value))
462 field = (ast_value*)entfield->field;
465 entity = entfield->entity;
469 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
470 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
471 *out = (ast_expression*)entfield;
476 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
478 switch (v->expression.vtype) {
480 return !!v->constval.vfloat;
482 return !!v->constval.vint;
484 if (OPTS_FLAG(CORRECT_LOGIC))
485 return v->constval.vvec.x &&
486 v->constval.vvec.y &&
489 return !!(v->constval.vvec.x);
491 if (!v->constval.vstring)
493 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
495 return !!v->constval.vstring[0];
497 compile_error(ctx, "internal error: immediate_is_true on invalid type");
498 return !!v->constval.vfunc;
502 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
506 ast_expression *out = NULL;
507 ast_expression *exprs[3];
508 ast_block *blocks[3];
509 ast_value *asvalue[3];
510 ast_binstore *asbinstore;
511 size_t i, assignop, addop, subop;
512 qcint generated_op = 0;
517 if (!vec_size(sy->ops)) {
518 parseerror(parser, "internal error: missing operator");
522 if (vec_last(sy->ops).isparen) {
523 parseerror(parser, "unmatched parenthesis");
527 op = &operators[vec_last(sy->ops).etype - 1];
528 ctx = vec_last(sy->ops).ctx;
530 if (vec_size(sy->out) < op->operands) {
531 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
532 op->op, (int)op->id);
536 vec_shrinkby(sy->ops, 1);
538 /* op(:?) has no input and no output */
542 vec_shrinkby(sy->out, op->operands);
543 for (i = 0; i < op->operands; ++i) {
544 exprs[i] = sy->out[vec_size(sy->out)+i].out;
545 blocks[i] = sy->out[vec_size(sy->out)+i].block;
546 asvalue[i] = (ast_value*)exprs[i];
548 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
549 !(i != 0 && op->id == opid2('?',':')) &&
550 !(i == 1 && op->id == opid1('.')))
552 if (ast_istype(exprs[i], ast_label))
553 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
555 compile_error(ast_ctx(exprs[i]), "not an expression");
556 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
560 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
561 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
565 #define NotSameType(T) \
566 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
567 exprs[0]->expression.vtype != T)
568 #define CanConstFold1(A) \
569 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
570 (A)->expression.vtype != TYPE_FUNCTION)
571 #define CanConstFold(A, B) \
572 (CanConstFold1(A) && CanConstFold1(B))
573 #define ConstV(i) (asvalue[(i)]->constval.vvec)
574 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
575 #define ConstS(i) (asvalue[(i)]->constval.vstring)
579 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
583 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
584 exprs[1]->expression.vtype == TYPE_NOEXPR)
586 if (exprs[1] == (ast_expression*)parser->const_vec[0])
587 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
588 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
589 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
590 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
591 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
593 compile_error(ctx, "access to invalid vector component");
597 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
598 if (exprs[1]->expression.vtype != TYPE_FIELD) {
599 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
602 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
604 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
605 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
609 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
615 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
616 !(exprs[0]->expression.vtype == TYPE_FIELD &&
617 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
619 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
620 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
623 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
624 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
625 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
628 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
629 if (rotate_entfield_array_index_nodes(&out))
632 /* This is not broken in fteqcc anymore */
633 if (opts.standard != COMPILER_GMQCC) {
634 /* this error doesn't need to make us bail out */
635 (void)!parsewarning(parser, WARN_EXTENSIONS,
636 "accessing array-field members of an entity without parenthesis\n"
637 " -> this is an extension from -std=gmqcc");
644 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
645 vec_push(sy->out, syexp(ctx, exprs[0]));
646 vec_push(sy->out, syexp(ctx, exprs[1]));
647 vec_last(sy->argc)++;
651 if (!ast_block_add_expr(blocks[0], exprs[1]))
654 blocks[0] = ast_block_new(ctx);
655 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
656 !ast_block_add_expr(blocks[0], exprs[1]))
661 if (!ast_block_set_type(blocks[0], exprs[1]))
664 vec_push(sy->out, syblock(ctx, blocks[0]));
671 switch (exprs[0]->expression.vtype) {
673 if (CanConstFold1(exprs[0]))
674 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
676 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
677 (ast_expression*)parser_const_float_0(parser),
681 if (CanConstFold1(exprs[0]))
682 out = (ast_expression*)parser_const_vector_f(parser,
683 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
685 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
686 (ast_expression*)parser_const_vector_0(parser),
690 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
691 type_name[exprs[0]->expression.vtype]);
697 switch (exprs[0]->expression.vtype) {
699 if (CanConstFold1(exprs[0]))
700 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
702 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
705 if (CanConstFold1(exprs[0]))
706 out = (ast_expression*)parser_const_float(parser,
707 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
709 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
712 if (CanConstFold1(exprs[0])) {
713 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
714 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
716 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
718 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
721 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
724 /* we don't constant-fold NOT for these types */
726 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
729 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
732 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
733 type_name[exprs[0]->expression.vtype]);
739 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
740 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
742 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
743 type_name[exprs[0]->expression.vtype],
744 type_name[exprs[1]->expression.vtype]);
747 switch (exprs[0]->expression.vtype) {
749 if (CanConstFold(exprs[0], exprs[1]))
751 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
754 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
757 if (CanConstFold(exprs[0], exprs[1]))
758 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
760 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
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]);
770 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
771 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
773 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
774 type_name[exprs[1]->expression.vtype],
775 type_name[exprs[0]->expression.vtype]);
778 switch (exprs[0]->expression.vtype) {
780 if (CanConstFold(exprs[0], exprs[1]))
781 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
783 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
786 if (CanConstFold(exprs[0], exprs[1]))
787 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
789 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
792 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
793 type_name[exprs[1]->expression.vtype],
794 type_name[exprs[0]->expression.vtype]);
799 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
800 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
801 exprs[1]->expression.vtype == TYPE_FLOAT) &&
802 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
803 exprs[0]->expression.vtype == TYPE_FLOAT)
806 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
807 type_name[exprs[1]->expression.vtype],
808 type_name[exprs[0]->expression.vtype]);
811 switch (exprs[0]->expression.vtype) {
813 if (exprs[1]->expression.vtype == TYPE_VECTOR)
815 if (CanConstFold(exprs[0], exprs[1]))
816 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
818 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
825 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
829 if (exprs[1]->expression.vtype == TYPE_FLOAT)
831 if (CanConstFold(exprs[0], exprs[1]))
832 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
834 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
838 if (CanConstFold(exprs[0], exprs[1]))
839 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
840 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
841 vector vec = ConstV(0);
842 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
843 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
844 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
845 out->expression.node.keep = false;
846 ((ast_member*)out)->rvalue = true;
848 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
850 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
851 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
852 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
853 out->expression.node.keep = false;
854 ((ast_member*)out)->rvalue = true;
856 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
858 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
859 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
860 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
861 out->expression.node.keep = false;
862 ((ast_member*)out)->rvalue = true;
864 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
867 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
869 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
870 vector vec = ConstV(1);
871 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
872 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
873 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
874 out->expression.node.keep = false;
875 ((ast_member*)out)->rvalue = true;
877 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
879 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
880 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
881 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
882 out->expression.node.keep = false;
883 ((ast_member*)out)->rvalue = true;
885 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
887 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
888 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
889 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
890 out->expression.node.keep = false;
891 ((ast_member*)out)->rvalue = true;
893 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
896 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
899 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
903 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
904 type_name[exprs[1]->expression.vtype],
905 type_name[exprs[0]->expression.vtype]);
910 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
911 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
912 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
913 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
916 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
917 if (CanConstFold(exprs[0], exprs[1]))
918 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
920 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
922 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
923 if (CanConstFold(exprs[0], exprs[1]))
924 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
926 if (CanConstFold1(exprs[1])) {
927 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
929 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
930 (ast_expression*)parser_const_float_1(parser),
934 compile_error(ctx, "internal error: failed to generate division");
937 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
942 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
943 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
944 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
950 compile_error(ctx, "qc does not have a modulo operator");
954 if (NotSameType(TYPE_FLOAT)) {
955 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
956 type_name[exprs[0]->expression.vtype],
957 type_name[exprs[1]->expression.vtype]);
960 if (CanConstFold(exprs[0], exprs[1]))
961 out = (ast_expression*)parser_const_float(parser,
962 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
963 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
965 out = (ast_expression*)ast_binary_new(ctx,
966 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
970 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
975 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
976 if (op->id == opid2('<','<'))
977 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
979 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
982 case opid3('<','<','='):
983 case opid3('>','>','='):
984 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
988 generated_op += 1; /* INSTR_OR */
990 generated_op += INSTR_AND;
991 if (CanConstFold(exprs[0], exprs[1]))
993 if (OPTS_FLAG(PERL_LOGIC)) {
994 if (immediate_is_true(ctx, asvalue[0]))
998 out = (ast_expression*)parser_const_float(parser,
999 ( (generated_op == INSTR_OR)
1000 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1001 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1006 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1007 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1008 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1009 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1012 for (i = 0; i < 2; ++i) {
1013 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1014 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1016 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1018 exprs[i] = out; out = NULL;
1019 if (OPTS_FLAG(PERL_LOGIC)) {
1020 /* here we want to keep the right expressions' type */
1024 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1025 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1027 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1029 exprs[i] = out; out = NULL;
1030 if (OPTS_FLAG(PERL_LOGIC)) {
1031 /* here we want to keep the right expressions' type */
1036 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1040 case opid2('?',':'):
1041 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1042 compile_error(ctx, "mismatched parenthesis/ternary");
1046 if (!ast_compare_type(exprs[1], exprs[2])) {
1047 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1048 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1049 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1052 if (CanConstFold1(exprs[0]))
1053 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1055 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1059 generated_op += 1; /* INSTR_GT */
1061 generated_op += 1; /* INSTR_LT */
1062 case opid2('>', '='):
1063 generated_op += 1; /* INSTR_GE */
1064 case opid2('<', '='):
1065 generated_op += INSTR_LE;
1066 if (NotSameType(TYPE_FLOAT)) {
1067 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1068 type_name[exprs[0]->expression.vtype],
1069 type_name[exprs[1]->expression.vtype]);
1072 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1074 case opid2('!', '='):
1075 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1076 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1077 type_name[exprs[0]->expression.vtype],
1078 type_name[exprs[1]->expression.vtype]);
1081 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1083 case opid2('=', '='):
1084 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1085 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1086 type_name[exprs[0]->expression.vtype],
1087 type_name[exprs[1]->expression.vtype]);
1090 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1094 if (ast_istype(exprs[0], ast_entfield)) {
1095 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1096 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1097 exprs[0]->expression.vtype == TYPE_FIELD &&
1098 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1100 assignop = type_storep_instr[TYPE_VECTOR];
1103 assignop = type_storep_instr[exprs[0]->expression.vtype];
1104 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1106 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1107 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1108 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1109 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1110 exprs[1]->expression.vtype == TYPE_FUNCTION)
1112 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1113 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1116 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1121 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1122 exprs[0]->expression.vtype == TYPE_FIELD &&
1123 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1125 assignop = type_store_instr[TYPE_VECTOR];
1128 assignop = type_store_instr[exprs[0]->expression.vtype];
1131 if (assignop == AINSTR_END) {
1132 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1133 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1134 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1136 else if (!ast_compare_type(exprs[0], exprs[1]))
1138 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1139 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1140 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1141 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1142 exprs[1]->expression.vtype == TYPE_FUNCTION)
1144 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1145 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1148 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1151 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1152 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1154 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1156 case opid3('+','+','P'):
1157 case opid3('-','-','P'):
1159 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1160 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1161 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1164 if (op->id == opid3('+','+','P'))
1165 addop = INSTR_ADD_F;
1167 addop = INSTR_SUB_F;
1168 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1169 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1171 if (ast_istype(exprs[0], ast_entfield)) {
1172 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1174 (ast_expression*)parser_const_float_1(parser));
1176 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1178 (ast_expression*)parser_const_float_1(parser));
1181 case opid3('S','+','+'):
1182 case opid3('S','-','-'):
1184 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1185 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1186 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1189 if (op->id == opid3('S','+','+')) {
1190 addop = INSTR_ADD_F;
1191 subop = INSTR_SUB_F;
1193 addop = INSTR_SUB_F;
1194 subop = INSTR_ADD_F;
1196 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1197 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1199 if (ast_istype(exprs[0], ast_entfield)) {
1200 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1202 (ast_expression*)parser_const_float_1(parser));
1204 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1206 (ast_expression*)parser_const_float_1(parser));
1210 out = (ast_expression*)ast_binary_new(ctx, subop,
1212 (ast_expression*)parser_const_float_1(parser));
1214 case opid2('+','='):
1215 case opid2('-','='):
1216 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1217 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1219 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1220 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1221 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1225 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1226 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1228 if (ast_istype(exprs[0], ast_entfield))
1229 assignop = type_storep_instr[exprs[0]->expression.vtype];
1231 assignop = type_store_instr[exprs[0]->expression.vtype];
1232 switch (exprs[0]->expression.vtype) {
1234 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1235 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1236 exprs[0], exprs[1]);
1239 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1240 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1241 exprs[0], exprs[1]);
1244 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1245 type_name[exprs[0]->expression.vtype],
1246 type_name[exprs[1]->expression.vtype]);
1250 case opid2('*','='):
1251 case opid2('/','='):
1252 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1253 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1254 exprs[0]->expression.vtype == TYPE_VECTOR))
1256 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1257 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1258 compile_error(ctx, "invalid types used in expression: %s and %s",
1262 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1263 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1265 if (ast_istype(exprs[0], ast_entfield))
1266 assignop = type_storep_instr[exprs[0]->expression.vtype];
1268 assignop = type_store_instr[exprs[0]->expression.vtype];
1269 switch (exprs[0]->expression.vtype) {
1271 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1272 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1273 exprs[0], exprs[1]);
1276 if (op->id == opid2('*','=')) {
1277 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1278 exprs[0], exprs[1]);
1280 /* there's no DIV_VF */
1281 if (CanConstFold1(exprs[1])) {
1282 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1284 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1285 (ast_expression*)parser_const_float_1(parser),
1289 compile_error(ctx, "internal error: failed to generate division");
1292 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1297 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1298 type_name[exprs[0]->expression.vtype],
1299 type_name[exprs[1]->expression.vtype]);
1303 case opid2('&','='):
1304 case opid2('|','='):
1305 if (NotSameType(TYPE_FLOAT)) {
1306 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1307 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1308 compile_error(ctx, "invalid types used in expression: %s and %s",
1312 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1313 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1315 if (ast_istype(exprs[0], ast_entfield))
1316 assignop = type_storep_instr[exprs[0]->expression.vtype];
1318 assignop = type_store_instr[exprs[0]->expression.vtype];
1319 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1320 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1321 exprs[0], exprs[1]);
1323 case opid3('&','~','='):
1324 /* This is like: a &= ~(b);
1325 * But QC has no bitwise-not, so we implement it as
1328 if (NotSameType(TYPE_FLOAT)) {
1329 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1330 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1331 compile_error(ctx, "invalid types used in expression: %s and %s",
1335 if (ast_istype(exprs[0], ast_entfield))
1336 assignop = type_storep_instr[exprs[0]->expression.vtype];
1338 assignop = type_store_instr[exprs[0]->expression.vtype];
1339 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1342 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1343 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1345 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1346 asbinstore->keep_dest = true;
1347 out = (ast_expression*)asbinstore;
1353 compile_error(ctx, "failed to apply operator %s", op->op);
1357 vec_push(sy->out, syexp(ctx, out));
1361 static bool parser_close_call(parser_t *parser, shunt *sy)
1363 /* was a function call */
1364 ast_expression *fun;
1365 ast_value *funval = NULL;
1369 size_t paramcount, i;
1371 fid = vec_last(sy->ops).off;
1372 vec_shrinkby(sy->ops, 1);
1374 /* out[fid] is the function
1375 * everything above is parameters...
1377 if (!vec_size(sy->argc)) {
1378 parseerror(parser, "internal error: no argument counter available");
1382 paramcount = vec_last(sy->argc);
1385 if (vec_size(sy->out) < fid) {
1386 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1387 (unsigned long)vec_size(sy->out),
1389 (unsigned long)paramcount);
1393 fun = sy->out[fid].out;
1395 if (fun == intrinsic_debug_typestring) {
1397 if (fid+2 != vec_size(sy->out) ||
1398 vec_last(sy->out).block)
1400 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1403 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1404 ast_unref(vec_last(sy->out).out);
1405 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1406 (ast_expression*)parser_const_string(parser, ty, false));
1407 vec_shrinkby(sy->out, 1);
1411 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1415 if (fid+1 < vec_size(sy->out))
1418 if (fid+1 + paramcount != vec_size(sy->out)) {
1419 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1420 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1424 for (i = 0; i < paramcount; ++i)
1425 vec_push(call->params, sy->out[fid+1 + i].out);
1426 vec_shrinkby(sy->out, paramcount);
1427 (void)!ast_call_check_types(call);
1428 if (parser->max_param_count < paramcount)
1429 parser->max_param_count = paramcount;
1431 if (ast_istype(fun, ast_value)) {
1432 funval = (ast_value*)fun;
1433 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1434 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1436 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1440 /* overwrite fid, the function, with a call */
1441 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1443 if (fun->expression.vtype != TYPE_FUNCTION) {
1444 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1448 if (!fun->expression.next) {
1449 parseerror(parser, "could not determine function return type");
1452 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1454 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1456 return !parsewarning(parser, WARN_DEPRECATED,
1457 "call to function (which is marked deprecated)\n",
1458 "-> it has been declared here: %s:%i",
1459 ast_ctx(fun).file, ast_ctx(fun).line);
1462 return !parsewarning(parser, WARN_DEPRECATED,
1463 "call to `%s` (which is marked deprecated)\n"
1464 "-> `%s` declared here: %s:%i",
1465 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1467 return !parsewarning(parser, WARN_DEPRECATED,
1468 "call to `%s` (deprecated: %s)\n"
1469 "-> `%s` declared here: %s:%i",
1470 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1474 if (vec_size(fun->expression.params) != paramcount &&
1475 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1476 vec_size(fun->expression.params) < paramcount))
1478 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1480 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1481 "too %s parameters for call to %s: expected %i, got %i\n"
1482 " -> `%s` has been declared here: %s:%i",
1483 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1484 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1486 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1487 "too %s parameters for function call: expected %i, got %i\n"
1488 " -> it has been declared here: %s:%i",
1489 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1490 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1497 static bool parser_close_paren(parser_t *parser, shunt *sy)
1499 if (!vec_size(sy->ops)) {
1500 parseerror(parser, "unmatched closing paren");
1504 while (vec_size(sy->ops)) {
1505 if (vec_last(sy->ops).isparen) {
1506 if (vec_last(sy->paren) == PAREN_FUNC) {
1508 if (!parser_close_call(parser, sy))
1512 if (vec_last(sy->paren) == PAREN_EXPR) {
1514 if (!vec_size(sy->out)) {
1515 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1516 vec_shrinkby(sy->ops, 1);
1519 vec_shrinkby(sy->ops, 1);
1522 if (vec_last(sy->paren) == PAREN_INDEX) {
1524 /* pop off the parenthesis */
1525 vec_shrinkby(sy->ops, 1);
1526 /* then apply the index operator */
1527 if (!parser_sy_apply_operator(parser, sy))
1531 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1532 vec_last(sy->paren) = PAREN_TERNARY2;
1533 /* pop off the parenthesis */
1534 vec_shrinkby(sy->ops, 1);
1537 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1540 if (!parser_sy_apply_operator(parser, sy))
1546 static void parser_reclassify_token(parser_t *parser)
1549 for (i = 0; i < operator_count; ++i) {
1550 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1551 parser->tok = TOKEN_OPERATOR;
1557 static ast_expression* parse_vararg_do(parser_t *parser)
1559 ast_expression *idx, *out;
1561 ast_value *funtype = parser->function->vtype;
1563 lex_ctx ctx = parser_ctx(parser);
1565 if (!parser_next(parser) || parser->tok != '(') {
1566 parseerror(parser, "expected parameter index and type in parenthesis");
1569 if (!parser_next(parser)) {
1570 parseerror(parser, "error parsing parameter index");
1574 idx = parse_expression_leave(parser, true, false, false);
1578 if (parser->tok != ',') {
1580 parseerror(parser, "expected comma after parameter index");
1584 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1586 parseerror(parser, "expected typename for vararg");
1590 typevar = parse_typename(parser, NULL, NULL);
1596 if (parser->tok != ')') {
1598 ast_delete(typevar);
1599 parseerror(parser, "expected closing paren");
1604 if (!parser_next(parser)) {
1606 ast_delete(typevar);
1607 parseerror(parser, "parse error after vararg");
1612 if (!parser->function->varargs) {
1614 ast_delete(typevar);
1615 parseerror(parser, "function has no variable argument list");
1619 if (funtype->expression.varparam &&
1620 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1624 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1625 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1626 compile_error(ast_ctx(typevar),
1627 "function was declared to take varargs of type `%s`, requested type is: %s",
1631 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1632 ast_type_adopt(out, typevar);
1633 ast_delete(typevar);
1637 static ast_expression* parse_vararg(parser_t *parser)
1639 bool old_noops = parser->lex->flags.noops;
1641 ast_expression *out;
1643 parser->lex->flags.noops = true;
1644 out = parse_vararg_do(parser);
1646 parser->lex->flags.noops = old_noops;
1650 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1652 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1653 parser->tok == TOKEN_IDENT &&
1654 !strcmp(parser_tokval(parser), "_"))
1656 /* a translatable string */
1659 parser->lex->flags.noops = true;
1660 if (!parser_next(parser) || parser->tok != '(') {
1661 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1664 parser->lex->flags.noops = false;
1665 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1666 parseerror(parser, "expected a constant string in translatable-string extension");
1669 val = parser_const_string(parser, parser_tokval(parser), true);
1672 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1674 if (!parser_next(parser) || parser->tok != ')') {
1675 parseerror(parser, "expected closing paren after translatable string");
1680 else if (parser->tok == TOKEN_DOTS)
1683 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1684 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1687 va = parse_vararg(parser);
1690 vec_push(sy->out, syexp(parser_ctx(parser), va));
1693 else if (parser->tok == TOKEN_FLOATCONST) {
1695 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1698 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1701 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1703 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1706 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1709 else if (parser->tok == TOKEN_STRINGCONST) {
1711 val = parser_const_string(parser, parser_tokval(parser), false);
1714 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1717 else if (parser->tok == TOKEN_VECTORCONST) {
1719 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1722 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1725 else if (parser->tok == TOKEN_IDENT)
1727 const char *ctoken = parser_tokval(parser);
1728 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1729 ast_expression *var;
1730 /* a_vector.{x,y,z} */
1731 if (!vec_size(sy->ops) ||
1732 !vec_last(sy->ops).etype ||
1733 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1734 (prev >= intrinsic_debug_typestring &&
1735 prev <= intrinsic_debug_typestring))
1737 /* When adding more intrinsics, fix the above condition */
1740 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1742 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1744 var = parser_find_var(parser, parser_tokval(parser));
1746 var = parser_find_field(parser, parser_tokval(parser));
1748 if (!var && with_labels) {
1749 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1751 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1752 var = (ast_expression*)lbl;
1753 vec_push(parser->labels, lbl);
1758 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1759 var = (ast_expression*)intrinsic_debug_typestring;
1763 char *correct = NULL;
1767 * sometimes people use preprocessing predefs without enabling them
1768 * i've done this thousands of times already myself. Lets check for
1769 * it in the predef table. And diagnose it better :)
1771 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1772 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1773 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1774 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1781 * TODO: determine the best score for the identifier: be it
1782 * a variable, a field.
1784 * We should also consider adding correction tables for
1785 * other things as well.
1787 if (opts.correction) {
1789 correct_init(&corr);
1791 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1792 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1793 if (strcmp(correct, parser_tokval(parser))) {
1795 } else if (correct) {
1800 correct_free(&corr);
1803 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1808 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1814 if (ast_istype(var, ast_value)) {
1815 ((ast_value*)var)->uses++;
1817 else if (ast_istype(var, ast_member)) {
1818 ast_member *mem = (ast_member*)var;
1819 if (ast_istype(mem->owner, ast_value))
1820 ((ast_value*)(mem->owner))->uses++;
1823 vec_push(sy->out, syexp(parser_ctx(parser), var));
1826 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1830 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1832 ast_expression *expr = NULL;
1835 bool wantop = false;
1836 /* only warn once about an assignment in a truth value because the current code
1837 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1839 bool warn_truthvalue = true;
1841 /* count the parens because an if starts with one, so the
1842 * end of a condition is an unmatched closing paren
1846 memset(&sy, 0, sizeof(sy));
1848 parser->lex->flags.noops = false;
1850 parser_reclassify_token(parser);
1854 if (parser->tok == TOKEN_TYPENAME) {
1855 parseerror(parser, "unexpected typename");
1859 if (parser->tok == TOKEN_OPERATOR)
1861 /* classify the operator */
1862 const oper_info *op;
1863 const oper_info *olast = NULL;
1865 for (o = 0; o < operator_count; ++o) {
1866 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1867 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1868 !strcmp(parser_tokval(parser), operators[o].op))
1873 if (o == operator_count) {
1874 /* no operator found... must be the end of the statement */
1877 /* found an operator */
1880 /* when declaring variables, a comma starts a new variable */
1881 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1882 /* fixup the token */
1887 /* a colon without a pervious question mark cannot be a ternary */
1888 if (!ternaries && op->id == opid2(':','?')) {
1893 if (op->id == opid1(',')) {
1894 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1895 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1899 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1900 olast = &operators[vec_last(sy.ops).etype-1];
1902 #define IsAssignOp(x) (\
1903 (x) == opid1('=') || \
1904 (x) == opid2('+','=') || \
1905 (x) == opid2('-','=') || \
1906 (x) == opid2('*','=') || \
1907 (x) == opid2('/','=') || \
1908 (x) == opid2('%','=') || \
1909 (x) == opid2('&','=') || \
1910 (x) == opid2('|','=') || \
1911 (x) == opid3('&','~','=') \
1913 if (warn_truthvalue) {
1914 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1915 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1916 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1919 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1920 warn_truthvalue = false;
1925 (op->prec < olast->prec) ||
1926 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1928 if (!parser_sy_apply_operator(parser, &sy))
1930 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1931 olast = &operators[vec_last(sy.ops).etype-1];
1936 if (op->id == opid1('(')) {
1938 size_t sycount = vec_size(sy.out);
1939 /* we expected an operator, this is the function-call operator */
1940 vec_push(sy.paren, PAREN_FUNC);
1941 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1942 vec_push(sy.argc, 0);
1944 vec_push(sy.paren, PAREN_EXPR);
1945 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1948 } else if (op->id == opid1('[')) {
1950 parseerror(parser, "unexpected array subscript");
1953 vec_push(sy.paren, PAREN_INDEX);
1954 /* push both the operator and the paren, this makes life easier */
1955 vec_push(sy.ops, syop(parser_ctx(parser), op));
1956 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1958 } else if (op->id == opid2('?',':')) {
1959 vec_push(sy.ops, syop(parser_ctx(parser), op));
1960 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1963 vec_push(sy.paren, PAREN_TERNARY1);
1964 } else if (op->id == opid2(':','?')) {
1965 if (!vec_size(sy.paren)) {
1966 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1969 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1970 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1973 if (!parser_close_paren(parser, &sy))
1975 vec_push(sy.ops, syop(parser_ctx(parser), op));
1979 vec_push(sy.ops, syop(parser_ctx(parser), op));
1980 wantop = !!(op->flags & OP_SUFFIX);
1983 else if (parser->tok == ')') {
1984 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1985 if (!parser_sy_apply_operator(parser, &sy))
1988 if (!vec_size(sy.paren))
1991 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1992 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1995 if (!parser_close_paren(parser, &sy))
1998 /* must be a function call without parameters */
1999 if (vec_last(sy.paren) != PAREN_FUNC) {
2000 parseerror(parser, "closing paren in invalid position");
2003 if (!parser_close_paren(parser, &sy))
2008 else if (parser->tok == '(') {
2009 parseerror(parser, "internal error: '(' should be classified as operator");
2012 else if (parser->tok == '[') {
2013 parseerror(parser, "internal error: '[' should be classified as operator");
2016 else if (parser->tok == ']') {
2017 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2018 if (!parser_sy_apply_operator(parser, &sy))
2021 if (!vec_size(sy.paren))
2023 if (vec_last(sy.paren) != PAREN_INDEX) {
2024 parseerror(parser, "mismatched parentheses, unexpected ']'");
2027 if (!parser_close_paren(parser, &sy))
2032 if (!parse_sya_operand(parser, &sy, with_labels))
2035 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2036 vec_last(sy.argc)++;
2041 parseerror(parser, "expected operator or end of statement");
2045 if (!parser_next(parser)) {
2048 if (parser->tok == ';' ||
2049 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2050 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2056 while (vec_size(sy.ops)) {
2057 if (!parser_sy_apply_operator(parser, &sy))
2061 parser->lex->flags.noops = true;
2062 if (!vec_size(sy.out)) {
2063 parseerror(parser, "empty expression");
2066 expr = sy.out[0].out;
2069 if (vec_size(sy.paren)) {
2070 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2078 parser->lex->flags.noops = true;
2079 for (i = 0; i < vec_size(sy.out); ++i) {
2081 ast_unref(sy.out[i].out);
2090 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2092 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2095 if (parser->tok != ';') {
2096 parseerror(parser, "semicolon expected after expression");
2100 if (!parser_next(parser)) {
2107 static void parser_enterblock(parser_t *parser)
2109 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2110 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2111 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2112 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2113 vec_push(parser->_block_ctx, parser_ctx(parser));
2116 vec_push(parser->correct_variables, correct_trie_new());
2117 vec_push(parser->correct_variables_score, NULL);
2120 static bool parser_leaveblock(parser_t *parser)
2123 size_t locals, typedefs;
2125 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2126 parseerror(parser, "internal error: parser_leaveblock with no block");
2130 util_htdel(vec_last(parser->variables));
2131 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2133 vec_pop(parser->variables);
2134 vec_pop(parser->correct_variables);
2135 vec_pop(parser->correct_variables_score);
2136 if (!vec_size(parser->_blocklocals)) {
2137 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2141 locals = vec_last(parser->_blocklocals);
2142 vec_pop(parser->_blocklocals);
2143 while (vec_size(parser->_locals) != locals) {
2144 ast_expression *e = vec_last(parser->_locals);
2145 ast_value *v = (ast_value*)e;
2146 vec_pop(parser->_locals);
2147 if (ast_istype(e, ast_value) && !v->uses) {
2148 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2153 typedefs = vec_last(parser->_blocktypedefs);
2154 while (vec_size(parser->_typedefs) != typedefs) {
2155 ast_delete(vec_last(parser->_typedefs));
2156 vec_pop(parser->_typedefs);
2158 util_htdel(vec_last(parser->typedefs));
2159 vec_pop(parser->typedefs);
2161 vec_pop(parser->_block_ctx);
2166 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2168 vec_push(parser->_locals, e);
2169 util_htset(vec_last(parser->variables), name, (void*)e);
2173 vec_last(parser->correct_variables),
2174 &vec_last(parser->correct_variables_score),
2179 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2181 vec_push(parser->globals, e);
2182 util_htset(parser->htglobals, name, e);
2186 parser->correct_variables[0],
2187 &parser->correct_variables_score[0],
2192 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2196 ast_expression *prev;
2198 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2200 ast_type_to_string(cond, ty, sizeof(ty));
2201 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2204 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2207 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2210 parseerror(parser, "internal error: failed to process condition");
2215 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2217 /* vector types need to be cast to true booleans */
2218 ast_binary *bin = (ast_binary*)cond;
2219 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2221 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2223 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2226 parseerror(parser, "internal error: failed to process condition");
2233 unary = (ast_unary*)cond;
2234 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2236 cond = unary->operand;
2237 unary->operand = NULL;
2240 unary = (ast_unary*)cond;
2244 parseerror(parser, "internal error: failed to process condition");
2246 if (ifnot) *_ifnot = !*_ifnot;
2250 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2253 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2256 lex_ctx ctx = parser_ctx(parser);
2258 (void)block; /* not touching */
2260 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2261 if (!parser_next(parser)) {
2262 parseerror(parser, "expected condition or 'not'");
2265 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2267 if (!parser_next(parser)) {
2268 parseerror(parser, "expected condition in parenthesis");
2272 if (parser->tok != '(') {
2273 parseerror(parser, "expected 'if' condition in parenthesis");
2276 /* parse into the expression */
2277 if (!parser_next(parser)) {
2278 parseerror(parser, "expected 'if' condition after opening paren");
2281 /* parse the condition */
2282 cond = parse_expression_leave(parser, false, true, false);
2286 if (parser->tok != ')') {
2287 parseerror(parser, "expected closing paren after 'if' condition");
2291 /* parse into the 'then' branch */
2292 if (!parser_next(parser)) {
2293 parseerror(parser, "expected statement for on-true branch of 'if'");
2297 if (!parse_statement_or_block(parser, &ontrue)) {
2302 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2303 /* check for an else */
2304 if (!strcmp(parser_tokval(parser), "else")) {
2305 /* parse into the 'else' branch */
2306 if (!parser_next(parser)) {
2307 parseerror(parser, "expected on-false branch after 'else'");
2312 if (!parse_statement_or_block(parser, &onfalse)) {
2319 cond = process_condition(parser, cond, &ifnot);
2321 if (ontrue) ast_delete(ontrue);
2322 if (onfalse) ast_delete(onfalse);
2327 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2329 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2330 *out = (ast_expression*)ifthen;
2334 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2335 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2340 /* skip the 'while' and get the body */
2341 if (!parser_next(parser)) {
2342 if (OPTS_FLAG(LOOP_LABELS))
2343 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2345 parseerror(parser, "expected 'while' condition in parenthesis");
2349 if (parser->tok == ':') {
2350 if (!OPTS_FLAG(LOOP_LABELS))
2351 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2352 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2353 parseerror(parser, "expected loop label");
2356 label = util_strdup(parser_tokval(parser));
2357 if (!parser_next(parser)) {
2359 parseerror(parser, "expected 'while' condition in parenthesis");
2364 if (parser->tok != '(') {
2365 parseerror(parser, "expected 'while' condition in parenthesis");
2369 vec_push(parser->breaks, label);
2370 vec_push(parser->continues, label);
2372 rv = parse_while_go(parser, block, out);
2375 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2376 parseerror(parser, "internal error: label stack corrupted");
2382 vec_pop(parser->breaks);
2383 vec_pop(parser->continues);
2388 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2391 ast_expression *cond, *ontrue;
2395 lex_ctx ctx = parser_ctx(parser);
2397 (void)block; /* not touching */
2399 /* parse into the expression */
2400 if (!parser_next(parser)) {
2401 parseerror(parser, "expected 'while' condition after opening paren");
2404 /* parse the condition */
2405 cond = parse_expression_leave(parser, false, true, false);
2409 if (parser->tok != ')') {
2410 parseerror(parser, "expected closing paren after 'while' condition");
2414 /* parse into the 'then' branch */
2415 if (!parser_next(parser)) {
2416 parseerror(parser, "expected while-loop body");
2420 if (!parse_statement_or_block(parser, &ontrue)) {
2425 cond = process_condition(parser, cond, &ifnot);
2430 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2431 *out = (ast_expression*)aloop;
2435 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2436 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2441 /* skip the 'do' and get the body */
2442 if (!parser_next(parser)) {
2443 if (OPTS_FLAG(LOOP_LABELS))
2444 parseerror(parser, "expected loop label or body");
2446 parseerror(parser, "expected loop body");
2450 if (parser->tok == ':') {
2451 if (!OPTS_FLAG(LOOP_LABELS))
2452 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2453 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2454 parseerror(parser, "expected loop label");
2457 label = util_strdup(parser_tokval(parser));
2458 if (!parser_next(parser)) {
2460 parseerror(parser, "expected loop body");
2465 vec_push(parser->breaks, label);
2466 vec_push(parser->continues, label);
2468 rv = parse_dowhile_go(parser, block, out);
2471 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2472 parseerror(parser, "internal error: label stack corrupted");
2478 vec_pop(parser->breaks);
2479 vec_pop(parser->continues);
2484 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2487 ast_expression *cond, *ontrue;
2491 lex_ctx ctx = parser_ctx(parser);
2493 (void)block; /* not touching */
2495 if (!parse_statement_or_block(parser, &ontrue))
2498 /* expect the "while" */
2499 if (parser->tok != TOKEN_KEYWORD ||
2500 strcmp(parser_tokval(parser), "while"))
2502 parseerror(parser, "expected 'while' and condition");
2507 /* skip the 'while' and check for opening paren */
2508 if (!parser_next(parser) || parser->tok != '(') {
2509 parseerror(parser, "expected 'while' condition in parenthesis");
2513 /* parse into the expression */
2514 if (!parser_next(parser)) {
2515 parseerror(parser, "expected 'while' condition after opening paren");
2519 /* parse the condition */
2520 cond = parse_expression_leave(parser, false, true, false);
2524 if (parser->tok != ')') {
2525 parseerror(parser, "expected closing paren after 'while' condition");
2531 if (!parser_next(parser) || parser->tok != ';') {
2532 parseerror(parser, "expected semicolon after condition");
2538 if (!parser_next(parser)) {
2539 parseerror(parser, "parse error");
2545 cond = process_condition(parser, cond, &ifnot);
2550 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2551 *out = (ast_expression*)aloop;
2555 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2556 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2561 /* skip the 'for' and check for opening paren */
2562 if (!parser_next(parser)) {
2563 if (OPTS_FLAG(LOOP_LABELS))
2564 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2566 parseerror(parser, "expected 'for' expressions in parenthesis");
2570 if (parser->tok == ':') {
2571 if (!OPTS_FLAG(LOOP_LABELS))
2572 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2573 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2574 parseerror(parser, "expected loop label");
2577 label = util_strdup(parser_tokval(parser));
2578 if (!parser_next(parser)) {
2580 parseerror(parser, "expected 'for' expressions in parenthesis");
2585 if (parser->tok != '(') {
2586 parseerror(parser, "expected 'for' expressions in parenthesis");
2590 vec_push(parser->breaks, label);
2591 vec_push(parser->continues, label);
2593 rv = parse_for_go(parser, block, out);
2596 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2597 parseerror(parser, "internal error: label stack corrupted");
2603 vec_pop(parser->breaks);
2604 vec_pop(parser->continues);
2608 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2611 ast_expression *initexpr, *cond, *increment, *ontrue;
2617 lex_ctx ctx = parser_ctx(parser);
2619 parser_enterblock(parser);
2626 /* parse into the expression */
2627 if (!parser_next(parser)) {
2628 parseerror(parser, "expected 'for' initializer after opening paren");
2633 if (parser->tok == TOKEN_IDENT)
2634 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2636 if (typevar || parser->tok == TOKEN_TYPENAME) {
2638 if (opts.standard != COMPILER_GMQCC) {
2639 if (parsewarning(parser, WARN_EXTENSIONS,
2640 "current standard does not allow variable declarations in for-loop initializers"))
2644 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2647 else if (parser->tok != ';')
2649 initexpr = parse_expression_leave(parser, false, false, false);
2654 /* move on to condition */
2655 if (parser->tok != ';') {
2656 parseerror(parser, "expected semicolon after for-loop initializer");
2659 if (!parser_next(parser)) {
2660 parseerror(parser, "expected for-loop condition");
2664 /* parse the condition */
2665 if (parser->tok != ';') {
2666 cond = parse_expression_leave(parser, false, true, false);
2671 /* move on to incrementor */
2672 if (parser->tok != ';') {
2673 parseerror(parser, "expected semicolon after for-loop initializer");
2676 if (!parser_next(parser)) {
2677 parseerror(parser, "expected for-loop condition");
2681 /* parse the incrementor */
2682 if (parser->tok != ')') {
2683 lex_ctx condctx = parser_ctx(parser);
2684 increment = parse_expression_leave(parser, false, false, false);
2687 if (!ast_side_effects(increment)) {
2688 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2694 if (parser->tok != ')') {
2695 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2698 /* parse into the 'then' branch */
2699 if (!parser_next(parser)) {
2700 parseerror(parser, "expected for-loop body");
2703 if (!parse_statement_or_block(parser, &ontrue))
2707 cond = process_condition(parser, cond, &ifnot);
2711 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2712 *out = (ast_expression*)aloop;
2714 if (!parser_leaveblock(parser))
2718 if (initexpr) ast_delete(initexpr);
2719 if (cond) ast_delete(cond);
2720 if (increment) ast_delete(increment);
2721 (void)!parser_leaveblock(parser);
2725 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2727 ast_expression *exp = NULL;
2728 ast_return *ret = NULL;
2729 ast_value *expected = parser->function->vtype;
2731 lex_ctx ctx = parser_ctx(parser);
2733 (void)block; /* not touching */
2735 if (!parser_next(parser)) {
2736 parseerror(parser, "expected return expression");
2740 if (parser->tok != ';') {
2741 exp = parse_expression(parser, false, false);
2745 if (exp->expression.vtype != TYPE_NIL &&
2746 exp->expression.vtype != expected->expression.next->expression.vtype)
2748 parseerror(parser, "return with invalid expression");
2751 ret = ast_return_new(ctx, exp);
2757 if (!parser_next(parser))
2758 parseerror(parser, "parse error");
2759 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2760 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2762 ret = ast_return_new(ctx, NULL);
2764 *out = (ast_expression*)ret;
2768 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2771 unsigned int levels = 0;
2772 lex_ctx ctx = parser_ctx(parser);
2773 const char **loops = (is_continue ? parser->continues : parser->breaks);
2775 (void)block; /* not touching */
2776 if (!parser_next(parser)) {
2777 parseerror(parser, "expected semicolon or loop label");
2781 if (!vec_size(loops)) {
2783 parseerror(parser, "`continue` can only be used inside loops");
2785 parseerror(parser, "`break` can only be used inside loops or switches");
2788 if (parser->tok == TOKEN_IDENT) {
2789 if (!OPTS_FLAG(LOOP_LABELS))
2790 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2791 i = vec_size(loops);
2793 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2796 parseerror(parser, "no such loop to %s: `%s`",
2797 (is_continue ? "continue" : "break out of"),
2798 parser_tokval(parser));
2803 if (!parser_next(parser)) {
2804 parseerror(parser, "expected semicolon");
2809 if (parser->tok != ';') {
2810 parseerror(parser, "expected semicolon");
2814 if (!parser_next(parser))
2815 parseerror(parser, "parse error");
2817 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2821 /* returns true when it was a variable qualifier, false otherwise!
2822 * on error, cvq is set to CV_WRONG
2824 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2826 bool had_const = false;
2827 bool had_var = false;
2828 bool had_noref = false;
2829 bool had_attrib = false;
2830 bool had_static = false;
2835 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2837 /* parse an attribute */
2838 if (!parser_next(parser)) {
2839 parseerror(parser, "expected attribute after `[[`");
2843 if (!strcmp(parser_tokval(parser), "noreturn")) {
2844 flags |= AST_FLAG_NORETURN;
2845 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2846 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2851 else if (!strcmp(parser_tokval(parser), "noref")) {
2853 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2854 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2859 else if (!strcmp(parser_tokval(parser), "inline")) {
2860 flags |= AST_FLAG_INLINE;
2861 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2862 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2869 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2870 flags |= AST_FLAG_DEPRECATED;
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "parse error in attribute");
2878 if (parser->tok == '(') {
2879 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2880 parseerror(parser, "`deprecated` attribute missing parameter");
2884 *message = util_strdup(parser_tokval(parser));
2886 if (!parser_next(parser)) {
2887 parseerror(parser, "parse error in attribute");
2891 if(parser->tok != ')') {
2892 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2896 if (!parser_next(parser)) {
2897 parseerror(parser, "parse error in attribute");
2902 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2903 parseerror(parser, "`deprecated` attribute expected `]]`");
2906 if (*message) mem_d(*message);
2914 /* Skip tokens until we hit a ]] */
2915 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2916 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2917 if (!parser_next(parser)) {
2918 parseerror(parser, "error inside attribute");
2925 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2927 else if (!strcmp(parser_tokval(parser), "const"))
2929 else if (!strcmp(parser_tokval(parser), "var"))
2931 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2933 else if (!strcmp(parser_tokval(parser), "noref"))
2935 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2940 if (!parser_next(parser))
2950 *is_static = had_static;
2954 parseerror(parser, "parse error after variable qualifier");
2959 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2960 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2965 /* skip the 'while' and get the body */
2966 if (!parser_next(parser)) {
2967 if (OPTS_FLAG(LOOP_LABELS))
2968 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2970 parseerror(parser, "expected 'switch' operand in parenthesis");
2974 if (parser->tok == ':') {
2975 if (!OPTS_FLAG(LOOP_LABELS))
2976 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2977 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2978 parseerror(parser, "expected loop label");
2981 label = util_strdup(parser_tokval(parser));
2982 if (!parser_next(parser)) {
2984 parseerror(parser, "expected 'switch' operand in parenthesis");
2989 if (parser->tok != '(') {
2990 parseerror(parser, "expected 'switch' operand in parenthesis");
2994 vec_push(parser->breaks, label);
2996 rv = parse_switch_go(parser, block, out);
2999 if (vec_last(parser->breaks) != label) {
3000 parseerror(parser, "internal error: label stack corrupted");
3006 vec_pop(parser->breaks);
3011 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3013 ast_expression *operand;
3016 ast_switch *switchnode;
3017 ast_switch_case swcase;
3020 bool noref, is_static;
3021 uint32_t qflags = 0;
3023 lex_ctx ctx = parser_ctx(parser);
3025 (void)block; /* not touching */
3028 /* parse into the expression */
3029 if (!parser_next(parser)) {
3030 parseerror(parser, "expected switch operand");
3033 /* parse the operand */
3034 operand = parse_expression_leave(parser, false, false, false);
3038 switchnode = ast_switch_new(ctx, operand);
3041 if (parser->tok != ')') {
3042 ast_delete(switchnode);
3043 parseerror(parser, "expected closing paren after 'switch' operand");
3047 /* parse over the opening paren */
3048 if (!parser_next(parser) || parser->tok != '{') {
3049 ast_delete(switchnode);
3050 parseerror(parser, "expected list of cases");
3054 if (!parser_next(parser)) {
3055 ast_delete(switchnode);
3056 parseerror(parser, "expected 'case' or 'default'");
3060 /* new block; allow some variables to be declared here */
3061 parser_enterblock(parser);
3064 if (parser->tok == TOKEN_IDENT)
3065 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3066 if (typevar || parser->tok == TOKEN_TYPENAME) {
3067 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3068 ast_delete(switchnode);
3073 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3075 if (cvq == CV_WRONG) {
3076 ast_delete(switchnode);
3079 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3080 ast_delete(switchnode);
3089 while (parser->tok != '}') {
3090 ast_block *caseblock;
3092 if (!strcmp(parser_tokval(parser), "case")) {
3093 if (!parser_next(parser)) {
3094 ast_delete(switchnode);
3095 parseerror(parser, "expected expression for case");
3098 swcase.value = parse_expression_leave(parser, false, false, false);
3099 if (!swcase.value) {
3100 ast_delete(switchnode);
3101 parseerror(parser, "expected expression for case");
3104 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3105 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3106 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3112 else if (!strcmp(parser_tokval(parser), "default")) {
3113 swcase.value = NULL;
3114 if (!parser_next(parser)) {
3115 ast_delete(switchnode);
3116 parseerror(parser, "expected colon");
3121 ast_delete(switchnode);
3122 parseerror(parser, "expected 'case' or 'default'");
3126 /* Now the colon and body */
3127 if (parser->tok != ':') {
3128 if (swcase.value) ast_unref(swcase.value);
3129 ast_delete(switchnode);
3130 parseerror(parser, "expected colon");
3134 if (!parser_next(parser)) {
3135 if (swcase.value) ast_unref(swcase.value);
3136 ast_delete(switchnode);
3137 parseerror(parser, "expected statements or case");
3140 caseblock = ast_block_new(parser_ctx(parser));
3142 if (swcase.value) ast_unref(swcase.value);
3143 ast_delete(switchnode);
3146 swcase.code = (ast_expression*)caseblock;
3147 vec_push(switchnode->cases, swcase);
3149 ast_expression *expr;
3150 if (parser->tok == '}')
3152 if (parser->tok == TOKEN_KEYWORD) {
3153 if (!strcmp(parser_tokval(parser), "case") ||
3154 !strcmp(parser_tokval(parser), "default"))
3159 if (!parse_statement(parser, caseblock, &expr, true)) {
3160 ast_delete(switchnode);
3165 if (!ast_block_add_expr(caseblock, expr)) {
3166 ast_delete(switchnode);
3172 parser_leaveblock(parser);
3175 if (parser->tok != '}') {
3176 ast_delete(switchnode);
3177 parseerror(parser, "expected closing paren of case list");
3180 if (!parser_next(parser)) {
3181 ast_delete(switchnode);
3182 parseerror(parser, "parse error after switch");
3185 *out = (ast_expression*)switchnode;
3189 /* parse computed goto sides */
3190 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3191 ast_expression *on_true;
3192 ast_expression *on_false;
3193 ast_expression *cond;
3198 if (ast_istype(*side, ast_ternary)) {
3199 ast_ternary *tern = (ast_ternary*)*side;
3200 on_true = parse_goto_computed(parser, &tern->on_true);
3201 on_false = parse_goto_computed(parser, &tern->on_false);
3203 if (!on_true || !on_false) {
3204 parseerror(parser, "expected label or expression in ternary");
3205 if (on_true) ast_unref(on_true);
3206 if (on_false) ast_unref(on_false);
3214 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3215 } else if (ast_istype(*side, ast_label)) {
3216 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3217 ast_goto_set_label(gt, ((ast_label*)*side));
3219 return (ast_expression*)gt;
3224 static bool parse_goto(parser_t *parser, ast_expression **out)
3226 ast_goto *gt = NULL;
3227 ast_expression *lbl;
3229 if (!parser_next(parser))
3232 if (parser->tok != TOKEN_IDENT) {
3233 ast_expression *expression;
3235 /* could be an expression i.e computed goto :-) */
3236 if (parser->tok != '(') {
3237 parseerror(parser, "expected label name after `goto`");
3241 /* failed to parse expression for goto */
3242 if (!(expression = parse_expression(parser, false, true)) ||
3243 !(*out = parse_goto_computed(parser, &expression))) {
3244 parseerror(parser, "invalid goto expression");
3245 ast_unref(expression);
3252 /* not computed goto */
3253 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3254 lbl = parser_find_label(parser, gt->name);
3256 if (!ast_istype(lbl, ast_label)) {
3257 parseerror(parser, "internal error: label is not an ast_label");
3261 ast_goto_set_label(gt, (ast_label*)lbl);
3264 vec_push(parser->gotos, gt);
3266 if (!parser_next(parser) || parser->tok != ';') {
3267 parseerror(parser, "semicolon expected after goto label");
3270 if (!parser_next(parser)) {
3271 parseerror(parser, "parse error after goto");
3275 *out = (ast_expression*)gt;
3279 static bool parse_skipwhite(parser_t *parser)
3282 if (!parser_next(parser))
3284 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3285 return parser->tok < TOKEN_ERROR;
3288 static bool parse_eol(parser_t *parser)
3290 if (!parse_skipwhite(parser))
3292 return parser->tok == TOKEN_EOL;
3295 static bool parse_pragma_do(parser_t *parser)
3297 if (!parser_next(parser) ||
3298 parser->tok != TOKEN_IDENT ||
3299 strcmp(parser_tokval(parser), "pragma"))
3301 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3304 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3305 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3309 if (!strcmp(parser_tokval(parser), "noref")) {
3310 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3311 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3314 parser->noref = !!parser_token(parser)->constval.i;
3315 if (!parse_eol(parser)) {
3316 parseerror(parser, "parse error after `noref` pragma");
3322 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3329 static bool parse_pragma(parser_t *parser)
3332 parser->lex->flags.preprocessing = true;
3333 parser->lex->flags.mergelines = true;
3334 rv = parse_pragma_do(parser);
3335 if (parser->tok != TOKEN_EOL) {
3336 parseerror(parser, "junk after pragma");
3339 parser->lex->flags.preprocessing = false;
3340 parser->lex->flags.mergelines = false;
3341 if (!parser_next(parser)) {
3342 parseerror(parser, "parse error after pragma");
3348 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3350 bool noref, is_static;
3352 uint32_t qflags = 0;
3353 ast_value *typevar = NULL;
3354 char *vstring = NULL;
3358 if (parser->tok == TOKEN_IDENT)
3359 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3361 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3363 /* local variable */
3365 parseerror(parser, "cannot declare a variable from here");
3368 if (opts.standard == COMPILER_QCC) {
3369 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3372 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3376 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3378 if (cvq == CV_WRONG)
3380 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3382 else if (parser->tok == TOKEN_KEYWORD)
3384 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3389 if (!parser_next(parser)) {
3390 parseerror(parser, "parse error after __builtin_debug_printtype");
3394 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3396 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3397 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3398 if (!parser_next(parser)) {
3399 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3405 if (!parse_statement(parser, block, out, allow_cases))
3408 con_out("__builtin_debug_printtype: got no output node\n");
3411 ast_type_to_string(*out, ty, sizeof(ty));
3412 con_out("__builtin_debug_printtype: `%s`\n", ty);
3417 else if (!strcmp(parser_tokval(parser), "return"))
3419 return parse_return(parser, block, out);
3421 else if (!strcmp(parser_tokval(parser), "if"))
3423 return parse_if(parser, block, out);
3425 else if (!strcmp(parser_tokval(parser), "while"))
3427 return parse_while(parser, block, out);
3429 else if (!strcmp(parser_tokval(parser), "do"))
3431 return parse_dowhile(parser, block, out);
3433 else if (!strcmp(parser_tokval(parser), "for"))
3435 if (opts.standard == COMPILER_QCC) {
3436 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3439 return parse_for(parser, block, out);
3441 else if (!strcmp(parser_tokval(parser), "break"))
3443 return parse_break_continue(parser, block, out, false);
3445 else if (!strcmp(parser_tokval(parser), "continue"))
3447 return parse_break_continue(parser, block, out, true);
3449 else if (!strcmp(parser_tokval(parser), "switch"))
3451 return parse_switch(parser, block, out);
3453 else if (!strcmp(parser_tokval(parser), "case") ||
3454 !strcmp(parser_tokval(parser), "default"))
3457 parseerror(parser, "unexpected 'case' label");
3462 else if (!strcmp(parser_tokval(parser), "goto"))
3464 return parse_goto(parser, out);
3466 else if (!strcmp(parser_tokval(parser), "typedef"))
3468 if (!parser_next(parser)) {
3469 parseerror(parser, "expected type definition after 'typedef'");
3472 return parse_typedef(parser);
3474 parseerror(parser, "Unexpected keyword");
3477 else if (parser->tok == '{')
3480 inner = parse_block(parser);
3483 *out = (ast_expression*)inner;
3486 else if (parser->tok == ':')
3490 if (!parser_next(parser)) {
3491 parseerror(parser, "expected label name");
3494 if (parser->tok != TOKEN_IDENT) {
3495 parseerror(parser, "label must be an identifier");
3498 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3500 if (!label->undefined) {
3501 parseerror(parser, "label `%s` already defined", label->name);
3504 label->undefined = false;
3507 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3508 vec_push(parser->labels, label);
3510 *out = (ast_expression*)label;
3511 if (!parser_next(parser)) {
3512 parseerror(parser, "parse error after label");
3515 for (i = 0; i < vec_size(parser->gotos); ++i) {
3516 if (!strcmp(parser->gotos[i]->name, label->name)) {
3517 ast_goto_set_label(parser->gotos[i], label);
3518 vec_remove(parser->gotos, i, 1);
3524 else if (parser->tok == ';')
3526 if (!parser_next(parser)) {
3527 parseerror(parser, "parse error after empty statement");
3534 lex_ctx ctx = parser_ctx(parser);
3535 ast_expression *exp = parse_expression(parser, false, false);
3539 if (!ast_side_effects(exp)) {
3540 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3547 static bool parse_enum(parser_t *parser)
3550 ast_value **values = NULL;
3551 ast_value *var = NULL;
3554 ast_expression *old;
3556 if (!parser_next(parser) || parser->tok != '{') {
3557 parseerror(parser, "expected `{` after `enum` keyword");
3562 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3563 if (parser->tok == '}') {
3564 /* allow an empty enum */
3567 parseerror(parser, "expected identifier or `}`");
3571 old = parser_find_field(parser, parser_tokval(parser));
3573 old = parser_find_global(parser, parser_tokval(parser));
3575 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3576 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3580 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3581 vec_push(values, var);
3582 var->cvq = CV_CONST;
3583 var->hasvalue = true;
3584 var->constval.vfloat = num++;
3586 parser_addglobal(parser, var->name, (ast_expression*)var);
3588 if (!parser_next(parser)) {
3589 parseerror(parser, "expected `=`, `}` or comma after identifier");
3593 if (parser->tok == ',')
3595 if (parser->tok == '}')
3597 if (parser->tok != '=') {
3598 parseerror(parser, "expected `=`, `}` or comma after identifier");
3602 if (!parser_next(parser)) {
3603 parseerror(parser, "expected expression after `=`");
3607 /* We got a value! */
3608 old = parse_expression_leave(parser, true, false, false);
3609 asvalue = (ast_value*)old;
3610 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3611 compile_error(ast_ctx(var), "constant value or expression expected");
3614 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3616 if (parser->tok == '}')
3618 if (parser->tok != ',') {
3619 parseerror(parser, "expected `}` or comma after expression");
3624 if (parser->tok != '}') {
3625 parseerror(parser, "internal error: breaking without `}`");
3629 if (!parser_next(parser) || parser->tok != ';') {
3630 parseerror(parser, "expected semicolon after enumeration");
3634 if (!parser_next(parser)) {
3635 parseerror(parser, "parse error after enumeration");
3647 static bool parse_block_into(parser_t *parser, ast_block *block)
3651 parser_enterblock(parser);
3653 if (!parser_next(parser)) { /* skip the '{' */
3654 parseerror(parser, "expected function body");
3658 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3660 ast_expression *expr = NULL;
3661 if (parser->tok == '}')
3664 if (!parse_statement(parser, block, &expr, false)) {
3665 /* parseerror(parser, "parse error"); */
3671 if (!ast_block_add_expr(block, expr)) {
3678 if (parser->tok != '}') {
3681 (void)parser_next(parser);
3685 if (!parser_leaveblock(parser))
3687 return retval && !!block;
3690 static ast_block* parse_block(parser_t *parser)
3693 block = ast_block_new(parser_ctx(parser));
3696 if (!parse_block_into(parser, block)) {
3697 ast_block_delete(block);
3703 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3705 if (parser->tok == '{') {
3706 *out = (ast_expression*)parse_block(parser);
3709 return parse_statement(parser, NULL, out, false);
3712 static bool create_vector_members(ast_value *var, ast_member **me)
3715 size_t len = strlen(var->name);
3717 for (i = 0; i < 3; ++i) {
3718 char *name = (char*)mem_a(len+3);
3719 memcpy(name, var->name, len);
3721 name[len+1] = 'x'+i;
3723 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3732 do { ast_member_delete(me[--i]); } while(i);
3736 static bool parse_function_body(parser_t *parser, ast_value *var)
3738 ast_block *block = NULL;
3743 ast_expression *framenum = NULL;
3744 ast_expression *nextthink = NULL;
3745 /* None of the following have to be deleted */
3746 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3747 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3748 bool has_frame_think;
3752 has_frame_think = false;
3753 old = parser->function;
3755 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3756 parseerror(parser, "gotos/labels leaking");
3760 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3761 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3762 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3768 if (parser->tok == '[') {
3769 /* got a frame definition: [ framenum, nextthink ]
3770 * this translates to:
3771 * self.frame = framenum;
3772 * self.nextthink = time + 0.1;
3773 * self.think = nextthink;
3777 fld_think = parser_find_field(parser, "think");
3778 fld_nextthink = parser_find_field(parser, "nextthink");
3779 fld_frame = parser_find_field(parser, "frame");
3780 if (!fld_think || !fld_nextthink || !fld_frame) {
3781 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3782 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3785 gbl_time = parser_find_global(parser, "time");
3786 gbl_self = parser_find_global(parser, "self");
3787 if (!gbl_time || !gbl_self) {
3788 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3789 parseerror(parser, "please declare the following globals: `time`, `self`");
3793 if (!parser_next(parser))
3796 framenum = parse_expression_leave(parser, true, false, false);
3798 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3801 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3802 ast_unref(framenum);
3803 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3807 if (parser->tok != ',') {
3808 ast_unref(framenum);
3809 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3810 parseerror(parser, "Got a %i\n", parser->tok);
3814 if (!parser_next(parser)) {
3815 ast_unref(framenum);
3819 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3821 /* qc allows the use of not-yet-declared functions here
3822 * - this automatically creates a prototype */
3823 ast_value *thinkfunc;
3824 ast_expression *functype = fld_think->expression.next;
3826 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3827 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3828 ast_unref(framenum);
3829 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3833 if (!parser_next(parser)) {
3834 ast_unref(framenum);
3835 ast_delete(thinkfunc);
3839 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3841 nextthink = (ast_expression*)thinkfunc;
3844 nextthink = parse_expression_leave(parser, true, false, false);
3846 ast_unref(framenum);
3847 parseerror(parser, "expected a think-function in [frame,think] notation");
3852 if (!ast_istype(nextthink, ast_value)) {
3853 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3857 if (retval && parser->tok != ']') {
3858 parseerror(parser, "expected closing `]` for [frame,think] notation");
3862 if (retval && !parser_next(parser)) {
3866 if (retval && parser->tok != '{') {
3867 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3872 ast_unref(nextthink);
3873 ast_unref(framenum);
3877 has_frame_think = true;
3880 block = ast_block_new(parser_ctx(parser));
3882 parseerror(parser, "failed to allocate block");
3883 if (has_frame_think) {
3884 ast_unref(nextthink);
3885 ast_unref(framenum);
3890 if (has_frame_think) {
3892 ast_expression *self_frame;
3893 ast_expression *self_nextthink;
3894 ast_expression *self_think;
3895 ast_expression *time_plus_1;
3896 ast_store *store_frame;
3897 ast_store *store_nextthink;
3898 ast_store *store_think;
3900 ctx = parser_ctx(parser);
3901 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3902 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3903 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3905 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3906 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3908 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3909 if (self_frame) ast_delete(self_frame);
3910 if (self_nextthink) ast_delete(self_nextthink);
3911 if (self_think) ast_delete(self_think);
3912 if (time_plus_1) ast_delete(time_plus_1);
3918 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3919 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3920 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3923 ast_delete(self_frame);
3926 if (!store_nextthink) {
3927 ast_delete(self_nextthink);
3931 ast_delete(self_think);
3935 if (store_frame) ast_delete(store_frame);
3936 if (store_nextthink) ast_delete(store_nextthink);
3937 if (store_think) ast_delete(store_think);
3940 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3941 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3942 !ast_block_add_expr(block, (ast_expression*)store_think))
3949 parseerror(parser, "failed to generate code for [frame,think]");
3950 ast_unref(nextthink);
3951 ast_unref(framenum);
3957 func = ast_function_new(ast_ctx(var), var->name, var);
3959 parseerror(parser, "failed to allocate function for `%s`", var->name);
3960 ast_block_delete(block);
3963 vec_push(parser->functions, func);
3965 parser_enterblock(parser);
3967 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3969 ast_value *param = var->expression.params[parami];
3972 if (param->expression.vtype != TYPE_VECTOR &&
3973 (param->expression.vtype != TYPE_FIELD ||
3974 param->expression.next->expression.vtype != TYPE_VECTOR))
3979 if (!create_vector_members(param, me)) {
3980 ast_block_delete(block);
3984 for (e = 0; e < 3; ++e) {
3985 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3986 ast_block_collect(block, (ast_expression*)me[e]);
3990 if (var->argcounter) {
3991 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3992 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3996 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3998 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3999 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4000 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4001 varargs->expression.count = 0;
4002 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4003 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4004 ast_delete(varargs);
4005 ast_block_delete(block);
4008 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4009 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4010 ast_delete(varargs);
4011 ast_block_delete(block);
4014 func->varargs = varargs;
4016 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4019 parser->function = func;
4020 if (!parse_block_into(parser, block)) {
4021 ast_block_delete(block);
4025 vec_push(func->blocks, block);
4027 parser->function = old;
4028 if (!parser_leaveblock(parser))
4030 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4031 parseerror(parser, "internal error: local scopes left");
4035 if (parser->tok == ';')
4036 return parser_next(parser);
4037 else if (opts.standard == COMPILER_QCC)
4038 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4042 (void)!parser_leaveblock(parser);
4043 vec_pop(parser->functions);
4044 ast_function_delete(func);
4045 var->constval.vfunc = NULL;
4048 parser->function = old;
4052 static ast_expression *array_accessor_split(
4057 ast_expression *left,
4058 ast_expression *right
4064 lex_ctx ctx = ast_ctx(array);
4066 if (!left || !right) {
4067 if (left) ast_delete(left);
4068 if (right) ast_delete(right);
4072 cmp = ast_binary_new(ctx, INSTR_LT,
4073 (ast_expression*)index,
4074 (ast_expression*)parser_const_float(parser, middle));
4078 parseerror(parser, "internal error: failed to create comparison for array setter");
4082 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4084 ast_delete(cmp); /* will delete left and right */
4085 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4089 return (ast_expression*)ifthen;
4092 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4094 lex_ctx ctx = ast_ctx(array);
4096 if (from+1 == afterend) {
4097 /* set this value */
4100 ast_array_index *subscript;
4102 int assignop = type_store_instr[value->expression.vtype];
4104 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4105 assignop = INSTR_STORE_V;
4107 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4111 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4113 ast_delete(subscript);
4117 block = ast_block_new(ctx);
4123 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4128 ret = ast_return_new(ctx, NULL);
4134 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4139 return (ast_expression*)block;
4141 ast_expression *left, *right;
4142 size_t diff = afterend - from;
4143 size_t middle = from + diff/2;
4144 left = array_setter_node(parser, array, index, value, from, middle);
4145 right = array_setter_node(parser, array, index, value, middle, afterend);
4146 return array_accessor_split(parser, array, index, middle, left, right);
4150 static ast_expression *array_field_setter_node(
4159 lex_ctx ctx = ast_ctx(array);
4161 if (from+1 == afterend) {
4162 /* set this value */
4165 ast_entfield *entfield;
4166 ast_array_index *subscript;
4168 int assignop = type_storep_instr[value->expression.vtype];
4170 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4171 assignop = INSTR_STOREP_V;
4173 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4177 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4178 subscript->expression.vtype = TYPE_FIELD;
4180 entfield = ast_entfield_new_force(ctx,
4181 (ast_expression*)entity,
4182 (ast_expression*)subscript,
4183 (ast_expression*)subscript);
4185 ast_delete(subscript);
4189 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4191 ast_delete(entfield);
4195 block = ast_block_new(ctx);
4201 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4206 ret = ast_return_new(ctx, NULL);
4212 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4217 return (ast_expression*)block;
4219 ast_expression *left, *right;
4220 size_t diff = afterend - from;
4221 size_t middle = from + diff/2;
4222 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4223 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4224 return array_accessor_split(parser, array, index, middle, left, right);
4228 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4230 lex_ctx ctx = ast_ctx(array);
4232 if (from+1 == afterend) {
4234 ast_array_index *subscript;
4236 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4240 ret = ast_return_new(ctx, (ast_expression*)subscript);
4242 ast_delete(subscript);
4246 return (ast_expression*)ret;
4248 ast_expression *left, *right;
4249 size_t diff = afterend - from;
4250 size_t middle = from + diff/2;
4251 left = array_getter_node(parser, array, index, from, middle);
4252 right = array_getter_node(parser, array, index, middle, afterend);
4253 return array_accessor_split(parser, array, index, middle, left, right);
4257 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4259 ast_function *func = NULL;
4260 ast_value *fval = NULL;
4261 ast_block *body = NULL;
4263 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4265 parseerror(parser, "failed to create accessor function value");
4269 func = ast_function_new(ast_ctx(array), funcname, fval);
4272 parseerror(parser, "failed to create accessor function node");
4276 body = ast_block_new(ast_ctx(array));
4278 parseerror(parser, "failed to create block for array accessor");
4284 vec_push(func->blocks, body);
4287 vec_push(parser->accessors, fval);
4292 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4294 ast_value *index = NULL;
4295 ast_value *value = NULL;
4299 if (!ast_istype(array->expression.next, ast_value)) {
4300 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4304 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4306 func = fval->constval.vfunc;
4307 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4309 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4310 value = ast_value_copy((ast_value*)array->expression.next);
4312 if (!index || !value) {
4313 parseerror(parser, "failed to create locals for array accessor");
4316 (void)!ast_value_set_name(value, "value"); /* not important */
4317 vec_push(fval->expression.params, index);
4318 vec_push(fval->expression.params, value);
4320 array->setter = fval;
4323 if (index) ast_delete(index);
4324 if (value) ast_delete(value);
4330 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4332 ast_expression *root = NULL;
4333 root = array_setter_node(parser, array,
4334 array->setter->expression.params[0],
4335 array->setter->expression.params[1],
4336 0, array->expression.count);
4338 parseerror(parser, "failed to build accessor search tree");
4341 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4348 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4350 if (!parser_create_array_setter_proto(parser, array, funcname))
4352 return parser_create_array_setter_impl(parser, array);
4355 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4357 ast_expression *root = NULL;
4358 ast_value *entity = NULL;
4359 ast_value *index = NULL;
4360 ast_value *value = NULL;
4364 if (!ast_istype(array->expression.next, ast_value)) {
4365 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4369 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4371 func = fval->constval.vfunc;
4372 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4374 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4375 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4376 value = ast_value_copy((ast_value*)array->expression.next);
4377 if (!entity || !index || !value) {
4378 parseerror(parser, "failed to create locals for array accessor");
4381 (void)!ast_value_set_name(value, "value"); /* not important */
4382 vec_push(fval->expression.params, entity);
4383 vec_push(fval->expression.params, index);
4384 vec_push(fval->expression.params, value);
4386 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4388 parseerror(parser, "failed to build accessor search tree");
4392 array->setter = fval;
4393 return ast_block_add_expr(func->blocks[0], root);
4395 if (entity) ast_delete(entity);
4396 if (index) ast_delete(index);
4397 if (value) ast_delete(value);
4398 if (root) ast_delete(root);
4404 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4406 ast_value *index = NULL;
4410 /* NOTE: checking array->expression.next rather than elemtype since
4411 * for fields elemtype is a temporary fieldtype.
4413 if (!ast_istype(array->expression.next, ast_value)) {
4414 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4418 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4420 func = fval->constval.vfunc;
4421 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4423 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4426 parseerror(parser, "failed to create locals for array accessor");
4429 vec_push(fval->expression.params, index);
4431 array->getter = fval;
4434 if (index) ast_delete(index);
4440 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4442 ast_expression *root = NULL;
4444 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4446 parseerror(parser, "failed to build accessor search tree");
4449 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4456 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4458 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4460 return parser_create_array_getter_impl(parser, array);
4463 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4464 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4472 bool variadic = false;
4473 ast_value *varparam = NULL;
4474 char *argcounter = NULL;
4476 ctx = parser_ctx(parser);
4478 /* for the sake of less code we parse-in in this function */
4479 if (!parser_next(parser)) {
4480 parseerror(parser, "expected parameter list");
4486 /* parse variables until we hit a closing paren */
4487 while (parser->tok != ')') {
4489 /* there must be commas between them */
4490 if (parser->tok != ',') {
4491 parseerror(parser, "expected comma or end of parameter list");
4494 if (!parser_next(parser)) {
4495 parseerror(parser, "expected parameter");
4501 if (parser->tok == TOKEN_DOTS) {
4502 /* '...' indicates a varargs function */
4504 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4505 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4508 if (parser->tok == TOKEN_IDENT) {
4509 argcounter = util_strdup(parser_tokval(parser));
4510 if (!parser_next(parser) || parser->tok != ')') {
4511 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4518 /* for anything else just parse a typename */
4519 param = parse_typename(parser, NULL, NULL);
4522 vec_push(params, param);
4523 if (param->expression.vtype >= TYPE_VARIANT) {
4524 char tname[1024]; /* typename is reserved in C++ */
4525 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4526 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4529 /* type-restricted varargs */
4530 if (parser->tok == TOKEN_DOTS) {
4532 varparam = vec_last(params);
4534 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4535 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4538 if (parser->tok == TOKEN_IDENT) {
4539 argcounter = util_strdup(parser_tokval(parser));
4540 if (!parser_next(parser) || parser->tok != ')') {
4541 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4549 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4553 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4554 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4557 if (!parser_next(parser)) {
4558 parseerror(parser, "parse error after typename");
4562 /* now turn 'var' into a function type */
4563 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4564 fval->expression.next = (ast_expression*)var;
4566 fval->expression.flags |= AST_FLAG_VARIADIC;
4569 var->expression.params = params;
4570 var->expression.varparam = (ast_expression*)varparam;
4571 var->argcounter = argcounter;
4580 for (i = 0; i < vec_size(params); ++i)
4581 ast_delete(params[i]);
4586 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4588 ast_expression *cexp;
4589 ast_value *cval, *tmp;
4592 ctx = parser_ctx(parser);
4594 if (!parser_next(parser)) {
4596 parseerror(parser, "expected array-size");
4600 cexp = parse_expression_leave(parser, true, false, false);
4602 if (!cexp || !ast_istype(cexp, ast_value)) {
4606 parseerror(parser, "expected array-size as constant positive integer");
4609 cval = (ast_value*)cexp;
4611 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4612 tmp->expression.next = (ast_expression*)var;
4615 if (cval->expression.vtype == TYPE_INTEGER)
4616 tmp->expression.count = cval->constval.vint;
4617 else if (cval->expression.vtype == TYPE_FLOAT)
4618 tmp->expression.count = cval->constval.vfloat;
4622 parseerror(parser, "array-size must be a positive integer constant");
4627 if (parser->tok != ']') {
4629 parseerror(parser, "expected ']' after array-size");
4632 if (!parser_next(parser)) {
4634 parseerror(parser, "error after parsing array size");
4640 /* Parse a complete typename.
4641 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4642 * but when parsing variables separated by comma
4643 * 'storebase' should point to where the base-type should be kept.
4644 * The base type makes up every bit of type information which comes *before* the
4647 * The following will be parsed in its entirety:
4649 * The 'basetype' in this case is 'void()'
4650 * and if there's a comma after it, say:
4652 * then the type-information 'void()' can be stored in 'storebase'
4654 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4656 ast_value *var, *tmp;
4659 const char *name = NULL;
4660 bool isfield = false;
4661 bool wasarray = false;
4662 size_t morefields = 0;
4664 ctx = parser_ctx(parser);
4666 /* types may start with a dot */
4667 if (parser->tok == '.') {
4669 /* if we parsed a dot we need a typename now */
4670 if (!parser_next(parser)) {
4671 parseerror(parser, "expected typename for field definition");
4675 /* Further dots are handled seperately because they won't be part of the
4678 while (parser->tok == '.') {
4680 if (!parser_next(parser)) {
4681 parseerror(parser, "expected typename for field definition");
4686 if (parser->tok == TOKEN_IDENT)
4687 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4688 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4689 parseerror(parser, "expected typename");
4693 /* generate the basic type value */
4694 if (cached_typedef) {
4695 var = ast_value_copy(cached_typedef);
4696 ast_value_set_name(var, "<type(from_def)>");
4698 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4700 for (; morefields; --morefields) {
4701 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4702 tmp->expression.next = (ast_expression*)var;
4706 /* do not yet turn into a field - remember:
4707 * .void() foo; is a field too
4708 * .void()() foo; is a function
4712 if (!parser_next(parser)) {
4714 parseerror(parser, "parse error after typename");
4718 /* an opening paren now starts the parameter-list of a function
4719 * this is where original-QC has parameter lists.
4720 * We allow a single parameter list here.
4721 * Much like fteqcc we don't allow `float()() x`
4723 if (parser->tok == '(') {
4724 var = parse_parameter_list(parser, var);
4729 /* store the base if requested */
4731 *storebase = ast_value_copy(var);
4733 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4734 tmp->expression.next = (ast_expression*)*storebase;
4739 /* there may be a name now */
4740 if (parser->tok == TOKEN_IDENT) {
4741 name = util_strdup(parser_tokval(parser));
4743 if (!parser_next(parser)) {
4745 parseerror(parser, "error after variable or field declaration");
4750 /* now this may be an array */
4751 if (parser->tok == '[') {
4753 var = parse_arraysize(parser, var);
4758 /* This is the point where we can turn it into a field */
4760 /* turn it into a field if desired */
4761 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4762 tmp->expression.next = (ast_expression*)var;
4766 /* now there may be function parens again */
4767 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4768 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4769 if (parser->tok == '(' && wasarray)
4770 parseerror(parser, "arrays as part of a return type is not supported");
4771 while (parser->tok == '(') {
4772 var = parse_parameter_list(parser, var);
4780 /* finally name it */
4782 if (!ast_value_set_name(var, name)) {
4784 parseerror(parser, "internal error: failed to set name");
4787 /* free the name, ast_value_set_name duplicates */
4794 static bool parse_typedef(parser_t *parser)
4796 ast_value *typevar, *oldtype;
4797 ast_expression *old;
4799 typevar = parse_typename(parser, NULL, NULL);
4804 if ( (old = parser_find_var(parser, typevar->name)) ) {
4805 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4806 " -> `%s` has been declared here: %s:%i",
4807 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4808 ast_delete(typevar);
4812 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4813 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4814 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4815 ast_delete(typevar);
4819 vec_push(parser->_typedefs, typevar);
4820 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4822 if (parser->tok != ';') {
4823 parseerror(parser, "expected semicolon after typedef");
4826 if (!parser_next(parser)) {
4827 parseerror(parser, "parse error after typedef");
4834 static const char *cvq_to_str(int cvq) {
4836 case CV_NONE: return "none";
4837 case CV_VAR: return "`var`";
4838 case CV_CONST: return "`const`";
4839 default: return "<INVALID>";
4843 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4846 if (proto->cvq != var->cvq) {
4847 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4848 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4849 parser->tok == '='))
4851 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4852 "`%s` declared with different qualifiers: %s\n"
4853 " -> previous declaration here: %s:%i uses %s",
4854 var->name, cvq_to_str(var->cvq),
4855 ast_ctx(proto).file, ast_ctx(proto).line,
4856 cvq_to_str(proto->cvq));
4859 av = (var ->expression.flags & AST_FLAG_NORETURN);
4860 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4862 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4863 "`%s` declared with different attributes%s\n"
4864 " -> previous declaration here: %s:%i",
4865 var->name, (av ? ": noreturn" : ""),
4866 ast_ctx(proto).file, ast_ctx(proto).line,
4867 (ao ? ": noreturn" : ""));
4872 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)
4876 ast_expression *old;
4880 ast_value *basetype = NULL;
4882 bool isparam = false;
4883 bool isvector = false;
4884 bool cleanvar = true;
4885 bool wasarray = false;
4889 if (!localblock && is_static)
4890 parseerror(parser, "`static` qualifier is not supported in global scope");
4892 /* get the first complete variable */
4893 var = parse_typename(parser, &basetype, cached_typedef);
4896 ast_delete(basetype);
4904 /* Part 0: finish the type */
4905 if (parser->tok == '(') {
4906 if (opts.standard == COMPILER_QCC)
4907 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4908 var = parse_parameter_list(parser, var);
4914 /* we only allow 1-dimensional arrays */
4915 if (parser->tok == '[') {
4917 var = parse_arraysize(parser, var);
4923 if (parser->tok == '(' && wasarray) {
4924 parseerror(parser, "arrays as part of a return type is not supported");
4925 /* we'll still parse the type completely for now */
4927 /* for functions returning functions */
4928 while (parser->tok == '(') {
4929 if (opts.standard == COMPILER_QCC)
4930 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4931 var = parse_parameter_list(parser, var);
4938 var->cvq = qualifier;
4939 var->expression.flags |= qflags;
4940 if (var->expression.flags & AST_FLAG_DEPRECATED)
4941 var->desc = vstring;
4944 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4945 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4946 * is then filled with the previous definition and the parameter-names replaced.
4948 if (!strcmp(var->name, "nil")) {
4949 if (OPTS_FLAG(UNTYPED_NIL)) {
4950 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4951 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4953 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4956 /* Deal with end_sys_ vars */
4958 if (!strcmp(var->name, "end_sys_globals")) {
4960 parser->crc_globals = vec_size(parser->globals);
4963 else if (!strcmp(var->name, "end_sys_fields")) {
4965 parser->crc_fields = vec_size(parser->fields);
4968 if (was_end && var->expression.vtype == TYPE_FIELD) {
4969 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4970 "global '%s' hint should not be a field",
4971 parser_tokval(parser)))
4978 if (!nofields && var->expression.vtype == TYPE_FIELD)
4980 /* deal with field declarations */
4981 old = parser_find_field(parser, var->name);
4983 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4984 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4993 parseerror(parser, "field `%s` already declared here: %s:%i",
4994 var->name, ast_ctx(old).file, ast_ctx(old).line);
4999 if ((opts.standard == COMPILER_QCC || opts.standard == COMPILER_FTEQCC) &&
5000 (old = parser_find_global(parser, var->name)))
5002 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5003 parseerror(parser, "field `%s` already declared here: %s:%i",
5004 var->name, ast_ctx(old).file, ast_ctx(old).line);
5011 /* deal with other globals */
5012 old = parser_find_global(parser, var->name);
5013 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5015 /* This is a function which had a prototype */
5016 if (!ast_istype(old, ast_value)) {
5017 parseerror(parser, "internal error: prototype is not an ast_value");
5021 proto = (ast_value*)old;
5022 proto->desc = var->desc;
5023 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5024 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5026 ast_ctx(proto).file, ast_ctx(proto).line);
5030 /* we need the new parameter-names */
5031 for (i = 0; i < vec_size(proto->expression.params); ++i)
5032 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5033 if (!parser_check_qualifiers(parser, var, proto)) {
5040 proto->expression.flags |= var->expression.flags;
5048 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5049 "global `%s` already declared here: %s:%i",
5050 var->name, ast_ctx(old).file, ast_ctx(old).line))
5055 proto = (ast_value*)old;
5056 if (!ast_istype(old, ast_value)) {
5057 parseerror(parser, "internal error: not an ast_value");
5062 if (!parser_check_qualifiers(parser, var, proto)) {
5067 proto->expression.flags |= var->expression.flags;
5071 if (opts.standard == COMPILER_QCC &&
5072 (old = parser_find_field(parser, var->name)))
5074 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5075 parseerror(parser, "global `%s` already declared here: %s:%i",
5076 var->name, ast_ctx(old).file, ast_ctx(old).line);
5083 else /* it's not a global */
5085 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5086 if (old && !isparam) {
5087 parseerror(parser, "local `%s` already declared here: %s:%i",
5088 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5092 old = parser_find_local(parser, var->name, 0, &isparam);
5093 if (old && isparam) {
5094 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5095 "local `%s` is shadowing a parameter", var->name))
5097 parseerror(parser, "local `%s` already declared here: %s:%i",
5098 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5102 if (opts.standard != COMPILER_GMQCC) {
5110 /* in a noref section we simply bump the usecount */
5111 if (noref || parser->noref)
5115 * Create the global/local, and deal with vector types.
5118 if (var->expression.vtype == TYPE_VECTOR)
5120 else if (var->expression.vtype == TYPE_FIELD &&
5121 var->expression.next->expression.vtype == TYPE_VECTOR)
5125 if (!create_vector_members(var, me)) {
5132 /* deal with global variables, fields, functions */
5133 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5134 var->isfield = true;
5135 vec_push(parser->fields, (ast_expression*)var);
5136 util_htset(parser->htfields, var->name, var);
5138 for (i = 0; i < 3; ++i) {
5139 vec_push(parser->fields, (ast_expression*)me[i]);
5140 util_htset(parser->htfields, me[i]->name, me[i]);
5145 parser_addglobal(parser, var->name, (ast_expression*)var);
5147 for (i = 0; i < 3; ++i) {
5148 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5154 /* a static adds itself to be generated like any other global
5155 * but is added to the local namespace instead
5157 char *defname = NULL;
5158 size_t prefix_len, ln;
5160 ln = strlen(parser->function->name);
5161 vec_append(defname, ln, parser->function->name);
5163 vec_append(defname, 2, "::");
5164 /* remember the length up to here */
5165 prefix_len = vec_size(defname);
5167 /* Add it to the local scope */
5168 util_htset(vec_last(parser->variables), var->name, (void*)var);
5172 vec_last(parser->correct_variables),
5173 &vec_last(parser->correct_variables_score),
5177 /* now rename the global */
5178 ln = strlen(var->name);
5179 vec_append(defname, ln, var->name);
5180 ast_value_set_name(var, defname);
5182 /* push it to the to-be-generated globals */
5183 vec_push(parser->globals, (ast_expression*)var);
5185 /* same game for the vector members */
5187 for (i = 0; i < 3; ++i) {
5188 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5192 vec_last(parser->correct_variables),
5193 &vec_last(parser->correct_variables_score),
5197 vec_shrinkto(defname, prefix_len);
5198 ln = strlen(me[i]->name);
5199 vec_append(defname, ln, me[i]->name);
5200 ast_member_set_name(me[i], defname);
5202 vec_push(parser->globals, (ast_expression*)me[i]);
5207 vec_push(localblock->locals, var);
5208 parser_addlocal(parser, var->name, (ast_expression*)var);
5210 for (i = 0; i < 3; ++i) {
5211 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5212 ast_block_collect(localblock, (ast_expression*)me[i]);
5218 me[0] = me[1] = me[2] = NULL;
5223 if (var->expression.vtype == TYPE_ARRAY) {
5225 snprintf(name, sizeof(name), "%s##SET", var->name);
5226 if (!parser_create_array_setter(parser, var, name))
5228 snprintf(name, sizeof(name), "%s##GET", var->name);
5229 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5232 else if (!localblock && !nofields &&
5233 var->expression.vtype == TYPE_FIELD &&
5234 var->expression.next->expression.vtype == TYPE_ARRAY)
5237 ast_expression *telem;
5239 ast_value *array = (ast_value*)var->expression.next;
5241 if (!ast_istype(var->expression.next, ast_value)) {
5242 parseerror(parser, "internal error: field element type must be an ast_value");
5246 snprintf(name, sizeof(name), "%s##SETF", var->name);
5247 if (!parser_create_array_field_setter(parser, array, name))
5250 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5251 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5252 tfield->expression.next = telem;
5253 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5254 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5262 if (parser->tok == ';') {
5263 ast_delete(basetype);
5264 if (!parser_next(parser)) {
5265 parseerror(parser, "error after variable declaration");
5271 if (parser->tok == ',')
5275 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5278 parseerror(parser, "missing comma or semicolon while parsing variables");
5282 if (localblock && opts.standard == COMPILER_QCC) {
5283 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5284 "initializing expression turns variable `%s` into a constant in this standard",
5291 if (parser->tok != '{') {
5292 if (parser->tok != '=') {
5293 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5297 if (!parser_next(parser)) {
5298 parseerror(parser, "error parsing initializer");
5302 else if (opts.standard == COMPILER_QCC) {
5303 parseerror(parser, "expected '=' before function body in this standard");
5306 if (parser->tok == '#') {
5307 ast_function *func = NULL;
5310 parseerror(parser, "cannot declare builtins within functions");
5313 if (var->expression.vtype != TYPE_FUNCTION) {
5314 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5317 if (!parser_next(parser)) {
5318 parseerror(parser, "expected builtin number");
5321 if (parser->tok != TOKEN_INTCONST) {
5322 parseerror(parser, "builtin number must be an integer constant");
5325 if (parser_token(parser)->constval.i < 0) {
5326 parseerror(parser, "builtin number must be an integer greater than zero");
5330 if (var->hasvalue) {
5331 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5332 "builtin `%s` has already been defined\n"
5333 " -> previous declaration here: %s:%i",
5334 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5338 func = ast_function_new(ast_ctx(var), var->name, var);
5340 parseerror(parser, "failed to allocate function for `%s`", var->name);
5343 vec_push(parser->functions, func);
5345 func->builtin = -parser_token(parser)->constval.i-1;
5348 if (!parser_next(parser)) {
5349 parseerror(parser, "expected comma or semicolon");
5351 ast_function_delete(func);
5352 var->constval.vfunc = NULL;
5356 else if (parser->tok == '{' || parser->tok == '[')
5359 parseerror(parser, "cannot declare functions within functions");
5364 ast_ctx(proto) = parser_ctx(parser);
5366 if (!parse_function_body(parser, var))
5368 ast_delete(basetype);
5369 for (i = 0; i < vec_size(parser->gotos); ++i)
5370 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5371 vec_free(parser->gotos);
5372 vec_free(parser->labels);
5375 ast_expression *cexp;
5378 cexp = parse_expression_leave(parser, true, false, false);
5383 cval = (ast_value*)cexp;
5384 if (cval != parser->nil &&
5385 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5388 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5392 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5393 qualifier != CV_VAR)
5395 var->cvq = CV_CONST;
5397 if (cval == parser->nil)
5398 var->expression.flags |= AST_FLAG_INITIALIZED;
5401 var->hasvalue = true;
5402 if (cval->expression.vtype == TYPE_STRING)
5403 var->constval.vstring = parser_strdup(cval->constval.vstring);
5404 else if (cval->expression.vtype == TYPE_FIELD)
5405 var->constval.vfield = cval;
5407 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5413 shunt sy = { NULL, NULL, NULL, NULL };
5416 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5417 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5418 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5419 if (!parser_sy_apply_operator(parser, &sy))
5422 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5423 parseerror(parser, "internal error: leaked operands");
5424 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5434 if (parser->tok == ',') {
5435 if (!parser_next(parser)) {
5436 parseerror(parser, "expected another variable");
5440 if (parser->tok != TOKEN_IDENT) {
5441 parseerror(parser, "expected another variable");
5444 var = ast_value_copy(basetype);
5446 ast_value_set_name(var, parser_tokval(parser));
5447 if (!parser_next(parser)) {
5448 parseerror(parser, "error parsing variable declaration");
5454 if (parser->tok != ';') {
5455 parseerror(parser, "missing semicolon after variables");
5459 if (!parser_next(parser)) {
5460 parseerror(parser, "parse error after variable declaration");
5464 ast_delete(basetype);
5468 if (cleanvar && var)
5470 ast_delete(basetype);
5474 ast_delete(basetype);
5475 if (cleanvar && var)
5477 if (me[0]) ast_member_delete(me[0]);
5478 if (me[1]) ast_member_delete(me[1]);
5479 if (me[2]) ast_member_delete(me[2]);
5483 static bool parser_global_statement(parser_t *parser)
5487 bool is_static = false;
5488 uint32_t qflags = 0;
5489 ast_value *istype = NULL;
5490 char *vstring = NULL;
5492 if (parser->tok == TOKEN_IDENT)
5493 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5495 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5497 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5499 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5501 if (cvq == CV_WRONG)
5503 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5505 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5507 return parse_enum(parser);
5509 else if (parser->tok == TOKEN_KEYWORD)
5511 if (!strcmp(parser_tokval(parser), "typedef")) {
5512 if (!parser_next(parser)) {
5513 parseerror(parser, "expected type definition after 'typedef'");
5516 return parse_typedef(parser);
5518 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5521 else if (parser->tok == '#')
5523 return parse_pragma(parser);
5525 else if (parser->tok == '$')
5527 if (!parser_next(parser)) {
5528 parseerror(parser, "parse error");
5534 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5540 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5542 return util_crc16(old, str, strlen(str));
5545 static void progdefs_crc_file(const char *str)
5547 /* write to progdefs.h here */
5551 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5553 old = progdefs_crc_sum(old, str);
5554 progdefs_crc_file(str);
5558 static void generate_checksum(parser_t *parser)
5560 uint16_t crc = 0xFFFF;
5564 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5565 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5567 progdefs_crc_file("\tint\tpad;\n");
5568 progdefs_crc_file("\tint\tofs_return[3];\n");
5569 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5570 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5571 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5572 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5573 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5574 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5575 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5576 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5578 for (i = 0; i < parser->crc_globals; ++i) {
5579 if (!ast_istype(parser->globals[i], ast_value))
5581 value = (ast_value*)(parser->globals[i]);
5582 switch (value->expression.vtype) {
5583 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5584 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5585 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5586 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5588 crc = progdefs_crc_both(crc, "\tint\t");
5591 crc = progdefs_crc_both(crc, value->name);
5592 crc = progdefs_crc_both(crc, ";\n");
5594 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5595 for (i = 0; i < parser->crc_fields; ++i) {
5596 if (!ast_istype(parser->fields[i], ast_value))
5598 value = (ast_value*)(parser->fields[i]);
5599 switch (value->expression.next->expression.vtype) {
5600 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5601 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5602 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5603 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5605 crc = progdefs_crc_both(crc, "\tint\t");
5608 crc = progdefs_crc_both(crc, value->name);
5609 crc = progdefs_crc_both(crc, ";\n");
5611 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5616 static parser_t *parser;
5623 parser = (parser_t*)mem_a(sizeof(parser_t));
5627 memset(parser, 0, sizeof(*parser));
5629 for (i = 0; i < operator_count; ++i) {
5630 if (operators[i].id == opid1('=')) {
5631 parser->assign_op = operators+i;
5635 if (!parser->assign_op) {
5636 printf("internal error: initializing parser: failed to find assign operator\n");
5641 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5642 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5643 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5644 vec_push(parser->_blocktypedefs, 0);
5647 vec_push(parser->correct_variables, correct_trie_new());
5648 vec_push(parser->correct_variables_score, NULL);
5650 empty_ctx.file = "<internal>";
5652 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5653 parser->nil->cvq = CV_CONST;
5654 if (OPTS_FLAG(UNTYPED_NIL))
5655 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5657 parser->max_param_count = 1;
5659 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5660 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5661 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5663 if (opts.add_info) {
5664 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5665 parser->reserved_version->cvq = CV_CONST;
5666 parser->reserved_version->hasvalue = true;
5667 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5668 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5670 parser->reserved_version = NULL;
5675 bool parser_compile()
5677 /* initial lexer/parser state */
5678 parser->lex->flags.noops = true;
5680 if (parser_next(parser))
5682 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5684 if (!parser_global_statement(parser)) {
5685 if (parser->tok == TOKEN_EOF)
5686 parseerror(parser, "unexpected eof");
5687 else if (compile_errors)
5688 parseerror(parser, "there have been errors, bailing out");
5689 lex_close(parser->lex);
5695 parseerror(parser, "parse error");
5696 lex_close(parser->lex);
5701 lex_close(parser->lex);
5704 return !compile_errors;
5707 bool parser_compile_file(const char *filename)
5709 parser->lex = lex_open(filename);
5711 con_err("failed to open file \"%s\"\n", filename);
5714 return parser_compile();
5717 bool parser_compile_string(const char *name, const char *str, size_t len)
5719 parser->lex = lex_open_string(str, len, name);
5721 con_err("failed to create lexer for string \"%s\"\n", name);
5724 return parser_compile();
5727 void parser_cleanup()
5730 for (i = 0; i < vec_size(parser->accessors); ++i) {
5731 ast_delete(parser->accessors[i]->constval.vfunc);
5732 parser->accessors[i]->constval.vfunc = NULL;
5733 ast_delete(parser->accessors[i]);
5735 for (i = 0; i < vec_size(parser->functions); ++i) {
5736 ast_delete(parser->functions[i]);
5738 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5739 ast_delete(parser->imm_vector[i]);
5741 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5742 ast_delete(parser->imm_string[i]);
5744 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5745 ast_delete(parser->imm_float[i]);
5747 for (i = 0; i < vec_size(parser->fields); ++i) {
5748 ast_delete(parser->fields[i]);
5750 for (i = 0; i < vec_size(parser->globals); ++i) {
5751 ast_delete(parser->globals[i]);
5753 vec_free(parser->accessors);
5754 vec_free(parser->functions);
5755 vec_free(parser->imm_vector);
5756 vec_free(parser->imm_string);
5757 vec_free(parser->imm_float);
5758 vec_free(parser->globals);
5759 vec_free(parser->fields);
5761 for (i = 0; i < vec_size(parser->variables); ++i)
5762 util_htdel(parser->variables[i]);
5763 vec_free(parser->variables);
5764 vec_free(parser->_blocklocals);
5765 vec_free(parser->_locals);
5768 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5769 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5771 vec_free(parser->correct_variables);
5772 vec_free(parser->correct_variables_score);
5775 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5776 ast_delete(parser->_typedefs[i]);
5777 vec_free(parser->_typedefs);
5778 for (i = 0; i < vec_size(parser->typedefs); ++i)
5779 util_htdel(parser->typedefs[i]);
5780 vec_free(parser->typedefs);
5781 vec_free(parser->_blocktypedefs);
5783 vec_free(parser->_block_ctx);
5785 vec_free(parser->labels);
5786 vec_free(parser->gotos);
5787 vec_free(parser->breaks);
5788 vec_free(parser->continues);
5790 ast_value_delete(parser->nil);
5792 ast_value_delete(parser->const_vec[0]);
5793 ast_value_delete(parser->const_vec[1]);
5794 ast_value_delete(parser->const_vec[2]);
5799 bool parser_finish(const char *output)
5805 if (compile_errors) {
5806 con_out("*** there were compile errors\n");
5810 ir = ir_builder_new("gmqcc_out");
5812 con_out("failed to allocate builder\n");
5816 for (i = 0; i < vec_size(parser->fields); ++i) {
5819 if (!ast_istype(parser->fields[i], ast_value))
5821 field = (ast_value*)parser->fields[i];
5822 hasvalue = field->hasvalue;
5823 field->hasvalue = false;
5824 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5825 con_out("failed to generate field %s\n", field->name);
5826 ir_builder_delete(ir);
5831 ast_expression *subtype;
5832 field->hasvalue = true;
5833 subtype = field->expression.next;
5834 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5835 if (subtype->expression.vtype == TYPE_FIELD)
5836 ifld->fieldtype = subtype->expression.next->expression.vtype;
5837 else if (subtype->expression.vtype == TYPE_FUNCTION)
5838 ifld->outtype = subtype->expression.next->expression.vtype;
5839 (void)!ir_value_set_field(field->ir_v, ifld);
5842 for (i = 0; i < vec_size(parser->globals); ++i) {
5844 if (!ast_istype(parser->globals[i], ast_value))
5846 asvalue = (ast_value*)(parser->globals[i]);
5847 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5848 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5849 "unused global: `%s`", asvalue->name);
5851 if (!ast_global_codegen(asvalue, ir, false)) {
5852 con_out("failed to generate global %s\n", asvalue->name);
5853 ir_builder_delete(ir);
5857 /* Build function vararg accessor ast tree now before generating
5858 * immediates, because the accessors may add new immediates
5860 for (i = 0; i < vec_size(parser->functions); ++i) {
5861 ast_function *f = parser->functions[i];
5863 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5864 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5865 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5866 con_out("failed to generate vararg setter for %s\n", f->name);
5867 ir_builder_delete(ir);
5870 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5871 con_out("failed to generate vararg getter for %s\n", f->name);
5872 ir_builder_delete(ir);
5876 ast_delete(f->varargs);
5881 /* Now we can generate immediates */
5882 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5883 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5884 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5885 ir_builder_delete(ir);
5889 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5890 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5891 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5892 ir_builder_delete(ir);
5896 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5897 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5898 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5899 ir_builder_delete(ir);
5903 for (i = 0; i < vec_size(parser->globals); ++i) {
5905 if (!ast_istype(parser->globals[i], ast_value))
5907 asvalue = (ast_value*)(parser->globals[i]);
5908 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5910 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5911 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5912 "uninitialized constant: `%s`",
5914 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5915 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5916 "uninitialized global: `%s`",
5919 if (!ast_generate_accessors(asvalue, ir)) {
5920 ir_builder_delete(ir);
5924 for (i = 0; i < vec_size(parser->fields); ++i) {
5926 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5928 if (!ast_istype((ast_expression*)asvalue, ast_value))
5930 if (asvalue->expression.vtype != TYPE_ARRAY)
5932 if (!ast_generate_accessors(asvalue, ir)) {
5933 ir_builder_delete(ir);
5937 if (parser->reserved_version &&
5938 !ast_global_codegen(parser->reserved_version, ir, false))
5940 con_out("failed to generate reserved::version");
5941 ir_builder_delete(ir);
5944 for (i = 0; i < vec_size(parser->functions); ++i) {
5945 ast_function *f = parser->functions[i];
5946 if (!ast_function_codegen(f, ir)) {
5947 con_out("failed to generate function %s\n", f->name);
5948 ir_builder_delete(ir);
5953 ir_builder_dump(ir, con_out);
5954 for (i = 0; i < vec_size(parser->functions); ++i) {
5955 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5956 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5957 ir_builder_delete(ir);
5962 if (compile_Werrors) {
5963 con_out("*** there were warnings treated as errors\n");
5964 compile_show_werrors();
5970 ir_builder_dump(ir, con_out);
5972 generate_checksum(parser);
5974 if (!ir_builder_generate(ir, output)) {
5975 con_out("*** failed to generate output file\n");
5976 ir_builder_delete(ir);
5981 ir_builder_delete(ir);