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 1024
35 #define TYPEDEF_HT_SIZE 16
37 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_vector_zero;
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;
91 /* Keep track of our ternary vs parenthesis nesting state.
92 * If we reach a 'comma' operator in a ternary without a paren,
93 * we shall trigger -Wternary-precedence.
98 ast_value *const_vec[3];
104 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
106 static void parser_enterblock(parser_t *parser);
107 static bool parser_leaveblock(parser_t *parser);
108 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
109 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
110 static bool parse_typedef(parser_t *parser);
111 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);
112 static ast_block* parse_block(parser_t *parser);
113 static bool parse_block_into(parser_t *parser, ast_block *block);
114 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
115 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
116 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
117 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
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 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
143 r = vcompile_warning(ctx, warntype, fmt, ap);
148 /**********************************************************************
149 * some maths used for constant folding
152 vector vec3_add(vector a, vector b)
161 vector vec3_sub(vector a, vector b)
170 qcfloat vec3_mulvv(vector a, vector b)
172 return (a.x * b.x + a.y * b.y + a.z * b.z);
175 vector vec3_mulvf(vector a, float b)
184 /**********************************************************************
188 bool parser_next(parser_t *parser)
190 /* lex_do kills the previous token */
191 parser->tok = lex_do(parser->lex);
192 if (parser->tok == TOKEN_EOF)
194 if (parser->tok >= TOKEN_ERROR) {
195 parseerror(parser, "lex error");
201 #define parser_tokval(p) ((p)->lex->tok.value)
202 #define parser_token(p) (&((p)->lex->tok))
203 #define parser_ctx(p) ((p)->lex->tok.ctx)
205 static ast_value* parser_const_float(parser_t *parser, double d)
209 for (i = 0; i < vec_size(parser->imm_float); ++i) {
210 const double compare = parser->imm_float[i]->constval.vfloat;
211 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
212 return parser->imm_float[i];
214 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
216 out->hasvalue = true;
217 out->constval.vfloat = d;
218 vec_push(parser->imm_float, out);
222 static ast_value* parser_const_float_0(parser_t *parser)
224 if (!parser->imm_float_zero)
225 parser->imm_float_zero = parser_const_float(parser, 0);
226 return parser->imm_float_zero;
229 static ast_value* parser_const_float_1(parser_t *parser)
231 if (!parser->imm_float_one)
232 parser->imm_float_one = parser_const_float(parser, 1);
233 return parser->imm_float_one;
236 static char *parser_strdup(const char *str)
239 /* actually dup empty strings */
240 char *out = (char*)mem_a(1);
244 return util_strdup(str);
247 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
251 for (i = 0; i < vec_size(parser->imm_string); ++i) {
252 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
253 return parser->imm_string[i];
257 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
258 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
260 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
262 out->hasvalue = true;
263 out->constval.vstring = parser_strdup(str);
264 vec_push(parser->imm_string, out);
268 static ast_value* parser_const_vector(parser_t *parser, vector v)
272 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
273 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
274 return parser->imm_vector[i];
276 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
278 out->hasvalue = true;
279 out->constval.vvec = v;
280 vec_push(parser->imm_vector, out);
284 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
290 return parser_const_vector(parser, v);
293 static ast_value* parser_const_vector_0(parser_t *parser)
295 if (!parser->imm_vector_zero)
296 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
297 return parser->imm_vector_zero;
300 static ast_expression* parser_find_field(parser_t *parser, const char *name)
302 return ( ast_expression*)util_htget(parser->htfields, name);
305 static ast_expression* parser_find_label(parser_t *parser, const char *name)
308 for(i = 0; i < vec_size(parser->labels); i++)
309 if (!strcmp(parser->labels[i]->name, name))
310 return (ast_expression*)parser->labels[i];
314 static ast_expression* parser_find_global(parser_t *parser, const char *name)
316 return (ast_expression*)util_htget(parser->htglobals, name);
319 static ast_expression* parser_find_param(parser_t *parser, const char *name)
323 if (!parser->function)
325 fun = parser->function->vtype;
326 for (i = 0; i < vec_size(fun->expression.params); ++i) {
327 if (!strcmp(fun->expression.params[i]->name, name))
328 return (ast_expression*)(fun->expression.params[i]);
333 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
338 hash = util_hthash(parser->htglobals, name);
341 for (i = vec_size(parser->variables); i > upto;) {
343 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
347 return parser_find_param(parser, name);
350 static ast_expression* parser_find_var(parser_t *parser, const char *name)
354 v = parser_find_local(parser, name, 0, &dummy);
355 if (!v) v = parser_find_global(parser, name);
359 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
363 hash = util_hthash(parser->typedefs[0], name);
365 for (i = vec_size(parser->typedefs); i > upto;) {
367 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
375 size_t etype; /* 0 = expression, others are operators */
379 ast_block *block; /* for commas and function calls */
388 #define SY_PAREN_EXPR '('
389 #define SY_PAREN_FUNC 'f'
390 #define SY_PAREN_INDEX '['
391 #define SY_PAREN_TERNARY '?'
393 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
404 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
408 e.out = (ast_expression*)v;
415 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
417 e.etype = 1 + (op - operators);
426 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
438 # define DEBUGSHUNTDO(x) x
440 # define DEBUGSHUNTDO(x)
443 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
444 * so we need to rotate it to become ent.(foo[n]).
446 static bool rotate_entfield_array_index_nodes(ast_expression **out)
448 ast_array_index *index;
449 ast_entfield *entfield;
453 ast_expression *entity;
455 lex_ctx ctx = ast_ctx(*out);
457 if (!ast_istype(*out, ast_array_index))
459 index = (ast_array_index*)*out;
461 if (!ast_istype(index->array, ast_entfield))
463 entfield = (ast_entfield*)index->array;
465 if (!ast_istype(entfield->field, ast_value))
467 field = (ast_value*)entfield->field;
470 entity = entfield->entity;
474 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
475 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
476 *out = (ast_expression*)entfield;
481 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
483 switch (v->expression.vtype) {
485 return !!v->constval.vfloat;
487 return !!v->constval.vint;
489 if (OPTS_FLAG(CORRECT_LOGIC))
490 return v->constval.vvec.x &&
491 v->constval.vvec.y &&
494 return !!(v->constval.vvec.x);
496 if (!v->constval.vstring)
498 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
500 return !!v->constval.vstring[0];
502 compile_error(ctx, "internal error: immediate_is_true on invalid type");
503 return !!v->constval.vfunc;
507 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
511 ast_expression *out = NULL;
512 ast_expression *exprs[3];
513 ast_block *blocks[3];
514 ast_value *asvalue[3];
515 ast_binstore *asbinstore;
516 size_t i, assignop, addop, subop;
517 qcint generated_op = 0;
522 if (!vec_size(sy->ops)) {
523 parseerror(parser, "internal error: missing operator");
527 if (vec_last(sy->ops).paren) {
528 parseerror(parser, "unmatched parenthesis");
532 op = &operators[vec_last(sy->ops).etype - 1];
533 ctx = vec_last(sy->ops).ctx;
535 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
537 if (vec_size(sy->out) < op->operands) {
538 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
539 op->op, (int)op->id);
543 vec_shrinkby(sy->ops, 1);
545 /* op(:?) has no input and no output */
549 vec_shrinkby(sy->out, op->operands);
550 for (i = 0; i < op->operands; ++i) {
551 exprs[i] = sy->out[vec_size(sy->out)+i].out;
552 blocks[i] = sy->out[vec_size(sy->out)+i].block;
553 asvalue[i] = (ast_value*)exprs[i];
555 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
556 !(i != 0 && op->id == opid2('?',':')) &&
557 !(i == 1 && op->id == opid1('.')))
559 if (ast_istype(exprs[i], ast_label))
560 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
562 compile_error(ast_ctx(exprs[i]), "not an expression");
563 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
567 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
568 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
572 #define NotSameType(T) \
573 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
574 exprs[0]->expression.vtype != T)
575 #define CanConstFold1(A) \
576 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
577 (A)->expression.vtype != TYPE_FUNCTION)
578 #define CanConstFold(A, B) \
579 (CanConstFold1(A) && CanConstFold1(B))
580 #define ConstV(i) (asvalue[(i)]->constval.vvec)
581 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
582 #define ConstS(i) (asvalue[(i)]->constval.vstring)
586 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
590 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
591 exprs[1]->expression.vtype == TYPE_NOEXPR)
593 if (exprs[1] == (ast_expression*)parser->const_vec[0])
594 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
595 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
596 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
597 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
598 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
600 parseerror(parser, "access to invalid vector component");
604 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
605 if (exprs[1]->expression.vtype != TYPE_FIELD) {
606 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
609 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
611 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
612 parseerror(parser, "vectors cannot be accessed this way");
616 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
622 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
623 !(exprs[0]->expression.vtype == TYPE_FIELD &&
624 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
626 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
627 parseerror(parser, "cannot index value of type %s", ty1);
630 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
631 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
632 parseerror(parser, "index must be of type float, not %s", ty1);
635 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
636 if (rotate_entfield_array_index_nodes(&out))
639 /* This is not broken in fteqcc anymore */
640 if (opts.standard != COMPILER_GMQCC) {
641 /* this error doesn't need to make us bail out */
642 (void)!parsewarning(parser, WARN_EXTENSIONS,
643 "accessing array-field members of an entity without parenthesis\n"
644 " -> this is an extension from -std=gmqcc");
652 if (!ast_block_add_expr(blocks[0], exprs[1]))
655 blocks[0] = ast_block_new(ctx);
656 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
657 !ast_block_add_expr(blocks[0], exprs[1]))
662 if (!ast_block_set_type(blocks[0], exprs[1]))
665 vec_push(sy->out, syblock(ctx, blocks[0]));
672 switch (exprs[0]->expression.vtype) {
674 if (CanConstFold1(exprs[0]))
675 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
677 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
678 (ast_expression*)parser_const_float_0(parser),
682 if (CanConstFold1(exprs[0]))
683 out = (ast_expression*)parser_const_vector_f(parser,
684 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
686 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
687 (ast_expression*)parser_const_vector_0(parser),
691 parseerror(parser, "invalid types used in expression: cannot negate type %s",
692 type_name[exprs[0]->expression.vtype]);
698 switch (exprs[0]->expression.vtype) {
700 if (CanConstFold1(exprs[0]))
701 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
703 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
706 if (CanConstFold1(exprs[0]))
707 out = (ast_expression*)parser_const_float(parser,
708 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
710 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
713 if (CanConstFold1(exprs[0])) {
714 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
715 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
717 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
719 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
720 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
725 /* we don't constant-fold NOT for these types */
727 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
730 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
733 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
734 type_name[exprs[0]->expression.vtype]);
740 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
741 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
743 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
744 type_name[exprs[0]->expression.vtype],
745 type_name[exprs[1]->expression.vtype]);
748 switch (exprs[0]->expression.vtype) {
750 if (CanConstFold(exprs[0], exprs[1]))
752 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
755 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
758 if (CanConstFold(exprs[0], exprs[1]))
759 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
761 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
764 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
765 type_name[exprs[0]->expression.vtype],
766 type_name[exprs[1]->expression.vtype]);
771 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
772 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
774 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
775 type_name[exprs[1]->expression.vtype],
776 type_name[exprs[0]->expression.vtype]);
779 switch (exprs[0]->expression.vtype) {
781 if (CanConstFold(exprs[0], exprs[1]))
782 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
784 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
787 if (CanConstFold(exprs[0], exprs[1]))
788 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
790 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
793 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
794 type_name[exprs[1]->expression.vtype],
795 type_name[exprs[0]->expression.vtype]);
800 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
801 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
802 exprs[1]->expression.vtype == TYPE_FLOAT) &&
803 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
804 exprs[0]->expression.vtype == TYPE_FLOAT)
807 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
808 type_name[exprs[1]->expression.vtype],
809 type_name[exprs[0]->expression.vtype]);
812 switch (exprs[0]->expression.vtype) {
814 if (exprs[1]->expression.vtype == TYPE_VECTOR)
816 if (CanConstFold(exprs[0], exprs[1]))
817 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
819 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
823 if (CanConstFold(exprs[0], exprs[1]))
824 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
826 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
830 if (exprs[1]->expression.vtype == TYPE_FLOAT)
832 if (CanConstFold(exprs[0], exprs[1]))
833 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
835 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
839 if (CanConstFold(exprs[0], exprs[1]))
840 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
841 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
842 vector vec = ConstV(0);
843 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
844 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
845 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
846 out->expression.node.keep = false;
847 ((ast_member*)out)->rvalue = true;
849 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
851 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
852 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
853 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
854 out->expression.node.keep = false;
855 ((ast_member*)out)->rvalue = true;
857 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
859 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
860 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
861 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
862 out->expression.node.keep = false;
863 ((ast_member*)out)->rvalue = true;
865 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
868 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
870 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
871 vector vec = ConstV(1);
872 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
873 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
874 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
875 out->expression.node.keep = false;
876 ((ast_member*)out)->rvalue = true;
878 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
880 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
881 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
882 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
883 out->expression.node.keep = false;
884 ((ast_member*)out)->rvalue = true;
886 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
888 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
889 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
890 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
891 out->expression.node.keep = false;
892 ((ast_member*)out)->rvalue = true;
894 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
897 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
900 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
904 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
905 type_name[exprs[1]->expression.vtype],
906 type_name[exprs[0]->expression.vtype]);
911 if (NotSameType(TYPE_FLOAT)) {
912 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
913 type_name[exprs[0]->expression.vtype],
914 type_name[exprs[1]->expression.vtype]);
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]);
924 parseerror(parser, "qc does not have a modulo operator");
928 if (NotSameType(TYPE_FLOAT)) {
929 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
930 type_name[exprs[0]->expression.vtype],
931 type_name[exprs[1]->expression.vtype]);
934 if (CanConstFold(exprs[0], exprs[1]))
935 out = (ast_expression*)parser_const_float(parser,
936 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
937 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
939 out = (ast_expression*)ast_binary_new(ctx,
940 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
944 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
949 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
950 if (op->id == opid2('<','<'))
951 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
953 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
956 case opid3('<','<','='):
957 case opid3('>','>','='):
958 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
962 generated_op += 1; /* INSTR_OR */
964 generated_op += INSTR_AND;
966 if (NotSameType(TYPE_FLOAT)) {
967 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
968 type_name[exprs[0]->expression.vtype],
969 type_name[exprs[1]->expression.vtype]);
970 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
971 parseerror(parser, "TODO: optional early out");
975 if (CanConstFold(exprs[0], exprs[1]))
977 if (OPTS_FLAG(PERL_LOGIC)) {
978 if (immediate_is_true(ctx, asvalue[0]))
982 out = (ast_expression*)parser_const_float(parser,
983 ( (generated_op == INSTR_OR)
984 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
985 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
990 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
991 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
992 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
993 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
996 for (i = 0; i < 2; ++i) {
997 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
998 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1000 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1002 exprs[i] = out; out = NULL;
1003 if (OPTS_FLAG(PERL_LOGIC)) {
1004 /* here we want to keep the right expressions' type */
1008 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1009 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1011 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1013 exprs[i] = out; out = NULL;
1014 if (OPTS_FLAG(PERL_LOGIC)) {
1015 /* here we want to keep the right expressions' type */
1020 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1024 case opid2('?',':'):
1025 if (vec_last(parser->pot) != POT_TERNARY2) {
1026 parseerror(parser, "mismatched parenthesis/ternary");
1029 vec_pop(parser->pot);
1030 if (!ast_compare_type(exprs[1], exprs[2])) {
1031 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1032 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1033 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1036 if (CanConstFold1(exprs[0]))
1037 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1039 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1043 generated_op += 1; /* INSTR_GT */
1045 generated_op += 1; /* INSTR_LT */
1046 case opid2('>', '='):
1047 generated_op += 1; /* INSTR_GE */
1048 case opid2('<', '='):
1049 generated_op += INSTR_LE;
1050 if (NotSameType(TYPE_FLOAT)) {
1051 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1052 type_name[exprs[0]->expression.vtype],
1053 type_name[exprs[1]->expression.vtype]);
1056 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1058 case opid2('!', '='):
1059 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1060 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1061 type_name[exprs[0]->expression.vtype],
1062 type_name[exprs[1]->expression.vtype]);
1065 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1067 case opid2('=', '='):
1068 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1069 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1070 type_name[exprs[0]->expression.vtype],
1071 type_name[exprs[1]->expression.vtype]);
1074 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1078 if (ast_istype(exprs[0], ast_entfield)) {
1079 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1080 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1081 exprs[0]->expression.vtype == TYPE_FIELD &&
1082 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1084 assignop = type_storep_instr[TYPE_VECTOR];
1087 assignop = type_storep_instr[exprs[0]->expression.vtype];
1088 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1090 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1091 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1092 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1093 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1094 exprs[1]->expression.vtype == TYPE_FUNCTION)
1096 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1097 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1100 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1105 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1106 exprs[0]->expression.vtype == TYPE_FIELD &&
1107 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1109 assignop = type_store_instr[TYPE_VECTOR];
1112 assignop = type_store_instr[exprs[0]->expression.vtype];
1115 if (assignop == AINSTR_END) {
1116 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1117 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1118 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1120 else if (!ast_compare_type(exprs[0], exprs[1]))
1122 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1125 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1126 exprs[1]->expression.vtype == TYPE_FUNCTION)
1128 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1129 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1132 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1135 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1136 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1138 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1140 case opid3('+','+','P'):
1141 case opid3('-','-','P'):
1143 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1144 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1145 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1148 if (op->id == opid3('+','+','P'))
1149 addop = INSTR_ADD_F;
1151 addop = INSTR_SUB_F;
1152 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1153 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1155 if (ast_istype(exprs[0], ast_entfield)) {
1156 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1158 (ast_expression*)parser_const_float_1(parser));
1160 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1162 (ast_expression*)parser_const_float_1(parser));
1165 case opid3('S','+','+'):
1166 case opid3('S','-','-'):
1168 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1169 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1170 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1173 if (op->id == opid3('S','+','+')) {
1174 addop = INSTR_ADD_F;
1175 subop = INSTR_SUB_F;
1177 addop = INSTR_SUB_F;
1178 subop = INSTR_ADD_F;
1180 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1181 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1183 if (ast_istype(exprs[0], ast_entfield)) {
1184 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1186 (ast_expression*)parser_const_float_1(parser));
1188 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1190 (ast_expression*)parser_const_float_1(parser));
1194 out = (ast_expression*)ast_binary_new(ctx, subop,
1196 (ast_expression*)parser_const_float_1(parser));
1198 case opid2('+','='):
1199 case opid2('-','='):
1200 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1201 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1203 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1204 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1205 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1209 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1210 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1212 if (ast_istype(exprs[0], ast_entfield))
1213 assignop = type_storep_instr[exprs[0]->expression.vtype];
1215 assignop = type_store_instr[exprs[0]->expression.vtype];
1216 switch (exprs[0]->expression.vtype) {
1218 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1219 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1220 exprs[0], exprs[1]);
1223 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1224 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1225 exprs[0], exprs[1]);
1228 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1229 type_name[exprs[0]->expression.vtype],
1230 type_name[exprs[1]->expression.vtype]);
1234 case opid2('*','='):
1235 case opid2('/','='):
1236 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1237 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1238 exprs[0]->expression.vtype == TYPE_VECTOR))
1240 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1241 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1242 parseerror(parser, "invalid types used in expression: %s and %s",
1246 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1247 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1249 if (ast_istype(exprs[0], ast_entfield))
1250 assignop = type_storep_instr[exprs[0]->expression.vtype];
1252 assignop = type_store_instr[exprs[0]->expression.vtype];
1253 switch (exprs[0]->expression.vtype) {
1255 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1256 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1257 exprs[0], exprs[1]);
1260 if (op->id == opid2('*','=')) {
1261 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1262 exprs[0], exprs[1]);
1264 /* there's no DIV_VF */
1265 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1266 (ast_expression*)parser_const_float_1(parser),
1270 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1275 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1276 type_name[exprs[0]->expression.vtype],
1277 type_name[exprs[1]->expression.vtype]);
1281 case opid2('&','='):
1282 case opid2('|','='):
1283 if (NotSameType(TYPE_FLOAT)) {
1284 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1285 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1286 parseerror(parser, "invalid types used in expression: %s and %s",
1290 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1291 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1293 if (ast_istype(exprs[0], ast_entfield))
1294 assignop = type_storep_instr[exprs[0]->expression.vtype];
1296 assignop = type_store_instr[exprs[0]->expression.vtype];
1297 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1298 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1299 exprs[0], exprs[1]);
1301 case opid3('&','~','='):
1302 /* This is like: a &= ~(b);
1303 * But QC has no bitwise-not, so we implement it as
1306 if (NotSameType(TYPE_FLOAT)) {
1307 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1308 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1309 parseerror(parser, "invalid types used in expression: %s and %s",
1313 if (ast_istype(exprs[0], ast_entfield))
1314 assignop = type_storep_instr[exprs[0]->expression.vtype];
1316 assignop = type_store_instr[exprs[0]->expression.vtype];
1317 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1320 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1321 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1323 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1324 asbinstore->keep_dest = true;
1325 out = (ast_expression*)asbinstore;
1331 parseerror(parser, "failed to apply operand %s", op->op);
1335 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1336 vec_push(sy->out, syexp(ctx, out));
1340 static bool parser_close_call(parser_t *parser, shunt *sy)
1342 /* was a function call */
1343 ast_expression *fun;
1349 vec_shrinkby(sy->ops, 1);
1350 fid = sy->ops[vec_size(sy->ops)].off;
1352 /* out[fid] is the function
1353 * everything above is parameters...
1354 * 0 params = nothing
1355 * 1 params = ast_expression
1359 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1360 parseerror(parser, "internal error: function call needs function and parameter list...");
1364 fun = sy->out[fid].out;
1366 if (fun == intrinsic_debug_typestring) {
1368 if (fid+2 != vec_size(sy->out) ||
1369 vec_last(sy->out).block)
1371 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1374 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1375 ast_unref(vec_last(sy->out).out);
1376 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1377 (ast_expression*)parser_const_string(parser, ty, false));
1378 vec_shrinkby(sy->out, 1);
1382 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1384 parseerror(parser, "internal error: failed to create ast_call node");
1388 if (fid+1 == vec_size(sy->out)) {
1391 } else if (fid+2 == vec_size(sy->out)) {
1393 vec_shrinkby(sy->out, 1);
1394 params = sy->out[vec_size(sy->out)].block;
1398 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1400 paramcount = vec_size(params->exprs);
1401 call->params = params->exprs;
1402 params->exprs = NULL;
1405 (void)!ast_call_check_types(call);
1407 parseerror(parser, "invalid function call");
1411 /* overwrite fid, the function, with a call */
1412 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1414 if (fun->expression.vtype != TYPE_FUNCTION) {
1415 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1419 if (!fun->expression.next) {
1420 parseerror(parser, "could not determine function return type");
1423 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1425 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1427 return !parsewarning(parser, WARN_DEPRECATED,
1428 "call to function (which is marked deprecated)\n",
1429 "-> it has been declared here: %s:%i",
1430 ast_ctx(fun).file, ast_ctx(fun).line);
1433 return !parsewarning(parser, WARN_DEPRECATED,
1434 "call to `%s` (which is marked deprecated)\n"
1435 "-> `%s` declared here: %s:%i",
1436 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1438 return !parsewarning(parser, WARN_DEPRECATED,
1439 "call to `%s` (deprecated: %s)\n"
1440 "-> `%s` declared here: %s:%i",
1441 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1445 if (vec_size(fun->expression.params) != paramcount &&
1446 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1447 vec_size(fun->expression.params) < paramcount))
1449 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1451 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1452 "too %s parameters for call to %s: expected %i, got %i\n"
1453 " -> `%s` has been declared here: %s:%i",
1454 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1455 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1457 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1458 "too %s parameters for function call: expected %i, got %i\n"
1459 " -> it has been declared here: %s:%i",
1460 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1461 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1468 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1470 if (!vec_size(sy->ops)) {
1471 parseerror(parser, "unmatched closing paren");
1474 /* this would for bit a + (x) because there are no operators inside (x)
1475 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1476 parseerror(parser, "empty parenthesis expression");
1480 while (vec_size(sy->ops)) {
1481 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1482 if (!parser_close_call(parser, sy))
1486 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1487 vec_shrinkby(sy->ops, 1);
1488 return !functions_only;
1490 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1493 /* pop off the parenthesis */
1494 vec_shrinkby(sy->ops, 1);
1495 /* then apply the index operator */
1496 if (!parser_sy_apply_operator(parser, sy))
1500 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1503 if (vec_last(parser->pot) != POT_TERNARY1) {
1504 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1507 vec_last(parser->pot) = POT_TERNARY2;
1508 /* pop off the parenthesis */
1509 vec_shrinkby(sy->ops, 1);
1512 if (!parser_sy_apply_operator(parser, sy))
1518 static void parser_reclassify_token(parser_t *parser)
1521 for (i = 0; i < operator_count; ++i) {
1522 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1523 parser->tok = TOKEN_OPERATOR;
1529 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1531 ast_expression *expr = NULL;
1533 bool wantop = false;
1534 /* only warn once about an assignment in a truth value because the current code
1535 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1537 bool warn_truthvalue = true;
1539 /* count the parens because an if starts with one, so the
1540 * end of a condition is an unmatched closing paren
1548 parser->lex->flags.noops = false;
1550 parser_reclassify_token(parser);
1554 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1555 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1557 /* a translatable string */
1561 parseerror(parser, "expected operator or end of statement, got constant");
1565 parser->lex->flags.noops = true;
1566 if (!parser_next(parser) || parser->tok != '(') {
1567 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1570 parser->lex->flags.noops = false;
1571 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1572 parseerror(parser, "expected a constant string in translatable-string extension");
1575 val = parser_const_string(parser, parser_tokval(parser), true);
1579 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1580 DEBUGSHUNTDO(con_out("push string\n"));
1582 if (!parser_next(parser) || parser->tok != ')') {
1583 parseerror(parser, "expected closing paren after translatable string");
1587 else if (parser->tok == TOKEN_IDENT)
1589 const char *ctoken = parser_tokval(parser);
1590 ast_expression *prev = vec_size(sy.out) ? vec_last(sy.out).out : NULL;
1591 ast_expression *var;
1593 parseerror(parser, "expected operator or end of statement");
1597 /* a_vector.{x,y,z} */
1598 if (!vec_size(sy.ops) ||
1599 !vec_last(sy.ops).etype ||
1600 operators[vec_last(sy.ops).etype-1].id != opid1('.') ||
1601 (prev >= intrinsic_debug_typestring &&
1602 prev <= intrinsic_debug_typestring))
1604 /* When adding more intrinsics, fix the above condition */
1607 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1609 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1611 var = parser_find_var(parser, parser_tokval(parser));
1613 var = parser_find_field(parser, parser_tokval(parser));
1615 if (!var && with_labels) {
1616 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1618 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1619 var = (ast_expression*)lbl;
1620 vec_push(parser->labels, lbl);
1625 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1626 var = (ast_expression*)intrinsic_debug_typestring;
1631 char *correct = NULL;
1634 * sometimes people use preprocessing predefs without enabling them
1635 * i've done this thousands of times already myself. Lets check for
1636 * it in the predef table. And diagnose it better :)
1638 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1639 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1640 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1641 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1648 * TODO: determine the best score for the identifier: be it
1649 * a variable, a field.
1651 * We should also consider adding correction tables for
1652 * other things as well.
1654 if (OPTS_FLAG(ENHANCED_DIAGNOSTICS)) {
1656 correct_init(&corr);
1658 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1659 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1660 if (strcmp(correct, parser_tokval(parser))) {
1662 } else if (correct) {
1667 correct_free(&corr);
1670 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1675 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1681 if (ast_istype(var, ast_value)) {
1682 ((ast_value*)var)->uses++;
1684 else if (ast_istype(var, ast_member)) {
1685 ast_member *mem = (ast_member*)var;
1686 if (ast_istype(mem->owner, ast_value))
1687 ((ast_value*)(mem->owner))->uses++;
1690 vec_push(sy.out, syexp(parser_ctx(parser), var));
1691 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1693 else if (parser->tok == TOKEN_FLOATCONST) {
1696 parseerror(parser, "expected operator or end of statement, got constant");
1700 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1703 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1704 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1706 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1709 parseerror(parser, "expected operator or end of statement, got constant");
1713 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1716 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1717 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1719 else if (parser->tok == TOKEN_STRINGCONST) {
1722 parseerror(parser, "expected operator or end of statement, got constant");
1726 val = parser_const_string(parser, parser_tokval(parser), false);
1729 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1730 DEBUGSHUNTDO(con_out("push string\n"));
1732 else if (parser->tok == TOKEN_VECTORCONST) {
1735 parseerror(parser, "expected operator or end of statement, got constant");
1739 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1742 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1743 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1744 parser_token(parser)->constval.v.x,
1745 parser_token(parser)->constval.v.y,
1746 parser_token(parser)->constval.v.z));
1748 else if (parser->tok == '(') {
1749 parseerror(parser, "internal error: '(' should be classified as operator");
1752 else if (parser->tok == '[') {
1753 parseerror(parser, "internal error: '[' should be classified as operator");
1756 else if (parser->tok == ')') {
1758 DEBUGSHUNTDO(con_out("do[op] )\n"));
1762 /* we do expect an operator next */
1763 /* closing an opening paren */
1764 if (!parser_close_paren(parser, &sy, false))
1766 if (vec_last(parser->pot) != POT_PAREN) {
1767 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1770 vec_pop(parser->pot);
1772 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1776 /* allowed for function calls */
1777 if (!parser_close_paren(parser, &sy, true))
1779 if (vec_last(parser->pot) != POT_PAREN) {
1780 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1783 vec_pop(parser->pot);
1787 else if (parser->tok == ']') {
1789 parseerror(parser, "operand expected");
1793 if (!parser_close_paren(parser, &sy, false))
1795 if (vec_last(parser->pot) != POT_PAREN) {
1796 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1799 vec_pop(parser->pot);
1802 else if (parser->tok == TOKEN_TYPENAME) {
1803 parseerror(parser, "unexpected typename");
1806 else if (parser->tok != TOKEN_OPERATOR) {
1808 parseerror(parser, "expected operator or end of statement");
1815 /* classify the operator */
1816 const oper_info *op;
1817 const oper_info *olast = NULL;
1819 for (o = 0; o < operator_count; ++o) {
1820 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1821 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1822 !strcmp(parser_tokval(parser), operators[o].op))
1827 if (o == operator_count) {
1828 /* no operator found... must be the end of the statement */
1831 /* found an operator */
1834 /* when declaring variables, a comma starts a new variable */
1835 if (op->id == opid1(',') && !parens && stopatcomma) {
1836 /* fixup the token */
1841 /* a colon without a pervious question mark cannot be a ternary */
1842 if (!ternaries && op->id == opid2(':','?')) {
1847 if (op->id == opid1(',')) {
1848 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1849 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1853 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1854 olast = &operators[vec_last(sy.ops).etype-1];
1856 #define IsAssignOp(x) (\
1857 (x) == opid1('=') || \
1858 (x) == opid2('+','=') || \
1859 (x) == opid2('-','=') || \
1860 (x) == opid2('*','=') || \
1861 (x) == opid2('/','=') || \
1862 (x) == opid2('%','=') || \
1863 (x) == opid2('&','=') || \
1864 (x) == opid2('|','=') || \
1865 (x) == opid3('&','~','=') \
1867 if (warn_truthvalue) {
1868 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1869 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1870 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1873 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1874 warn_truthvalue = false;
1879 (op->prec < olast->prec) ||
1880 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1882 if (!parser_sy_apply_operator(parser, &sy))
1884 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1885 olast = &operators[vec_last(sy.ops).etype-1];
1890 if (op->id == opid1('(')) {
1892 size_t sycount = vec_size(sy.out);
1893 DEBUGSHUNTDO(con_out("push [op] (\n"));
1894 ++parens; vec_push(parser->pot, POT_PAREN);
1895 /* we expected an operator, this is the function-call operator */
1896 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1898 ++parens; vec_push(parser->pot, POT_PAREN);
1899 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1900 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1903 } else if (op->id == opid1('[')) {
1905 parseerror(parser, "unexpected array subscript");
1908 ++parens; vec_push(parser->pot, POT_PAREN);
1909 /* push both the operator and the paren, this makes life easier */
1910 vec_push(sy.ops, syop(parser_ctx(parser), op));
1911 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1913 } else if (op->id == opid2('?',':')) {
1914 vec_push(sy.ops, syop(parser_ctx(parser), op));
1915 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1918 vec_push(parser->pot, POT_TERNARY1);
1919 } else if (op->id == opid2(':','?')) {
1920 if (!vec_size(parser->pot)) {
1921 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1924 if (vec_last(parser->pot) != POT_TERNARY1) {
1925 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1928 if (!parser_close_paren(parser, &sy, false))
1930 vec_push(sy.ops, syop(parser_ctx(parser), op));
1934 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1935 vec_push(sy.ops, syop(parser_ctx(parser), op));
1936 wantop = !!(op->flags & OP_SUFFIX);
1939 if (!parser_next(parser)) {
1942 if (parser->tok == ';' ||
1943 (!parens && (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1949 while (vec_size(sy.ops)) {
1950 if (!parser_sy_apply_operator(parser, &sy))
1954 parser->lex->flags.noops = true;
1955 if (!vec_size(sy.out)) {
1956 parseerror(parser, "empty expression");
1959 expr = sy.out[0].out;
1962 DEBUGSHUNTDO(con_out("shunt done\n"));
1963 if (vec_size(parser->pot)) {
1964 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1967 vec_free(parser->pot);
1971 parser->lex->flags.noops = true;
1977 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1979 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1982 if (parser->tok != ';') {
1983 parseerror(parser, "semicolon expected after expression");
1987 if (!parser_next(parser)) {
1994 static void parser_enterblock(parser_t *parser)
1996 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1997 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1998 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1999 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2000 vec_push(parser->_block_ctx, parser_ctx(parser));
2003 vec_push(parser->correct_variables, correct_trie_new());
2004 vec_push(parser->correct_variables_score, NULL);
2007 static bool parser_leaveblock(parser_t *parser)
2010 size_t locals, typedefs;
2012 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2013 parseerror(parser, "internal error: parser_leaveblock with no block");
2017 util_htdel(vec_last(parser->variables));
2018 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2020 vec_pop(parser->variables);
2021 vec_pop(parser->correct_variables);
2022 vec_pop(parser->correct_variables_score);
2023 if (!vec_size(parser->_blocklocals)) {
2024 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2028 locals = vec_last(parser->_blocklocals);
2029 vec_pop(parser->_blocklocals);
2030 while (vec_size(parser->_locals) != locals) {
2031 ast_expression *e = vec_last(parser->_locals);
2032 ast_value *v = (ast_value*)e;
2033 vec_pop(parser->_locals);
2034 if (ast_istype(e, ast_value) && !v->uses) {
2035 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2040 typedefs = vec_last(parser->_blocktypedefs);
2041 while (vec_size(parser->_typedefs) != typedefs) {
2042 ast_delete(vec_last(parser->_typedefs));
2043 vec_pop(parser->_typedefs);
2045 util_htdel(vec_last(parser->typedefs));
2046 vec_pop(parser->typedefs);
2048 vec_pop(parser->_block_ctx);
2053 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2055 vec_push(parser->_locals, e);
2056 util_htset(vec_last(parser->variables), name, (void*)e);
2060 vec_last(parser->correct_variables),
2061 &vec_last(parser->correct_variables_score),
2066 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2068 vec_push(parser->globals, e);
2069 util_htset(parser->htglobals, name, e);
2073 parser->correct_variables[0],
2074 &parser->correct_variables_score[0],
2079 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2083 ast_expression *prev;
2085 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2088 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2091 parseerror(parser, "internal error: failed to process condition");
2096 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2098 /* vector types need to be cast to true booleans */
2099 ast_binary *bin = (ast_binary*)cond;
2100 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2102 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2104 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2107 parseerror(parser, "internal error: failed to process condition");
2114 unary = (ast_unary*)cond;
2115 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2117 cond = unary->operand;
2118 unary->operand = NULL;
2121 unary = (ast_unary*)cond;
2125 parseerror(parser, "internal error: failed to process condition");
2127 if (ifnot) *_ifnot = !*_ifnot;
2131 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2134 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2137 lex_ctx ctx = parser_ctx(parser);
2139 (void)block; /* not touching */
2141 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2142 if (!parser_next(parser)) {
2143 parseerror(parser, "expected condition or 'not'");
2146 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2148 if (!parser_next(parser)) {
2149 parseerror(parser, "expected condition in parenthesis");
2153 if (parser->tok != '(') {
2154 parseerror(parser, "expected 'if' condition in parenthesis");
2157 /* parse into the expression */
2158 if (!parser_next(parser)) {
2159 parseerror(parser, "expected 'if' condition after opening paren");
2162 /* parse the condition */
2163 cond = parse_expression_leave(parser, false, true, false);
2167 if (parser->tok != ')') {
2168 parseerror(parser, "expected closing paren after 'if' condition");
2172 /* parse into the 'then' branch */
2173 if (!parser_next(parser)) {
2174 parseerror(parser, "expected statement for on-true branch of 'if'");
2178 if (!parse_statement_or_block(parser, &ontrue)) {
2183 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2184 /* check for an else */
2185 if (!strcmp(parser_tokval(parser), "else")) {
2186 /* parse into the 'else' branch */
2187 if (!parser_next(parser)) {
2188 parseerror(parser, "expected on-false branch after 'else'");
2193 if (!parse_statement_or_block(parser, &onfalse)) {
2200 cond = process_condition(parser, cond, &ifnot);
2202 if (ontrue) ast_delete(ontrue);
2203 if (onfalse) ast_delete(onfalse);
2208 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2210 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2211 *out = (ast_expression*)ifthen;
2215 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2216 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2221 /* skip the 'while' and get the body */
2222 if (!parser_next(parser)) {
2223 if (OPTS_FLAG(LOOP_LABELS))
2224 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2226 parseerror(parser, "expected 'while' condition in parenthesis");
2230 if (parser->tok == ':') {
2231 if (!OPTS_FLAG(LOOP_LABELS))
2232 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2233 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2234 parseerror(parser, "expected loop label");
2237 label = util_strdup(parser_tokval(parser));
2238 if (!parser_next(parser)) {
2240 parseerror(parser, "expected 'while' condition in parenthesis");
2245 if (parser->tok != '(') {
2246 parseerror(parser, "expected 'while' condition in parenthesis");
2250 vec_push(parser->breaks, label);
2251 vec_push(parser->continues, label);
2253 rv = parse_while_go(parser, block, out);
2256 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2257 parseerror(parser, "internal error: label stack corrupted");
2263 vec_pop(parser->breaks);
2264 vec_pop(parser->continues);
2269 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2272 ast_expression *cond, *ontrue;
2276 lex_ctx ctx = parser_ctx(parser);
2278 (void)block; /* not touching */
2280 /* parse into the expression */
2281 if (!parser_next(parser)) {
2282 parseerror(parser, "expected 'while' condition after opening paren");
2285 /* parse the condition */
2286 cond = parse_expression_leave(parser, false, true, false);
2290 if (parser->tok != ')') {
2291 parseerror(parser, "expected closing paren after 'while' condition");
2295 /* parse into the 'then' branch */
2296 if (!parser_next(parser)) {
2297 parseerror(parser, "expected while-loop body");
2301 if (!parse_statement_or_block(parser, &ontrue)) {
2306 cond = process_condition(parser, cond, &ifnot);
2311 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2312 *out = (ast_expression*)aloop;
2316 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2317 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2322 /* skip the 'do' and get the body */
2323 if (!parser_next(parser)) {
2324 if (OPTS_FLAG(LOOP_LABELS))
2325 parseerror(parser, "expected loop label or body");
2327 parseerror(parser, "expected loop body");
2331 if (parser->tok == ':') {
2332 if (!OPTS_FLAG(LOOP_LABELS))
2333 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2334 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2335 parseerror(parser, "expected loop label");
2338 label = util_strdup(parser_tokval(parser));
2339 if (!parser_next(parser)) {
2341 parseerror(parser, "expected loop body");
2346 vec_push(parser->breaks, label);
2347 vec_push(parser->continues, label);
2349 rv = parse_dowhile_go(parser, block, out);
2352 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2353 parseerror(parser, "internal error: label stack corrupted");
2359 vec_pop(parser->breaks);
2360 vec_pop(parser->continues);
2365 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2368 ast_expression *cond, *ontrue;
2372 lex_ctx ctx = parser_ctx(parser);
2374 (void)block; /* not touching */
2376 if (!parse_statement_or_block(parser, &ontrue))
2379 /* expect the "while" */
2380 if (parser->tok != TOKEN_KEYWORD ||
2381 strcmp(parser_tokval(parser), "while"))
2383 parseerror(parser, "expected 'while' and condition");
2388 /* skip the 'while' and check for opening paren */
2389 if (!parser_next(parser) || parser->tok != '(') {
2390 parseerror(parser, "expected 'while' condition in parenthesis");
2394 /* parse into the expression */
2395 if (!parser_next(parser)) {
2396 parseerror(parser, "expected 'while' condition after opening paren");
2400 /* parse the condition */
2401 cond = parse_expression_leave(parser, false, true, false);
2405 if (parser->tok != ')') {
2406 parseerror(parser, "expected closing paren after 'while' condition");
2412 if (!parser_next(parser) || parser->tok != ';') {
2413 parseerror(parser, "expected semicolon after condition");
2419 if (!parser_next(parser)) {
2420 parseerror(parser, "parse error");
2426 cond = process_condition(parser, cond, &ifnot);
2431 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2432 *out = (ast_expression*)aloop;
2436 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2437 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2442 /* skip the 'for' and check for opening paren */
2443 if (!parser_next(parser)) {
2444 if (OPTS_FLAG(LOOP_LABELS))
2445 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2447 parseerror(parser, "expected 'for' expressions in parenthesis");
2451 if (parser->tok == ':') {
2452 if (!OPTS_FLAG(LOOP_LABELS))
2453 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2454 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2455 parseerror(parser, "expected loop label");
2458 label = util_strdup(parser_tokval(parser));
2459 if (!parser_next(parser)) {
2461 parseerror(parser, "expected 'for' expressions in parenthesis");
2466 if (parser->tok != '(') {
2467 parseerror(parser, "expected 'for' expressions in parenthesis");
2471 vec_push(parser->breaks, label);
2472 vec_push(parser->continues, label);
2474 rv = parse_for_go(parser, block, out);
2477 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2478 parseerror(parser, "internal error: label stack corrupted");
2484 vec_pop(parser->breaks);
2485 vec_pop(parser->continues);
2489 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2492 ast_expression *initexpr, *cond, *increment, *ontrue;
2498 lex_ctx ctx = parser_ctx(parser);
2500 parser_enterblock(parser);
2507 /* parse into the expression */
2508 if (!parser_next(parser)) {
2509 parseerror(parser, "expected 'for' initializer after opening paren");
2514 if (parser->tok == TOKEN_IDENT)
2515 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2517 if (typevar || parser->tok == TOKEN_TYPENAME) {
2519 if (opts.standard != COMPILER_GMQCC) {
2520 if (parsewarning(parser, WARN_EXTENSIONS,
2521 "current standard does not allow variable declarations in for-loop initializers"))
2525 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2528 else if (parser->tok != ';')
2530 initexpr = parse_expression_leave(parser, false, false, false);
2535 /* move on to condition */
2536 if (parser->tok != ';') {
2537 parseerror(parser, "expected semicolon after for-loop initializer");
2540 if (!parser_next(parser)) {
2541 parseerror(parser, "expected for-loop condition");
2545 /* parse the condition */
2546 if (parser->tok != ';') {
2547 cond = parse_expression_leave(parser, false, true, false);
2552 /* move on to incrementor */
2553 if (parser->tok != ';') {
2554 parseerror(parser, "expected semicolon after for-loop initializer");
2557 if (!parser_next(parser)) {
2558 parseerror(parser, "expected for-loop condition");
2562 /* parse the incrementor */
2563 if (parser->tok != ')') {
2564 increment = parse_expression_leave(parser, false, false, false);
2567 if (!ast_side_effects(increment)) {
2568 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2574 if (parser->tok != ')') {
2575 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2578 /* parse into the 'then' branch */
2579 if (!parser_next(parser)) {
2580 parseerror(parser, "expected for-loop body");
2583 if (!parse_statement_or_block(parser, &ontrue))
2587 cond = process_condition(parser, cond, &ifnot);
2591 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2592 *out = (ast_expression*)aloop;
2594 if (!parser_leaveblock(parser))
2598 if (initexpr) ast_delete(initexpr);
2599 if (cond) ast_delete(cond);
2600 if (increment) ast_delete(increment);
2601 (void)!parser_leaveblock(parser);
2605 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2607 ast_expression *exp = NULL;
2608 ast_return *ret = NULL;
2609 ast_value *expected = parser->function->vtype;
2611 lex_ctx ctx = parser_ctx(parser);
2613 (void)block; /* not touching */
2615 if (!parser_next(parser)) {
2616 parseerror(parser, "expected return expression");
2620 if (parser->tok != ';') {
2621 exp = parse_expression(parser, false, false);
2625 if (exp->expression.vtype != TYPE_NIL &&
2626 exp->expression.vtype != expected->expression.next->expression.vtype)
2628 parseerror(parser, "return with invalid expression");
2631 ret = ast_return_new(ctx, exp);
2637 if (!parser_next(parser))
2638 parseerror(parser, "parse error");
2639 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2640 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2642 ret = ast_return_new(ctx, NULL);
2644 *out = (ast_expression*)ret;
2648 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2651 unsigned int levels = 0;
2652 lex_ctx ctx = parser_ctx(parser);
2653 const char **loops = (is_continue ? parser->continues : parser->breaks);
2655 (void)block; /* not touching */
2656 if (!parser_next(parser)) {
2657 parseerror(parser, "expected semicolon or loop label");
2661 if (!vec_size(loops)) {
2663 parseerror(parser, "`continue` can only be used inside loops");
2665 parseerror(parser, "`break` can only be used inside loops or switches");
2668 if (parser->tok == TOKEN_IDENT) {
2669 if (!OPTS_FLAG(LOOP_LABELS))
2670 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2671 i = vec_size(loops);
2673 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2676 parseerror(parser, "no such loop to %s: `%s`",
2677 (is_continue ? "continue" : "break out of"),
2678 parser_tokval(parser));
2683 if (!parser_next(parser)) {
2684 parseerror(parser, "expected semicolon");
2689 if (parser->tok != ';') {
2690 parseerror(parser, "expected semicolon");
2694 if (!parser_next(parser))
2695 parseerror(parser, "parse error");
2697 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2701 /* returns true when it was a variable qualifier, false otherwise!
2702 * on error, cvq is set to CV_WRONG
2704 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2706 bool had_const = false;
2707 bool had_var = false;
2708 bool had_noref = false;
2709 bool had_attrib = false;
2710 bool had_static = false;
2715 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2717 /* parse an attribute */
2718 if (!parser_next(parser)) {
2719 parseerror(parser, "expected attribute after `[[`");
2723 if (!strcmp(parser_tokval(parser), "noreturn")) {
2724 flags |= AST_FLAG_NORETURN;
2725 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2726 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2731 else if (!strcmp(parser_tokval(parser), "noref")) {
2733 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2734 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2739 else if (!strcmp(parser_tokval(parser), "inline")) {
2740 flags |= AST_FLAG_INLINE;
2741 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2742 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2749 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2750 flags |= AST_FLAG_DEPRECATED;
2753 if (!parser_next(parser)) {
2754 parseerror(parser, "parse error in attribute");
2758 if (parser->tok == '(') {
2759 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2760 parseerror(parser, "`deprecated` attribute missing parameter");
2764 *message = util_strdup(parser_tokval(parser));
2766 if (!parser_next(parser)) {
2767 parseerror(parser, "parse error in attribute");
2771 if(parser->tok != ')') {
2772 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2776 if (!parser_next(parser)) {
2777 parseerror(parser, "parse error in attribute");
2782 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2783 parseerror(parser, "`deprecated` attribute expected `]]`");
2786 if (*message) mem_d(*message);
2794 /* Skip tokens until we hit a ]] */
2795 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2796 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "error inside attribute");
2805 else if (!strcmp(parser_tokval(parser), "static"))
2807 else if (!strcmp(parser_tokval(parser), "const"))
2809 else if (!strcmp(parser_tokval(parser), "var"))
2811 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2813 else if (!strcmp(parser_tokval(parser), "noref"))
2815 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2820 if (!parser_next(parser))
2830 *is_static = had_static;
2834 parseerror(parser, "parse error after variable qualifier");
2839 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2840 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2845 /* skip the 'while' and get the body */
2846 if (!parser_next(parser)) {
2847 if (OPTS_FLAG(LOOP_LABELS))
2848 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2850 parseerror(parser, "expected 'switch' operand in parenthesis");
2854 if (parser->tok == ':') {
2855 if (!OPTS_FLAG(LOOP_LABELS))
2856 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2857 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2858 parseerror(parser, "expected loop label");
2861 label = util_strdup(parser_tokval(parser));
2862 if (!parser_next(parser)) {
2864 parseerror(parser, "expected 'switch' operand in parenthesis");
2869 if (parser->tok != '(') {
2870 parseerror(parser, "expected 'switch' operand in parenthesis");
2874 vec_push(parser->breaks, label);
2876 rv = parse_switch_go(parser, block, out);
2879 if (vec_last(parser->breaks) != label) {
2880 parseerror(parser, "internal error: label stack corrupted");
2886 vec_pop(parser->breaks);
2891 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2893 ast_expression *operand;
2896 ast_switch *switchnode;
2897 ast_switch_case swcase;
2900 bool noref, is_static;
2901 uint32_t qflags = 0;
2903 lex_ctx ctx = parser_ctx(parser);
2905 (void)block; /* not touching */
2908 /* parse into the expression */
2909 if (!parser_next(parser)) {
2910 parseerror(parser, "expected switch operand");
2913 /* parse the operand */
2914 operand = parse_expression_leave(parser, false, false, false);
2918 switchnode = ast_switch_new(ctx, operand);
2921 if (parser->tok != ')') {
2922 ast_delete(switchnode);
2923 parseerror(parser, "expected closing paren after 'switch' operand");
2927 /* parse over the opening paren */
2928 if (!parser_next(parser) || parser->tok != '{') {
2929 ast_delete(switchnode);
2930 parseerror(parser, "expected list of cases");
2934 if (!parser_next(parser)) {
2935 ast_delete(switchnode);
2936 parseerror(parser, "expected 'case' or 'default'");
2940 /* new block; allow some variables to be declared here */
2941 parser_enterblock(parser);
2944 if (parser->tok == TOKEN_IDENT)
2945 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2946 if (typevar || parser->tok == TOKEN_TYPENAME) {
2947 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2948 ast_delete(switchnode);
2953 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2955 if (cvq == CV_WRONG) {
2956 ast_delete(switchnode);
2959 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2960 ast_delete(switchnode);
2969 while (parser->tok != '}') {
2970 ast_block *caseblock;
2972 if (!strcmp(parser_tokval(parser), "case")) {
2973 if (!parser_next(parser)) {
2974 ast_delete(switchnode);
2975 parseerror(parser, "expected expression for case");
2978 swcase.value = parse_expression_leave(parser, false, false, false);
2979 if (!swcase.value) {
2980 ast_delete(switchnode);
2981 parseerror(parser, "expected expression for case");
2984 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2985 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2986 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2992 else if (!strcmp(parser_tokval(parser), "default")) {
2993 swcase.value = NULL;
2994 if (!parser_next(parser)) {
2995 ast_delete(switchnode);
2996 parseerror(parser, "expected colon");
3001 ast_delete(switchnode);
3002 parseerror(parser, "expected 'case' or 'default'");
3006 /* Now the colon and body */
3007 if (parser->tok != ':') {
3008 if (swcase.value) ast_unref(swcase.value);
3009 ast_delete(switchnode);
3010 parseerror(parser, "expected colon");
3014 if (!parser_next(parser)) {
3015 if (swcase.value) ast_unref(swcase.value);
3016 ast_delete(switchnode);
3017 parseerror(parser, "expected statements or case");
3020 caseblock = ast_block_new(parser_ctx(parser));
3022 if (swcase.value) ast_unref(swcase.value);
3023 ast_delete(switchnode);
3026 swcase.code = (ast_expression*)caseblock;
3027 vec_push(switchnode->cases, swcase);
3029 ast_expression *expr;
3030 if (parser->tok == '}')
3032 if (parser->tok == TOKEN_KEYWORD) {
3033 if (!strcmp(parser_tokval(parser), "case") ||
3034 !strcmp(parser_tokval(parser), "default"))
3039 if (!parse_statement(parser, caseblock, &expr, true)) {
3040 ast_delete(switchnode);
3045 if (!ast_block_add_expr(caseblock, expr)) {
3046 ast_delete(switchnode);
3052 parser_leaveblock(parser);
3055 if (parser->tok != '}') {
3056 ast_delete(switchnode);
3057 parseerror(parser, "expected closing paren of case list");
3060 if (!parser_next(parser)) {
3061 ast_delete(switchnode);
3062 parseerror(parser, "parse error after switch");
3065 *out = (ast_expression*)switchnode;
3069 /* parse computed goto sides */
3070 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3071 ast_expression *on_true;
3072 ast_expression *on_false;
3073 ast_expression *cond;
3078 if (ast_istype(*side, ast_ternary)) {
3079 ast_ternary *tern = (ast_ternary*)*side;
3080 on_true = parse_goto_computed(parser, &tern->on_true);
3081 on_false = parse_goto_computed(parser, &tern->on_false);
3083 if (!on_true || !on_false) {
3084 parseerror(parser, "expected label or expression in ternary");
3085 if (on_true) ast_unref(on_true);
3086 if (on_false) ast_unref(on_false);
3094 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3095 } else if (ast_istype(*side, ast_label)) {
3096 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3097 ast_goto_set_label(gt, ((ast_label*)*side));
3099 return (ast_expression*)gt;
3104 static bool parse_goto(parser_t *parser, ast_expression **out)
3106 ast_goto *gt = NULL;
3107 ast_expression *lbl;
3109 if (!parser_next(parser))
3112 if (parser->tok != TOKEN_IDENT) {
3113 ast_expression *expression;
3115 /* could be an expression i.e computed goto :-) */
3116 if (parser->tok != '(') {
3117 parseerror(parser, "expected label name after `goto`");
3121 /* failed to parse expression for goto */
3122 if (!(expression = parse_expression(parser, false, true)) ||
3123 !(*out = parse_goto_computed(parser, &expression))) {
3124 parseerror(parser, "invalid goto expression");
3125 ast_unref(expression);
3132 /* not computed goto */
3133 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3134 lbl = parser_find_label(parser, gt->name);
3136 if (!ast_istype(lbl, ast_label)) {
3137 parseerror(parser, "internal error: label is not an ast_label");
3141 ast_goto_set_label(gt, (ast_label*)lbl);
3144 vec_push(parser->gotos, gt);
3146 if (!parser_next(parser) || parser->tok != ';') {
3147 parseerror(parser, "semicolon expected after goto label");
3150 if (!parser_next(parser)) {
3151 parseerror(parser, "parse error after goto");
3155 *out = (ast_expression*)gt;
3159 static bool parse_skipwhite(parser_t *parser)
3162 if (!parser_next(parser))
3164 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3165 return parser->tok < TOKEN_ERROR;
3168 static bool parse_eol(parser_t *parser)
3170 if (!parse_skipwhite(parser))
3172 return parser->tok == TOKEN_EOL;
3175 static bool parse_pragma_do(parser_t *parser)
3177 if (!parser_next(parser) ||
3178 parser->tok != TOKEN_IDENT ||
3179 strcmp(parser_tokval(parser), "pragma"))
3181 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3184 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3185 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3189 if (!strcmp(parser_tokval(parser), "noref")) {
3190 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3191 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3194 parser->noref = !!parser_token(parser)->constval.i;
3195 if (!parse_eol(parser)) {
3196 parseerror(parser, "parse error after `noref` pragma");
3202 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3209 static bool parse_pragma(parser_t *parser)
3212 parser->lex->flags.preprocessing = true;
3213 parser->lex->flags.mergelines = true;
3214 rv = parse_pragma_do(parser);
3215 if (parser->tok != TOKEN_EOL) {
3216 parseerror(parser, "junk after pragma");
3219 parser->lex->flags.preprocessing = false;
3220 parser->lex->flags.mergelines = false;
3221 if (!parser_next(parser)) {
3222 parseerror(parser, "parse error after pragma");
3228 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3230 bool noref, is_static;
3232 uint32_t qflags = 0;
3233 ast_value *typevar = NULL;
3234 char *vstring = NULL;
3238 if (parser->tok == TOKEN_IDENT)
3239 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3241 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3243 /* local variable */
3245 parseerror(parser, "cannot declare a variable from here");
3248 if (opts.standard == COMPILER_QCC) {
3249 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3252 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3256 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3258 if (cvq == CV_WRONG)
3260 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3262 else if (parser->tok == TOKEN_KEYWORD)
3264 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3269 if (!parser_next(parser)) {
3270 parseerror(parser, "parse error after __builtin_debug_printtype");
3274 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3276 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3277 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3278 if (!parser_next(parser)) {
3279 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3285 if (!parse_statement(parser, block, out, allow_cases))
3288 con_out("__builtin_debug_printtype: got no output node\n");
3291 ast_type_to_string(*out, ty, sizeof(ty));
3292 con_out("__builtin_debug_printtype: `%s`\n", ty);
3297 else if (!strcmp(parser_tokval(parser), "return"))
3299 return parse_return(parser, block, out);
3301 else if (!strcmp(parser_tokval(parser), "if"))
3303 return parse_if(parser, block, out);
3305 else if (!strcmp(parser_tokval(parser), "while"))
3307 return parse_while(parser, block, out);
3309 else if (!strcmp(parser_tokval(parser), "do"))
3311 return parse_dowhile(parser, block, out);
3313 else if (!strcmp(parser_tokval(parser), "for"))
3315 if (opts.standard == COMPILER_QCC) {
3316 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3319 return parse_for(parser, block, out);
3321 else if (!strcmp(parser_tokval(parser), "break"))
3323 return parse_break_continue(parser, block, out, false);
3325 else if (!strcmp(parser_tokval(parser), "continue"))
3327 return parse_break_continue(parser, block, out, true);
3329 else if (!strcmp(parser_tokval(parser), "switch"))
3331 return parse_switch(parser, block, out);
3333 else if (!strcmp(parser_tokval(parser), "case") ||
3334 !strcmp(parser_tokval(parser), "default"))
3337 parseerror(parser, "unexpected 'case' label");
3342 else if (!strcmp(parser_tokval(parser), "goto"))
3344 return parse_goto(parser, out);
3346 else if (!strcmp(parser_tokval(parser), "typedef"))
3348 if (!parser_next(parser)) {
3349 parseerror(parser, "expected type definition after 'typedef'");
3352 return parse_typedef(parser);
3354 parseerror(parser, "Unexpected keyword");
3357 else if (parser->tok == '{')
3360 inner = parse_block(parser);
3363 *out = (ast_expression*)inner;
3366 else if (parser->tok == ':')
3370 if (!parser_next(parser)) {
3371 parseerror(parser, "expected label name");
3374 if (parser->tok != TOKEN_IDENT) {
3375 parseerror(parser, "label must be an identifier");
3378 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3380 if (!label->undefined) {
3381 parseerror(parser, "label `%s` already defined", label->name);
3384 label->undefined = false;
3387 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3388 vec_push(parser->labels, label);
3390 *out = (ast_expression*)label;
3391 if (!parser_next(parser)) {
3392 parseerror(parser, "parse error after label");
3395 for (i = 0; i < vec_size(parser->gotos); ++i) {
3396 if (!strcmp(parser->gotos[i]->name, label->name)) {
3397 ast_goto_set_label(parser->gotos[i], label);
3398 vec_remove(parser->gotos, i, 1);
3404 else if (parser->tok == ';')
3406 if (!parser_next(parser)) {
3407 parseerror(parser, "parse error after empty statement");
3414 ast_expression *exp = parse_expression(parser, false, false);
3418 if (!ast_side_effects(exp)) {
3419 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3426 static bool parse_enum(parser_t *parser)
3429 ast_value **values = NULL;
3430 ast_value *var = NULL;
3433 ast_expression *old;
3435 if (!parser_next(parser) || parser->tok != '{') {
3436 parseerror(parser, "expected `{` after `enum` keyword");
3441 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3442 if (parser->tok == '}') {
3443 /* allow an empty enum */
3446 parseerror(parser, "expected identifier or `}`");
3450 old = parser_find_field(parser, parser_tokval(parser));
3452 old = parser_find_global(parser, parser_tokval(parser));
3454 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3455 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3459 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3460 vec_push(values, var);
3461 var->cvq = CV_CONST;
3462 var->hasvalue = true;
3463 var->constval.vfloat = num++;
3465 parser_addglobal(parser, var->name, (ast_expression*)var);
3467 if (!parser_next(parser)) {
3468 parseerror(parser, "expected `=`, `}` or comma after identifier");
3472 if (parser->tok == ',')
3474 if (parser->tok == '}')
3476 if (parser->tok != '=') {
3477 parseerror(parser, "expected `=`, `}` or comma after identifier");
3481 if (!parser_next(parser)) {
3482 parseerror(parser, "expected expression after `=`");
3486 /* We got a value! */
3487 old = parse_expression_leave(parser, true, false, false);
3488 asvalue = (ast_value*)old;
3489 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3490 parseerror(parser, "enumeration value for must be a constant");
3493 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3495 if (parser->tok == '}')
3497 if (parser->tok != ',') {
3498 parseerror(parser, "expected `}` or comma after expression");
3503 if (parser->tok != '}') {
3504 parseerror(parser, "internal error: breaking without `}`");
3508 if (!parser_next(parser) || parser->tok != ';') {
3509 parseerror(parser, "expected semicolon after enumeration");
3513 if (!parser_next(parser)) {
3514 parseerror(parser, "parse error after enumeration");
3526 static bool parse_block_into(parser_t *parser, ast_block *block)
3530 parser_enterblock(parser);
3532 if (!parser_next(parser)) { /* skip the '{' */
3533 parseerror(parser, "expected function body");
3537 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3539 ast_expression *expr = NULL;
3540 if (parser->tok == '}')
3543 if (!parse_statement(parser, block, &expr, false)) {
3544 /* parseerror(parser, "parse error"); */
3550 if (!ast_block_add_expr(block, expr)) {
3557 if (parser->tok != '}') {
3560 (void)parser_next(parser);
3564 if (!parser_leaveblock(parser))
3566 return retval && !!block;
3569 static ast_block* parse_block(parser_t *parser)
3572 block = ast_block_new(parser_ctx(parser));
3575 if (!parse_block_into(parser, block)) {
3576 ast_block_delete(block);
3582 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3584 if (parser->tok == '{') {
3585 *out = (ast_expression*)parse_block(parser);
3588 return parse_statement(parser, NULL, out, false);
3591 static bool create_vector_members(ast_value *var, ast_member **me)
3594 size_t len = strlen(var->name);
3596 for (i = 0; i < 3; ++i) {
3597 char *name = (char*)mem_a(len+3);
3598 memcpy(name, var->name, len);
3600 name[len+1] = 'x'+i;
3602 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3611 do { ast_member_delete(me[--i]); } while(i);
3615 static bool parse_function_body(parser_t *parser, ast_value *var)
3617 ast_block *block = NULL;
3622 ast_expression *framenum = NULL;
3623 ast_expression *nextthink = NULL;
3624 /* None of the following have to be deleted */
3625 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3626 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3627 bool has_frame_think;
3631 has_frame_think = false;
3632 old = parser->function;
3634 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3635 parseerror(parser, "gotos/labels leaking");
3639 if (var->expression.flags & AST_FLAG_VARIADIC) {
3640 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3641 "variadic function with implementation will not be able to access additional parameters"))
3647 if (parser->tok == '[') {
3648 /* got a frame definition: [ framenum, nextthink ]
3649 * this translates to:
3650 * self.frame = framenum;
3651 * self.nextthink = time + 0.1;
3652 * self.think = nextthink;
3656 fld_think = parser_find_field(parser, "think");
3657 fld_nextthink = parser_find_field(parser, "nextthink");
3658 fld_frame = parser_find_field(parser, "frame");
3659 if (!fld_think || !fld_nextthink || !fld_frame) {
3660 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3661 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3664 gbl_time = parser_find_global(parser, "time");
3665 gbl_self = parser_find_global(parser, "self");
3666 if (!gbl_time || !gbl_self) {
3667 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3668 parseerror(parser, "please declare the following globals: `time`, `self`");
3672 if (!parser_next(parser))
3675 framenum = parse_expression_leave(parser, true, false, false);
3677 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3680 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3681 ast_unref(framenum);
3682 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3686 if (parser->tok != ',') {
3687 ast_unref(framenum);
3688 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3689 parseerror(parser, "Got a %i\n", parser->tok);
3693 if (!parser_next(parser)) {
3694 ast_unref(framenum);
3698 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3700 /* qc allows the use of not-yet-declared functions here
3701 * - this automatically creates a prototype */
3702 ast_value *thinkfunc;
3703 ast_expression *functype = fld_think->expression.next;
3705 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3706 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3707 ast_unref(framenum);
3708 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3712 if (!parser_next(parser)) {
3713 ast_unref(framenum);
3714 ast_delete(thinkfunc);
3718 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3720 nextthink = (ast_expression*)thinkfunc;
3723 nextthink = parse_expression_leave(parser, true, false, false);
3725 ast_unref(framenum);
3726 parseerror(parser, "expected a think-function in [frame,think] notation");
3731 if (!ast_istype(nextthink, ast_value)) {
3732 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3736 if (retval && parser->tok != ']') {
3737 parseerror(parser, "expected closing `]` for [frame,think] notation");
3741 if (retval && !parser_next(parser)) {
3745 if (retval && parser->tok != '{') {
3746 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3751 ast_unref(nextthink);
3752 ast_unref(framenum);
3756 has_frame_think = true;
3759 block = ast_block_new(parser_ctx(parser));
3761 parseerror(parser, "failed to allocate block");
3762 if (has_frame_think) {
3763 ast_unref(nextthink);
3764 ast_unref(framenum);
3769 if (has_frame_think) {
3771 ast_expression *self_frame;
3772 ast_expression *self_nextthink;
3773 ast_expression *self_think;
3774 ast_expression *time_plus_1;
3775 ast_store *store_frame;
3776 ast_store *store_nextthink;
3777 ast_store *store_think;
3779 ctx = parser_ctx(parser);
3780 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3781 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3782 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3784 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3785 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3787 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3788 if (self_frame) ast_delete(self_frame);
3789 if (self_nextthink) ast_delete(self_nextthink);
3790 if (self_think) ast_delete(self_think);
3791 if (time_plus_1) ast_delete(time_plus_1);
3797 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3798 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3799 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3802 ast_delete(self_frame);
3805 if (!store_nextthink) {
3806 ast_delete(self_nextthink);
3810 ast_delete(self_think);
3814 if (store_frame) ast_delete(store_frame);
3815 if (store_nextthink) ast_delete(store_nextthink);
3816 if (store_think) ast_delete(store_think);
3819 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3820 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3821 !ast_block_add_expr(block, (ast_expression*)store_think))
3828 parseerror(parser, "failed to generate code for [frame,think]");
3829 ast_unref(nextthink);
3830 ast_unref(framenum);
3836 parser_enterblock(parser);
3838 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3840 ast_value *param = var->expression.params[parami];
3843 if (param->expression.vtype != TYPE_VECTOR &&
3844 (param->expression.vtype != TYPE_FIELD ||
3845 param->expression.next->expression.vtype != TYPE_VECTOR))
3850 if (!create_vector_members(param, me)) {
3851 ast_block_delete(block);
3855 for (e = 0; e < 3; ++e) {
3856 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3857 ast_block_collect(block, (ast_expression*)me[e]);
3861 func = ast_function_new(ast_ctx(var), var->name, var);
3863 parseerror(parser, "failed to allocate function for `%s`", var->name);
3864 ast_block_delete(block);
3867 vec_push(parser->functions, func);
3869 parser->function = func;
3870 if (!parse_block_into(parser, block)) {
3871 ast_block_delete(block);
3875 vec_push(func->blocks, block);
3877 parser->function = old;
3878 if (!parser_leaveblock(parser))
3880 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3881 parseerror(parser, "internal error: local scopes left");
3885 if (parser->tok == ';')
3886 return parser_next(parser);
3887 else if (opts.standard == COMPILER_QCC)
3888 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3892 vec_pop(parser->functions);
3893 ast_function_delete(func);
3894 var->constval.vfunc = NULL;
3897 (void)!parser_leaveblock(parser);
3898 parser->function = old;
3902 static ast_expression *array_accessor_split(
3907 ast_expression *left,
3908 ast_expression *right
3914 lex_ctx ctx = ast_ctx(array);
3916 if (!left || !right) {
3917 if (left) ast_delete(left);
3918 if (right) ast_delete(right);
3922 cmp = ast_binary_new(ctx, INSTR_LT,
3923 (ast_expression*)index,
3924 (ast_expression*)parser_const_float(parser, middle));
3928 parseerror(parser, "internal error: failed to create comparison for array setter");
3932 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3934 ast_delete(cmp); /* will delete left and right */
3935 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3939 return (ast_expression*)ifthen;
3942 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3944 lex_ctx ctx = ast_ctx(array);
3946 if (from+1 == afterend) {
3947 /* set this value */
3950 ast_array_index *subscript;
3952 int assignop = type_store_instr[value->expression.vtype];
3954 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3955 assignop = INSTR_STORE_V;
3957 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3961 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3963 ast_delete(subscript);
3967 block = ast_block_new(ctx);
3973 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3978 ret = ast_return_new(ctx, NULL);
3984 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3989 return (ast_expression*)block;
3991 ast_expression *left, *right;
3992 size_t diff = afterend - from;
3993 size_t middle = from + diff/2;
3994 left = array_setter_node(parser, array, index, value, from, middle);
3995 right = array_setter_node(parser, array, index, value, middle, afterend);
3996 return array_accessor_split(parser, array, index, middle, left, right);
4000 static ast_expression *array_field_setter_node(
4009 lex_ctx ctx = ast_ctx(array);
4011 if (from+1 == afterend) {
4012 /* set this value */
4015 ast_entfield *entfield;
4016 ast_array_index *subscript;
4018 int assignop = type_storep_instr[value->expression.vtype];
4020 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4021 assignop = INSTR_STOREP_V;
4023 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4027 entfield = ast_entfield_new_force(ctx,
4028 (ast_expression*)entity,
4029 (ast_expression*)subscript,
4030 (ast_expression*)subscript);
4032 ast_delete(subscript);
4036 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4038 ast_delete(entfield);
4042 block = ast_block_new(ctx);
4048 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4053 ret = ast_return_new(ctx, NULL);
4059 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4064 return (ast_expression*)block;
4066 ast_expression *left, *right;
4067 size_t diff = afterend - from;
4068 size_t middle = from + diff/2;
4069 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4070 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4071 return array_accessor_split(parser, array, index, middle, left, right);
4075 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4077 lex_ctx ctx = ast_ctx(array);
4079 if (from+1 == afterend) {
4081 ast_array_index *subscript;
4083 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4087 ret = ast_return_new(ctx, (ast_expression*)subscript);
4089 ast_delete(subscript);
4093 return (ast_expression*)ret;
4095 ast_expression *left, *right;
4096 size_t diff = afterend - from;
4097 size_t middle = from + diff/2;
4098 left = array_getter_node(parser, array, index, from, middle);
4099 right = array_getter_node(parser, array, index, middle, afterend);
4100 return array_accessor_split(parser, array, index, middle, left, right);
4104 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4106 ast_function *func = NULL;
4107 ast_value *fval = NULL;
4108 ast_block *body = NULL;
4110 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4112 parseerror(parser, "failed to create accessor function value");
4116 func = ast_function_new(ast_ctx(array), funcname, fval);
4119 parseerror(parser, "failed to create accessor function node");
4123 body = ast_block_new(ast_ctx(array));
4125 parseerror(parser, "failed to create block for array accessor");
4131 vec_push(func->blocks, body);
4134 vec_push(parser->accessors, fval);
4139 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4141 ast_expression *root = NULL;
4142 ast_value *index = NULL;
4143 ast_value *value = NULL;
4147 if (!ast_istype(array->expression.next, ast_value)) {
4148 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4152 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4154 func = fval->constval.vfunc;
4155 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4157 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4158 value = ast_value_copy((ast_value*)array->expression.next);
4160 if (!index || !value) {
4161 parseerror(parser, "failed to create locals for array accessor");
4164 (void)!ast_value_set_name(value, "value"); /* not important */
4165 vec_push(fval->expression.params, index);
4166 vec_push(fval->expression.params, value);
4168 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4170 parseerror(parser, "failed to build accessor search tree");
4174 array->setter = fval;
4175 return ast_block_add_expr(func->blocks[0], root);
4177 if (index) ast_delete(index);
4178 if (value) ast_delete(value);
4179 if (root) ast_delete(root);
4185 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4187 ast_expression *root = NULL;
4188 ast_value *entity = NULL;
4189 ast_value *index = NULL;
4190 ast_value *value = NULL;
4194 if (!ast_istype(array->expression.next, ast_value)) {
4195 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4199 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4201 func = fval->constval.vfunc;
4202 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4204 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4205 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4206 value = ast_value_copy((ast_value*)array->expression.next);
4207 if (!entity || !index || !value) {
4208 parseerror(parser, "failed to create locals for array accessor");
4211 (void)!ast_value_set_name(value, "value"); /* not important */
4212 vec_push(fval->expression.params, entity);
4213 vec_push(fval->expression.params, index);
4214 vec_push(fval->expression.params, value);
4216 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4218 parseerror(parser, "failed to build accessor search tree");
4222 array->setter = fval;
4223 return ast_block_add_expr(func->blocks[0], root);
4225 if (entity) ast_delete(entity);
4226 if (index) ast_delete(index);
4227 if (value) ast_delete(value);
4228 if (root) ast_delete(root);
4234 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4236 ast_expression *root = NULL;
4237 ast_value *index = NULL;
4241 /* NOTE: checking array->expression.next rather than elemtype since
4242 * for fields elemtype is a temporary fieldtype.
4244 if (!ast_istype(array->expression.next, ast_value)) {
4245 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4249 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4251 func = fval->constval.vfunc;
4252 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4254 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4257 parseerror(parser, "failed to create locals for array accessor");
4260 vec_push(fval->expression.params, index);
4262 root = array_getter_node(parser, array, index, 0, array->expression.count);
4264 parseerror(parser, "failed to build accessor search tree");
4268 array->getter = fval;
4269 return ast_block_add_expr(func->blocks[0], root);
4271 if (index) ast_delete(index);
4272 if (root) ast_delete(root);
4278 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4279 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4287 bool variadic = false;
4289 ctx = parser_ctx(parser);
4291 /* for the sake of less code we parse-in in this function */
4292 if (!parser_next(parser)) {
4293 parseerror(parser, "expected parameter list");
4299 /* parse variables until we hit a closing paren */
4300 while (parser->tok != ')') {
4302 /* there must be commas between them */
4303 if (parser->tok != ',') {
4304 parseerror(parser, "expected comma or end of parameter list");
4307 if (!parser_next(parser)) {
4308 parseerror(parser, "expected parameter");
4314 if (parser->tok == TOKEN_DOTS) {
4315 /* '...' indicates a varargs function */
4317 if (!parser_next(parser)) {
4318 parseerror(parser, "expected parameter");
4321 if (parser->tok != ')') {
4322 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4328 /* for anything else just parse a typename */
4329 param = parse_typename(parser, NULL, NULL);
4332 vec_push(params, param);
4333 if (param->expression.vtype >= TYPE_VARIANT) {
4334 char tname[1024]; /* typename is reserved in C++ */
4335 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4336 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4342 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4346 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4347 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4350 if (!parser_next(parser)) {
4351 parseerror(parser, "parse error after typename");
4355 /* now turn 'var' into a function type */
4356 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4357 fval->expression.next = (ast_expression*)var;
4359 fval->expression.flags |= AST_FLAG_VARIADIC;
4362 var->expression.params = params;
4369 for (i = 0; i < vec_size(params); ++i)
4370 ast_delete(params[i]);
4375 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4377 ast_expression *cexp;
4378 ast_value *cval, *tmp;
4381 ctx = parser_ctx(parser);
4383 if (!parser_next(parser)) {
4385 parseerror(parser, "expected array-size");
4389 cexp = parse_expression_leave(parser, true, false, false);
4391 if (!cexp || !ast_istype(cexp, ast_value)) {
4395 parseerror(parser, "expected array-size as constant positive integer");
4398 cval = (ast_value*)cexp;
4400 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4401 tmp->expression.next = (ast_expression*)var;
4404 if (cval->expression.vtype == TYPE_INTEGER)
4405 tmp->expression.count = cval->constval.vint;
4406 else if (cval->expression.vtype == TYPE_FLOAT)
4407 tmp->expression.count = cval->constval.vfloat;
4411 parseerror(parser, "array-size must be a positive integer constant");
4416 if (parser->tok != ']') {
4418 parseerror(parser, "expected ']' after array-size");
4421 if (!parser_next(parser)) {
4423 parseerror(parser, "error after parsing array size");
4429 /* Parse a complete typename.
4430 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4431 * but when parsing variables separated by comma
4432 * 'storebase' should point to where the base-type should be kept.
4433 * The base type makes up every bit of type information which comes *before* the
4436 * The following will be parsed in its entirety:
4438 * The 'basetype' in this case is 'void()'
4439 * and if there's a comma after it, say:
4441 * then the type-information 'void()' can be stored in 'storebase'
4443 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4445 ast_value *var, *tmp;
4448 const char *name = NULL;
4449 bool isfield = false;
4450 bool wasarray = false;
4451 size_t morefields = 0;
4453 ctx = parser_ctx(parser);
4455 /* types may start with a dot */
4456 if (parser->tok == '.') {
4458 /* if we parsed a dot we need a typename now */
4459 if (!parser_next(parser)) {
4460 parseerror(parser, "expected typename for field definition");
4464 /* Further dots are handled seperately because they won't be part of the
4467 while (parser->tok == '.') {
4469 if (!parser_next(parser)) {
4470 parseerror(parser, "expected typename for field definition");
4475 if (parser->tok == TOKEN_IDENT)
4476 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4477 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4478 parseerror(parser, "expected typename");
4482 /* generate the basic type value */
4483 if (cached_typedef) {
4484 var = ast_value_copy(cached_typedef);
4485 ast_value_set_name(var, "<type(from_def)>");
4487 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4489 for (; morefields; --morefields) {
4490 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4491 tmp->expression.next = (ast_expression*)var;
4495 /* do not yet turn into a field - remember:
4496 * .void() foo; is a field too
4497 * .void()() foo; is a function
4501 if (!parser_next(parser)) {
4503 parseerror(parser, "parse error after typename");
4507 /* an opening paren now starts the parameter-list of a function
4508 * this is where original-QC has parameter lists.
4509 * We allow a single parameter list here.
4510 * Much like fteqcc we don't allow `float()() x`
4512 if (parser->tok == '(') {
4513 var = parse_parameter_list(parser, var);
4518 /* store the base if requested */
4520 *storebase = ast_value_copy(var);
4522 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4523 tmp->expression.next = (ast_expression*)*storebase;
4528 /* there may be a name now */
4529 if (parser->tok == TOKEN_IDENT) {
4530 name = util_strdup(parser_tokval(parser));
4532 if (!parser_next(parser)) {
4534 parseerror(parser, "error after variable or field declaration");
4539 /* now this may be an array */
4540 if (parser->tok == '[') {
4542 var = parse_arraysize(parser, var);
4547 /* This is the point where we can turn it into a field */
4549 /* turn it into a field if desired */
4550 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4551 tmp->expression.next = (ast_expression*)var;
4555 /* now there may be function parens again */
4556 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4557 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4558 if (parser->tok == '(' && wasarray)
4559 parseerror(parser, "arrays as part of a return type is not supported");
4560 while (parser->tok == '(') {
4561 var = parse_parameter_list(parser, var);
4570 /* finally name it */
4572 if (!ast_value_set_name(var, name)) {
4574 parseerror(parser, "internal error: failed to set name");
4577 /* free the name, ast_value_set_name duplicates */
4584 static bool parse_typedef(parser_t *parser)
4586 ast_value *typevar, *oldtype;
4587 ast_expression *old;
4589 typevar = parse_typename(parser, NULL, NULL);
4594 if ( (old = parser_find_var(parser, typevar->name)) ) {
4595 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4596 " -> `%s` has been declared here: %s:%i",
4597 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4598 ast_delete(typevar);
4602 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4603 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4604 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4605 ast_delete(typevar);
4609 vec_push(parser->_typedefs, typevar);
4610 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4612 if (parser->tok != ';') {
4613 parseerror(parser, "expected semicolon after typedef");
4616 if (!parser_next(parser)) {
4617 parseerror(parser, "parse error after typedef");
4624 static const char *cvq_to_str(int cvq) {
4626 case CV_NONE: return "none";
4627 case CV_VAR: return "`var`";
4628 case CV_CONST: return "`const`";
4629 default: return "<INVALID>";
4633 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4636 if (proto->cvq != var->cvq) {
4637 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4638 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4639 parser->tok == '='))
4641 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4642 "`%s` declared with different qualifiers: %s\n"
4643 " -> previous declaration here: %s:%i uses %s",
4644 var->name, cvq_to_str(var->cvq),
4645 ast_ctx(proto).file, ast_ctx(proto).line,
4646 cvq_to_str(proto->cvq));
4649 av = (var ->expression.flags & AST_FLAG_NORETURN);
4650 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4652 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4653 "`%s` declared with different attributes%s\n"
4654 " -> previous declaration here: %s:%i",
4655 var->name, (av ? ": noreturn" : ""),
4656 ast_ctx(proto).file, ast_ctx(proto).line,
4657 (ao ? ": noreturn" : ""));
4662 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)
4666 ast_expression *old;
4670 ast_value *basetype = NULL;
4672 bool isparam = false;
4673 bool isvector = false;
4674 bool cleanvar = true;
4675 bool wasarray = false;
4679 if (!localblock && is_static)
4680 parseerror(parser, "`static` qualifier is not supported in global scope");
4682 /* get the first complete variable */
4683 var = parse_typename(parser, &basetype, cached_typedef);
4686 ast_delete(basetype);
4694 /* Part 0: finish the type */
4695 if (parser->tok == '(') {
4696 if (opts.standard == COMPILER_QCC)
4697 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4698 var = parse_parameter_list(parser, var);
4704 /* we only allow 1-dimensional arrays */
4705 if (parser->tok == '[') {
4707 var = parse_arraysize(parser, var);
4713 if (parser->tok == '(' && wasarray) {
4714 parseerror(parser, "arrays as part of a return type is not supported");
4715 /* we'll still parse the type completely for now */
4717 /* for functions returning functions */
4718 while (parser->tok == '(') {
4719 if (opts.standard == COMPILER_QCC)
4720 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4721 var = parse_parameter_list(parser, var);
4728 var->cvq = qualifier;
4729 var->expression.flags |= qflags;
4730 if (var->expression.flags & AST_FLAG_DEPRECATED)
4731 var->desc = vstring;
4734 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4735 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4736 * is then filled with the previous definition and the parameter-names replaced.
4738 if (!strcmp(var->name, "nil")) {
4739 if (OPTS_FLAG(UNTYPED_NIL)) {
4740 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4741 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4743 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4746 /* Deal with end_sys_ vars */
4748 if (!strcmp(var->name, "end_sys_globals")) {
4750 parser->crc_globals = vec_size(parser->globals);
4753 else if (!strcmp(var->name, "end_sys_fields")) {
4755 parser->crc_fields = vec_size(parser->fields);
4758 if (was_end && var->expression.vtype == TYPE_FIELD) {
4759 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4760 "global '%s' hint should not be a field",
4761 parser_tokval(parser)))
4768 if (!nofields && var->expression.vtype == TYPE_FIELD)
4770 /* deal with field declarations */
4771 old = parser_find_field(parser, var->name);
4773 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4774 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4783 parseerror(parser, "field `%s` already declared here: %s:%i",
4784 var->name, ast_ctx(old).file, ast_ctx(old).line);
4789 if (opts.standard == COMPILER_QCC &&
4790 (old = parser_find_global(parser, var->name)))
4792 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4793 parseerror(parser, "field `%s` already declared here: %s:%i",
4794 var->name, ast_ctx(old).file, ast_ctx(old).line);
4801 /* deal with other globals */
4802 old = parser_find_global(parser, var->name);
4803 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4805 /* This is a function which had a prototype */
4806 if (!ast_istype(old, ast_value)) {
4807 parseerror(parser, "internal error: prototype is not an ast_value");
4811 proto = (ast_value*)old;
4812 proto->desc = var->desc;
4813 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4814 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4816 ast_ctx(proto).file, ast_ctx(proto).line);
4820 /* we need the new parameter-names */
4821 for (i = 0; i < vec_size(proto->expression.params); ++i)
4822 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4823 if (!parser_check_qualifiers(parser, var, proto)) {
4830 proto->expression.flags |= var->expression.flags;
4838 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4839 "global `%s` already declared here: %s:%i",
4840 var->name, ast_ctx(old).file, ast_ctx(old).line))
4845 proto = (ast_value*)old;
4846 if (!ast_istype(old, ast_value)) {
4847 parseerror(parser, "internal error: not an ast_value");
4852 if (!parser_check_qualifiers(parser, var, proto)) {
4857 proto->expression.flags |= var->expression.flags;
4861 if (opts.standard == COMPILER_QCC &&
4862 (old = parser_find_field(parser, var->name)))
4864 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4865 parseerror(parser, "global `%s` already declared here: %s:%i",
4866 var->name, ast_ctx(old).file, ast_ctx(old).line);
4873 else /* it's not a global */
4875 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4876 if (old && !isparam) {
4877 parseerror(parser, "local `%s` already declared here: %s:%i",
4878 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4882 old = parser_find_local(parser, var->name, 0, &isparam);
4883 if (old && isparam) {
4884 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4885 "local `%s` is shadowing a parameter", var->name))
4887 parseerror(parser, "local `%s` already declared here: %s:%i",
4888 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4892 if (opts.standard != COMPILER_GMQCC) {
4900 /* in a noref section we simply bump the usecount */
4901 if (noref || parser->noref)
4905 * Create the global/local, and deal with vector types.
4908 if (var->expression.vtype == TYPE_VECTOR)
4910 else if (var->expression.vtype == TYPE_FIELD &&
4911 var->expression.next->expression.vtype == TYPE_VECTOR)
4915 if (!create_vector_members(var, me)) {
4922 /* deal with global variables, fields, functions */
4923 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4924 var->isfield = true;
4925 vec_push(parser->fields, (ast_expression*)var);
4926 util_htset(parser->htfields, var->name, var);
4928 for (i = 0; i < 3; ++i) {
4929 vec_push(parser->fields, (ast_expression*)me[i]);
4930 util_htset(parser->htfields, me[i]->name, me[i]);
4935 parser_addglobal(parser, var->name, (ast_expression*)var);
4937 for (i = 0; i < 3; ++i) {
4938 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
4944 /* a static adds itself to be generated like any other global
4945 * but is added to the local namespace instead
4947 char *defname = NULL;
4948 size_t prefix_len, ln;
4950 ln = strlen(parser->function->name);
4951 vec_append(defname, ln, parser->function->name);
4953 vec_append(defname, 2, "::");
4954 /* remember the length up to here */
4955 prefix_len = vec_size(defname);
4957 /* Add it to the local scope */
4958 util_htset(vec_last(parser->variables), var->name, (void*)var);
4962 vec_last(parser->correct_variables),
4963 &vec_last(parser->correct_variables_score),
4967 /* now rename the global */
4968 ln = strlen(var->name);
4969 vec_append(defname, ln, var->name);
4970 ast_value_set_name(var, defname);
4972 /* push it to the to-be-generated globals */
4973 vec_push(parser->globals, (ast_expression*)var);
4975 /* same game for the vector members */
4977 for (i = 0; i < 3; ++i) {
4978 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4982 vec_last(parser->correct_variables),
4983 &vec_last(parser->correct_variables_score),
4987 vec_shrinkto(defname, prefix_len);
4988 ln = strlen(me[i]->name);
4989 vec_append(defname, ln, me[i]->name);
4990 ast_member_set_name(me[i], defname);
4992 vec_push(parser->globals, (ast_expression*)me[i]);
4997 vec_push(localblock->locals, var);
4998 parser_addlocal(parser, var->name, (ast_expression*)var);
5000 for (i = 0; i < 3; ++i) {
5001 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5002 ast_block_collect(localblock, (ast_expression*)me[i]);
5008 me[0] = me[1] = me[2] = NULL;
5013 if (var->expression.vtype == TYPE_ARRAY) {
5015 snprintf(name, sizeof(name), "%s##SET", var->name);
5016 if (!parser_create_array_setter(parser, var, name))
5018 snprintf(name, sizeof(name), "%s##GET", var->name);
5019 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5022 else if (!localblock && !nofields &&
5023 var->expression.vtype == TYPE_FIELD &&
5024 var->expression.next->expression.vtype == TYPE_ARRAY)
5027 ast_expression *telem;
5029 ast_value *array = (ast_value*)var->expression.next;
5031 if (!ast_istype(var->expression.next, ast_value)) {
5032 parseerror(parser, "internal error: field element type must be an ast_value");
5036 snprintf(name, sizeof(name), "%s##SETF", var->name);
5037 if (!parser_create_array_field_setter(parser, array, name))
5040 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5041 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5042 tfield->expression.next = telem;
5043 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5044 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5052 if (parser->tok == ';') {
5053 ast_delete(basetype);
5054 if (!parser_next(parser)) {
5055 parseerror(parser, "error after variable declaration");
5061 if (parser->tok == ',')
5065 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5068 parseerror(parser, "missing comma or semicolon while parsing variables");
5072 if (localblock && opts.standard == COMPILER_QCC) {
5073 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5074 "initializing expression turns variable `%s` into a constant in this standard",
5081 if (parser->tok != '{') {
5082 if (parser->tok != '=') {
5083 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5087 if (!parser_next(parser)) {
5088 parseerror(parser, "error parsing initializer");
5092 else if (opts.standard == COMPILER_QCC) {
5093 parseerror(parser, "expected '=' before function body in this standard");
5096 if (parser->tok == '#') {
5097 ast_function *func = NULL;
5100 parseerror(parser, "cannot declare builtins within functions");
5103 if (var->expression.vtype != TYPE_FUNCTION) {
5104 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5107 if (!parser_next(parser)) {
5108 parseerror(parser, "expected builtin number");
5111 if (parser->tok != TOKEN_INTCONST) {
5112 parseerror(parser, "builtin number must be an integer constant");
5115 if (parser_token(parser)->constval.i < 0) {
5116 parseerror(parser, "builtin number must be an integer greater than zero");
5120 if (var->hasvalue) {
5121 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5122 "builtin `%s` has already been defined\n"
5123 " -> previous declaration here: %s:%i",
5124 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5128 func = ast_function_new(ast_ctx(var), var->name, var);
5130 parseerror(parser, "failed to allocate function for `%s`", var->name);
5133 vec_push(parser->functions, func);
5135 func->builtin = -parser_token(parser)->constval.i-1;
5138 if (!parser_next(parser)) {
5139 parseerror(parser, "expected comma or semicolon");
5141 ast_function_delete(func);
5142 var->constval.vfunc = NULL;
5146 else if (parser->tok == '{' || parser->tok == '[')
5149 parseerror(parser, "cannot declare functions within functions");
5154 ast_ctx(proto) = parser_ctx(parser);
5156 if (!parse_function_body(parser, var))
5158 ast_delete(basetype);
5159 for (i = 0; i < vec_size(parser->gotos); ++i)
5160 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5161 vec_free(parser->gotos);
5162 vec_free(parser->labels);
5165 ast_expression *cexp;
5168 cexp = parse_expression_leave(parser, true, false, false);
5173 cval = (ast_value*)cexp;
5174 if (cval != parser->nil &&
5175 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5178 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5182 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5183 qualifier != CV_VAR)
5185 var->cvq = CV_CONST;
5187 if (cval == parser->nil)
5188 var->expression.flags |= AST_FLAG_INITIALIZED;
5191 var->hasvalue = true;
5192 if (cval->expression.vtype == TYPE_STRING)
5193 var->constval.vstring = parser_strdup(cval->constval.vstring);
5194 else if (cval->expression.vtype == TYPE_FIELD)
5195 var->constval.vfield = cval;
5197 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5203 shunt sy = { NULL, NULL };
5206 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5207 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5208 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5209 if (!parser_sy_apply_operator(parser, &sy))
5212 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5213 parseerror(parser, "internal error: leaked operands");
5214 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5224 if (parser->tok == ',') {
5225 if (!parser_next(parser)) {
5226 parseerror(parser, "expected another variable");
5230 if (parser->tok != TOKEN_IDENT) {
5231 parseerror(parser, "expected another variable");
5234 var = ast_value_copy(basetype);
5236 ast_value_set_name(var, parser_tokval(parser));
5237 if (!parser_next(parser)) {
5238 parseerror(parser, "error parsing variable declaration");
5244 if (parser->tok != ';') {
5245 parseerror(parser, "missing semicolon after variables");
5249 if (!parser_next(parser)) {
5250 parseerror(parser, "parse error after variable declaration");
5254 ast_delete(basetype);
5258 if (cleanvar && var)
5260 ast_delete(basetype);
5264 ast_delete(basetype);
5265 if (cleanvar && var)
5267 if (me[0]) ast_member_delete(me[0]);
5268 if (me[1]) ast_member_delete(me[1]);
5269 if (me[2]) ast_member_delete(me[2]);
5273 static bool parser_global_statement(parser_t *parser)
5277 bool is_static = false;
5278 uint32_t qflags = 0;
5279 ast_value *istype = NULL;
5280 char *vstring = NULL;
5282 if (parser->tok == TOKEN_IDENT)
5283 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5285 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5287 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5289 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5291 if (cvq == CV_WRONG)
5293 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5295 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5297 return parse_enum(parser);
5299 else if (parser->tok == TOKEN_KEYWORD)
5301 if (!strcmp(parser_tokval(parser), "typedef")) {
5302 if (!parser_next(parser)) {
5303 parseerror(parser, "expected type definition after 'typedef'");
5306 return parse_typedef(parser);
5308 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5311 else if (parser->tok == '#')
5313 return parse_pragma(parser);
5315 else if (parser->tok == '$')
5317 if (!parser_next(parser)) {
5318 parseerror(parser, "parse error");
5324 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5330 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5332 return util_crc16(old, str, strlen(str));
5335 static void progdefs_crc_file(const char *str)
5337 /* write to progdefs.h here */
5341 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5343 old = progdefs_crc_sum(old, str);
5344 progdefs_crc_file(str);
5348 static void generate_checksum(parser_t *parser)
5350 uint16_t crc = 0xFFFF;
5354 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5355 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5357 progdefs_crc_file("\tint\tpad;\n");
5358 progdefs_crc_file("\tint\tofs_return[3];\n");
5359 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5360 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5361 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5362 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5363 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5364 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5365 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5366 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5368 for (i = 0; i < parser->crc_globals; ++i) {
5369 if (!ast_istype(parser->globals[i], ast_value))
5371 value = (ast_value*)(parser->globals[i]);
5372 switch (value->expression.vtype) {
5373 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5374 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5375 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5376 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5378 crc = progdefs_crc_both(crc, "\tint\t");
5381 crc = progdefs_crc_both(crc, value->name);
5382 crc = progdefs_crc_both(crc, ";\n");
5384 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5385 for (i = 0; i < parser->crc_fields; ++i) {
5386 if (!ast_istype(parser->fields[i], ast_value))
5388 value = (ast_value*)(parser->fields[i]);
5389 switch (value->expression.next->expression.vtype) {
5390 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5391 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5392 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5393 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5395 crc = progdefs_crc_both(crc, "\tint\t");
5398 crc = progdefs_crc_both(crc, value->name);
5399 crc = progdefs_crc_both(crc, ";\n");
5401 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5406 static parser_t *parser;
5413 parser = (parser_t*)mem_a(sizeof(parser_t));
5417 memset(parser, 0, sizeof(*parser));
5419 for (i = 0; i < operator_count; ++i) {
5420 if (operators[i].id == opid1('=')) {
5421 parser->assign_op = operators+i;
5425 if (!parser->assign_op) {
5426 printf("internal error: initializing parser: failed to find assign operator\n");
5431 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5432 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5433 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5434 vec_push(parser->_blocktypedefs, 0);
5437 vec_push(parser->correct_variables, correct_trie_new());
5438 vec_push(parser->correct_variables_score, NULL);
5440 empty_ctx.file = "<internal>";
5442 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5443 parser->nil->cvq = CV_CONST;
5444 if (OPTS_FLAG(UNTYPED_NIL))
5445 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5447 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5448 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5449 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5453 bool parser_compile()
5455 /* initial lexer/parser state */
5456 parser->lex->flags.noops = true;
5458 if (parser_next(parser))
5460 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5462 if (!parser_global_statement(parser)) {
5463 if (parser->tok == TOKEN_EOF)
5464 parseerror(parser, "unexpected eof");
5465 else if (compile_errors)
5466 parseerror(parser, "there have been errors, bailing out");
5467 lex_close(parser->lex);
5473 parseerror(parser, "parse error");
5474 lex_close(parser->lex);
5479 lex_close(parser->lex);
5482 return !compile_errors;
5485 bool parser_compile_file(const char *filename)
5487 parser->lex = lex_open(filename);
5489 con_err("failed to open file \"%s\"\n", filename);
5492 return parser_compile();
5495 bool parser_compile_string(const char *name, const char *str, size_t len)
5497 parser->lex = lex_open_string(str, len, name);
5499 con_err("failed to create lexer for string \"%s\"\n", name);
5502 return parser_compile();
5505 void parser_cleanup()
5508 for (i = 0; i < vec_size(parser->accessors); ++i) {
5509 ast_delete(parser->accessors[i]->constval.vfunc);
5510 parser->accessors[i]->constval.vfunc = NULL;
5511 ast_delete(parser->accessors[i]);
5513 for (i = 0; i < vec_size(parser->functions); ++i) {
5514 ast_delete(parser->functions[i]);
5516 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5517 ast_delete(parser->imm_vector[i]);
5519 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5520 ast_delete(parser->imm_string[i]);
5522 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5523 ast_delete(parser->imm_float[i]);
5525 for (i = 0; i < vec_size(parser->fields); ++i) {
5526 ast_delete(parser->fields[i]);
5528 for (i = 0; i < vec_size(parser->globals); ++i) {
5529 ast_delete(parser->globals[i]);
5531 vec_free(parser->accessors);
5532 vec_free(parser->functions);
5533 vec_free(parser->imm_vector);
5534 vec_free(parser->imm_string);
5535 vec_free(parser->imm_float);
5536 vec_free(parser->globals);
5537 vec_free(parser->fields);
5539 for (i = 0; i < vec_size(parser->variables); ++i)
5540 util_htdel(parser->variables[i]);
5541 vec_free(parser->variables);
5542 vec_free(parser->_blocklocals);
5543 vec_free(parser->_locals);
5546 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5547 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5549 vec_free(parser->correct_variables);
5550 vec_free(parser->correct_variables_score);
5553 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5554 ast_delete(parser->_typedefs[i]);
5555 vec_free(parser->_typedefs);
5556 for (i = 0; i < vec_size(parser->typedefs); ++i)
5557 util_htdel(parser->typedefs[i]);
5558 vec_free(parser->typedefs);
5559 vec_free(parser->_blocktypedefs);
5561 vec_free(parser->_block_ctx);
5563 vec_free(parser->labels);
5564 vec_free(parser->gotos);
5565 vec_free(parser->breaks);
5566 vec_free(parser->continues);
5568 ast_value_delete(parser->nil);
5570 ast_value_delete(parser->const_vec[0]);
5571 ast_value_delete(parser->const_vec[1]);
5572 ast_value_delete(parser->const_vec[2]);
5577 bool parser_finish(const char *output)
5583 if (compile_errors) {
5584 con_out("*** there were compile errors\n");
5588 ir = ir_builder_new("gmqcc_out");
5590 con_out("failed to allocate builder\n");
5594 for (i = 0; i < vec_size(parser->fields); ++i) {
5597 if (!ast_istype(parser->fields[i], ast_value))
5599 field = (ast_value*)parser->fields[i];
5600 hasvalue = field->hasvalue;
5601 field->hasvalue = false;
5602 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5603 con_out("failed to generate field %s\n", field->name);
5604 ir_builder_delete(ir);
5609 ast_expression *subtype;
5610 field->hasvalue = true;
5611 subtype = field->expression.next;
5612 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5613 if (subtype->expression.vtype == TYPE_FIELD)
5614 ifld->fieldtype = subtype->expression.next->expression.vtype;
5615 else if (subtype->expression.vtype == TYPE_FUNCTION)
5616 ifld->outtype = subtype->expression.next->expression.vtype;
5617 (void)!ir_value_set_field(field->ir_v, ifld);
5620 for (i = 0; i < vec_size(parser->globals); ++i) {
5622 if (!ast_istype(parser->globals[i], ast_value))
5624 asvalue = (ast_value*)(parser->globals[i]);
5625 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5626 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5627 "unused global: `%s`", asvalue->name);
5629 if (!ast_global_codegen(asvalue, ir, false)) {
5630 con_out("failed to generate global %s\n", asvalue->name);
5631 ir_builder_delete(ir);
5635 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5636 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5637 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5638 ir_builder_delete(ir);
5642 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5643 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5644 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5645 ir_builder_delete(ir);
5649 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5650 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5651 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5652 ir_builder_delete(ir);
5656 for (i = 0; i < vec_size(parser->globals); ++i) {
5658 if (!ast_istype(parser->globals[i], ast_value))
5660 asvalue = (ast_value*)(parser->globals[i]);
5661 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5663 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5664 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5665 "uninitialized constant: `%s`",
5667 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5668 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5669 "uninitialized global: `%s`",
5672 if (!ast_generate_accessors(asvalue, ir)) {
5673 ir_builder_delete(ir);
5677 for (i = 0; i < vec_size(parser->fields); ++i) {
5679 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5681 if (!ast_istype((ast_expression*)asvalue, ast_value))
5683 if (asvalue->expression.vtype != TYPE_ARRAY)
5685 if (!ast_generate_accessors(asvalue, ir)) {
5686 ir_builder_delete(ir);
5690 for (i = 0; i < vec_size(parser->functions); ++i) {
5691 if (!ast_function_codegen(parser->functions[i], ir)) {
5692 con_out("failed to generate function %s\n", parser->functions[i]->name);
5693 ir_builder_delete(ir);
5698 ir_builder_dump(ir, con_out);
5699 for (i = 0; i < vec_size(parser->functions); ++i) {
5700 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5701 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5702 ir_builder_delete(ir);
5707 if (compile_Werrors) {
5708 con_out("*** there were warnings treated as errors\n");
5709 compile_show_werrors();
5715 ir_builder_dump(ir, con_out);
5717 generate_checksum(parser);
5719 if (!ir_builder_generate(ir, output)) {
5720 con_out("*** failed to generate output file\n");
5721 ir_builder_delete(ir);
5726 ir_builder_delete(ir);