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;
57 ast_value *reserved_version;
62 ast_function *function;
64 /* All the labels the function defined...
65 * Should they be in ast_function instead?
70 const char **continues;
72 /* A list of hashtables for each scope */
78 /* same as above but for the spelling corrector */
79 correct_trie_t **correct_variables;
80 size_t ***correct_variables_score; /* vector of vector of size_t* */
82 /* not to be used directly, we use the hash table */
83 ast_expression **_locals;
85 ast_value **_typedefs;
86 size_t *_blocktypedefs;
89 /* we store the '=' operator info */
90 const oper_info *assign_op;
92 /* Keep track of our ternary vs parenthesis nesting state.
93 * If we reach a 'comma' operator in a ternary without a paren,
94 * we shall trigger -Wternary-precedence.
99 ast_value *const_vec[3];
104 /* collected information */
105 size_t max_param_count;
108 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
110 static void parser_enterblock(parser_t *parser);
111 static bool parser_leaveblock(parser_t *parser);
112 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
113 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
114 static bool parse_typedef(parser_t *parser);
115 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);
116 static ast_block* parse_block(parser_t *parser);
117 static bool parse_block_into(parser_t *parser, ast_block *block);
118 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
119 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
120 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
121 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
122 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
123 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
124 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
126 static void parseerror(parser_t *parser, const char *fmt, ...)
130 vcompile_error(parser->lex->tok.ctx, fmt, ap);
134 /* returns true if it counts as an error */
135 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
140 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
145 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
150 r = vcompile_warning(ctx, warntype, fmt, ap);
155 /**********************************************************************
156 * some maths used for constant folding
159 vector vec3_add(vector a, vector b)
168 vector vec3_sub(vector a, vector b)
177 qcfloat vec3_mulvv(vector a, vector b)
179 return (a.x * b.x + a.y * b.y + a.z * b.z);
182 vector vec3_mulvf(vector a, float b)
191 /**********************************************************************
195 bool parser_next(parser_t *parser)
197 /* lex_do kills the previous token */
198 parser->tok = lex_do(parser->lex);
199 if (parser->tok == TOKEN_EOF)
201 if (parser->tok >= TOKEN_ERROR) {
202 parseerror(parser, "lex error");
208 #define parser_tokval(p) ((p)->lex->tok.value)
209 #define parser_token(p) (&((p)->lex->tok))
210 #define parser_ctx(p) ((p)->lex->tok.ctx)
212 static ast_value* parser_const_float(parser_t *parser, double d)
217 for (i = 0; i < vec_size(parser->imm_float); ++i) {
218 const double compare = parser->imm_float[i]->constval.vfloat;
219 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
220 return parser->imm_float[i];
223 ctx = parser_ctx(parser);
225 memset(&ctx, 0, sizeof(ctx));
227 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
229 out->hasvalue = true;
230 out->constval.vfloat = d;
231 vec_push(parser->imm_float, out);
235 static ast_value* parser_const_float_0(parser_t *parser)
237 if (!parser->imm_float_zero)
238 parser->imm_float_zero = parser_const_float(parser, 0);
239 return parser->imm_float_zero;
242 static ast_value* parser_const_float_1(parser_t *parser)
244 if (!parser->imm_float_one)
245 parser->imm_float_one = parser_const_float(parser, 1);
246 return parser->imm_float_one;
249 static char *parser_strdup(const char *str)
252 /* actually dup empty strings */
253 char *out = (char*)mem_a(1);
257 return util_strdup(str);
260 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
264 for (i = 0; i < vec_size(parser->imm_string); ++i) {
265 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
266 return parser->imm_string[i];
270 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
271 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
273 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
275 out->hasvalue = true;
276 out->constval.vstring = parser_strdup(str);
277 vec_push(parser->imm_string, out);
281 static ast_value* parser_const_vector(parser_t *parser, vector v)
285 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
286 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
287 return parser->imm_vector[i];
289 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
291 out->hasvalue = true;
292 out->constval.vvec = v;
293 vec_push(parser->imm_vector, out);
297 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
303 return parser_const_vector(parser, v);
306 static ast_value* parser_const_vector_0(parser_t *parser)
308 if (!parser->imm_vector_zero)
309 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
310 return parser->imm_vector_zero;
313 static ast_expression* parser_find_field(parser_t *parser, const char *name)
315 return ( ast_expression*)util_htget(parser->htfields, name);
318 static ast_expression* parser_find_label(parser_t *parser, const char *name)
321 for(i = 0; i < vec_size(parser->labels); i++)
322 if (!strcmp(parser->labels[i]->name, name))
323 return (ast_expression*)parser->labels[i];
327 static ast_expression* parser_find_global(parser_t *parser, const char *name)
329 return (ast_expression*)util_htget(parser->htglobals, name);
332 static ast_expression* parser_find_param(parser_t *parser, const char *name)
336 if (!parser->function)
338 fun = parser->function->vtype;
339 for (i = 0; i < vec_size(fun->expression.params); ++i) {
340 if (!strcmp(fun->expression.params[i]->name, name))
341 return (ast_expression*)(fun->expression.params[i]);
346 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
351 hash = util_hthash(parser->htglobals, name);
354 for (i = vec_size(parser->variables); i > upto;) {
356 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
360 return parser_find_param(parser, name);
363 static ast_expression* parser_find_var(parser_t *parser, const char *name)
367 v = parser_find_local(parser, name, 0, &dummy);
368 if (!v) v = parser_find_global(parser, name);
372 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
376 hash = util_hthash(parser->typedefs[0], name);
378 for (i = vec_size(parser->typedefs); i > upto;) {
380 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
388 size_t etype; /* 0 = expression, others are operators */
392 ast_block *block; /* for commas and function calls */
401 #define SY_PAREN_EXPR '('
402 #define SY_PAREN_FUNC 'f'
403 #define SY_PAREN_INDEX '['
404 #define SY_PAREN_TERNARY '?'
406 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
417 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
421 e.out = (ast_expression*)v;
428 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
430 e.etype = 1 + (op - operators);
439 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
451 # define DEBUGSHUNTDO(x) x
453 # define DEBUGSHUNTDO(x)
456 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
457 * so we need to rotate it to become ent.(foo[n]).
459 static bool rotate_entfield_array_index_nodes(ast_expression **out)
461 ast_array_index *index;
462 ast_entfield *entfield;
466 ast_expression *entity;
468 lex_ctx ctx = ast_ctx(*out);
470 if (!ast_istype(*out, ast_array_index))
472 index = (ast_array_index*)*out;
474 if (!ast_istype(index->array, ast_entfield))
476 entfield = (ast_entfield*)index->array;
478 if (!ast_istype(entfield->field, ast_value))
480 field = (ast_value*)entfield->field;
483 entity = entfield->entity;
487 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
488 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
489 *out = (ast_expression*)entfield;
494 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
496 switch (v->expression.vtype) {
498 return !!v->constval.vfloat;
500 return !!v->constval.vint;
502 if (OPTS_FLAG(CORRECT_LOGIC))
503 return v->constval.vvec.x &&
504 v->constval.vvec.y &&
507 return !!(v->constval.vvec.x);
509 if (!v->constval.vstring)
511 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
513 return !!v->constval.vstring[0];
515 compile_error(ctx, "internal error: immediate_is_true on invalid type");
516 return !!v->constval.vfunc;
520 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
524 ast_expression *out = NULL;
525 ast_expression *exprs[3];
526 ast_block *blocks[3];
527 ast_value *asvalue[3];
528 ast_binstore *asbinstore;
529 size_t i, assignop, addop, subop;
530 qcint generated_op = 0;
535 if (!vec_size(sy->ops)) {
536 parseerror(parser, "internal error: missing operator");
540 if (vec_last(sy->ops).paren) {
541 parseerror(parser, "unmatched parenthesis");
545 op = &operators[vec_last(sy->ops).etype - 1];
546 ctx = vec_last(sy->ops).ctx;
548 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
550 if (vec_size(sy->out) < op->operands) {
551 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
552 op->op, (int)op->id);
556 vec_shrinkby(sy->ops, 1);
558 /* op(:?) has no input and no output */
562 vec_shrinkby(sy->out, op->operands);
563 for (i = 0; i < op->operands; ++i) {
564 exprs[i] = sy->out[vec_size(sy->out)+i].out;
565 blocks[i] = sy->out[vec_size(sy->out)+i].block;
566 asvalue[i] = (ast_value*)exprs[i];
568 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
569 !(i != 0 && op->id == opid2('?',':')) &&
570 !(i == 1 && op->id == opid1('.')))
572 if (ast_istype(exprs[i], ast_label))
573 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
575 compile_error(ast_ctx(exprs[i]), "not an expression");
576 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
580 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
581 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
585 #define NotSameType(T) \
586 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
587 exprs[0]->expression.vtype != T)
588 #define CanConstFold1(A) \
589 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
590 (A)->expression.vtype != TYPE_FUNCTION)
591 #define CanConstFold(A, B) \
592 (CanConstFold1(A) && CanConstFold1(B))
593 #define ConstV(i) (asvalue[(i)]->constval.vvec)
594 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
595 #define ConstS(i) (asvalue[(i)]->constval.vstring)
599 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
603 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
604 exprs[1]->expression.vtype == TYPE_NOEXPR)
606 if (exprs[1] == (ast_expression*)parser->const_vec[0])
607 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
608 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
609 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
610 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
611 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
613 parseerror(parser, "access to invalid vector component");
617 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
618 if (exprs[1]->expression.vtype != TYPE_FIELD) {
619 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
622 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
624 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
625 parseerror(parser, "vectors cannot be accessed this way");
629 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
635 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
636 !(exprs[0]->expression.vtype == TYPE_FIELD &&
637 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
639 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
640 parseerror(parser, "cannot index value of type %s", ty1);
643 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
644 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
645 parseerror(parser, "index must be of type float, not %s", ty1);
648 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
649 if (rotate_entfield_array_index_nodes(&out))
652 /* This is not broken in fteqcc anymore */
653 if (opts.standard != COMPILER_GMQCC) {
654 /* this error doesn't need to make us bail out */
655 (void)!parsewarning(parser, WARN_EXTENSIONS,
656 "accessing array-field members of an entity without parenthesis\n"
657 " -> this is an extension from -std=gmqcc");
665 if (!ast_block_add_expr(blocks[0], exprs[1]))
668 blocks[0] = ast_block_new(ctx);
669 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
670 !ast_block_add_expr(blocks[0], exprs[1]))
675 if (!ast_block_set_type(blocks[0], exprs[1]))
678 vec_push(sy->out, syblock(ctx, blocks[0]));
685 switch (exprs[0]->expression.vtype) {
687 if (CanConstFold1(exprs[0]))
688 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
690 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
691 (ast_expression*)parser_const_float_0(parser),
695 if (CanConstFold1(exprs[0]))
696 out = (ast_expression*)parser_const_vector_f(parser,
697 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
699 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
700 (ast_expression*)parser_const_vector_0(parser),
704 parseerror(parser, "invalid types used in expression: cannot negate type %s",
705 type_name[exprs[0]->expression.vtype]);
711 switch (exprs[0]->expression.vtype) {
713 if (CanConstFold1(exprs[0]))
714 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
716 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
719 if (CanConstFold1(exprs[0]))
720 out = (ast_expression*)parser_const_float(parser,
721 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
723 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
726 if (CanConstFold1(exprs[0])) {
727 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
728 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
730 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
732 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
733 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
735 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
738 /* we don't constant-fold NOT for these types */
740 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
743 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
746 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
747 type_name[exprs[0]->expression.vtype]);
753 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
754 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
756 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
757 type_name[exprs[0]->expression.vtype],
758 type_name[exprs[1]->expression.vtype]);
761 switch (exprs[0]->expression.vtype) {
763 if (CanConstFold(exprs[0], exprs[1]))
765 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
768 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
771 if (CanConstFold(exprs[0], exprs[1]))
772 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
774 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
777 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
778 type_name[exprs[0]->expression.vtype],
779 type_name[exprs[1]->expression.vtype]);
784 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
785 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
787 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
788 type_name[exprs[1]->expression.vtype],
789 type_name[exprs[0]->expression.vtype]);
792 switch (exprs[0]->expression.vtype) {
794 if (CanConstFold(exprs[0], exprs[1]))
795 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
797 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
800 if (CanConstFold(exprs[0], exprs[1]))
801 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
803 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
806 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
807 type_name[exprs[1]->expression.vtype],
808 type_name[exprs[0]->expression.vtype]);
813 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
814 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
815 exprs[1]->expression.vtype == TYPE_FLOAT) &&
816 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
817 exprs[0]->expression.vtype == TYPE_FLOAT)
820 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
821 type_name[exprs[1]->expression.vtype],
822 type_name[exprs[0]->expression.vtype]);
825 switch (exprs[0]->expression.vtype) {
827 if (exprs[1]->expression.vtype == TYPE_VECTOR)
829 if (CanConstFold(exprs[0], exprs[1]))
830 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
832 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
836 if (CanConstFold(exprs[0], exprs[1]))
837 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
839 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
843 if (exprs[1]->expression.vtype == TYPE_FLOAT)
845 if (CanConstFold(exprs[0], exprs[1]))
846 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
848 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
852 if (CanConstFold(exprs[0], exprs[1]))
853 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
854 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
855 vector vec = ConstV(0);
856 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
857 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
858 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
859 out->expression.node.keep = false;
860 ((ast_member*)out)->rvalue = true;
862 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
864 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
865 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
866 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
867 out->expression.node.keep = false;
868 ((ast_member*)out)->rvalue = true;
870 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
872 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
873 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
874 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
875 out->expression.node.keep = false;
876 ((ast_member*)out)->rvalue = true;
878 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
881 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
883 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
884 vector vec = ConstV(1);
885 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
886 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
887 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
888 out->expression.node.keep = false;
889 ((ast_member*)out)->rvalue = true;
891 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
893 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
894 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
895 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
896 out->expression.node.keep = false;
897 ((ast_member*)out)->rvalue = true;
899 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
901 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
902 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
903 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
904 out->expression.node.keep = false;
905 ((ast_member*)out)->rvalue = true;
907 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
910 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
913 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
917 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
918 type_name[exprs[1]->expression.vtype],
919 type_name[exprs[0]->expression.vtype]);
924 if (NotSameType(TYPE_FLOAT)) {
925 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
926 type_name[exprs[0]->expression.vtype],
927 type_name[exprs[1]->expression.vtype]);
930 if (CanConstFold(exprs[0], exprs[1]))
931 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
933 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
937 parseerror(parser, "qc does not have a modulo operator");
941 if (NotSameType(TYPE_FLOAT)) {
942 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
943 type_name[exprs[0]->expression.vtype],
944 type_name[exprs[1]->expression.vtype]);
947 if (CanConstFold(exprs[0], exprs[1]))
948 out = (ast_expression*)parser_const_float(parser,
949 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
950 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
952 out = (ast_expression*)ast_binary_new(ctx,
953 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
957 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
962 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
963 if (op->id == opid2('<','<'))
964 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
966 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
969 case opid3('<','<','='):
970 case opid3('>','>','='):
971 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
975 generated_op += 1; /* INSTR_OR */
977 generated_op += INSTR_AND;
979 if (NotSameType(TYPE_FLOAT)) {
980 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
981 type_name[exprs[0]->expression.vtype],
982 type_name[exprs[1]->expression.vtype]);
983 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
984 parseerror(parser, "TODO: optional early out");
988 if (CanConstFold(exprs[0], exprs[1]))
990 if (OPTS_FLAG(PERL_LOGIC)) {
991 if (immediate_is_true(ctx, asvalue[0]))
995 out = (ast_expression*)parser_const_float(parser,
996 ( (generated_op == INSTR_OR)
997 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
998 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1003 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1004 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1005 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1006 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1009 for (i = 0; i < 2; ++i) {
1010 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1011 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1013 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1015 exprs[i] = out; out = NULL;
1016 if (OPTS_FLAG(PERL_LOGIC)) {
1017 /* here we want to keep the right expressions' type */
1021 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1022 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1024 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1026 exprs[i] = out; out = NULL;
1027 if (OPTS_FLAG(PERL_LOGIC)) {
1028 /* here we want to keep the right expressions' type */
1033 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1037 case opid2('?',':'):
1038 if (vec_last(parser->pot) != POT_TERNARY2) {
1039 parseerror(parser, "mismatched parenthesis/ternary");
1042 vec_pop(parser->pot);
1043 if (!ast_compare_type(exprs[1], exprs[2])) {
1044 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1045 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1046 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1049 if (CanConstFold1(exprs[0]))
1050 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1052 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1056 generated_op += 1; /* INSTR_GT */
1058 generated_op += 1; /* INSTR_LT */
1059 case opid2('>', '='):
1060 generated_op += 1; /* INSTR_GE */
1061 case opid2('<', '='):
1062 generated_op += INSTR_LE;
1063 if (NotSameType(TYPE_FLOAT)) {
1064 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1065 type_name[exprs[0]->expression.vtype],
1066 type_name[exprs[1]->expression.vtype]);
1069 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1071 case opid2('!', '='):
1072 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1073 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1074 type_name[exprs[0]->expression.vtype],
1075 type_name[exprs[1]->expression.vtype]);
1078 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1080 case opid2('=', '='):
1081 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1082 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1083 type_name[exprs[0]->expression.vtype],
1084 type_name[exprs[1]->expression.vtype]);
1087 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1091 if (ast_istype(exprs[0], ast_entfield)) {
1092 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1093 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1094 exprs[0]->expression.vtype == TYPE_FIELD &&
1095 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1097 assignop = type_storep_instr[TYPE_VECTOR];
1100 assignop = type_storep_instr[exprs[0]->expression.vtype];
1101 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1103 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1104 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1105 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1106 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1107 exprs[1]->expression.vtype == TYPE_FUNCTION)
1109 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1110 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1113 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1118 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1119 exprs[0]->expression.vtype == TYPE_FIELD &&
1120 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1122 assignop = type_store_instr[TYPE_VECTOR];
1125 assignop = type_store_instr[exprs[0]->expression.vtype];
1128 if (assignop == AINSTR_END) {
1129 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1130 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1131 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1133 else if (!ast_compare_type(exprs[0], exprs[1]))
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1137 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1138 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1139 exprs[1]->expression.vtype == TYPE_FUNCTION)
1141 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1142 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1145 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1148 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1149 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1151 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1153 case opid3('+','+','P'):
1154 case opid3('-','-','P'):
1156 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1157 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1158 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1161 if (op->id == opid3('+','+','P'))
1162 addop = INSTR_ADD_F;
1164 addop = INSTR_SUB_F;
1165 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1166 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1168 if (ast_istype(exprs[0], ast_entfield)) {
1169 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1171 (ast_expression*)parser_const_float_1(parser));
1173 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1175 (ast_expression*)parser_const_float_1(parser));
1178 case opid3('S','+','+'):
1179 case opid3('S','-','-'):
1181 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1182 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1183 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1186 if (op->id == opid3('S','+','+')) {
1187 addop = INSTR_ADD_F;
1188 subop = INSTR_SUB_F;
1190 addop = INSTR_SUB_F;
1191 subop = INSTR_ADD_F;
1193 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1194 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1196 if (ast_istype(exprs[0], ast_entfield)) {
1197 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1199 (ast_expression*)parser_const_float_1(parser));
1201 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1203 (ast_expression*)parser_const_float_1(parser));
1207 out = (ast_expression*)ast_binary_new(ctx, subop,
1209 (ast_expression*)parser_const_float_1(parser));
1211 case opid2('+','='):
1212 case opid2('-','='):
1213 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1214 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1216 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1217 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1218 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1222 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1223 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1225 if (ast_istype(exprs[0], ast_entfield))
1226 assignop = type_storep_instr[exprs[0]->expression.vtype];
1228 assignop = type_store_instr[exprs[0]->expression.vtype];
1229 switch (exprs[0]->expression.vtype) {
1231 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1232 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1233 exprs[0], exprs[1]);
1236 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1237 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1238 exprs[0], exprs[1]);
1241 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1242 type_name[exprs[0]->expression.vtype],
1243 type_name[exprs[1]->expression.vtype]);
1247 case opid2('*','='):
1248 case opid2('/','='):
1249 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1250 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1251 exprs[0]->expression.vtype == TYPE_VECTOR))
1253 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1254 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1255 parseerror(parser, "invalid types used in expression: %s and %s",
1259 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1260 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1262 if (ast_istype(exprs[0], ast_entfield))
1263 assignop = type_storep_instr[exprs[0]->expression.vtype];
1265 assignop = type_store_instr[exprs[0]->expression.vtype];
1266 switch (exprs[0]->expression.vtype) {
1268 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1269 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1270 exprs[0], exprs[1]);
1273 if (op->id == opid2('*','=')) {
1274 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1275 exprs[0], exprs[1]);
1277 /* there's no DIV_VF */
1278 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1279 (ast_expression*)parser_const_float_1(parser),
1283 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1288 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1289 type_name[exprs[0]->expression.vtype],
1290 type_name[exprs[1]->expression.vtype]);
1294 case opid2('&','='):
1295 case opid2('|','='):
1296 if (NotSameType(TYPE_FLOAT)) {
1297 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1298 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1299 parseerror(parser, "invalid types used in expression: %s and %s",
1303 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1304 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1306 if (ast_istype(exprs[0], ast_entfield))
1307 assignop = type_storep_instr[exprs[0]->expression.vtype];
1309 assignop = type_store_instr[exprs[0]->expression.vtype];
1310 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1311 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1312 exprs[0], exprs[1]);
1314 case opid3('&','~','='):
1315 /* This is like: a &= ~(b);
1316 * But QC has no bitwise-not, so we implement it as
1319 if (NotSameType(TYPE_FLOAT)) {
1320 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1321 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1322 parseerror(parser, "invalid types used in expression: %s and %s",
1326 if (ast_istype(exprs[0], ast_entfield))
1327 assignop = type_storep_instr[exprs[0]->expression.vtype];
1329 assignop = type_store_instr[exprs[0]->expression.vtype];
1330 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1333 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1334 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1336 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1337 asbinstore->keep_dest = true;
1338 out = (ast_expression*)asbinstore;
1344 parseerror(parser, "failed to apply operand %s", op->op);
1348 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1349 vec_push(sy->out, syexp(ctx, out));
1353 static bool parser_close_call(parser_t *parser, shunt *sy)
1355 /* was a function call */
1356 ast_expression *fun;
1357 ast_value *funval = NULL;
1363 vec_shrinkby(sy->ops, 1);
1364 fid = sy->ops[vec_size(sy->ops)].off;
1366 /* out[fid] is the function
1367 * everything above is parameters...
1368 * 0 params = nothing
1369 * 1 params = ast_expression
1373 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1374 parseerror(parser, "internal error: function call needs function and parameter list...");
1378 fun = sy->out[fid].out;
1380 if (fun == intrinsic_debug_typestring) {
1382 if (fid+2 != vec_size(sy->out) ||
1383 vec_last(sy->out).block)
1385 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1388 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1389 ast_unref(vec_last(sy->out).out);
1390 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1391 (ast_expression*)parser_const_string(parser, ty, false));
1392 vec_shrinkby(sy->out, 1);
1396 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1398 parseerror(parser, "internal error: failed to create ast_call node");
1402 if (fid+1 == vec_size(sy->out)) {
1405 } else if (fid+2 == vec_size(sy->out)) {
1407 vec_shrinkby(sy->out, 1);
1408 params = sy->out[vec_size(sy->out)].block;
1412 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1414 paramcount = vec_size(params->exprs);
1415 call->params = params->exprs;
1416 params->exprs = NULL;
1419 if (parser->max_param_count < paramcount)
1420 parser->max_param_count = paramcount;
1421 (void)!ast_call_check_types(call);
1423 parseerror(parser, "invalid function call");
1427 if (ast_istype(fun, ast_value)) {
1428 funval = (ast_value*)fun;
1429 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1430 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1433 if (paramcount < vec_size(fun->expression.params))
1436 va_count = paramcount - vec_size(fun->expression.params);
1437 call->va_count = (ast_expression*)parser_const_float(parser, (double)va_count);
1441 /* overwrite fid, the function, with a call */
1442 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1444 if (fun->expression.vtype != TYPE_FUNCTION) {
1445 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1449 if (!fun->expression.next) {
1450 parseerror(parser, "could not determine function return type");
1453 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1455 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1457 return !parsewarning(parser, WARN_DEPRECATED,
1458 "call to function (which is marked deprecated)\n",
1459 "-> it has been declared here: %s:%i",
1460 ast_ctx(fun).file, ast_ctx(fun).line);
1463 return !parsewarning(parser, WARN_DEPRECATED,
1464 "call to `%s` (which is marked deprecated)\n"
1465 "-> `%s` declared here: %s:%i",
1466 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1468 return !parsewarning(parser, WARN_DEPRECATED,
1469 "call to `%s` (deprecated: %s)\n"
1470 "-> `%s` declared here: %s:%i",
1471 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1475 if (vec_size(fun->expression.params) != paramcount &&
1476 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1477 vec_size(fun->expression.params) < paramcount))
1479 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1481 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1482 "too %s parameters for call to %s: expected %i, got %i\n"
1483 " -> `%s` has been declared here: %s:%i",
1484 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1485 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1487 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1488 "too %s parameters for function call: expected %i, got %i\n"
1489 " -> it has been declared here: %s:%i",
1490 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1491 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1498 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1500 if (!vec_size(sy->ops)) {
1501 parseerror(parser, "unmatched closing paren");
1504 /* this would for bit a + (x) because there are no operators inside (x)
1505 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1506 parseerror(parser, "empty parenthesis expression");
1510 while (vec_size(sy->ops)) {
1511 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1512 if (!parser_close_call(parser, sy))
1516 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1517 vec_shrinkby(sy->ops, 1);
1518 return !functions_only;
1520 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1523 /* pop off the parenthesis */
1524 vec_shrinkby(sy->ops, 1);
1525 /* then apply the index operator */
1526 if (!parser_sy_apply_operator(parser, sy))
1530 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1533 if (vec_last(parser->pot) != POT_TERNARY1) {
1534 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1537 vec_last(parser->pot) = POT_TERNARY2;
1538 /* pop off the parenthesis */
1539 vec_shrinkby(sy->ops, 1);
1542 if (!parser_sy_apply_operator(parser, sy))
1548 static void parser_reclassify_token(parser_t *parser)
1551 for (i = 0; i < operator_count; ++i) {
1552 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1553 parser->tok = TOKEN_OPERATOR;
1559 static ast_expression* parse_vararg_do(parser_t *parser)
1561 ast_expression *idx, *out;
1563 ast_value *funtype = parser->function->vtype;
1565 lex_ctx ctx = parser_ctx(parser);
1567 if (!parser_next(parser) || parser->tok != '(') {
1568 parseerror(parser, "expected parameter index and type in parenthesis");
1571 if (!parser_next(parser)) {
1572 parseerror(parser, "error parsing parameter index");
1576 idx = parse_expression_leave(parser, true, false, false);
1580 if (parser->tok != ',') {
1582 parseerror(parser, "expected comma after parameter index");
1586 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1588 parseerror(parser, "expected typename for vararg");
1592 typevar = parse_typename(parser, NULL, NULL);
1598 if (parser->tok != ')') {
1600 ast_delete(typevar);
1601 parseerror(parser, "expected closing paren");
1606 if (!parser_next(parser)) {
1608 ast_delete(typevar);
1609 parseerror(parser, "parse error after vararg");
1614 if (!parser->function->varargs) {
1616 ast_delete(typevar);
1617 parseerror(parser, "function has no variable argument list");
1621 if (funtype->expression.varparam &&
1622 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1626 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1627 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1628 compile_error(ast_ctx(typevar),
1629 "function was declared to take varargs of type `%s`, requested type is: %s",
1633 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1634 ast_type_adopt(out, typevar);
1635 ast_delete(typevar);
1639 static ast_expression* parse_vararg(parser_t *parser)
1641 bool old_noops = parser->lex->flags.noops;
1642 enum parser_pot *old_pot = parser->pot;
1644 ast_expression *out;
1647 parser->lex->flags.noops = true;
1648 out = parse_vararg_do(parser);
1650 parser->pot = old_pot;
1651 parser->lex->flags.noops = old_noops;
1655 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1657 ast_expression *expr = NULL;
1659 bool wantop = false;
1660 /* only warn once about an assignment in a truth value because the current code
1661 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1663 bool warn_truthvalue = true;
1665 /* count the parens because an if starts with one, so the
1666 * end of a condition is an unmatched closing paren
1674 parser->lex->flags.noops = false;
1676 parser_reclassify_token(parser);
1680 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1681 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1683 /* a translatable string */
1687 parseerror(parser, "expected operator or end of statement, got constant");
1691 parser->lex->flags.noops = true;
1692 if (!parser_next(parser) || parser->tok != '(') {
1693 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1696 parser->lex->flags.noops = false;
1697 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1698 parseerror(parser, "expected a constant string in translatable-string extension");
1701 val = parser_const_string(parser, parser_tokval(parser), true);
1705 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1706 DEBUGSHUNTDO(con_out("push string\n"));
1708 if (!parser_next(parser) || parser->tok != ')') {
1709 parseerror(parser, "expected closing paren after translatable string");
1713 else if (parser->tok == TOKEN_DOTS)
1717 parseerror(parser, "expected operator or end of statement");
1721 va = parse_vararg(parser);
1724 vec_push(sy.out, syexp(parser_ctx(parser), va));
1725 DEBUGSHUNTDO(con_out("push `...`\n"));
1727 else if (parser->tok == TOKEN_IDENT)
1729 const char *ctoken = parser_tokval(parser);
1730 ast_expression *prev = vec_size(sy.out) ? vec_last(sy.out).out : NULL;
1731 ast_expression *var;
1733 parseerror(parser, "expected operator or end of statement");
1737 /* a_vector.{x,y,z} */
1738 if (!vec_size(sy.ops) ||
1739 !vec_last(sy.ops).etype ||
1740 operators[vec_last(sy.ops).etype-1].id != opid1('.') ||
1741 (prev >= intrinsic_debug_typestring &&
1742 prev <= intrinsic_debug_typestring))
1744 /* When adding more intrinsics, fix the above condition */
1747 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1749 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1751 var = parser_find_var(parser, parser_tokval(parser));
1753 var = parser_find_field(parser, parser_tokval(parser));
1755 if (!var && with_labels) {
1756 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1758 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1759 var = (ast_expression*)lbl;
1760 vec_push(parser->labels, lbl);
1765 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1766 var = (ast_expression*)intrinsic_debug_typestring;
1771 char *correct = NULL;
1774 * sometimes people use preprocessing predefs without enabling them
1775 * i've done this thousands of times already myself. Lets check for
1776 * it in the predef table. And diagnose it better :)
1778 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1779 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1780 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1781 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1788 * TODO: determine the best score for the identifier: be it
1789 * a variable, a field.
1791 * We should also consider adding correction tables for
1792 * other things as well.
1794 if (OPTS_FLAG(ENHANCED_DIAGNOSTICS)) {
1796 correct_init(&corr);
1798 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1799 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1800 if (strcmp(correct, parser_tokval(parser))) {
1802 } else if (correct) {
1807 correct_free(&corr);
1810 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1815 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1821 if (ast_istype(var, ast_value)) {
1822 ((ast_value*)var)->uses++;
1824 else if (ast_istype(var, ast_member)) {
1825 ast_member *mem = (ast_member*)var;
1826 if (ast_istype(mem->owner, ast_value))
1827 ((ast_value*)(mem->owner))->uses++;
1830 vec_push(sy.out, syexp(parser_ctx(parser), var));
1831 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1833 else if (parser->tok == TOKEN_FLOATCONST) {
1836 parseerror(parser, "expected operator or end of statement, got constant");
1840 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1843 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1844 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1846 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1849 parseerror(parser, "expected operator or end of statement, got constant");
1853 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1856 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1857 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1859 else if (parser->tok == TOKEN_STRINGCONST) {
1862 parseerror(parser, "expected operator or end of statement, got constant");
1866 val = parser_const_string(parser, parser_tokval(parser), false);
1869 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1870 DEBUGSHUNTDO(con_out("push string\n"));
1872 else if (parser->tok == TOKEN_VECTORCONST) {
1875 parseerror(parser, "expected operator or end of statement, got constant");
1879 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1882 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1883 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1884 parser_token(parser)->constval.v.x,
1885 parser_token(parser)->constval.v.y,
1886 parser_token(parser)->constval.v.z));
1888 else if (parser->tok == '(') {
1889 parseerror(parser, "internal error: '(' should be classified as operator");
1892 else if (parser->tok == '[') {
1893 parseerror(parser, "internal error: '[' should be classified as operator");
1896 else if (parser->tok == ')') {
1898 DEBUGSHUNTDO(con_out("do[op] )\n"));
1902 /* we do expect an operator next */
1903 /* closing an opening paren */
1904 if (!parser_close_paren(parser, &sy, false))
1906 if (vec_last(parser->pot) != POT_PAREN) {
1907 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1910 vec_pop(parser->pot);
1912 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1916 /* allowed for function calls */
1917 if (!parser_close_paren(parser, &sy, true))
1919 if (vec_last(parser->pot) != POT_PAREN) {
1920 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1923 vec_pop(parser->pot);
1927 else if (parser->tok == ']') {
1929 parseerror(parser, "operand expected");
1933 if (!parser_close_paren(parser, &sy, false))
1935 if (vec_last(parser->pot) != POT_PAREN) {
1936 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1939 vec_pop(parser->pot);
1942 else if (parser->tok == TOKEN_TYPENAME) {
1943 parseerror(parser, "unexpected typename");
1946 else if (parser->tok != TOKEN_OPERATOR) {
1948 parseerror(parser, "expected operator or end of statement");
1955 /* classify the operator */
1956 const oper_info *op;
1957 const oper_info *olast = NULL;
1959 for (o = 0; o < operator_count; ++o) {
1960 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1961 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1962 !strcmp(parser_tokval(parser), operators[o].op))
1967 if (o == operator_count) {
1968 /* no operator found... must be the end of the statement */
1971 /* found an operator */
1974 /* when declaring variables, a comma starts a new variable */
1975 if (op->id == opid1(',') && !parens && stopatcomma) {
1976 /* fixup the token */
1981 /* a colon without a pervious question mark cannot be a ternary */
1982 if (!ternaries && op->id == opid2(':','?')) {
1987 if (op->id == opid1(',')) {
1988 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1989 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1993 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1994 olast = &operators[vec_last(sy.ops).etype-1];
1996 #define IsAssignOp(x) (\
1997 (x) == opid1('=') || \
1998 (x) == opid2('+','=') || \
1999 (x) == opid2('-','=') || \
2000 (x) == opid2('*','=') || \
2001 (x) == opid2('/','=') || \
2002 (x) == opid2('%','=') || \
2003 (x) == opid2('&','=') || \
2004 (x) == opid2('|','=') || \
2005 (x) == opid3('&','~','=') \
2007 if (warn_truthvalue) {
2008 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2009 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2010 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
2013 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2014 warn_truthvalue = false;
2019 (op->prec < olast->prec) ||
2020 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2022 if (!parser_sy_apply_operator(parser, &sy))
2024 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
2025 olast = &operators[vec_last(sy.ops).etype-1];
2030 if (op->id == opid1('(')) {
2032 size_t sycount = vec_size(sy.out);
2033 DEBUGSHUNTDO(con_out("push [op] (\n"));
2034 ++parens; vec_push(parser->pot, POT_PAREN);
2035 /* we expected an operator, this is the function-call operator */
2036 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
2038 ++parens; vec_push(parser->pot, POT_PAREN);
2039 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
2040 DEBUGSHUNTDO(con_out("push [nop] (\n"));
2043 } else if (op->id == opid1('[')) {
2045 parseerror(parser, "unexpected array subscript");
2048 ++parens; vec_push(parser->pot, POT_PAREN);
2049 /* push both the operator and the paren, this makes life easier */
2050 vec_push(sy.ops, syop(parser_ctx(parser), op));
2051 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
2053 } else if (op->id == opid2('?',':')) {
2054 vec_push(sy.ops, syop(parser_ctx(parser), op));
2055 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
2058 vec_push(parser->pot, POT_TERNARY1);
2059 } else if (op->id == opid2(':','?')) {
2060 if (!vec_size(parser->pot)) {
2061 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2064 if (vec_last(parser->pot) != POT_TERNARY1) {
2065 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2068 if (!parser_close_paren(parser, &sy, false))
2070 vec_push(sy.ops, syop(parser_ctx(parser), op));
2074 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
2075 vec_push(sy.ops, syop(parser_ctx(parser), op));
2076 wantop = !!(op->flags & OP_SUFFIX);
2079 if (!parser_next(parser)) {
2082 if (parser->tok == ';' ||
2083 (!parens && (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2089 while (vec_size(sy.ops)) {
2090 if (!parser_sy_apply_operator(parser, &sy))
2094 parser->lex->flags.noops = true;
2095 if (!vec_size(sy.out)) {
2096 parseerror(parser, "empty expression");
2099 expr = sy.out[0].out;
2102 DEBUGSHUNTDO(con_out("shunt done\n"));
2103 if (vec_size(parser->pot)) {
2104 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
2107 vec_free(parser->pot);
2111 parser->lex->flags.noops = true;
2117 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2119 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2122 if (parser->tok != ';') {
2123 parseerror(parser, "semicolon expected after expression");
2127 if (!parser_next(parser)) {
2134 static void parser_enterblock(parser_t *parser)
2136 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2137 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2138 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2139 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2140 vec_push(parser->_block_ctx, parser_ctx(parser));
2143 vec_push(parser->correct_variables, correct_trie_new());
2144 vec_push(parser->correct_variables_score, NULL);
2147 static bool parser_leaveblock(parser_t *parser)
2150 size_t locals, typedefs;
2152 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2153 parseerror(parser, "internal error: parser_leaveblock with no block");
2157 util_htdel(vec_last(parser->variables));
2158 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2160 vec_pop(parser->variables);
2161 vec_pop(parser->correct_variables);
2162 vec_pop(parser->correct_variables_score);
2163 if (!vec_size(parser->_blocklocals)) {
2164 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2168 locals = vec_last(parser->_blocklocals);
2169 vec_pop(parser->_blocklocals);
2170 while (vec_size(parser->_locals) != locals) {
2171 ast_expression *e = vec_last(parser->_locals);
2172 ast_value *v = (ast_value*)e;
2173 vec_pop(parser->_locals);
2174 if (ast_istype(e, ast_value) && !v->uses) {
2175 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2180 typedefs = vec_last(parser->_blocktypedefs);
2181 while (vec_size(parser->_typedefs) != typedefs) {
2182 ast_delete(vec_last(parser->_typedefs));
2183 vec_pop(parser->_typedefs);
2185 util_htdel(vec_last(parser->typedefs));
2186 vec_pop(parser->typedefs);
2188 vec_pop(parser->_block_ctx);
2193 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2195 vec_push(parser->_locals, e);
2196 util_htset(vec_last(parser->variables), name, (void*)e);
2200 vec_last(parser->correct_variables),
2201 &vec_last(parser->correct_variables_score),
2206 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2208 vec_push(parser->globals, e);
2209 util_htset(parser->htglobals, name, e);
2213 parser->correct_variables[0],
2214 &parser->correct_variables_score[0],
2219 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2223 ast_expression *prev;
2225 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2228 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2231 parseerror(parser, "internal error: failed to process condition");
2236 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2238 /* vector types need to be cast to true booleans */
2239 ast_binary *bin = (ast_binary*)cond;
2240 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2242 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2244 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2247 parseerror(parser, "internal error: failed to process condition");
2254 unary = (ast_unary*)cond;
2255 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2257 cond = unary->operand;
2258 unary->operand = NULL;
2261 unary = (ast_unary*)cond;
2265 parseerror(parser, "internal error: failed to process condition");
2267 if (ifnot) *_ifnot = !*_ifnot;
2271 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2274 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2277 lex_ctx ctx = parser_ctx(parser);
2279 (void)block; /* not touching */
2281 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2282 if (!parser_next(parser)) {
2283 parseerror(parser, "expected condition or 'not'");
2286 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2288 if (!parser_next(parser)) {
2289 parseerror(parser, "expected condition in parenthesis");
2293 if (parser->tok != '(') {
2294 parseerror(parser, "expected 'if' condition in parenthesis");
2297 /* parse into the expression */
2298 if (!parser_next(parser)) {
2299 parseerror(parser, "expected 'if' condition after opening paren");
2302 /* parse the condition */
2303 cond = parse_expression_leave(parser, false, true, false);
2307 if (parser->tok != ')') {
2308 parseerror(parser, "expected closing paren after 'if' condition");
2312 /* parse into the 'then' branch */
2313 if (!parser_next(parser)) {
2314 parseerror(parser, "expected statement for on-true branch of 'if'");
2318 if (!parse_statement_or_block(parser, &ontrue)) {
2323 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2324 /* check for an else */
2325 if (!strcmp(parser_tokval(parser), "else")) {
2326 /* parse into the 'else' branch */
2327 if (!parser_next(parser)) {
2328 parseerror(parser, "expected on-false branch after 'else'");
2333 if (!parse_statement_or_block(parser, &onfalse)) {
2340 cond = process_condition(parser, cond, &ifnot);
2342 if (ontrue) ast_delete(ontrue);
2343 if (onfalse) ast_delete(onfalse);
2348 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2350 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2351 *out = (ast_expression*)ifthen;
2355 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2356 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2361 /* skip the 'while' and get the body */
2362 if (!parser_next(parser)) {
2363 if (OPTS_FLAG(LOOP_LABELS))
2364 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2366 parseerror(parser, "expected 'while' condition in parenthesis");
2370 if (parser->tok == ':') {
2371 if (!OPTS_FLAG(LOOP_LABELS))
2372 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2373 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2374 parseerror(parser, "expected loop label");
2377 label = util_strdup(parser_tokval(parser));
2378 if (!parser_next(parser)) {
2380 parseerror(parser, "expected 'while' condition in parenthesis");
2385 if (parser->tok != '(') {
2386 parseerror(parser, "expected 'while' condition in parenthesis");
2390 vec_push(parser->breaks, label);
2391 vec_push(parser->continues, label);
2393 rv = parse_while_go(parser, block, out);
2396 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2397 parseerror(parser, "internal error: label stack corrupted");
2403 vec_pop(parser->breaks);
2404 vec_pop(parser->continues);
2409 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2412 ast_expression *cond, *ontrue;
2416 lex_ctx ctx = parser_ctx(parser);
2418 (void)block; /* not touching */
2420 /* parse into the expression */
2421 if (!parser_next(parser)) {
2422 parseerror(parser, "expected 'while' condition after opening paren");
2425 /* parse the condition */
2426 cond = parse_expression_leave(parser, false, true, false);
2430 if (parser->tok != ')') {
2431 parseerror(parser, "expected closing paren after 'while' condition");
2435 /* parse into the 'then' branch */
2436 if (!parser_next(parser)) {
2437 parseerror(parser, "expected while-loop body");
2441 if (!parse_statement_or_block(parser, &ontrue)) {
2446 cond = process_condition(parser, cond, &ifnot);
2451 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2452 *out = (ast_expression*)aloop;
2456 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2457 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2462 /* skip the 'do' and get the body */
2463 if (!parser_next(parser)) {
2464 if (OPTS_FLAG(LOOP_LABELS))
2465 parseerror(parser, "expected loop label or body");
2467 parseerror(parser, "expected loop body");
2471 if (parser->tok == ':') {
2472 if (!OPTS_FLAG(LOOP_LABELS))
2473 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2474 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2475 parseerror(parser, "expected loop label");
2478 label = util_strdup(parser_tokval(parser));
2479 if (!parser_next(parser)) {
2481 parseerror(parser, "expected loop body");
2486 vec_push(parser->breaks, label);
2487 vec_push(parser->continues, label);
2489 rv = parse_dowhile_go(parser, block, out);
2492 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2493 parseerror(parser, "internal error: label stack corrupted");
2499 vec_pop(parser->breaks);
2500 vec_pop(parser->continues);
2505 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2508 ast_expression *cond, *ontrue;
2512 lex_ctx ctx = parser_ctx(parser);
2514 (void)block; /* not touching */
2516 if (!parse_statement_or_block(parser, &ontrue))
2519 /* expect the "while" */
2520 if (parser->tok != TOKEN_KEYWORD ||
2521 strcmp(parser_tokval(parser), "while"))
2523 parseerror(parser, "expected 'while' and condition");
2528 /* skip the 'while' and check for opening paren */
2529 if (!parser_next(parser) || parser->tok != '(') {
2530 parseerror(parser, "expected 'while' condition in parenthesis");
2534 /* parse into the expression */
2535 if (!parser_next(parser)) {
2536 parseerror(parser, "expected 'while' condition after opening paren");
2540 /* parse the condition */
2541 cond = parse_expression_leave(parser, false, true, false);
2545 if (parser->tok != ')') {
2546 parseerror(parser, "expected closing paren after 'while' condition");
2552 if (!parser_next(parser) || parser->tok != ';') {
2553 parseerror(parser, "expected semicolon after condition");
2559 if (!parser_next(parser)) {
2560 parseerror(parser, "parse error");
2566 cond = process_condition(parser, cond, &ifnot);
2571 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2572 *out = (ast_expression*)aloop;
2576 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2577 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2582 /* skip the 'for' and check for opening paren */
2583 if (!parser_next(parser)) {
2584 if (OPTS_FLAG(LOOP_LABELS))
2585 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2587 parseerror(parser, "expected 'for' expressions in parenthesis");
2591 if (parser->tok == ':') {
2592 if (!OPTS_FLAG(LOOP_LABELS))
2593 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2594 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2595 parseerror(parser, "expected loop label");
2598 label = util_strdup(parser_tokval(parser));
2599 if (!parser_next(parser)) {
2601 parseerror(parser, "expected 'for' expressions in parenthesis");
2606 if (parser->tok != '(') {
2607 parseerror(parser, "expected 'for' expressions in parenthesis");
2611 vec_push(parser->breaks, label);
2612 vec_push(parser->continues, label);
2614 rv = parse_for_go(parser, block, out);
2617 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2618 parseerror(parser, "internal error: label stack corrupted");
2624 vec_pop(parser->breaks);
2625 vec_pop(parser->continues);
2629 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2632 ast_expression *initexpr, *cond, *increment, *ontrue;
2638 lex_ctx ctx = parser_ctx(parser);
2640 parser_enterblock(parser);
2647 /* parse into the expression */
2648 if (!parser_next(parser)) {
2649 parseerror(parser, "expected 'for' initializer after opening paren");
2654 if (parser->tok == TOKEN_IDENT)
2655 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2657 if (typevar || parser->tok == TOKEN_TYPENAME) {
2659 if (opts.standard != COMPILER_GMQCC) {
2660 if (parsewarning(parser, WARN_EXTENSIONS,
2661 "current standard does not allow variable declarations in for-loop initializers"))
2665 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2668 else if (parser->tok != ';')
2670 initexpr = parse_expression_leave(parser, false, false, false);
2675 /* move on to condition */
2676 if (parser->tok != ';') {
2677 parseerror(parser, "expected semicolon after for-loop initializer");
2680 if (!parser_next(parser)) {
2681 parseerror(parser, "expected for-loop condition");
2685 /* parse the condition */
2686 if (parser->tok != ';') {
2687 cond = parse_expression_leave(parser, false, true, false);
2692 /* move on to incrementor */
2693 if (parser->tok != ';') {
2694 parseerror(parser, "expected semicolon after for-loop initializer");
2697 if (!parser_next(parser)) {
2698 parseerror(parser, "expected for-loop condition");
2702 /* parse the incrementor */
2703 if (parser->tok != ')') {
2704 increment = parse_expression_leave(parser, false, false, false);
2707 if (!ast_side_effects(increment)) {
2708 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2714 if (parser->tok != ')') {
2715 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2718 /* parse into the 'then' branch */
2719 if (!parser_next(parser)) {
2720 parseerror(parser, "expected for-loop body");
2723 if (!parse_statement_or_block(parser, &ontrue))
2727 cond = process_condition(parser, cond, &ifnot);
2731 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2732 *out = (ast_expression*)aloop;
2734 if (!parser_leaveblock(parser))
2738 if (initexpr) ast_delete(initexpr);
2739 if (cond) ast_delete(cond);
2740 if (increment) ast_delete(increment);
2741 (void)!parser_leaveblock(parser);
2745 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2747 ast_expression *exp = NULL;
2748 ast_return *ret = NULL;
2749 ast_value *expected = parser->function->vtype;
2751 lex_ctx ctx = parser_ctx(parser);
2753 (void)block; /* not touching */
2755 if (!parser_next(parser)) {
2756 parseerror(parser, "expected return expression");
2760 if (parser->tok != ';') {
2761 exp = parse_expression(parser, false, false);
2765 if (exp->expression.vtype != TYPE_NIL &&
2766 exp->expression.vtype != expected->expression.next->expression.vtype)
2768 parseerror(parser, "return with invalid expression");
2771 ret = ast_return_new(ctx, exp);
2777 if (!parser_next(parser))
2778 parseerror(parser, "parse error");
2779 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2780 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2782 ret = ast_return_new(ctx, NULL);
2784 *out = (ast_expression*)ret;
2788 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2791 unsigned int levels = 0;
2792 lex_ctx ctx = parser_ctx(parser);
2793 const char **loops = (is_continue ? parser->continues : parser->breaks);
2795 (void)block; /* not touching */
2796 if (!parser_next(parser)) {
2797 parseerror(parser, "expected semicolon or loop label");
2801 if (!vec_size(loops)) {
2803 parseerror(parser, "`continue` can only be used inside loops");
2805 parseerror(parser, "`break` can only be used inside loops or switches");
2808 if (parser->tok == TOKEN_IDENT) {
2809 if (!OPTS_FLAG(LOOP_LABELS))
2810 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2811 i = vec_size(loops);
2813 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2816 parseerror(parser, "no such loop to %s: `%s`",
2817 (is_continue ? "continue" : "break out of"),
2818 parser_tokval(parser));
2823 if (!parser_next(parser)) {
2824 parseerror(parser, "expected semicolon");
2829 if (parser->tok != ';') {
2830 parseerror(parser, "expected semicolon");
2834 if (!parser_next(parser))
2835 parseerror(parser, "parse error");
2837 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2841 /* returns true when it was a variable qualifier, false otherwise!
2842 * on error, cvq is set to CV_WRONG
2844 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2846 bool had_const = false;
2847 bool had_var = false;
2848 bool had_noref = false;
2849 bool had_attrib = false;
2850 bool had_static = false;
2855 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2857 /* parse an attribute */
2858 if (!parser_next(parser)) {
2859 parseerror(parser, "expected attribute after `[[`");
2863 if (!strcmp(parser_tokval(parser), "noreturn")) {
2864 flags |= AST_FLAG_NORETURN;
2865 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2866 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2871 else if (!strcmp(parser_tokval(parser), "noref")) {
2873 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2874 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2879 else if (!strcmp(parser_tokval(parser), "inline")) {
2880 flags |= AST_FLAG_INLINE;
2881 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2882 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2889 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2890 flags |= AST_FLAG_DEPRECATED;
2893 if (!parser_next(parser)) {
2894 parseerror(parser, "parse error in attribute");
2898 if (parser->tok == '(') {
2899 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2900 parseerror(parser, "`deprecated` attribute missing parameter");
2904 *message = util_strdup(parser_tokval(parser));
2906 if (!parser_next(parser)) {
2907 parseerror(parser, "parse error in attribute");
2911 if(parser->tok != ')') {
2912 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2916 if (!parser_next(parser)) {
2917 parseerror(parser, "parse error in attribute");
2922 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2923 parseerror(parser, "`deprecated` attribute expected `]]`");
2926 if (*message) mem_d(*message);
2934 /* Skip tokens until we hit a ]] */
2935 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2936 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2937 if (!parser_next(parser)) {
2938 parseerror(parser, "error inside attribute");
2945 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2947 else if (!strcmp(parser_tokval(parser), "const"))
2949 else if (!strcmp(parser_tokval(parser), "var"))
2951 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2953 else if (!strcmp(parser_tokval(parser), "noref"))
2955 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2960 if (!parser_next(parser))
2970 *is_static = had_static;
2974 parseerror(parser, "parse error after variable qualifier");
2979 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2980 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2985 /* skip the 'while' and get the body */
2986 if (!parser_next(parser)) {
2987 if (OPTS_FLAG(LOOP_LABELS))
2988 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2990 parseerror(parser, "expected 'switch' operand in parenthesis");
2994 if (parser->tok == ':') {
2995 if (!OPTS_FLAG(LOOP_LABELS))
2996 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2997 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2998 parseerror(parser, "expected loop label");
3001 label = util_strdup(parser_tokval(parser));
3002 if (!parser_next(parser)) {
3004 parseerror(parser, "expected 'switch' operand in parenthesis");
3009 if (parser->tok != '(') {
3010 parseerror(parser, "expected 'switch' operand in parenthesis");
3014 vec_push(parser->breaks, label);
3016 rv = parse_switch_go(parser, block, out);
3019 if (vec_last(parser->breaks) != label) {
3020 parseerror(parser, "internal error: label stack corrupted");
3026 vec_pop(parser->breaks);
3031 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3033 ast_expression *operand;
3036 ast_switch *switchnode;
3037 ast_switch_case swcase;
3040 bool noref, is_static;
3041 uint32_t qflags = 0;
3043 lex_ctx ctx = parser_ctx(parser);
3045 (void)block; /* not touching */
3048 /* parse into the expression */
3049 if (!parser_next(parser)) {
3050 parseerror(parser, "expected switch operand");
3053 /* parse the operand */
3054 operand = parse_expression_leave(parser, false, false, false);
3058 switchnode = ast_switch_new(ctx, operand);
3061 if (parser->tok != ')') {
3062 ast_delete(switchnode);
3063 parseerror(parser, "expected closing paren after 'switch' operand");
3067 /* parse over the opening paren */
3068 if (!parser_next(parser) || parser->tok != '{') {
3069 ast_delete(switchnode);
3070 parseerror(parser, "expected list of cases");
3074 if (!parser_next(parser)) {
3075 ast_delete(switchnode);
3076 parseerror(parser, "expected 'case' or 'default'");
3080 /* new block; allow some variables to be declared here */
3081 parser_enterblock(parser);
3084 if (parser->tok == TOKEN_IDENT)
3085 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3086 if (typevar || parser->tok == TOKEN_TYPENAME) {
3087 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3088 ast_delete(switchnode);
3093 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3095 if (cvq == CV_WRONG) {
3096 ast_delete(switchnode);
3099 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3100 ast_delete(switchnode);
3109 while (parser->tok != '}') {
3110 ast_block *caseblock;
3112 if (!strcmp(parser_tokval(parser), "case")) {
3113 if (!parser_next(parser)) {
3114 ast_delete(switchnode);
3115 parseerror(parser, "expected expression for case");
3118 swcase.value = parse_expression_leave(parser, false, false, false);
3119 if (!swcase.value) {
3120 ast_delete(switchnode);
3121 parseerror(parser, "expected expression for case");
3124 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3125 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3126 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3132 else if (!strcmp(parser_tokval(parser), "default")) {
3133 swcase.value = NULL;
3134 if (!parser_next(parser)) {
3135 ast_delete(switchnode);
3136 parseerror(parser, "expected colon");
3141 ast_delete(switchnode);
3142 parseerror(parser, "expected 'case' or 'default'");
3146 /* Now the colon and body */
3147 if (parser->tok != ':') {
3148 if (swcase.value) ast_unref(swcase.value);
3149 ast_delete(switchnode);
3150 parseerror(parser, "expected colon");
3154 if (!parser_next(parser)) {
3155 if (swcase.value) ast_unref(swcase.value);
3156 ast_delete(switchnode);
3157 parseerror(parser, "expected statements or case");
3160 caseblock = ast_block_new(parser_ctx(parser));
3162 if (swcase.value) ast_unref(swcase.value);
3163 ast_delete(switchnode);
3166 swcase.code = (ast_expression*)caseblock;
3167 vec_push(switchnode->cases, swcase);
3169 ast_expression *expr;
3170 if (parser->tok == '}')
3172 if (parser->tok == TOKEN_KEYWORD) {
3173 if (!strcmp(parser_tokval(parser), "case") ||
3174 !strcmp(parser_tokval(parser), "default"))
3179 if (!parse_statement(parser, caseblock, &expr, true)) {
3180 ast_delete(switchnode);
3185 if (!ast_block_add_expr(caseblock, expr)) {
3186 ast_delete(switchnode);
3192 parser_leaveblock(parser);
3195 if (parser->tok != '}') {
3196 ast_delete(switchnode);
3197 parseerror(parser, "expected closing paren of case list");
3200 if (!parser_next(parser)) {
3201 ast_delete(switchnode);
3202 parseerror(parser, "parse error after switch");
3205 *out = (ast_expression*)switchnode;
3209 /* parse computed goto sides */
3210 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3211 ast_expression *on_true;
3212 ast_expression *on_false;
3213 ast_expression *cond;
3218 if (ast_istype(*side, ast_ternary)) {
3219 ast_ternary *tern = (ast_ternary*)*side;
3220 on_true = parse_goto_computed(parser, &tern->on_true);
3221 on_false = parse_goto_computed(parser, &tern->on_false);
3223 if (!on_true || !on_false) {
3224 parseerror(parser, "expected label or expression in ternary");
3225 if (on_true) ast_unref(on_true);
3226 if (on_false) ast_unref(on_false);
3234 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3235 } else if (ast_istype(*side, ast_label)) {
3236 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3237 ast_goto_set_label(gt, ((ast_label*)*side));
3239 return (ast_expression*)gt;
3244 static bool parse_goto(parser_t *parser, ast_expression **out)
3246 ast_goto *gt = NULL;
3247 ast_expression *lbl;
3249 if (!parser_next(parser))
3252 if (parser->tok != TOKEN_IDENT) {
3253 ast_expression *expression;
3255 /* could be an expression i.e computed goto :-) */
3256 if (parser->tok != '(') {
3257 parseerror(parser, "expected label name after `goto`");
3261 /* failed to parse expression for goto */
3262 if (!(expression = parse_expression(parser, false, true)) ||
3263 !(*out = parse_goto_computed(parser, &expression))) {
3264 parseerror(parser, "invalid goto expression");
3265 ast_unref(expression);
3272 /* not computed goto */
3273 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3274 lbl = parser_find_label(parser, gt->name);
3276 if (!ast_istype(lbl, ast_label)) {
3277 parseerror(parser, "internal error: label is not an ast_label");
3281 ast_goto_set_label(gt, (ast_label*)lbl);
3284 vec_push(parser->gotos, gt);
3286 if (!parser_next(parser) || parser->tok != ';') {
3287 parseerror(parser, "semicolon expected after goto label");
3290 if (!parser_next(parser)) {
3291 parseerror(parser, "parse error after goto");
3295 *out = (ast_expression*)gt;
3299 static bool parse_skipwhite(parser_t *parser)
3302 if (!parser_next(parser))
3304 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3305 return parser->tok < TOKEN_ERROR;
3308 static bool parse_eol(parser_t *parser)
3310 if (!parse_skipwhite(parser))
3312 return parser->tok == TOKEN_EOL;
3315 static bool parse_pragma_do(parser_t *parser)
3317 if (!parser_next(parser) ||
3318 parser->tok != TOKEN_IDENT ||
3319 strcmp(parser_tokval(parser), "pragma"))
3321 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3324 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3325 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3329 if (!strcmp(parser_tokval(parser), "noref")) {
3330 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3331 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3334 parser->noref = !!parser_token(parser)->constval.i;
3335 if (!parse_eol(parser)) {
3336 parseerror(parser, "parse error after `noref` pragma");
3342 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3349 static bool parse_pragma(parser_t *parser)
3352 parser->lex->flags.preprocessing = true;
3353 parser->lex->flags.mergelines = true;
3354 rv = parse_pragma_do(parser);
3355 if (parser->tok != TOKEN_EOL) {
3356 parseerror(parser, "junk after pragma");
3359 parser->lex->flags.preprocessing = false;
3360 parser->lex->flags.mergelines = false;
3361 if (!parser_next(parser)) {
3362 parseerror(parser, "parse error after pragma");
3368 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3370 bool noref, is_static;
3372 uint32_t qflags = 0;
3373 ast_value *typevar = NULL;
3374 char *vstring = NULL;
3378 if (parser->tok == TOKEN_IDENT)
3379 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3381 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3383 /* local variable */
3385 parseerror(parser, "cannot declare a variable from here");
3388 if (opts.standard == COMPILER_QCC) {
3389 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3392 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3396 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3398 if (cvq == CV_WRONG)
3400 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3402 else if (parser->tok == TOKEN_KEYWORD)
3404 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3409 if (!parser_next(parser)) {
3410 parseerror(parser, "parse error after __builtin_debug_printtype");
3414 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3416 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3417 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3418 if (!parser_next(parser)) {
3419 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3425 if (!parse_statement(parser, block, out, allow_cases))
3428 con_out("__builtin_debug_printtype: got no output node\n");
3431 ast_type_to_string(*out, ty, sizeof(ty));
3432 con_out("__builtin_debug_printtype: `%s`\n", ty);
3437 else if (!strcmp(parser_tokval(parser), "return"))
3439 return parse_return(parser, block, out);
3441 else if (!strcmp(parser_tokval(parser), "if"))
3443 return parse_if(parser, block, out);
3445 else if (!strcmp(parser_tokval(parser), "while"))
3447 return parse_while(parser, block, out);
3449 else if (!strcmp(parser_tokval(parser), "do"))
3451 return parse_dowhile(parser, block, out);
3453 else if (!strcmp(parser_tokval(parser), "for"))
3455 if (opts.standard == COMPILER_QCC) {
3456 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3459 return parse_for(parser, block, out);
3461 else if (!strcmp(parser_tokval(parser), "break"))
3463 return parse_break_continue(parser, block, out, false);
3465 else if (!strcmp(parser_tokval(parser), "continue"))
3467 return parse_break_continue(parser, block, out, true);
3469 else if (!strcmp(parser_tokval(parser), "switch"))
3471 return parse_switch(parser, block, out);
3473 else if (!strcmp(parser_tokval(parser), "case") ||
3474 !strcmp(parser_tokval(parser), "default"))
3477 parseerror(parser, "unexpected 'case' label");
3482 else if (!strcmp(parser_tokval(parser), "goto"))
3484 return parse_goto(parser, out);
3486 else if (!strcmp(parser_tokval(parser), "typedef"))
3488 if (!parser_next(parser)) {
3489 parseerror(parser, "expected type definition after 'typedef'");
3492 return parse_typedef(parser);
3494 parseerror(parser, "Unexpected keyword");
3497 else if (parser->tok == '{')
3500 inner = parse_block(parser);
3503 *out = (ast_expression*)inner;
3506 else if (parser->tok == ':')
3510 if (!parser_next(parser)) {
3511 parseerror(parser, "expected label name");
3514 if (parser->tok != TOKEN_IDENT) {
3515 parseerror(parser, "label must be an identifier");
3518 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3520 if (!label->undefined) {
3521 parseerror(parser, "label `%s` already defined", label->name);
3524 label->undefined = false;
3527 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3528 vec_push(parser->labels, label);
3530 *out = (ast_expression*)label;
3531 if (!parser_next(parser)) {
3532 parseerror(parser, "parse error after label");
3535 for (i = 0; i < vec_size(parser->gotos); ++i) {
3536 if (!strcmp(parser->gotos[i]->name, label->name)) {
3537 ast_goto_set_label(parser->gotos[i], label);
3538 vec_remove(parser->gotos, i, 1);
3544 else if (parser->tok == ';')
3546 if (!parser_next(parser)) {
3547 parseerror(parser, "parse error after empty statement");
3554 ast_expression *exp = parse_expression(parser, false, false);
3558 if (!ast_side_effects(exp)) {
3559 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3566 static bool parse_enum(parser_t *parser)
3569 ast_value **values = NULL;
3570 ast_value *var = NULL;
3573 ast_expression *old;
3575 if (!parser_next(parser) || parser->tok != '{') {
3576 parseerror(parser, "expected `{` after `enum` keyword");
3581 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3582 if (parser->tok == '}') {
3583 /* allow an empty enum */
3586 parseerror(parser, "expected identifier or `}`");
3590 old = parser_find_field(parser, parser_tokval(parser));
3592 old = parser_find_global(parser, parser_tokval(parser));
3594 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3595 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3599 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3600 vec_push(values, var);
3601 var->cvq = CV_CONST;
3602 var->hasvalue = true;
3603 var->constval.vfloat = num++;
3605 parser_addglobal(parser, var->name, (ast_expression*)var);
3607 if (!parser_next(parser)) {
3608 parseerror(parser, "expected `=`, `}` or comma after identifier");
3612 if (parser->tok == ',')
3614 if (parser->tok == '}')
3616 if (parser->tok != '=') {
3617 parseerror(parser, "expected `=`, `}` or comma after identifier");
3621 if (!parser_next(parser)) {
3622 parseerror(parser, "expected expression after `=`");
3626 /* We got a value! */
3627 old = parse_expression_leave(parser, true, false, false);
3628 asvalue = (ast_value*)old;
3629 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3630 compile_error(ast_ctx(var), "constant value or expression expected");
3633 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3635 if (parser->tok == '}')
3637 if (parser->tok != ',') {
3638 parseerror(parser, "expected `}` or comma after expression");
3643 if (parser->tok != '}') {
3644 parseerror(parser, "internal error: breaking without `}`");
3648 if (!parser_next(parser) || parser->tok != ';') {
3649 parseerror(parser, "expected semicolon after enumeration");
3653 if (!parser_next(parser)) {
3654 parseerror(parser, "parse error after enumeration");
3666 static bool parse_block_into(parser_t *parser, ast_block *block)
3670 parser_enterblock(parser);
3672 if (!parser_next(parser)) { /* skip the '{' */
3673 parseerror(parser, "expected function body");
3677 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3679 ast_expression *expr = NULL;
3680 if (parser->tok == '}')
3683 if (!parse_statement(parser, block, &expr, false)) {
3684 /* parseerror(parser, "parse error"); */
3690 if (!ast_block_add_expr(block, expr)) {
3697 if (parser->tok != '}') {
3700 (void)parser_next(parser);
3704 if (!parser_leaveblock(parser))
3706 return retval && !!block;
3709 static ast_block* parse_block(parser_t *parser)
3712 block = ast_block_new(parser_ctx(parser));
3715 if (!parse_block_into(parser, block)) {
3716 ast_block_delete(block);
3722 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3724 if (parser->tok == '{') {
3725 *out = (ast_expression*)parse_block(parser);
3728 return parse_statement(parser, NULL, out, false);
3731 static bool create_vector_members(ast_value *var, ast_member **me)
3734 size_t len = strlen(var->name);
3736 for (i = 0; i < 3; ++i) {
3737 char *name = (char*)mem_a(len+3);
3738 memcpy(name, var->name, len);
3740 name[len+1] = 'x'+i;
3742 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3751 do { ast_member_delete(me[--i]); } while(i);
3755 static bool parse_function_body(parser_t *parser, ast_value *var)
3757 ast_block *block = NULL;
3762 ast_expression *framenum = NULL;
3763 ast_expression *nextthink = NULL;
3764 /* None of the following have to be deleted */
3765 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3766 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3767 bool has_frame_think;
3771 has_frame_think = false;
3772 old = parser->function;
3774 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3775 parseerror(parser, "gotos/labels leaking");
3779 if (var->expression.flags & AST_FLAG_VARIADIC) {
3780 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3781 "variadic function with implementation will not be able to access additional parameters"))
3787 if (parser->tok == '[') {
3788 /* got a frame definition: [ framenum, nextthink ]
3789 * this translates to:
3790 * self.frame = framenum;
3791 * self.nextthink = time + 0.1;
3792 * self.think = nextthink;
3796 fld_think = parser_find_field(parser, "think");
3797 fld_nextthink = parser_find_field(parser, "nextthink");
3798 fld_frame = parser_find_field(parser, "frame");
3799 if (!fld_think || !fld_nextthink || !fld_frame) {
3800 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3801 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3804 gbl_time = parser_find_global(parser, "time");
3805 gbl_self = parser_find_global(parser, "self");
3806 if (!gbl_time || !gbl_self) {
3807 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3808 parseerror(parser, "please declare the following globals: `time`, `self`");
3812 if (!parser_next(parser))
3815 framenum = parse_expression_leave(parser, true, false, false);
3817 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3820 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3821 ast_unref(framenum);
3822 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3826 if (parser->tok != ',') {
3827 ast_unref(framenum);
3828 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3829 parseerror(parser, "Got a %i\n", parser->tok);
3833 if (!parser_next(parser)) {
3834 ast_unref(framenum);
3838 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3840 /* qc allows the use of not-yet-declared functions here
3841 * - this automatically creates a prototype */
3842 ast_value *thinkfunc;
3843 ast_expression *functype = fld_think->expression.next;
3845 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3846 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3847 ast_unref(framenum);
3848 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3852 if (!parser_next(parser)) {
3853 ast_unref(framenum);
3854 ast_delete(thinkfunc);
3858 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3860 nextthink = (ast_expression*)thinkfunc;
3863 nextthink = parse_expression_leave(parser, true, false, false);
3865 ast_unref(framenum);
3866 parseerror(parser, "expected a think-function in [frame,think] notation");
3871 if (!ast_istype(nextthink, ast_value)) {
3872 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3876 if (retval && parser->tok != ']') {
3877 parseerror(parser, "expected closing `]` for [frame,think] notation");
3881 if (retval && !parser_next(parser)) {
3885 if (retval && parser->tok != '{') {
3886 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3891 ast_unref(nextthink);
3892 ast_unref(framenum);
3896 has_frame_think = true;
3899 block = ast_block_new(parser_ctx(parser));
3901 parseerror(parser, "failed to allocate block");
3902 if (has_frame_think) {
3903 ast_unref(nextthink);
3904 ast_unref(framenum);
3909 if (has_frame_think) {
3911 ast_expression *self_frame;
3912 ast_expression *self_nextthink;
3913 ast_expression *self_think;
3914 ast_expression *time_plus_1;
3915 ast_store *store_frame;
3916 ast_store *store_nextthink;
3917 ast_store *store_think;
3919 ctx = parser_ctx(parser);
3920 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3921 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3922 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3924 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3925 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3927 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3928 if (self_frame) ast_delete(self_frame);
3929 if (self_nextthink) ast_delete(self_nextthink);
3930 if (self_think) ast_delete(self_think);
3931 if (time_plus_1) ast_delete(time_plus_1);
3937 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3938 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3939 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3942 ast_delete(self_frame);
3945 if (!store_nextthink) {
3946 ast_delete(self_nextthink);
3950 ast_delete(self_think);
3954 if (store_frame) ast_delete(store_frame);
3955 if (store_nextthink) ast_delete(store_nextthink);
3956 if (store_think) ast_delete(store_think);
3959 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3960 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3961 !ast_block_add_expr(block, (ast_expression*)store_think))
3968 parseerror(parser, "failed to generate code for [frame,think]");
3969 ast_unref(nextthink);
3970 ast_unref(framenum);
3976 parser_enterblock(parser);
3978 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3980 ast_value *param = var->expression.params[parami];
3983 if (param->expression.vtype != TYPE_VECTOR &&
3984 (param->expression.vtype != TYPE_FIELD ||
3985 param->expression.next->expression.vtype != TYPE_VECTOR))
3990 if (!create_vector_members(param, me)) {
3991 ast_block_delete(block);
3995 for (e = 0; e < 3; ++e) {
3996 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3997 ast_block_collect(block, (ast_expression*)me[e]);
4001 func = ast_function_new(ast_ctx(var), var->name, var);
4003 parseerror(parser, "failed to allocate function for `%s`", var->name);
4004 ast_block_delete(block);
4007 vec_push(parser->functions, func);
4009 if (var->expression.flags & AST_FLAG_VARIADIC) {
4011 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4012 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4013 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4014 varargs->expression.count = 0;
4015 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4016 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4017 ast_delete(varargs);
4018 ast_block_delete(block);
4021 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4022 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4023 ast_delete(varargs);
4024 ast_block_delete(block);
4027 func->varargs = varargs;
4030 parser->function = func;
4031 if (!parse_block_into(parser, block)) {
4032 ast_block_delete(block);
4036 vec_push(func->blocks, block);
4038 parser->function = old;
4039 if (!parser_leaveblock(parser))
4041 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4042 parseerror(parser, "internal error: local scopes left");
4046 if (parser->tok == ';')
4047 return parser_next(parser);
4048 else if (opts.standard == COMPILER_QCC)
4049 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4053 vec_pop(parser->functions);
4054 ast_function_delete(func);
4055 var->constval.vfunc = NULL;
4058 (void)!parser_leaveblock(parser);
4059 parser->function = old;
4063 static ast_expression *array_accessor_split(
4068 ast_expression *left,
4069 ast_expression *right
4075 lex_ctx ctx = ast_ctx(array);
4077 if (!left || !right) {
4078 if (left) ast_delete(left);
4079 if (right) ast_delete(right);
4083 cmp = ast_binary_new(ctx, INSTR_LT,
4084 (ast_expression*)index,
4085 (ast_expression*)parser_const_float(parser, middle));
4089 parseerror(parser, "internal error: failed to create comparison for array setter");
4093 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4095 ast_delete(cmp); /* will delete left and right */
4096 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4100 return (ast_expression*)ifthen;
4103 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4105 lex_ctx ctx = ast_ctx(array);
4107 if (from+1 == afterend) {
4108 /* set this value */
4111 ast_array_index *subscript;
4113 int assignop = type_store_instr[value->expression.vtype];
4115 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4116 assignop = INSTR_STORE_V;
4118 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4122 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4124 ast_delete(subscript);
4128 block = ast_block_new(ctx);
4134 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4139 ret = ast_return_new(ctx, NULL);
4145 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4150 return (ast_expression*)block;
4152 ast_expression *left, *right;
4153 size_t diff = afterend - from;
4154 size_t middle = from + diff/2;
4155 left = array_setter_node(parser, array, index, value, from, middle);
4156 right = array_setter_node(parser, array, index, value, middle, afterend);
4157 return array_accessor_split(parser, array, index, middle, left, right);
4161 static ast_expression *array_field_setter_node(
4170 lex_ctx ctx = ast_ctx(array);
4172 if (from+1 == afterend) {
4173 /* set this value */
4176 ast_entfield *entfield;
4177 ast_array_index *subscript;
4179 int assignop = type_storep_instr[value->expression.vtype];
4181 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4182 assignop = INSTR_STOREP_V;
4184 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4188 entfield = ast_entfield_new_force(ctx,
4189 (ast_expression*)entity,
4190 (ast_expression*)subscript,
4191 (ast_expression*)subscript);
4193 ast_delete(subscript);
4197 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4199 ast_delete(entfield);
4203 block = ast_block_new(ctx);
4209 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4214 ret = ast_return_new(ctx, NULL);
4220 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4225 return (ast_expression*)block;
4227 ast_expression *left, *right;
4228 size_t diff = afterend - from;
4229 size_t middle = from + diff/2;
4230 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4231 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4232 return array_accessor_split(parser, array, index, middle, left, right);
4236 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4238 lex_ctx ctx = ast_ctx(array);
4240 if (from+1 == afterend) {
4242 ast_array_index *subscript;
4244 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4248 ret = ast_return_new(ctx, (ast_expression*)subscript);
4250 ast_delete(subscript);
4254 return (ast_expression*)ret;
4256 ast_expression *left, *right;
4257 size_t diff = afterend - from;
4258 size_t middle = from + diff/2;
4259 left = array_getter_node(parser, array, index, from, middle);
4260 right = array_getter_node(parser, array, index, middle, afterend);
4261 return array_accessor_split(parser, array, index, middle, left, right);
4265 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4267 ast_function *func = NULL;
4268 ast_value *fval = NULL;
4269 ast_block *body = NULL;
4271 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4273 parseerror(parser, "failed to create accessor function value");
4277 func = ast_function_new(ast_ctx(array), funcname, fval);
4280 parseerror(parser, "failed to create accessor function node");
4284 body = ast_block_new(ast_ctx(array));
4286 parseerror(parser, "failed to create block for array accessor");
4292 vec_push(func->blocks, body);
4295 vec_push(parser->accessors, fval);
4300 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4302 ast_value *index = NULL;
4303 ast_value *value = NULL;
4307 if (!ast_istype(array->expression.next, ast_value)) {
4308 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4312 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4314 func = fval->constval.vfunc;
4315 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4317 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4318 value = ast_value_copy((ast_value*)array->expression.next);
4320 if (!index || !value) {
4321 parseerror(parser, "failed to create locals for array accessor");
4324 (void)!ast_value_set_name(value, "value"); /* not important */
4325 vec_push(fval->expression.params, index);
4326 vec_push(fval->expression.params, value);
4328 array->setter = fval;
4331 if (index) ast_delete(index);
4332 if (value) ast_delete(value);
4338 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4340 ast_expression *root = NULL;
4341 root = array_setter_node(parser, array,
4342 array->setter->expression.params[0],
4343 array->setter->expression.params[1],
4344 0, array->expression.count);
4346 parseerror(parser, "failed to build accessor search tree");
4349 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4356 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4358 if (!parser_create_array_setter_proto(parser, array, funcname))
4360 return parser_create_array_setter_impl(parser, array);
4363 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4365 ast_expression *root = NULL;
4366 ast_value *entity = NULL;
4367 ast_value *index = NULL;
4368 ast_value *value = NULL;
4372 if (!ast_istype(array->expression.next, ast_value)) {
4373 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4377 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4379 func = fval->constval.vfunc;
4380 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4382 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4383 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4384 value = ast_value_copy((ast_value*)array->expression.next);
4385 if (!entity || !index || !value) {
4386 parseerror(parser, "failed to create locals for array accessor");
4389 (void)!ast_value_set_name(value, "value"); /* not important */
4390 vec_push(fval->expression.params, entity);
4391 vec_push(fval->expression.params, index);
4392 vec_push(fval->expression.params, value);
4394 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4396 parseerror(parser, "failed to build accessor search tree");
4400 array->setter = fval;
4401 return ast_block_add_expr(func->blocks[0], root);
4403 if (entity) ast_delete(entity);
4404 if (index) ast_delete(index);
4405 if (value) ast_delete(value);
4406 if (root) ast_delete(root);
4412 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4414 ast_value *index = NULL;
4418 /* NOTE: checking array->expression.next rather than elemtype since
4419 * for fields elemtype is a temporary fieldtype.
4421 if (!ast_istype(array->expression.next, ast_value)) {
4422 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4426 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4428 func = fval->constval.vfunc;
4429 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4431 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4434 parseerror(parser, "failed to create locals for array accessor");
4437 vec_push(fval->expression.params, index);
4439 array->getter = fval;
4442 if (index) ast_delete(index);
4448 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4450 ast_expression *root = NULL;
4452 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4454 parseerror(parser, "failed to build accessor search tree");
4457 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4464 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4466 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4468 return parser_create_array_getter_impl(parser, array);
4471 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4472 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4480 bool variadic = false;
4481 ast_value *varparam = NULL;
4482 char *argcounter = NULL;
4484 ctx = parser_ctx(parser);
4486 /* for the sake of less code we parse-in in this function */
4487 if (!parser_next(parser)) {
4488 parseerror(parser, "expected parameter list");
4494 /* parse variables until we hit a closing paren */
4495 while (parser->tok != ')') {
4497 /* there must be commas between them */
4498 if (parser->tok != ',') {
4499 parseerror(parser, "expected comma or end of parameter list");
4502 if (!parser_next(parser)) {
4503 parseerror(parser, "expected parameter");
4509 if (parser->tok == TOKEN_DOTS) {
4510 /* '...' indicates a varargs function */
4512 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4513 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4516 if (parser->tok == TOKEN_IDENT) {
4517 argcounter = util_strdup(parser_tokval(parser));
4518 if (!parser_next(parser) || parser->tok != ')') {
4519 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4526 /* for anything else just parse a typename */
4527 param = parse_typename(parser, NULL, NULL);
4530 vec_push(params, param);
4531 if (param->expression.vtype >= TYPE_VARIANT) {
4532 char tname[1024]; /* typename is reserved in C++ */
4533 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4534 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4537 /* type-restricted varargs */
4538 if (parser->tok == TOKEN_DOTS) {
4540 varparam = vec_last(params);
4542 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4543 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4546 if (parser->tok == TOKEN_IDENT) {
4547 argcounter = util_strdup(parser_tokval(parser));
4548 if (!parser_next(parser) || parser->tok != ')') {
4549 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4557 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4561 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4562 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4565 if (!parser_next(parser)) {
4566 parseerror(parser, "parse error after typename");
4570 /* now turn 'var' into a function type */
4571 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4572 fval->expression.next = (ast_expression*)var;
4574 fval->expression.flags |= AST_FLAG_VARIADIC;
4577 var->expression.params = params;
4578 var->expression.varparam = (ast_expression*)varparam;
4579 var->argcounter = argcounter;
4588 for (i = 0; i < vec_size(params); ++i)
4589 ast_delete(params[i]);
4594 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4596 ast_expression *cexp;
4597 ast_value *cval, *tmp;
4600 ctx = parser_ctx(parser);
4602 if (!parser_next(parser)) {
4604 parseerror(parser, "expected array-size");
4608 cexp = parse_expression_leave(parser, true, false, false);
4610 if (!cexp || !ast_istype(cexp, ast_value)) {
4614 parseerror(parser, "expected array-size as constant positive integer");
4617 cval = (ast_value*)cexp;
4619 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4620 tmp->expression.next = (ast_expression*)var;
4623 if (cval->expression.vtype == TYPE_INTEGER)
4624 tmp->expression.count = cval->constval.vint;
4625 else if (cval->expression.vtype == TYPE_FLOAT)
4626 tmp->expression.count = cval->constval.vfloat;
4630 parseerror(parser, "array-size must be a positive integer constant");
4635 if (parser->tok != ']') {
4637 parseerror(parser, "expected ']' after array-size");
4640 if (!parser_next(parser)) {
4642 parseerror(parser, "error after parsing array size");
4648 /* Parse a complete typename.
4649 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4650 * but when parsing variables separated by comma
4651 * 'storebase' should point to where the base-type should be kept.
4652 * The base type makes up every bit of type information which comes *before* the
4655 * The following will be parsed in its entirety:
4657 * The 'basetype' in this case is 'void()'
4658 * and if there's a comma after it, say:
4660 * then the type-information 'void()' can be stored in 'storebase'
4662 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4664 ast_value *var, *tmp;
4667 const char *name = NULL;
4668 bool isfield = false;
4669 bool wasarray = false;
4670 size_t morefields = 0;
4672 ctx = parser_ctx(parser);
4674 /* types may start with a dot */
4675 if (parser->tok == '.') {
4677 /* if we parsed a dot we need a typename now */
4678 if (!parser_next(parser)) {
4679 parseerror(parser, "expected typename for field definition");
4683 /* Further dots are handled seperately because they won't be part of the
4686 while (parser->tok == '.') {
4688 if (!parser_next(parser)) {
4689 parseerror(parser, "expected typename for field definition");
4694 if (parser->tok == TOKEN_IDENT)
4695 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4696 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4697 parseerror(parser, "expected typename");
4701 /* generate the basic type value */
4702 if (cached_typedef) {
4703 var = ast_value_copy(cached_typedef);
4704 ast_value_set_name(var, "<type(from_def)>");
4706 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4708 for (; morefields; --morefields) {
4709 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4710 tmp->expression.next = (ast_expression*)var;
4714 /* do not yet turn into a field - remember:
4715 * .void() foo; is a field too
4716 * .void()() foo; is a function
4720 if (!parser_next(parser)) {
4722 parseerror(parser, "parse error after typename");
4726 /* an opening paren now starts the parameter-list of a function
4727 * this is where original-QC has parameter lists.
4728 * We allow a single parameter list here.
4729 * Much like fteqcc we don't allow `float()() x`
4731 if (parser->tok == '(') {
4732 var = parse_parameter_list(parser, var);
4737 /* store the base if requested */
4739 *storebase = ast_value_copy(var);
4741 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4742 tmp->expression.next = (ast_expression*)*storebase;
4747 /* there may be a name now */
4748 if (parser->tok == TOKEN_IDENT) {
4749 name = util_strdup(parser_tokval(parser));
4751 if (!parser_next(parser)) {
4753 parseerror(parser, "error after variable or field declaration");
4758 /* now this may be an array */
4759 if (parser->tok == '[') {
4761 var = parse_arraysize(parser, var);
4766 /* This is the point where we can turn it into a field */
4768 /* turn it into a field if desired */
4769 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4770 tmp->expression.next = (ast_expression*)var;
4774 /* now there may be function parens again */
4775 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4776 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4777 if (parser->tok == '(' && wasarray)
4778 parseerror(parser, "arrays as part of a return type is not supported");
4779 while (parser->tok == '(') {
4780 var = parse_parameter_list(parser, var);
4789 /* finally name it */
4791 if (!ast_value_set_name(var, name)) {
4793 parseerror(parser, "internal error: failed to set name");
4796 /* free the name, ast_value_set_name duplicates */
4803 static bool parse_typedef(parser_t *parser)
4805 ast_value *typevar, *oldtype;
4806 ast_expression *old;
4808 typevar = parse_typename(parser, NULL, NULL);
4813 if ( (old = parser_find_var(parser, typevar->name)) ) {
4814 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4815 " -> `%s` has been declared here: %s:%i",
4816 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4817 ast_delete(typevar);
4821 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4822 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4823 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4824 ast_delete(typevar);
4828 vec_push(parser->_typedefs, typevar);
4829 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4831 if (parser->tok != ';') {
4832 parseerror(parser, "expected semicolon after typedef");
4835 if (!parser_next(parser)) {
4836 parseerror(parser, "parse error after typedef");
4843 static const char *cvq_to_str(int cvq) {
4845 case CV_NONE: return "none";
4846 case CV_VAR: return "`var`";
4847 case CV_CONST: return "`const`";
4848 default: return "<INVALID>";
4852 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4855 if (proto->cvq != var->cvq) {
4856 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4857 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4858 parser->tok == '='))
4860 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4861 "`%s` declared with different qualifiers: %s\n"
4862 " -> previous declaration here: %s:%i uses %s",
4863 var->name, cvq_to_str(var->cvq),
4864 ast_ctx(proto).file, ast_ctx(proto).line,
4865 cvq_to_str(proto->cvq));
4868 av = (var ->expression.flags & AST_FLAG_NORETURN);
4869 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4871 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4872 "`%s` declared with different attributes%s\n"
4873 " -> previous declaration here: %s:%i",
4874 var->name, (av ? ": noreturn" : ""),
4875 ast_ctx(proto).file, ast_ctx(proto).line,
4876 (ao ? ": noreturn" : ""));
4881 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)
4885 ast_expression *old;
4889 ast_value *basetype = NULL;
4891 bool isparam = false;
4892 bool isvector = false;
4893 bool cleanvar = true;
4894 bool wasarray = false;
4898 if (!localblock && is_static)
4899 parseerror(parser, "`static` qualifier is not supported in global scope");
4901 /* get the first complete variable */
4902 var = parse_typename(parser, &basetype, cached_typedef);
4905 ast_delete(basetype);
4913 /* Part 0: finish the type */
4914 if (parser->tok == '(') {
4915 if (opts.standard == COMPILER_QCC)
4916 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4917 var = parse_parameter_list(parser, var);
4923 /* we only allow 1-dimensional arrays */
4924 if (parser->tok == '[') {
4926 var = parse_arraysize(parser, var);
4932 if (parser->tok == '(' && wasarray) {
4933 parseerror(parser, "arrays as part of a return type is not supported");
4934 /* we'll still parse the type completely for now */
4936 /* for functions returning functions */
4937 while (parser->tok == '(') {
4938 if (opts.standard == COMPILER_QCC)
4939 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4940 var = parse_parameter_list(parser, var);
4947 var->cvq = qualifier;
4948 var->expression.flags |= qflags;
4949 if (var->expression.flags & AST_FLAG_DEPRECATED)
4950 var->desc = vstring;
4953 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4954 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4955 * is then filled with the previous definition and the parameter-names replaced.
4957 if (!strcmp(var->name, "nil")) {
4958 if (OPTS_FLAG(UNTYPED_NIL)) {
4959 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4960 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4962 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4965 /* Deal with end_sys_ vars */
4967 if (!strcmp(var->name, "end_sys_globals")) {
4969 parser->crc_globals = vec_size(parser->globals);
4972 else if (!strcmp(var->name, "end_sys_fields")) {
4974 parser->crc_fields = vec_size(parser->fields);
4977 if (was_end && var->expression.vtype == TYPE_FIELD) {
4978 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4979 "global '%s' hint should not be a field",
4980 parser_tokval(parser)))
4987 if (!nofields && var->expression.vtype == TYPE_FIELD)
4989 /* deal with field declarations */
4990 old = parser_find_field(parser, var->name);
4992 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4993 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5002 parseerror(parser, "field `%s` already declared here: %s:%i",
5003 var->name, ast_ctx(old).file, ast_ctx(old).line);
5008 if (opts.standard == COMPILER_QCC &&
5009 (old = parser_find_global(parser, var->name)))
5011 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5012 parseerror(parser, "field `%s` already declared here: %s:%i",
5013 var->name, ast_ctx(old).file, ast_ctx(old).line);
5020 /* deal with other globals */
5021 old = parser_find_global(parser, var->name);
5022 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5024 /* This is a function which had a prototype */
5025 if (!ast_istype(old, ast_value)) {
5026 parseerror(parser, "internal error: prototype is not an ast_value");
5030 proto = (ast_value*)old;
5031 proto->desc = var->desc;
5032 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5033 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5035 ast_ctx(proto).file, ast_ctx(proto).line);
5039 /* we need the new parameter-names */
5040 for (i = 0; i < vec_size(proto->expression.params); ++i)
5041 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5042 if (!parser_check_qualifiers(parser, var, proto)) {
5049 proto->expression.flags |= var->expression.flags;
5057 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5058 "global `%s` already declared here: %s:%i",
5059 var->name, ast_ctx(old).file, ast_ctx(old).line))
5064 proto = (ast_value*)old;
5065 if (!ast_istype(old, ast_value)) {
5066 parseerror(parser, "internal error: not an ast_value");
5071 if (!parser_check_qualifiers(parser, var, proto)) {
5076 proto->expression.flags |= var->expression.flags;
5080 if (opts.standard == COMPILER_QCC &&
5081 (old = parser_find_field(parser, var->name)))
5083 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5084 parseerror(parser, "global `%s` already declared here: %s:%i",
5085 var->name, ast_ctx(old).file, ast_ctx(old).line);
5092 else /* it's not a global */
5094 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5095 if (old && !isparam) {
5096 parseerror(parser, "local `%s` already declared here: %s:%i",
5097 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5101 old = parser_find_local(parser, var->name, 0, &isparam);
5102 if (old && isparam) {
5103 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5104 "local `%s` is shadowing a parameter", var->name))
5106 parseerror(parser, "local `%s` already declared here: %s:%i",
5107 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5111 if (opts.standard != COMPILER_GMQCC) {
5119 /* in a noref section we simply bump the usecount */
5120 if (noref || parser->noref)
5124 * Create the global/local, and deal with vector types.
5127 if (var->expression.vtype == TYPE_VECTOR)
5129 else if (var->expression.vtype == TYPE_FIELD &&
5130 var->expression.next->expression.vtype == TYPE_VECTOR)
5134 if (!create_vector_members(var, me)) {
5141 /* deal with global variables, fields, functions */
5142 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5143 var->isfield = true;
5144 vec_push(parser->fields, (ast_expression*)var);
5145 util_htset(parser->htfields, var->name, var);
5147 for (i = 0; i < 3; ++i) {
5148 vec_push(parser->fields, (ast_expression*)me[i]);
5149 util_htset(parser->htfields, me[i]->name, me[i]);
5154 parser_addglobal(parser, var->name, (ast_expression*)var);
5156 for (i = 0; i < 3; ++i) {
5157 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5163 /* a static adds itself to be generated like any other global
5164 * but is added to the local namespace instead
5166 char *defname = NULL;
5167 size_t prefix_len, ln;
5169 ln = strlen(parser->function->name);
5170 vec_append(defname, ln, parser->function->name);
5172 vec_append(defname, 2, "::");
5173 /* remember the length up to here */
5174 prefix_len = vec_size(defname);
5176 /* Add it to the local scope */
5177 util_htset(vec_last(parser->variables), var->name, (void*)var);
5181 vec_last(parser->correct_variables),
5182 &vec_last(parser->correct_variables_score),
5186 /* now rename the global */
5187 ln = strlen(var->name);
5188 vec_append(defname, ln, var->name);
5189 ast_value_set_name(var, defname);
5191 /* push it to the to-be-generated globals */
5192 vec_push(parser->globals, (ast_expression*)var);
5194 /* same game for the vector members */
5196 for (i = 0; i < 3; ++i) {
5197 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5201 vec_last(parser->correct_variables),
5202 &vec_last(parser->correct_variables_score),
5206 vec_shrinkto(defname, prefix_len);
5207 ln = strlen(me[i]->name);
5208 vec_append(defname, ln, me[i]->name);
5209 ast_member_set_name(me[i], defname);
5211 vec_push(parser->globals, (ast_expression*)me[i]);
5216 vec_push(localblock->locals, var);
5217 parser_addlocal(parser, var->name, (ast_expression*)var);
5219 for (i = 0; i < 3; ++i) {
5220 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5221 ast_block_collect(localblock, (ast_expression*)me[i]);
5227 me[0] = me[1] = me[2] = NULL;
5232 if (var->expression.vtype == TYPE_ARRAY) {
5234 snprintf(name, sizeof(name), "%s##SET", var->name);
5235 if (!parser_create_array_setter(parser, var, name))
5237 snprintf(name, sizeof(name), "%s##GET", var->name);
5238 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5241 else if (!localblock && !nofields &&
5242 var->expression.vtype == TYPE_FIELD &&
5243 var->expression.next->expression.vtype == TYPE_ARRAY)
5246 ast_expression *telem;
5248 ast_value *array = (ast_value*)var->expression.next;
5250 if (!ast_istype(var->expression.next, ast_value)) {
5251 parseerror(parser, "internal error: field element type must be an ast_value");
5255 snprintf(name, sizeof(name), "%s##SETF", var->name);
5256 if (!parser_create_array_field_setter(parser, array, name))
5259 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5260 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5261 tfield->expression.next = telem;
5262 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5263 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5271 if (parser->tok == ';') {
5272 ast_delete(basetype);
5273 if (!parser_next(parser)) {
5274 parseerror(parser, "error after variable declaration");
5280 if (parser->tok == ',')
5284 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5287 parseerror(parser, "missing comma or semicolon while parsing variables");
5291 if (localblock && opts.standard == COMPILER_QCC) {
5292 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5293 "initializing expression turns variable `%s` into a constant in this standard",
5300 if (parser->tok != '{') {
5301 if (parser->tok != '=') {
5302 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5306 if (!parser_next(parser)) {
5307 parseerror(parser, "error parsing initializer");
5311 else if (opts.standard == COMPILER_QCC) {
5312 parseerror(parser, "expected '=' before function body in this standard");
5315 if (parser->tok == '#') {
5316 ast_function *func = NULL;
5319 parseerror(parser, "cannot declare builtins within functions");
5322 if (var->expression.vtype != TYPE_FUNCTION) {
5323 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5326 if (!parser_next(parser)) {
5327 parseerror(parser, "expected builtin number");
5330 if (parser->tok != TOKEN_INTCONST) {
5331 parseerror(parser, "builtin number must be an integer constant");
5334 if (parser_token(parser)->constval.i < 0) {
5335 parseerror(parser, "builtin number must be an integer greater than zero");
5339 if (var->hasvalue) {
5340 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5341 "builtin `%s` has already been defined\n"
5342 " -> previous declaration here: %s:%i",
5343 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5347 func = ast_function_new(ast_ctx(var), var->name, var);
5349 parseerror(parser, "failed to allocate function for `%s`", var->name);
5352 vec_push(parser->functions, func);
5354 func->builtin = -parser_token(parser)->constval.i-1;
5357 if (!parser_next(parser)) {
5358 parseerror(parser, "expected comma or semicolon");
5360 ast_function_delete(func);
5361 var->constval.vfunc = NULL;
5365 else if (parser->tok == '{' || parser->tok == '[')
5368 parseerror(parser, "cannot declare functions within functions");
5373 ast_ctx(proto) = parser_ctx(parser);
5375 if (!parse_function_body(parser, var))
5377 ast_delete(basetype);
5378 for (i = 0; i < vec_size(parser->gotos); ++i)
5379 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5380 vec_free(parser->gotos);
5381 vec_free(parser->labels);
5384 ast_expression *cexp;
5387 cexp = parse_expression_leave(parser, true, false, false);
5392 cval = (ast_value*)cexp;
5393 if (cval != parser->nil &&
5394 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5397 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5401 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5402 qualifier != CV_VAR)
5404 var->cvq = CV_CONST;
5406 if (cval == parser->nil)
5407 var->expression.flags |= AST_FLAG_INITIALIZED;
5410 var->hasvalue = true;
5411 if (cval->expression.vtype == TYPE_STRING)
5412 var->constval.vstring = parser_strdup(cval->constval.vstring);
5413 else if (cval->expression.vtype == TYPE_FIELD)
5414 var->constval.vfield = cval;
5416 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5422 shunt sy = { NULL, NULL };
5425 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5426 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5427 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5428 if (!parser_sy_apply_operator(parser, &sy))
5431 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5432 parseerror(parser, "internal error: leaked operands");
5433 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5443 if (parser->tok == ',') {
5444 if (!parser_next(parser)) {
5445 parseerror(parser, "expected another variable");
5449 if (parser->tok != TOKEN_IDENT) {
5450 parseerror(parser, "expected another variable");
5453 var = ast_value_copy(basetype);
5455 ast_value_set_name(var, parser_tokval(parser));
5456 if (!parser_next(parser)) {
5457 parseerror(parser, "error parsing variable declaration");
5463 if (parser->tok != ';') {
5464 parseerror(parser, "missing semicolon after variables");
5468 if (!parser_next(parser)) {
5469 parseerror(parser, "parse error after variable declaration");
5473 ast_delete(basetype);
5477 if (cleanvar && var)
5479 ast_delete(basetype);
5483 ast_delete(basetype);
5484 if (cleanvar && var)
5486 if (me[0]) ast_member_delete(me[0]);
5487 if (me[1]) ast_member_delete(me[1]);
5488 if (me[2]) ast_member_delete(me[2]);
5492 static bool parser_global_statement(parser_t *parser)
5496 bool is_static = false;
5497 uint32_t qflags = 0;
5498 ast_value *istype = NULL;
5499 char *vstring = NULL;
5501 if (parser->tok == TOKEN_IDENT)
5502 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5504 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5506 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5508 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5510 if (cvq == CV_WRONG)
5512 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5514 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5516 return parse_enum(parser);
5518 else if (parser->tok == TOKEN_KEYWORD)
5520 if (!strcmp(parser_tokval(parser), "typedef")) {
5521 if (!parser_next(parser)) {
5522 parseerror(parser, "expected type definition after 'typedef'");
5525 return parse_typedef(parser);
5527 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5530 else if (parser->tok == '#')
5532 return parse_pragma(parser);
5534 else if (parser->tok == '$')
5536 if (!parser_next(parser)) {
5537 parseerror(parser, "parse error");
5543 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5549 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5551 return util_crc16(old, str, strlen(str));
5554 static void progdefs_crc_file(const char *str)
5556 /* write to progdefs.h here */
5560 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5562 old = progdefs_crc_sum(old, str);
5563 progdefs_crc_file(str);
5567 static void generate_checksum(parser_t *parser)
5569 uint16_t crc = 0xFFFF;
5573 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5574 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5576 progdefs_crc_file("\tint\tpad;\n");
5577 progdefs_crc_file("\tint\tofs_return[3];\n");
5578 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5579 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5580 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5581 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5582 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5583 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5584 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5585 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5587 for (i = 0; i < parser->crc_globals; ++i) {
5588 if (!ast_istype(parser->globals[i], ast_value))
5590 value = (ast_value*)(parser->globals[i]);
5591 switch (value->expression.vtype) {
5592 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5593 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5594 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5595 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5597 crc = progdefs_crc_both(crc, "\tint\t");
5600 crc = progdefs_crc_both(crc, value->name);
5601 crc = progdefs_crc_both(crc, ";\n");
5603 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5604 for (i = 0; i < parser->crc_fields; ++i) {
5605 if (!ast_istype(parser->fields[i], ast_value))
5607 value = (ast_value*)(parser->fields[i]);
5608 switch (value->expression.next->expression.vtype) {
5609 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5610 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5611 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5612 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5614 crc = progdefs_crc_both(crc, "\tint\t");
5617 crc = progdefs_crc_both(crc, value->name);
5618 crc = progdefs_crc_both(crc, ";\n");
5620 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5625 static parser_t *parser;
5632 parser = (parser_t*)mem_a(sizeof(parser_t));
5636 memset(parser, 0, sizeof(*parser));
5638 for (i = 0; i < operator_count; ++i) {
5639 if (operators[i].id == opid1('=')) {
5640 parser->assign_op = operators+i;
5644 if (!parser->assign_op) {
5645 printf("internal error: initializing parser: failed to find assign operator\n");
5650 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5651 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5652 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5653 vec_push(parser->_blocktypedefs, 0);
5656 vec_push(parser->correct_variables, correct_trie_new());
5657 vec_push(parser->correct_variables_score, NULL);
5659 empty_ctx.file = "<internal>";
5661 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5662 parser->nil->cvq = CV_CONST;
5663 if (OPTS_FLAG(UNTYPED_NIL))
5664 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5666 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5667 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5668 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5670 if (opts.add_info) {
5671 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5672 parser->reserved_version->cvq = CV_CONST;
5673 parser->reserved_version->hasvalue = true;
5674 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5675 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5677 parser->reserved_version = NULL;
5682 bool parser_compile()
5684 /* initial lexer/parser state */
5685 parser->lex->flags.noops = true;
5687 if (parser_next(parser))
5689 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5691 if (!parser_global_statement(parser)) {
5692 if (parser->tok == TOKEN_EOF)
5693 parseerror(parser, "unexpected eof");
5694 else if (compile_errors)
5695 parseerror(parser, "there have been errors, bailing out");
5696 lex_close(parser->lex);
5702 parseerror(parser, "parse error");
5703 lex_close(parser->lex);
5708 lex_close(parser->lex);
5711 return !compile_errors;
5714 bool parser_compile_file(const char *filename)
5716 parser->lex = lex_open(filename);
5718 con_err("failed to open file \"%s\"\n", filename);
5721 return parser_compile();
5724 bool parser_compile_string(const char *name, const char *str, size_t len)
5726 parser->lex = lex_open_string(str, len, name);
5728 con_err("failed to create lexer for string \"%s\"\n", name);
5731 return parser_compile();
5734 void parser_cleanup()
5737 for (i = 0; i < vec_size(parser->accessors); ++i) {
5738 ast_delete(parser->accessors[i]->constval.vfunc);
5739 parser->accessors[i]->constval.vfunc = NULL;
5740 ast_delete(parser->accessors[i]);
5742 for (i = 0; i < vec_size(parser->functions); ++i) {
5743 ast_delete(parser->functions[i]);
5745 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5746 ast_delete(parser->imm_vector[i]);
5748 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5749 ast_delete(parser->imm_string[i]);
5751 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5752 ast_delete(parser->imm_float[i]);
5754 for (i = 0; i < vec_size(parser->fields); ++i) {
5755 ast_delete(parser->fields[i]);
5757 for (i = 0; i < vec_size(parser->globals); ++i) {
5758 ast_delete(parser->globals[i]);
5760 vec_free(parser->accessors);
5761 vec_free(parser->functions);
5762 vec_free(parser->imm_vector);
5763 vec_free(parser->imm_string);
5764 vec_free(parser->imm_float);
5765 vec_free(parser->globals);
5766 vec_free(parser->fields);
5768 for (i = 0; i < vec_size(parser->variables); ++i)
5769 util_htdel(parser->variables[i]);
5770 vec_free(parser->variables);
5771 vec_free(parser->_blocklocals);
5772 vec_free(parser->_locals);
5775 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5776 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5778 vec_free(parser->correct_variables);
5779 vec_free(parser->correct_variables_score);
5782 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5783 ast_delete(parser->_typedefs[i]);
5784 vec_free(parser->_typedefs);
5785 for (i = 0; i < vec_size(parser->typedefs); ++i)
5786 util_htdel(parser->typedefs[i]);
5787 vec_free(parser->typedefs);
5788 vec_free(parser->_blocktypedefs);
5790 vec_free(parser->_block_ctx);
5792 vec_free(parser->labels);
5793 vec_free(parser->gotos);
5794 vec_free(parser->breaks);
5795 vec_free(parser->continues);
5797 ast_value_delete(parser->nil);
5799 ast_value_delete(parser->const_vec[0]);
5800 ast_value_delete(parser->const_vec[1]);
5801 ast_value_delete(parser->const_vec[2]);
5806 bool parser_finish(const char *output)
5812 if (compile_errors) {
5813 con_out("*** there were compile errors\n");
5817 ir = ir_builder_new("gmqcc_out");
5819 con_out("failed to allocate builder\n");
5823 for (i = 0; i < vec_size(parser->fields); ++i) {
5826 if (!ast_istype(parser->fields[i], ast_value))
5828 field = (ast_value*)parser->fields[i];
5829 hasvalue = field->hasvalue;
5830 field->hasvalue = false;
5831 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5832 con_out("failed to generate field %s\n", field->name);
5833 ir_builder_delete(ir);
5838 ast_expression *subtype;
5839 field->hasvalue = true;
5840 subtype = field->expression.next;
5841 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5842 if (subtype->expression.vtype == TYPE_FIELD)
5843 ifld->fieldtype = subtype->expression.next->expression.vtype;
5844 else if (subtype->expression.vtype == TYPE_FUNCTION)
5845 ifld->outtype = subtype->expression.next->expression.vtype;
5846 (void)!ir_value_set_field(field->ir_v, ifld);
5849 for (i = 0; i < vec_size(parser->globals); ++i) {
5851 if (!ast_istype(parser->globals[i], ast_value))
5853 asvalue = (ast_value*)(parser->globals[i]);
5854 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5855 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5856 "unused global: `%s`", asvalue->name);
5858 if (!ast_global_codegen(asvalue, ir, false)) {
5859 con_out("failed to generate global %s\n", asvalue->name);
5860 ir_builder_delete(ir);
5864 /* Build function vararg accessor ast tree now before generating
5865 * immediates, because the accessors may add new immediates
5867 for (i = 0; i < vec_size(parser->functions); ++i) {
5868 ast_function *f = parser->functions[i];
5870 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5871 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5872 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5873 con_out("failed to generate vararg setter for %s\n", f->name);
5874 ir_builder_delete(ir);
5877 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5878 con_out("failed to generate vararg getter for %s\n", f->name);
5879 ir_builder_delete(ir);
5883 ast_delete(f->varargs);
5888 /* Now we can generate immediates */
5889 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5890 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5891 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5892 ir_builder_delete(ir);
5896 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5897 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5898 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5899 ir_builder_delete(ir);
5903 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5904 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5905 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5906 ir_builder_delete(ir);
5910 for (i = 0; i < vec_size(parser->globals); ++i) {
5912 if (!ast_istype(parser->globals[i], ast_value))
5914 asvalue = (ast_value*)(parser->globals[i]);
5915 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5917 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5918 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5919 "uninitialized constant: `%s`",
5921 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5922 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5923 "uninitialized global: `%s`",
5926 if (!ast_generate_accessors(asvalue, ir)) {
5927 ir_builder_delete(ir);
5931 for (i = 0; i < vec_size(parser->fields); ++i) {
5933 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5935 if (!ast_istype((ast_expression*)asvalue, ast_value))
5937 if (asvalue->expression.vtype != TYPE_ARRAY)
5939 if (!ast_generate_accessors(asvalue, ir)) {
5940 ir_builder_delete(ir);
5944 if (parser->reserved_version &&
5945 !ast_global_codegen(parser->reserved_version, ir, false))
5947 con_out("failed to generate reserved::version");
5948 ir_builder_delete(ir);
5951 for (i = 0; i < vec_size(parser->functions); ++i) {
5952 ast_function *f = parser->functions[i];
5953 if (!ast_function_codegen(f, ir)) {
5954 con_out("failed to generate function %s\n", f->name);
5955 ir_builder_delete(ir);
5960 ir_builder_dump(ir, con_out);
5961 for (i = 0; i < vec_size(parser->functions); ++i) {
5962 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5963 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5964 ir_builder_delete(ir);
5969 if (compile_Werrors) {
5970 con_out("*** there were warnings treated as errors\n");
5971 compile_show_werrors();
5977 ir_builder_dump(ir, con_out);
5979 generate_checksum(parser);
5981 if (!ir_builder_generate(ir, output)) {
5982 con_out("*** failed to generate output file\n");
5983 ir_builder_delete(ir);
5988 ir_builder_delete(ir);