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 parseerror(parser, "TODO: bitxor");
937 case opid3('<','<','='):
938 case opid3('>','>','='):
939 parseerror(parser, "TODO: shifts");
943 generated_op += 1; /* INSTR_OR */
945 generated_op += INSTR_AND;
947 if (NotSameType(TYPE_FLOAT)) {
948 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
949 type_name[exprs[0]->expression.vtype],
950 type_name[exprs[1]->expression.vtype]);
951 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
952 parseerror(parser, "TODO: optional early out");
956 if (CanConstFold(exprs[0], exprs[1]))
958 if (OPTS_FLAG(PERL_LOGIC)) {
959 if (immediate_is_true(ctx, asvalue[0]))
963 out = (ast_expression*)parser_const_float(parser,
964 ( (generated_op == INSTR_OR)
965 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
966 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
971 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
972 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
973 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
974 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
977 for (i = 0; i < 2; ++i) {
978 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
979 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
981 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
983 exprs[i] = out; out = NULL;
984 if (OPTS_FLAG(PERL_LOGIC)) {
985 /* here we want to keep the right expressions' type */
989 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
990 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
992 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
994 exprs[i] = out; out = NULL;
995 if (OPTS_FLAG(PERL_LOGIC)) {
996 /* here we want to keep the right expressions' type */
1001 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1005 case opid2('?',':'):
1006 if (vec_last(parser->pot) != POT_TERNARY2) {
1007 parseerror(parser, "mismatched parenthesis/ternary");
1010 vec_pop(parser->pot);
1011 if (!ast_compare_type(exprs[1], exprs[2])) {
1012 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1013 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1014 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1017 if (CanConstFold1(exprs[0]))
1018 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1020 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1024 generated_op += 1; /* INSTR_GT */
1026 generated_op += 1; /* INSTR_LT */
1027 case opid2('>', '='):
1028 generated_op += 1; /* INSTR_GE */
1029 case opid2('<', '='):
1030 generated_op += INSTR_LE;
1031 if (NotSameType(TYPE_FLOAT)) {
1032 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1033 type_name[exprs[0]->expression.vtype],
1034 type_name[exprs[1]->expression.vtype]);
1037 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1039 case opid2('!', '='):
1040 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1041 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1042 type_name[exprs[0]->expression.vtype],
1043 type_name[exprs[1]->expression.vtype]);
1046 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1048 case opid2('=', '='):
1049 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1050 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1051 type_name[exprs[0]->expression.vtype],
1052 type_name[exprs[1]->expression.vtype]);
1055 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1059 if (ast_istype(exprs[0], ast_entfield)) {
1060 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1061 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1062 exprs[0]->expression.vtype == TYPE_FIELD &&
1063 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1065 assignop = type_storep_instr[TYPE_VECTOR];
1068 assignop = type_storep_instr[exprs[0]->expression.vtype];
1069 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1071 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1072 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1073 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1074 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1075 exprs[1]->expression.vtype == TYPE_FUNCTION)
1077 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1078 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1081 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1086 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1087 exprs[0]->expression.vtype == TYPE_FIELD &&
1088 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1090 assignop = type_store_instr[TYPE_VECTOR];
1093 assignop = type_store_instr[exprs[0]->expression.vtype];
1096 if (assignop == AINSTR_END) {
1097 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1098 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1099 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1101 else if (!ast_compare_type(exprs[0], exprs[1]))
1103 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1104 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1105 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1106 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1107 exprs[1]->expression.vtype == TYPE_FUNCTION)
1109 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1110 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1113 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1116 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1117 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1119 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1121 case opid3('+','+','P'):
1122 case opid3('-','-','P'):
1124 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1125 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1126 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1129 if (op->id == opid3('+','+','P'))
1130 addop = INSTR_ADD_F;
1132 addop = INSTR_SUB_F;
1133 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1134 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1136 if (ast_istype(exprs[0], ast_entfield)) {
1137 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1139 (ast_expression*)parser_const_float_1(parser));
1141 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1143 (ast_expression*)parser_const_float_1(parser));
1146 case opid3('S','+','+'):
1147 case opid3('S','-','-'):
1149 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1150 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1151 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1154 if (op->id == opid3('S','+','+')) {
1155 addop = INSTR_ADD_F;
1156 subop = INSTR_SUB_F;
1158 addop = INSTR_SUB_F;
1159 subop = INSTR_ADD_F;
1161 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1162 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1164 if (ast_istype(exprs[0], ast_entfield)) {
1165 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1167 (ast_expression*)parser_const_float_1(parser));
1169 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1171 (ast_expression*)parser_const_float_1(parser));
1175 out = (ast_expression*)ast_binary_new(ctx, subop,
1177 (ast_expression*)parser_const_float_1(parser));
1179 case opid2('+','='):
1180 case opid2('-','='):
1181 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1182 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1184 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1185 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1186 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1190 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1191 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1193 if (ast_istype(exprs[0], ast_entfield))
1194 assignop = type_storep_instr[exprs[0]->expression.vtype];
1196 assignop = type_store_instr[exprs[0]->expression.vtype];
1197 switch (exprs[0]->expression.vtype) {
1199 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1200 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1201 exprs[0], exprs[1]);
1204 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1205 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1206 exprs[0], exprs[1]);
1209 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1210 type_name[exprs[0]->expression.vtype],
1211 type_name[exprs[1]->expression.vtype]);
1215 case opid2('*','='):
1216 case opid2('/','='):
1217 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1218 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1219 exprs[0]->expression.vtype == TYPE_VECTOR))
1221 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1222 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1223 parseerror(parser, "invalid types used in expression: %s and %s",
1227 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1228 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1230 if (ast_istype(exprs[0], ast_entfield))
1231 assignop = type_storep_instr[exprs[0]->expression.vtype];
1233 assignop = type_store_instr[exprs[0]->expression.vtype];
1234 switch (exprs[0]->expression.vtype) {
1236 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1237 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1238 exprs[0], exprs[1]);
1241 if (op->id == opid2('*','=')) {
1242 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1243 exprs[0], exprs[1]);
1245 /* there's no DIV_VF */
1246 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1247 (ast_expression*)parser_const_float_1(parser),
1251 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1256 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1257 type_name[exprs[0]->expression.vtype],
1258 type_name[exprs[1]->expression.vtype]);
1262 case opid2('&','='):
1263 case opid2('|','='):
1264 if (NotSameType(TYPE_FLOAT)) {
1265 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1266 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1267 parseerror(parser, "invalid types used in expression: %s and %s",
1271 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1272 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1274 if (ast_istype(exprs[0], ast_entfield))
1275 assignop = type_storep_instr[exprs[0]->expression.vtype];
1277 assignop = type_store_instr[exprs[0]->expression.vtype];
1278 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1279 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1280 exprs[0], exprs[1]);
1282 case opid3('&','~','='):
1283 /* This is like: a &= ~(b);
1284 * But QC has no bitwise-not, so we implement it as
1287 if (NotSameType(TYPE_FLOAT)) {
1288 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1289 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1290 parseerror(parser, "invalid types used in expression: %s and %s",
1294 if (ast_istype(exprs[0], ast_entfield))
1295 assignop = type_storep_instr[exprs[0]->expression.vtype];
1297 assignop = type_store_instr[exprs[0]->expression.vtype];
1298 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1301 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1302 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1304 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1305 asbinstore->keep_dest = true;
1306 out = (ast_expression*)asbinstore;
1312 parseerror(parser, "failed to apply operand %s", op->op);
1316 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1317 vec_push(sy->out, syexp(ctx, out));
1321 static bool parser_close_call(parser_t *parser, shunt *sy)
1323 /* was a function call */
1324 ast_expression *fun;
1330 vec_shrinkby(sy->ops, 1);
1331 fid = sy->ops[vec_size(sy->ops)].off;
1333 /* out[fid] is the function
1334 * everything above is parameters...
1335 * 0 params = nothing
1336 * 1 params = ast_expression
1340 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1341 parseerror(parser, "internal error: function call needs function and parameter list...");
1345 fun = sy->out[fid].out;
1347 if (fun == intrinsic_debug_typestring) {
1349 if (fid+2 != vec_size(sy->out) ||
1350 vec_last(sy->out).block)
1352 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1355 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1356 ast_unref(vec_last(sy->out).out);
1357 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1358 (ast_expression*)parser_const_string(parser, ty, false));
1359 vec_shrinkby(sy->out, 1);
1363 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1365 parseerror(parser, "internal error: failed to create ast_call node");
1369 if (fid+1 == vec_size(sy->out)) {
1372 } else if (fid+2 == vec_size(sy->out)) {
1374 vec_shrinkby(sy->out, 1);
1375 params = sy->out[vec_size(sy->out)].block;
1379 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1381 paramcount = vec_size(params->exprs);
1382 call->params = params->exprs;
1383 params->exprs = NULL;
1386 (void)!ast_call_check_types(call);
1388 parseerror(parser, "invalid function call");
1392 /* overwrite fid, the function, with a call */
1393 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1395 if (fun->expression.vtype != TYPE_FUNCTION) {
1396 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1400 if (!fun->expression.next) {
1401 parseerror(parser, "could not determine function return type");
1404 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1406 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1408 return !parsewarning(parser, WARN_DEPRECATED,
1409 "call to function (which is marked deprecated)\n",
1410 "-> it has been declared here: %s:%i",
1411 ast_ctx(fun).file, ast_ctx(fun).line);
1414 return !parsewarning(parser, WARN_DEPRECATED,
1415 "call to `%s` (which is marked deprecated)\n"
1416 "-> `%s` declared here: %s:%i",
1417 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1419 return !parsewarning(parser, WARN_DEPRECATED,
1420 "call to `%s` (deprecated: %s)\n"
1421 "-> `%s` declared here: %s:%i",
1422 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1426 if (vec_size(fun->expression.params) != paramcount &&
1427 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1428 vec_size(fun->expression.params) < paramcount))
1430 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1432 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1433 "too %s parameters for call to %s: expected %i, got %i\n"
1434 " -> `%s` has been declared here: %s:%i",
1435 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1436 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1438 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1439 "too %s parameters for function call: expected %i, got %i\n"
1440 " -> it has been declared here: %s:%i",
1441 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1442 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1449 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1451 if (!vec_size(sy->ops)) {
1452 parseerror(parser, "unmatched closing paren");
1455 /* this would for bit a + (x) because there are no operators inside (x)
1456 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1457 parseerror(parser, "empty parenthesis expression");
1461 while (vec_size(sy->ops)) {
1462 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1463 if (!parser_close_call(parser, sy))
1467 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1468 vec_shrinkby(sy->ops, 1);
1469 return !functions_only;
1471 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1474 /* pop off the parenthesis */
1475 vec_shrinkby(sy->ops, 1);
1476 /* then apply the index operator */
1477 if (!parser_sy_apply_operator(parser, sy))
1481 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1484 if (vec_last(parser->pot) != POT_TERNARY1) {
1485 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1488 vec_last(parser->pot) = POT_TERNARY2;
1489 /* pop off the parenthesis */
1490 vec_shrinkby(sy->ops, 1);
1493 if (!parser_sy_apply_operator(parser, sy))
1499 static void parser_reclassify_token(parser_t *parser)
1502 for (i = 0; i < operator_count; ++i) {
1503 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1504 parser->tok = TOKEN_OPERATOR;
1510 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1512 ast_expression *expr = NULL;
1514 bool wantop = false;
1515 bool gotmemberof = false;
1516 /* only warn once about an assignment in a truth value because the current code
1517 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1519 bool warn_truthvalue = true;
1521 /* count the parens because an if starts with one, so the
1522 * end of a condition is an unmatched closing paren
1530 parser->lex->flags.noops = false;
1532 parser_reclassify_token(parser);
1537 gotmemberof = false;
1539 parser->memberof = 0;
1541 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1542 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1544 /* a translatable string */
1548 parseerror(parser, "expected operator or end of statement, got constant");
1552 parser->lex->flags.noops = true;
1553 if (!parser_next(parser) || parser->tok != '(') {
1554 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1557 parser->lex->flags.noops = false;
1558 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1559 parseerror(parser, "expected a constant string in translatable-string extension");
1562 val = parser_const_string(parser, parser_tokval(parser), true);
1566 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1567 DEBUGSHUNTDO(con_out("push string\n"));
1569 if (!parser_next(parser) || parser->tok != ')') {
1570 parseerror(parser, "expected closing paren after translatable string");
1574 else if (parser->tok == TOKEN_IDENT)
1576 ast_expression *var;
1578 parseerror(parser, "expected operator or end of statement");
1583 if (opts.standard == COMPILER_GMQCC)
1585 if (parser->memberof == TYPE_ENTITY) {
1586 /* still get vars first since there could be a fieldpointer */
1587 var = parser_find_var(parser, parser_tokval(parser));
1589 var = parser_find_field(parser, parser_tokval(parser));
1591 else if (parser->memberof == TYPE_VECTOR)
1593 parseerror(parser, "TODO: implement effective vector member access");
1596 else if (parser->memberof) {
1597 parseerror(parser, "namespace for member not found");
1601 var = parser_find_var(parser, parser_tokval(parser));
1603 var = parser_find_var(parser, parser_tokval(parser));
1605 var = parser_find_field(parser, parser_tokval(parser));
1607 if (!var && with_labels) {
1608 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1610 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1611 var = (ast_expression*)lbl;
1612 vec_push(parser->labels, lbl);
1617 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1618 var = (ast_expression*)intrinsic_debug_typestring;
1623 char *correct = NULL;
1626 * sometimes people use preprocessing predefs without enabling them
1627 * i've done this thousands of times already myself. Lets check for
1628 * it in the predef table. And diagnose it better :)
1630 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1631 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1632 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1633 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1640 * TODO: determine the best score for the identifier: be it
1641 * a variable, a field.
1643 * We should also consider adding correction tables for
1644 * other things as well.
1646 if (OPTS_FLAG(ENHANCED_DIAGNOSTICS)) {
1648 correct_init(&corr);
1650 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1651 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1652 if (strcmp(correct, parser_tokval(parser))) {
1654 } else if (correct) {
1659 correct_free(&corr);
1662 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1667 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1673 if (ast_istype(var, ast_value)) {
1674 ((ast_value*)var)->uses++;
1676 else if (ast_istype(var, ast_member)) {
1677 ast_member *mem = (ast_member*)var;
1678 if (ast_istype(mem->owner, ast_value))
1679 ((ast_value*)(mem->owner))->uses++;
1682 vec_push(sy.out, syexp(parser_ctx(parser), var));
1683 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1685 else if (parser->tok == TOKEN_FLOATCONST) {
1688 parseerror(parser, "expected operator or end of statement, got constant");
1692 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1695 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1696 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1698 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1701 parseerror(parser, "expected operator or end of statement, got constant");
1705 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1708 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1709 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1711 else if (parser->tok == TOKEN_STRINGCONST) {
1714 parseerror(parser, "expected operator or end of statement, got constant");
1718 val = parser_const_string(parser, parser_tokval(parser), false);
1721 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1722 DEBUGSHUNTDO(con_out("push string\n"));
1724 else if (parser->tok == TOKEN_VECTORCONST) {
1727 parseerror(parser, "expected operator or end of statement, got constant");
1731 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1734 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1735 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1736 parser_token(parser)->constval.v.x,
1737 parser_token(parser)->constval.v.y,
1738 parser_token(parser)->constval.v.z));
1740 else if (parser->tok == '(') {
1741 parseerror(parser, "internal error: '(' should be classified as operator");
1744 else if (parser->tok == '[') {
1745 parseerror(parser, "internal error: '[' should be classified as operator");
1748 else if (parser->tok == ')') {
1750 DEBUGSHUNTDO(con_out("do[op] )\n"));
1754 /* we do expect an operator next */
1755 /* closing an opening paren */
1756 if (!parser_close_paren(parser, &sy, false))
1758 if (vec_last(parser->pot) != POT_PAREN) {
1759 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1762 vec_pop(parser->pot);
1764 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1768 /* allowed for function calls */
1769 if (!parser_close_paren(parser, &sy, true))
1771 if (vec_last(parser->pot) != POT_PAREN) {
1772 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1775 vec_pop(parser->pot);
1779 else if (parser->tok == ']') {
1781 parseerror(parser, "operand expected");
1785 if (!parser_close_paren(parser, &sy, false))
1787 if (vec_last(parser->pot) != POT_PAREN) {
1788 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1791 vec_pop(parser->pot);
1794 else if (parser->tok == TOKEN_TYPENAME) {
1795 parseerror(parser, "unexpected typename");
1798 else if (parser->tok != TOKEN_OPERATOR) {
1800 parseerror(parser, "expected operator or end of statement");
1807 /* classify the operator */
1808 const oper_info *op;
1809 const oper_info *olast = NULL;
1811 for (o = 0; o < operator_count; ++o) {
1812 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1813 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1814 !strcmp(parser_tokval(parser), operators[o].op))
1819 if (o == operator_count) {
1820 /* no operator found... must be the end of the statement */
1823 /* found an operator */
1826 /* when declaring variables, a comma starts a new variable */
1827 if (op->id == opid1(',') && !parens && stopatcomma) {
1828 /* fixup the token */
1833 /* a colon without a pervious question mark cannot be a ternary */
1834 if (!ternaries && op->id == opid2(':','?')) {
1839 if (op->id == opid1(',')) {
1840 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1841 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1845 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1846 olast = &operators[vec_last(sy.ops).etype-1];
1848 #define IsAssignOp(x) (\
1849 (x) == opid1('=') || \
1850 (x) == opid2('+','=') || \
1851 (x) == opid2('-','=') || \
1852 (x) == opid2('*','=') || \
1853 (x) == opid2('/','=') || \
1854 (x) == opid2('%','=') || \
1855 (x) == opid2('&','=') || \
1856 (x) == opid2('|','=') || \
1857 (x) == opid3('&','~','=') \
1859 if (warn_truthvalue) {
1860 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1861 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1862 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1865 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1866 warn_truthvalue = false;
1871 (op->prec < olast->prec) ||
1872 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1874 if (!parser_sy_apply_operator(parser, &sy))
1876 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1877 olast = &operators[vec_last(sy.ops).etype-1];
1882 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1883 /* for gmqcc standard: open up the namespace of the previous type */
1884 ast_expression *prevex = vec_last(sy.out).out;
1886 parseerror(parser, "unexpected member operator");
1889 if (prevex->expression.vtype == TYPE_ENTITY)
1890 parser->memberof = TYPE_ENTITY;
1891 else if (prevex->expression.vtype == TYPE_VECTOR)
1892 parser->memberof = TYPE_VECTOR;
1894 parseerror(parser, "type error: type has no members");
1900 if (op->id == opid1('(')) {
1902 size_t sycount = vec_size(sy.out);
1903 DEBUGSHUNTDO(con_out("push [op] (\n"));
1904 ++parens; vec_push(parser->pot, POT_PAREN);
1905 /* we expected an operator, this is the function-call operator */
1906 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1908 ++parens; vec_push(parser->pot, POT_PAREN);
1909 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1910 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1913 } else if (op->id == opid1('[')) {
1915 parseerror(parser, "unexpected array subscript");
1918 ++parens; vec_push(parser->pot, POT_PAREN);
1919 /* push both the operator and the paren, this makes life easier */
1920 vec_push(sy.ops, syop(parser_ctx(parser), op));
1921 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1923 } else if (op->id == opid2('?',':')) {
1924 vec_push(sy.ops, syop(parser_ctx(parser), op));
1925 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1928 vec_push(parser->pot, POT_TERNARY1);
1929 } else if (op->id == opid2(':','?')) {
1930 if (!vec_size(parser->pot)) {
1931 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1934 if (vec_last(parser->pot) != POT_TERNARY1) {
1935 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1938 if (!parser_close_paren(parser, &sy, false))
1940 vec_push(sy.ops, syop(parser_ctx(parser), op));
1944 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1945 vec_push(sy.ops, syop(parser_ctx(parser), op));
1946 wantop = !!(op->flags & OP_SUFFIX);
1949 if (!parser_next(parser)) {
1952 if (parser->tok == ';' ||
1953 (!parens && parser->tok == ']'))
1959 while (vec_size(sy.ops)) {
1960 if (!parser_sy_apply_operator(parser, &sy))
1964 parser->lex->flags.noops = true;
1965 if (!vec_size(sy.out)) {
1966 parseerror(parser, "empty expression");
1969 expr = sy.out[0].out;
1972 DEBUGSHUNTDO(con_out("shunt done\n"));
1973 if (vec_size(parser->pot)) {
1974 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1977 vec_free(parser->pot);
1981 parser->lex->flags.noops = true;
1987 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1989 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1992 if (!parser_next(parser)) {
1999 static void parser_enterblock(parser_t *parser)
2001 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2002 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2003 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2004 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2005 vec_push(parser->_block_ctx, parser_ctx(parser));
2008 vec_push(parser->correct_variables, correct_trie_new());
2009 vec_push(parser->correct_variables_score, NULL);
2012 static bool parser_leaveblock(parser_t *parser)
2015 size_t locals, typedefs;
2017 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2018 parseerror(parser, "internal error: parser_leaveblock with no block");
2022 util_htdel(vec_last(parser->variables));
2023 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2025 vec_pop(parser->variables);
2026 vec_pop(parser->correct_variables);
2027 vec_pop(parser->correct_variables_score);
2028 if (!vec_size(parser->_blocklocals)) {
2029 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2033 locals = vec_last(parser->_blocklocals);
2034 vec_pop(parser->_blocklocals);
2035 while (vec_size(parser->_locals) != locals) {
2036 ast_expression *e = vec_last(parser->_locals);
2037 ast_value *v = (ast_value*)e;
2038 vec_pop(parser->_locals);
2039 if (ast_istype(e, ast_value) && !v->uses) {
2040 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2045 typedefs = vec_last(parser->_blocktypedefs);
2046 while (vec_size(parser->_typedefs) != typedefs) {
2047 ast_delete(vec_last(parser->_typedefs));
2048 vec_pop(parser->_typedefs);
2050 util_htdel(vec_last(parser->typedefs));
2051 vec_pop(parser->typedefs);
2053 vec_pop(parser->_block_ctx);
2058 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2060 vec_push(parser->_locals, e);
2061 util_htset(vec_last(parser->variables), name, (void*)e);
2065 vec_last(parser->correct_variables),
2066 &vec_last(parser->correct_variables_score),
2071 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2073 vec_push(parser->globals, e);
2074 util_htset(parser->htglobals, name, e);
2078 parser->correct_variables[0],
2079 &parser->correct_variables_score[0],
2084 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2088 ast_expression *prev;
2090 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2093 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2096 parseerror(parser, "internal error: failed to process condition");
2101 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2103 /* vector types need to be cast to true booleans */
2104 ast_binary *bin = (ast_binary*)cond;
2105 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2107 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2109 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2112 parseerror(parser, "internal error: failed to process condition");
2119 unary = (ast_unary*)cond;
2120 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2122 cond = unary->operand;
2123 unary->operand = NULL;
2126 unary = (ast_unary*)cond;
2130 parseerror(parser, "internal error: failed to process condition");
2132 if (ifnot) *_ifnot = !*_ifnot;
2136 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2139 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2142 lex_ctx ctx = parser_ctx(parser);
2144 (void)block; /* not touching */
2146 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2147 if (!parser_next(parser)) {
2148 parseerror(parser, "expected condition or 'not'");
2151 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2153 if (!parser_next(parser)) {
2154 parseerror(parser, "expected condition in parenthesis");
2158 if (parser->tok != '(') {
2159 parseerror(parser, "expected 'if' condition in parenthesis");
2162 /* parse into the expression */
2163 if (!parser_next(parser)) {
2164 parseerror(parser, "expected 'if' condition after opening paren");
2167 /* parse the condition */
2168 cond = parse_expression_leave(parser, false, true, false);
2172 if (parser->tok != ')') {
2173 parseerror(parser, "expected closing paren after 'if' condition");
2177 /* parse into the 'then' branch */
2178 if (!parser_next(parser)) {
2179 parseerror(parser, "expected statement for on-true branch of 'if'");
2183 if (!parse_statement_or_block(parser, &ontrue)) {
2188 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2189 /* check for an else */
2190 if (!strcmp(parser_tokval(parser), "else")) {
2191 /* parse into the 'else' branch */
2192 if (!parser_next(parser)) {
2193 parseerror(parser, "expected on-false branch after 'else'");
2198 if (!parse_statement_or_block(parser, &onfalse)) {
2205 cond = process_condition(parser, cond, &ifnot);
2207 if (ontrue) ast_delete(ontrue);
2208 if (onfalse) ast_delete(onfalse);
2213 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2215 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2216 *out = (ast_expression*)ifthen;
2220 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2221 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2226 /* skip the 'while' and get the body */
2227 if (!parser_next(parser)) {
2228 if (OPTS_FLAG(LOOP_LABELS))
2229 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2231 parseerror(parser, "expected 'while' condition in parenthesis");
2235 if (parser->tok == ':') {
2236 if (!OPTS_FLAG(LOOP_LABELS))
2237 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2238 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2239 parseerror(parser, "expected loop label");
2242 label = util_strdup(parser_tokval(parser));
2243 if (!parser_next(parser)) {
2245 parseerror(parser, "expected 'while' condition in parenthesis");
2250 if (parser->tok != '(') {
2251 parseerror(parser, "expected 'while' condition in parenthesis");
2255 vec_push(parser->breaks, label);
2256 vec_push(parser->continues, label);
2258 rv = parse_while_go(parser, block, out);
2261 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2262 parseerror(parser, "internal error: label stack corrupted");
2268 vec_pop(parser->breaks);
2269 vec_pop(parser->continues);
2274 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2277 ast_expression *cond, *ontrue;
2281 lex_ctx ctx = parser_ctx(parser);
2283 (void)block; /* not touching */
2285 /* parse into the expression */
2286 if (!parser_next(parser)) {
2287 parseerror(parser, "expected 'while' condition after opening paren");
2290 /* parse the condition */
2291 cond = parse_expression_leave(parser, false, true, false);
2295 if (parser->tok != ')') {
2296 parseerror(parser, "expected closing paren after 'while' condition");
2300 /* parse into the 'then' branch */
2301 if (!parser_next(parser)) {
2302 parseerror(parser, "expected while-loop body");
2306 if (!parse_statement_or_block(parser, &ontrue)) {
2311 cond = process_condition(parser, cond, &ifnot);
2316 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2317 *out = (ast_expression*)aloop;
2321 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2322 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2327 /* skip the 'do' and get the body */
2328 if (!parser_next(parser)) {
2329 if (OPTS_FLAG(LOOP_LABELS))
2330 parseerror(parser, "expected loop label or body");
2332 parseerror(parser, "expected loop body");
2336 if (parser->tok == ':') {
2337 if (!OPTS_FLAG(LOOP_LABELS))
2338 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2339 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2340 parseerror(parser, "expected loop label");
2343 label = util_strdup(parser_tokval(parser));
2344 if (!parser_next(parser)) {
2346 parseerror(parser, "expected loop body");
2351 vec_push(parser->breaks, label);
2352 vec_push(parser->continues, label);
2354 rv = parse_dowhile_go(parser, block, out);
2357 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2358 parseerror(parser, "internal error: label stack corrupted");
2364 vec_pop(parser->breaks);
2365 vec_pop(parser->continues);
2370 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2373 ast_expression *cond, *ontrue;
2377 lex_ctx ctx = parser_ctx(parser);
2379 (void)block; /* not touching */
2381 if (!parse_statement_or_block(parser, &ontrue))
2384 /* expect the "while" */
2385 if (parser->tok != TOKEN_KEYWORD ||
2386 strcmp(parser_tokval(parser), "while"))
2388 parseerror(parser, "expected 'while' and condition");
2393 /* skip the 'while' and check for opening paren */
2394 if (!parser_next(parser) || parser->tok != '(') {
2395 parseerror(parser, "expected 'while' condition in parenthesis");
2399 /* parse into the expression */
2400 if (!parser_next(parser)) {
2401 parseerror(parser, "expected 'while' condition after opening paren");
2405 /* parse the condition */
2406 cond = parse_expression_leave(parser, false, true, false);
2410 if (parser->tok != ')') {
2411 parseerror(parser, "expected closing paren after 'while' condition");
2417 if (!parser_next(parser) || parser->tok != ';') {
2418 parseerror(parser, "expected semicolon after condition");
2424 if (!parser_next(parser)) {
2425 parseerror(parser, "parse error");
2431 cond = process_condition(parser, cond, &ifnot);
2436 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2437 *out = (ast_expression*)aloop;
2441 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2442 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2447 /* skip the 'for' and check for opening paren */
2448 if (!parser_next(parser)) {
2449 if (OPTS_FLAG(LOOP_LABELS))
2450 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2452 parseerror(parser, "expected 'for' expressions in parenthesis");
2456 if (parser->tok == ':') {
2457 if (!OPTS_FLAG(LOOP_LABELS))
2458 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2459 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2460 parseerror(parser, "expected loop label");
2463 label = util_strdup(parser_tokval(parser));
2464 if (!parser_next(parser)) {
2466 parseerror(parser, "expected 'for' expressions in parenthesis");
2471 if (parser->tok != '(') {
2472 parseerror(parser, "expected 'for' expressions in parenthesis");
2476 vec_push(parser->breaks, label);
2477 vec_push(parser->continues, label);
2479 rv = parse_for_go(parser, block, out);
2482 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2483 parseerror(parser, "internal error: label stack corrupted");
2489 vec_pop(parser->breaks);
2490 vec_pop(parser->continues);
2494 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2497 ast_expression *initexpr, *cond, *increment, *ontrue;
2503 lex_ctx ctx = parser_ctx(parser);
2505 parser_enterblock(parser);
2512 /* parse into the expression */
2513 if (!parser_next(parser)) {
2514 parseerror(parser, "expected 'for' initializer after opening paren");
2519 if (parser->tok == TOKEN_IDENT)
2520 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2522 if (typevar || parser->tok == TOKEN_TYPENAME) {
2524 if (opts.standard != COMPILER_GMQCC) {
2525 if (parsewarning(parser, WARN_EXTENSIONS,
2526 "current standard does not allow variable declarations in for-loop initializers"))
2530 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2533 else if (parser->tok != ';')
2535 initexpr = parse_expression_leave(parser, false, false, false);
2540 /* move on to condition */
2541 if (parser->tok != ';') {
2542 parseerror(parser, "expected semicolon after for-loop initializer");
2545 if (!parser_next(parser)) {
2546 parseerror(parser, "expected for-loop condition");
2550 /* parse the condition */
2551 if (parser->tok != ';') {
2552 cond = parse_expression_leave(parser, false, true, false);
2557 /* move on to incrementor */
2558 if (parser->tok != ';') {
2559 parseerror(parser, "expected semicolon after for-loop initializer");
2562 if (!parser_next(parser)) {
2563 parseerror(parser, "expected for-loop condition");
2567 /* parse the incrementor */
2568 if (parser->tok != ')') {
2569 increment = parse_expression_leave(parser, false, false, false);
2572 if (!ast_side_effects(increment)) {
2573 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2579 if (parser->tok != ')') {
2580 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2583 /* parse into the 'then' branch */
2584 if (!parser_next(parser)) {
2585 parseerror(parser, "expected for-loop body");
2588 if (!parse_statement_or_block(parser, &ontrue))
2592 cond = process_condition(parser, cond, &ifnot);
2596 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2597 *out = (ast_expression*)aloop;
2599 if (!parser_leaveblock(parser))
2603 if (initexpr) ast_delete(initexpr);
2604 if (cond) ast_delete(cond);
2605 if (increment) ast_delete(increment);
2606 (void)!parser_leaveblock(parser);
2610 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2612 ast_expression *exp = NULL;
2613 ast_return *ret = NULL;
2614 ast_value *expected = parser->function->vtype;
2616 lex_ctx ctx = parser_ctx(parser);
2618 (void)block; /* not touching */
2620 if (!parser_next(parser)) {
2621 parseerror(parser, "expected return expression");
2625 if (parser->tok != ';') {
2626 exp = parse_expression(parser, false, false);
2630 if (exp->expression.vtype != TYPE_NIL &&
2631 exp->expression.vtype != expected->expression.next->expression.vtype)
2633 parseerror(parser, "return with invalid expression");
2636 ret = ast_return_new(ctx, exp);
2642 if (!parser_next(parser))
2643 parseerror(parser, "parse error");
2644 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2645 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2647 ret = ast_return_new(ctx, NULL);
2649 *out = (ast_expression*)ret;
2653 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2656 unsigned int levels = 0;
2657 lex_ctx ctx = parser_ctx(parser);
2658 const char **loops = (is_continue ? parser->continues : parser->breaks);
2660 (void)block; /* not touching */
2661 if (!parser_next(parser)) {
2662 parseerror(parser, "expected semicolon or loop label");
2666 if (!vec_size(loops)) {
2668 parseerror(parser, "`continue` can only be used inside loops");
2670 parseerror(parser, "`break` can only be used inside loops or switches");
2673 if (parser->tok == TOKEN_IDENT) {
2674 if (!OPTS_FLAG(LOOP_LABELS))
2675 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2676 i = vec_size(loops);
2678 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2681 parseerror(parser, "no such loop to %s: `%s`",
2682 (is_continue ? "continue" : "break out of"),
2683 parser_tokval(parser));
2688 if (!parser_next(parser)) {
2689 parseerror(parser, "expected semicolon");
2694 if (parser->tok != ';') {
2695 parseerror(parser, "expected semicolon");
2699 if (!parser_next(parser))
2700 parseerror(parser, "parse error");
2702 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2706 /* returns true when it was a variable qualifier, false otherwise!
2707 * on error, cvq is set to CV_WRONG
2709 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2711 bool had_const = false;
2712 bool had_var = false;
2713 bool had_noref = false;
2714 bool had_attrib = false;
2715 bool had_static = false;
2720 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2722 /* parse an attribute */
2723 if (!parser_next(parser)) {
2724 parseerror(parser, "expected attribute after `[[`");
2728 if (!strcmp(parser_tokval(parser), "noreturn")) {
2729 flags |= AST_FLAG_NORETURN;
2730 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2731 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2736 else if (!strcmp(parser_tokval(parser), "noref")) {
2738 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2739 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2744 else if (!strcmp(parser_tokval(parser), "inline")) {
2745 flags |= AST_FLAG_INLINE;
2746 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2747 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2754 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2755 flags |= AST_FLAG_DEPRECATED;
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "parse error in attribute");
2763 if (parser->tok == '(') {
2764 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2765 parseerror(parser, "`deprecated` attribute missing parameter");
2769 *message = util_strdup(parser_tokval(parser));
2771 if (!parser_next(parser)) {
2772 parseerror(parser, "parse error in attribute");
2776 if(parser->tok != ')') {
2777 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2781 if (!parser_next(parser)) {
2782 parseerror(parser, "parse error in attribute");
2787 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2788 parseerror(parser, "`deprecated` attribute expected `]]`");
2791 if (*message) mem_d(*message);
2799 /* Skip tokens until we hit a ]] */
2800 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2801 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2802 if (!parser_next(parser)) {
2803 parseerror(parser, "error inside attribute");
2810 else if (!strcmp(parser_tokval(parser), "static"))
2812 else if (!strcmp(parser_tokval(parser), "const"))
2814 else if (!strcmp(parser_tokval(parser), "var"))
2816 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2818 else if (!strcmp(parser_tokval(parser), "noref"))
2820 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2825 if (!parser_next(parser))
2835 *is_static = had_static;
2839 parseerror(parser, "parse error after variable qualifier");
2844 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2845 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2850 /* skip the 'while' and get the body */
2851 if (!parser_next(parser)) {
2852 if (OPTS_FLAG(LOOP_LABELS))
2853 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2855 parseerror(parser, "expected 'switch' operand in parenthesis");
2859 if (parser->tok == ':') {
2860 if (!OPTS_FLAG(LOOP_LABELS))
2861 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2862 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2863 parseerror(parser, "expected loop label");
2866 label = util_strdup(parser_tokval(parser));
2867 if (!parser_next(parser)) {
2869 parseerror(parser, "expected 'switch' operand in parenthesis");
2874 if (parser->tok != '(') {
2875 parseerror(parser, "expected 'switch' operand in parenthesis");
2879 vec_push(parser->breaks, label);
2881 rv = parse_switch_go(parser, block, out);
2884 if (vec_last(parser->breaks) != label) {
2885 parseerror(parser, "internal error: label stack corrupted");
2891 vec_pop(parser->breaks);
2896 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2898 ast_expression *operand;
2901 ast_switch *switchnode;
2902 ast_switch_case swcase;
2905 bool noref, is_static;
2906 uint32_t qflags = 0;
2908 lex_ctx ctx = parser_ctx(parser);
2910 (void)block; /* not touching */
2913 /* parse into the expression */
2914 if (!parser_next(parser)) {
2915 parseerror(parser, "expected switch operand");
2918 /* parse the operand */
2919 operand = parse_expression_leave(parser, false, false, false);
2923 switchnode = ast_switch_new(ctx, operand);
2926 if (parser->tok != ')') {
2927 ast_delete(switchnode);
2928 parseerror(parser, "expected closing paren after 'switch' operand");
2932 /* parse over the opening paren */
2933 if (!parser_next(parser) || parser->tok != '{') {
2934 ast_delete(switchnode);
2935 parseerror(parser, "expected list of cases");
2939 if (!parser_next(parser)) {
2940 ast_delete(switchnode);
2941 parseerror(parser, "expected 'case' or 'default'");
2945 /* new block; allow some variables to be declared here */
2946 parser_enterblock(parser);
2949 if (parser->tok == TOKEN_IDENT)
2950 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2951 if (typevar || parser->tok == TOKEN_TYPENAME) {
2952 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2953 ast_delete(switchnode);
2958 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2960 if (cvq == CV_WRONG) {
2961 ast_delete(switchnode);
2964 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2965 ast_delete(switchnode);
2974 while (parser->tok != '}') {
2975 ast_block *caseblock;
2977 if (!strcmp(parser_tokval(parser), "case")) {
2978 if (!parser_next(parser)) {
2979 ast_delete(switchnode);
2980 parseerror(parser, "expected expression for case");
2983 swcase.value = parse_expression_leave(parser, false, false, false);
2984 if (!swcase.value) {
2985 ast_delete(switchnode);
2986 parseerror(parser, "expected expression for case");
2989 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2990 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2991 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2997 else if (!strcmp(parser_tokval(parser), "default")) {
2998 swcase.value = NULL;
2999 if (!parser_next(parser)) {
3000 ast_delete(switchnode);
3001 parseerror(parser, "expected colon");
3006 ast_delete(switchnode);
3007 parseerror(parser, "expected 'case' or 'default'");
3011 /* Now the colon and body */
3012 if (parser->tok != ':') {
3013 if (swcase.value) ast_unref(swcase.value);
3014 ast_delete(switchnode);
3015 parseerror(parser, "expected colon");
3019 if (!parser_next(parser)) {
3020 if (swcase.value) ast_unref(swcase.value);
3021 ast_delete(switchnode);
3022 parseerror(parser, "expected statements or case");
3025 caseblock = ast_block_new(parser_ctx(parser));
3027 if (swcase.value) ast_unref(swcase.value);
3028 ast_delete(switchnode);
3031 swcase.code = (ast_expression*)caseblock;
3032 vec_push(switchnode->cases, swcase);
3034 ast_expression *expr;
3035 if (parser->tok == '}')
3037 if (parser->tok == TOKEN_KEYWORD) {
3038 if (!strcmp(parser_tokval(parser), "case") ||
3039 !strcmp(parser_tokval(parser), "default"))
3044 if (!parse_statement(parser, caseblock, &expr, true)) {
3045 ast_delete(switchnode);
3050 if (!ast_block_add_expr(caseblock, expr)) {
3051 ast_delete(switchnode);
3057 parser_leaveblock(parser);
3060 if (parser->tok != '}') {
3061 ast_delete(switchnode);
3062 parseerror(parser, "expected closing paren of case list");
3065 if (!parser_next(parser)) {
3066 ast_delete(switchnode);
3067 parseerror(parser, "parse error after switch");
3070 *out = (ast_expression*)switchnode;
3074 /* parse computed goto sides */
3075 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3076 ast_expression *on_true;
3077 ast_expression *on_false;
3078 ast_expression *cond;
3083 if (ast_istype(*side, ast_ternary)) {
3084 ast_ternary *tern = (ast_ternary*)*side;
3085 on_true = parse_goto_computed(parser, &tern->on_true);
3086 on_false = parse_goto_computed(parser, &tern->on_false);
3088 if (!on_true || !on_false) {
3089 parseerror(parser, "expected label or expression in ternary");
3090 if (on_true) ast_unref(on_true);
3091 if (on_false) ast_unref(on_false);
3099 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3100 } else if (ast_istype(*side, ast_label)) {
3101 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3102 ast_goto_set_label(gt, ((ast_label*)*side));
3104 return (ast_expression*)gt;
3109 static bool parse_goto(parser_t *parser, ast_expression **out)
3111 ast_goto *gt = NULL;
3112 ast_expression *lbl;
3114 if (!parser_next(parser))
3117 if (parser->tok != TOKEN_IDENT) {
3118 ast_expression *expression;
3120 /* could be an expression i.e computed goto :-) */
3121 if (parser->tok != '(') {
3122 parseerror(parser, "expected label name after `goto`");
3126 /* failed to parse expression for goto */
3127 if (!(expression = parse_expression(parser, false, true)) ||
3128 !(*out = parse_goto_computed(parser, &expression))) {
3129 parseerror(parser, "invalid goto expression");
3130 ast_unref(expression);
3137 /* not computed goto */
3138 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3139 lbl = parser_find_label(parser, gt->name);
3141 if (!ast_istype(lbl, ast_label)) {
3142 parseerror(parser, "internal error: label is not an ast_label");
3146 ast_goto_set_label(gt, (ast_label*)lbl);
3149 vec_push(parser->gotos, gt);
3151 if (!parser_next(parser) || parser->tok != ';') {
3152 parseerror(parser, "semicolon expected after goto label");
3155 if (!parser_next(parser)) {
3156 parseerror(parser, "parse error after goto");
3160 *out = (ast_expression*)gt;
3164 static bool parse_skipwhite(parser_t *parser)
3167 if (!parser_next(parser))
3169 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3170 return parser->tok < TOKEN_ERROR;
3173 static bool parse_eol(parser_t *parser)
3175 if (!parse_skipwhite(parser))
3177 return parser->tok == TOKEN_EOL;
3180 static bool parse_pragma_do(parser_t *parser)
3182 if (!parser_next(parser) ||
3183 parser->tok != TOKEN_IDENT ||
3184 strcmp(parser_tokval(parser), "pragma"))
3186 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3189 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3190 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3194 if (!strcmp(parser_tokval(parser), "noref")) {
3195 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3196 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3199 parser->noref = !!parser_token(parser)->constval.i;
3200 if (!parse_eol(parser)) {
3201 parseerror(parser, "parse error after `noref` pragma");
3207 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3214 static bool parse_pragma(parser_t *parser)
3217 parser->lex->flags.preprocessing = true;
3218 parser->lex->flags.mergelines = true;
3219 rv = parse_pragma_do(parser);
3220 if (parser->tok != TOKEN_EOL) {
3221 parseerror(parser, "junk after pragma");
3224 parser->lex->flags.preprocessing = false;
3225 parser->lex->flags.mergelines = false;
3226 if (!parser_next(parser)) {
3227 parseerror(parser, "parse error after pragma");
3233 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3235 bool noref, is_static;
3237 uint32_t qflags = 0;
3238 ast_value *typevar = NULL;
3239 char *vstring = NULL;
3243 if (parser->tok == TOKEN_IDENT)
3244 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3246 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3248 /* local variable */
3250 parseerror(parser, "cannot declare a variable from here");
3253 if (opts.standard == COMPILER_QCC) {
3254 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3257 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3261 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3263 if (cvq == CV_WRONG)
3265 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3267 else if (parser->tok == TOKEN_KEYWORD)
3269 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3274 if (!parser_next(parser)) {
3275 parseerror(parser, "parse error after __builtin_debug_printtype");
3279 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3281 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3282 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3283 if (!parser_next(parser)) {
3284 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3290 if (!parse_statement(parser, block, out, allow_cases))
3293 con_out("__builtin_debug_printtype: got no output node\n");
3296 ast_type_to_string(*out, ty, sizeof(ty));
3297 con_out("__builtin_debug_printtype: `%s`\n", ty);
3302 else if (!strcmp(parser_tokval(parser), "return"))
3304 return parse_return(parser, block, out);
3306 else if (!strcmp(parser_tokval(parser), "if"))
3308 return parse_if(parser, block, out);
3310 else if (!strcmp(parser_tokval(parser), "while"))
3312 return parse_while(parser, block, out);
3314 else if (!strcmp(parser_tokval(parser), "do"))
3316 return parse_dowhile(parser, block, out);
3318 else if (!strcmp(parser_tokval(parser), "for"))
3320 if (opts.standard == COMPILER_QCC) {
3321 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3324 return parse_for(parser, block, out);
3326 else if (!strcmp(parser_tokval(parser), "break"))
3328 return parse_break_continue(parser, block, out, false);
3330 else if (!strcmp(parser_tokval(parser), "continue"))
3332 return parse_break_continue(parser, block, out, true);
3334 else if (!strcmp(parser_tokval(parser), "switch"))
3336 return parse_switch(parser, block, out);
3338 else if (!strcmp(parser_tokval(parser), "case") ||
3339 !strcmp(parser_tokval(parser), "default"))
3342 parseerror(parser, "unexpected 'case' label");
3347 else if (!strcmp(parser_tokval(parser), "goto"))
3349 return parse_goto(parser, out);
3351 else if (!strcmp(parser_tokval(parser), "typedef"))
3353 if (!parser_next(parser)) {
3354 parseerror(parser, "expected type definition after 'typedef'");
3357 return parse_typedef(parser);
3359 parseerror(parser, "Unexpected keyword");
3362 else if (parser->tok == '{')
3365 inner = parse_block(parser);
3368 *out = (ast_expression*)inner;
3371 else if (parser->tok == ':')
3375 if (!parser_next(parser)) {
3376 parseerror(parser, "expected label name");
3379 if (parser->tok != TOKEN_IDENT) {
3380 parseerror(parser, "label must be an identifier");
3383 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3385 if (!label->undefined) {
3386 parseerror(parser, "label `%s` already defined", label->name);
3389 label->undefined = false;
3392 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3393 vec_push(parser->labels, label);
3395 *out = (ast_expression*)label;
3396 if (!parser_next(parser)) {
3397 parseerror(parser, "parse error after label");
3400 for (i = 0; i < vec_size(parser->gotos); ++i) {
3401 if (!strcmp(parser->gotos[i]->name, label->name)) {
3402 ast_goto_set_label(parser->gotos[i], label);
3403 vec_remove(parser->gotos, i, 1);
3409 else if (parser->tok == ';')
3411 if (!parser_next(parser)) {
3412 parseerror(parser, "parse error after empty statement");
3419 ast_expression *exp = parse_expression(parser, false, false);
3423 if (!ast_side_effects(exp)) {
3424 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3431 static bool parse_block_into(parser_t *parser, ast_block *block)
3435 parser_enterblock(parser);
3437 if (!parser_next(parser)) { /* skip the '{' */
3438 parseerror(parser, "expected function body");
3442 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3444 ast_expression *expr = NULL;
3445 if (parser->tok == '}')
3448 if (!parse_statement(parser, block, &expr, false)) {
3449 /* parseerror(parser, "parse error"); */
3455 if (!ast_block_add_expr(block, expr)) {
3462 if (parser->tok != '}') {
3465 (void)parser_next(parser);
3469 if (!parser_leaveblock(parser))
3471 return retval && !!block;
3474 static ast_block* parse_block(parser_t *parser)
3477 block = ast_block_new(parser_ctx(parser));
3480 if (!parse_block_into(parser, block)) {
3481 ast_block_delete(block);
3487 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3489 if (parser->tok == '{') {
3490 *out = (ast_expression*)parse_block(parser);
3493 return parse_statement(parser, NULL, out, false);
3496 static bool create_vector_members(ast_value *var, ast_member **me)
3499 size_t len = strlen(var->name);
3501 for (i = 0; i < 3; ++i) {
3502 char *name = (char*)mem_a(len+3);
3503 memcpy(name, var->name, len);
3505 name[len+1] = 'x'+i;
3507 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3516 do { ast_member_delete(me[--i]); } while(i);
3520 static bool parse_function_body(parser_t *parser, ast_value *var)
3522 ast_block *block = NULL;
3527 ast_expression *framenum = NULL;
3528 ast_expression *nextthink = NULL;
3529 /* None of the following have to be deleted */
3530 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3531 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3532 bool has_frame_think;
3536 has_frame_think = false;
3537 old = parser->function;
3539 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3540 parseerror(parser, "gotos/labels leaking");
3544 if (var->expression.flags & AST_FLAG_VARIADIC) {
3545 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3546 "variadic function with implementation will not be able to access additional parameters"))
3552 if (parser->tok == '[') {
3553 /* got a frame definition: [ framenum, nextthink ]
3554 * this translates to:
3555 * self.frame = framenum;
3556 * self.nextthink = time + 0.1;
3557 * self.think = nextthink;
3561 fld_think = parser_find_field(parser, "think");
3562 fld_nextthink = parser_find_field(parser, "nextthink");
3563 fld_frame = parser_find_field(parser, "frame");
3564 if (!fld_think || !fld_nextthink || !fld_frame) {
3565 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3566 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3569 gbl_time = parser_find_global(parser, "time");
3570 gbl_self = parser_find_global(parser, "self");
3571 if (!gbl_time || !gbl_self) {
3572 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3573 parseerror(parser, "please declare the following globals: `time`, `self`");
3577 if (!parser_next(parser))
3580 framenum = parse_expression_leave(parser, true, false, false);
3582 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3585 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3586 ast_unref(framenum);
3587 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3591 if (parser->tok != ',') {
3592 ast_unref(framenum);
3593 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3594 parseerror(parser, "Got a %i\n", parser->tok);
3598 if (!parser_next(parser)) {
3599 ast_unref(framenum);
3603 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3605 /* qc allows the use of not-yet-declared functions here
3606 * - this automatically creates a prototype */
3607 ast_value *thinkfunc;
3608 ast_expression *functype = fld_think->expression.next;
3610 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3611 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3612 ast_unref(framenum);
3613 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3617 if (!parser_next(parser)) {
3618 ast_unref(framenum);
3619 ast_delete(thinkfunc);
3623 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3625 nextthink = (ast_expression*)thinkfunc;
3628 nextthink = parse_expression_leave(parser, true, false, false);
3630 ast_unref(framenum);
3631 parseerror(parser, "expected a think-function in [frame,think] notation");
3636 if (!ast_istype(nextthink, ast_value)) {
3637 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3641 if (retval && parser->tok != ']') {
3642 parseerror(parser, "expected closing `]` for [frame,think] notation");
3646 if (retval && !parser_next(parser)) {
3650 if (retval && parser->tok != '{') {
3651 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3656 ast_unref(nextthink);
3657 ast_unref(framenum);
3661 has_frame_think = true;
3664 block = ast_block_new(parser_ctx(parser));
3666 parseerror(parser, "failed to allocate block");
3667 if (has_frame_think) {
3668 ast_unref(nextthink);
3669 ast_unref(framenum);
3674 if (has_frame_think) {
3676 ast_expression *self_frame;
3677 ast_expression *self_nextthink;
3678 ast_expression *self_think;
3679 ast_expression *time_plus_1;
3680 ast_store *store_frame;
3681 ast_store *store_nextthink;
3682 ast_store *store_think;
3684 ctx = parser_ctx(parser);
3685 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3686 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3687 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3689 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3690 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3692 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3693 if (self_frame) ast_delete(self_frame);
3694 if (self_nextthink) ast_delete(self_nextthink);
3695 if (self_think) ast_delete(self_think);
3696 if (time_plus_1) ast_delete(time_plus_1);
3702 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3703 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3704 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3707 ast_delete(self_frame);
3710 if (!store_nextthink) {
3711 ast_delete(self_nextthink);
3715 ast_delete(self_think);
3719 if (store_frame) ast_delete(store_frame);
3720 if (store_nextthink) ast_delete(store_nextthink);
3721 if (store_think) ast_delete(store_think);
3724 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3725 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3726 !ast_block_add_expr(block, (ast_expression*)store_think))
3733 parseerror(parser, "failed to generate code for [frame,think]");
3734 ast_unref(nextthink);
3735 ast_unref(framenum);
3741 parser_enterblock(parser);
3743 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3745 ast_value *param = var->expression.params[parami];
3748 if (param->expression.vtype != TYPE_VECTOR &&
3749 (param->expression.vtype != TYPE_FIELD ||
3750 param->expression.next->expression.vtype != TYPE_VECTOR))
3755 if (!create_vector_members(param, me)) {
3756 ast_block_delete(block);
3760 for (e = 0; e < 3; ++e) {
3761 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3762 ast_block_collect(block, (ast_expression*)me[e]);
3766 func = ast_function_new(ast_ctx(var), var->name, var);
3768 parseerror(parser, "failed to allocate function for `%s`", var->name);
3769 ast_block_delete(block);
3772 vec_push(parser->functions, func);
3774 parser->function = func;
3775 if (!parse_block_into(parser, block)) {
3776 ast_block_delete(block);
3780 vec_push(func->blocks, block);
3782 parser->function = old;
3783 if (!parser_leaveblock(parser))
3785 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3786 parseerror(parser, "internal error: local scopes left");
3790 if (parser->tok == ';')
3791 return parser_next(parser);
3792 else if (opts.standard == COMPILER_QCC)
3793 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3797 vec_pop(parser->functions);
3798 ast_function_delete(func);
3799 var->constval.vfunc = NULL;
3802 (void)!parser_leaveblock(parser);
3803 parser->function = old;
3807 static ast_expression *array_accessor_split(
3812 ast_expression *left,
3813 ast_expression *right
3819 lex_ctx ctx = ast_ctx(array);
3821 if (!left || !right) {
3822 if (left) ast_delete(left);
3823 if (right) ast_delete(right);
3827 cmp = ast_binary_new(ctx, INSTR_LT,
3828 (ast_expression*)index,
3829 (ast_expression*)parser_const_float(parser, middle));
3833 parseerror(parser, "internal error: failed to create comparison for array setter");
3837 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3839 ast_delete(cmp); /* will delete left and right */
3840 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3844 return (ast_expression*)ifthen;
3847 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3849 lex_ctx ctx = ast_ctx(array);
3851 if (from+1 == afterend) {
3852 /* set this value */
3855 ast_array_index *subscript;
3857 int assignop = type_store_instr[value->expression.vtype];
3859 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3860 assignop = INSTR_STORE_V;
3862 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3866 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3868 ast_delete(subscript);
3872 block = ast_block_new(ctx);
3878 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3883 ret = ast_return_new(ctx, NULL);
3889 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3894 return (ast_expression*)block;
3896 ast_expression *left, *right;
3897 size_t diff = afterend - from;
3898 size_t middle = from + diff/2;
3899 left = array_setter_node(parser, array, index, value, from, middle);
3900 right = array_setter_node(parser, array, index, value, middle, afterend);
3901 return array_accessor_split(parser, array, index, middle, left, right);
3905 static ast_expression *array_field_setter_node(
3914 lex_ctx ctx = ast_ctx(array);
3916 if (from+1 == afterend) {
3917 /* set this value */
3920 ast_entfield *entfield;
3921 ast_array_index *subscript;
3923 int assignop = type_storep_instr[value->expression.vtype];
3925 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3926 assignop = INSTR_STOREP_V;
3928 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3932 entfield = ast_entfield_new_force(ctx,
3933 (ast_expression*)entity,
3934 (ast_expression*)subscript,
3935 (ast_expression*)subscript);
3937 ast_delete(subscript);
3941 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3943 ast_delete(entfield);
3947 block = ast_block_new(ctx);
3953 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3958 ret = ast_return_new(ctx, NULL);
3964 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3969 return (ast_expression*)block;
3971 ast_expression *left, *right;
3972 size_t diff = afterend - from;
3973 size_t middle = from + diff/2;
3974 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3975 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3976 return array_accessor_split(parser, array, index, middle, left, right);
3980 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3982 lex_ctx ctx = ast_ctx(array);
3984 if (from+1 == afterend) {
3986 ast_array_index *subscript;
3988 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3992 ret = ast_return_new(ctx, (ast_expression*)subscript);
3994 ast_delete(subscript);
3998 return (ast_expression*)ret;
4000 ast_expression *left, *right;
4001 size_t diff = afterend - from;
4002 size_t middle = from + diff/2;
4003 left = array_getter_node(parser, array, index, from, middle);
4004 right = array_getter_node(parser, array, index, middle, afterend);
4005 return array_accessor_split(parser, array, index, middle, left, right);
4009 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4011 ast_function *func = NULL;
4012 ast_value *fval = NULL;
4013 ast_block *body = NULL;
4015 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4017 parseerror(parser, "failed to create accessor function value");
4021 func = ast_function_new(ast_ctx(array), funcname, fval);
4024 parseerror(parser, "failed to create accessor function node");
4028 body = ast_block_new(ast_ctx(array));
4030 parseerror(parser, "failed to create block for array accessor");
4036 vec_push(func->blocks, body);
4039 vec_push(parser->accessors, fval);
4044 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4046 ast_expression *root = NULL;
4047 ast_value *index = NULL;
4048 ast_value *value = NULL;
4052 if (!ast_istype(array->expression.next, ast_value)) {
4053 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4057 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4059 func = fval->constval.vfunc;
4060 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4062 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4063 value = ast_value_copy((ast_value*)array->expression.next);
4065 if (!index || !value) {
4066 parseerror(parser, "failed to create locals for array accessor");
4069 (void)!ast_value_set_name(value, "value"); /* not important */
4070 vec_push(fval->expression.params, index);
4071 vec_push(fval->expression.params, value);
4073 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4075 parseerror(parser, "failed to build accessor search tree");
4079 array->setter = fval;
4080 return ast_block_add_expr(func->blocks[0], root);
4082 if (index) ast_delete(index);
4083 if (value) ast_delete(value);
4084 if (root) ast_delete(root);
4090 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4092 ast_expression *root = NULL;
4093 ast_value *entity = NULL;
4094 ast_value *index = NULL;
4095 ast_value *value = NULL;
4099 if (!ast_istype(array->expression.next, ast_value)) {
4100 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4104 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4106 func = fval->constval.vfunc;
4107 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4109 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4110 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4111 value = ast_value_copy((ast_value*)array->expression.next);
4112 if (!entity || !index || !value) {
4113 parseerror(parser, "failed to create locals for array accessor");
4116 (void)!ast_value_set_name(value, "value"); /* not important */
4117 vec_push(fval->expression.params, entity);
4118 vec_push(fval->expression.params, index);
4119 vec_push(fval->expression.params, value);
4121 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4123 parseerror(parser, "failed to build accessor search tree");
4127 array->setter = fval;
4128 return ast_block_add_expr(func->blocks[0], root);
4130 if (entity) ast_delete(entity);
4131 if (index) ast_delete(index);
4132 if (value) ast_delete(value);
4133 if (root) ast_delete(root);
4139 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4141 ast_expression *root = NULL;
4142 ast_value *index = NULL;
4146 /* NOTE: checking array->expression.next rather than elemtype since
4147 * for fields elemtype is a temporary fieldtype.
4149 if (!ast_istype(array->expression.next, ast_value)) {
4150 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4154 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4156 func = fval->constval.vfunc;
4157 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4159 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4162 parseerror(parser, "failed to create locals for array accessor");
4165 vec_push(fval->expression.params, index);
4167 root = array_getter_node(parser, array, index, 0, array->expression.count);
4169 parseerror(parser, "failed to build accessor search tree");
4173 array->getter = fval;
4174 return ast_block_add_expr(func->blocks[0], root);
4176 if (index) ast_delete(index);
4177 if (root) ast_delete(root);
4183 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4184 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4192 bool variadic = false;
4194 ctx = parser_ctx(parser);
4196 /* for the sake of less code we parse-in in this function */
4197 if (!parser_next(parser)) {
4198 parseerror(parser, "expected parameter list");
4204 /* parse variables until we hit a closing paren */
4205 while (parser->tok != ')') {
4207 /* there must be commas between them */
4208 if (parser->tok != ',') {
4209 parseerror(parser, "expected comma or end of parameter list");
4212 if (!parser_next(parser)) {
4213 parseerror(parser, "expected parameter");
4219 if (parser->tok == TOKEN_DOTS) {
4220 /* '...' indicates a varargs function */
4222 if (!parser_next(parser)) {
4223 parseerror(parser, "expected parameter");
4226 if (parser->tok != ')') {
4227 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4233 /* for anything else just parse a typename */
4234 param = parse_typename(parser, NULL, NULL);
4237 vec_push(params, param);
4238 if (param->expression.vtype >= TYPE_VARIANT) {
4239 char tname[1024]; /* typename is reserved in C++ */
4240 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4241 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4247 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4251 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4252 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4255 if (!parser_next(parser)) {
4256 parseerror(parser, "parse error after typename");
4260 /* now turn 'var' into a function type */
4261 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4262 fval->expression.next = (ast_expression*)var;
4264 fval->expression.flags |= AST_FLAG_VARIADIC;
4267 var->expression.params = params;
4274 for (i = 0; i < vec_size(params); ++i)
4275 ast_delete(params[i]);
4280 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4282 ast_expression *cexp;
4283 ast_value *cval, *tmp;
4286 ctx = parser_ctx(parser);
4288 if (!parser_next(parser)) {
4290 parseerror(parser, "expected array-size");
4294 cexp = parse_expression_leave(parser, true, false, false);
4296 if (!cexp || !ast_istype(cexp, ast_value)) {
4300 parseerror(parser, "expected array-size as constant positive integer");
4303 cval = (ast_value*)cexp;
4305 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4306 tmp->expression.next = (ast_expression*)var;
4309 if (cval->expression.vtype == TYPE_INTEGER)
4310 tmp->expression.count = cval->constval.vint;
4311 else if (cval->expression.vtype == TYPE_FLOAT)
4312 tmp->expression.count = cval->constval.vfloat;
4316 parseerror(parser, "array-size must be a positive integer constant");
4321 if (parser->tok != ']') {
4323 parseerror(parser, "expected ']' after array-size");
4326 if (!parser_next(parser)) {
4328 parseerror(parser, "error after parsing array size");
4334 /* Parse a complete typename.
4335 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4336 * but when parsing variables separated by comma
4337 * 'storebase' should point to where the base-type should be kept.
4338 * The base type makes up every bit of type information which comes *before* the
4341 * The following will be parsed in its entirety:
4343 * The 'basetype' in this case is 'void()'
4344 * and if there's a comma after it, say:
4346 * then the type-information 'void()' can be stored in 'storebase'
4348 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4350 ast_value *var, *tmp;
4353 const char *name = NULL;
4354 bool isfield = false;
4355 bool wasarray = false;
4356 size_t morefields = 0;
4358 ctx = parser_ctx(parser);
4360 /* types may start with a dot */
4361 if (parser->tok == '.') {
4363 /* if we parsed a dot we need a typename now */
4364 if (!parser_next(parser)) {
4365 parseerror(parser, "expected typename for field definition");
4369 /* Further dots are handled seperately because they won't be part of the
4372 while (parser->tok == '.') {
4374 if (!parser_next(parser)) {
4375 parseerror(parser, "expected typename for field definition");
4380 if (parser->tok == TOKEN_IDENT)
4381 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4382 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4383 parseerror(parser, "expected typename");
4387 /* generate the basic type value */
4388 if (cached_typedef) {
4389 var = ast_value_copy(cached_typedef);
4390 ast_value_set_name(var, "<type(from_def)>");
4392 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4394 for (; morefields; --morefields) {
4395 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4396 tmp->expression.next = (ast_expression*)var;
4400 /* do not yet turn into a field - remember:
4401 * .void() foo; is a field too
4402 * .void()() foo; is a function
4406 if (!parser_next(parser)) {
4408 parseerror(parser, "parse error after typename");
4412 /* an opening paren now starts the parameter-list of a function
4413 * this is where original-QC has parameter lists.
4414 * We allow a single parameter list here.
4415 * Much like fteqcc we don't allow `float()() x`
4417 if (parser->tok == '(') {
4418 var = parse_parameter_list(parser, var);
4423 /* store the base if requested */
4425 *storebase = ast_value_copy(var);
4427 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4428 tmp->expression.next = (ast_expression*)*storebase;
4433 /* there may be a name now */
4434 if (parser->tok == TOKEN_IDENT) {
4435 name = util_strdup(parser_tokval(parser));
4437 if (!parser_next(parser)) {
4439 parseerror(parser, "error after variable or field declaration");
4444 /* now this may be an array */
4445 if (parser->tok == '[') {
4447 var = parse_arraysize(parser, var);
4452 /* This is the point where we can turn it into a field */
4454 /* turn it into a field if desired */
4455 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4456 tmp->expression.next = (ast_expression*)var;
4460 /* now there may be function parens again */
4461 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4462 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4463 if (parser->tok == '(' && wasarray)
4464 parseerror(parser, "arrays as part of a return type is not supported");
4465 while (parser->tok == '(') {
4466 var = parse_parameter_list(parser, var);
4475 /* finally name it */
4477 if (!ast_value_set_name(var, name)) {
4479 parseerror(parser, "internal error: failed to set name");
4482 /* free the name, ast_value_set_name duplicates */
4489 static bool parse_typedef(parser_t *parser)
4491 ast_value *typevar, *oldtype;
4492 ast_expression *old;
4494 typevar = parse_typename(parser, NULL, NULL);
4499 if ( (old = parser_find_var(parser, typevar->name)) ) {
4500 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4501 " -> `%s` has been declared here: %s:%i",
4502 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4503 ast_delete(typevar);
4507 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4508 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4509 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4510 ast_delete(typevar);
4514 vec_push(parser->_typedefs, typevar);
4515 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4517 if (parser->tok != ';') {
4518 parseerror(parser, "expected semicolon after typedef");
4521 if (!parser_next(parser)) {
4522 parseerror(parser, "parse error after typedef");
4529 static const char *cvq_to_str(int cvq) {
4531 case CV_NONE: return "none";
4532 case CV_VAR: return "`var`";
4533 case CV_CONST: return "`const`";
4534 default: return "<INVALID>";
4538 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4541 if (proto->cvq != var->cvq) {
4542 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4543 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4544 parser->tok == '='))
4546 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4547 "`%s` declared with different qualifiers: %s\n"
4548 " -> previous declaration here: %s:%i uses %s",
4549 var->name, cvq_to_str(var->cvq),
4550 ast_ctx(proto).file, ast_ctx(proto).line,
4551 cvq_to_str(proto->cvq));
4554 av = (var ->expression.flags & AST_FLAG_NORETURN);
4555 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4557 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4558 "`%s` declared with different attributes%s\n"
4559 " -> previous declaration here: %s:%i",
4560 var->name, (av ? ": noreturn" : ""),
4561 ast_ctx(proto).file, ast_ctx(proto).line,
4562 (ao ? ": noreturn" : ""));
4567 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)
4571 ast_expression *old;
4575 ast_value *basetype = NULL;
4577 bool isparam = false;
4578 bool isvector = false;
4579 bool cleanvar = true;
4580 bool wasarray = false;
4584 if (!localblock && is_static)
4585 parseerror(parser, "`static` qualifier is not supported in global scope");
4587 /* get the first complete variable */
4588 var = parse_typename(parser, &basetype, cached_typedef);
4591 ast_delete(basetype);
4599 /* Part 0: finish the type */
4600 if (parser->tok == '(') {
4601 if (opts.standard == COMPILER_QCC)
4602 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4603 var = parse_parameter_list(parser, var);
4609 /* we only allow 1-dimensional arrays */
4610 if (parser->tok == '[') {
4612 var = parse_arraysize(parser, var);
4618 if (parser->tok == '(' && wasarray) {
4619 parseerror(parser, "arrays as part of a return type is not supported");
4620 /* we'll still parse the type completely for now */
4622 /* for functions returning functions */
4623 while (parser->tok == '(') {
4624 if (opts.standard == COMPILER_QCC)
4625 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4626 var = parse_parameter_list(parser, var);
4633 var->cvq = qualifier;
4634 var->expression.flags |= qflags;
4635 if (var->expression.flags & AST_FLAG_DEPRECATED)
4636 var->desc = vstring;
4639 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4640 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4641 * is then filled with the previous definition and the parameter-names replaced.
4643 if (!strcmp(var->name, "nil")) {
4644 if (OPTS_FLAG(UNTYPED_NIL)) {
4645 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4646 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4648 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4651 /* Deal with end_sys_ vars */
4653 if (!strcmp(var->name, "end_sys_globals")) {
4655 parser->crc_globals = vec_size(parser->globals);
4658 else if (!strcmp(var->name, "end_sys_fields")) {
4660 parser->crc_fields = vec_size(parser->fields);
4663 if (was_end && var->expression.vtype == TYPE_FIELD) {
4664 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4665 "global '%s' hint should not be a field",
4666 parser_tokval(parser)))
4673 if (!nofields && var->expression.vtype == TYPE_FIELD)
4675 /* deal with field declarations */
4676 old = parser_find_field(parser, var->name);
4678 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4679 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4688 parseerror(parser, "field `%s` already declared here: %s:%i",
4689 var->name, ast_ctx(old).file, ast_ctx(old).line);
4694 if (opts.standard == COMPILER_QCC &&
4695 (old = parser_find_global(parser, var->name)))
4697 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4698 parseerror(parser, "field `%s` already declared here: %s:%i",
4699 var->name, ast_ctx(old).file, ast_ctx(old).line);
4706 /* deal with other globals */
4707 old = parser_find_global(parser, var->name);
4708 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4710 /* This is a function which had a prototype */
4711 if (!ast_istype(old, ast_value)) {
4712 parseerror(parser, "internal error: prototype is not an ast_value");
4716 proto = (ast_value*)old;
4717 proto->desc = var->desc;
4718 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4719 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4721 ast_ctx(proto).file, ast_ctx(proto).line);
4725 /* we need the new parameter-names */
4726 for (i = 0; i < vec_size(proto->expression.params); ++i)
4727 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4728 if (!parser_check_qualifiers(parser, var, proto)) {
4735 proto->expression.flags |= var->expression.flags;
4743 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4744 "global `%s` already declared here: %s:%i",
4745 var->name, ast_ctx(old).file, ast_ctx(old).line))
4750 proto = (ast_value*)old;
4751 if (!ast_istype(old, ast_value)) {
4752 parseerror(parser, "internal error: not an ast_value");
4757 if (!parser_check_qualifiers(parser, var, proto)) {
4762 proto->expression.flags |= var->expression.flags;
4766 if (opts.standard == COMPILER_QCC &&
4767 (old = parser_find_field(parser, var->name)))
4769 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4770 parseerror(parser, "global `%s` already declared here: %s:%i",
4771 var->name, ast_ctx(old).file, ast_ctx(old).line);
4778 else /* it's not a global */
4780 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4781 if (old && !isparam) {
4782 parseerror(parser, "local `%s` already declared here: %s:%i",
4783 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4787 old = parser_find_local(parser, var->name, 0, &isparam);
4788 if (old && isparam) {
4789 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4790 "local `%s` is shadowing a parameter", var->name))
4792 parseerror(parser, "local `%s` already declared here: %s:%i",
4793 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4797 if (opts.standard != COMPILER_GMQCC) {
4805 /* in a noref section we simply bump the usecount */
4806 if (noref || parser->noref)
4810 * Create the global/local, and deal with vector types.
4813 if (var->expression.vtype == TYPE_VECTOR)
4815 else if (var->expression.vtype == TYPE_FIELD &&
4816 var->expression.next->expression.vtype == TYPE_VECTOR)
4820 if (!create_vector_members(var, me)) {
4827 /* deal with global variables, fields, functions */
4828 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4829 var->isfield = true;
4830 vec_push(parser->fields, (ast_expression*)var);
4831 util_htset(parser->htfields, var->name, var);
4833 for (i = 0; i < 3; ++i) {
4834 vec_push(parser->fields, (ast_expression*)me[i]);
4835 util_htset(parser->htfields, me[i]->name, me[i]);
4840 parser_addglobal(parser, var->name, (ast_expression*)var);
4842 for (i = 0; i < 3; ++i) {
4843 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
4849 /* a static adds itself to be generated like any other global
4850 * but is added to the local namespace instead
4852 char *defname = NULL;
4853 size_t prefix_len, ln;
4855 ln = strlen(parser->function->name);
4856 vec_append(defname, ln, parser->function->name);
4858 vec_append(defname, 2, "::");
4859 /* remember the length up to here */
4860 prefix_len = vec_size(defname);
4862 /* Add it to the local scope */
4863 util_htset(vec_last(parser->variables), var->name, (void*)var);
4867 vec_last(parser->correct_variables),
4868 &vec_last(parser->correct_variables_score),
4872 /* now rename the global */
4873 ln = strlen(var->name);
4874 vec_append(defname, ln, var->name);
4875 ast_value_set_name(var, defname);
4877 /* push it to the to-be-generated globals */
4878 vec_push(parser->globals, (ast_expression*)var);
4880 /* same game for the vector members */
4882 for (i = 0; i < 3; ++i) {
4883 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4887 vec_last(parser->correct_variables),
4888 &vec_last(parser->correct_variables_score),
4892 vec_shrinkto(defname, prefix_len);
4893 ln = strlen(me[i]->name);
4894 vec_append(defname, ln, me[i]->name);
4895 ast_member_set_name(me[i], defname);
4897 vec_push(parser->globals, (ast_expression*)me[i]);
4902 vec_push(localblock->locals, var);
4903 parser_addlocal(parser, var->name, (ast_expression*)var);
4905 for (i = 0; i < 3; ++i) {
4906 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4907 ast_block_collect(localblock, (ast_expression*)me[i]);
4913 me[0] = me[1] = me[2] = NULL;
4918 if (var->expression.vtype == TYPE_ARRAY) {
4920 snprintf(name, sizeof(name), "%s##SET", var->name);
4921 if (!parser_create_array_setter(parser, var, name))
4923 snprintf(name, sizeof(name), "%s##GET", var->name);
4924 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4927 else if (!localblock && !nofields &&
4928 var->expression.vtype == TYPE_FIELD &&
4929 var->expression.next->expression.vtype == TYPE_ARRAY)
4932 ast_expression *telem;
4934 ast_value *array = (ast_value*)var->expression.next;
4936 if (!ast_istype(var->expression.next, ast_value)) {
4937 parseerror(parser, "internal error: field element type must be an ast_value");
4941 snprintf(name, sizeof(name), "%s##SETF", var->name);
4942 if (!parser_create_array_field_setter(parser, array, name))
4945 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4946 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4947 tfield->expression.next = telem;
4948 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4949 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4957 if (parser->tok == ';') {
4958 ast_delete(basetype);
4959 if (!parser_next(parser)) {
4960 parseerror(parser, "error after variable declaration");
4966 if (parser->tok == ',')
4970 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4973 parseerror(parser, "missing comma or semicolon while parsing variables");
4977 if (localblock && opts.standard == COMPILER_QCC) {
4978 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4979 "initializing expression turns variable `%s` into a constant in this standard",
4986 if (parser->tok != '{') {
4987 if (parser->tok != '=') {
4988 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4992 if (!parser_next(parser)) {
4993 parseerror(parser, "error parsing initializer");
4997 else if (opts.standard == COMPILER_QCC) {
4998 parseerror(parser, "expected '=' before function body in this standard");
5001 if (parser->tok == '#') {
5002 ast_function *func = NULL;
5005 parseerror(parser, "cannot declare builtins within functions");
5008 if (var->expression.vtype != TYPE_FUNCTION) {
5009 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5012 if (!parser_next(parser)) {
5013 parseerror(parser, "expected builtin number");
5016 if (parser->tok != TOKEN_INTCONST) {
5017 parseerror(parser, "builtin number must be an integer constant");
5020 if (parser_token(parser)->constval.i < 0) {
5021 parseerror(parser, "builtin number must be an integer greater than zero");
5025 if (var->hasvalue) {
5026 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5027 "builtin `%s` has already been defined\n"
5028 " -> previous declaration here: %s:%i",
5029 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5033 func = ast_function_new(ast_ctx(var), var->name, var);
5035 parseerror(parser, "failed to allocate function for `%s`", var->name);
5038 vec_push(parser->functions, func);
5040 func->builtin = -parser_token(parser)->constval.i-1;
5043 if (!parser_next(parser)) {
5044 parseerror(parser, "expected comma or semicolon");
5046 ast_function_delete(func);
5047 var->constval.vfunc = NULL;
5051 else if (parser->tok == '{' || parser->tok == '[')
5054 parseerror(parser, "cannot declare functions within functions");
5059 ast_ctx(proto) = parser_ctx(parser);
5061 if (!parse_function_body(parser, var))
5063 ast_delete(basetype);
5064 for (i = 0; i < vec_size(parser->gotos); ++i)
5065 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5066 vec_free(parser->gotos);
5067 vec_free(parser->labels);
5070 ast_expression *cexp;
5073 cexp = parse_expression_leave(parser, true, false, false);
5078 cval = (ast_value*)cexp;
5079 if (cval != parser->nil &&
5080 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5083 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5087 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5088 qualifier != CV_VAR)
5090 var->cvq = CV_CONST;
5092 if (cval == parser->nil)
5093 var->expression.flags |= AST_FLAG_INITIALIZED;
5096 var->hasvalue = true;
5097 if (cval->expression.vtype == TYPE_STRING)
5098 var->constval.vstring = parser_strdup(cval->constval.vstring);
5099 else if (cval->expression.vtype == TYPE_FIELD)
5100 var->constval.vfield = cval;
5102 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5108 shunt sy = { NULL, NULL };
5111 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5112 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5113 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5114 if (!parser_sy_apply_operator(parser, &sy))
5117 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5118 parseerror(parser, "internal error: leaked operands");
5119 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5129 if (parser->tok == ',') {
5130 if (!parser_next(parser)) {
5131 parseerror(parser, "expected another variable");
5135 if (parser->tok != TOKEN_IDENT) {
5136 parseerror(parser, "expected another variable");
5139 var = ast_value_copy(basetype);
5141 ast_value_set_name(var, parser_tokval(parser));
5142 if (!parser_next(parser)) {
5143 parseerror(parser, "error parsing variable declaration");
5149 if (parser->tok != ';') {
5150 parseerror(parser, "missing semicolon after variables");
5154 if (!parser_next(parser)) {
5155 parseerror(parser, "parse error after variable declaration");
5159 ast_delete(basetype);
5163 if (cleanvar && var)
5165 ast_delete(basetype);
5169 ast_delete(basetype);
5170 if (cleanvar && var)
5172 if (me[0]) ast_member_delete(me[0]);
5173 if (me[1]) ast_member_delete(me[1]);
5174 if (me[2]) ast_member_delete(me[2]);
5178 static bool parser_global_statement(parser_t *parser)
5182 bool is_static = false;
5183 uint32_t qflags = 0;
5184 ast_value *istype = NULL;
5185 char *vstring = NULL;
5187 if (parser->tok == TOKEN_IDENT)
5188 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5190 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5192 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5194 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5196 if (cvq == CV_WRONG)
5198 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5200 else if (parser->tok == TOKEN_KEYWORD)
5202 if (!strcmp(parser_tokval(parser), "typedef")) {
5203 if (!parser_next(parser)) {
5204 parseerror(parser, "expected type definition after 'typedef'");
5207 return parse_typedef(parser);
5209 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5212 else if (parser->tok == '#')
5214 return parse_pragma(parser);
5216 else if (parser->tok == '$')
5218 if (!parser_next(parser)) {
5219 parseerror(parser, "parse error");
5225 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5231 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5233 return util_crc16(old, str, strlen(str));
5236 static void progdefs_crc_file(const char *str)
5238 /* write to progdefs.h here */
5242 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5244 old = progdefs_crc_sum(old, str);
5245 progdefs_crc_file(str);
5249 static void generate_checksum(parser_t *parser)
5251 uint16_t crc = 0xFFFF;
5255 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5256 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5258 progdefs_crc_file("\tint\tpad;\n");
5259 progdefs_crc_file("\tint\tofs_return[3];\n");
5260 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5261 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5262 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5263 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5264 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5265 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5266 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5267 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5269 for (i = 0; i < parser->crc_globals; ++i) {
5270 if (!ast_istype(parser->globals[i], ast_value))
5272 value = (ast_value*)(parser->globals[i]);
5273 switch (value->expression.vtype) {
5274 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5275 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5276 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5277 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5279 crc = progdefs_crc_both(crc, "\tint\t");
5282 crc = progdefs_crc_both(crc, value->name);
5283 crc = progdefs_crc_both(crc, ";\n");
5285 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5286 for (i = 0; i < parser->crc_fields; ++i) {
5287 if (!ast_istype(parser->fields[i], ast_value))
5289 value = (ast_value*)(parser->fields[i]);
5290 switch (value->expression.next->expression.vtype) {
5291 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5292 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5293 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5294 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5296 crc = progdefs_crc_both(crc, "\tint\t");
5299 crc = progdefs_crc_both(crc, value->name);
5300 crc = progdefs_crc_both(crc, ";\n");
5302 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5307 static parser_t *parser;
5314 parser = (parser_t*)mem_a(sizeof(parser_t));
5318 memset(parser, 0, sizeof(*parser));
5320 for (i = 0; i < operator_count; ++i) {
5321 if (operators[i].id == opid1('=')) {
5322 parser->assign_op = operators+i;
5326 if (!parser->assign_op) {
5327 printf("internal error: initializing parser: failed to find assign operator\n");
5332 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5333 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5334 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5335 vec_push(parser->_blocktypedefs, 0);
5338 vec_push(parser->correct_variables, correct_trie_new());
5339 vec_push(parser->correct_variables_score, NULL);
5341 empty_ctx.file = "<internal>";
5343 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5344 parser->nil->cvq = CV_CONST;
5345 if (OPTS_FLAG(UNTYPED_NIL))
5346 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5350 bool parser_compile()
5352 /* initial lexer/parser state */
5353 parser->lex->flags.noops = true;
5355 if (parser_next(parser))
5357 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5359 if (!parser_global_statement(parser)) {
5360 if (parser->tok == TOKEN_EOF)
5361 parseerror(parser, "unexpected eof");
5362 else if (compile_errors)
5363 parseerror(parser, "there have been errors, bailing out");
5364 lex_close(parser->lex);
5370 parseerror(parser, "parse error");
5371 lex_close(parser->lex);
5376 lex_close(parser->lex);
5379 return !compile_errors;
5382 bool parser_compile_file(const char *filename)
5384 parser->lex = lex_open(filename);
5386 con_err("failed to open file \"%s\"\n", filename);
5389 return parser_compile();
5392 bool parser_compile_string(const char *name, const char *str, size_t len)
5394 parser->lex = lex_open_string(str, len, name);
5396 con_err("failed to create lexer for string \"%s\"\n", name);
5399 return parser_compile();
5402 void parser_cleanup()
5405 for (i = 0; i < vec_size(parser->accessors); ++i) {
5406 ast_delete(parser->accessors[i]->constval.vfunc);
5407 parser->accessors[i]->constval.vfunc = NULL;
5408 ast_delete(parser->accessors[i]);
5410 for (i = 0; i < vec_size(parser->functions); ++i) {
5411 ast_delete(parser->functions[i]);
5413 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5414 ast_delete(parser->imm_vector[i]);
5416 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5417 ast_delete(parser->imm_string[i]);
5419 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5420 ast_delete(parser->imm_float[i]);
5422 for (i = 0; i < vec_size(parser->fields); ++i) {
5423 ast_delete(parser->fields[i]);
5425 for (i = 0; i < vec_size(parser->globals); ++i) {
5426 ast_delete(parser->globals[i]);
5428 vec_free(parser->accessors);
5429 vec_free(parser->functions);
5430 vec_free(parser->imm_vector);
5431 vec_free(parser->imm_string);
5432 vec_free(parser->imm_float);
5433 vec_free(parser->globals);
5434 vec_free(parser->fields);
5436 for (i = 0; i < vec_size(parser->variables); ++i)
5437 util_htdel(parser->variables[i]);
5438 vec_free(parser->variables);
5439 vec_free(parser->_blocklocals);
5440 vec_free(parser->_locals);
5443 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5444 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5446 vec_free(parser->correct_variables);
5447 vec_free(parser->correct_variables_score);
5450 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5451 ast_delete(parser->_typedefs[i]);
5452 vec_free(parser->_typedefs);
5453 for (i = 0; i < vec_size(parser->typedefs); ++i)
5454 util_htdel(parser->typedefs[i]);
5455 vec_free(parser->typedefs);
5456 vec_free(parser->_blocktypedefs);
5458 vec_free(parser->_block_ctx);
5460 vec_free(parser->labels);
5461 vec_free(parser->gotos);
5462 vec_free(parser->breaks);
5463 vec_free(parser->continues);
5465 ast_value_delete(parser->nil);
5470 bool parser_finish(const char *output)
5476 if (compile_errors) {
5477 con_out("*** there were compile errors\n");
5481 ir = ir_builder_new("gmqcc_out");
5483 con_out("failed to allocate builder\n");
5487 for (i = 0; i < vec_size(parser->fields); ++i) {
5490 if (!ast_istype(parser->fields[i], ast_value))
5492 field = (ast_value*)parser->fields[i];
5493 hasvalue = field->hasvalue;
5494 field->hasvalue = false;
5495 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5496 con_out("failed to generate field %s\n", field->name);
5497 ir_builder_delete(ir);
5502 ast_expression *subtype;
5503 field->hasvalue = true;
5504 subtype = field->expression.next;
5505 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5506 if (subtype->expression.vtype == TYPE_FIELD)
5507 ifld->fieldtype = subtype->expression.next->expression.vtype;
5508 else if (subtype->expression.vtype == TYPE_FUNCTION)
5509 ifld->outtype = subtype->expression.next->expression.vtype;
5510 (void)!ir_value_set_field(field->ir_v, ifld);
5513 for (i = 0; i < vec_size(parser->globals); ++i) {
5515 if (!ast_istype(parser->globals[i], ast_value))
5517 asvalue = (ast_value*)(parser->globals[i]);
5518 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5519 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5520 "unused global: `%s`", asvalue->name);
5522 if (!ast_global_codegen(asvalue, ir, false)) {
5523 con_out("failed to generate global %s\n", asvalue->name);
5524 ir_builder_delete(ir);
5528 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5529 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5530 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5531 ir_builder_delete(ir);
5535 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5536 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5537 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5538 ir_builder_delete(ir);
5542 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5543 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5544 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5545 ir_builder_delete(ir);
5549 for (i = 0; i < vec_size(parser->globals); ++i) {
5551 if (!ast_istype(parser->globals[i], ast_value))
5553 asvalue = (ast_value*)(parser->globals[i]);
5554 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5556 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5557 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5558 "uninitialized constant: `%s`",
5560 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5561 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5562 "uninitialized global: `%s`",
5565 if (!ast_generate_accessors(asvalue, ir)) {
5566 ir_builder_delete(ir);
5570 for (i = 0; i < vec_size(parser->fields); ++i) {
5572 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5574 if (!ast_istype((ast_expression*)asvalue, ast_value))
5576 if (asvalue->expression.vtype != TYPE_ARRAY)
5578 if (!ast_generate_accessors(asvalue, ir)) {
5579 ir_builder_delete(ir);
5583 for (i = 0; i < vec_size(parser->functions); ++i) {
5584 if (!ast_function_codegen(parser->functions[i], ir)) {
5585 con_out("failed to generate function %s\n", parser->functions[i]->name);
5586 ir_builder_delete(ir);
5591 ir_builder_dump(ir, con_out);
5592 for (i = 0; i < vec_size(parser->functions); ++i) {
5593 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5594 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5595 ir_builder_delete(ir);
5600 if (compile_Werrors) {
5601 con_out("*** there were warnings treated as errors\n");
5602 compile_show_werrors();
5608 ir_builder_dump(ir, con_out);
5610 generate_checksum(parser);
5612 if (!ir_builder_generate(ir, output)) {
5613 con_out("*** failed to generate output file\n");
5614 ir_builder_delete(ir);
5619 ir_builder_delete(ir);