2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
37 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_vector_zero;
61 ast_function *function;
63 /* All the labels the function defined...
64 * Should they be in ast_function instead?
69 const char **continues;
71 /* A list of hashtables for each scope */
77 /* same as above but for the spelling corrector */
78 correct_trie_t **correct_variables;
79 size_t ***correct_variables_score; /* vector of vector of size_t* */
81 /* not to be used directly, we use the hash table */
82 ast_expression **_locals;
84 ast_value **_typedefs;
85 size_t *_blocktypedefs;
88 /* we store the '=' operator info */
89 const oper_info *assign_op;
91 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
92 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
93 * anything else: type error
97 /* Keep track of our ternary vs parenthesis nesting state.
98 * If we reach a 'comma' operator in a ternary without a paren,
99 * we shall trigger -Wternary-precedence.
101 enum parser_pot *pot;
107 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
109 static void parser_enterblock(parser_t *parser);
110 static bool parser_leaveblock(parser_t *parser);
111 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
112 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
113 static bool parse_typedef(parser_t *parser);
114 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);
115 static ast_block* parse_block(parser_t *parser);
116 static bool parse_block_into(parser_t *parser, ast_block *block);
117 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
118 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
119 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
120 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
122 static void parseerror(parser_t *parser, const char *fmt, ...)
126 vcompile_error(parser->lex->tok.ctx, fmt, ap);
130 /* returns true if it counts as an error */
131 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
136 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
141 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
146 r = vcompile_warning(ctx, warntype, fmt, ap);
151 /**********************************************************************
152 * some maths used for constant folding
155 vector vec3_add(vector a, vector b)
164 vector vec3_sub(vector a, vector b)
173 qcfloat vec3_mulvv(vector a, vector b)
175 return (a.x * b.x + a.y * b.y + a.z * b.z);
178 vector vec3_mulvf(vector a, float b)
187 /**********************************************************************
191 bool parser_next(parser_t *parser)
193 /* lex_do kills the previous token */
194 parser->tok = lex_do(parser->lex);
195 if (parser->tok == TOKEN_EOF)
197 if (parser->tok >= TOKEN_ERROR) {
198 parseerror(parser, "lex error");
204 #define parser_tokval(p) ((p)->lex->tok.value)
205 #define parser_token(p) (&((p)->lex->tok))
206 #define parser_ctx(p) ((p)->lex->tok.ctx)
208 static ast_value* parser_const_float(parser_t *parser, double d)
212 for (i = 0; i < vec_size(parser->imm_float); ++i) {
213 const double compare = parser->imm_float[i]->constval.vfloat;
214 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
215 return parser->imm_float[i];
217 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
219 out->hasvalue = true;
220 out->constval.vfloat = d;
221 vec_push(parser->imm_float, out);
225 static ast_value* parser_const_float_0(parser_t *parser)
227 if (!parser->imm_float_zero)
228 parser->imm_float_zero = parser_const_float(parser, 0);
229 return parser->imm_float_zero;
232 static ast_value* parser_const_float_1(parser_t *parser)
234 if (!parser->imm_float_one)
235 parser->imm_float_one = parser_const_float(parser, 1);
236 return parser->imm_float_one;
239 static char *parser_strdup(const char *str)
242 /* actually dup empty strings */
243 char *out = (char*)mem_a(1);
247 return util_strdup(str);
250 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
254 for (i = 0; i < vec_size(parser->imm_string); ++i) {
255 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
256 return parser->imm_string[i];
260 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
261 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
263 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
265 out->hasvalue = true;
266 out->constval.vstring = parser_strdup(str);
267 vec_push(parser->imm_string, out);
271 static ast_value* parser_const_vector(parser_t *parser, vector v)
275 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
276 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
277 return parser->imm_vector[i];
279 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
281 out->hasvalue = true;
282 out->constval.vvec = v;
283 vec_push(parser->imm_vector, out);
287 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
293 return parser_const_vector(parser, v);
296 static ast_value* parser_const_vector_0(parser_t *parser)
298 if (!parser->imm_vector_zero)
299 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
300 return parser->imm_vector_zero;
303 static ast_expression* parser_find_field(parser_t *parser, const char *name)
305 return ( ast_expression*)util_htget(parser->htfields, name);
308 static ast_expression* parser_find_label(parser_t *parser, const char *name)
311 for(i = 0; i < vec_size(parser->labels); i++)
312 if (!strcmp(parser->labels[i]->name, name))
313 return (ast_expression*)parser->labels[i];
317 static ast_expression* parser_find_global(parser_t *parser, const char *name)
319 return (ast_expression*)util_htget(parser->htglobals, name);
322 static ast_expression* parser_find_param(parser_t *parser, const char *name)
326 if (!parser->function)
328 fun = parser->function->vtype;
329 for (i = 0; i < vec_size(fun->expression.params); ++i) {
330 if (!strcmp(fun->expression.params[i]->name, name))
331 return (ast_expression*)(fun->expression.params[i]);
336 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
341 hash = util_hthash(parser->htglobals, name);
344 for (i = vec_size(parser->variables); i > upto;) {
346 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
350 return parser_find_param(parser, name);
353 static ast_expression* parser_find_var(parser_t *parser, const char *name)
357 v = parser_find_local(parser, name, 0, &dummy);
358 if (!v) v = parser_find_global(parser, name);
362 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
366 hash = util_hthash(parser->typedefs[0], name);
368 for (i = vec_size(parser->typedefs); i > upto;) {
370 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
378 size_t etype; /* 0 = expression, others are operators */
382 ast_block *block; /* for commas and function calls */
391 #define SY_PAREN_EXPR '('
392 #define SY_PAREN_FUNC 'f'
393 #define SY_PAREN_INDEX '['
394 #define SY_PAREN_TERNARY '?'
396 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
407 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
411 e.out = (ast_expression*)v;
418 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
420 e.etype = 1 + (op - operators);
429 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
441 # define DEBUGSHUNTDO(x) x
443 # define DEBUGSHUNTDO(x)
446 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
447 * so we need to rotate it to become ent.(foo[n]).
449 static bool rotate_entfield_array_index_nodes(ast_expression **out)
451 ast_array_index *index;
452 ast_entfield *entfield;
456 ast_expression *entity;
458 lex_ctx ctx = ast_ctx(*out);
460 if (!ast_istype(*out, ast_array_index))
462 index = (ast_array_index*)*out;
464 if (!ast_istype(index->array, ast_entfield))
466 entfield = (ast_entfield*)index->array;
468 if (!ast_istype(entfield->field, ast_value))
470 field = (ast_value*)entfield->field;
473 entity = entfield->entity;
477 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
478 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
479 *out = (ast_expression*)entfield;
484 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
486 switch (v->expression.vtype) {
488 return !!v->constval.vfloat;
490 return !!v->constval.vint;
492 if (OPTS_FLAG(CORRECT_LOGIC))
493 return v->constval.vvec.x &&
494 v->constval.vvec.y &&
497 return !!(v->constval.vvec.x);
499 if (!v->constval.vstring)
501 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
503 return !!v->constval.vstring[0];
505 compile_error(ctx, "internal error: immediate_is_true on invalid type");
506 return !!v->constval.vfunc;
510 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
514 ast_expression *out = NULL;
515 ast_expression *exprs[3];
516 ast_block *blocks[3];
517 ast_value *asvalue[3];
518 ast_binstore *asbinstore;
519 size_t i, assignop, addop, subop;
520 qcint generated_op = 0;
525 if (!vec_size(sy->ops)) {
526 parseerror(parser, "internal error: missing operator");
530 if (vec_last(sy->ops).paren) {
531 parseerror(parser, "unmatched parenthesis");
535 op = &operators[vec_last(sy->ops).etype - 1];
536 ctx = vec_last(sy->ops).ctx;
538 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
540 if (vec_size(sy->out) < op->operands) {
541 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
542 op->op, (int)op->id);
546 vec_shrinkby(sy->ops, 1);
548 /* op(:?) has no input and no output */
552 vec_shrinkby(sy->out, op->operands);
553 for (i = 0; i < op->operands; ++i) {
554 exprs[i] = sy->out[vec_size(sy->out)+i].out;
555 blocks[i] = sy->out[vec_size(sy->out)+i].block;
556 asvalue[i] = (ast_value*)exprs[i];
558 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
559 !(i != 0 && op->id == opid2('?',':')))
561 if (ast_istype(exprs[i], ast_label))
562 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
564 compile_error(ast_ctx(exprs[i]), "not an expression");
565 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
569 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
570 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
574 #define NotSameType(T) \
575 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
576 exprs[0]->expression.vtype != T)
577 #define CanConstFold1(A) \
578 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
579 (A)->expression.vtype != TYPE_FUNCTION)
580 #define CanConstFold(A, B) \
581 (CanConstFold1(A) && CanConstFold1(B))
582 #define ConstV(i) (asvalue[(i)]->constval.vvec)
583 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
584 #define ConstS(i) (asvalue[(i)]->constval.vstring)
588 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
592 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
593 if (exprs[1]->expression.vtype != TYPE_FIELD) {
594 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
597 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
599 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
600 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
604 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
610 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
611 !(exprs[0]->expression.vtype == TYPE_FIELD &&
612 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
614 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
615 parseerror(parser, "cannot index value of type %s", ty1);
618 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
619 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
620 parseerror(parser, "index must be of type float, not %s", ty1);
623 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
624 if (rotate_entfield_array_index_nodes(&out))
627 /* This is not broken in fteqcc anymore */
628 if (opts.standard != COMPILER_GMQCC) {
629 /* this error doesn't need to make us bail out */
630 (void)!parsewarning(parser, WARN_EXTENSIONS,
631 "accessing array-field members of an entity without parenthesis\n"
632 " -> this is an extension from -std=gmqcc");
640 if (!ast_block_add_expr(blocks[0], exprs[1]))
643 blocks[0] = ast_block_new(ctx);
644 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
645 !ast_block_add_expr(blocks[0], exprs[1]))
650 if (!ast_block_set_type(blocks[0], exprs[1]))
653 vec_push(sy->out, syblock(ctx, blocks[0]));
660 switch (exprs[0]->expression.vtype) {
662 if (CanConstFold1(exprs[0]))
663 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
665 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
666 (ast_expression*)parser_const_float_0(parser),
670 if (CanConstFold1(exprs[0]))
671 out = (ast_expression*)parser_const_vector_f(parser,
672 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
674 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
675 (ast_expression*)parser_const_vector_0(parser),
679 parseerror(parser, "invalid types used in expression: cannot negate type %s",
680 type_name[exprs[0]->expression.vtype]);
686 switch (exprs[0]->expression.vtype) {
688 if (CanConstFold1(exprs[0]))
689 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
691 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
694 if (CanConstFold1(exprs[0]))
695 out = (ast_expression*)parser_const_float(parser,
696 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
698 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
701 if (CanConstFold1(exprs[0])) {
702 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
703 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
705 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
707 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
708 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
710 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
713 /* we don't constant-fold NOT for these types */
715 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
718 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
721 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
722 type_name[exprs[0]->expression.vtype]);
728 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
729 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
731 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
732 type_name[exprs[0]->expression.vtype],
733 type_name[exprs[1]->expression.vtype]);
736 switch (exprs[0]->expression.vtype) {
738 if (CanConstFold(exprs[0], exprs[1]))
740 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
743 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
746 if (CanConstFold(exprs[0], exprs[1]))
747 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
749 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
752 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
753 type_name[exprs[0]->expression.vtype],
754 type_name[exprs[1]->expression.vtype]);
759 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
760 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
762 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
763 type_name[exprs[1]->expression.vtype],
764 type_name[exprs[0]->expression.vtype]);
767 switch (exprs[0]->expression.vtype) {
769 if (CanConstFold(exprs[0], exprs[1]))
770 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
772 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
775 if (CanConstFold(exprs[0], exprs[1]))
776 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
778 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
781 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
782 type_name[exprs[1]->expression.vtype],
783 type_name[exprs[0]->expression.vtype]);
788 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
789 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
790 exprs[1]->expression.vtype == TYPE_FLOAT) &&
791 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
792 exprs[0]->expression.vtype == TYPE_FLOAT)
795 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
796 type_name[exprs[1]->expression.vtype],
797 type_name[exprs[0]->expression.vtype]);
800 switch (exprs[0]->expression.vtype) {
802 if (exprs[1]->expression.vtype == TYPE_VECTOR)
804 if (CanConstFold(exprs[0], exprs[1]))
805 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
807 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
811 if (CanConstFold(exprs[0], exprs[1]))
812 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
814 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
818 if (exprs[1]->expression.vtype == TYPE_FLOAT)
820 if (CanConstFold(exprs[0], exprs[1]))
821 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
823 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
827 if (CanConstFold(exprs[0], exprs[1]))
828 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
829 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
830 vector vec = ConstV(0);
831 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
832 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
833 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
834 out->expression.node.keep = false;
835 ((ast_member*)out)->rvalue = true;
837 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
839 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
840 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
841 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
842 out->expression.node.keep = false;
843 ((ast_member*)out)->rvalue = true;
845 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
847 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
848 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
849 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, 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.z), out);
856 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
858 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
859 vector vec = ConstV(1);
860 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
861 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
862 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
863 out->expression.node.keep = false;
864 ((ast_member*)out)->rvalue = true;
866 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
868 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
869 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
870 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
871 out->expression.node.keep = false;
872 ((ast_member*)out)->rvalue = true;
874 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
876 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
877 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
878 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, 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.z));
885 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
888 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
892 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
893 type_name[exprs[1]->expression.vtype],
894 type_name[exprs[0]->expression.vtype]);
899 if (NotSameType(TYPE_FLOAT)) {
900 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
901 type_name[exprs[0]->expression.vtype],
902 type_name[exprs[1]->expression.vtype]);
905 if (CanConstFold(exprs[0], exprs[1]))
906 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
908 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
912 parseerror(parser, "qc does not have a modulo operator");
916 if (NotSameType(TYPE_FLOAT)) {
917 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
918 type_name[exprs[0]->expression.vtype],
919 type_name[exprs[1]->expression.vtype]);
922 if (CanConstFold(exprs[0], exprs[1]))
923 out = (ast_expression*)parser_const_float(parser,
924 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
925 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
927 out = (ast_expression*)ast_binary_new(ctx,
928 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
932 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
937 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
938 if (op->id == opid2('<','<'))
939 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
941 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
944 case opid3('<','<','='):
945 case opid3('>','>','='):
946 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
950 generated_op += 1; /* INSTR_OR */
952 generated_op += INSTR_AND;
954 if (NotSameType(TYPE_FLOAT)) {
955 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
956 type_name[exprs[0]->expression.vtype],
957 type_name[exprs[1]->expression.vtype]);
958 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
959 parseerror(parser, "TODO: optional early out");
963 if (CanConstFold(exprs[0], exprs[1]))
965 if (OPTS_FLAG(PERL_LOGIC)) {
966 if (immediate_is_true(ctx, asvalue[0]))
970 out = (ast_expression*)parser_const_float(parser,
971 ( (generated_op == INSTR_OR)
972 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
973 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
978 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
979 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
980 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
981 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
984 for (i = 0; i < 2; ++i) {
985 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
986 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
988 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
990 exprs[i] = out; out = NULL;
991 if (OPTS_FLAG(PERL_LOGIC)) {
992 /* here we want to keep the right expressions' type */
996 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
997 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
999 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1001 exprs[i] = out; out = NULL;
1002 if (OPTS_FLAG(PERL_LOGIC)) {
1003 /* here we want to keep the right expressions' type */
1008 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1012 case opid2('?',':'):
1013 if (vec_last(parser->pot) != POT_TERNARY2) {
1014 parseerror(parser, "mismatched parenthesis/ternary");
1017 vec_pop(parser->pot);
1018 if (!ast_compare_type(exprs[1], exprs[2])) {
1019 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1020 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1021 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1024 if (CanConstFold1(exprs[0]))
1025 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1027 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1031 generated_op += 1; /* INSTR_GT */
1033 generated_op += 1; /* INSTR_LT */
1034 case opid2('>', '='):
1035 generated_op += 1; /* INSTR_GE */
1036 case opid2('<', '='):
1037 generated_op += INSTR_LE;
1038 if (NotSameType(TYPE_FLOAT)) {
1039 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1040 type_name[exprs[0]->expression.vtype],
1041 type_name[exprs[1]->expression.vtype]);
1044 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1046 case opid2('!', '='):
1047 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1048 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1049 type_name[exprs[0]->expression.vtype],
1050 type_name[exprs[1]->expression.vtype]);
1053 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1055 case opid2('=', '='):
1056 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1057 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1058 type_name[exprs[0]->expression.vtype],
1059 type_name[exprs[1]->expression.vtype]);
1062 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1066 if (ast_istype(exprs[0], ast_entfield)) {
1067 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1068 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1069 exprs[0]->expression.vtype == TYPE_FIELD &&
1070 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1072 assignop = type_storep_instr[TYPE_VECTOR];
1075 assignop = type_storep_instr[exprs[0]->expression.vtype];
1076 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1078 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1079 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1080 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1081 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1082 exprs[1]->expression.vtype == TYPE_FUNCTION)
1084 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1085 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1088 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1093 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1094 exprs[0]->expression.vtype == TYPE_FIELD &&
1095 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1097 assignop = type_store_instr[TYPE_VECTOR];
1100 assignop = type_store_instr[exprs[0]->expression.vtype];
1103 if (assignop == AINSTR_END) {
1104 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1105 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1106 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1108 else if (!ast_compare_type(exprs[0], exprs[1]))
1110 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1111 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1112 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1113 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1114 exprs[1]->expression.vtype == TYPE_FUNCTION)
1116 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1117 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1120 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1123 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1124 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1126 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1128 case opid3('+','+','P'):
1129 case opid3('-','-','P'):
1131 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1132 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1133 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1136 if (op->id == opid3('+','+','P'))
1137 addop = INSTR_ADD_F;
1139 addop = INSTR_SUB_F;
1140 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1141 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1143 if (ast_istype(exprs[0], ast_entfield)) {
1144 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1146 (ast_expression*)parser_const_float_1(parser));
1148 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1150 (ast_expression*)parser_const_float_1(parser));
1153 case opid3('S','+','+'):
1154 case opid3('S','-','-'):
1156 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1157 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1158 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1161 if (op->id == opid3('S','+','+')) {
1162 addop = INSTR_ADD_F;
1163 subop = INSTR_SUB_F;
1165 addop = INSTR_SUB_F;
1166 subop = INSTR_ADD_F;
1168 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1169 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1171 if (ast_istype(exprs[0], ast_entfield)) {
1172 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1174 (ast_expression*)parser_const_float_1(parser));
1176 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1178 (ast_expression*)parser_const_float_1(parser));
1182 out = (ast_expression*)ast_binary_new(ctx, subop,
1184 (ast_expression*)parser_const_float_1(parser));
1186 case opid2('+','='):
1187 case opid2('-','='):
1188 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1189 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1191 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1192 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1193 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1197 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1198 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1200 if (ast_istype(exprs[0], ast_entfield))
1201 assignop = type_storep_instr[exprs[0]->expression.vtype];
1203 assignop = type_store_instr[exprs[0]->expression.vtype];
1204 switch (exprs[0]->expression.vtype) {
1206 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1207 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1208 exprs[0], exprs[1]);
1211 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1212 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1213 exprs[0], exprs[1]);
1216 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1217 type_name[exprs[0]->expression.vtype],
1218 type_name[exprs[1]->expression.vtype]);
1222 case opid2('*','='):
1223 case opid2('/','='):
1224 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1225 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1226 exprs[0]->expression.vtype == TYPE_VECTOR))
1228 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1229 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1230 parseerror(parser, "invalid types used in expression: %s and %s",
1234 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1235 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1237 if (ast_istype(exprs[0], ast_entfield))
1238 assignop = type_storep_instr[exprs[0]->expression.vtype];
1240 assignop = type_store_instr[exprs[0]->expression.vtype];
1241 switch (exprs[0]->expression.vtype) {
1243 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1244 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1245 exprs[0], exprs[1]);
1248 if (op->id == opid2('*','=')) {
1249 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1250 exprs[0], exprs[1]);
1252 /* there's no DIV_VF */
1253 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1254 (ast_expression*)parser_const_float_1(parser),
1258 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1263 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1264 type_name[exprs[0]->expression.vtype],
1265 type_name[exprs[1]->expression.vtype]);
1269 case opid2('&','='):
1270 case opid2('|','='):
1271 if (NotSameType(TYPE_FLOAT)) {
1272 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1273 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1274 parseerror(parser, "invalid types used in expression: %s and %s",
1278 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1279 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1281 if (ast_istype(exprs[0], ast_entfield))
1282 assignop = type_storep_instr[exprs[0]->expression.vtype];
1284 assignop = type_store_instr[exprs[0]->expression.vtype];
1285 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1286 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1287 exprs[0], exprs[1]);
1289 case opid3('&','~','='):
1290 /* This is like: a &= ~(b);
1291 * But QC has no bitwise-not, so we implement it as
1294 if (NotSameType(TYPE_FLOAT)) {
1295 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1296 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1297 parseerror(parser, "invalid types used in expression: %s and %s",
1301 if (ast_istype(exprs[0], ast_entfield))
1302 assignop = type_storep_instr[exprs[0]->expression.vtype];
1304 assignop = type_store_instr[exprs[0]->expression.vtype];
1305 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1308 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1309 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1311 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1312 asbinstore->keep_dest = true;
1313 out = (ast_expression*)asbinstore;
1319 parseerror(parser, "failed to apply operand %s", op->op);
1323 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1324 vec_push(sy->out, syexp(ctx, out));
1328 static bool parser_close_call(parser_t *parser, shunt *sy)
1330 /* was a function call */
1331 ast_expression *fun;
1337 vec_shrinkby(sy->ops, 1);
1338 fid = sy->ops[vec_size(sy->ops)].off;
1340 /* out[fid] is the function
1341 * everything above is parameters...
1342 * 0 params = nothing
1343 * 1 params = ast_expression
1347 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1348 parseerror(parser, "internal error: function call needs function and parameter list...");
1352 fun = sy->out[fid].out;
1354 if (fun == intrinsic_debug_typestring) {
1356 if (fid+2 != vec_size(sy->out) ||
1357 vec_last(sy->out).block)
1359 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1362 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1363 ast_unref(vec_last(sy->out).out);
1364 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1365 (ast_expression*)parser_const_string(parser, ty, false));
1366 vec_shrinkby(sy->out, 1);
1370 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1372 parseerror(parser, "internal error: failed to create ast_call node");
1376 if (fid+1 == vec_size(sy->out)) {
1379 } else if (fid+2 == vec_size(sy->out)) {
1381 vec_shrinkby(sy->out, 1);
1382 params = sy->out[vec_size(sy->out)].block;
1386 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1388 paramcount = vec_size(params->exprs);
1389 call->params = params->exprs;
1390 params->exprs = NULL;
1393 (void)!ast_call_check_types(call);
1395 parseerror(parser, "invalid function call");
1399 /* overwrite fid, the function, with a call */
1400 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1402 if (fun->expression.vtype != TYPE_FUNCTION) {
1403 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1407 if (!fun->expression.next) {
1408 parseerror(parser, "could not determine function return type");
1411 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1413 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1415 return !parsewarning(parser, WARN_DEPRECATED,
1416 "call to function (which is marked deprecated)\n",
1417 "-> it has been declared here: %s:%i",
1418 ast_ctx(fun).file, ast_ctx(fun).line);
1421 return !parsewarning(parser, WARN_DEPRECATED,
1422 "call to `%s` (which is marked deprecated)\n"
1423 "-> `%s` declared here: %s:%i",
1424 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1426 return !parsewarning(parser, WARN_DEPRECATED,
1427 "call to `%s` (deprecated: %s)\n"
1428 "-> `%s` declared here: %s:%i",
1429 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1433 if (vec_size(fun->expression.params) != paramcount &&
1434 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1435 vec_size(fun->expression.params) < paramcount))
1437 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1439 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1440 "too %s parameters for call to %s: expected %i, got %i\n"
1441 " -> `%s` has been declared here: %s:%i",
1442 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1443 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1445 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1446 "too %s parameters for function call: expected %i, got %i\n"
1447 " -> it has been declared here: %s:%i",
1448 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1449 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1456 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1458 if (!vec_size(sy->ops)) {
1459 parseerror(parser, "unmatched closing paren");
1462 /* this would for bit a + (x) because there are no operators inside (x)
1463 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1464 parseerror(parser, "empty parenthesis expression");
1468 while (vec_size(sy->ops)) {
1469 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1470 if (!parser_close_call(parser, sy))
1474 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1475 vec_shrinkby(sy->ops, 1);
1476 return !functions_only;
1478 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1481 /* pop off the parenthesis */
1482 vec_shrinkby(sy->ops, 1);
1483 /* then apply the index operator */
1484 if (!parser_sy_apply_operator(parser, sy))
1488 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1491 if (vec_last(parser->pot) != POT_TERNARY1) {
1492 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1495 vec_last(parser->pot) = POT_TERNARY2;
1496 /* pop off the parenthesis */
1497 vec_shrinkby(sy->ops, 1);
1500 if (!parser_sy_apply_operator(parser, sy))
1506 static void parser_reclassify_token(parser_t *parser)
1509 for (i = 0; i < operator_count; ++i) {
1510 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1511 parser->tok = TOKEN_OPERATOR;
1517 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1519 ast_expression *expr = NULL;
1521 bool wantop = false;
1522 bool gotmemberof = false;
1523 /* only warn once about an assignment in a truth value because the current code
1524 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1526 bool warn_truthvalue = true;
1528 /* count the parens because an if starts with one, so the
1529 * end of a condition is an unmatched closing paren
1537 parser->lex->flags.noops = false;
1539 parser_reclassify_token(parser);
1544 gotmemberof = false;
1546 parser->memberof = 0;
1548 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1549 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1551 /* a translatable string */
1555 parseerror(parser, "expected operator or end of statement, got constant");
1559 parser->lex->flags.noops = true;
1560 if (!parser_next(parser) || parser->tok != '(') {
1561 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1564 parser->lex->flags.noops = false;
1565 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1566 parseerror(parser, "expected a constant string in translatable-string extension");
1569 val = parser_const_string(parser, parser_tokval(parser), true);
1573 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1574 DEBUGSHUNTDO(con_out("push string\n"));
1576 if (!parser_next(parser) || parser->tok != ')') {
1577 parseerror(parser, "expected closing paren after translatable string");
1581 else if (parser->tok == TOKEN_IDENT)
1583 ast_expression *var;
1585 parseerror(parser, "expected operator or end of statement");
1590 if (opts.standard == COMPILER_GMQCC)
1592 if (parser->memberof == TYPE_ENTITY) {
1593 /* still get vars first since there could be a fieldpointer */
1594 var = parser_find_var(parser, parser_tokval(parser));
1596 var = parser_find_field(parser, parser_tokval(parser));
1598 else if (parser->memberof == TYPE_VECTOR)
1600 parseerror(parser, "TODO: implement effective vector member access");
1603 else if (parser->memberof) {
1604 parseerror(parser, "namespace for member not found");
1608 var = parser_find_var(parser, parser_tokval(parser));
1610 var = parser_find_var(parser, parser_tokval(parser));
1612 var = parser_find_field(parser, parser_tokval(parser));
1614 if (!var && with_labels) {
1615 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1617 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1618 var = (ast_expression*)lbl;
1619 vec_push(parser->labels, lbl);
1624 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1625 var = (ast_expression*)intrinsic_debug_typestring;
1630 char *correct = NULL;
1633 * sometimes people use preprocessing predefs without enabling them
1634 * i've done this thousands of times already myself. Lets check for
1635 * it in the predef table. And diagnose it better :)
1637 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1638 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1639 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1640 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1647 * TODO: determine the best score for the identifier: be it
1648 * a variable, a field.
1650 * We should also consider adding correction tables for
1651 * other things as well.
1653 if (OPTS_FLAG(ENHANCED_DIAGNOSTICS)) {
1655 correct_init(&corr);
1657 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1658 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1659 if (strcmp(correct, parser_tokval(parser))) {
1661 } else if (correct) {
1666 correct_free(&corr);
1669 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1674 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1680 if (ast_istype(var, ast_value)) {
1681 ((ast_value*)var)->uses++;
1683 else if (ast_istype(var, ast_member)) {
1684 ast_member *mem = (ast_member*)var;
1685 if (ast_istype(mem->owner, ast_value))
1686 ((ast_value*)(mem->owner))->uses++;
1689 vec_push(sy.out, syexp(parser_ctx(parser), var));
1690 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1692 else if (parser->tok == TOKEN_FLOATCONST) {
1695 parseerror(parser, "expected operator or end of statement, got constant");
1699 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1702 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1703 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1705 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1708 parseerror(parser, "expected operator or end of statement, got constant");
1712 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1715 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1716 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1718 else if (parser->tok == TOKEN_STRINGCONST) {
1721 parseerror(parser, "expected operator or end of statement, got constant");
1725 val = parser_const_string(parser, parser_tokval(parser), false);
1728 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1729 DEBUGSHUNTDO(con_out("push string\n"));
1731 else if (parser->tok == TOKEN_VECTORCONST) {
1734 parseerror(parser, "expected operator or end of statement, got constant");
1738 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1741 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1742 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1743 parser_token(parser)->constval.v.x,
1744 parser_token(parser)->constval.v.y,
1745 parser_token(parser)->constval.v.z));
1747 else if (parser->tok == '(') {
1748 parseerror(parser, "internal error: '(' should be classified as operator");
1751 else if (parser->tok == '[') {
1752 parseerror(parser, "internal error: '[' should be classified as operator");
1755 else if (parser->tok == ')') {
1757 DEBUGSHUNTDO(con_out("do[op] )\n"));
1761 /* we do expect an operator next */
1762 /* closing an opening paren */
1763 if (!parser_close_paren(parser, &sy, false))
1765 if (vec_last(parser->pot) != POT_PAREN) {
1766 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1769 vec_pop(parser->pot);
1771 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1775 /* allowed for function calls */
1776 if (!parser_close_paren(parser, &sy, true))
1778 if (vec_last(parser->pot) != POT_PAREN) {
1779 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1782 vec_pop(parser->pot);
1786 else if (parser->tok == ']') {
1788 parseerror(parser, "operand expected");
1792 if (!parser_close_paren(parser, &sy, false))
1794 if (vec_last(parser->pot) != POT_PAREN) {
1795 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1798 vec_pop(parser->pot);
1801 else if (parser->tok == TOKEN_TYPENAME) {
1802 parseerror(parser, "unexpected typename");
1805 else if (parser->tok != TOKEN_OPERATOR) {
1807 parseerror(parser, "expected operator or end of statement");
1814 /* classify the operator */
1815 const oper_info *op;
1816 const oper_info *olast = NULL;
1818 for (o = 0; o < operator_count; ++o) {
1819 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1820 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1821 !strcmp(parser_tokval(parser), operators[o].op))
1826 if (o == operator_count) {
1827 /* no operator found... must be the end of the statement */
1830 /* found an operator */
1833 /* when declaring variables, a comma starts a new variable */
1834 if (op->id == opid1(',') && !parens && stopatcomma) {
1835 /* fixup the token */
1840 /* a colon without a pervious question mark cannot be a ternary */
1841 if (!ternaries && op->id == opid2(':','?')) {
1846 if (op->id == opid1(',')) {
1847 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1848 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1852 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1853 olast = &operators[vec_last(sy.ops).etype-1];
1855 #define IsAssignOp(x) (\
1856 (x) == opid1('=') || \
1857 (x) == opid2('+','=') || \
1858 (x) == opid2('-','=') || \
1859 (x) == opid2('*','=') || \
1860 (x) == opid2('/','=') || \
1861 (x) == opid2('%','=') || \
1862 (x) == opid2('&','=') || \
1863 (x) == opid2('|','=') || \
1864 (x) == opid3('&','~','=') \
1866 if (warn_truthvalue) {
1867 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1868 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1869 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1872 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1873 warn_truthvalue = false;
1878 (op->prec < olast->prec) ||
1879 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1881 if (!parser_sy_apply_operator(parser, &sy))
1883 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1884 olast = &operators[vec_last(sy.ops).etype-1];
1889 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1890 /* for gmqcc standard: open up the namespace of the previous type */
1891 ast_expression *prevex = vec_last(sy.out).out;
1893 parseerror(parser, "unexpected member operator");
1896 if (prevex->expression.vtype == TYPE_ENTITY)
1897 parser->memberof = TYPE_ENTITY;
1898 else if (prevex->expression.vtype == TYPE_VECTOR)
1899 parser->memberof = TYPE_VECTOR;
1901 parseerror(parser, "type error: type has no members");
1907 if (op->id == opid1('(')) {
1909 size_t sycount = vec_size(sy.out);
1910 DEBUGSHUNTDO(con_out("push [op] (\n"));
1911 ++parens; vec_push(parser->pot, POT_PAREN);
1912 /* we expected an operator, this is the function-call operator */
1913 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1915 ++parens; vec_push(parser->pot, POT_PAREN);
1916 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1917 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1920 } else if (op->id == opid1('[')) {
1922 parseerror(parser, "unexpected array subscript");
1925 ++parens; vec_push(parser->pot, POT_PAREN);
1926 /* push both the operator and the paren, this makes life easier */
1927 vec_push(sy.ops, syop(parser_ctx(parser), op));
1928 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1930 } else if (op->id == opid2('?',':')) {
1931 vec_push(sy.ops, syop(parser_ctx(parser), op));
1932 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1935 vec_push(parser->pot, POT_TERNARY1);
1936 } else if (op->id == opid2(':','?')) {
1937 if (!vec_size(parser->pot)) {
1938 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1941 if (vec_last(parser->pot) != POT_TERNARY1) {
1942 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1945 if (!parser_close_paren(parser, &sy, false))
1947 vec_push(sy.ops, syop(parser_ctx(parser), op));
1951 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1952 vec_push(sy.ops, syop(parser_ctx(parser), op));
1953 wantop = !!(op->flags & OP_SUFFIX);
1956 if (!parser_next(parser)) {
1959 if (parser->tok == ';' ||
1960 (!parens && parser->tok == ']'))
1966 while (vec_size(sy.ops)) {
1967 if (!parser_sy_apply_operator(parser, &sy))
1971 parser->lex->flags.noops = true;
1972 if (!vec_size(sy.out)) {
1973 parseerror(parser, "empty expression");
1976 expr = sy.out[0].out;
1979 DEBUGSHUNTDO(con_out("shunt done\n"));
1980 if (vec_size(parser->pot)) {
1981 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1984 vec_free(parser->pot);
1988 parser->lex->flags.noops = true;
1994 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1996 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1999 if (!parser_next(parser)) {
2006 static void parser_enterblock(parser_t *parser)
2008 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2009 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2010 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2011 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2012 vec_push(parser->_block_ctx, parser_ctx(parser));
2015 vec_push(parser->correct_variables, correct_trie_new());
2016 vec_push(parser->correct_variables_score, NULL);
2019 static bool parser_leaveblock(parser_t *parser)
2022 size_t locals, typedefs;
2024 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2025 parseerror(parser, "internal error: parser_leaveblock with no block");
2029 util_htdel(vec_last(parser->variables));
2030 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2032 vec_pop(parser->variables);
2033 vec_pop(parser->correct_variables);
2034 vec_pop(parser->correct_variables_score);
2035 if (!vec_size(parser->_blocklocals)) {
2036 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2040 locals = vec_last(parser->_blocklocals);
2041 vec_pop(parser->_blocklocals);
2042 while (vec_size(parser->_locals) != locals) {
2043 ast_expression *e = vec_last(parser->_locals);
2044 ast_value *v = (ast_value*)e;
2045 vec_pop(parser->_locals);
2046 if (ast_istype(e, ast_value) && !v->uses) {
2047 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2052 typedefs = vec_last(parser->_blocktypedefs);
2053 while (vec_size(parser->_typedefs) != typedefs) {
2054 ast_delete(vec_last(parser->_typedefs));
2055 vec_pop(parser->_typedefs);
2057 util_htdel(vec_last(parser->typedefs));
2058 vec_pop(parser->typedefs);
2060 vec_pop(parser->_block_ctx);
2065 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2067 vec_push(parser->_locals, e);
2068 util_htset(vec_last(parser->variables), name, (void*)e);
2072 vec_last(parser->correct_variables),
2073 &vec_last(parser->correct_variables_score),
2078 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2080 vec_push(parser->globals, e);
2081 util_htset(parser->htglobals, name, e);
2085 parser->correct_variables[0],
2086 &parser->correct_variables_score[0],
2091 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2095 ast_expression *prev;
2097 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2100 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2103 parseerror(parser, "internal error: failed to process condition");
2108 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2110 /* vector types need to be cast to true booleans */
2111 ast_binary *bin = (ast_binary*)cond;
2112 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2114 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2116 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2119 parseerror(parser, "internal error: failed to process condition");
2126 unary = (ast_unary*)cond;
2127 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2129 cond = unary->operand;
2130 unary->operand = NULL;
2133 unary = (ast_unary*)cond;
2137 parseerror(parser, "internal error: failed to process condition");
2139 if (ifnot) *_ifnot = !*_ifnot;
2143 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2146 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2149 lex_ctx ctx = parser_ctx(parser);
2151 (void)block; /* not touching */
2153 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2154 if (!parser_next(parser)) {
2155 parseerror(parser, "expected condition or 'not'");
2158 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2160 if (!parser_next(parser)) {
2161 parseerror(parser, "expected condition in parenthesis");
2165 if (parser->tok != '(') {
2166 parseerror(parser, "expected 'if' condition in parenthesis");
2169 /* parse into the expression */
2170 if (!parser_next(parser)) {
2171 parseerror(parser, "expected 'if' condition after opening paren");
2174 /* parse the condition */
2175 cond = parse_expression_leave(parser, false, true, false);
2179 if (parser->tok != ')') {
2180 parseerror(parser, "expected closing paren after 'if' condition");
2184 /* parse into the 'then' branch */
2185 if (!parser_next(parser)) {
2186 parseerror(parser, "expected statement for on-true branch of 'if'");
2190 if (!parse_statement_or_block(parser, &ontrue)) {
2195 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2196 /* check for an else */
2197 if (!strcmp(parser_tokval(parser), "else")) {
2198 /* parse into the 'else' branch */
2199 if (!parser_next(parser)) {
2200 parseerror(parser, "expected on-false branch after 'else'");
2205 if (!parse_statement_or_block(parser, &onfalse)) {
2212 cond = process_condition(parser, cond, &ifnot);
2214 if (ontrue) ast_delete(ontrue);
2215 if (onfalse) ast_delete(onfalse);
2220 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2222 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2223 *out = (ast_expression*)ifthen;
2227 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2228 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2233 /* skip the 'while' and get the body */
2234 if (!parser_next(parser)) {
2235 if (OPTS_FLAG(LOOP_LABELS))
2236 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2238 parseerror(parser, "expected 'while' condition in parenthesis");
2242 if (parser->tok == ':') {
2243 if (!OPTS_FLAG(LOOP_LABELS))
2244 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2245 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2246 parseerror(parser, "expected loop label");
2249 label = util_strdup(parser_tokval(parser));
2250 if (!parser_next(parser)) {
2252 parseerror(parser, "expected 'while' condition in parenthesis");
2257 if (parser->tok != '(') {
2258 parseerror(parser, "expected 'while' condition in parenthesis");
2262 vec_push(parser->breaks, label);
2263 vec_push(parser->continues, label);
2265 rv = parse_while_go(parser, block, out);
2268 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2269 parseerror(parser, "internal error: label stack corrupted");
2275 vec_pop(parser->breaks);
2276 vec_pop(parser->continues);
2281 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2284 ast_expression *cond, *ontrue;
2288 lex_ctx ctx = parser_ctx(parser);
2290 (void)block; /* not touching */
2292 /* parse into the expression */
2293 if (!parser_next(parser)) {
2294 parseerror(parser, "expected 'while' condition after opening paren");
2297 /* parse the condition */
2298 cond = parse_expression_leave(parser, false, true, false);
2302 if (parser->tok != ')') {
2303 parseerror(parser, "expected closing paren after 'while' condition");
2307 /* parse into the 'then' branch */
2308 if (!parser_next(parser)) {
2309 parseerror(parser, "expected while-loop body");
2313 if (!parse_statement_or_block(parser, &ontrue)) {
2318 cond = process_condition(parser, cond, &ifnot);
2323 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2324 *out = (ast_expression*)aloop;
2328 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2329 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2334 /* skip the 'do' and get the body */
2335 if (!parser_next(parser)) {
2336 if (OPTS_FLAG(LOOP_LABELS))
2337 parseerror(parser, "expected loop label or body");
2339 parseerror(parser, "expected loop body");
2343 if (parser->tok == ':') {
2344 if (!OPTS_FLAG(LOOP_LABELS))
2345 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2346 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2347 parseerror(parser, "expected loop label");
2350 label = util_strdup(parser_tokval(parser));
2351 if (!parser_next(parser)) {
2353 parseerror(parser, "expected loop body");
2358 vec_push(parser->breaks, label);
2359 vec_push(parser->continues, label);
2361 rv = parse_dowhile_go(parser, block, out);
2364 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2365 parseerror(parser, "internal error: label stack corrupted");
2371 vec_pop(parser->breaks);
2372 vec_pop(parser->continues);
2377 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2380 ast_expression *cond, *ontrue;
2384 lex_ctx ctx = parser_ctx(parser);
2386 (void)block; /* not touching */
2388 if (!parse_statement_or_block(parser, &ontrue))
2391 /* expect the "while" */
2392 if (parser->tok != TOKEN_KEYWORD ||
2393 strcmp(parser_tokval(parser), "while"))
2395 parseerror(parser, "expected 'while' and condition");
2400 /* skip the 'while' and check for opening paren */
2401 if (!parser_next(parser) || parser->tok != '(') {
2402 parseerror(parser, "expected 'while' condition in parenthesis");
2406 /* parse into the expression */
2407 if (!parser_next(parser)) {
2408 parseerror(parser, "expected 'while' condition after opening paren");
2412 /* parse the condition */
2413 cond = parse_expression_leave(parser, false, true, false);
2417 if (parser->tok != ')') {
2418 parseerror(parser, "expected closing paren after 'while' condition");
2424 if (!parser_next(parser) || parser->tok != ';') {
2425 parseerror(parser, "expected semicolon after condition");
2431 if (!parser_next(parser)) {
2432 parseerror(parser, "parse error");
2438 cond = process_condition(parser, cond, &ifnot);
2443 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2444 *out = (ast_expression*)aloop;
2448 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2449 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2454 /* skip the 'for' and check for opening paren */
2455 if (!parser_next(parser)) {
2456 if (OPTS_FLAG(LOOP_LABELS))
2457 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2459 parseerror(parser, "expected 'for' expressions in parenthesis");
2463 if (parser->tok == ':') {
2464 if (!OPTS_FLAG(LOOP_LABELS))
2465 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2466 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2467 parseerror(parser, "expected loop label");
2470 label = util_strdup(parser_tokval(parser));
2471 if (!parser_next(parser)) {
2473 parseerror(parser, "expected 'for' expressions in parenthesis");
2478 if (parser->tok != '(') {
2479 parseerror(parser, "expected 'for' expressions in parenthesis");
2483 vec_push(parser->breaks, label);
2484 vec_push(parser->continues, label);
2486 rv = parse_for_go(parser, block, out);
2489 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2490 parseerror(parser, "internal error: label stack corrupted");
2496 vec_pop(parser->breaks);
2497 vec_pop(parser->continues);
2501 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2504 ast_expression *initexpr, *cond, *increment, *ontrue;
2510 lex_ctx ctx = parser_ctx(parser);
2512 parser_enterblock(parser);
2519 /* parse into the expression */
2520 if (!parser_next(parser)) {
2521 parseerror(parser, "expected 'for' initializer after opening paren");
2526 if (parser->tok == TOKEN_IDENT)
2527 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2529 if (typevar || parser->tok == TOKEN_TYPENAME) {
2531 if (opts.standard != COMPILER_GMQCC) {
2532 if (parsewarning(parser, WARN_EXTENSIONS,
2533 "current standard does not allow variable declarations in for-loop initializers"))
2537 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2540 else if (parser->tok != ';')
2542 initexpr = parse_expression_leave(parser, false, false, false);
2547 /* move on to condition */
2548 if (parser->tok != ';') {
2549 parseerror(parser, "expected semicolon after for-loop initializer");
2552 if (!parser_next(parser)) {
2553 parseerror(parser, "expected for-loop condition");
2557 /* parse the condition */
2558 if (parser->tok != ';') {
2559 cond = parse_expression_leave(parser, false, true, false);
2564 /* move on to incrementor */
2565 if (parser->tok != ';') {
2566 parseerror(parser, "expected semicolon after for-loop initializer");
2569 if (!parser_next(parser)) {
2570 parseerror(parser, "expected for-loop condition");
2574 /* parse the incrementor */
2575 if (parser->tok != ')') {
2576 increment = parse_expression_leave(parser, false, false, false);
2579 if (!ast_side_effects(increment)) {
2580 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2586 if (parser->tok != ')') {
2587 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2590 /* parse into the 'then' branch */
2591 if (!parser_next(parser)) {
2592 parseerror(parser, "expected for-loop body");
2595 if (!parse_statement_or_block(parser, &ontrue))
2599 cond = process_condition(parser, cond, &ifnot);
2603 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2604 *out = (ast_expression*)aloop;
2606 if (!parser_leaveblock(parser))
2610 if (initexpr) ast_delete(initexpr);
2611 if (cond) ast_delete(cond);
2612 if (increment) ast_delete(increment);
2613 (void)!parser_leaveblock(parser);
2617 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2619 ast_expression *exp = NULL;
2620 ast_return *ret = NULL;
2621 ast_value *expected = parser->function->vtype;
2623 lex_ctx ctx = parser_ctx(parser);
2625 (void)block; /* not touching */
2627 if (!parser_next(parser)) {
2628 parseerror(parser, "expected return expression");
2632 if (parser->tok != ';') {
2633 exp = parse_expression(parser, false, false);
2637 if (exp->expression.vtype != TYPE_NIL &&
2638 exp->expression.vtype != expected->expression.next->expression.vtype)
2640 parseerror(parser, "return with invalid expression");
2643 ret = ast_return_new(ctx, exp);
2649 if (!parser_next(parser))
2650 parseerror(parser, "parse error");
2651 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2652 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2654 ret = ast_return_new(ctx, NULL);
2656 *out = (ast_expression*)ret;
2660 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2663 unsigned int levels = 0;
2664 lex_ctx ctx = parser_ctx(parser);
2665 const char **loops = (is_continue ? parser->continues : parser->breaks);
2667 (void)block; /* not touching */
2668 if (!parser_next(parser)) {
2669 parseerror(parser, "expected semicolon or loop label");
2673 if (!vec_size(loops)) {
2675 parseerror(parser, "`continue` can only be used inside loops");
2677 parseerror(parser, "`break` can only be used inside loops or switches");
2680 if (parser->tok == TOKEN_IDENT) {
2681 if (!OPTS_FLAG(LOOP_LABELS))
2682 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2683 i = vec_size(loops);
2685 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2688 parseerror(parser, "no such loop to %s: `%s`",
2689 (is_continue ? "continue" : "break out of"),
2690 parser_tokval(parser));
2695 if (!parser_next(parser)) {
2696 parseerror(parser, "expected semicolon");
2701 if (parser->tok != ';') {
2702 parseerror(parser, "expected semicolon");
2706 if (!parser_next(parser))
2707 parseerror(parser, "parse error");
2709 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2713 /* returns true when it was a variable qualifier, false otherwise!
2714 * on error, cvq is set to CV_WRONG
2716 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2718 bool had_const = false;
2719 bool had_var = false;
2720 bool had_noref = false;
2721 bool had_attrib = false;
2722 bool had_static = false;
2727 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2729 /* parse an attribute */
2730 if (!parser_next(parser)) {
2731 parseerror(parser, "expected attribute after `[[`");
2735 if (!strcmp(parser_tokval(parser), "noreturn")) {
2736 flags |= AST_FLAG_NORETURN;
2737 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2738 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2743 else if (!strcmp(parser_tokval(parser), "noref")) {
2745 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2746 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2751 else if (!strcmp(parser_tokval(parser), "inline")) {
2752 flags |= AST_FLAG_INLINE;
2753 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2754 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2761 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2762 flags |= AST_FLAG_DEPRECATED;
2765 if (!parser_next(parser)) {
2766 parseerror(parser, "parse error in attribute");
2770 if (parser->tok == '(') {
2771 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2772 parseerror(parser, "`deprecated` attribute missing parameter");
2776 *message = util_strdup(parser_tokval(parser));
2778 if (!parser_next(parser)) {
2779 parseerror(parser, "parse error in attribute");
2783 if(parser->tok != ')') {
2784 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2788 if (!parser_next(parser)) {
2789 parseerror(parser, "parse error in attribute");
2794 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2795 parseerror(parser, "`deprecated` attribute expected `]]`");
2798 if (*message) mem_d(*message);
2806 /* Skip tokens until we hit a ]] */
2807 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2808 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2809 if (!parser_next(parser)) {
2810 parseerror(parser, "error inside attribute");
2817 else if (!strcmp(parser_tokval(parser), "static"))
2819 else if (!strcmp(parser_tokval(parser), "const"))
2821 else if (!strcmp(parser_tokval(parser), "var"))
2823 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2825 else if (!strcmp(parser_tokval(parser), "noref"))
2827 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2832 if (!parser_next(parser))
2842 *is_static = had_static;
2846 parseerror(parser, "parse error after variable qualifier");
2851 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2852 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2857 /* skip the 'while' and get the body */
2858 if (!parser_next(parser)) {
2859 if (OPTS_FLAG(LOOP_LABELS))
2860 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2862 parseerror(parser, "expected 'switch' operand in parenthesis");
2866 if (parser->tok == ':') {
2867 if (!OPTS_FLAG(LOOP_LABELS))
2868 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2869 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2870 parseerror(parser, "expected loop label");
2873 label = util_strdup(parser_tokval(parser));
2874 if (!parser_next(parser)) {
2876 parseerror(parser, "expected 'switch' operand in parenthesis");
2881 if (parser->tok != '(') {
2882 parseerror(parser, "expected 'switch' operand in parenthesis");
2886 vec_push(parser->breaks, label);
2888 rv = parse_switch_go(parser, block, out);
2891 if (vec_last(parser->breaks) != label) {
2892 parseerror(parser, "internal error: label stack corrupted");
2898 vec_pop(parser->breaks);
2903 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2905 ast_expression *operand;
2908 ast_switch *switchnode;
2909 ast_switch_case swcase;
2912 bool noref, is_static;
2913 uint32_t qflags = 0;
2915 lex_ctx ctx = parser_ctx(parser);
2917 (void)block; /* not touching */
2920 /* parse into the expression */
2921 if (!parser_next(parser)) {
2922 parseerror(parser, "expected switch operand");
2925 /* parse the operand */
2926 operand = parse_expression_leave(parser, false, false, false);
2930 switchnode = ast_switch_new(ctx, operand);
2933 if (parser->tok != ')') {
2934 ast_delete(switchnode);
2935 parseerror(parser, "expected closing paren after 'switch' operand");
2939 /* parse over the opening paren */
2940 if (!parser_next(parser) || parser->tok != '{') {
2941 ast_delete(switchnode);
2942 parseerror(parser, "expected list of cases");
2946 if (!parser_next(parser)) {
2947 ast_delete(switchnode);
2948 parseerror(parser, "expected 'case' or 'default'");
2952 /* new block; allow some variables to be declared here */
2953 parser_enterblock(parser);
2956 if (parser->tok == TOKEN_IDENT)
2957 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2958 if (typevar || parser->tok == TOKEN_TYPENAME) {
2959 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2960 ast_delete(switchnode);
2965 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2967 if (cvq == CV_WRONG) {
2968 ast_delete(switchnode);
2971 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2972 ast_delete(switchnode);
2981 while (parser->tok != '}') {
2982 ast_block *caseblock;
2984 if (!strcmp(parser_tokval(parser), "case")) {
2985 if (!parser_next(parser)) {
2986 ast_delete(switchnode);
2987 parseerror(parser, "expected expression for case");
2990 swcase.value = parse_expression_leave(parser, false, false, false);
2991 if (!swcase.value) {
2992 ast_delete(switchnode);
2993 parseerror(parser, "expected expression for case");
2996 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2997 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2998 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3004 else if (!strcmp(parser_tokval(parser), "default")) {
3005 swcase.value = NULL;
3006 if (!parser_next(parser)) {
3007 ast_delete(switchnode);
3008 parseerror(parser, "expected colon");
3013 ast_delete(switchnode);
3014 parseerror(parser, "expected 'case' or 'default'");
3018 /* Now the colon and body */
3019 if (parser->tok != ':') {
3020 if (swcase.value) ast_unref(swcase.value);
3021 ast_delete(switchnode);
3022 parseerror(parser, "expected colon");
3026 if (!parser_next(parser)) {
3027 if (swcase.value) ast_unref(swcase.value);
3028 ast_delete(switchnode);
3029 parseerror(parser, "expected statements or case");
3032 caseblock = ast_block_new(parser_ctx(parser));
3034 if (swcase.value) ast_unref(swcase.value);
3035 ast_delete(switchnode);
3038 swcase.code = (ast_expression*)caseblock;
3039 vec_push(switchnode->cases, swcase);
3041 ast_expression *expr;
3042 if (parser->tok == '}')
3044 if (parser->tok == TOKEN_KEYWORD) {
3045 if (!strcmp(parser_tokval(parser), "case") ||
3046 !strcmp(parser_tokval(parser), "default"))
3051 if (!parse_statement(parser, caseblock, &expr, true)) {
3052 ast_delete(switchnode);
3057 if (!ast_block_add_expr(caseblock, expr)) {
3058 ast_delete(switchnode);
3064 parser_leaveblock(parser);
3067 if (parser->tok != '}') {
3068 ast_delete(switchnode);
3069 parseerror(parser, "expected closing paren of case list");
3072 if (!parser_next(parser)) {
3073 ast_delete(switchnode);
3074 parseerror(parser, "parse error after switch");
3077 *out = (ast_expression*)switchnode;
3081 /* parse computed goto sides */
3082 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3083 ast_expression *on_true;
3084 ast_expression *on_false;
3085 ast_expression *cond;
3090 if (ast_istype(*side, ast_ternary)) {
3091 ast_ternary *tern = (ast_ternary*)*side;
3092 on_true = parse_goto_computed(parser, &tern->on_true);
3093 on_false = parse_goto_computed(parser, &tern->on_false);
3095 if (!on_true || !on_false) {
3096 parseerror(parser, "expected label or expression in ternary");
3097 if (on_true) ast_unref(on_true);
3098 if (on_false) ast_unref(on_false);
3106 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3107 } else if (ast_istype(*side, ast_label)) {
3108 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3109 ast_goto_set_label(gt, ((ast_label*)*side));
3111 return (ast_expression*)gt;
3116 static bool parse_goto(parser_t *parser, ast_expression **out)
3118 ast_goto *gt = NULL;
3119 ast_expression *lbl;
3121 if (!parser_next(parser))
3124 if (parser->tok != TOKEN_IDENT) {
3125 ast_expression *expression;
3127 /* could be an expression i.e computed goto :-) */
3128 if (parser->tok != '(') {
3129 parseerror(parser, "expected label name after `goto`");
3133 /* failed to parse expression for goto */
3134 if (!(expression = parse_expression(parser, false, true)) ||
3135 !(*out = parse_goto_computed(parser, &expression))) {
3136 parseerror(parser, "invalid goto expression");
3137 ast_unref(expression);
3144 /* not computed goto */
3145 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3146 lbl = parser_find_label(parser, gt->name);
3148 if (!ast_istype(lbl, ast_label)) {
3149 parseerror(parser, "internal error: label is not an ast_label");
3153 ast_goto_set_label(gt, (ast_label*)lbl);
3156 vec_push(parser->gotos, gt);
3158 if (!parser_next(parser) || parser->tok != ';') {
3159 parseerror(parser, "semicolon expected after goto label");
3162 if (!parser_next(parser)) {
3163 parseerror(parser, "parse error after goto");
3167 *out = (ast_expression*)gt;
3171 static bool parse_skipwhite(parser_t *parser)
3174 if (!parser_next(parser))
3176 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3177 return parser->tok < TOKEN_ERROR;
3180 static bool parse_eol(parser_t *parser)
3182 if (!parse_skipwhite(parser))
3184 return parser->tok == TOKEN_EOL;
3187 static bool parse_pragma_do(parser_t *parser)
3189 if (!parser_next(parser) ||
3190 parser->tok != TOKEN_IDENT ||
3191 strcmp(parser_tokval(parser), "pragma"))
3193 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3196 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3197 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3201 if (!strcmp(parser_tokval(parser), "noref")) {
3202 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3203 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3206 parser->noref = !!parser_token(parser)->constval.i;
3207 if (!parse_eol(parser)) {
3208 parseerror(parser, "parse error after `noref` pragma");
3214 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3221 static bool parse_pragma(parser_t *parser)
3224 parser->lex->flags.preprocessing = true;
3225 parser->lex->flags.mergelines = true;
3226 rv = parse_pragma_do(parser);
3227 if (parser->tok != TOKEN_EOL) {
3228 parseerror(parser, "junk after pragma");
3231 parser->lex->flags.preprocessing = false;
3232 parser->lex->flags.mergelines = false;
3233 if (!parser_next(parser)) {
3234 parseerror(parser, "parse error after pragma");
3240 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3242 bool noref, is_static;
3244 uint32_t qflags = 0;
3245 ast_value *typevar = NULL;
3246 char *vstring = NULL;
3250 if (parser->tok == TOKEN_IDENT)
3251 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3253 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3255 /* local variable */
3257 parseerror(parser, "cannot declare a variable from here");
3260 if (opts.standard == COMPILER_QCC) {
3261 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3264 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3268 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3270 if (cvq == CV_WRONG)
3272 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3274 else if (parser->tok == TOKEN_KEYWORD)
3276 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3281 if (!parser_next(parser)) {
3282 parseerror(parser, "parse error after __builtin_debug_printtype");
3286 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3288 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3289 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3290 if (!parser_next(parser)) {
3291 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3297 if (!parse_statement(parser, block, out, allow_cases))
3300 con_out("__builtin_debug_printtype: got no output node\n");
3303 ast_type_to_string(*out, ty, sizeof(ty));
3304 con_out("__builtin_debug_printtype: `%s`\n", ty);
3309 else if (!strcmp(parser_tokval(parser), "return"))
3311 return parse_return(parser, block, out);
3313 else if (!strcmp(parser_tokval(parser), "if"))
3315 return parse_if(parser, block, out);
3317 else if (!strcmp(parser_tokval(parser), "while"))
3319 return parse_while(parser, block, out);
3321 else if (!strcmp(parser_tokval(parser), "do"))
3323 return parse_dowhile(parser, block, out);
3325 else if (!strcmp(parser_tokval(parser), "for"))
3327 if (opts.standard == COMPILER_QCC) {
3328 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3331 return parse_for(parser, block, out);
3333 else if (!strcmp(parser_tokval(parser), "break"))
3335 return parse_break_continue(parser, block, out, false);
3337 else if (!strcmp(parser_tokval(parser), "continue"))
3339 return parse_break_continue(parser, block, out, true);
3341 else if (!strcmp(parser_tokval(parser), "switch"))
3343 return parse_switch(parser, block, out);
3345 else if (!strcmp(parser_tokval(parser), "case") ||
3346 !strcmp(parser_tokval(parser), "default"))
3349 parseerror(parser, "unexpected 'case' label");
3354 else if (!strcmp(parser_tokval(parser), "goto"))
3356 return parse_goto(parser, out);
3358 else if (!strcmp(parser_tokval(parser), "typedef"))
3360 if (!parser_next(parser)) {
3361 parseerror(parser, "expected type definition after 'typedef'");
3364 return parse_typedef(parser);
3366 parseerror(parser, "Unexpected keyword");
3369 else if (parser->tok == '{')
3372 inner = parse_block(parser);
3375 *out = (ast_expression*)inner;
3378 else if (parser->tok == ':')
3382 if (!parser_next(parser)) {
3383 parseerror(parser, "expected label name");
3386 if (parser->tok != TOKEN_IDENT) {
3387 parseerror(parser, "label must be an identifier");
3390 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3392 if (!label->undefined) {
3393 parseerror(parser, "label `%s` already defined", label->name);
3396 label->undefined = false;
3399 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3400 vec_push(parser->labels, label);
3402 *out = (ast_expression*)label;
3403 if (!parser_next(parser)) {
3404 parseerror(parser, "parse error after label");
3407 for (i = 0; i < vec_size(parser->gotos); ++i) {
3408 if (!strcmp(parser->gotos[i]->name, label->name)) {
3409 ast_goto_set_label(parser->gotos[i], label);
3410 vec_remove(parser->gotos, i, 1);
3416 else if (parser->tok == ';')
3418 if (!parser_next(parser)) {
3419 parseerror(parser, "parse error after empty statement");
3426 ast_expression *exp = parse_expression(parser, false, false);
3430 if (!ast_side_effects(exp)) {
3431 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3438 static bool parse_block_into(parser_t *parser, ast_block *block)
3442 parser_enterblock(parser);
3444 if (!parser_next(parser)) { /* skip the '{' */
3445 parseerror(parser, "expected function body");
3449 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3451 ast_expression *expr = NULL;
3452 if (parser->tok == '}')
3455 if (!parse_statement(parser, block, &expr, false)) {
3456 /* parseerror(parser, "parse error"); */
3462 if (!ast_block_add_expr(block, expr)) {
3469 if (parser->tok != '}') {
3472 (void)parser_next(parser);
3476 if (!parser_leaveblock(parser))
3478 return retval && !!block;
3481 static ast_block* parse_block(parser_t *parser)
3484 block = ast_block_new(parser_ctx(parser));
3487 if (!parse_block_into(parser, block)) {
3488 ast_block_delete(block);
3494 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3496 if (parser->tok == '{') {
3497 *out = (ast_expression*)parse_block(parser);
3500 return parse_statement(parser, NULL, out, false);
3503 static bool create_vector_members(ast_value *var, ast_member **me)
3506 size_t len = strlen(var->name);
3508 for (i = 0; i < 3; ++i) {
3509 char *name = (char*)mem_a(len+3);
3510 memcpy(name, var->name, len);
3512 name[len+1] = 'x'+i;
3514 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3523 do { ast_member_delete(me[--i]); } while(i);
3527 static bool parse_function_body(parser_t *parser, ast_value *var)
3529 ast_block *block = NULL;
3534 ast_expression *framenum = NULL;
3535 ast_expression *nextthink = NULL;
3536 /* None of the following have to be deleted */
3537 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3538 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3539 bool has_frame_think;
3543 has_frame_think = false;
3544 old = parser->function;
3546 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3547 parseerror(parser, "gotos/labels leaking");
3551 if (var->expression.flags & AST_FLAG_VARIADIC) {
3552 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3553 "variadic function with implementation will not be able to access additional parameters"))
3559 if (parser->tok == '[') {
3560 /* got a frame definition: [ framenum, nextthink ]
3561 * this translates to:
3562 * self.frame = framenum;
3563 * self.nextthink = time + 0.1;
3564 * self.think = nextthink;
3568 fld_think = parser_find_field(parser, "think");
3569 fld_nextthink = parser_find_field(parser, "nextthink");
3570 fld_frame = parser_find_field(parser, "frame");
3571 if (!fld_think || !fld_nextthink || !fld_frame) {
3572 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3573 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3576 gbl_time = parser_find_global(parser, "time");
3577 gbl_self = parser_find_global(parser, "self");
3578 if (!gbl_time || !gbl_self) {
3579 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3580 parseerror(parser, "please declare the following globals: `time`, `self`");
3584 if (!parser_next(parser))
3587 framenum = parse_expression_leave(parser, true, false, false);
3589 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3592 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3593 ast_unref(framenum);
3594 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3598 if (parser->tok != ',') {
3599 ast_unref(framenum);
3600 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3601 parseerror(parser, "Got a %i\n", parser->tok);
3605 if (!parser_next(parser)) {
3606 ast_unref(framenum);
3610 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3612 /* qc allows the use of not-yet-declared functions here
3613 * - this automatically creates a prototype */
3614 ast_value *thinkfunc;
3615 ast_expression *functype = fld_think->expression.next;
3617 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3618 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3619 ast_unref(framenum);
3620 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3624 if (!parser_next(parser)) {
3625 ast_unref(framenum);
3626 ast_delete(thinkfunc);
3630 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3632 nextthink = (ast_expression*)thinkfunc;
3635 nextthink = parse_expression_leave(parser, true, false, false);
3637 ast_unref(framenum);
3638 parseerror(parser, "expected a think-function in [frame,think] notation");
3643 if (!ast_istype(nextthink, ast_value)) {
3644 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3648 if (retval && parser->tok != ']') {
3649 parseerror(parser, "expected closing `]` for [frame,think] notation");
3653 if (retval && !parser_next(parser)) {
3657 if (retval && parser->tok != '{') {
3658 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3663 ast_unref(nextthink);
3664 ast_unref(framenum);
3668 has_frame_think = true;
3671 block = ast_block_new(parser_ctx(parser));
3673 parseerror(parser, "failed to allocate block");
3674 if (has_frame_think) {
3675 ast_unref(nextthink);
3676 ast_unref(framenum);
3681 if (has_frame_think) {
3683 ast_expression *self_frame;
3684 ast_expression *self_nextthink;
3685 ast_expression *self_think;
3686 ast_expression *time_plus_1;
3687 ast_store *store_frame;
3688 ast_store *store_nextthink;
3689 ast_store *store_think;
3691 ctx = parser_ctx(parser);
3692 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3693 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3694 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3696 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3697 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3699 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3700 if (self_frame) ast_delete(self_frame);
3701 if (self_nextthink) ast_delete(self_nextthink);
3702 if (self_think) ast_delete(self_think);
3703 if (time_plus_1) ast_delete(time_plus_1);
3709 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3710 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3711 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3714 ast_delete(self_frame);
3717 if (!store_nextthink) {
3718 ast_delete(self_nextthink);
3722 ast_delete(self_think);
3726 if (store_frame) ast_delete(store_frame);
3727 if (store_nextthink) ast_delete(store_nextthink);
3728 if (store_think) ast_delete(store_think);
3731 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3732 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3733 !ast_block_add_expr(block, (ast_expression*)store_think))
3740 parseerror(parser, "failed to generate code for [frame,think]");
3741 ast_unref(nextthink);
3742 ast_unref(framenum);
3748 parser_enterblock(parser);
3750 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3752 ast_value *param = var->expression.params[parami];
3755 if (param->expression.vtype != TYPE_VECTOR &&
3756 (param->expression.vtype != TYPE_FIELD ||
3757 param->expression.next->expression.vtype != TYPE_VECTOR))
3762 if (!create_vector_members(param, me)) {
3763 ast_block_delete(block);
3767 for (e = 0; e < 3; ++e) {
3768 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3769 ast_block_collect(block, (ast_expression*)me[e]);
3773 func = ast_function_new(ast_ctx(var), var->name, var);
3775 parseerror(parser, "failed to allocate function for `%s`", var->name);
3776 ast_block_delete(block);
3779 vec_push(parser->functions, func);
3781 parser->function = func;
3782 if (!parse_block_into(parser, block)) {
3783 ast_block_delete(block);
3787 vec_push(func->blocks, block);
3789 parser->function = old;
3790 if (!parser_leaveblock(parser))
3792 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3793 parseerror(parser, "internal error: local scopes left");
3797 if (parser->tok == ';')
3798 return parser_next(parser);
3799 else if (opts.standard == COMPILER_QCC)
3800 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3804 vec_pop(parser->functions);
3805 ast_function_delete(func);
3806 var->constval.vfunc = NULL;
3809 (void)!parser_leaveblock(parser);
3810 parser->function = old;
3814 static ast_expression *array_accessor_split(
3819 ast_expression *left,
3820 ast_expression *right
3826 lex_ctx ctx = ast_ctx(array);
3828 if (!left || !right) {
3829 if (left) ast_delete(left);
3830 if (right) ast_delete(right);
3834 cmp = ast_binary_new(ctx, INSTR_LT,
3835 (ast_expression*)index,
3836 (ast_expression*)parser_const_float(parser, middle));
3840 parseerror(parser, "internal error: failed to create comparison for array setter");
3844 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3846 ast_delete(cmp); /* will delete left and right */
3847 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3851 return (ast_expression*)ifthen;
3854 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3856 lex_ctx ctx = ast_ctx(array);
3858 if (from+1 == afterend) {
3859 /* set this value */
3862 ast_array_index *subscript;
3864 int assignop = type_store_instr[value->expression.vtype];
3866 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3867 assignop = INSTR_STORE_V;
3869 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3873 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3875 ast_delete(subscript);
3879 block = ast_block_new(ctx);
3885 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3890 ret = ast_return_new(ctx, NULL);
3896 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3901 return (ast_expression*)block;
3903 ast_expression *left, *right;
3904 size_t diff = afterend - from;
3905 size_t middle = from + diff/2;
3906 left = array_setter_node(parser, array, index, value, from, middle);
3907 right = array_setter_node(parser, array, index, value, middle, afterend);
3908 return array_accessor_split(parser, array, index, middle, left, right);
3912 static ast_expression *array_field_setter_node(
3921 lex_ctx ctx = ast_ctx(array);
3923 if (from+1 == afterend) {
3924 /* set this value */
3927 ast_entfield *entfield;
3928 ast_array_index *subscript;
3930 int assignop = type_storep_instr[value->expression.vtype];
3932 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3933 assignop = INSTR_STOREP_V;
3935 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3939 entfield = ast_entfield_new_force(ctx,
3940 (ast_expression*)entity,
3941 (ast_expression*)subscript,
3942 (ast_expression*)subscript);
3944 ast_delete(subscript);
3948 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3950 ast_delete(entfield);
3954 block = ast_block_new(ctx);
3960 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3965 ret = ast_return_new(ctx, NULL);
3971 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3976 return (ast_expression*)block;
3978 ast_expression *left, *right;
3979 size_t diff = afterend - from;
3980 size_t middle = from + diff/2;
3981 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3982 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3983 return array_accessor_split(parser, array, index, middle, left, right);
3987 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3989 lex_ctx ctx = ast_ctx(array);
3991 if (from+1 == afterend) {
3993 ast_array_index *subscript;
3995 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3999 ret = ast_return_new(ctx, (ast_expression*)subscript);
4001 ast_delete(subscript);
4005 return (ast_expression*)ret;
4007 ast_expression *left, *right;
4008 size_t diff = afterend - from;
4009 size_t middle = from + diff/2;
4010 left = array_getter_node(parser, array, index, from, middle);
4011 right = array_getter_node(parser, array, index, middle, afterend);
4012 return array_accessor_split(parser, array, index, middle, left, right);
4016 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4018 ast_function *func = NULL;
4019 ast_value *fval = NULL;
4020 ast_block *body = NULL;
4022 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4024 parseerror(parser, "failed to create accessor function value");
4028 func = ast_function_new(ast_ctx(array), funcname, fval);
4031 parseerror(parser, "failed to create accessor function node");
4035 body = ast_block_new(ast_ctx(array));
4037 parseerror(parser, "failed to create block for array accessor");
4043 vec_push(func->blocks, body);
4046 vec_push(parser->accessors, fval);
4051 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4053 ast_expression *root = NULL;
4054 ast_value *index = NULL;
4055 ast_value *value = NULL;
4059 if (!ast_istype(array->expression.next, ast_value)) {
4060 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4064 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4066 func = fval->constval.vfunc;
4067 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4069 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4070 value = ast_value_copy((ast_value*)array->expression.next);
4072 if (!index || !value) {
4073 parseerror(parser, "failed to create locals for array accessor");
4076 (void)!ast_value_set_name(value, "value"); /* not important */
4077 vec_push(fval->expression.params, index);
4078 vec_push(fval->expression.params, value);
4080 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4082 parseerror(parser, "failed to build accessor search tree");
4086 array->setter = fval;
4087 return ast_block_add_expr(func->blocks[0], root);
4089 if (index) ast_delete(index);
4090 if (value) ast_delete(value);
4091 if (root) ast_delete(root);
4097 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4099 ast_expression *root = NULL;
4100 ast_value *entity = NULL;
4101 ast_value *index = NULL;
4102 ast_value *value = NULL;
4106 if (!ast_istype(array->expression.next, ast_value)) {
4107 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4111 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4113 func = fval->constval.vfunc;
4114 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4116 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4117 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4118 value = ast_value_copy((ast_value*)array->expression.next);
4119 if (!entity || !index || !value) {
4120 parseerror(parser, "failed to create locals for array accessor");
4123 (void)!ast_value_set_name(value, "value"); /* not important */
4124 vec_push(fval->expression.params, entity);
4125 vec_push(fval->expression.params, index);
4126 vec_push(fval->expression.params, value);
4128 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4130 parseerror(parser, "failed to build accessor search tree");
4134 array->setter = fval;
4135 return ast_block_add_expr(func->blocks[0], root);
4137 if (entity) ast_delete(entity);
4138 if (index) ast_delete(index);
4139 if (value) ast_delete(value);
4140 if (root) ast_delete(root);
4146 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4148 ast_expression *root = NULL;
4149 ast_value *index = NULL;
4153 /* NOTE: checking array->expression.next rather than elemtype since
4154 * for fields elemtype is a temporary fieldtype.
4156 if (!ast_istype(array->expression.next, ast_value)) {
4157 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4161 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4163 func = fval->constval.vfunc;
4164 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4166 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4169 parseerror(parser, "failed to create locals for array accessor");
4172 vec_push(fval->expression.params, index);
4174 root = array_getter_node(parser, array, index, 0, array->expression.count);
4176 parseerror(parser, "failed to build accessor search tree");
4180 array->getter = fval;
4181 return ast_block_add_expr(func->blocks[0], root);
4183 if (index) ast_delete(index);
4184 if (root) ast_delete(root);
4190 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4191 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4199 bool variadic = false;
4201 ctx = parser_ctx(parser);
4203 /* for the sake of less code we parse-in in this function */
4204 if (!parser_next(parser)) {
4205 parseerror(parser, "expected parameter list");
4211 /* parse variables until we hit a closing paren */
4212 while (parser->tok != ')') {
4214 /* there must be commas between them */
4215 if (parser->tok != ',') {
4216 parseerror(parser, "expected comma or end of parameter list");
4219 if (!parser_next(parser)) {
4220 parseerror(parser, "expected parameter");
4226 if (parser->tok == TOKEN_DOTS) {
4227 /* '...' indicates a varargs function */
4229 if (!parser_next(parser)) {
4230 parseerror(parser, "expected parameter");
4233 if (parser->tok != ')') {
4234 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4240 /* for anything else just parse a typename */
4241 param = parse_typename(parser, NULL, NULL);
4244 vec_push(params, param);
4245 if (param->expression.vtype >= TYPE_VARIANT) {
4246 char tname[1024]; /* typename is reserved in C++ */
4247 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4248 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4254 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4258 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4259 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4262 if (!parser_next(parser)) {
4263 parseerror(parser, "parse error after typename");
4267 /* now turn 'var' into a function type */
4268 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4269 fval->expression.next = (ast_expression*)var;
4271 fval->expression.flags |= AST_FLAG_VARIADIC;
4274 var->expression.params = params;
4281 for (i = 0; i < vec_size(params); ++i)
4282 ast_delete(params[i]);
4287 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4289 ast_expression *cexp;
4290 ast_value *cval, *tmp;
4293 ctx = parser_ctx(parser);
4295 if (!parser_next(parser)) {
4297 parseerror(parser, "expected array-size");
4301 cexp = parse_expression_leave(parser, true, false, false);
4303 if (!cexp || !ast_istype(cexp, ast_value)) {
4307 parseerror(parser, "expected array-size as constant positive integer");
4310 cval = (ast_value*)cexp;
4312 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4313 tmp->expression.next = (ast_expression*)var;
4316 if (cval->expression.vtype == TYPE_INTEGER)
4317 tmp->expression.count = cval->constval.vint;
4318 else if (cval->expression.vtype == TYPE_FLOAT)
4319 tmp->expression.count = cval->constval.vfloat;
4323 parseerror(parser, "array-size must be a positive integer constant");
4328 if (parser->tok != ']') {
4330 parseerror(parser, "expected ']' after array-size");
4333 if (!parser_next(parser)) {
4335 parseerror(parser, "error after parsing array size");
4341 /* Parse a complete typename.
4342 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4343 * but when parsing variables separated by comma
4344 * 'storebase' should point to where the base-type should be kept.
4345 * The base type makes up every bit of type information which comes *before* the
4348 * The following will be parsed in its entirety:
4350 * The 'basetype' in this case is 'void()'
4351 * and if there's a comma after it, say:
4353 * then the type-information 'void()' can be stored in 'storebase'
4355 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4357 ast_value *var, *tmp;
4360 const char *name = NULL;
4361 bool isfield = false;
4362 bool wasarray = false;
4363 size_t morefields = 0;
4365 ctx = parser_ctx(parser);
4367 /* types may start with a dot */
4368 if (parser->tok == '.') {
4370 /* if we parsed a dot we need a typename now */
4371 if (!parser_next(parser)) {
4372 parseerror(parser, "expected typename for field definition");
4376 /* Further dots are handled seperately because they won't be part of the
4379 while (parser->tok == '.') {
4381 if (!parser_next(parser)) {
4382 parseerror(parser, "expected typename for field definition");
4387 if (parser->tok == TOKEN_IDENT)
4388 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4389 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4390 parseerror(parser, "expected typename");
4394 /* generate the basic type value */
4395 if (cached_typedef) {
4396 var = ast_value_copy(cached_typedef);
4397 ast_value_set_name(var, "<type(from_def)>");
4399 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4401 for (; morefields; --morefields) {
4402 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4403 tmp->expression.next = (ast_expression*)var;
4407 /* do not yet turn into a field - remember:
4408 * .void() foo; is a field too
4409 * .void()() foo; is a function
4413 if (!parser_next(parser)) {
4415 parseerror(parser, "parse error after typename");
4419 /* an opening paren now starts the parameter-list of a function
4420 * this is where original-QC has parameter lists.
4421 * We allow a single parameter list here.
4422 * Much like fteqcc we don't allow `float()() x`
4424 if (parser->tok == '(') {
4425 var = parse_parameter_list(parser, var);
4430 /* store the base if requested */
4432 *storebase = ast_value_copy(var);
4434 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4435 tmp->expression.next = (ast_expression*)*storebase;
4440 /* there may be a name now */
4441 if (parser->tok == TOKEN_IDENT) {
4442 name = util_strdup(parser_tokval(parser));
4444 if (!parser_next(parser)) {
4446 parseerror(parser, "error after variable or field declaration");
4451 /* now this may be an array */
4452 if (parser->tok == '[') {
4454 var = parse_arraysize(parser, var);
4459 /* This is the point where we can turn it into a field */
4461 /* turn it into a field if desired */
4462 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4463 tmp->expression.next = (ast_expression*)var;
4467 /* now there may be function parens again */
4468 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4469 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4470 if (parser->tok == '(' && wasarray)
4471 parseerror(parser, "arrays as part of a return type is not supported");
4472 while (parser->tok == '(') {
4473 var = parse_parameter_list(parser, var);
4482 /* finally name it */
4484 if (!ast_value_set_name(var, name)) {
4486 parseerror(parser, "internal error: failed to set name");
4489 /* free the name, ast_value_set_name duplicates */
4496 static bool parse_typedef(parser_t *parser)
4498 ast_value *typevar, *oldtype;
4499 ast_expression *old;
4501 typevar = parse_typename(parser, NULL, NULL);
4506 if ( (old = parser_find_var(parser, typevar->name)) ) {
4507 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4508 " -> `%s` has been declared here: %s:%i",
4509 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4510 ast_delete(typevar);
4514 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4515 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4516 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4517 ast_delete(typevar);
4521 vec_push(parser->_typedefs, typevar);
4522 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4524 if (parser->tok != ';') {
4525 parseerror(parser, "expected semicolon after typedef");
4528 if (!parser_next(parser)) {
4529 parseerror(parser, "parse error after typedef");
4536 static const char *cvq_to_str(int cvq) {
4538 case CV_NONE: return "none";
4539 case CV_VAR: return "`var`";
4540 case CV_CONST: return "`const`";
4541 default: return "<INVALID>";
4545 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4548 if (proto->cvq != var->cvq) {
4549 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4550 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4551 parser->tok == '='))
4553 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4554 "`%s` declared with different qualifiers: %s\n"
4555 " -> previous declaration here: %s:%i uses %s",
4556 var->name, cvq_to_str(var->cvq),
4557 ast_ctx(proto).file, ast_ctx(proto).line,
4558 cvq_to_str(proto->cvq));
4561 av = (var ->expression.flags & AST_FLAG_NORETURN);
4562 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4564 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4565 "`%s` declared with different attributes%s\n"
4566 " -> previous declaration here: %s:%i",
4567 var->name, (av ? ": noreturn" : ""),
4568 ast_ctx(proto).file, ast_ctx(proto).line,
4569 (ao ? ": noreturn" : ""));
4574 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)
4578 ast_expression *old;
4582 ast_value *basetype = NULL;
4584 bool isparam = false;
4585 bool isvector = false;
4586 bool cleanvar = true;
4587 bool wasarray = false;
4591 if (!localblock && is_static)
4592 parseerror(parser, "`static` qualifier is not supported in global scope");
4594 /* get the first complete variable */
4595 var = parse_typename(parser, &basetype, cached_typedef);
4598 ast_delete(basetype);
4606 /* Part 0: finish the type */
4607 if (parser->tok == '(') {
4608 if (opts.standard == COMPILER_QCC)
4609 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4610 var = parse_parameter_list(parser, var);
4616 /* we only allow 1-dimensional arrays */
4617 if (parser->tok == '[') {
4619 var = parse_arraysize(parser, var);
4625 if (parser->tok == '(' && wasarray) {
4626 parseerror(parser, "arrays as part of a return type is not supported");
4627 /* we'll still parse the type completely for now */
4629 /* for functions returning functions */
4630 while (parser->tok == '(') {
4631 if (opts.standard == COMPILER_QCC)
4632 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4633 var = parse_parameter_list(parser, var);
4640 var->cvq = qualifier;
4641 var->expression.flags |= qflags;
4642 if (var->expression.flags & AST_FLAG_DEPRECATED)
4643 var->desc = vstring;
4646 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4647 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4648 * is then filled with the previous definition and the parameter-names replaced.
4650 if (!strcmp(var->name, "nil")) {
4651 if (OPTS_FLAG(UNTYPED_NIL)) {
4652 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4653 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4655 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4658 /* Deal with end_sys_ vars */
4660 if (!strcmp(var->name, "end_sys_globals")) {
4662 parser->crc_globals = vec_size(parser->globals);
4665 else if (!strcmp(var->name, "end_sys_fields")) {
4667 parser->crc_fields = vec_size(parser->fields);
4670 if (was_end && var->expression.vtype == TYPE_FIELD) {
4671 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4672 "global '%s' hint should not be a field",
4673 parser_tokval(parser)))
4680 if (!nofields && var->expression.vtype == TYPE_FIELD)
4682 /* deal with field declarations */
4683 old = parser_find_field(parser, var->name);
4685 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4686 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4695 parseerror(parser, "field `%s` already declared here: %s:%i",
4696 var->name, ast_ctx(old).file, ast_ctx(old).line);
4701 if (opts.standard == COMPILER_QCC &&
4702 (old = parser_find_global(parser, var->name)))
4704 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4705 parseerror(parser, "field `%s` already declared here: %s:%i",
4706 var->name, ast_ctx(old).file, ast_ctx(old).line);
4713 /* deal with other globals */
4714 old = parser_find_global(parser, var->name);
4715 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4717 /* This is a function which had a prototype */
4718 if (!ast_istype(old, ast_value)) {
4719 parseerror(parser, "internal error: prototype is not an ast_value");
4723 proto = (ast_value*)old;
4724 proto->desc = var->desc;
4725 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4726 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4728 ast_ctx(proto).file, ast_ctx(proto).line);
4732 /* we need the new parameter-names */
4733 for (i = 0; i < vec_size(proto->expression.params); ++i)
4734 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4735 if (!parser_check_qualifiers(parser, var, proto)) {
4742 proto->expression.flags |= var->expression.flags;
4750 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4751 "global `%s` already declared here: %s:%i",
4752 var->name, ast_ctx(old).file, ast_ctx(old).line))
4757 proto = (ast_value*)old;
4758 if (!ast_istype(old, ast_value)) {
4759 parseerror(parser, "internal error: not an ast_value");
4764 if (!parser_check_qualifiers(parser, var, proto)) {
4769 proto->expression.flags |= var->expression.flags;
4773 if (opts.standard == COMPILER_QCC &&
4774 (old = parser_find_field(parser, var->name)))
4776 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4777 parseerror(parser, "global `%s` already declared here: %s:%i",
4778 var->name, ast_ctx(old).file, ast_ctx(old).line);
4785 else /* it's not a global */
4787 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4788 if (old && !isparam) {
4789 parseerror(parser, "local `%s` already declared here: %s:%i",
4790 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4794 old = parser_find_local(parser, var->name, 0, &isparam);
4795 if (old && isparam) {
4796 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4797 "local `%s` is shadowing a parameter", var->name))
4799 parseerror(parser, "local `%s` already declared here: %s:%i",
4800 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4804 if (opts.standard != COMPILER_GMQCC) {
4812 /* in a noref section we simply bump the usecount */
4813 if (noref || parser->noref)
4817 * Create the global/local, and deal with vector types.
4820 if (var->expression.vtype == TYPE_VECTOR)
4822 else if (var->expression.vtype == TYPE_FIELD &&
4823 var->expression.next->expression.vtype == TYPE_VECTOR)
4827 if (!create_vector_members(var, me)) {
4834 /* deal with global variables, fields, functions */
4835 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4836 var->isfield = true;
4837 vec_push(parser->fields, (ast_expression*)var);
4838 util_htset(parser->htfields, var->name, var);
4840 for (i = 0; i < 3; ++i) {
4841 vec_push(parser->fields, (ast_expression*)me[i]);
4842 util_htset(parser->htfields, me[i]->name, me[i]);
4847 parser_addglobal(parser, var->name, (ast_expression*)var);
4849 for (i = 0; i < 3; ++i) {
4850 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
4856 /* a static adds itself to be generated like any other global
4857 * but is added to the local namespace instead
4859 char *defname = NULL;
4860 size_t prefix_len, ln;
4862 ln = strlen(parser->function->name);
4863 vec_append(defname, ln, parser->function->name);
4865 vec_append(defname, 2, "::");
4866 /* remember the length up to here */
4867 prefix_len = vec_size(defname);
4869 /* Add it to the local scope */
4870 util_htset(vec_last(parser->variables), var->name, (void*)var);
4874 vec_last(parser->correct_variables),
4875 &vec_last(parser->correct_variables_score),
4879 /* now rename the global */
4880 ln = strlen(var->name);
4881 vec_append(defname, ln, var->name);
4882 ast_value_set_name(var, defname);
4884 /* push it to the to-be-generated globals */
4885 vec_push(parser->globals, (ast_expression*)var);
4887 /* same game for the vector members */
4889 for (i = 0; i < 3; ++i) {
4890 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4894 vec_last(parser->correct_variables),
4895 &vec_last(parser->correct_variables_score),
4899 vec_shrinkto(defname, prefix_len);
4900 ln = strlen(me[i]->name);
4901 vec_append(defname, ln, me[i]->name);
4902 ast_member_set_name(me[i], defname);
4904 vec_push(parser->globals, (ast_expression*)me[i]);
4909 vec_push(localblock->locals, var);
4910 parser_addlocal(parser, var->name, (ast_expression*)var);
4912 for (i = 0; i < 3; ++i) {
4913 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4914 ast_block_collect(localblock, (ast_expression*)me[i]);
4920 me[0] = me[1] = me[2] = NULL;
4925 if (var->expression.vtype == TYPE_ARRAY) {
4927 snprintf(name, sizeof(name), "%s##SET", var->name);
4928 if (!parser_create_array_setter(parser, var, name))
4930 snprintf(name, sizeof(name), "%s##GET", var->name);
4931 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4934 else if (!localblock && !nofields &&
4935 var->expression.vtype == TYPE_FIELD &&
4936 var->expression.next->expression.vtype == TYPE_ARRAY)
4939 ast_expression *telem;
4941 ast_value *array = (ast_value*)var->expression.next;
4943 if (!ast_istype(var->expression.next, ast_value)) {
4944 parseerror(parser, "internal error: field element type must be an ast_value");
4948 snprintf(name, sizeof(name), "%s##SETF", var->name);
4949 if (!parser_create_array_field_setter(parser, array, name))
4952 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4953 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4954 tfield->expression.next = telem;
4955 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4956 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4964 if (parser->tok == ';') {
4965 ast_delete(basetype);
4966 if (!parser_next(parser)) {
4967 parseerror(parser, "error after variable declaration");
4973 if (parser->tok == ',')
4977 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4980 parseerror(parser, "missing comma or semicolon while parsing variables");
4984 if (localblock && opts.standard == COMPILER_QCC) {
4985 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4986 "initializing expression turns variable `%s` into a constant in this standard",
4993 if (parser->tok != '{') {
4994 if (parser->tok != '=') {
4995 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4999 if (!parser_next(parser)) {
5000 parseerror(parser, "error parsing initializer");
5004 else if (opts.standard == COMPILER_QCC) {
5005 parseerror(parser, "expected '=' before function body in this standard");
5008 if (parser->tok == '#') {
5009 ast_function *func = NULL;
5012 parseerror(parser, "cannot declare builtins within functions");
5015 if (var->expression.vtype != TYPE_FUNCTION) {
5016 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5019 if (!parser_next(parser)) {
5020 parseerror(parser, "expected builtin number");
5023 if (parser->tok != TOKEN_INTCONST) {
5024 parseerror(parser, "builtin number must be an integer constant");
5027 if (parser_token(parser)->constval.i < 0) {
5028 parseerror(parser, "builtin number must be an integer greater than zero");
5032 if (var->hasvalue) {
5033 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5034 "builtin `%s` has already been defined\n"
5035 " -> previous declaration here: %s:%i",
5036 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5040 func = ast_function_new(ast_ctx(var), var->name, var);
5042 parseerror(parser, "failed to allocate function for `%s`", var->name);
5045 vec_push(parser->functions, func);
5047 func->builtin = -parser_token(parser)->constval.i-1;
5050 if (!parser_next(parser)) {
5051 parseerror(parser, "expected comma or semicolon");
5053 ast_function_delete(func);
5054 var->constval.vfunc = NULL;
5058 else if (parser->tok == '{' || parser->tok == '[')
5061 parseerror(parser, "cannot declare functions within functions");
5066 ast_ctx(proto) = parser_ctx(parser);
5068 if (!parse_function_body(parser, var))
5070 ast_delete(basetype);
5071 for (i = 0; i < vec_size(parser->gotos); ++i)
5072 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5073 vec_free(parser->gotos);
5074 vec_free(parser->labels);
5077 ast_expression *cexp;
5080 cexp = parse_expression_leave(parser, true, false, false);
5085 cval = (ast_value*)cexp;
5086 if (cval != parser->nil &&
5087 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5090 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5094 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5095 qualifier != CV_VAR)
5097 var->cvq = CV_CONST;
5099 if (cval == parser->nil)
5100 var->expression.flags |= AST_FLAG_INITIALIZED;
5103 var->hasvalue = true;
5104 if (cval->expression.vtype == TYPE_STRING)
5105 var->constval.vstring = parser_strdup(cval->constval.vstring);
5106 else if (cval->expression.vtype == TYPE_FIELD)
5107 var->constval.vfield = cval;
5109 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5115 shunt sy = { NULL, NULL };
5118 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5119 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5120 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5121 if (!parser_sy_apply_operator(parser, &sy))
5124 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5125 parseerror(parser, "internal error: leaked operands");
5126 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5136 if (parser->tok == ',') {
5137 if (!parser_next(parser)) {
5138 parseerror(parser, "expected another variable");
5142 if (parser->tok != TOKEN_IDENT) {
5143 parseerror(parser, "expected another variable");
5146 var = ast_value_copy(basetype);
5148 ast_value_set_name(var, parser_tokval(parser));
5149 if (!parser_next(parser)) {
5150 parseerror(parser, "error parsing variable declaration");
5156 if (parser->tok != ';') {
5157 parseerror(parser, "missing semicolon after variables");
5161 if (!parser_next(parser)) {
5162 parseerror(parser, "parse error after variable declaration");
5166 ast_delete(basetype);
5170 if (cleanvar && var)
5172 ast_delete(basetype);
5176 ast_delete(basetype);
5177 if (cleanvar && var)
5179 if (me[0]) ast_member_delete(me[0]);
5180 if (me[1]) ast_member_delete(me[1]);
5181 if (me[2]) ast_member_delete(me[2]);
5185 static bool parser_global_statement(parser_t *parser)
5189 bool is_static = false;
5190 uint32_t qflags = 0;
5191 ast_value *istype = NULL;
5192 char *vstring = NULL;
5194 if (parser->tok == TOKEN_IDENT)
5195 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5197 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5199 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5201 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5203 if (cvq == CV_WRONG)
5205 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5207 else if (parser->tok == TOKEN_KEYWORD)
5209 if (!strcmp(parser_tokval(parser), "typedef")) {
5210 if (!parser_next(parser)) {
5211 parseerror(parser, "expected type definition after 'typedef'");
5214 return parse_typedef(parser);
5216 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5219 else if (parser->tok == '#')
5221 return parse_pragma(parser);
5223 else if (parser->tok == '$')
5225 if (!parser_next(parser)) {
5226 parseerror(parser, "parse error");
5232 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5238 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5240 return util_crc16(old, str, strlen(str));
5243 static void progdefs_crc_file(const char *str)
5245 /* write to progdefs.h here */
5249 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5251 old = progdefs_crc_sum(old, str);
5252 progdefs_crc_file(str);
5256 static void generate_checksum(parser_t *parser)
5258 uint16_t crc = 0xFFFF;
5262 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5263 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5265 progdefs_crc_file("\tint\tpad;\n");
5266 progdefs_crc_file("\tint\tofs_return[3];\n");
5267 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5268 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5269 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5270 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5271 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5272 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5273 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5274 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5276 for (i = 0; i < parser->crc_globals; ++i) {
5277 if (!ast_istype(parser->globals[i], ast_value))
5279 value = (ast_value*)(parser->globals[i]);
5280 switch (value->expression.vtype) {
5281 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5282 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5283 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5284 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5286 crc = progdefs_crc_both(crc, "\tint\t");
5289 crc = progdefs_crc_both(crc, value->name);
5290 crc = progdefs_crc_both(crc, ";\n");
5292 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5293 for (i = 0; i < parser->crc_fields; ++i) {
5294 if (!ast_istype(parser->fields[i], ast_value))
5296 value = (ast_value*)(parser->fields[i]);
5297 switch (value->expression.next->expression.vtype) {
5298 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5299 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5300 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5301 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5303 crc = progdefs_crc_both(crc, "\tint\t");
5306 crc = progdefs_crc_both(crc, value->name);
5307 crc = progdefs_crc_both(crc, ";\n");
5309 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5314 static parser_t *parser;
5321 parser = (parser_t*)mem_a(sizeof(parser_t));
5325 memset(parser, 0, sizeof(*parser));
5327 for (i = 0; i < operator_count; ++i) {
5328 if (operators[i].id == opid1('=')) {
5329 parser->assign_op = operators+i;
5333 if (!parser->assign_op) {
5334 printf("internal error: initializing parser: failed to find assign operator\n");
5339 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5340 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5341 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5342 vec_push(parser->_blocktypedefs, 0);
5345 vec_push(parser->correct_variables, correct_trie_new());
5346 vec_push(parser->correct_variables_score, NULL);
5348 empty_ctx.file = "<internal>";
5350 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5351 parser->nil->cvq = CV_CONST;
5352 if (OPTS_FLAG(UNTYPED_NIL))
5353 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5357 bool parser_compile()
5359 /* initial lexer/parser state */
5360 parser->lex->flags.noops = true;
5362 if (parser_next(parser))
5364 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5366 if (!parser_global_statement(parser)) {
5367 if (parser->tok == TOKEN_EOF)
5368 parseerror(parser, "unexpected eof");
5369 else if (compile_errors)
5370 parseerror(parser, "there have been errors, bailing out");
5371 lex_close(parser->lex);
5377 parseerror(parser, "parse error");
5378 lex_close(parser->lex);
5383 lex_close(parser->lex);
5386 return !compile_errors;
5389 bool parser_compile_file(const char *filename)
5391 parser->lex = lex_open(filename);
5393 con_err("failed to open file \"%s\"\n", filename);
5396 return parser_compile();
5399 bool parser_compile_string(const char *name, const char *str, size_t len)
5401 parser->lex = lex_open_string(str, len, name);
5403 con_err("failed to create lexer for string \"%s\"\n", name);
5406 return parser_compile();
5409 void parser_cleanup()
5412 for (i = 0; i < vec_size(parser->accessors); ++i) {
5413 ast_delete(parser->accessors[i]->constval.vfunc);
5414 parser->accessors[i]->constval.vfunc = NULL;
5415 ast_delete(parser->accessors[i]);
5417 for (i = 0; i < vec_size(parser->functions); ++i) {
5418 ast_delete(parser->functions[i]);
5420 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5421 ast_delete(parser->imm_vector[i]);
5423 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5424 ast_delete(parser->imm_string[i]);
5426 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5427 ast_delete(parser->imm_float[i]);
5429 for (i = 0; i < vec_size(parser->fields); ++i) {
5430 ast_delete(parser->fields[i]);
5432 for (i = 0; i < vec_size(parser->globals); ++i) {
5433 ast_delete(parser->globals[i]);
5435 vec_free(parser->accessors);
5436 vec_free(parser->functions);
5437 vec_free(parser->imm_vector);
5438 vec_free(parser->imm_string);
5439 vec_free(parser->imm_float);
5440 vec_free(parser->globals);
5441 vec_free(parser->fields);
5443 for (i = 0; i < vec_size(parser->variables); ++i)
5444 util_htdel(parser->variables[i]);
5445 vec_free(parser->variables);
5446 vec_free(parser->_blocklocals);
5447 vec_free(parser->_locals);
5450 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5451 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5453 vec_free(parser->correct_variables);
5454 vec_free(parser->correct_variables_score);
5457 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5458 ast_delete(parser->_typedefs[i]);
5459 vec_free(parser->_typedefs);
5460 for (i = 0; i < vec_size(parser->typedefs); ++i)
5461 util_htdel(parser->typedefs[i]);
5462 vec_free(parser->typedefs);
5463 vec_free(parser->_blocktypedefs);
5465 vec_free(parser->_block_ctx);
5467 vec_free(parser->labels);
5468 vec_free(parser->gotos);
5469 vec_free(parser->breaks);
5470 vec_free(parser->continues);
5472 ast_value_delete(parser->nil);
5477 bool parser_finish(const char *output)
5483 if (compile_errors) {
5484 con_out("*** there were compile errors\n");
5488 ir = ir_builder_new("gmqcc_out");
5490 con_out("failed to allocate builder\n");
5494 for (i = 0; i < vec_size(parser->fields); ++i) {
5497 if (!ast_istype(parser->fields[i], ast_value))
5499 field = (ast_value*)parser->fields[i];
5500 hasvalue = field->hasvalue;
5501 field->hasvalue = false;
5502 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5503 con_out("failed to generate field %s\n", field->name);
5504 ir_builder_delete(ir);
5509 ast_expression *subtype;
5510 field->hasvalue = true;
5511 subtype = field->expression.next;
5512 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5513 if (subtype->expression.vtype == TYPE_FIELD)
5514 ifld->fieldtype = subtype->expression.next->expression.vtype;
5515 else if (subtype->expression.vtype == TYPE_FUNCTION)
5516 ifld->outtype = subtype->expression.next->expression.vtype;
5517 (void)!ir_value_set_field(field->ir_v, ifld);
5520 for (i = 0; i < vec_size(parser->globals); ++i) {
5522 if (!ast_istype(parser->globals[i], ast_value))
5524 asvalue = (ast_value*)(parser->globals[i]);
5525 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5526 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5527 "unused global: `%s`", asvalue->name);
5529 if (!ast_global_codegen(asvalue, ir, false)) {
5530 con_out("failed to generate global %s\n", asvalue->name);
5531 ir_builder_delete(ir);
5535 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5536 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5537 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5538 ir_builder_delete(ir);
5542 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5543 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5544 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5545 ir_builder_delete(ir);
5549 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5550 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5551 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5552 ir_builder_delete(ir);
5556 for (i = 0; i < vec_size(parser->globals); ++i) {
5558 if (!ast_istype(parser->globals[i], ast_value))
5560 asvalue = (ast_value*)(parser->globals[i]);
5561 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5563 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5564 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5565 "uninitialized constant: `%s`",
5567 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5568 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5569 "uninitialized global: `%s`",
5572 if (!ast_generate_accessors(asvalue, ir)) {
5573 ir_builder_delete(ir);
5577 for (i = 0; i < vec_size(parser->fields); ++i) {
5579 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5581 if (!ast_istype((ast_expression*)asvalue, ast_value))
5583 if (asvalue->expression.vtype != TYPE_ARRAY)
5585 if (!ast_generate_accessors(asvalue, ir)) {
5586 ir_builder_delete(ir);
5590 for (i = 0; i < vec_size(parser->functions); ++i) {
5591 if (!ast_function_codegen(parser->functions[i], ir)) {
5592 con_out("failed to generate function %s\n", parser->functions[i]->name);
5593 ir_builder_delete(ir);
5598 ir_builder_dump(ir, con_out);
5599 for (i = 0; i < vec_size(parser->functions); ++i) {
5600 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5601 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5602 ir_builder_delete(ir);
5607 if (compile_Werrors) {
5608 con_out("*** there were warnings treated as errors\n");
5609 compile_show_werrors();
5615 ir_builder_dump(ir, con_out);
5617 generate_checksum(parser);
5619 if (!ir_builder_generate(ir, output)) {
5620 con_out("*** failed to generate output file\n");
5621 ir_builder_delete(ir);
5626 ir_builder_delete(ir);