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 const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
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);
123 static void parseerror(parser_t *parser, const char *fmt, ...)
127 vcompile_error(parser->lex->tok.ctx, fmt, ap);
131 /* returns true if it counts as an error */
132 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
137 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
142 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
147 r = vcompile_warning(ctx, warntype, fmt, ap);
152 /**********************************************************************
153 * some maths used for constant folding
156 vector vec3_add(vector a, vector b)
165 vector vec3_sub(vector a, vector b)
174 qcfloat vec3_mulvv(vector a, vector b)
176 return (a.x * b.x + a.y * b.y + a.z * b.z);
179 vector vec3_mulvf(vector a, float b)
188 /**********************************************************************
192 bool parser_next(parser_t *parser)
194 /* lex_do kills the previous token */
195 parser->tok = lex_do(parser->lex);
196 if (parser->tok == TOKEN_EOF)
198 if (parser->tok >= TOKEN_ERROR) {
199 parseerror(parser, "lex error");
205 #define parser_tokval(p) ((p)->lex->tok.value)
206 #define parser_token(p) (&((p)->lex->tok))
207 #define parser_ctx(p) ((p)->lex->tok.ctx)
209 static ast_value* parser_const_float(parser_t *parser, double d)
213 for (i = 0; i < vec_size(parser->imm_float); ++i) {
214 const double compare = parser->imm_float[i]->constval.vfloat;
215 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
216 return parser->imm_float[i];
218 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
220 out->hasvalue = true;
221 out->constval.vfloat = d;
222 vec_push(parser->imm_float, out);
226 static ast_value* parser_const_float_0(parser_t *parser)
228 if (!parser->imm_float_zero)
229 parser->imm_float_zero = parser_const_float(parser, 0);
230 return parser->imm_float_zero;
233 static ast_value* parser_const_float_1(parser_t *parser)
235 if (!parser->imm_float_one)
236 parser->imm_float_one = parser_const_float(parser, 1);
237 return parser->imm_float_one;
240 static char *parser_strdup(const char *str)
243 /* actually dup empty strings */
244 char *out = (char*)mem_a(1);
248 return util_strdup(str);
251 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
255 for (i = 0; i < vec_size(parser->imm_string); ++i) {
256 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
257 return parser->imm_string[i];
261 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
262 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
264 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
266 out->hasvalue = true;
267 out->constval.vstring = parser_strdup(str);
268 vec_push(parser->imm_string, out);
272 static ast_value* parser_const_vector(parser_t *parser, vector v)
276 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
277 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
278 return parser->imm_vector[i];
280 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
282 out->hasvalue = true;
283 out->constval.vvec = v;
284 vec_push(parser->imm_vector, out);
288 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
294 return parser_const_vector(parser, v);
297 static ast_value* parser_const_vector_0(parser_t *parser)
299 if (!parser->imm_vector_zero)
300 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
301 return parser->imm_vector_zero;
304 static ast_expression* parser_find_field(parser_t *parser, const char *name)
306 return ( ast_expression*)util_htget(parser->htfields, name);
309 static ast_expression* parser_find_label(parser_t *parser, const char *name)
312 for(i = 0; i < vec_size(parser->labels); i++)
313 if (!strcmp(parser->labels[i]->name, name))
314 return (ast_expression*)parser->labels[i];
318 static ast_expression* parser_find_global(parser_t *parser, const char *name)
320 return (ast_expression*)util_htget(parser->htglobals, name);
323 static ast_expression* parser_find_param(parser_t *parser, const char *name)
327 if (!parser->function)
329 fun = parser->function->vtype;
330 for (i = 0; i < vec_size(fun->expression.params); ++i) {
331 if (!strcmp(fun->expression.params[i]->name, name))
332 return (ast_expression*)(fun->expression.params[i]);
337 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
342 hash = util_hthash(parser->htglobals, name);
345 for (i = vec_size(parser->variables); i > upto;) {
347 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
351 return parser_find_param(parser, name);
354 static ast_expression* parser_find_var(parser_t *parser, const char *name)
358 v = parser_find_local(parser, name, 0, &dummy);
359 if (!v) v = parser_find_global(parser, name);
363 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
367 hash = util_hthash(parser->typedefs[0], name);
369 for (i = vec_size(parser->typedefs); i > upto;) {
371 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
379 size_t etype; /* 0 = expression, others are operators */
383 ast_block *block; /* for commas and function calls */
392 #define SY_PAREN_EXPR '('
393 #define SY_PAREN_FUNC 'f'
394 #define SY_PAREN_INDEX '['
395 #define SY_PAREN_TERNARY '?'
397 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
408 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
412 e.out = (ast_expression*)v;
419 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
421 e.etype = 1 + (op - operators);
430 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
442 # define DEBUGSHUNTDO(x) x
444 # define DEBUGSHUNTDO(x)
447 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
448 * so we need to rotate it to become ent.(foo[n]).
450 static bool rotate_entfield_array_index_nodes(ast_expression **out)
452 ast_array_index *index;
453 ast_entfield *entfield;
457 ast_expression *entity;
459 lex_ctx ctx = ast_ctx(*out);
461 if (!ast_istype(*out, ast_array_index))
463 index = (ast_array_index*)*out;
465 if (!ast_istype(index->array, ast_entfield))
467 entfield = (ast_entfield*)index->array;
469 if (!ast_istype(entfield->field, ast_value))
471 field = (ast_value*)entfield->field;
474 entity = entfield->entity;
478 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
479 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
480 *out = (ast_expression*)entfield;
485 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
487 switch (v->expression.vtype) {
489 return !!v->constval.vfloat;
491 return !!v->constval.vint;
493 if (OPTS_FLAG(CORRECT_LOGIC))
494 return v->constval.vvec.x &&
495 v->constval.vvec.y &&
498 return !!(v->constval.vvec.x);
500 if (!v->constval.vstring)
502 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
504 return !!v->constval.vstring[0];
506 compile_error(ctx, "internal error: immediate_is_true on invalid type");
507 return !!v->constval.vfunc;
511 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
515 ast_expression *out = NULL;
516 ast_expression *exprs[3];
517 ast_block *blocks[3];
518 ast_value *asvalue[3];
519 ast_binstore *asbinstore;
520 size_t i, assignop, addop, subop;
521 qcint generated_op = 0;
526 if (!vec_size(sy->ops)) {
527 parseerror(parser, "internal error: missing operator");
531 if (vec_last(sy->ops).paren) {
532 parseerror(parser, "unmatched parenthesis");
536 op = &operators[vec_last(sy->ops).etype - 1];
537 ctx = vec_last(sy->ops).ctx;
539 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
541 if (vec_size(sy->out) < op->operands) {
542 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
543 op->op, (int)op->id);
547 vec_shrinkby(sy->ops, 1);
549 /* op(:?) has no input and no output */
553 vec_shrinkby(sy->out, op->operands);
554 for (i = 0; i < op->operands; ++i) {
555 exprs[i] = sy->out[vec_size(sy->out)+i].out;
556 blocks[i] = sy->out[vec_size(sy->out)+i].block;
557 asvalue[i] = (ast_value*)exprs[i];
559 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
560 !(i != 0 && op->id == opid2('?',':')) &&
561 !(i == 1 && op->id == opid1('.')))
563 if (ast_istype(exprs[i], ast_label))
564 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
566 compile_error(ast_ctx(exprs[i]), "not an expression");
567 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
571 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
572 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
576 #define NotSameType(T) \
577 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
578 exprs[0]->expression.vtype != T)
579 #define CanConstFold1(A) \
580 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
581 (A)->expression.vtype != TYPE_FUNCTION)
582 #define CanConstFold(A, B) \
583 (CanConstFold1(A) && CanConstFold1(B))
584 #define ConstV(i) (asvalue[(i)]->constval.vvec)
585 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
586 #define ConstS(i) (asvalue[(i)]->constval.vstring)
590 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
594 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
595 exprs[1]->expression.vtype == TYPE_NOEXPR)
597 if (exprs[1] == (ast_expression*)parser->const_vec[0])
598 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
599 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
600 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
601 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
602 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
604 parseerror(parser, "access to invalid vector component");
608 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
609 if (exprs[1]->expression.vtype != TYPE_FIELD) {
610 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
613 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
615 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
616 parseerror(parser, "vectors cannot be accessed this way");
620 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
626 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
627 !(exprs[0]->expression.vtype == TYPE_FIELD &&
628 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
630 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
631 parseerror(parser, "cannot index value of type %s", ty1);
634 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
635 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
636 parseerror(parser, "index must be of type float, not %s", ty1);
639 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
640 if (rotate_entfield_array_index_nodes(&out))
643 /* This is not broken in fteqcc anymore */
644 if (opts.standard != COMPILER_GMQCC) {
645 /* this error doesn't need to make us bail out */
646 (void)!parsewarning(parser, WARN_EXTENSIONS,
647 "accessing array-field members of an entity without parenthesis\n"
648 " -> this is an extension from -std=gmqcc");
656 if (!ast_block_add_expr(blocks[0], exprs[1]))
659 blocks[0] = ast_block_new(ctx);
660 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
661 !ast_block_add_expr(blocks[0], exprs[1]))
666 if (!ast_block_set_type(blocks[0], exprs[1]))
669 vec_push(sy->out, syblock(ctx, blocks[0]));
676 switch (exprs[0]->expression.vtype) {
678 if (CanConstFold1(exprs[0]))
679 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
681 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
682 (ast_expression*)parser_const_float_0(parser),
686 if (CanConstFold1(exprs[0]))
687 out = (ast_expression*)parser_const_vector_f(parser,
688 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
690 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
691 (ast_expression*)parser_const_vector_0(parser),
695 parseerror(parser, "invalid types used in expression: cannot negate type %s",
696 type_name[exprs[0]->expression.vtype]);
702 switch (exprs[0]->expression.vtype) {
704 if (CanConstFold1(exprs[0]))
705 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
707 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
710 if (CanConstFold1(exprs[0]))
711 out = (ast_expression*)parser_const_float(parser,
712 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
714 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
717 if (CanConstFold1(exprs[0])) {
718 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
719 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
721 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
723 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
724 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
726 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
729 /* we don't constant-fold NOT for these types */
731 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
734 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
737 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
738 type_name[exprs[0]->expression.vtype]);
744 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
745 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
747 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
748 type_name[exprs[0]->expression.vtype],
749 type_name[exprs[1]->expression.vtype]);
752 switch (exprs[0]->expression.vtype) {
754 if (CanConstFold(exprs[0], exprs[1]))
756 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
759 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
762 if (CanConstFold(exprs[0], exprs[1]))
763 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
765 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
768 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
769 type_name[exprs[0]->expression.vtype],
770 type_name[exprs[1]->expression.vtype]);
775 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
776 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
778 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
779 type_name[exprs[1]->expression.vtype],
780 type_name[exprs[0]->expression.vtype]);
783 switch (exprs[0]->expression.vtype) {
785 if (CanConstFold(exprs[0], exprs[1]))
786 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
788 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
791 if (CanConstFold(exprs[0], exprs[1]))
792 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
794 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
797 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
798 type_name[exprs[1]->expression.vtype],
799 type_name[exprs[0]->expression.vtype]);
804 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
805 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
806 exprs[1]->expression.vtype == TYPE_FLOAT) &&
807 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
808 exprs[0]->expression.vtype == TYPE_FLOAT)
811 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
812 type_name[exprs[1]->expression.vtype],
813 type_name[exprs[0]->expression.vtype]);
816 switch (exprs[0]->expression.vtype) {
818 if (exprs[1]->expression.vtype == TYPE_VECTOR)
820 if (CanConstFold(exprs[0], exprs[1]))
821 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
823 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
827 if (CanConstFold(exprs[0], exprs[1]))
828 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
830 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
834 if (exprs[1]->expression.vtype == TYPE_FLOAT)
836 if (CanConstFold(exprs[0], exprs[1]))
837 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
839 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
843 if (CanConstFold(exprs[0], exprs[1]))
844 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
845 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
846 vector vec = ConstV(0);
847 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
848 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
849 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
850 out->expression.node.keep = false;
851 ((ast_member*)out)->rvalue = true;
853 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
855 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
856 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
857 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
858 out->expression.node.keep = false;
859 ((ast_member*)out)->rvalue = true;
861 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
863 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
864 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
865 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
866 out->expression.node.keep = false;
867 ((ast_member*)out)->rvalue = true;
869 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
872 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
874 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
875 vector vec = ConstV(1);
876 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
877 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
878 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
879 out->expression.node.keep = false;
880 ((ast_member*)out)->rvalue = true;
882 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
884 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
885 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
886 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
887 out->expression.node.keep = false;
888 ((ast_member*)out)->rvalue = true;
890 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
892 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
893 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
894 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
895 out->expression.node.keep = false;
896 ((ast_member*)out)->rvalue = true;
898 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
901 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
904 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
908 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
909 type_name[exprs[1]->expression.vtype],
910 type_name[exprs[0]->expression.vtype]);
915 if (NotSameType(TYPE_FLOAT)) {
916 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
917 type_name[exprs[0]->expression.vtype],
918 type_name[exprs[1]->expression.vtype]);
921 if (CanConstFold(exprs[0], exprs[1]))
922 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
924 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
928 parseerror(parser, "qc does not have a modulo operator");
932 if (NotSameType(TYPE_FLOAT)) {
933 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
934 type_name[exprs[0]->expression.vtype],
935 type_name[exprs[1]->expression.vtype]);
938 if (CanConstFold(exprs[0], exprs[1]))
939 out = (ast_expression*)parser_const_float(parser,
940 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
941 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
943 out = (ast_expression*)ast_binary_new(ctx,
944 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
948 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
953 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
954 if (op->id == opid2('<','<'))
955 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
957 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
960 case opid3('<','<','='):
961 case opid3('>','>','='):
962 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
966 generated_op += 1; /* INSTR_OR */
968 generated_op += INSTR_AND;
970 if (NotSameType(TYPE_FLOAT)) {
971 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
972 type_name[exprs[0]->expression.vtype],
973 type_name[exprs[1]->expression.vtype]);
974 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
975 parseerror(parser, "TODO: optional early out");
979 if (CanConstFold(exprs[0], exprs[1]))
981 if (OPTS_FLAG(PERL_LOGIC)) {
982 if (immediate_is_true(ctx, asvalue[0]))
986 out = (ast_expression*)parser_const_float(parser,
987 ( (generated_op == INSTR_OR)
988 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
989 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
994 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
995 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
996 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
997 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1000 for (i = 0; i < 2; ++i) {
1001 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1002 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1004 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1006 exprs[i] = out; out = NULL;
1007 if (OPTS_FLAG(PERL_LOGIC)) {
1008 /* here we want to keep the right expressions' type */
1012 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1013 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1015 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1017 exprs[i] = out; out = NULL;
1018 if (OPTS_FLAG(PERL_LOGIC)) {
1019 /* here we want to keep the right expressions' type */
1024 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1028 case opid2('?',':'):
1029 if (vec_last(parser->pot) != POT_TERNARY2) {
1030 parseerror(parser, "mismatched parenthesis/ternary");
1033 vec_pop(parser->pot);
1034 if (!ast_compare_type(exprs[1], exprs[2])) {
1035 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1036 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1037 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1040 if (CanConstFold1(exprs[0]))
1041 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1043 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1047 generated_op += 1; /* INSTR_GT */
1049 generated_op += 1; /* INSTR_LT */
1050 case opid2('>', '='):
1051 generated_op += 1; /* INSTR_GE */
1052 case opid2('<', '='):
1053 generated_op += INSTR_LE;
1054 if (NotSameType(TYPE_FLOAT)) {
1055 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1056 type_name[exprs[0]->expression.vtype],
1057 type_name[exprs[1]->expression.vtype]);
1060 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1062 case opid2('!', '='):
1063 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
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, type_ne_instr[exprs[0]->expression.vtype], 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_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1082 if (ast_istype(exprs[0], ast_entfield)) {
1083 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1084 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1085 exprs[0]->expression.vtype == TYPE_FIELD &&
1086 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1088 assignop = type_storep_instr[TYPE_VECTOR];
1091 assignop = type_storep_instr[exprs[0]->expression.vtype];
1092 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1094 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1095 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1096 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1097 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1098 exprs[1]->expression.vtype == TYPE_FUNCTION)
1100 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1101 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1104 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1109 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1110 exprs[0]->expression.vtype == TYPE_FIELD &&
1111 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1113 assignop = type_store_instr[TYPE_VECTOR];
1116 assignop = type_store_instr[exprs[0]->expression.vtype];
1119 if (assignop == AINSTR_END) {
1120 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1121 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1122 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1124 else if (!ast_compare_type(exprs[0], exprs[1]))
1126 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1129 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1130 exprs[1]->expression.vtype == TYPE_FUNCTION)
1132 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1133 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1136 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1139 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1140 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1142 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1144 case opid3('+','+','P'):
1145 case opid3('-','-','P'):
1147 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1148 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1149 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1152 if (op->id == opid3('+','+','P'))
1153 addop = INSTR_ADD_F;
1155 addop = INSTR_SUB_F;
1156 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1157 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1159 if (ast_istype(exprs[0], ast_entfield)) {
1160 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1162 (ast_expression*)parser_const_float_1(parser));
1164 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1166 (ast_expression*)parser_const_float_1(parser));
1169 case opid3('S','+','+'):
1170 case opid3('S','-','-'):
1172 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1173 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1174 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1177 if (op->id == opid3('S','+','+')) {
1178 addop = INSTR_ADD_F;
1179 subop = INSTR_SUB_F;
1181 addop = INSTR_SUB_F;
1182 subop = INSTR_ADD_F;
1184 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1185 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1187 if (ast_istype(exprs[0], ast_entfield)) {
1188 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1190 (ast_expression*)parser_const_float_1(parser));
1192 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1194 (ast_expression*)parser_const_float_1(parser));
1198 out = (ast_expression*)ast_binary_new(ctx, subop,
1200 (ast_expression*)parser_const_float_1(parser));
1202 case opid2('+','='):
1203 case opid2('-','='):
1204 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1205 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1207 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1208 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1209 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1213 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1214 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1216 if (ast_istype(exprs[0], ast_entfield))
1217 assignop = type_storep_instr[exprs[0]->expression.vtype];
1219 assignop = type_store_instr[exprs[0]->expression.vtype];
1220 switch (exprs[0]->expression.vtype) {
1222 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1223 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1224 exprs[0], exprs[1]);
1227 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1228 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1229 exprs[0], exprs[1]);
1232 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1233 type_name[exprs[0]->expression.vtype],
1234 type_name[exprs[1]->expression.vtype]);
1238 case opid2('*','='):
1239 case opid2('/','='):
1240 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1241 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1242 exprs[0]->expression.vtype == TYPE_VECTOR))
1244 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1245 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1246 parseerror(parser, "invalid types used in expression: %s and %s",
1250 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1251 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1253 if (ast_istype(exprs[0], ast_entfield))
1254 assignop = type_storep_instr[exprs[0]->expression.vtype];
1256 assignop = type_store_instr[exprs[0]->expression.vtype];
1257 switch (exprs[0]->expression.vtype) {
1259 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1260 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1261 exprs[0], exprs[1]);
1264 if (op->id == opid2('*','=')) {
1265 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1266 exprs[0], exprs[1]);
1268 /* there's no DIV_VF */
1269 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1270 (ast_expression*)parser_const_float_1(parser),
1274 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1279 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1280 type_name[exprs[0]->expression.vtype],
1281 type_name[exprs[1]->expression.vtype]);
1285 case opid2('&','='):
1286 case opid2('|','='):
1287 if (NotSameType(TYPE_FLOAT)) {
1288 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1289 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1290 parseerror(parser, "invalid types used in expression: %s and %s",
1294 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1295 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1297 if (ast_istype(exprs[0], ast_entfield))
1298 assignop = type_storep_instr[exprs[0]->expression.vtype];
1300 assignop = type_store_instr[exprs[0]->expression.vtype];
1301 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1302 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1303 exprs[0], exprs[1]);
1305 case opid3('&','~','='):
1306 /* This is like: a &= ~(b);
1307 * But QC has no bitwise-not, so we implement it as
1310 if (NotSameType(TYPE_FLOAT)) {
1311 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1312 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1313 parseerror(parser, "invalid types used in expression: %s and %s",
1317 if (ast_istype(exprs[0], ast_entfield))
1318 assignop = type_storep_instr[exprs[0]->expression.vtype];
1320 assignop = type_store_instr[exprs[0]->expression.vtype];
1321 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1324 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1325 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1327 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1328 asbinstore->keep_dest = true;
1329 out = (ast_expression*)asbinstore;
1335 parseerror(parser, "failed to apply operand %s", op->op);
1339 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1340 vec_push(sy->out, syexp(ctx, out));
1344 static bool parser_close_call(parser_t *parser, shunt *sy)
1346 /* was a function call */
1347 ast_expression *fun;
1353 vec_shrinkby(sy->ops, 1);
1354 fid = sy->ops[vec_size(sy->ops)].off;
1356 /* out[fid] is the function
1357 * everything above is parameters...
1358 * 0 params = nothing
1359 * 1 params = ast_expression
1363 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1364 parseerror(parser, "internal error: function call needs function and parameter list...");
1368 fun = sy->out[fid].out;
1370 if (fun == intrinsic_debug_typestring) {
1372 if (fid+2 != vec_size(sy->out) ||
1373 vec_last(sy->out).block)
1375 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1378 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1379 ast_unref(vec_last(sy->out).out);
1380 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1381 (ast_expression*)parser_const_string(parser, ty, false));
1382 vec_shrinkby(sy->out, 1);
1386 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1388 parseerror(parser, "internal error: failed to create ast_call node");
1392 if (fid+1 == vec_size(sy->out)) {
1395 } else if (fid+2 == vec_size(sy->out)) {
1397 vec_shrinkby(sy->out, 1);
1398 params = sy->out[vec_size(sy->out)].block;
1402 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1404 paramcount = vec_size(params->exprs);
1405 call->params = params->exprs;
1406 params->exprs = NULL;
1409 if (parser->max_param_count < paramcount)
1410 parser->max_param_count = paramcount;
1411 (void)!ast_call_check_types(call);
1413 parseerror(parser, "invalid function call");
1417 /* overwrite fid, the function, with a call */
1418 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1420 if (fun->expression.vtype != TYPE_FUNCTION) {
1421 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1425 if (!fun->expression.next) {
1426 parseerror(parser, "could not determine function return type");
1429 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1431 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1433 return !parsewarning(parser, WARN_DEPRECATED,
1434 "call to function (which is marked deprecated)\n",
1435 "-> it has been declared here: %s:%i",
1436 ast_ctx(fun).file, ast_ctx(fun).line);
1439 return !parsewarning(parser, WARN_DEPRECATED,
1440 "call to `%s` (which is marked deprecated)\n"
1441 "-> `%s` declared here: %s:%i",
1442 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1444 return !parsewarning(parser, WARN_DEPRECATED,
1445 "call to `%s` (deprecated: %s)\n"
1446 "-> `%s` declared here: %s:%i",
1447 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1451 if (vec_size(fun->expression.params) != paramcount &&
1452 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1453 vec_size(fun->expression.params) < paramcount))
1455 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1457 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1458 "too %s parameters for call to %s: expected %i, got %i\n"
1459 " -> `%s` has been declared here: %s:%i",
1460 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1461 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1463 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1464 "too %s parameters for function call: expected %i, got %i\n"
1465 " -> it has been declared here: %s:%i",
1466 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1467 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1474 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1476 if (!vec_size(sy->ops)) {
1477 parseerror(parser, "unmatched closing paren");
1480 /* this would for bit a + (x) because there are no operators inside (x)
1481 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1482 parseerror(parser, "empty parenthesis expression");
1486 while (vec_size(sy->ops)) {
1487 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1488 if (!parser_close_call(parser, sy))
1492 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1493 vec_shrinkby(sy->ops, 1);
1494 return !functions_only;
1496 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1499 /* pop off the parenthesis */
1500 vec_shrinkby(sy->ops, 1);
1501 /* then apply the index operator */
1502 if (!parser_sy_apply_operator(parser, sy))
1506 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1509 if (vec_last(parser->pot) != POT_TERNARY1) {
1510 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1513 vec_last(parser->pot) = POT_TERNARY2;
1514 /* pop off the parenthesis */
1515 vec_shrinkby(sy->ops, 1);
1518 if (!parser_sy_apply_operator(parser, sy))
1524 static void parser_reclassify_token(parser_t *parser)
1527 for (i = 0; i < operator_count; ++i) {
1528 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1529 parser->tok = TOKEN_OPERATOR;
1535 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1537 ast_expression *expr = NULL;
1539 bool wantop = false;
1540 /* only warn once about an assignment in a truth value because the current code
1541 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1543 bool warn_truthvalue = true;
1545 /* count the parens because an if starts with one, so the
1546 * end of a condition is an unmatched closing paren
1554 parser->lex->flags.noops = false;
1556 parser_reclassify_token(parser);
1560 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1561 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1563 /* a translatable string */
1567 parseerror(parser, "expected operator or end of statement, got constant");
1571 parser->lex->flags.noops = true;
1572 if (!parser_next(parser) || parser->tok != '(') {
1573 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1576 parser->lex->flags.noops = false;
1577 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1578 parseerror(parser, "expected a constant string in translatable-string extension");
1581 val = parser_const_string(parser, parser_tokval(parser), true);
1585 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1586 DEBUGSHUNTDO(con_out("push string\n"));
1588 if (!parser_next(parser) || parser->tok != ')') {
1589 parseerror(parser, "expected closing paren after translatable string");
1593 else if (parser->tok == TOKEN_IDENT)
1595 const char *ctoken = parser_tokval(parser);
1596 ast_expression *prev = vec_size(sy.out) ? vec_last(sy.out).out : NULL;
1597 ast_expression *var;
1599 parseerror(parser, "expected operator or end of statement");
1603 /* a_vector.{x,y,z} */
1604 if (!vec_size(sy.ops) ||
1605 !vec_last(sy.ops).etype ||
1606 operators[vec_last(sy.ops).etype-1].id != opid1('.') ||
1607 (prev >= intrinsic_debug_typestring &&
1608 prev <= intrinsic_debug_typestring))
1610 /* When adding more intrinsics, fix the above condition */
1613 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1615 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1617 var = parser_find_var(parser, parser_tokval(parser));
1619 var = parser_find_field(parser, parser_tokval(parser));
1621 if (!var && with_labels) {
1622 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1624 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1625 var = (ast_expression*)lbl;
1626 vec_push(parser->labels, lbl);
1631 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1632 var = (ast_expression*)intrinsic_debug_typestring;
1637 char *correct = NULL;
1640 * sometimes people use preprocessing predefs without enabling them
1641 * i've done this thousands of times already myself. Lets check for
1642 * it in the predef table. And diagnose it better :)
1644 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1645 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1646 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1647 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1654 * TODO: determine the best score for the identifier: be it
1655 * a variable, a field.
1657 * We should also consider adding correction tables for
1658 * other things as well.
1660 if (OPTS_FLAG(ENHANCED_DIAGNOSTICS)) {
1662 correct_init(&corr);
1664 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1665 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1666 if (strcmp(correct, parser_tokval(parser))) {
1668 } else if (correct) {
1673 correct_free(&corr);
1676 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1681 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1687 if (ast_istype(var, ast_value)) {
1688 ((ast_value*)var)->uses++;
1690 else if (ast_istype(var, ast_member)) {
1691 ast_member *mem = (ast_member*)var;
1692 if (ast_istype(mem->owner, ast_value))
1693 ((ast_value*)(mem->owner))->uses++;
1696 vec_push(sy.out, syexp(parser_ctx(parser), var));
1697 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1699 else if (parser->tok == TOKEN_FLOATCONST) {
1702 parseerror(parser, "expected operator or end of statement, got constant");
1706 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1709 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1710 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1712 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1715 parseerror(parser, "expected operator or end of statement, got constant");
1719 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1722 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1723 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1725 else if (parser->tok == TOKEN_STRINGCONST) {
1728 parseerror(parser, "expected operator or end of statement, got constant");
1732 val = parser_const_string(parser, parser_tokval(parser), false);
1735 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1736 DEBUGSHUNTDO(con_out("push string\n"));
1738 else if (parser->tok == TOKEN_VECTORCONST) {
1741 parseerror(parser, "expected operator or end of statement, got constant");
1745 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1748 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1749 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1750 parser_token(parser)->constval.v.x,
1751 parser_token(parser)->constval.v.y,
1752 parser_token(parser)->constval.v.z));
1754 else if (parser->tok == '(') {
1755 parseerror(parser, "internal error: '(' should be classified as operator");
1758 else if (parser->tok == '[') {
1759 parseerror(parser, "internal error: '[' should be classified as operator");
1762 else if (parser->tok == ')') {
1764 DEBUGSHUNTDO(con_out("do[op] )\n"));
1768 /* we do expect an operator next */
1769 /* closing an opening paren */
1770 if (!parser_close_paren(parser, &sy, false))
1772 if (vec_last(parser->pot) != POT_PAREN) {
1773 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1776 vec_pop(parser->pot);
1778 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1782 /* allowed for function calls */
1783 if (!parser_close_paren(parser, &sy, true))
1785 if (vec_last(parser->pot) != POT_PAREN) {
1786 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1789 vec_pop(parser->pot);
1793 else if (parser->tok == ']') {
1795 parseerror(parser, "operand expected");
1799 if (!parser_close_paren(parser, &sy, false))
1801 if (vec_last(parser->pot) != POT_PAREN) {
1802 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1805 vec_pop(parser->pot);
1808 else if (parser->tok == TOKEN_TYPENAME) {
1809 parseerror(parser, "unexpected typename");
1812 else if (parser->tok != TOKEN_OPERATOR) {
1814 parseerror(parser, "expected operator or end of statement");
1821 /* classify the operator */
1822 const oper_info *op;
1823 const oper_info *olast = NULL;
1825 for (o = 0; o < operator_count; ++o) {
1826 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1827 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1828 !strcmp(parser_tokval(parser), operators[o].op))
1833 if (o == operator_count) {
1834 /* no operator found... must be the end of the statement */
1837 /* found an operator */
1840 /* when declaring variables, a comma starts a new variable */
1841 if (op->id == opid1(',') && !parens && stopatcomma) {
1842 /* fixup the token */
1847 /* a colon without a pervious question mark cannot be a ternary */
1848 if (!ternaries && op->id == opid2(':','?')) {
1853 if (op->id == opid1(',')) {
1854 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1855 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1859 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1860 olast = &operators[vec_last(sy.ops).etype-1];
1862 #define IsAssignOp(x) (\
1863 (x) == opid1('=') || \
1864 (x) == opid2('+','=') || \
1865 (x) == opid2('-','=') || \
1866 (x) == opid2('*','=') || \
1867 (x) == opid2('/','=') || \
1868 (x) == opid2('%','=') || \
1869 (x) == opid2('&','=') || \
1870 (x) == opid2('|','=') || \
1871 (x) == opid3('&','~','=') \
1873 if (warn_truthvalue) {
1874 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1875 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1876 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1879 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1880 warn_truthvalue = false;
1885 (op->prec < olast->prec) ||
1886 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1888 if (!parser_sy_apply_operator(parser, &sy))
1890 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1891 olast = &operators[vec_last(sy.ops).etype-1];
1896 if (op->id == opid1('(')) {
1898 size_t sycount = vec_size(sy.out);
1899 DEBUGSHUNTDO(con_out("push [op] (\n"));
1900 ++parens; vec_push(parser->pot, POT_PAREN);
1901 /* we expected an operator, this is the function-call operator */
1902 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1904 ++parens; vec_push(parser->pot, POT_PAREN);
1905 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1906 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1909 } else if (op->id == opid1('[')) {
1911 parseerror(parser, "unexpected array subscript");
1914 ++parens; vec_push(parser->pot, POT_PAREN);
1915 /* push both the operator and the paren, this makes life easier */
1916 vec_push(sy.ops, syop(parser_ctx(parser), op));
1917 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1919 } else if (op->id == opid2('?',':')) {
1920 vec_push(sy.ops, syop(parser_ctx(parser), op));
1921 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1924 vec_push(parser->pot, POT_TERNARY1);
1925 } else if (op->id == opid2(':','?')) {
1926 if (!vec_size(parser->pot)) {
1927 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1930 if (vec_last(parser->pot) != POT_TERNARY1) {
1931 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1934 if (!parser_close_paren(parser, &sy, false))
1936 vec_push(sy.ops, syop(parser_ctx(parser), op));
1940 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1941 vec_push(sy.ops, syop(parser_ctx(parser), op));
1942 wantop = !!(op->flags & OP_SUFFIX);
1945 if (!parser_next(parser)) {
1948 if (parser->tok == ';' ||
1949 (!parens && (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1955 while (vec_size(sy.ops)) {
1956 if (!parser_sy_apply_operator(parser, &sy))
1960 parser->lex->flags.noops = true;
1961 if (!vec_size(sy.out)) {
1962 parseerror(parser, "empty expression");
1965 expr = sy.out[0].out;
1968 DEBUGSHUNTDO(con_out("shunt done\n"));
1969 if (vec_size(parser->pot)) {
1970 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1973 vec_free(parser->pot);
1977 parser->lex->flags.noops = true;
1983 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1985 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1988 if (parser->tok != ';') {
1989 parseerror(parser, "semicolon expected after expression");
1993 if (!parser_next(parser)) {
2000 static void parser_enterblock(parser_t *parser)
2002 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2003 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2004 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2005 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2006 vec_push(parser->_block_ctx, parser_ctx(parser));
2009 vec_push(parser->correct_variables, correct_trie_new());
2010 vec_push(parser->correct_variables_score, NULL);
2013 static bool parser_leaveblock(parser_t *parser)
2016 size_t locals, typedefs;
2018 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2019 parseerror(parser, "internal error: parser_leaveblock with no block");
2023 util_htdel(vec_last(parser->variables));
2024 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2026 vec_pop(parser->variables);
2027 vec_pop(parser->correct_variables);
2028 vec_pop(parser->correct_variables_score);
2029 if (!vec_size(parser->_blocklocals)) {
2030 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2034 locals = vec_last(parser->_blocklocals);
2035 vec_pop(parser->_blocklocals);
2036 while (vec_size(parser->_locals) != locals) {
2037 ast_expression *e = vec_last(parser->_locals);
2038 ast_value *v = (ast_value*)e;
2039 vec_pop(parser->_locals);
2040 if (ast_istype(e, ast_value) && !v->uses) {
2041 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2046 typedefs = vec_last(parser->_blocktypedefs);
2047 while (vec_size(parser->_typedefs) != typedefs) {
2048 ast_delete(vec_last(parser->_typedefs));
2049 vec_pop(parser->_typedefs);
2051 util_htdel(vec_last(parser->typedefs));
2052 vec_pop(parser->typedefs);
2054 vec_pop(parser->_block_ctx);
2059 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2061 vec_push(parser->_locals, e);
2062 util_htset(vec_last(parser->variables), name, (void*)e);
2066 vec_last(parser->correct_variables),
2067 &vec_last(parser->correct_variables_score),
2072 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2074 vec_push(parser->globals, e);
2075 util_htset(parser->htglobals, name, e);
2079 parser->correct_variables[0],
2080 &parser->correct_variables_score[0],
2085 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2089 ast_expression *prev;
2091 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2094 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2097 parseerror(parser, "internal error: failed to process condition");
2102 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2104 /* vector types need to be cast to true booleans */
2105 ast_binary *bin = (ast_binary*)cond;
2106 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2108 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2110 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2113 parseerror(parser, "internal error: failed to process condition");
2120 unary = (ast_unary*)cond;
2121 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2123 cond = unary->operand;
2124 unary->operand = NULL;
2127 unary = (ast_unary*)cond;
2131 parseerror(parser, "internal error: failed to process condition");
2133 if (ifnot) *_ifnot = !*_ifnot;
2137 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2140 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2143 lex_ctx ctx = parser_ctx(parser);
2145 (void)block; /* not touching */
2147 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2148 if (!parser_next(parser)) {
2149 parseerror(parser, "expected condition or 'not'");
2152 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2154 if (!parser_next(parser)) {
2155 parseerror(parser, "expected condition in parenthesis");
2159 if (parser->tok != '(') {
2160 parseerror(parser, "expected 'if' condition in parenthesis");
2163 /* parse into the expression */
2164 if (!parser_next(parser)) {
2165 parseerror(parser, "expected 'if' condition after opening paren");
2168 /* parse the condition */
2169 cond = parse_expression_leave(parser, false, true, false);
2173 if (parser->tok != ')') {
2174 parseerror(parser, "expected closing paren after 'if' condition");
2178 /* parse into the 'then' branch */
2179 if (!parser_next(parser)) {
2180 parseerror(parser, "expected statement for on-true branch of 'if'");
2184 if (!parse_statement_or_block(parser, &ontrue)) {
2189 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2190 /* check for an else */
2191 if (!strcmp(parser_tokval(parser), "else")) {
2192 /* parse into the 'else' branch */
2193 if (!parser_next(parser)) {
2194 parseerror(parser, "expected on-false branch after 'else'");
2199 if (!parse_statement_or_block(parser, &onfalse)) {
2206 cond = process_condition(parser, cond, &ifnot);
2208 if (ontrue) ast_delete(ontrue);
2209 if (onfalse) ast_delete(onfalse);
2214 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2216 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2217 *out = (ast_expression*)ifthen;
2221 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2222 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2227 /* skip the 'while' and get the body */
2228 if (!parser_next(parser)) {
2229 if (OPTS_FLAG(LOOP_LABELS))
2230 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2232 parseerror(parser, "expected 'while' condition in parenthesis");
2236 if (parser->tok == ':') {
2237 if (!OPTS_FLAG(LOOP_LABELS))
2238 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2239 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2240 parseerror(parser, "expected loop label");
2243 label = util_strdup(parser_tokval(parser));
2244 if (!parser_next(parser)) {
2246 parseerror(parser, "expected 'while' condition in parenthesis");
2251 if (parser->tok != '(') {
2252 parseerror(parser, "expected 'while' condition in parenthesis");
2256 vec_push(parser->breaks, label);
2257 vec_push(parser->continues, label);
2259 rv = parse_while_go(parser, block, out);
2262 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2263 parseerror(parser, "internal error: label stack corrupted");
2269 vec_pop(parser->breaks);
2270 vec_pop(parser->continues);
2275 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2278 ast_expression *cond, *ontrue;
2282 lex_ctx ctx = parser_ctx(parser);
2284 (void)block; /* not touching */
2286 /* parse into the expression */
2287 if (!parser_next(parser)) {
2288 parseerror(parser, "expected 'while' condition after opening paren");
2291 /* parse the condition */
2292 cond = parse_expression_leave(parser, false, true, false);
2296 if (parser->tok != ')') {
2297 parseerror(parser, "expected closing paren after 'while' condition");
2301 /* parse into the 'then' branch */
2302 if (!parser_next(parser)) {
2303 parseerror(parser, "expected while-loop body");
2307 if (!parse_statement_or_block(parser, &ontrue)) {
2312 cond = process_condition(parser, cond, &ifnot);
2317 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2318 *out = (ast_expression*)aloop;
2322 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2323 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2328 /* skip the 'do' and get the body */
2329 if (!parser_next(parser)) {
2330 if (OPTS_FLAG(LOOP_LABELS))
2331 parseerror(parser, "expected loop label or body");
2333 parseerror(parser, "expected loop body");
2337 if (parser->tok == ':') {
2338 if (!OPTS_FLAG(LOOP_LABELS))
2339 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2340 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2341 parseerror(parser, "expected loop label");
2344 label = util_strdup(parser_tokval(parser));
2345 if (!parser_next(parser)) {
2347 parseerror(parser, "expected loop body");
2352 vec_push(parser->breaks, label);
2353 vec_push(parser->continues, label);
2355 rv = parse_dowhile_go(parser, block, out);
2358 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2359 parseerror(parser, "internal error: label stack corrupted");
2365 vec_pop(parser->breaks);
2366 vec_pop(parser->continues);
2371 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2374 ast_expression *cond, *ontrue;
2378 lex_ctx ctx = parser_ctx(parser);
2380 (void)block; /* not touching */
2382 if (!parse_statement_or_block(parser, &ontrue))
2385 /* expect the "while" */
2386 if (parser->tok != TOKEN_KEYWORD ||
2387 strcmp(parser_tokval(parser), "while"))
2389 parseerror(parser, "expected 'while' and condition");
2394 /* skip the 'while' and check for opening paren */
2395 if (!parser_next(parser) || parser->tok != '(') {
2396 parseerror(parser, "expected 'while' condition in parenthesis");
2400 /* parse into the expression */
2401 if (!parser_next(parser)) {
2402 parseerror(parser, "expected 'while' condition after opening paren");
2406 /* parse the condition */
2407 cond = parse_expression_leave(parser, false, true, false);
2411 if (parser->tok != ')') {
2412 parseerror(parser, "expected closing paren after 'while' condition");
2418 if (!parser_next(parser) || parser->tok != ';') {
2419 parseerror(parser, "expected semicolon after condition");
2425 if (!parser_next(parser)) {
2426 parseerror(parser, "parse error");
2432 cond = process_condition(parser, cond, &ifnot);
2437 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2438 *out = (ast_expression*)aloop;
2442 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2443 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2448 /* skip the 'for' and check for opening paren */
2449 if (!parser_next(parser)) {
2450 if (OPTS_FLAG(LOOP_LABELS))
2451 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2453 parseerror(parser, "expected 'for' expressions in parenthesis");
2457 if (parser->tok == ':') {
2458 if (!OPTS_FLAG(LOOP_LABELS))
2459 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2460 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2461 parseerror(parser, "expected loop label");
2464 label = util_strdup(parser_tokval(parser));
2465 if (!parser_next(parser)) {
2467 parseerror(parser, "expected 'for' expressions in parenthesis");
2472 if (parser->tok != '(') {
2473 parseerror(parser, "expected 'for' expressions in parenthesis");
2477 vec_push(parser->breaks, label);
2478 vec_push(parser->continues, label);
2480 rv = parse_for_go(parser, block, out);
2483 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2484 parseerror(parser, "internal error: label stack corrupted");
2490 vec_pop(parser->breaks);
2491 vec_pop(parser->continues);
2495 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2498 ast_expression *initexpr, *cond, *increment, *ontrue;
2504 lex_ctx ctx = parser_ctx(parser);
2506 parser_enterblock(parser);
2513 /* parse into the expression */
2514 if (!parser_next(parser)) {
2515 parseerror(parser, "expected 'for' initializer after opening paren");
2520 if (parser->tok == TOKEN_IDENT)
2521 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2523 if (typevar || parser->tok == TOKEN_TYPENAME) {
2525 if (opts.standard != COMPILER_GMQCC) {
2526 if (parsewarning(parser, WARN_EXTENSIONS,
2527 "current standard does not allow variable declarations in for-loop initializers"))
2531 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2534 else if (parser->tok != ';')
2536 initexpr = parse_expression_leave(parser, false, false, false);
2541 /* move on to condition */
2542 if (parser->tok != ';') {
2543 parseerror(parser, "expected semicolon after for-loop initializer");
2546 if (!parser_next(parser)) {
2547 parseerror(parser, "expected for-loop condition");
2551 /* parse the condition */
2552 if (parser->tok != ';') {
2553 cond = parse_expression_leave(parser, false, true, false);
2558 /* move on to incrementor */
2559 if (parser->tok != ';') {
2560 parseerror(parser, "expected semicolon after for-loop initializer");
2563 if (!parser_next(parser)) {
2564 parseerror(parser, "expected for-loop condition");
2568 /* parse the incrementor */
2569 if (parser->tok != ')') {
2570 increment = parse_expression_leave(parser, false, false, false);
2573 if (!ast_side_effects(increment)) {
2574 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2580 if (parser->tok != ')') {
2581 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2584 /* parse into the 'then' branch */
2585 if (!parser_next(parser)) {
2586 parseerror(parser, "expected for-loop body");
2589 if (!parse_statement_or_block(parser, &ontrue))
2593 cond = process_condition(parser, cond, &ifnot);
2597 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2598 *out = (ast_expression*)aloop;
2600 if (!parser_leaveblock(parser))
2604 if (initexpr) ast_delete(initexpr);
2605 if (cond) ast_delete(cond);
2606 if (increment) ast_delete(increment);
2607 (void)!parser_leaveblock(parser);
2611 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2613 ast_expression *exp = NULL;
2614 ast_return *ret = NULL;
2615 ast_value *expected = parser->function->vtype;
2617 lex_ctx ctx = parser_ctx(parser);
2619 (void)block; /* not touching */
2621 if (!parser_next(parser)) {
2622 parseerror(parser, "expected return expression");
2626 if (parser->tok != ';') {
2627 exp = parse_expression(parser, false, false);
2631 if (exp->expression.vtype != TYPE_NIL &&
2632 exp->expression.vtype != expected->expression.next->expression.vtype)
2634 parseerror(parser, "return with invalid expression");
2637 ret = ast_return_new(ctx, exp);
2643 if (!parser_next(parser))
2644 parseerror(parser, "parse error");
2645 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2646 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2648 ret = ast_return_new(ctx, NULL);
2650 *out = (ast_expression*)ret;
2654 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2657 unsigned int levels = 0;
2658 lex_ctx ctx = parser_ctx(parser);
2659 const char **loops = (is_continue ? parser->continues : parser->breaks);
2661 (void)block; /* not touching */
2662 if (!parser_next(parser)) {
2663 parseerror(parser, "expected semicolon or loop label");
2667 if (!vec_size(loops)) {
2669 parseerror(parser, "`continue` can only be used inside loops");
2671 parseerror(parser, "`break` can only be used inside loops or switches");
2674 if (parser->tok == TOKEN_IDENT) {
2675 if (!OPTS_FLAG(LOOP_LABELS))
2676 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2677 i = vec_size(loops);
2679 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2682 parseerror(parser, "no such loop to %s: `%s`",
2683 (is_continue ? "continue" : "break out of"),
2684 parser_tokval(parser));
2689 if (!parser_next(parser)) {
2690 parseerror(parser, "expected semicolon");
2695 if (parser->tok != ';') {
2696 parseerror(parser, "expected semicolon");
2700 if (!parser_next(parser))
2701 parseerror(parser, "parse error");
2703 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2707 /* returns true when it was a variable qualifier, false otherwise!
2708 * on error, cvq is set to CV_WRONG
2710 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2712 bool had_const = false;
2713 bool had_var = false;
2714 bool had_noref = false;
2715 bool had_attrib = false;
2716 bool had_static = false;
2721 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2723 /* parse an attribute */
2724 if (!parser_next(parser)) {
2725 parseerror(parser, "expected attribute after `[[`");
2729 if (!strcmp(parser_tokval(parser), "noreturn")) {
2730 flags |= AST_FLAG_NORETURN;
2731 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2732 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2737 else if (!strcmp(parser_tokval(parser), "noref")) {
2739 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2740 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2745 else if (!strcmp(parser_tokval(parser), "inline")) {
2746 flags |= AST_FLAG_INLINE;
2747 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2748 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2755 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2756 flags |= AST_FLAG_DEPRECATED;
2759 if (!parser_next(parser)) {
2760 parseerror(parser, "parse error in attribute");
2764 if (parser->tok == '(') {
2765 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2766 parseerror(parser, "`deprecated` attribute missing parameter");
2770 *message = util_strdup(parser_tokval(parser));
2772 if (!parser_next(parser)) {
2773 parseerror(parser, "parse error in attribute");
2777 if(parser->tok != ')') {
2778 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2782 if (!parser_next(parser)) {
2783 parseerror(parser, "parse error in attribute");
2788 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2789 parseerror(parser, "`deprecated` attribute expected `]]`");
2792 if (*message) mem_d(*message);
2800 /* Skip tokens until we hit a ]] */
2801 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2802 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2803 if (!parser_next(parser)) {
2804 parseerror(parser, "error inside attribute");
2811 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2813 else if (!strcmp(parser_tokval(parser), "const"))
2815 else if (!strcmp(parser_tokval(parser), "var"))
2817 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2819 else if (!strcmp(parser_tokval(parser), "noref"))
2821 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2826 if (!parser_next(parser))
2836 *is_static = had_static;
2840 parseerror(parser, "parse error after variable qualifier");
2845 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2846 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2851 /* skip the 'while' and get the body */
2852 if (!parser_next(parser)) {
2853 if (OPTS_FLAG(LOOP_LABELS))
2854 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2856 parseerror(parser, "expected 'switch' operand in parenthesis");
2860 if (parser->tok == ':') {
2861 if (!OPTS_FLAG(LOOP_LABELS))
2862 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2863 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2864 parseerror(parser, "expected loop label");
2867 label = util_strdup(parser_tokval(parser));
2868 if (!parser_next(parser)) {
2870 parseerror(parser, "expected 'switch' operand in parenthesis");
2875 if (parser->tok != '(') {
2876 parseerror(parser, "expected 'switch' operand in parenthesis");
2880 vec_push(parser->breaks, label);
2882 rv = parse_switch_go(parser, block, out);
2885 if (vec_last(parser->breaks) != label) {
2886 parseerror(parser, "internal error: label stack corrupted");
2892 vec_pop(parser->breaks);
2897 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2899 ast_expression *operand;
2902 ast_switch *switchnode;
2903 ast_switch_case swcase;
2906 bool noref, is_static;
2907 uint32_t qflags = 0;
2909 lex_ctx ctx = parser_ctx(parser);
2911 (void)block; /* not touching */
2914 /* parse into the expression */
2915 if (!parser_next(parser)) {
2916 parseerror(parser, "expected switch operand");
2919 /* parse the operand */
2920 operand = parse_expression_leave(parser, false, false, false);
2924 switchnode = ast_switch_new(ctx, operand);
2927 if (parser->tok != ')') {
2928 ast_delete(switchnode);
2929 parseerror(parser, "expected closing paren after 'switch' operand");
2933 /* parse over the opening paren */
2934 if (!parser_next(parser) || parser->tok != '{') {
2935 ast_delete(switchnode);
2936 parseerror(parser, "expected list of cases");
2940 if (!parser_next(parser)) {
2941 ast_delete(switchnode);
2942 parseerror(parser, "expected 'case' or 'default'");
2946 /* new block; allow some variables to be declared here */
2947 parser_enterblock(parser);
2950 if (parser->tok == TOKEN_IDENT)
2951 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2952 if (typevar || parser->tok == TOKEN_TYPENAME) {
2953 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2954 ast_delete(switchnode);
2959 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2961 if (cvq == CV_WRONG) {
2962 ast_delete(switchnode);
2965 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2966 ast_delete(switchnode);
2975 while (parser->tok != '}') {
2976 ast_block *caseblock;
2978 if (!strcmp(parser_tokval(parser), "case")) {
2979 if (!parser_next(parser)) {
2980 ast_delete(switchnode);
2981 parseerror(parser, "expected expression for case");
2984 swcase.value = parse_expression_leave(parser, false, false, false);
2985 if (!swcase.value) {
2986 ast_delete(switchnode);
2987 parseerror(parser, "expected expression for case");
2990 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2991 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2992 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2998 else if (!strcmp(parser_tokval(parser), "default")) {
2999 swcase.value = NULL;
3000 if (!parser_next(parser)) {
3001 ast_delete(switchnode);
3002 parseerror(parser, "expected colon");
3007 ast_delete(switchnode);
3008 parseerror(parser, "expected 'case' or 'default'");
3012 /* Now the colon and body */
3013 if (parser->tok != ':') {
3014 if (swcase.value) ast_unref(swcase.value);
3015 ast_delete(switchnode);
3016 parseerror(parser, "expected colon");
3020 if (!parser_next(parser)) {
3021 if (swcase.value) ast_unref(swcase.value);
3022 ast_delete(switchnode);
3023 parseerror(parser, "expected statements or case");
3026 caseblock = ast_block_new(parser_ctx(parser));
3028 if (swcase.value) ast_unref(swcase.value);
3029 ast_delete(switchnode);
3032 swcase.code = (ast_expression*)caseblock;
3033 vec_push(switchnode->cases, swcase);
3035 ast_expression *expr;
3036 if (parser->tok == '}')
3038 if (parser->tok == TOKEN_KEYWORD) {
3039 if (!strcmp(parser_tokval(parser), "case") ||
3040 !strcmp(parser_tokval(parser), "default"))
3045 if (!parse_statement(parser, caseblock, &expr, true)) {
3046 ast_delete(switchnode);
3051 if (!ast_block_add_expr(caseblock, expr)) {
3052 ast_delete(switchnode);
3058 parser_leaveblock(parser);
3061 if (parser->tok != '}') {
3062 ast_delete(switchnode);
3063 parseerror(parser, "expected closing paren of case list");
3066 if (!parser_next(parser)) {
3067 ast_delete(switchnode);
3068 parseerror(parser, "parse error after switch");
3071 *out = (ast_expression*)switchnode;
3075 /* parse computed goto sides */
3076 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3077 ast_expression *on_true;
3078 ast_expression *on_false;
3079 ast_expression *cond;
3084 if (ast_istype(*side, ast_ternary)) {
3085 ast_ternary *tern = (ast_ternary*)*side;
3086 on_true = parse_goto_computed(parser, &tern->on_true);
3087 on_false = parse_goto_computed(parser, &tern->on_false);
3089 if (!on_true || !on_false) {
3090 parseerror(parser, "expected label or expression in ternary");
3091 if (on_true) ast_unref(on_true);
3092 if (on_false) ast_unref(on_false);
3100 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3101 } else if (ast_istype(*side, ast_label)) {
3102 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3103 ast_goto_set_label(gt, ((ast_label*)*side));
3105 return (ast_expression*)gt;
3110 static bool parse_goto(parser_t *parser, ast_expression **out)
3112 ast_goto *gt = NULL;
3113 ast_expression *lbl;
3115 if (!parser_next(parser))
3118 if (parser->tok != TOKEN_IDENT) {
3119 ast_expression *expression;
3121 /* could be an expression i.e computed goto :-) */
3122 if (parser->tok != '(') {
3123 parseerror(parser, "expected label name after `goto`");
3127 /* failed to parse expression for goto */
3128 if (!(expression = parse_expression(parser, false, true)) ||
3129 !(*out = parse_goto_computed(parser, &expression))) {
3130 parseerror(parser, "invalid goto expression");
3131 ast_unref(expression);
3138 /* not computed goto */
3139 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3140 lbl = parser_find_label(parser, gt->name);
3142 if (!ast_istype(lbl, ast_label)) {
3143 parseerror(parser, "internal error: label is not an ast_label");
3147 ast_goto_set_label(gt, (ast_label*)lbl);
3150 vec_push(parser->gotos, gt);
3152 if (!parser_next(parser) || parser->tok != ';') {
3153 parseerror(parser, "semicolon expected after goto label");
3156 if (!parser_next(parser)) {
3157 parseerror(parser, "parse error after goto");
3161 *out = (ast_expression*)gt;
3165 static bool parse_skipwhite(parser_t *parser)
3168 if (!parser_next(parser))
3170 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3171 return parser->tok < TOKEN_ERROR;
3174 static bool parse_eol(parser_t *parser)
3176 if (!parse_skipwhite(parser))
3178 return parser->tok == TOKEN_EOL;
3181 static bool parse_pragma_do(parser_t *parser)
3183 if (!parser_next(parser) ||
3184 parser->tok != TOKEN_IDENT ||
3185 strcmp(parser_tokval(parser), "pragma"))
3187 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3190 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3191 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3195 if (!strcmp(parser_tokval(parser), "noref")) {
3196 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3197 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3200 parser->noref = !!parser_token(parser)->constval.i;
3201 if (!parse_eol(parser)) {
3202 parseerror(parser, "parse error after `noref` pragma");
3208 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3215 static bool parse_pragma(parser_t *parser)
3218 parser->lex->flags.preprocessing = true;
3219 parser->lex->flags.mergelines = true;
3220 rv = parse_pragma_do(parser);
3221 if (parser->tok != TOKEN_EOL) {
3222 parseerror(parser, "junk after pragma");
3225 parser->lex->flags.preprocessing = false;
3226 parser->lex->flags.mergelines = false;
3227 if (!parser_next(parser)) {
3228 parseerror(parser, "parse error after pragma");
3234 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3236 bool noref, is_static;
3238 uint32_t qflags = 0;
3239 ast_value *typevar = NULL;
3240 char *vstring = NULL;
3244 if (parser->tok == TOKEN_IDENT)
3245 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3247 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3249 /* local variable */
3251 parseerror(parser, "cannot declare a variable from here");
3254 if (opts.standard == COMPILER_QCC) {
3255 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3258 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3262 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3264 if (cvq == CV_WRONG)
3266 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3268 else if (parser->tok == TOKEN_KEYWORD)
3270 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3275 if (!parser_next(parser)) {
3276 parseerror(parser, "parse error after __builtin_debug_printtype");
3280 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3282 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3283 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3284 if (!parser_next(parser)) {
3285 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3291 if (!parse_statement(parser, block, out, allow_cases))
3294 con_out("__builtin_debug_printtype: got no output node\n");
3297 ast_type_to_string(*out, ty, sizeof(ty));
3298 con_out("__builtin_debug_printtype: `%s`\n", ty);
3303 else if (!strcmp(parser_tokval(parser), "return"))
3305 return parse_return(parser, block, out);
3307 else if (!strcmp(parser_tokval(parser), "if"))
3309 return parse_if(parser, block, out);
3311 else if (!strcmp(parser_tokval(parser), "while"))
3313 return parse_while(parser, block, out);
3315 else if (!strcmp(parser_tokval(parser), "do"))
3317 return parse_dowhile(parser, block, out);
3319 else if (!strcmp(parser_tokval(parser), "for"))
3321 if (opts.standard == COMPILER_QCC) {
3322 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3325 return parse_for(parser, block, out);
3327 else if (!strcmp(parser_tokval(parser), "break"))
3329 return parse_break_continue(parser, block, out, false);
3331 else if (!strcmp(parser_tokval(parser), "continue"))
3333 return parse_break_continue(parser, block, out, true);
3335 else if (!strcmp(parser_tokval(parser), "switch"))
3337 return parse_switch(parser, block, out);
3339 else if (!strcmp(parser_tokval(parser), "case") ||
3340 !strcmp(parser_tokval(parser), "default"))
3343 parseerror(parser, "unexpected 'case' label");
3348 else if (!strcmp(parser_tokval(parser), "goto"))
3350 return parse_goto(parser, out);
3352 else if (!strcmp(parser_tokval(parser), "typedef"))
3354 if (!parser_next(parser)) {
3355 parseerror(parser, "expected type definition after 'typedef'");
3358 return parse_typedef(parser);
3360 parseerror(parser, "Unexpected keyword");
3363 else if (parser->tok == '{')
3366 inner = parse_block(parser);
3369 *out = (ast_expression*)inner;
3372 else if (parser->tok == ':')
3376 if (!parser_next(parser)) {
3377 parseerror(parser, "expected label name");
3380 if (parser->tok != TOKEN_IDENT) {
3381 parseerror(parser, "label must be an identifier");
3384 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3386 if (!label->undefined) {
3387 parseerror(parser, "label `%s` already defined", label->name);
3390 label->undefined = false;
3393 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3394 vec_push(parser->labels, label);
3396 *out = (ast_expression*)label;
3397 if (!parser_next(parser)) {
3398 parseerror(parser, "parse error after label");
3401 for (i = 0; i < vec_size(parser->gotos); ++i) {
3402 if (!strcmp(parser->gotos[i]->name, label->name)) {
3403 ast_goto_set_label(parser->gotos[i], label);
3404 vec_remove(parser->gotos, i, 1);
3410 else if (parser->tok == ';')
3412 if (!parser_next(parser)) {
3413 parseerror(parser, "parse error after empty statement");
3420 ast_expression *exp = parse_expression(parser, false, false);
3424 if (!ast_side_effects(exp)) {
3425 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3432 static bool parse_enum(parser_t *parser)
3435 ast_value **values = NULL;
3436 ast_value *var = NULL;
3439 ast_expression *old;
3441 if (!parser_next(parser) || parser->tok != '{') {
3442 parseerror(parser, "expected `{` after `enum` keyword");
3447 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3448 if (parser->tok == '}') {
3449 /* allow an empty enum */
3452 parseerror(parser, "expected identifier or `}`");
3456 old = parser_find_field(parser, parser_tokval(parser));
3458 old = parser_find_global(parser, parser_tokval(parser));
3460 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3461 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3465 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3466 vec_push(values, var);
3467 var->cvq = CV_CONST;
3468 var->hasvalue = true;
3469 var->constval.vfloat = num++;
3471 parser_addglobal(parser, var->name, (ast_expression*)var);
3473 if (!parser_next(parser)) {
3474 parseerror(parser, "expected `=`, `}` or comma after identifier");
3478 if (parser->tok == ',')
3480 if (parser->tok == '}')
3482 if (parser->tok != '=') {
3483 parseerror(parser, "expected `=`, `}` or comma after identifier");
3487 if (!parser_next(parser)) {
3488 parseerror(parser, "expected expression after `=`");
3492 /* We got a value! */
3493 old = parse_expression_leave(parser, true, false, false);
3494 asvalue = (ast_value*)old;
3495 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3496 compile_error(ast_ctx(var), "constant value or expression expected");
3499 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3501 if (parser->tok == '}')
3503 if (parser->tok != ',') {
3504 parseerror(parser, "expected `}` or comma after expression");
3509 if (parser->tok != '}') {
3510 parseerror(parser, "internal error: breaking without `}`");
3514 if (!parser_next(parser) || parser->tok != ';') {
3515 parseerror(parser, "expected semicolon after enumeration");
3519 if (!parser_next(parser)) {
3520 parseerror(parser, "parse error after enumeration");
3532 static bool parse_block_into(parser_t *parser, ast_block *block)
3536 parser_enterblock(parser);
3538 if (!parser_next(parser)) { /* skip the '{' */
3539 parseerror(parser, "expected function body");
3543 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3545 ast_expression *expr = NULL;
3546 if (parser->tok == '}')
3549 if (!parse_statement(parser, block, &expr, false)) {
3550 /* parseerror(parser, "parse error"); */
3556 if (!ast_block_add_expr(block, expr)) {
3563 if (parser->tok != '}') {
3566 (void)parser_next(parser);
3570 if (!parser_leaveblock(parser))
3572 return retval && !!block;
3575 static ast_block* parse_block(parser_t *parser)
3578 block = ast_block_new(parser_ctx(parser));
3581 if (!parse_block_into(parser, block)) {
3582 ast_block_delete(block);
3588 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3590 if (parser->tok == '{') {
3591 *out = (ast_expression*)parse_block(parser);
3594 return parse_statement(parser, NULL, out, false);
3597 static bool create_vector_members(ast_value *var, ast_member **me)
3600 size_t len = strlen(var->name);
3602 for (i = 0; i < 3; ++i) {
3603 char *name = (char*)mem_a(len+3);
3604 memcpy(name, var->name, len);
3606 name[len+1] = 'x'+i;
3608 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3617 do { ast_member_delete(me[--i]); } while(i);
3621 static bool parse_function_body(parser_t *parser, ast_value *var)
3623 ast_block *block = NULL;
3628 ast_expression *framenum = NULL;
3629 ast_expression *nextthink = NULL;
3630 /* None of the following have to be deleted */
3631 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3632 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3633 bool has_frame_think;
3637 has_frame_think = false;
3638 old = parser->function;
3640 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3641 parseerror(parser, "gotos/labels leaking");
3645 if (var->expression.flags & AST_FLAG_VARIADIC) {
3646 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3647 "variadic function with implementation will not be able to access additional parameters"))
3653 if (parser->tok == '[') {
3654 /* got a frame definition: [ framenum, nextthink ]
3655 * this translates to:
3656 * self.frame = framenum;
3657 * self.nextthink = time + 0.1;
3658 * self.think = nextthink;
3662 fld_think = parser_find_field(parser, "think");
3663 fld_nextthink = parser_find_field(parser, "nextthink");
3664 fld_frame = parser_find_field(parser, "frame");
3665 if (!fld_think || !fld_nextthink || !fld_frame) {
3666 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3667 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3670 gbl_time = parser_find_global(parser, "time");
3671 gbl_self = parser_find_global(parser, "self");
3672 if (!gbl_time || !gbl_self) {
3673 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3674 parseerror(parser, "please declare the following globals: `time`, `self`");
3678 if (!parser_next(parser))
3681 framenum = parse_expression_leave(parser, true, false, false);
3683 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3686 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3687 ast_unref(framenum);
3688 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3692 if (parser->tok != ',') {
3693 ast_unref(framenum);
3694 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3695 parseerror(parser, "Got a %i\n", parser->tok);
3699 if (!parser_next(parser)) {
3700 ast_unref(framenum);
3704 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3706 /* qc allows the use of not-yet-declared functions here
3707 * - this automatically creates a prototype */
3708 ast_value *thinkfunc;
3709 ast_expression *functype = fld_think->expression.next;
3711 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3712 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3713 ast_unref(framenum);
3714 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3718 if (!parser_next(parser)) {
3719 ast_unref(framenum);
3720 ast_delete(thinkfunc);
3724 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3726 nextthink = (ast_expression*)thinkfunc;
3729 nextthink = parse_expression_leave(parser, true, false, false);
3731 ast_unref(framenum);
3732 parseerror(parser, "expected a think-function in [frame,think] notation");
3737 if (!ast_istype(nextthink, ast_value)) {
3738 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3742 if (retval && parser->tok != ']') {
3743 parseerror(parser, "expected closing `]` for [frame,think] notation");
3747 if (retval && !parser_next(parser)) {
3751 if (retval && parser->tok != '{') {
3752 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3757 ast_unref(nextthink);
3758 ast_unref(framenum);
3762 has_frame_think = true;
3765 block = ast_block_new(parser_ctx(parser));
3767 parseerror(parser, "failed to allocate block");
3768 if (has_frame_think) {
3769 ast_unref(nextthink);
3770 ast_unref(framenum);
3775 if (has_frame_think) {
3777 ast_expression *self_frame;
3778 ast_expression *self_nextthink;
3779 ast_expression *self_think;
3780 ast_expression *time_plus_1;
3781 ast_store *store_frame;
3782 ast_store *store_nextthink;
3783 ast_store *store_think;
3785 ctx = parser_ctx(parser);
3786 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3787 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3788 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3790 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3791 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3793 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3794 if (self_frame) ast_delete(self_frame);
3795 if (self_nextthink) ast_delete(self_nextthink);
3796 if (self_think) ast_delete(self_think);
3797 if (time_plus_1) ast_delete(time_plus_1);
3803 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3804 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3805 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3808 ast_delete(self_frame);
3811 if (!store_nextthink) {
3812 ast_delete(self_nextthink);
3816 ast_delete(self_think);
3820 if (store_frame) ast_delete(store_frame);
3821 if (store_nextthink) ast_delete(store_nextthink);
3822 if (store_think) ast_delete(store_think);
3825 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3826 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3827 !ast_block_add_expr(block, (ast_expression*)store_think))
3834 parseerror(parser, "failed to generate code for [frame,think]");
3835 ast_unref(nextthink);
3836 ast_unref(framenum);
3842 parser_enterblock(parser);
3844 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3846 ast_value *param = var->expression.params[parami];
3849 if (param->expression.vtype != TYPE_VECTOR &&
3850 (param->expression.vtype != TYPE_FIELD ||
3851 param->expression.next->expression.vtype != TYPE_VECTOR))
3856 if (!create_vector_members(param, me)) {
3857 ast_block_delete(block);
3861 for (e = 0; e < 3; ++e) {
3862 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3863 ast_block_collect(block, (ast_expression*)me[e]);
3867 func = ast_function_new(ast_ctx(var), var->name, var);
3869 parseerror(parser, "failed to allocate function for `%s`", var->name);
3870 ast_block_delete(block);
3873 vec_push(parser->functions, func);
3875 parser->function = func;
3876 if (!parse_block_into(parser, block)) {
3877 ast_block_delete(block);
3881 vec_push(func->blocks, block);
3883 parser->function = old;
3884 if (!parser_leaveblock(parser))
3886 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3887 parseerror(parser, "internal error: local scopes left");
3891 if (parser->tok == ';')
3892 return parser_next(parser);
3893 else if (opts.standard == COMPILER_QCC)
3894 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3898 vec_pop(parser->functions);
3899 ast_function_delete(func);
3900 var->constval.vfunc = NULL;
3903 (void)!parser_leaveblock(parser);
3904 parser->function = old;
3908 static ast_expression *array_accessor_split(
3913 ast_expression *left,
3914 ast_expression *right
3920 lex_ctx ctx = ast_ctx(array);
3922 if (!left || !right) {
3923 if (left) ast_delete(left);
3924 if (right) ast_delete(right);
3928 cmp = ast_binary_new(ctx, INSTR_LT,
3929 (ast_expression*)index,
3930 (ast_expression*)parser_const_float(parser, middle));
3934 parseerror(parser, "internal error: failed to create comparison for array setter");
3938 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3940 ast_delete(cmp); /* will delete left and right */
3941 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3945 return (ast_expression*)ifthen;
3948 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3950 lex_ctx ctx = ast_ctx(array);
3952 if (from+1 == afterend) {
3953 /* set this value */
3956 ast_array_index *subscript;
3958 int assignop = type_store_instr[value->expression.vtype];
3960 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3961 assignop = INSTR_STORE_V;
3963 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3967 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3969 ast_delete(subscript);
3973 block = ast_block_new(ctx);
3979 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3984 ret = ast_return_new(ctx, NULL);
3990 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3995 return (ast_expression*)block;
3997 ast_expression *left, *right;
3998 size_t diff = afterend - from;
3999 size_t middle = from + diff/2;
4000 left = array_setter_node(parser, array, index, value, from, middle);
4001 right = array_setter_node(parser, array, index, value, middle, afterend);
4002 return array_accessor_split(parser, array, index, middle, left, right);
4006 static ast_expression *array_field_setter_node(
4015 lex_ctx ctx = ast_ctx(array);
4017 if (from+1 == afterend) {
4018 /* set this value */
4021 ast_entfield *entfield;
4022 ast_array_index *subscript;
4024 int assignop = type_storep_instr[value->expression.vtype];
4026 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4027 assignop = INSTR_STOREP_V;
4029 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4033 entfield = ast_entfield_new_force(ctx,
4034 (ast_expression*)entity,
4035 (ast_expression*)subscript,
4036 (ast_expression*)subscript);
4038 ast_delete(subscript);
4042 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4044 ast_delete(entfield);
4048 block = ast_block_new(ctx);
4054 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4059 ret = ast_return_new(ctx, NULL);
4065 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4070 return (ast_expression*)block;
4072 ast_expression *left, *right;
4073 size_t diff = afterend - from;
4074 size_t middle = from + diff/2;
4075 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4076 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4077 return array_accessor_split(parser, array, index, middle, left, right);
4081 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4083 lex_ctx ctx = ast_ctx(array);
4085 if (from+1 == afterend) {
4087 ast_array_index *subscript;
4089 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4093 ret = ast_return_new(ctx, (ast_expression*)subscript);
4095 ast_delete(subscript);
4099 return (ast_expression*)ret;
4101 ast_expression *left, *right;
4102 size_t diff = afterend - from;
4103 size_t middle = from + diff/2;
4104 left = array_getter_node(parser, array, index, from, middle);
4105 right = array_getter_node(parser, array, index, middle, afterend);
4106 return array_accessor_split(parser, array, index, middle, left, right);
4110 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4112 ast_function *func = NULL;
4113 ast_value *fval = NULL;
4114 ast_block *body = NULL;
4116 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4118 parseerror(parser, "failed to create accessor function value");
4122 func = ast_function_new(ast_ctx(array), funcname, fval);
4125 parseerror(parser, "failed to create accessor function node");
4129 body = ast_block_new(ast_ctx(array));
4131 parseerror(parser, "failed to create block for array accessor");
4137 vec_push(func->blocks, body);
4140 vec_push(parser->accessors, fval);
4145 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4147 ast_expression *root = NULL;
4148 ast_value *index = NULL;
4149 ast_value *value = NULL;
4153 if (!ast_istype(array->expression.next, ast_value)) {
4154 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4158 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4160 func = fval->constval.vfunc;
4161 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4163 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4164 value = ast_value_copy((ast_value*)array->expression.next);
4166 if (!index || !value) {
4167 parseerror(parser, "failed to create locals for array accessor");
4170 (void)!ast_value_set_name(value, "value"); /* not important */
4171 vec_push(fval->expression.params, index);
4172 vec_push(fval->expression.params, value);
4174 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4176 parseerror(parser, "failed to build accessor search tree");
4180 array->setter = fval;
4181 return ast_block_add_expr(func->blocks[0], root);
4183 if (index) ast_delete(index);
4184 if (value) ast_delete(value);
4185 if (root) ast_delete(root);
4191 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4193 ast_expression *root = NULL;
4194 ast_value *entity = NULL;
4195 ast_value *index = NULL;
4196 ast_value *value = NULL;
4200 if (!ast_istype(array->expression.next, ast_value)) {
4201 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4205 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4207 func = fval->constval.vfunc;
4208 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4210 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4211 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4212 value = ast_value_copy((ast_value*)array->expression.next);
4213 if (!entity || !index || !value) {
4214 parseerror(parser, "failed to create locals for array accessor");
4217 (void)!ast_value_set_name(value, "value"); /* not important */
4218 vec_push(fval->expression.params, entity);
4219 vec_push(fval->expression.params, index);
4220 vec_push(fval->expression.params, value);
4222 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4224 parseerror(parser, "failed to build accessor search tree");
4228 array->setter = fval;
4229 return ast_block_add_expr(func->blocks[0], root);
4231 if (entity) ast_delete(entity);
4232 if (index) ast_delete(index);
4233 if (value) ast_delete(value);
4234 if (root) ast_delete(root);
4240 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4242 ast_expression *root = NULL;
4243 ast_value *index = NULL;
4247 /* NOTE: checking array->expression.next rather than elemtype since
4248 * for fields elemtype is a temporary fieldtype.
4250 if (!ast_istype(array->expression.next, ast_value)) {
4251 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4255 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4257 func = fval->constval.vfunc;
4258 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4260 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4263 parseerror(parser, "failed to create locals for array accessor");
4266 vec_push(fval->expression.params, index);
4268 root = array_getter_node(parser, array, index, 0, array->expression.count);
4270 parseerror(parser, "failed to build accessor search tree");
4274 array->getter = fval;
4275 return ast_block_add_expr(func->blocks[0], root);
4277 if (index) ast_delete(index);
4278 if (root) ast_delete(root);
4284 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4285 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4293 bool variadic = false;
4294 ast_value *varparam = NULL;
4295 char *argcounter = NULL;
4297 ctx = parser_ctx(parser);
4299 /* for the sake of less code we parse-in in this function */
4300 if (!parser_next(parser)) {
4301 parseerror(parser, "expected parameter list");
4307 /* parse variables until we hit a closing paren */
4308 while (parser->tok != ')') {
4310 /* there must be commas between them */
4311 if (parser->tok != ',') {
4312 parseerror(parser, "expected comma or end of parameter list");
4315 if (!parser_next(parser)) {
4316 parseerror(parser, "expected parameter");
4322 if (parser->tok == TOKEN_DOTS) {
4323 /* '...' indicates a varargs function */
4325 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4326 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4329 if (parser->tok == TOKEN_IDENT) {
4330 argcounter = util_strdup(parser_tokval(parser));
4331 if (!parser_next(parser) || parser->tok != ')') {
4332 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4339 /* for anything else just parse a typename */
4340 param = parse_typename(parser, NULL, NULL);
4343 vec_push(params, param);
4344 if (param->expression.vtype >= TYPE_VARIANT) {
4345 char tname[1024]; /* typename is reserved in C++ */
4346 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4347 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4350 /* type-restricted varargs */
4351 if (parser->tok == TOKEN_DOTS) {
4353 varparam = vec_last(params);
4355 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4356 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4359 if (parser->tok == TOKEN_IDENT) {
4360 argcounter = util_strdup(parser_tokval(parser));
4361 if (!parser_next(parser) || parser->tok != ')') {
4362 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4370 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4374 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4375 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4378 if (!parser_next(parser)) {
4379 parseerror(parser, "parse error after typename");
4383 /* now turn 'var' into a function type */
4384 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4385 fval->expression.next = (ast_expression*)var;
4387 fval->expression.flags |= AST_FLAG_VARIADIC;
4390 var->expression.params = params;
4391 var->expression.varparam = (ast_expression*)varparam;
4392 var->argcounter = argcounter;
4401 for (i = 0; i < vec_size(params); ++i)
4402 ast_delete(params[i]);
4407 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4409 ast_expression *cexp;
4410 ast_value *cval, *tmp;
4413 ctx = parser_ctx(parser);
4415 if (!parser_next(parser)) {
4417 parseerror(parser, "expected array-size");
4421 cexp = parse_expression_leave(parser, true, false, false);
4423 if (!cexp || !ast_istype(cexp, ast_value)) {
4427 parseerror(parser, "expected array-size as constant positive integer");
4430 cval = (ast_value*)cexp;
4432 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4433 tmp->expression.next = (ast_expression*)var;
4436 if (cval->expression.vtype == TYPE_INTEGER)
4437 tmp->expression.count = cval->constval.vint;
4438 else if (cval->expression.vtype == TYPE_FLOAT)
4439 tmp->expression.count = cval->constval.vfloat;
4443 parseerror(parser, "array-size must be a positive integer constant");
4448 if (parser->tok != ']') {
4450 parseerror(parser, "expected ']' after array-size");
4453 if (!parser_next(parser)) {
4455 parseerror(parser, "error after parsing array size");
4461 /* Parse a complete typename.
4462 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4463 * but when parsing variables separated by comma
4464 * 'storebase' should point to where the base-type should be kept.
4465 * The base type makes up every bit of type information which comes *before* the
4468 * The following will be parsed in its entirety:
4470 * The 'basetype' in this case is 'void()'
4471 * and if there's a comma after it, say:
4473 * then the type-information 'void()' can be stored in 'storebase'
4475 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4477 ast_value *var, *tmp;
4480 const char *name = NULL;
4481 bool isfield = false;
4482 bool wasarray = false;
4483 size_t morefields = 0;
4485 ctx = parser_ctx(parser);
4487 /* types may start with a dot */
4488 if (parser->tok == '.') {
4490 /* if we parsed a dot we need a typename now */
4491 if (!parser_next(parser)) {
4492 parseerror(parser, "expected typename for field definition");
4496 /* Further dots are handled seperately because they won't be part of the
4499 while (parser->tok == '.') {
4501 if (!parser_next(parser)) {
4502 parseerror(parser, "expected typename for field definition");
4507 if (parser->tok == TOKEN_IDENT)
4508 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4509 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4510 parseerror(parser, "expected typename");
4514 /* generate the basic type value */
4515 if (cached_typedef) {
4516 var = ast_value_copy(cached_typedef);
4517 ast_value_set_name(var, "<type(from_def)>");
4519 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4521 for (; morefields; --morefields) {
4522 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4523 tmp->expression.next = (ast_expression*)var;
4527 /* do not yet turn into a field - remember:
4528 * .void() foo; is a field too
4529 * .void()() foo; is a function
4533 if (!parser_next(parser)) {
4535 parseerror(parser, "parse error after typename");
4539 /* an opening paren now starts the parameter-list of a function
4540 * this is where original-QC has parameter lists.
4541 * We allow a single parameter list here.
4542 * Much like fteqcc we don't allow `float()() x`
4544 if (parser->tok == '(') {
4545 var = parse_parameter_list(parser, var);
4550 /* store the base if requested */
4552 *storebase = ast_value_copy(var);
4554 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4555 tmp->expression.next = (ast_expression*)*storebase;
4560 /* there may be a name now */
4561 if (parser->tok == TOKEN_IDENT) {
4562 name = util_strdup(parser_tokval(parser));
4564 if (!parser_next(parser)) {
4566 parseerror(parser, "error after variable or field declaration");
4571 /* now this may be an array */
4572 if (parser->tok == '[') {
4574 var = parse_arraysize(parser, var);
4579 /* This is the point where we can turn it into a field */
4581 /* turn it into a field if desired */
4582 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4583 tmp->expression.next = (ast_expression*)var;
4587 /* now there may be function parens again */
4588 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4589 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4590 if (parser->tok == '(' && wasarray)
4591 parseerror(parser, "arrays as part of a return type is not supported");
4592 while (parser->tok == '(') {
4593 var = parse_parameter_list(parser, var);
4602 /* finally name it */
4604 if (!ast_value_set_name(var, name)) {
4606 parseerror(parser, "internal error: failed to set name");
4609 /* free the name, ast_value_set_name duplicates */
4616 static bool parse_typedef(parser_t *parser)
4618 ast_value *typevar, *oldtype;
4619 ast_expression *old;
4621 typevar = parse_typename(parser, NULL, NULL);
4626 if ( (old = parser_find_var(parser, typevar->name)) ) {
4627 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4628 " -> `%s` has been declared here: %s:%i",
4629 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4630 ast_delete(typevar);
4634 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4635 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4636 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4637 ast_delete(typevar);
4641 vec_push(parser->_typedefs, typevar);
4642 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4644 if (parser->tok != ';') {
4645 parseerror(parser, "expected semicolon after typedef");
4648 if (!parser_next(parser)) {
4649 parseerror(parser, "parse error after typedef");
4656 static const char *cvq_to_str(int cvq) {
4658 case CV_NONE: return "none";
4659 case CV_VAR: return "`var`";
4660 case CV_CONST: return "`const`";
4661 default: return "<INVALID>";
4665 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4668 if (proto->cvq != var->cvq) {
4669 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4670 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4671 parser->tok == '='))
4673 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4674 "`%s` declared with different qualifiers: %s\n"
4675 " -> previous declaration here: %s:%i uses %s",
4676 var->name, cvq_to_str(var->cvq),
4677 ast_ctx(proto).file, ast_ctx(proto).line,
4678 cvq_to_str(proto->cvq));
4681 av = (var ->expression.flags & AST_FLAG_NORETURN);
4682 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4684 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4685 "`%s` declared with different attributes%s\n"
4686 " -> previous declaration here: %s:%i",
4687 var->name, (av ? ": noreturn" : ""),
4688 ast_ctx(proto).file, ast_ctx(proto).line,
4689 (ao ? ": noreturn" : ""));
4694 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)
4698 ast_expression *old;
4702 ast_value *basetype = NULL;
4704 bool isparam = false;
4705 bool isvector = false;
4706 bool cleanvar = true;
4707 bool wasarray = false;
4711 if (!localblock && is_static)
4712 parseerror(parser, "`static` qualifier is not supported in global scope");
4714 /* get the first complete variable */
4715 var = parse_typename(parser, &basetype, cached_typedef);
4718 ast_delete(basetype);
4726 /* Part 0: finish the type */
4727 if (parser->tok == '(') {
4728 if (opts.standard == COMPILER_QCC)
4729 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4730 var = parse_parameter_list(parser, var);
4736 /* we only allow 1-dimensional arrays */
4737 if (parser->tok == '[') {
4739 var = parse_arraysize(parser, var);
4745 if (parser->tok == '(' && wasarray) {
4746 parseerror(parser, "arrays as part of a return type is not supported");
4747 /* we'll still parse the type completely for now */
4749 /* for functions returning functions */
4750 while (parser->tok == '(') {
4751 if (opts.standard == COMPILER_QCC)
4752 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4753 var = parse_parameter_list(parser, var);
4760 var->cvq = qualifier;
4761 var->expression.flags |= qflags;
4762 if (var->expression.flags & AST_FLAG_DEPRECATED)
4763 var->desc = vstring;
4766 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4767 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4768 * is then filled with the previous definition and the parameter-names replaced.
4770 if (!strcmp(var->name, "nil")) {
4771 if (OPTS_FLAG(UNTYPED_NIL)) {
4772 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4773 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4775 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4778 /* Deal with end_sys_ vars */
4780 if (!strcmp(var->name, "end_sys_globals")) {
4782 parser->crc_globals = vec_size(parser->globals);
4785 else if (!strcmp(var->name, "end_sys_fields")) {
4787 parser->crc_fields = vec_size(parser->fields);
4790 if (was_end && var->expression.vtype == TYPE_FIELD) {
4791 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4792 "global '%s' hint should not be a field",
4793 parser_tokval(parser)))
4800 if (!nofields && var->expression.vtype == TYPE_FIELD)
4802 /* deal with field declarations */
4803 old = parser_find_field(parser, var->name);
4805 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4806 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4815 parseerror(parser, "field `%s` already declared here: %s:%i",
4816 var->name, ast_ctx(old).file, ast_ctx(old).line);
4821 if (opts.standard == COMPILER_QCC &&
4822 (old = parser_find_global(parser, var->name)))
4824 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4825 parseerror(parser, "field `%s` already declared here: %s:%i",
4826 var->name, ast_ctx(old).file, ast_ctx(old).line);
4833 /* deal with other globals */
4834 old = parser_find_global(parser, var->name);
4835 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4837 /* This is a function which had a prototype */
4838 if (!ast_istype(old, ast_value)) {
4839 parseerror(parser, "internal error: prototype is not an ast_value");
4843 proto = (ast_value*)old;
4844 proto->desc = var->desc;
4845 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4846 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4848 ast_ctx(proto).file, ast_ctx(proto).line);
4852 /* we need the new parameter-names */
4853 for (i = 0; i < vec_size(proto->expression.params); ++i)
4854 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4855 if (!parser_check_qualifiers(parser, var, proto)) {
4862 proto->expression.flags |= var->expression.flags;
4870 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4871 "global `%s` already declared here: %s:%i",
4872 var->name, ast_ctx(old).file, ast_ctx(old).line))
4877 proto = (ast_value*)old;
4878 if (!ast_istype(old, ast_value)) {
4879 parseerror(parser, "internal error: not an ast_value");
4884 if (!parser_check_qualifiers(parser, var, proto)) {
4889 proto->expression.flags |= var->expression.flags;
4893 if (opts.standard == COMPILER_QCC &&
4894 (old = parser_find_field(parser, var->name)))
4896 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4897 parseerror(parser, "global `%s` already declared here: %s:%i",
4898 var->name, ast_ctx(old).file, ast_ctx(old).line);
4905 else /* it's not a global */
4907 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4908 if (old && !isparam) {
4909 parseerror(parser, "local `%s` already declared here: %s:%i",
4910 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4914 old = parser_find_local(parser, var->name, 0, &isparam);
4915 if (old && isparam) {
4916 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4917 "local `%s` is shadowing a parameter", var->name))
4919 parseerror(parser, "local `%s` already declared here: %s:%i",
4920 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4924 if (opts.standard != COMPILER_GMQCC) {
4932 /* in a noref section we simply bump the usecount */
4933 if (noref || parser->noref)
4937 * Create the global/local, and deal with vector types.
4940 if (var->expression.vtype == TYPE_VECTOR)
4942 else if (var->expression.vtype == TYPE_FIELD &&
4943 var->expression.next->expression.vtype == TYPE_VECTOR)
4947 if (!create_vector_members(var, me)) {
4954 /* deal with global variables, fields, functions */
4955 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4956 var->isfield = true;
4957 vec_push(parser->fields, (ast_expression*)var);
4958 util_htset(parser->htfields, var->name, var);
4960 for (i = 0; i < 3; ++i) {
4961 vec_push(parser->fields, (ast_expression*)me[i]);
4962 util_htset(parser->htfields, me[i]->name, me[i]);
4967 parser_addglobal(parser, var->name, (ast_expression*)var);
4969 for (i = 0; i < 3; ++i) {
4970 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
4976 /* a static adds itself to be generated like any other global
4977 * but is added to the local namespace instead
4979 char *defname = NULL;
4980 size_t prefix_len, ln;
4982 ln = strlen(parser->function->name);
4983 vec_append(defname, ln, parser->function->name);
4985 vec_append(defname, 2, "::");
4986 /* remember the length up to here */
4987 prefix_len = vec_size(defname);
4989 /* Add it to the local scope */
4990 util_htset(vec_last(parser->variables), var->name, (void*)var);
4994 vec_last(parser->correct_variables),
4995 &vec_last(parser->correct_variables_score),
4999 /* now rename the global */
5000 ln = strlen(var->name);
5001 vec_append(defname, ln, var->name);
5002 ast_value_set_name(var, defname);
5004 /* push it to the to-be-generated globals */
5005 vec_push(parser->globals, (ast_expression*)var);
5007 /* same game for the vector members */
5009 for (i = 0; i < 3; ++i) {
5010 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5014 vec_last(parser->correct_variables),
5015 &vec_last(parser->correct_variables_score),
5019 vec_shrinkto(defname, prefix_len);
5020 ln = strlen(me[i]->name);
5021 vec_append(defname, ln, me[i]->name);
5022 ast_member_set_name(me[i], defname);
5024 vec_push(parser->globals, (ast_expression*)me[i]);
5029 vec_push(localblock->locals, var);
5030 parser_addlocal(parser, var->name, (ast_expression*)var);
5032 for (i = 0; i < 3; ++i) {
5033 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5034 ast_block_collect(localblock, (ast_expression*)me[i]);
5040 me[0] = me[1] = me[2] = NULL;
5045 if (var->expression.vtype == TYPE_ARRAY) {
5047 snprintf(name, sizeof(name), "%s##SET", var->name);
5048 if (!parser_create_array_setter(parser, var, name))
5050 snprintf(name, sizeof(name), "%s##GET", var->name);
5051 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5054 else if (!localblock && !nofields &&
5055 var->expression.vtype == TYPE_FIELD &&
5056 var->expression.next->expression.vtype == TYPE_ARRAY)
5059 ast_expression *telem;
5061 ast_value *array = (ast_value*)var->expression.next;
5063 if (!ast_istype(var->expression.next, ast_value)) {
5064 parseerror(parser, "internal error: field element type must be an ast_value");
5068 snprintf(name, sizeof(name), "%s##SETF", var->name);
5069 if (!parser_create_array_field_setter(parser, array, name))
5072 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5073 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5074 tfield->expression.next = telem;
5075 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5076 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5084 if (parser->tok == ';') {
5085 ast_delete(basetype);
5086 if (!parser_next(parser)) {
5087 parseerror(parser, "error after variable declaration");
5093 if (parser->tok == ',')
5097 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5100 parseerror(parser, "missing comma or semicolon while parsing variables");
5104 if (localblock && opts.standard == COMPILER_QCC) {
5105 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5106 "initializing expression turns variable `%s` into a constant in this standard",
5113 if (parser->tok != '{') {
5114 if (parser->tok != '=') {
5115 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5119 if (!parser_next(parser)) {
5120 parseerror(parser, "error parsing initializer");
5124 else if (opts.standard == COMPILER_QCC) {
5125 parseerror(parser, "expected '=' before function body in this standard");
5128 if (parser->tok == '#') {
5129 ast_function *func = NULL;
5132 parseerror(parser, "cannot declare builtins within functions");
5135 if (var->expression.vtype != TYPE_FUNCTION) {
5136 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5139 if (!parser_next(parser)) {
5140 parseerror(parser, "expected builtin number");
5143 if (parser->tok != TOKEN_INTCONST) {
5144 parseerror(parser, "builtin number must be an integer constant");
5147 if (parser_token(parser)->constval.i < 0) {
5148 parseerror(parser, "builtin number must be an integer greater than zero");
5152 if (var->hasvalue) {
5153 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5154 "builtin `%s` has already been defined\n"
5155 " -> previous declaration here: %s:%i",
5156 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5160 func = ast_function_new(ast_ctx(var), var->name, var);
5162 parseerror(parser, "failed to allocate function for `%s`", var->name);
5165 vec_push(parser->functions, func);
5167 func->builtin = -parser_token(parser)->constval.i-1;
5170 if (!parser_next(parser)) {
5171 parseerror(parser, "expected comma or semicolon");
5173 ast_function_delete(func);
5174 var->constval.vfunc = NULL;
5178 else if (parser->tok == '{' || parser->tok == '[')
5181 parseerror(parser, "cannot declare functions within functions");
5186 ast_ctx(proto) = parser_ctx(parser);
5188 if (!parse_function_body(parser, var))
5190 ast_delete(basetype);
5191 for (i = 0; i < vec_size(parser->gotos); ++i)
5192 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5193 vec_free(parser->gotos);
5194 vec_free(parser->labels);
5197 ast_expression *cexp;
5200 cexp = parse_expression_leave(parser, true, false, false);
5205 cval = (ast_value*)cexp;
5206 if (cval != parser->nil &&
5207 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5210 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5214 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5215 qualifier != CV_VAR)
5217 var->cvq = CV_CONST;
5219 if (cval == parser->nil)
5220 var->expression.flags |= AST_FLAG_INITIALIZED;
5223 var->hasvalue = true;
5224 if (cval->expression.vtype == TYPE_STRING)
5225 var->constval.vstring = parser_strdup(cval->constval.vstring);
5226 else if (cval->expression.vtype == TYPE_FIELD)
5227 var->constval.vfield = cval;
5229 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5235 shunt sy = { NULL, NULL };
5238 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5239 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5240 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5241 if (!parser_sy_apply_operator(parser, &sy))
5244 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5245 parseerror(parser, "internal error: leaked operands");
5246 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5256 if (parser->tok == ',') {
5257 if (!parser_next(parser)) {
5258 parseerror(parser, "expected another variable");
5262 if (parser->tok != TOKEN_IDENT) {
5263 parseerror(parser, "expected another variable");
5266 var = ast_value_copy(basetype);
5268 ast_value_set_name(var, parser_tokval(parser));
5269 if (!parser_next(parser)) {
5270 parseerror(parser, "error parsing variable declaration");
5276 if (parser->tok != ';') {
5277 parseerror(parser, "missing semicolon after variables");
5281 if (!parser_next(parser)) {
5282 parseerror(parser, "parse error after variable declaration");
5286 ast_delete(basetype);
5290 if (cleanvar && var)
5292 ast_delete(basetype);
5296 ast_delete(basetype);
5297 if (cleanvar && var)
5299 if (me[0]) ast_member_delete(me[0]);
5300 if (me[1]) ast_member_delete(me[1]);
5301 if (me[2]) ast_member_delete(me[2]);
5305 static bool parser_global_statement(parser_t *parser)
5309 bool is_static = false;
5310 uint32_t qflags = 0;
5311 ast_value *istype = NULL;
5312 char *vstring = NULL;
5314 if (parser->tok == TOKEN_IDENT)
5315 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5317 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5319 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5321 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5323 if (cvq == CV_WRONG)
5325 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5327 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5329 return parse_enum(parser);
5331 else if (parser->tok == TOKEN_KEYWORD)
5333 if (!strcmp(parser_tokval(parser), "typedef")) {
5334 if (!parser_next(parser)) {
5335 parseerror(parser, "expected type definition after 'typedef'");
5338 return parse_typedef(parser);
5340 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5343 else if (parser->tok == '#')
5345 return parse_pragma(parser);
5347 else if (parser->tok == '$')
5349 if (!parser_next(parser)) {
5350 parseerror(parser, "parse error");
5356 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5362 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5364 return util_crc16(old, str, strlen(str));
5367 static void progdefs_crc_file(const char *str)
5369 /* write to progdefs.h here */
5373 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5375 old = progdefs_crc_sum(old, str);
5376 progdefs_crc_file(str);
5380 static void generate_checksum(parser_t *parser)
5382 uint16_t crc = 0xFFFF;
5386 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5387 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5389 progdefs_crc_file("\tint\tpad;\n");
5390 progdefs_crc_file("\tint\tofs_return[3];\n");
5391 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5392 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5393 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5394 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5395 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5396 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5397 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5398 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5400 for (i = 0; i < parser->crc_globals; ++i) {
5401 if (!ast_istype(parser->globals[i], ast_value))
5403 value = (ast_value*)(parser->globals[i]);
5404 switch (value->expression.vtype) {
5405 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5406 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5407 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5408 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5410 crc = progdefs_crc_both(crc, "\tint\t");
5413 crc = progdefs_crc_both(crc, value->name);
5414 crc = progdefs_crc_both(crc, ";\n");
5416 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5417 for (i = 0; i < parser->crc_fields; ++i) {
5418 if (!ast_istype(parser->fields[i], ast_value))
5420 value = (ast_value*)(parser->fields[i]);
5421 switch (value->expression.next->expression.vtype) {
5422 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5423 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5424 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5425 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5427 crc = progdefs_crc_both(crc, "\tint\t");
5430 crc = progdefs_crc_both(crc, value->name);
5431 crc = progdefs_crc_both(crc, ";\n");
5433 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5438 static parser_t *parser;
5445 parser = (parser_t*)mem_a(sizeof(parser_t));
5449 memset(parser, 0, sizeof(*parser));
5451 for (i = 0; i < operator_count; ++i) {
5452 if (operators[i].id == opid1('=')) {
5453 parser->assign_op = operators+i;
5457 if (!parser->assign_op) {
5458 printf("internal error: initializing parser: failed to find assign operator\n");
5463 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5464 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5465 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5466 vec_push(parser->_blocktypedefs, 0);
5469 vec_push(parser->correct_variables, correct_trie_new());
5470 vec_push(parser->correct_variables_score, NULL);
5472 empty_ctx.file = "<internal>";
5474 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5475 parser->nil->cvq = CV_CONST;
5476 if (OPTS_FLAG(UNTYPED_NIL))
5477 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5479 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5480 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5481 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5483 if (opts.add_info) {
5484 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5485 parser->reserved_version->cvq = CV_CONST;
5486 parser->reserved_version->hasvalue = true;
5487 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5488 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5490 parser->reserved_version = NULL;
5495 bool parser_compile()
5497 /* initial lexer/parser state */
5498 parser->lex->flags.noops = true;
5500 if (parser_next(parser))
5502 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5504 if (!parser_global_statement(parser)) {
5505 if (parser->tok == TOKEN_EOF)
5506 parseerror(parser, "unexpected eof");
5507 else if (compile_errors)
5508 parseerror(parser, "there have been errors, bailing out");
5509 lex_close(parser->lex);
5515 parseerror(parser, "parse error");
5516 lex_close(parser->lex);
5521 lex_close(parser->lex);
5524 return !compile_errors;
5527 bool parser_compile_file(const char *filename)
5529 parser->lex = lex_open(filename);
5531 con_err("failed to open file \"%s\"\n", filename);
5534 return parser_compile();
5537 bool parser_compile_string(const char *name, const char *str, size_t len)
5539 parser->lex = lex_open_string(str, len, name);
5541 con_err("failed to create lexer for string \"%s\"\n", name);
5544 return parser_compile();
5547 void parser_cleanup()
5550 for (i = 0; i < vec_size(parser->accessors); ++i) {
5551 ast_delete(parser->accessors[i]->constval.vfunc);
5552 parser->accessors[i]->constval.vfunc = NULL;
5553 ast_delete(parser->accessors[i]);
5555 for (i = 0; i < vec_size(parser->functions); ++i) {
5556 ast_delete(parser->functions[i]);
5558 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5559 ast_delete(parser->imm_vector[i]);
5561 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5562 ast_delete(parser->imm_string[i]);
5564 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5565 ast_delete(parser->imm_float[i]);
5567 for (i = 0; i < vec_size(parser->fields); ++i) {
5568 ast_delete(parser->fields[i]);
5570 for (i = 0; i < vec_size(parser->globals); ++i) {
5571 ast_delete(parser->globals[i]);
5573 vec_free(parser->accessors);
5574 vec_free(parser->functions);
5575 vec_free(parser->imm_vector);
5576 vec_free(parser->imm_string);
5577 vec_free(parser->imm_float);
5578 vec_free(parser->globals);
5579 vec_free(parser->fields);
5581 for (i = 0; i < vec_size(parser->variables); ++i)
5582 util_htdel(parser->variables[i]);
5583 vec_free(parser->variables);
5584 vec_free(parser->_blocklocals);
5585 vec_free(parser->_locals);
5588 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5589 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5591 vec_free(parser->correct_variables);
5592 vec_free(parser->correct_variables_score);
5595 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5596 ast_delete(parser->_typedefs[i]);
5597 vec_free(parser->_typedefs);
5598 for (i = 0; i < vec_size(parser->typedefs); ++i)
5599 util_htdel(parser->typedefs[i]);
5600 vec_free(parser->typedefs);
5601 vec_free(parser->_blocktypedefs);
5603 vec_free(parser->_block_ctx);
5605 vec_free(parser->labels);
5606 vec_free(parser->gotos);
5607 vec_free(parser->breaks);
5608 vec_free(parser->continues);
5610 ast_value_delete(parser->nil);
5612 ast_value_delete(parser->const_vec[0]);
5613 ast_value_delete(parser->const_vec[1]);
5614 ast_value_delete(parser->const_vec[2]);
5619 bool parser_finish(const char *output)
5625 if (compile_errors) {
5626 con_out("*** there were compile errors\n");
5630 ir = ir_builder_new("gmqcc_out");
5632 con_out("failed to allocate builder\n");
5636 for (i = 0; i < vec_size(parser->fields); ++i) {
5639 if (!ast_istype(parser->fields[i], ast_value))
5641 field = (ast_value*)parser->fields[i];
5642 hasvalue = field->hasvalue;
5643 field->hasvalue = false;
5644 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5645 con_out("failed to generate field %s\n", field->name);
5646 ir_builder_delete(ir);
5651 ast_expression *subtype;
5652 field->hasvalue = true;
5653 subtype = field->expression.next;
5654 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5655 if (subtype->expression.vtype == TYPE_FIELD)
5656 ifld->fieldtype = subtype->expression.next->expression.vtype;
5657 else if (subtype->expression.vtype == TYPE_FUNCTION)
5658 ifld->outtype = subtype->expression.next->expression.vtype;
5659 (void)!ir_value_set_field(field->ir_v, ifld);
5662 for (i = 0; i < vec_size(parser->globals); ++i) {
5664 if (!ast_istype(parser->globals[i], ast_value))
5666 asvalue = (ast_value*)(parser->globals[i]);
5667 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5668 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5669 "unused global: `%s`", asvalue->name);
5671 if (!ast_global_codegen(asvalue, ir, false)) {
5672 con_out("failed to generate global %s\n", asvalue->name);
5673 ir_builder_delete(ir);
5677 if (parser->reserved_version &&
5678 !ast_global_codegen(parser->reserved_version, ir, false))
5680 con_out("failed to generate reserved::version");
5681 ir_builder_delete(ir);
5684 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5685 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5686 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5687 ir_builder_delete(ir);
5691 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5692 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5693 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5694 ir_builder_delete(ir);
5698 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5699 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5700 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5701 ir_builder_delete(ir);
5705 for (i = 0; i < vec_size(parser->globals); ++i) {
5707 if (!ast_istype(parser->globals[i], ast_value))
5709 asvalue = (ast_value*)(parser->globals[i]);
5710 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5712 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5713 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5714 "uninitialized constant: `%s`",
5716 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5717 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5718 "uninitialized global: `%s`",
5721 if (!ast_generate_accessors(asvalue, ir)) {
5722 ir_builder_delete(ir);
5726 for (i = 0; i < vec_size(parser->fields); ++i) {
5728 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5730 if (!ast_istype((ast_expression*)asvalue, ast_value))
5732 if (asvalue->expression.vtype != TYPE_ARRAY)
5734 if (!ast_generate_accessors(asvalue, ir)) {
5735 ir_builder_delete(ir);
5739 for (i = 0; i < vec_size(parser->functions); ++i) {
5740 if (!ast_function_codegen(parser->functions[i], ir)) {
5741 con_out("failed to generate function %s\n", parser->functions[i]->name);
5742 ir_builder_delete(ir);
5747 ir_builder_dump(ir, con_out);
5748 for (i = 0; i < vec_size(parser->functions); ++i) {
5749 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5750 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5751 ir_builder_delete(ir);
5756 if (compile_Werrors) {
5757 con_out("*** there were warnings treated as errors\n");
5758 compile_show_werrors();
5764 ir_builder_dump(ir, con_out);
5766 generate_checksum(parser);
5768 if (!ir_builder_generate(ir, output)) {
5769 con_out("*** failed to generate output file\n");
5770 ir_builder_delete(ir);
5775 ir_builder_delete(ir);