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 /* not to be used directly, we use the hash table */
78 ast_expression **_locals;
80 ast_value **_typedefs;
81 size_t *_blocktypedefs;
84 /* we store the '=' operator info */
85 const oper_info *assign_op;
87 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
88 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
89 * anything else: type error
93 /* Keep track of our ternary vs parenthesis nesting state.
94 * If we reach a 'comma' operator in a ternary without a paren,
95 * we shall trigger -Wternary-precedence.
103 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
105 static void parser_enterblock(parser_t *parser);
106 static bool parser_leaveblock(parser_t *parser);
107 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
108 static bool parse_typedef(parser_t *parser);
109 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);
110 static ast_block* parse_block(parser_t *parser);
111 static bool parse_block_into(parser_t *parser, ast_block *block);
112 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
113 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
114 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
115 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
117 static void parseerror(parser_t *parser, const char *fmt, ...)
121 vcompile_error(parser->lex->tok.ctx, fmt, ap);
125 /* returns true if it counts as an error */
126 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
131 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
136 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
141 r = vcompile_warning(ctx, warntype, fmt, ap);
146 /**********************************************************************
147 * some maths used for constant folding
150 vector vec3_add(vector a, vector b)
159 vector vec3_sub(vector a, vector b)
168 qcfloat vec3_mulvv(vector a, vector b)
170 return (a.x * b.x + a.y * b.y + a.z * b.z);
173 vector vec3_mulvf(vector a, float b)
182 /**********************************************************************
186 bool parser_next(parser_t *parser)
188 /* lex_do kills the previous token */
189 parser->tok = lex_do(parser->lex);
190 if (parser->tok == TOKEN_EOF)
192 if (parser->tok >= TOKEN_ERROR) {
193 parseerror(parser, "lex error");
199 #define parser_tokval(p) ((p)->lex->tok.value)
200 #define parser_token(p) (&((p)->lex->tok))
201 #define parser_ctx(p) ((p)->lex->tok.ctx)
203 static ast_value* parser_const_float(parser_t *parser, double d)
207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
208 const double compare = parser->imm_float[i]->constval.vfloat;
209 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
210 return parser->imm_float[i];
212 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
214 out->hasvalue = true;
215 out->constval.vfloat = d;
216 vec_push(parser->imm_float, out);
220 static ast_value* parser_const_float_0(parser_t *parser)
222 if (!parser->imm_float_zero)
223 parser->imm_float_zero = parser_const_float(parser, 0);
224 return parser->imm_float_zero;
227 static ast_value* parser_const_float_1(parser_t *parser)
229 if (!parser->imm_float_one)
230 parser->imm_float_one = parser_const_float(parser, 1);
231 return parser->imm_float_one;
234 static char *parser_strdup(const char *str)
237 /* actually dup empty strings */
238 char *out = (char*)mem_a(1);
242 return util_strdup(str);
245 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
249 for (i = 0; i < vec_size(parser->imm_string); ++i) {
250 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
251 return parser->imm_string[i];
255 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
256 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
258 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
260 out->hasvalue = true;
261 out->constval.vstring = parser_strdup(str);
262 vec_push(parser->imm_string, out);
266 static ast_value* parser_const_vector(parser_t *parser, vector v)
270 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
271 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
272 return parser->imm_vector[i];
274 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
276 out->hasvalue = true;
277 out->constval.vvec = v;
278 vec_push(parser->imm_vector, out);
282 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
288 return parser_const_vector(parser, v);
291 static ast_value* parser_const_vector_0(parser_t *parser)
293 if (!parser->imm_vector_zero)
294 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
295 return parser->imm_vector_zero;
298 static ast_expression* parser_find_field(parser_t *parser, const char *name)
300 return ( ast_expression*)util_htget(parser->htfields, name);
303 static ast_expression* parser_find_label(parser_t *parser, const char *name)
306 for(i = 0; i < vec_size(parser->labels); i++)
307 if (!strcmp(parser->labels[i]->name, name))
308 return (ast_expression*)parser->labels[i];
312 static ast_expression* parser_find_global(parser_t *parser, const char *name)
314 return (ast_expression*)util_htget(parser->htglobals, name);
317 static ast_expression* parser_find_param(parser_t *parser, const char *name)
321 if (!parser->function)
323 fun = parser->function->vtype;
324 for (i = 0; i < vec_size(fun->expression.params); ++i) {
325 if (!strcmp(fun->expression.params[i]->name, name))
326 return (ast_expression*)(fun->expression.params[i]);
331 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
336 hash = util_hthash(parser->htglobals, name);
339 for (i = vec_size(parser->variables); i > upto;) {
341 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
345 return parser_find_param(parser, name);
348 static ast_expression* parser_find_var(parser_t *parser, const char *name)
352 v = parser_find_local(parser, name, 0, &dummy);
353 if (!v) v = parser_find_global(parser, name);
357 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
361 hash = util_hthash(parser->typedefs[0], name);
363 for (i = vec_size(parser->typedefs); i > upto;) {
365 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
373 size_t etype; /* 0 = expression, others are operators */
377 ast_block *block; /* for commas and function calls */
386 #define SY_PAREN_EXPR '('
387 #define SY_PAREN_FUNC 'f'
388 #define SY_PAREN_INDEX '['
389 #define SY_PAREN_TERNARY '?'
391 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
402 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
406 e.out = (ast_expression*)v;
413 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
415 e.etype = 1 + (op - operators);
424 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
436 # define DEBUGSHUNTDO(x) x
438 # define DEBUGSHUNTDO(x)
441 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
442 * so we need to rotate it to become ent.(foo[n]).
444 static bool rotate_entfield_array_index_nodes(ast_expression **out)
446 ast_array_index *index;
447 ast_entfield *entfield;
451 ast_expression *entity;
453 lex_ctx ctx = ast_ctx(*out);
455 if (!ast_istype(*out, ast_array_index))
457 index = (ast_array_index*)*out;
459 if (!ast_istype(index->array, ast_entfield))
461 entfield = (ast_entfield*)index->array;
463 if (!ast_istype(entfield->field, ast_value))
465 field = (ast_value*)entfield->field;
468 entity = entfield->entity;
472 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
473 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
474 *out = (ast_expression*)entfield;
479 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
481 switch (v->expression.vtype) {
483 return !!v->constval.vfloat;
485 return !!v->constval.vint;
487 if (OPTS_FLAG(CORRECT_LOGIC))
488 return v->constval.vvec.x &&
489 v->constval.vvec.y &&
492 return !!(v->constval.vvec.x);
494 if (!v->constval.vstring)
496 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
498 return !!v->constval.vstring[0];
500 compile_error(ctx, "internal error: immediate_is_true on invalid type");
501 return !!v->constval.vfunc;
505 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
509 ast_expression *out = NULL;
510 ast_expression *exprs[3];
511 ast_block *blocks[3];
512 ast_value *asvalue[3];
513 ast_binstore *asbinstore;
514 size_t i, assignop, addop, subop;
515 qcint generated_op = 0;
520 if (!vec_size(sy->ops)) {
521 parseerror(parser, "internal error: missing operator");
525 if (vec_last(sy->ops).paren) {
526 parseerror(parser, "unmatched parenthesis");
530 op = &operators[vec_last(sy->ops).etype - 1];
531 ctx = vec_last(sy->ops).ctx;
533 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
535 if (vec_size(sy->out) < op->operands) {
536 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
537 op->op, (int)op->id);
541 vec_shrinkby(sy->ops, 1);
543 /* op(:?) has no input and no output */
547 vec_shrinkby(sy->out, op->operands);
548 for (i = 0; i < op->operands; ++i) {
549 exprs[i] = sy->out[vec_size(sy->out)+i].out;
550 blocks[i] = sy->out[vec_size(sy->out)+i].block;
551 asvalue[i] = (ast_value*)exprs[i];
553 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
554 !(i != 0 && op->id == opid2('?',':')))
556 if (ast_istype(exprs[i], ast_label))
557 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
559 compile_error(ast_ctx(exprs[i]), "not an expression");
560 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
564 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
565 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
569 #define NotSameType(T) \
570 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
571 exprs[0]->expression.vtype != T)
572 #define CanConstFold1(A) \
573 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
574 (A)->expression.vtype != TYPE_FUNCTION)
575 #define CanConstFold(A, B) \
576 (CanConstFold1(A) && CanConstFold1(B))
577 #define ConstV(i) (asvalue[(i)]->constval.vvec)
578 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
579 #define ConstS(i) (asvalue[(i)]->constval.vstring)
583 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
587 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
588 if (exprs[1]->expression.vtype != TYPE_FIELD) {
589 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
592 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
594 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
595 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
599 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
605 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
606 !(exprs[0]->expression.vtype == TYPE_FIELD &&
607 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
609 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
610 parseerror(parser, "cannot index value of type %s", ty1);
613 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
614 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
615 parseerror(parser, "index must be of type float, not %s", ty1);
618 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
619 if (rotate_entfield_array_index_nodes(&out))
622 /* This is not broken in fteqcc anymore */
623 if (opts.standard != COMPILER_GMQCC) {
624 /* this error doesn't need to make us bail out */
625 (void)!parsewarning(parser, WARN_EXTENSIONS,
626 "accessing array-field members of an entity without parenthesis\n"
627 " -> this is an extension from -std=gmqcc");
635 if (!ast_block_add_expr(blocks[0], exprs[1]))
638 blocks[0] = ast_block_new(ctx);
639 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
640 !ast_block_add_expr(blocks[0], exprs[1]))
645 if (!ast_block_set_type(blocks[0], exprs[1]))
648 vec_push(sy->out, syblock(ctx, blocks[0]));
655 switch (exprs[0]->expression.vtype) {
657 if (CanConstFold1(exprs[0]))
658 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
660 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
661 (ast_expression*)parser_const_float_0(parser),
665 if (CanConstFold1(exprs[0]))
666 out = (ast_expression*)parser_const_vector_f(parser,
667 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
669 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
670 (ast_expression*)parser_const_vector_0(parser),
674 parseerror(parser, "invalid types used in expression: cannot negate type %s",
675 type_name[exprs[0]->expression.vtype]);
681 switch (exprs[0]->expression.vtype) {
683 if (CanConstFold1(exprs[0]))
684 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
686 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
689 if (CanConstFold1(exprs[0]))
690 out = (ast_expression*)parser_const_float(parser,
691 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
693 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
696 if (CanConstFold1(exprs[0])) {
697 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
698 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
700 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
702 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
703 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
705 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
708 /* we don't constant-fold NOT for these types */
710 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
713 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
716 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
717 type_name[exprs[0]->expression.vtype]);
723 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
724 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
726 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
727 type_name[exprs[0]->expression.vtype],
728 type_name[exprs[1]->expression.vtype]);
731 switch (exprs[0]->expression.vtype) {
733 if (CanConstFold(exprs[0], exprs[1]))
735 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
738 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
741 if (CanConstFold(exprs[0], exprs[1]))
742 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
744 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
747 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
748 type_name[exprs[0]->expression.vtype],
749 type_name[exprs[1]->expression.vtype]);
754 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
755 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
757 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
758 type_name[exprs[1]->expression.vtype],
759 type_name[exprs[0]->expression.vtype]);
762 switch (exprs[0]->expression.vtype) {
764 if (CanConstFold(exprs[0], exprs[1]))
765 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
767 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
770 if (CanConstFold(exprs[0], exprs[1]))
771 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
773 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
776 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
777 type_name[exprs[1]->expression.vtype],
778 type_name[exprs[0]->expression.vtype]);
783 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
784 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
785 exprs[1]->expression.vtype == TYPE_FLOAT) &&
786 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
787 exprs[0]->expression.vtype == TYPE_FLOAT)
790 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
791 type_name[exprs[1]->expression.vtype],
792 type_name[exprs[0]->expression.vtype]);
795 switch (exprs[0]->expression.vtype) {
797 if (exprs[1]->expression.vtype == TYPE_VECTOR)
799 if (CanConstFold(exprs[0], exprs[1]))
800 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
802 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
806 if (CanConstFold(exprs[0], exprs[1]))
807 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
809 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
813 if (exprs[1]->expression.vtype == TYPE_FLOAT)
815 if (CanConstFold(exprs[0], exprs[1]))
816 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
818 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
824 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
825 vector vec = ConstV(0);
826 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
827 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
828 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
829 out->expression.node.keep = false;
830 ((ast_member*)out)->rvalue = true;
832 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
834 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
835 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
836 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
837 out->expression.node.keep = false;
838 ((ast_member*)out)->rvalue = true;
840 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
842 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
843 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
844 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
845 out->expression.node.keep = false;
846 ((ast_member*)out)->rvalue = true;
848 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
851 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
853 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
854 vector vec = ConstV(1);
855 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
856 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
857 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
858 out->expression.node.keep = false;
859 ((ast_member*)out)->rvalue = true;
861 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
863 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
864 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
865 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
866 out->expression.node.keep = false;
867 ((ast_member*)out)->rvalue = true;
869 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
871 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
872 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
873 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
874 out->expression.node.keep = false;
875 ((ast_member*)out)->rvalue = true;
877 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
880 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
883 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
887 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
888 type_name[exprs[1]->expression.vtype],
889 type_name[exprs[0]->expression.vtype]);
894 if (NotSameType(TYPE_FLOAT)) {
895 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
896 type_name[exprs[0]->expression.vtype],
897 type_name[exprs[1]->expression.vtype]);
900 if (CanConstFold(exprs[0], exprs[1]))
901 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
903 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
907 parseerror(parser, "qc does not have a modulo operator");
911 if (NotSameType(TYPE_FLOAT)) {
912 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
913 type_name[exprs[0]->expression.vtype],
914 type_name[exprs[1]->expression.vtype]);
917 if (CanConstFold(exprs[0], exprs[1]))
918 out = (ast_expression*)parser_const_float(parser,
919 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
920 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
922 out = (ast_expression*)ast_binary_new(ctx,
923 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
927 parseerror(parser, "TODO: bitxor");
932 case opid3('<','<','='):
933 case opid3('>','>','='):
934 parseerror(parser, "TODO: shifts");
938 generated_op += 1; /* INSTR_OR */
940 generated_op += INSTR_AND;
942 if (NotSameType(TYPE_FLOAT)) {
943 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
944 type_name[exprs[0]->expression.vtype],
945 type_name[exprs[1]->expression.vtype]);
946 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
947 parseerror(parser, "TODO: optional early out");
951 if (CanConstFold(exprs[0], exprs[1]))
953 if (OPTS_FLAG(PERL_LOGIC)) {
954 if (immediate_is_true(ctx, asvalue[0]))
958 out = (ast_expression*)parser_const_float(parser,
959 ( (generated_op == INSTR_OR)
960 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
961 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
966 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
967 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
968 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
969 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
972 for (i = 0; i < 2; ++i) {
973 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
974 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
976 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
978 exprs[i] = out; out = NULL;
979 if (OPTS_FLAG(PERL_LOGIC)) {
980 /* here we want to keep the right expressions' type */
984 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
985 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
987 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
989 exprs[i] = out; out = NULL;
990 if (OPTS_FLAG(PERL_LOGIC)) {
991 /* here we want to keep the right expressions' type */
996 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1000 case opid2('?',':'):
1001 if (vec_last(parser->pot) != POT_TERNARY2) {
1002 parseerror(parser, "mismatched parenthesis/ternary");
1005 vec_pop(parser->pot);
1006 if (!ast_compare_type(exprs[1], exprs[2])) {
1007 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1008 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1009 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1012 if (CanConstFold1(exprs[0]))
1013 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1015 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1019 generated_op += 1; /* INSTR_GT */
1021 generated_op += 1; /* INSTR_LT */
1022 case opid2('>', '='):
1023 generated_op += 1; /* INSTR_GE */
1024 case opid2('<', '='):
1025 generated_op += INSTR_LE;
1026 if (NotSameType(TYPE_FLOAT)) {
1027 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1028 type_name[exprs[0]->expression.vtype],
1029 type_name[exprs[1]->expression.vtype]);
1032 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1034 case opid2('!', '='):
1035 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1036 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1037 type_name[exprs[0]->expression.vtype],
1038 type_name[exprs[1]->expression.vtype]);
1041 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1043 case opid2('=', '='):
1044 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1045 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1046 type_name[exprs[0]->expression.vtype],
1047 type_name[exprs[1]->expression.vtype]);
1050 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1054 if (ast_istype(exprs[0], ast_entfield)) {
1055 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1056 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1057 exprs[0]->expression.vtype == TYPE_FIELD &&
1058 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1060 assignop = type_storep_instr[TYPE_VECTOR];
1063 assignop = type_storep_instr[exprs[0]->expression.vtype];
1064 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1066 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1067 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1068 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1069 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1070 exprs[1]->expression.vtype == TYPE_FUNCTION)
1072 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1073 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1076 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1081 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1082 exprs[0]->expression.vtype == TYPE_FIELD &&
1083 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1085 assignop = type_store_instr[TYPE_VECTOR];
1088 assignop = type_store_instr[exprs[0]->expression.vtype];
1091 if (assignop == AINSTR_END) {
1092 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1094 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1096 else if (!ast_compare_type(exprs[0], exprs[1]))
1098 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1099 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1100 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1101 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1102 exprs[1]->expression.vtype == TYPE_FUNCTION)
1104 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1105 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1108 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1111 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1112 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1114 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1116 case opid3('+','+','P'):
1117 case opid3('-','-','P'):
1119 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1120 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1121 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1124 if (op->id == opid3('+','+','P'))
1125 addop = INSTR_ADD_F;
1127 addop = INSTR_SUB_F;
1128 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1129 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1131 if (ast_istype(exprs[0], ast_entfield)) {
1132 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1134 (ast_expression*)parser_const_float_1(parser));
1136 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1138 (ast_expression*)parser_const_float_1(parser));
1141 case opid3('S','+','+'):
1142 case opid3('S','-','-'):
1144 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1145 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1146 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1149 if (op->id == opid3('S','+','+')) {
1150 addop = INSTR_ADD_F;
1151 subop = INSTR_SUB_F;
1153 addop = INSTR_SUB_F;
1154 subop = INSTR_ADD_F;
1156 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1157 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1159 if (ast_istype(exprs[0], ast_entfield)) {
1160 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1162 (ast_expression*)parser_const_float_1(parser));
1164 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1166 (ast_expression*)parser_const_float_1(parser));
1170 out = (ast_expression*)ast_binary_new(ctx, subop,
1172 (ast_expression*)parser_const_float_1(parser));
1174 case opid2('+','='):
1175 case opid2('-','='):
1176 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1177 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1179 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1180 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1181 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1185 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1186 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1188 if (ast_istype(exprs[0], ast_entfield))
1189 assignop = type_storep_instr[exprs[0]->expression.vtype];
1191 assignop = type_store_instr[exprs[0]->expression.vtype];
1192 switch (exprs[0]->expression.vtype) {
1194 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1195 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1196 exprs[0], exprs[1]);
1199 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1200 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1201 exprs[0], exprs[1]);
1204 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1205 type_name[exprs[0]->expression.vtype],
1206 type_name[exprs[1]->expression.vtype]);
1210 case opid2('*','='):
1211 case opid2('/','='):
1212 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1213 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1214 exprs[0]->expression.vtype == TYPE_VECTOR))
1216 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1217 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1218 parseerror(parser, "invalid types used in expression: %s and %s",
1222 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1223 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1225 if (ast_istype(exprs[0], ast_entfield))
1226 assignop = type_storep_instr[exprs[0]->expression.vtype];
1228 assignop = type_store_instr[exprs[0]->expression.vtype];
1229 switch (exprs[0]->expression.vtype) {
1231 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1232 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1233 exprs[0], exprs[1]);
1236 if (op->id == opid2('*','=')) {
1237 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1238 exprs[0], exprs[1]);
1240 /* there's no DIV_VF */
1241 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1242 (ast_expression*)parser_const_float_1(parser),
1246 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1251 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1252 type_name[exprs[0]->expression.vtype],
1253 type_name[exprs[1]->expression.vtype]);
1257 case opid2('&','='):
1258 case opid2('|','='):
1259 if (NotSameType(TYPE_FLOAT)) {
1260 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1261 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1262 parseerror(parser, "invalid types used in expression: %s and %s",
1266 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1267 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1269 if (ast_istype(exprs[0], ast_entfield))
1270 assignop = type_storep_instr[exprs[0]->expression.vtype];
1272 assignop = type_store_instr[exprs[0]->expression.vtype];
1273 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1274 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1275 exprs[0], exprs[1]);
1277 case opid3('&','~','='):
1278 /* This is like: a &= ~(b);
1279 * But QC has no bitwise-not, so we implement it as
1282 if (NotSameType(TYPE_FLOAT)) {
1283 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1284 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1285 parseerror(parser, "invalid types used in expression: %s and %s",
1289 if (ast_istype(exprs[0], ast_entfield))
1290 assignop = type_storep_instr[exprs[0]->expression.vtype];
1292 assignop = type_store_instr[exprs[0]->expression.vtype];
1293 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1296 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1297 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1299 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1300 asbinstore->keep_dest = true;
1301 out = (ast_expression*)asbinstore;
1307 parseerror(parser, "failed to apply operand %s", op->op);
1311 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1312 vec_push(sy->out, syexp(ctx, out));
1316 static bool parser_close_call(parser_t *parser, shunt *sy)
1318 /* was a function call */
1319 ast_expression *fun;
1325 vec_shrinkby(sy->ops, 1);
1326 fid = sy->ops[vec_size(sy->ops)].off;
1328 /* out[fid] is the function
1329 * everything above is parameters...
1330 * 0 params = nothing
1331 * 1 params = ast_expression
1335 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1336 parseerror(parser, "internal error: function call needs function and parameter list...");
1340 fun = sy->out[fid].out;
1342 if (fun == intrinsic_debug_typestring) {
1344 if (fid+2 != vec_size(sy->out) ||
1345 vec_last(sy->out).block)
1347 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1350 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1351 ast_unref(vec_last(sy->out).out);
1352 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1353 (ast_expression*)parser_const_string(parser, ty, false));
1354 vec_shrinkby(sy->out, 1);
1358 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1360 parseerror(parser, "internal error: failed to create ast_call node");
1364 if (fid+1 == vec_size(sy->out)) {
1367 } else if (fid+2 == vec_size(sy->out)) {
1369 vec_shrinkby(sy->out, 1);
1370 params = sy->out[vec_size(sy->out)].block;
1374 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1376 paramcount = vec_size(params->exprs);
1377 call->params = params->exprs;
1378 params->exprs = NULL;
1381 (void)!ast_call_check_types(call);
1383 parseerror(parser, "invalid function call");
1387 /* overwrite fid, the function, with a call */
1388 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1390 if (fun->expression.vtype != TYPE_FUNCTION) {
1391 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1395 if (!fun->expression.next) {
1396 parseerror(parser, "could not determine function return type");
1399 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1401 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1403 return !parsewarning(parser, WARN_DEPRECATED,
1404 "call to function (which is marked deprecated)\n",
1405 "-> it has been declared here: %s:%i",
1406 ast_ctx(fun).file, ast_ctx(fun).line);
1409 return !parsewarning(parser, WARN_DEPRECATED,
1410 "call to `%s` (which is marked deprecated)\n"
1411 "-> `%s` declared here: %s:%i",
1412 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1414 return !parsewarning(parser, WARN_DEPRECATED,
1415 "call to `%s` (deprecated: %s)\n"
1416 "-> `%s` declared here: %s:%i",
1417 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1421 if (vec_size(fun->expression.params) != paramcount &&
1422 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1423 vec_size(fun->expression.params) < paramcount))
1425 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1427 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1428 "too %s parameters for call to %s: expected %i, got %i\n"
1429 " -> `%s` has been declared here: %s:%i",
1430 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1431 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1433 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1434 "too %s parameters for function call: expected %i, got %i\n"
1435 " -> it has been declared here: %s:%i",
1436 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1437 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1444 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1446 if (!vec_size(sy->ops)) {
1447 parseerror(parser, "unmatched closing paren");
1450 /* this would for bit a + (x) because there are no operators inside (x)
1451 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1452 parseerror(parser, "empty parenthesis expression");
1456 while (vec_size(sy->ops)) {
1457 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1458 if (!parser_close_call(parser, sy))
1462 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1463 vec_shrinkby(sy->ops, 1);
1464 return !functions_only;
1466 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1469 /* pop off the parenthesis */
1470 vec_shrinkby(sy->ops, 1);
1471 /* then apply the index operator */
1472 if (!parser_sy_apply_operator(parser, sy))
1476 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1479 if (vec_last(parser->pot) != POT_TERNARY1) {
1480 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1483 vec_last(parser->pot) = POT_TERNARY2;
1484 /* pop off the parenthesis */
1485 vec_shrinkby(sy->ops, 1);
1488 if (!parser_sy_apply_operator(parser, sy))
1494 static void parser_reclassify_token(parser_t *parser)
1497 for (i = 0; i < operator_count; ++i) {
1498 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1499 parser->tok = TOKEN_OPERATOR;
1505 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1507 ast_expression *expr = NULL;
1509 bool wantop = false;
1510 bool gotmemberof = false;
1511 /* only warn once about an assignment in a truth value because the current code
1512 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1514 bool warn_truthvalue = true;
1516 /* count the parens because an if starts with one, so the
1517 * end of a condition is an unmatched closing paren
1525 parser->lex->flags.noops = false;
1527 parser_reclassify_token(parser);
1532 gotmemberof = false;
1534 parser->memberof = 0;
1536 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1537 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1539 /* a translatable string */
1543 parseerror(parser, "expected operator or end of statement, got constant");
1547 parser->lex->flags.noops = true;
1548 if (!parser_next(parser) || parser->tok != '(') {
1549 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1552 parser->lex->flags.noops = false;
1553 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1554 parseerror(parser, "expected a constant string in translatable-string extension");
1557 val = parser_const_string(parser, parser_tokval(parser), true);
1561 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1562 DEBUGSHUNTDO(con_out("push string\n"));
1564 if (!parser_next(parser) || parser->tok != ')') {
1565 parseerror(parser, "expected closing paren after translatable string");
1569 else if (parser->tok == TOKEN_IDENT)
1571 ast_expression *var;
1573 parseerror(parser, "expected operator or end of statement");
1578 if (opts.standard == COMPILER_GMQCC)
1580 if (parser->memberof == TYPE_ENTITY) {
1581 /* still get vars first since there could be a fieldpointer */
1582 var = parser_find_var(parser, parser_tokval(parser));
1584 var = parser_find_field(parser, parser_tokval(parser));
1586 else if (parser->memberof == TYPE_VECTOR)
1588 parseerror(parser, "TODO: implement effective vector member access");
1591 else if (parser->memberof) {
1592 parseerror(parser, "namespace for member not found");
1596 var = parser_find_var(parser, parser_tokval(parser));
1598 var = parser_find_var(parser, parser_tokval(parser));
1600 var = parser_find_field(parser, parser_tokval(parser));
1602 if (!var && with_labels) {
1603 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1605 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1606 var = (ast_expression*)lbl;
1607 vec_push(parser->labels, lbl);
1612 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1613 var = (ast_expression*)intrinsic_debug_typestring;
1618 * sometimes people use preprocessing predefs without enabling them
1619 * i've done this thousands of times already myself. Lets check for
1620 * it in the predef table. And diagnose it better :)
1622 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1624 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1625 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1626 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1632 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1638 if (ast_istype(var, ast_value)) {
1639 ((ast_value*)var)->uses++;
1641 else if (ast_istype(var, ast_member)) {
1642 ast_member *mem = (ast_member*)var;
1643 if (ast_istype(mem->owner, ast_value))
1644 ((ast_value*)(mem->owner))->uses++;
1647 vec_push(sy.out, syexp(parser_ctx(parser), var));
1648 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1650 else if (parser->tok == TOKEN_FLOATCONST) {
1653 parseerror(parser, "expected operator or end of statement, got constant");
1657 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1660 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1661 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1663 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1666 parseerror(parser, "expected operator or end of statement, got constant");
1670 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1673 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1674 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1676 else if (parser->tok == TOKEN_STRINGCONST) {
1679 parseerror(parser, "expected operator or end of statement, got constant");
1683 val = parser_const_string(parser, parser_tokval(parser), false);
1686 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1687 DEBUGSHUNTDO(con_out("push string\n"));
1689 else if (parser->tok == TOKEN_VECTORCONST) {
1692 parseerror(parser, "expected operator or end of statement, got constant");
1696 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1699 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1700 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1701 parser_token(parser)->constval.v.x,
1702 parser_token(parser)->constval.v.y,
1703 parser_token(parser)->constval.v.z));
1705 else if (parser->tok == '(') {
1706 parseerror(parser, "internal error: '(' should be classified as operator");
1709 else if (parser->tok == '[') {
1710 parseerror(parser, "internal error: '[' should be classified as operator");
1713 else if (parser->tok == ')') {
1715 DEBUGSHUNTDO(con_out("do[op] )\n"));
1719 /* we do expect an operator next */
1720 /* closing an opening paren */
1721 if (!parser_close_paren(parser, &sy, false))
1723 if (vec_last(parser->pot) != POT_PAREN) {
1724 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1727 vec_pop(parser->pot);
1729 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1733 /* allowed for function calls */
1734 if (!parser_close_paren(parser, &sy, true))
1736 if (vec_last(parser->pot) != POT_PAREN) {
1737 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1740 vec_pop(parser->pot);
1744 else if (parser->tok == ']') {
1746 parseerror(parser, "operand expected");
1750 if (!parser_close_paren(parser, &sy, false))
1752 if (vec_last(parser->pot) != POT_PAREN) {
1753 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1756 vec_pop(parser->pot);
1759 else if (parser->tok == TOKEN_TYPENAME) {
1760 parseerror(parser, "unexpected typename");
1763 else if (parser->tok != TOKEN_OPERATOR) {
1765 parseerror(parser, "expected operator or end of statement");
1772 /* classify the operator */
1773 const oper_info *op;
1774 const oper_info *olast = NULL;
1776 for (o = 0; o < operator_count; ++o) {
1777 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1778 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1779 !strcmp(parser_tokval(parser), operators[o].op))
1784 if (o == operator_count) {
1785 /* no operator found... must be the end of the statement */
1788 /* found an operator */
1791 /* when declaring variables, a comma starts a new variable */
1792 if (op->id == opid1(',') && !parens && stopatcomma) {
1793 /* fixup the token */
1798 /* a colon without a pervious question mark cannot be a ternary */
1799 if (!ternaries && op->id == opid2(':','?')) {
1804 if (op->id == opid1(',')) {
1805 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1806 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1810 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1811 olast = &operators[vec_last(sy.ops).etype-1];
1813 #define IsAssignOp(x) (\
1814 (x) == opid1('=') || \
1815 (x) == opid2('+','=') || \
1816 (x) == opid2('-','=') || \
1817 (x) == opid2('*','=') || \
1818 (x) == opid2('/','=') || \
1819 (x) == opid2('%','=') || \
1820 (x) == opid2('&','=') || \
1821 (x) == opid2('|','=') || \
1822 (x) == opid3('&','~','=') \
1824 if (warn_truthvalue) {
1825 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1826 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1827 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1830 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1831 warn_truthvalue = false;
1836 (op->prec < olast->prec) ||
1837 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1839 if (!parser_sy_apply_operator(parser, &sy))
1841 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1842 olast = &operators[vec_last(sy.ops).etype-1];
1847 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1848 /* for gmqcc standard: open up the namespace of the previous type */
1849 ast_expression *prevex = vec_last(sy.out).out;
1851 parseerror(parser, "unexpected member operator");
1854 if (prevex->expression.vtype == TYPE_ENTITY)
1855 parser->memberof = TYPE_ENTITY;
1856 else if (prevex->expression.vtype == TYPE_VECTOR)
1857 parser->memberof = TYPE_VECTOR;
1859 parseerror(parser, "type error: type has no members");
1865 if (op->id == opid1('(')) {
1867 size_t sycount = vec_size(sy.out);
1868 DEBUGSHUNTDO(con_out("push [op] (\n"));
1869 ++parens; vec_push(parser->pot, POT_PAREN);
1870 /* we expected an operator, this is the function-call operator */
1871 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1873 ++parens; vec_push(parser->pot, POT_PAREN);
1874 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1875 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1878 } else if (op->id == opid1('[')) {
1880 parseerror(parser, "unexpected array subscript");
1883 ++parens; vec_push(parser->pot, POT_PAREN);
1884 /* push both the operator and the paren, this makes life easier */
1885 vec_push(sy.ops, syop(parser_ctx(parser), op));
1886 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1888 } else if (op->id == opid2('?',':')) {
1889 vec_push(sy.ops, syop(parser_ctx(parser), op));
1890 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1893 vec_push(parser->pot, POT_TERNARY1);
1894 } else if (op->id == opid2(':','?')) {
1895 if (!vec_size(parser->pot)) {
1896 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1899 if (vec_last(parser->pot) != POT_TERNARY1) {
1900 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1903 if (!parser_close_paren(parser, &sy, false))
1905 vec_push(sy.ops, syop(parser_ctx(parser), op));
1909 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1910 vec_push(sy.ops, syop(parser_ctx(parser), op));
1911 wantop = !!(op->flags & OP_SUFFIX);
1914 if (!parser_next(parser)) {
1917 if (parser->tok == ';' ||
1918 (!parens && parser->tok == ']'))
1924 while (vec_size(sy.ops)) {
1925 if (!parser_sy_apply_operator(parser, &sy))
1929 parser->lex->flags.noops = true;
1930 if (!vec_size(sy.out)) {
1931 parseerror(parser, "empty expression");
1934 expr = sy.out[0].out;
1937 DEBUGSHUNTDO(con_out("shunt done\n"));
1938 if (vec_size(parser->pot)) {
1939 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1942 vec_free(parser->pot);
1946 parser->lex->flags.noops = true;
1952 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1954 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1957 if (!parser_next(parser)) {
1964 static void parser_enterblock(parser_t *parser)
1966 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1967 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1968 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1969 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1970 vec_push(parser->_block_ctx, parser_ctx(parser));
1973 static bool parser_leaveblock(parser_t *parser)
1976 size_t locals, typedefs;
1978 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1979 parseerror(parser, "internal error: parser_leaveblock with no block");
1983 util_htdel(vec_last(parser->variables));
1984 vec_pop(parser->variables);
1985 if (!vec_size(parser->_blocklocals)) {
1986 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1990 locals = vec_last(parser->_blocklocals);
1991 vec_pop(parser->_blocklocals);
1992 while (vec_size(parser->_locals) != locals) {
1993 ast_expression *e = vec_last(parser->_locals);
1994 ast_value *v = (ast_value*)e;
1995 vec_pop(parser->_locals);
1996 if (ast_istype(e, ast_value) && !v->uses) {
1997 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2002 typedefs = vec_last(parser->_blocktypedefs);
2003 while (vec_size(parser->_typedefs) != typedefs) {
2004 ast_delete(vec_last(parser->_typedefs));
2005 vec_pop(parser->_typedefs);
2007 util_htdel(vec_last(parser->typedefs));
2008 vec_pop(parser->typedefs);
2010 vec_pop(parser->_block_ctx);
2014 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2016 vec_push(parser->_locals, e);
2017 util_htset(vec_last(parser->variables), name, (void*)e);
2020 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2024 ast_expression *prev;
2026 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2029 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2032 parseerror(parser, "internal error: failed to process condition");
2037 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2039 /* vector types need to be cast to true booleans */
2040 ast_binary *bin = (ast_binary*)cond;
2041 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2043 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2045 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2048 parseerror(parser, "internal error: failed to process condition");
2055 unary = (ast_unary*)cond;
2056 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2058 cond = unary->operand;
2059 unary->operand = NULL;
2062 unary = (ast_unary*)cond;
2066 parseerror(parser, "internal error: failed to process condition");
2068 if (ifnot) *_ifnot = !*_ifnot;
2072 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2075 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2078 lex_ctx ctx = parser_ctx(parser);
2080 (void)block; /* not touching */
2082 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2083 if (!parser_next(parser)) {
2084 parseerror(parser, "expected condition or 'not'");
2087 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2089 if (!parser_next(parser)) {
2090 parseerror(parser, "expected condition in parenthesis");
2094 if (parser->tok != '(') {
2095 parseerror(parser, "expected 'if' condition in parenthesis");
2098 /* parse into the expression */
2099 if (!parser_next(parser)) {
2100 parseerror(parser, "expected 'if' condition after opening paren");
2103 /* parse the condition */
2104 cond = parse_expression_leave(parser, false, true, false);
2108 if (parser->tok != ')') {
2109 parseerror(parser, "expected closing paren after 'if' condition");
2113 /* parse into the 'then' branch */
2114 if (!parser_next(parser)) {
2115 parseerror(parser, "expected statement for on-true branch of 'if'");
2119 if (!parse_statement_or_block(parser, &ontrue)) {
2123 /* check for an else */
2124 if (!strcmp(parser_tokval(parser), "else")) {
2125 /* parse into the 'else' branch */
2126 if (!parser_next(parser)) {
2127 parseerror(parser, "expected on-false branch after 'else'");
2132 if (!parse_statement_or_block(parser, &onfalse)) {
2139 cond = process_condition(parser, cond, &ifnot);
2141 if (ontrue) ast_delete(ontrue);
2142 if (onfalse) ast_delete(onfalse);
2147 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2149 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2150 *out = (ast_expression*)ifthen;
2154 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2155 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2160 /* skip the 'while' and get the body */
2161 if (!parser_next(parser)) {
2162 if (OPTS_FLAG(LOOP_LABELS))
2163 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2165 parseerror(parser, "expected 'while' condition in parenthesis");
2169 if (parser->tok == ':') {
2170 if (!OPTS_FLAG(LOOP_LABELS))
2171 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2172 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2173 parseerror(parser, "expected loop label");
2176 label = util_strdup(parser_tokval(parser));
2177 if (!parser_next(parser)) {
2179 parseerror(parser, "expected 'while' condition in parenthesis");
2184 if (parser->tok != '(') {
2185 parseerror(parser, "expected 'while' condition in parenthesis");
2189 vec_push(parser->breaks, label);
2190 vec_push(parser->continues, label);
2192 rv = parse_while_go(parser, block, out);
2195 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2196 parseerror(parser, "internal error: label stack corrupted");
2202 vec_pop(parser->breaks);
2203 vec_pop(parser->continues);
2208 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2211 ast_expression *cond, *ontrue;
2215 lex_ctx ctx = parser_ctx(parser);
2217 (void)block; /* not touching */
2219 /* parse into the expression */
2220 if (!parser_next(parser)) {
2221 parseerror(parser, "expected 'while' condition after opening paren");
2224 /* parse the condition */
2225 cond = parse_expression_leave(parser, false, true, false);
2229 if (parser->tok != ')') {
2230 parseerror(parser, "expected closing paren after 'while' condition");
2234 /* parse into the 'then' branch */
2235 if (!parser_next(parser)) {
2236 parseerror(parser, "expected while-loop body");
2240 if (!parse_statement_or_block(parser, &ontrue)) {
2245 cond = process_condition(parser, cond, &ifnot);
2250 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2251 *out = (ast_expression*)aloop;
2255 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2256 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2261 /* skip the 'do' and get the body */
2262 if (!parser_next(parser)) {
2263 if (OPTS_FLAG(LOOP_LABELS))
2264 parseerror(parser, "expected loop label or body");
2266 parseerror(parser, "expected loop body");
2270 if (parser->tok == ':') {
2271 if (!OPTS_FLAG(LOOP_LABELS))
2272 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2273 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2274 parseerror(parser, "expected loop label");
2277 label = util_strdup(parser_tokval(parser));
2278 if (!parser_next(parser)) {
2280 parseerror(parser, "expected loop body");
2285 vec_push(parser->breaks, label);
2286 vec_push(parser->continues, label);
2288 rv = parse_dowhile_go(parser, block, out);
2291 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2292 parseerror(parser, "internal error: label stack corrupted");
2298 vec_pop(parser->breaks);
2299 vec_pop(parser->continues);
2304 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2307 ast_expression *cond, *ontrue;
2311 lex_ctx ctx = parser_ctx(parser);
2313 (void)block; /* not touching */
2315 if (!parse_statement_or_block(parser, &ontrue))
2318 /* expect the "while" */
2319 if (parser->tok != TOKEN_KEYWORD ||
2320 strcmp(parser_tokval(parser), "while"))
2322 parseerror(parser, "expected 'while' and condition");
2327 /* skip the 'while' and check for opening paren */
2328 if (!parser_next(parser) || parser->tok != '(') {
2329 parseerror(parser, "expected 'while' condition in parenthesis");
2333 /* parse into the expression */
2334 if (!parser_next(parser)) {
2335 parseerror(parser, "expected 'while' condition after opening paren");
2339 /* parse the condition */
2340 cond = parse_expression_leave(parser, false, true, false);
2344 if (parser->tok != ')') {
2345 parseerror(parser, "expected closing paren after 'while' condition");
2351 if (!parser_next(parser) || parser->tok != ';') {
2352 parseerror(parser, "expected semicolon after condition");
2358 if (!parser_next(parser)) {
2359 parseerror(parser, "parse error");
2365 cond = process_condition(parser, cond, &ifnot);
2370 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2371 *out = (ast_expression*)aloop;
2375 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2376 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2381 /* skip the 'for' and check for opening paren */
2382 if (!parser_next(parser)) {
2383 if (OPTS_FLAG(LOOP_LABELS))
2384 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2386 parseerror(parser, "expected 'for' expressions in parenthesis");
2390 if (parser->tok == ':') {
2391 if (!OPTS_FLAG(LOOP_LABELS))
2392 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2393 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2394 parseerror(parser, "expected loop label");
2397 label = util_strdup(parser_tokval(parser));
2398 if (!parser_next(parser)) {
2400 parseerror(parser, "expected 'for' expressions in parenthesis");
2405 if (parser->tok != '(') {
2406 parseerror(parser, "expected 'for' expressions in parenthesis");
2410 vec_push(parser->breaks, label);
2411 vec_push(parser->continues, label);
2413 rv = parse_for_go(parser, block, out);
2416 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2417 parseerror(parser, "internal error: label stack corrupted");
2423 vec_pop(parser->breaks);
2424 vec_pop(parser->continues);
2428 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2431 ast_expression *initexpr, *cond, *increment, *ontrue;
2437 lex_ctx ctx = parser_ctx(parser);
2439 parser_enterblock(parser);
2446 /* parse into the expression */
2447 if (!parser_next(parser)) {
2448 parseerror(parser, "expected 'for' initializer after opening paren");
2453 if (parser->tok == TOKEN_IDENT)
2454 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2456 if (typevar || parser->tok == TOKEN_TYPENAME) {
2458 if (opts.standard != COMPILER_GMQCC) {
2459 if (parsewarning(parser, WARN_EXTENSIONS,
2460 "current standard does not allow variable declarations in for-loop initializers"))
2464 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2467 else if (parser->tok != ';')
2469 initexpr = parse_expression_leave(parser, false, false, false);
2474 /* move on to condition */
2475 if (parser->tok != ';') {
2476 parseerror(parser, "expected semicolon after for-loop initializer");
2479 if (!parser_next(parser)) {
2480 parseerror(parser, "expected for-loop condition");
2484 /* parse the condition */
2485 if (parser->tok != ';') {
2486 cond = parse_expression_leave(parser, false, true, false);
2491 /* move on to incrementor */
2492 if (parser->tok != ';') {
2493 parseerror(parser, "expected semicolon after for-loop initializer");
2496 if (!parser_next(parser)) {
2497 parseerror(parser, "expected for-loop condition");
2501 /* parse the incrementor */
2502 if (parser->tok != ')') {
2503 increment = parse_expression_leave(parser, false, false, false);
2506 if (!ast_side_effects(increment)) {
2507 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2513 if (parser->tok != ')') {
2514 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2517 /* parse into the 'then' branch */
2518 if (!parser_next(parser)) {
2519 parseerror(parser, "expected for-loop body");
2522 if (!parse_statement_or_block(parser, &ontrue))
2526 cond = process_condition(parser, cond, &ifnot);
2530 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2531 *out = (ast_expression*)aloop;
2533 if (!parser_leaveblock(parser))
2537 if (initexpr) ast_delete(initexpr);
2538 if (cond) ast_delete(cond);
2539 if (increment) ast_delete(increment);
2540 (void)!parser_leaveblock(parser);
2544 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2546 ast_expression *exp = NULL;
2547 ast_return *ret = NULL;
2548 ast_value *expected = parser->function->vtype;
2550 lex_ctx ctx = parser_ctx(parser);
2552 (void)block; /* not touching */
2554 if (!parser_next(parser)) {
2555 parseerror(parser, "expected return expression");
2559 if (parser->tok != ';') {
2560 exp = parse_expression(parser, false, false);
2564 if (exp->expression.vtype != TYPE_NIL &&
2565 exp->expression.vtype != expected->expression.next->expression.vtype)
2567 parseerror(parser, "return with invalid expression");
2570 ret = ast_return_new(ctx, exp);
2576 if (!parser_next(parser))
2577 parseerror(parser, "parse error");
2578 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2579 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2581 ret = ast_return_new(ctx, NULL);
2583 *out = (ast_expression*)ret;
2587 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2590 unsigned int levels = 0;
2591 lex_ctx ctx = parser_ctx(parser);
2592 const char **loops = (is_continue ? parser->continues : parser->breaks);
2594 (void)block; /* not touching */
2595 if (!parser_next(parser)) {
2596 parseerror(parser, "expected semicolon or loop label");
2600 if (parser->tok == TOKEN_IDENT) {
2601 if (!OPTS_FLAG(LOOP_LABELS))
2602 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2603 i = vec_size(loops);
2605 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2608 parseerror(parser, "no such loop to %s: `%s`",
2609 (is_continue ? "continue" : "break out of"),
2610 parser_tokval(parser));
2615 if (!parser_next(parser)) {
2616 parseerror(parser, "expected semicolon");
2621 if (parser->tok != ';') {
2622 parseerror(parser, "expected semicolon");
2626 if (!parser_next(parser))
2627 parseerror(parser, "parse error");
2629 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2633 /* returns true when it was a variable qualifier, false otherwise!
2634 * on error, cvq is set to CV_WRONG
2636 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2638 bool had_const = false;
2639 bool had_var = false;
2640 bool had_noref = false;
2641 bool had_attrib = false;
2642 bool had_static = false;
2647 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2649 /* parse an attribute */
2650 if (!parser_next(parser)) {
2651 parseerror(parser, "expected attribute after `[[`");
2655 if (!strcmp(parser_tokval(parser), "noreturn")) {
2656 flags |= AST_FLAG_NORETURN;
2657 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2658 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2663 else if (!strcmp(parser_tokval(parser), "noref")) {
2665 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2666 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2671 else if (!strcmp(parser_tokval(parser), "inline")) {
2672 flags |= AST_FLAG_INLINE;
2673 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2674 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2681 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2682 flags |= AST_FLAG_DEPRECATED;
2685 if (!parser_next(parser)) {
2686 parseerror(parser, "parse error in attribute");
2690 if (parser->tok == '(') {
2691 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2692 parseerror(parser, "`deprecated` attribute missing parameter");
2696 *message = util_strdup(parser_tokval(parser));
2698 if (!parser_next(parser)) {
2699 parseerror(parser, "parse error in attribute");
2703 if(parser->tok != ')') {
2704 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2708 if (!parser_next(parser)) {
2709 parseerror(parser, "parse error in attribute");
2714 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2715 parseerror(parser, "`deprecated` attribute expected `]]`");
2718 if (*message) mem_d(*message);
2726 /* Skip tokens until we hit a ]] */
2727 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2728 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2729 if (!parser_next(parser)) {
2730 parseerror(parser, "error inside attribute");
2737 else if (!strcmp(parser_tokval(parser), "static"))
2739 else if (!strcmp(parser_tokval(parser), "const"))
2741 else if (!strcmp(parser_tokval(parser), "var"))
2743 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2745 else if (!strcmp(parser_tokval(parser), "noref"))
2747 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2752 if (!parser_next(parser))
2762 *is_static = had_static;
2766 parseerror(parser, "parse error after variable qualifier");
2771 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2772 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2777 /* skip the 'while' and get the body */
2778 if (!parser_next(parser)) {
2779 if (OPTS_FLAG(LOOP_LABELS))
2780 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2782 parseerror(parser, "expected 'switch' operand in parenthesis");
2786 if (parser->tok == ':') {
2787 if (!OPTS_FLAG(LOOP_LABELS))
2788 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2789 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2790 parseerror(parser, "expected loop label");
2793 label = util_strdup(parser_tokval(parser));
2794 if (!parser_next(parser)) {
2796 parseerror(parser, "expected 'switch' operand in parenthesis");
2801 if (parser->tok != '(') {
2802 parseerror(parser, "expected 'switch' operand in parenthesis");
2806 vec_push(parser->breaks, label);
2808 rv = parse_switch_go(parser, block, out);
2811 if (vec_last(parser->breaks) != label) {
2812 parseerror(parser, "internal error: label stack corrupted");
2818 vec_pop(parser->breaks);
2823 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2825 ast_expression *operand;
2828 ast_switch *switchnode;
2829 ast_switch_case swcase;
2832 bool noref, is_static;
2833 uint32_t qflags = 0;
2835 lex_ctx ctx = parser_ctx(parser);
2837 (void)block; /* not touching */
2840 /* parse into the expression */
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "expected switch operand");
2845 /* parse the operand */
2846 operand = parse_expression_leave(parser, false, false, false);
2850 switchnode = ast_switch_new(ctx, operand);
2853 if (parser->tok != ')') {
2854 ast_delete(switchnode);
2855 parseerror(parser, "expected closing paren after 'switch' operand");
2859 /* parse over the opening paren */
2860 if (!parser_next(parser) || parser->tok != '{') {
2861 ast_delete(switchnode);
2862 parseerror(parser, "expected list of cases");
2866 if (!parser_next(parser)) {
2867 ast_delete(switchnode);
2868 parseerror(parser, "expected 'case' or 'default'");
2872 /* new block; allow some variables to be declared here */
2873 parser_enterblock(parser);
2876 if (parser->tok == TOKEN_IDENT)
2877 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2878 if (typevar || parser->tok == TOKEN_TYPENAME) {
2879 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2880 ast_delete(switchnode);
2885 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2887 if (cvq == CV_WRONG) {
2888 ast_delete(switchnode);
2891 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2892 ast_delete(switchnode);
2901 while (parser->tok != '}') {
2902 ast_block *caseblock;
2904 if (!strcmp(parser_tokval(parser), "case")) {
2905 if (!parser_next(parser)) {
2906 ast_delete(switchnode);
2907 parseerror(parser, "expected expression for case");
2910 swcase.value = parse_expression_leave(parser, false, false, false);
2911 if (!swcase.value) {
2912 ast_delete(switchnode);
2913 parseerror(parser, "expected expression for case");
2916 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2917 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2918 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2924 else if (!strcmp(parser_tokval(parser), "default")) {
2925 swcase.value = NULL;
2926 if (!parser_next(parser)) {
2927 ast_delete(switchnode);
2928 parseerror(parser, "expected colon");
2933 ast_delete(switchnode);
2934 parseerror(parser, "expected 'case' or 'default'");
2938 /* Now the colon and body */
2939 if (parser->tok != ':') {
2940 if (swcase.value) ast_unref(swcase.value);
2941 ast_delete(switchnode);
2942 parseerror(parser, "expected colon");
2946 if (!parser_next(parser)) {
2947 if (swcase.value) ast_unref(swcase.value);
2948 ast_delete(switchnode);
2949 parseerror(parser, "expected statements or case");
2952 caseblock = ast_block_new(parser_ctx(parser));
2954 if (swcase.value) ast_unref(swcase.value);
2955 ast_delete(switchnode);
2958 swcase.code = (ast_expression*)caseblock;
2959 vec_push(switchnode->cases, swcase);
2961 ast_expression *expr;
2962 if (parser->tok == '}')
2964 if (parser->tok == TOKEN_KEYWORD) {
2965 if (!strcmp(parser_tokval(parser), "case") ||
2966 !strcmp(parser_tokval(parser), "default"))
2971 if (!parse_statement(parser, caseblock, &expr, true)) {
2972 ast_delete(switchnode);
2977 if (!ast_block_add_expr(caseblock, expr)) {
2978 ast_delete(switchnode);
2984 parser_leaveblock(parser);
2987 if (parser->tok != '}') {
2988 ast_delete(switchnode);
2989 parseerror(parser, "expected closing paren of case list");
2992 if (!parser_next(parser)) {
2993 ast_delete(switchnode);
2994 parseerror(parser, "parse error after switch");
2997 *out = (ast_expression*)switchnode;
3001 /* parse computed goto sides */
3002 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression *side) {
3003 ast_expression *on_true;
3004 ast_expression *on_false;
3009 if (ast_istype(side, ast_ternary)) {
3010 on_true = parse_goto_computed(parser, ((ast_ternary*)side)->on_true);
3011 on_false = parse_goto_computed(parser, ((ast_ternary*)side)->on_false);
3013 if (!on_true || !on_false) {
3014 parseerror(parser, "expected label or expression in ternary");
3015 if (((ast_ternary*)side)->on_false) ast_unref(((ast_ternary*)side)->on_false);
3016 if (((ast_ternary*)side)->on_true) ast_unref(((ast_ternary*)side)->on_true);
3020 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), ((ast_ternary*)side)->cond, on_true, on_false);
3021 } else if (ast_istype(side, ast_label)) {
3022 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)side)->name);
3023 ast_goto_set_label(gt, ((ast_label*)side));
3024 return (ast_expression*)gt;
3029 static bool parse_goto(parser_t *parser, ast_expression **out)
3031 ast_goto *gt = NULL;
3032 ast_expression *lbl;
3034 if (!parser_next(parser))
3037 if (parser->tok != TOKEN_IDENT) {
3038 ast_expression *expression;
3040 /* could be an expression i.e computed goto :-) */
3041 if (parser->tok != '(') {
3042 parseerror(parser, "expected label name after `goto`");
3046 /* failed to parse expression for goto */
3047 if (!(expression = parse_expression(parser, false, true)) ||
3048 !(*out = parse_goto_computed(parser, expression))) {
3049 parseerror(parser, "invalid goto expression");
3050 ast_unref(expression);
3057 /* not computed goto */
3058 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3059 lbl = parser_find_label(parser, gt->name);
3061 if (!ast_istype(lbl, ast_label)) {
3062 parseerror(parser, "internal error: label is not an ast_label");
3066 ast_goto_set_label(gt, (ast_label*)lbl);
3069 vec_push(parser->gotos, gt);
3071 if (!parser_next(parser) || parser->tok != ';') {
3072 parseerror(parser, "semicolon expected after goto label");
3075 if (!parser_next(parser)) {
3076 parseerror(parser, "parse error after goto");
3080 *out = (ast_expression*)gt;
3084 static bool parse_skipwhite(parser_t *parser)
3087 if (!parser_next(parser))
3089 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3090 return parser->tok < TOKEN_ERROR;
3093 static bool parse_eol(parser_t *parser)
3095 if (!parse_skipwhite(parser))
3097 return parser->tok == TOKEN_EOL;
3100 static bool parse_pragma_do(parser_t *parser)
3102 if (!parser_next(parser) ||
3103 parser->tok != TOKEN_IDENT ||
3104 strcmp(parser_tokval(parser), "pragma"))
3106 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3109 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3110 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3114 if (!strcmp(parser_tokval(parser), "noref")) {
3115 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3116 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3119 parser->noref = !!parser_token(parser)->constval.i;
3120 if (!parse_eol(parser)) {
3121 parseerror(parser, "parse error after `noref` pragma");
3127 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3134 static bool parse_pragma(parser_t *parser)
3137 parser->lex->flags.preprocessing = true;
3138 parser->lex->flags.mergelines = true;
3139 rv = parse_pragma_do(parser);
3140 if (parser->tok != TOKEN_EOL) {
3141 parseerror(parser, "junk after pragma");
3144 parser->lex->flags.preprocessing = false;
3145 parser->lex->flags.mergelines = false;
3146 if (!parser_next(parser)) {
3147 parseerror(parser, "parse error after pragma");
3153 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3155 bool noref, is_static;
3157 uint32_t qflags = 0;
3158 ast_value *typevar = NULL;
3159 char *vstring = NULL;
3163 if (parser->tok == TOKEN_IDENT)
3164 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3166 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3168 /* local variable */
3170 parseerror(parser, "cannot declare a variable from here");
3173 if (opts.standard == COMPILER_QCC) {
3174 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3177 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3181 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3183 if (cvq == CV_WRONG)
3185 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3187 else if (parser->tok == TOKEN_KEYWORD)
3189 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3194 if (!parser_next(parser)) {
3195 parseerror(parser, "parse error after __builtin_debug_printtype");
3199 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3201 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3202 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3203 if (!parser_next(parser)) {
3204 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3210 if (!parse_statement(parser, block, out, allow_cases))
3213 con_out("__builtin_debug_printtype: got no output node\n");
3216 ast_type_to_string(*out, ty, sizeof(ty));
3217 con_out("__builtin_debug_printtype: `%s`\n", ty);
3222 else if (!strcmp(parser_tokval(parser), "return"))
3224 return parse_return(parser, block, out);
3226 else if (!strcmp(parser_tokval(parser), "if"))
3228 return parse_if(parser, block, out);
3230 else if (!strcmp(parser_tokval(parser), "while"))
3232 return parse_while(parser, block, out);
3234 else if (!strcmp(parser_tokval(parser), "do"))
3236 return parse_dowhile(parser, block, out);
3238 else if (!strcmp(parser_tokval(parser), "for"))
3240 if (opts.standard == COMPILER_QCC) {
3241 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3244 return parse_for(parser, block, out);
3246 else if (!strcmp(parser_tokval(parser), "break"))
3248 return parse_break_continue(parser, block, out, false);
3250 else if (!strcmp(parser_tokval(parser), "continue"))
3252 return parse_break_continue(parser, block, out, true);
3254 else if (!strcmp(parser_tokval(parser), "switch"))
3256 return parse_switch(parser, block, out);
3258 else if (!strcmp(parser_tokval(parser), "case") ||
3259 !strcmp(parser_tokval(parser), "default"))
3262 parseerror(parser, "unexpected 'case' label");
3267 else if (!strcmp(parser_tokval(parser), "goto"))
3269 return parse_goto(parser, out);
3271 else if (!strcmp(parser_tokval(parser), "typedef"))
3273 if (!parser_next(parser)) {
3274 parseerror(parser, "expected type definition after 'typedef'");
3277 return parse_typedef(parser);
3279 parseerror(parser, "Unexpected keyword");
3282 else if (parser->tok == '{')
3285 inner = parse_block(parser);
3288 *out = (ast_expression*)inner;
3291 else if (parser->tok == ':')
3295 if (!parser_next(parser)) {
3296 parseerror(parser, "expected label name");
3299 if (parser->tok != TOKEN_IDENT) {
3300 parseerror(parser, "label must be an identifier");
3303 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3305 if (!label->undefined) {
3306 parseerror(parser, "label `%s` already defined", label->name);
3309 label->undefined = false;
3312 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3313 vec_push(parser->labels, label);
3315 *out = (ast_expression*)label;
3316 if (!parser_next(parser)) {
3317 parseerror(parser, "parse error after label");
3320 for (i = 0; i < vec_size(parser->gotos); ++i) {
3321 if (!strcmp(parser->gotos[i]->name, label->name)) {
3322 ast_goto_set_label(parser->gotos[i], label);
3323 vec_remove(parser->gotos, i, 1);
3329 else if (parser->tok == ';')
3331 if (!parser_next(parser)) {
3332 parseerror(parser, "parse error after empty statement");
3339 ast_expression *exp = parse_expression(parser, false, false);
3343 if (!ast_side_effects(exp)) {
3344 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3351 static bool parse_block_into(parser_t *parser, ast_block *block)
3355 parser_enterblock(parser);
3357 if (!parser_next(parser)) { /* skip the '{' */
3358 parseerror(parser, "expected function body");
3362 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3364 ast_expression *expr = NULL;
3365 if (parser->tok == '}')
3368 if (!parse_statement(parser, block, &expr, false)) {
3369 /* parseerror(parser, "parse error"); */
3375 if (!ast_block_add_expr(block, expr)) {
3382 if (parser->tok != '}') {
3385 (void)parser_next(parser);
3389 if (!parser_leaveblock(parser))
3391 return retval && !!block;
3394 static ast_block* parse_block(parser_t *parser)
3397 block = ast_block_new(parser_ctx(parser));
3400 if (!parse_block_into(parser, block)) {
3401 ast_block_delete(block);
3407 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3409 if (parser->tok == '{') {
3410 *out = (ast_expression*)parse_block(parser);
3413 return parse_statement(parser, NULL, out, false);
3416 static bool create_vector_members(ast_value *var, ast_member **me)
3419 size_t len = strlen(var->name);
3421 for (i = 0; i < 3; ++i) {
3422 char *name = (char*)mem_a(len+3);
3423 memcpy(name, var->name, len);
3425 name[len+1] = 'x'+i;
3427 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3436 do { ast_member_delete(me[--i]); } while(i);
3440 static bool parse_function_body(parser_t *parser, ast_value *var)
3442 ast_block *block = NULL;
3447 ast_expression *framenum = NULL;
3448 ast_expression *nextthink = NULL;
3449 /* None of the following have to be deleted */
3450 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3451 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3452 bool has_frame_think;
3456 has_frame_think = false;
3457 old = parser->function;
3459 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3460 parseerror(parser, "gotos/labels leaking");
3464 if (var->expression.flags & AST_FLAG_VARIADIC) {
3465 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3466 "variadic function with implementation will not be able to access additional parameters"))
3472 if (parser->tok == '[') {
3473 /* got a frame definition: [ framenum, nextthink ]
3474 * this translates to:
3475 * self.frame = framenum;
3476 * self.nextthink = time + 0.1;
3477 * self.think = nextthink;
3481 fld_think = parser_find_field(parser, "think");
3482 fld_nextthink = parser_find_field(parser, "nextthink");
3483 fld_frame = parser_find_field(parser, "frame");
3484 if (!fld_think || !fld_nextthink || !fld_frame) {
3485 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3486 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3489 gbl_time = parser_find_global(parser, "time");
3490 gbl_self = parser_find_global(parser, "self");
3491 if (!gbl_time || !gbl_self) {
3492 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3493 parseerror(parser, "please declare the following globals: `time`, `self`");
3497 if (!parser_next(parser))
3500 framenum = parse_expression_leave(parser, true, false, false);
3502 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3505 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3506 ast_unref(framenum);
3507 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3511 if (parser->tok != ',') {
3512 ast_unref(framenum);
3513 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3514 parseerror(parser, "Got a %i\n", parser->tok);
3518 if (!parser_next(parser)) {
3519 ast_unref(framenum);
3523 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3525 /* qc allows the use of not-yet-declared functions here
3526 * - this automatically creates a prototype */
3527 ast_value *thinkfunc;
3528 ast_expression *functype = fld_think->expression.next;
3530 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3531 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3532 ast_unref(framenum);
3533 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3537 if (!parser_next(parser)) {
3538 ast_unref(framenum);
3539 ast_delete(thinkfunc);
3543 vec_push(parser->globals, (ast_expression*)thinkfunc);
3544 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3545 nextthink = (ast_expression*)thinkfunc;
3548 nextthink = parse_expression_leave(parser, true, false, false);
3550 ast_unref(framenum);
3551 parseerror(parser, "expected a think-function in [frame,think] notation");
3556 if (!ast_istype(nextthink, ast_value)) {
3557 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3561 if (retval && parser->tok != ']') {
3562 parseerror(parser, "expected closing `]` for [frame,think] notation");
3566 if (retval && !parser_next(parser)) {
3570 if (retval && parser->tok != '{') {
3571 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3576 ast_unref(nextthink);
3577 ast_unref(framenum);
3581 has_frame_think = true;
3584 block = ast_block_new(parser_ctx(parser));
3586 parseerror(parser, "failed to allocate block");
3587 if (has_frame_think) {
3588 ast_unref(nextthink);
3589 ast_unref(framenum);
3594 if (has_frame_think) {
3596 ast_expression *self_frame;
3597 ast_expression *self_nextthink;
3598 ast_expression *self_think;
3599 ast_expression *time_plus_1;
3600 ast_store *store_frame;
3601 ast_store *store_nextthink;
3602 ast_store *store_think;
3604 ctx = parser_ctx(parser);
3605 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3606 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3607 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3609 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3610 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3612 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3613 if (self_frame) ast_delete(self_frame);
3614 if (self_nextthink) ast_delete(self_nextthink);
3615 if (self_think) ast_delete(self_think);
3616 if (time_plus_1) ast_delete(time_plus_1);
3622 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3623 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3624 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3627 ast_delete(self_frame);
3630 if (!store_nextthink) {
3631 ast_delete(self_nextthink);
3635 ast_delete(self_think);
3639 if (store_frame) ast_delete(store_frame);
3640 if (store_nextthink) ast_delete(store_nextthink);
3641 if (store_think) ast_delete(store_think);
3644 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3645 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3646 !ast_block_add_expr(block, (ast_expression*)store_think))
3653 parseerror(parser, "failed to generate code for [frame,think]");
3654 ast_unref(nextthink);
3655 ast_unref(framenum);
3661 parser_enterblock(parser);
3663 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3665 ast_value *param = var->expression.params[parami];
3668 if (param->expression.vtype != TYPE_VECTOR &&
3669 (param->expression.vtype != TYPE_FIELD ||
3670 param->expression.next->expression.vtype != TYPE_VECTOR))
3675 if (!create_vector_members(param, me)) {
3676 ast_block_delete(block);
3680 for (e = 0; e < 3; ++e) {
3681 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3682 ast_block_collect(block, (ast_expression*)me[e]);
3686 func = ast_function_new(ast_ctx(var), var->name, var);
3688 parseerror(parser, "failed to allocate function for `%s`", var->name);
3689 ast_block_delete(block);
3692 vec_push(parser->functions, func);
3694 parser->function = func;
3695 if (!parse_block_into(parser, block)) {
3696 ast_block_delete(block);
3700 vec_push(func->blocks, block);
3702 parser->function = old;
3703 if (!parser_leaveblock(parser))
3705 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3706 parseerror(parser, "internal error: local scopes left");
3710 if (parser->tok == ';')
3711 return parser_next(parser);
3712 else if (opts.standard == COMPILER_QCC)
3713 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3717 vec_pop(parser->functions);
3718 ast_function_delete(func);
3719 var->constval.vfunc = NULL;
3722 (void)!parser_leaveblock(parser);
3723 parser->function = old;
3727 static ast_expression *array_accessor_split(
3732 ast_expression *left,
3733 ast_expression *right
3739 lex_ctx ctx = ast_ctx(array);
3741 if (!left || !right) {
3742 if (left) ast_delete(left);
3743 if (right) ast_delete(right);
3747 cmp = ast_binary_new(ctx, INSTR_LT,
3748 (ast_expression*)index,
3749 (ast_expression*)parser_const_float(parser, middle));
3753 parseerror(parser, "internal error: failed to create comparison for array setter");
3757 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3759 ast_delete(cmp); /* will delete left and right */
3760 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3764 return (ast_expression*)ifthen;
3767 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3769 lex_ctx ctx = ast_ctx(array);
3771 if (from+1 == afterend) {
3772 /* set this value */
3775 ast_array_index *subscript;
3777 int assignop = type_store_instr[value->expression.vtype];
3779 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3780 assignop = INSTR_STORE_V;
3782 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3786 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3788 ast_delete(subscript);
3792 block = ast_block_new(ctx);
3798 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3803 ret = ast_return_new(ctx, NULL);
3809 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3814 return (ast_expression*)block;
3816 ast_expression *left, *right;
3817 size_t diff = afterend - from;
3818 size_t middle = from + diff/2;
3819 left = array_setter_node(parser, array, index, value, from, middle);
3820 right = array_setter_node(parser, array, index, value, middle, afterend);
3821 return array_accessor_split(parser, array, index, middle, left, right);
3825 static ast_expression *array_field_setter_node(
3834 lex_ctx ctx = ast_ctx(array);
3836 if (from+1 == afterend) {
3837 /* set this value */
3840 ast_entfield *entfield;
3841 ast_array_index *subscript;
3843 int assignop = type_storep_instr[value->expression.vtype];
3845 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3846 assignop = INSTR_STOREP_V;
3848 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3852 entfield = ast_entfield_new_force(ctx,
3853 (ast_expression*)entity,
3854 (ast_expression*)subscript,
3855 (ast_expression*)subscript);
3857 ast_delete(subscript);
3861 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3863 ast_delete(entfield);
3867 block = ast_block_new(ctx);
3873 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3878 ret = ast_return_new(ctx, NULL);
3884 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3889 return (ast_expression*)block;
3891 ast_expression *left, *right;
3892 size_t diff = afterend - from;
3893 size_t middle = from + diff/2;
3894 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3895 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3896 return array_accessor_split(parser, array, index, middle, left, right);
3900 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3902 lex_ctx ctx = ast_ctx(array);
3904 if (from+1 == afterend) {
3906 ast_array_index *subscript;
3908 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3912 ret = ast_return_new(ctx, (ast_expression*)subscript);
3914 ast_delete(subscript);
3918 return (ast_expression*)ret;
3920 ast_expression *left, *right;
3921 size_t diff = afterend - from;
3922 size_t middle = from + diff/2;
3923 left = array_getter_node(parser, array, index, from, middle);
3924 right = array_getter_node(parser, array, index, middle, afterend);
3925 return array_accessor_split(parser, array, index, middle, left, right);
3929 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3931 ast_function *func = NULL;
3932 ast_value *fval = NULL;
3933 ast_block *body = NULL;
3935 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3937 parseerror(parser, "failed to create accessor function value");
3941 func = ast_function_new(ast_ctx(array), funcname, fval);
3944 parseerror(parser, "failed to create accessor function node");
3948 body = ast_block_new(ast_ctx(array));
3950 parseerror(parser, "failed to create block for array accessor");
3956 vec_push(func->blocks, body);
3959 vec_push(parser->accessors, fval);
3964 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3966 ast_expression *root = NULL;
3967 ast_value *index = NULL;
3968 ast_value *value = NULL;
3972 if (!ast_istype(array->expression.next, ast_value)) {
3973 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3977 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3979 func = fval->constval.vfunc;
3980 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3982 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3983 value = ast_value_copy((ast_value*)array->expression.next);
3985 if (!index || !value) {
3986 parseerror(parser, "failed to create locals for array accessor");
3989 (void)!ast_value_set_name(value, "value"); /* not important */
3990 vec_push(fval->expression.params, index);
3991 vec_push(fval->expression.params, value);
3993 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3995 parseerror(parser, "failed to build accessor search tree");
3999 array->setter = fval;
4000 return ast_block_add_expr(func->blocks[0], root);
4002 if (index) ast_delete(index);
4003 if (value) ast_delete(value);
4004 if (root) ast_delete(root);
4010 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4012 ast_expression *root = NULL;
4013 ast_value *entity = NULL;
4014 ast_value *index = NULL;
4015 ast_value *value = NULL;
4019 if (!ast_istype(array->expression.next, ast_value)) {
4020 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4024 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4026 func = fval->constval.vfunc;
4027 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4029 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4030 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4031 value = ast_value_copy((ast_value*)array->expression.next);
4032 if (!entity || !index || !value) {
4033 parseerror(parser, "failed to create locals for array accessor");
4036 (void)!ast_value_set_name(value, "value"); /* not important */
4037 vec_push(fval->expression.params, entity);
4038 vec_push(fval->expression.params, index);
4039 vec_push(fval->expression.params, value);
4041 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4043 parseerror(parser, "failed to build accessor search tree");
4047 array->setter = fval;
4048 return ast_block_add_expr(func->blocks[0], root);
4050 if (entity) ast_delete(entity);
4051 if (index) ast_delete(index);
4052 if (value) ast_delete(value);
4053 if (root) ast_delete(root);
4059 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4061 ast_expression *root = NULL;
4062 ast_value *index = NULL;
4066 /* NOTE: checking array->expression.next rather than elemtype since
4067 * for fields elemtype is a temporary fieldtype.
4069 if (!ast_istype(array->expression.next, ast_value)) {
4070 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4074 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4076 func = fval->constval.vfunc;
4077 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4079 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4082 parseerror(parser, "failed to create locals for array accessor");
4085 vec_push(fval->expression.params, index);
4087 root = array_getter_node(parser, array, index, 0, array->expression.count);
4089 parseerror(parser, "failed to build accessor search tree");
4093 array->getter = fval;
4094 return ast_block_add_expr(func->blocks[0], root);
4096 if (index) ast_delete(index);
4097 if (root) ast_delete(root);
4103 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4104 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4112 bool variadic = false;
4114 ctx = parser_ctx(parser);
4116 /* for the sake of less code we parse-in in this function */
4117 if (!parser_next(parser)) {
4118 parseerror(parser, "expected parameter list");
4124 /* parse variables until we hit a closing paren */
4125 while (parser->tok != ')') {
4127 /* there must be commas between them */
4128 if (parser->tok != ',') {
4129 parseerror(parser, "expected comma or end of parameter list");
4132 if (!parser_next(parser)) {
4133 parseerror(parser, "expected parameter");
4139 if (parser->tok == TOKEN_DOTS) {
4140 /* '...' indicates a varargs function */
4142 if (!parser_next(parser)) {
4143 parseerror(parser, "expected parameter");
4146 if (parser->tok != ')') {
4147 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4153 /* for anything else just parse a typename */
4154 param = parse_typename(parser, NULL, NULL);
4157 vec_push(params, param);
4158 if (param->expression.vtype >= TYPE_VARIANT) {
4159 char tname[1024]; /* typename is reserved in C++ */
4160 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4161 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4167 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4171 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4172 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4175 if (!parser_next(parser)) {
4176 parseerror(parser, "parse error after typename");
4180 /* now turn 'var' into a function type */
4181 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4182 fval->expression.next = (ast_expression*)var;
4184 fval->expression.flags |= AST_FLAG_VARIADIC;
4187 var->expression.params = params;
4194 for (i = 0; i < vec_size(params); ++i)
4195 ast_delete(params[i]);
4200 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4202 ast_expression *cexp;
4203 ast_value *cval, *tmp;
4206 ctx = parser_ctx(parser);
4208 if (!parser_next(parser)) {
4210 parseerror(parser, "expected array-size");
4214 cexp = parse_expression_leave(parser, true, false, false);
4216 if (!cexp || !ast_istype(cexp, ast_value)) {
4220 parseerror(parser, "expected array-size as constant positive integer");
4223 cval = (ast_value*)cexp;
4225 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4226 tmp->expression.next = (ast_expression*)var;
4229 if (cval->expression.vtype == TYPE_INTEGER)
4230 tmp->expression.count = cval->constval.vint;
4231 else if (cval->expression.vtype == TYPE_FLOAT)
4232 tmp->expression.count = cval->constval.vfloat;
4236 parseerror(parser, "array-size must be a positive integer constant");
4241 if (parser->tok != ']') {
4243 parseerror(parser, "expected ']' after array-size");
4246 if (!parser_next(parser)) {
4248 parseerror(parser, "error after parsing array size");
4254 /* Parse a complete typename.
4255 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4256 * but when parsing variables separated by comma
4257 * 'storebase' should point to where the base-type should be kept.
4258 * The base type makes up every bit of type information which comes *before* the
4261 * The following will be parsed in its entirety:
4263 * The 'basetype' in this case is 'void()'
4264 * and if there's a comma after it, say:
4266 * then the type-information 'void()' can be stored in 'storebase'
4268 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4270 ast_value *var, *tmp;
4273 const char *name = NULL;
4274 bool isfield = false;
4275 bool wasarray = false;
4276 size_t morefields = 0;
4278 ctx = parser_ctx(parser);
4280 /* types may start with a dot */
4281 if (parser->tok == '.') {
4283 /* if we parsed a dot we need a typename now */
4284 if (!parser_next(parser)) {
4285 parseerror(parser, "expected typename for field definition");
4289 /* Further dots are handled seperately because they won't be part of the
4292 while (parser->tok == '.') {
4294 if (!parser_next(parser)) {
4295 parseerror(parser, "expected typename for field definition");
4300 if (parser->tok == TOKEN_IDENT)
4301 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4302 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4303 parseerror(parser, "expected typename");
4307 /* generate the basic type value */
4308 if (cached_typedef) {
4309 var = ast_value_copy(cached_typedef);
4310 ast_value_set_name(var, "<type(from_def)>");
4312 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4314 for (; morefields; --morefields) {
4315 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4316 tmp->expression.next = (ast_expression*)var;
4320 /* do not yet turn into a field - remember:
4321 * .void() foo; is a field too
4322 * .void()() foo; is a function
4326 if (!parser_next(parser)) {
4328 parseerror(parser, "parse error after typename");
4332 /* an opening paren now starts the parameter-list of a function
4333 * this is where original-QC has parameter lists.
4334 * We allow a single parameter list here.
4335 * Much like fteqcc we don't allow `float()() x`
4337 if (parser->tok == '(') {
4338 var = parse_parameter_list(parser, var);
4343 /* store the base if requested */
4345 *storebase = ast_value_copy(var);
4347 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4348 tmp->expression.next = (ast_expression*)*storebase;
4353 /* there may be a name now */
4354 if (parser->tok == TOKEN_IDENT) {
4355 name = util_strdup(parser_tokval(parser));
4357 if (!parser_next(parser)) {
4359 parseerror(parser, "error after variable or field declaration");
4364 /* now this may be an array */
4365 if (parser->tok == '[') {
4367 var = parse_arraysize(parser, var);
4372 /* This is the point where we can turn it into a field */
4374 /* turn it into a field if desired */
4375 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4376 tmp->expression.next = (ast_expression*)var;
4380 /* now there may be function parens again */
4381 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4382 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4383 if (parser->tok == '(' && wasarray)
4384 parseerror(parser, "arrays as part of a return type is not supported");
4385 while (parser->tok == '(') {
4386 var = parse_parameter_list(parser, var);
4395 /* finally name it */
4397 if (!ast_value_set_name(var, name)) {
4399 parseerror(parser, "internal error: failed to set name");
4402 /* free the name, ast_value_set_name duplicates */
4409 static bool parse_typedef(parser_t *parser)
4411 ast_value *typevar, *oldtype;
4412 ast_expression *old;
4414 typevar = parse_typename(parser, NULL, NULL);
4419 if ( (old = parser_find_var(parser, typevar->name)) ) {
4420 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4421 " -> `%s` has been declared here: %s:%i",
4422 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4423 ast_delete(typevar);
4427 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4428 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4429 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4430 ast_delete(typevar);
4434 vec_push(parser->_typedefs, typevar);
4435 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4437 if (parser->tok != ';') {
4438 parseerror(parser, "expected semicolon after typedef");
4441 if (!parser_next(parser)) {
4442 parseerror(parser, "parse error after typedef");
4449 static const char *cvq_to_str(int cvq) {
4451 case CV_NONE: return "none";
4452 case CV_VAR: return "`var`";
4453 case CV_CONST: return "`const`";
4454 default: return "<INVALID>";
4458 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4461 if (proto->cvq != var->cvq) {
4462 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4463 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4464 parser->tok == '='))
4466 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4467 "`%s` declared with different qualifiers: %s\n"
4468 " -> previous declaration here: %s:%i uses %s",
4469 var->name, cvq_to_str(var->cvq),
4470 ast_ctx(proto).file, ast_ctx(proto).line,
4471 cvq_to_str(proto->cvq));
4474 av = (var ->expression.flags & AST_FLAG_NORETURN);
4475 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4477 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4478 "`%s` declared with different attributes%s\n"
4479 " -> previous declaration here: %s:%i",
4480 var->name, (av ? ": noreturn" : ""),
4481 ast_ctx(proto).file, ast_ctx(proto).line,
4482 (ao ? ": noreturn" : ""));
4487 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)
4491 ast_expression *old;
4495 ast_value *basetype = NULL;
4497 bool isparam = false;
4498 bool isvector = false;
4499 bool cleanvar = true;
4500 bool wasarray = false;
4504 if (!localblock && is_static)
4505 parseerror(parser, "`static` qualifier is not supported in global scope");
4507 /* get the first complete variable */
4508 var = parse_typename(parser, &basetype, cached_typedef);
4511 ast_delete(basetype);
4519 /* Part 0: finish the type */
4520 if (parser->tok == '(') {
4521 if (opts.standard == COMPILER_QCC)
4522 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4523 var = parse_parameter_list(parser, var);
4529 /* we only allow 1-dimensional arrays */
4530 if (parser->tok == '[') {
4532 var = parse_arraysize(parser, var);
4538 if (parser->tok == '(' && wasarray) {
4539 parseerror(parser, "arrays as part of a return type is not supported");
4540 /* we'll still parse the type completely for now */
4542 /* for functions returning functions */
4543 while (parser->tok == '(') {
4544 if (opts.standard == COMPILER_QCC)
4545 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4546 var = parse_parameter_list(parser, var);
4553 var->cvq = qualifier;
4554 var->expression.flags |= qflags;
4555 if (var->expression.flags & AST_FLAG_DEPRECATED)
4556 var->desc = vstring;
4559 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4560 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4561 * is then filled with the previous definition and the parameter-names replaced.
4563 if (!strcmp(var->name, "nil")) {
4564 if (OPTS_FLAG(UNTYPED_NIL)) {
4565 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4566 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4568 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4571 /* Deal with end_sys_ vars */
4573 if (!strcmp(var->name, "end_sys_globals")) {
4575 parser->crc_globals = vec_size(parser->globals);
4578 else if (!strcmp(var->name, "end_sys_fields")) {
4580 parser->crc_fields = vec_size(parser->fields);
4583 if (was_end && var->expression.vtype == TYPE_FIELD) {
4584 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4585 "global '%s' hint should not be a field",
4586 parser_tokval(parser)))
4593 if (!nofields && var->expression.vtype == TYPE_FIELD)
4595 /* deal with field declarations */
4596 old = parser_find_field(parser, var->name);
4598 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4599 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4608 parseerror(parser, "field `%s` already declared here: %s:%i",
4609 var->name, ast_ctx(old).file, ast_ctx(old).line);
4614 if (opts.standard == COMPILER_QCC &&
4615 (old = parser_find_global(parser, var->name)))
4617 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4618 parseerror(parser, "field `%s` already declared here: %s:%i",
4619 var->name, ast_ctx(old).file, ast_ctx(old).line);
4626 /* deal with other globals */
4627 old = parser_find_global(parser, var->name);
4628 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4630 /* This is a function which had a prototype */
4631 if (!ast_istype(old, ast_value)) {
4632 parseerror(parser, "internal error: prototype is not an ast_value");
4636 proto = (ast_value*)old;
4637 proto->desc = var->desc;
4638 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4639 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4641 ast_ctx(proto).file, ast_ctx(proto).line);
4645 /* we need the new parameter-names */
4646 for (i = 0; i < vec_size(proto->expression.params); ++i)
4647 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4648 if (!parser_check_qualifiers(parser, var, proto)) {
4655 proto->expression.flags |= var->expression.flags;
4663 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4664 "global `%s` already declared here: %s:%i",
4665 var->name, ast_ctx(old).file, ast_ctx(old).line))
4670 proto = (ast_value*)old;
4671 if (!ast_istype(old, ast_value)) {
4672 parseerror(parser, "internal error: not an ast_value");
4677 if (!parser_check_qualifiers(parser, var, proto)) {
4682 proto->expression.flags |= var->expression.flags;
4686 if (opts.standard == COMPILER_QCC &&
4687 (old = parser_find_field(parser, var->name)))
4689 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4690 parseerror(parser, "global `%s` already declared here: %s:%i",
4691 var->name, ast_ctx(old).file, ast_ctx(old).line);
4698 else /* it's not a global */
4700 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4701 if (old && !isparam) {
4702 parseerror(parser, "local `%s` already declared here: %s:%i",
4703 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4707 old = parser_find_local(parser, var->name, 0, &isparam);
4708 if (old && isparam) {
4709 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4710 "local `%s` is shadowing a parameter", var->name))
4712 parseerror(parser, "local `%s` already declared here: %s:%i",
4713 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4717 if (opts.standard != COMPILER_GMQCC) {
4725 /* in a noref section we simply bump the usecount */
4726 if (noref || parser->noref)
4730 * Create the global/local, and deal with vector types.
4733 if (var->expression.vtype == TYPE_VECTOR)
4735 else if (var->expression.vtype == TYPE_FIELD &&
4736 var->expression.next->expression.vtype == TYPE_VECTOR)
4740 if (!create_vector_members(var, me)) {
4747 /* deal with global variables, fields, functions */
4748 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4749 var->isfield = true;
4750 vec_push(parser->fields, (ast_expression*)var);
4751 util_htset(parser->htfields, var->name, var);
4753 for (i = 0; i < 3; ++i) {
4754 vec_push(parser->fields, (ast_expression*)me[i]);
4755 util_htset(parser->htfields, me[i]->name, me[i]);
4760 vec_push(parser->globals, (ast_expression*)var);
4761 util_htset(parser->htglobals, var->name, var);
4763 for (i = 0; i < 3; ++i) {
4764 vec_push(parser->globals, (ast_expression*)me[i]);
4765 util_htset(parser->htglobals, me[i]->name, me[i]);
4771 /* a static adds itself to be generated like any other global
4772 * but is added to the local namespace instead
4774 char *defname = NULL;
4775 size_t prefix_len, ln;
4777 ln = strlen(parser->function->name);
4778 vec_append(defname, ln, parser->function->name);
4780 vec_append(defname, 2, "::");
4781 /* remember the length up to here */
4782 prefix_len = vec_size(defname);
4784 /* Add it to the local scope */
4785 util_htset(vec_last(parser->variables), var->name, (void*)var);
4786 /* now rename the global */
4787 ln = strlen(var->name);
4788 vec_append(defname, ln, var->name);
4789 ast_value_set_name(var, defname);
4791 /* push it to the to-be-generated globals */
4792 vec_push(parser->globals, (ast_expression*)var);
4794 /* same game for the vector members */
4796 for (i = 0; i < 3; ++i) {
4797 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4799 vec_shrinkto(defname, prefix_len);
4800 ln = strlen(me[i]->name);
4801 vec_append(defname, ln, me[i]->name);
4802 ast_member_set_name(me[i], defname);
4804 vec_push(parser->globals, (ast_expression*)me[i]);
4809 vec_push(localblock->locals, var);
4810 parser_addlocal(parser, var->name, (ast_expression*)var);
4812 for (i = 0; i < 3; ++i) {
4813 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4814 ast_block_collect(localblock, (ast_expression*)me[i]);
4820 me[0] = me[1] = me[2] = NULL;
4825 if (var->expression.vtype == TYPE_ARRAY) {
4827 snprintf(name, sizeof(name), "%s##SET", var->name);
4828 if (!parser_create_array_setter(parser, var, name))
4830 snprintf(name, sizeof(name), "%s##GET", var->name);
4831 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4834 else if (!localblock && !nofields &&
4835 var->expression.vtype == TYPE_FIELD &&
4836 var->expression.next->expression.vtype == TYPE_ARRAY)
4839 ast_expression *telem;
4841 ast_value *array = (ast_value*)var->expression.next;
4843 if (!ast_istype(var->expression.next, ast_value)) {
4844 parseerror(parser, "internal error: field element type must be an ast_value");
4848 snprintf(name, sizeof(name), "%s##SETF", var->name);
4849 if (!parser_create_array_field_setter(parser, array, name))
4852 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4853 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4854 tfield->expression.next = telem;
4855 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4856 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4864 if (parser->tok == ';') {
4865 ast_delete(basetype);
4866 if (!parser_next(parser)) {
4867 parseerror(parser, "error after variable declaration");
4873 if (parser->tok == ',')
4877 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4880 parseerror(parser, "missing comma or semicolon while parsing variables");
4884 if (localblock && opts.standard == COMPILER_QCC) {
4885 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4886 "initializing expression turns variable `%s` into a constant in this standard",
4893 if (parser->tok != '{') {
4894 if (parser->tok != '=') {
4895 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4899 if (!parser_next(parser)) {
4900 parseerror(parser, "error parsing initializer");
4904 else if (opts.standard == COMPILER_QCC) {
4905 parseerror(parser, "expected '=' before function body in this standard");
4908 if (parser->tok == '#') {
4909 ast_function *func = NULL;
4912 parseerror(parser, "cannot declare builtins within functions");
4915 if (var->expression.vtype != TYPE_FUNCTION) {
4916 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4919 if (!parser_next(parser)) {
4920 parseerror(parser, "expected builtin number");
4923 if (parser->tok != TOKEN_INTCONST) {
4924 parseerror(parser, "builtin number must be an integer constant");
4927 if (parser_token(parser)->constval.i < 0) {
4928 parseerror(parser, "builtin number must be an integer greater than zero");
4932 if (var->hasvalue) {
4933 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4934 "builtin `%s` has already been defined\n"
4935 " -> previous declaration here: %s:%i",
4936 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4940 func = ast_function_new(ast_ctx(var), var->name, var);
4942 parseerror(parser, "failed to allocate function for `%s`", var->name);
4945 vec_push(parser->functions, func);
4947 func->builtin = -parser_token(parser)->constval.i-1;
4950 if (!parser_next(parser)) {
4951 parseerror(parser, "expected comma or semicolon");
4953 ast_function_delete(func);
4954 var->constval.vfunc = NULL;
4958 else if (parser->tok == '{' || parser->tok == '[')
4961 parseerror(parser, "cannot declare functions within functions");
4966 ast_ctx(proto) = parser_ctx(parser);
4968 if (!parse_function_body(parser, var))
4970 ast_delete(basetype);
4971 for (i = 0; i < vec_size(parser->gotos); ++i)
4972 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4973 vec_free(parser->gotos);
4974 vec_free(parser->labels);
4977 ast_expression *cexp;
4980 cexp = parse_expression_leave(parser, true, false, false);
4985 cval = (ast_value*)cexp;
4986 if (cval != parser->nil &&
4987 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4990 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4994 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4995 qualifier != CV_VAR)
4997 var->cvq = CV_CONST;
4999 if (cval == parser->nil)
5000 var->expression.flags |= AST_FLAG_INITIALIZED;
5003 var->hasvalue = true;
5004 if (cval->expression.vtype == TYPE_STRING)
5005 var->constval.vstring = parser_strdup(cval->constval.vstring);
5006 else if (cval->expression.vtype == TYPE_FIELD)
5007 var->constval.vfield = cval;
5009 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5015 shunt sy = { NULL, NULL };
5018 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5019 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5020 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5021 if (!parser_sy_apply_operator(parser, &sy))
5024 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5025 parseerror(parser, "internal error: leaked operands");
5026 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5036 if (parser->tok == ',') {
5037 if (!parser_next(parser)) {
5038 parseerror(parser, "expected another variable");
5042 if (parser->tok != TOKEN_IDENT) {
5043 parseerror(parser, "expected another variable");
5046 var = ast_value_copy(basetype);
5048 ast_value_set_name(var, parser_tokval(parser));
5049 if (!parser_next(parser)) {
5050 parseerror(parser, "error parsing variable declaration");
5056 if (parser->tok != ';') {
5057 parseerror(parser, "missing semicolon after variables");
5061 if (!parser_next(parser)) {
5062 parseerror(parser, "parse error after variable declaration");
5066 ast_delete(basetype);
5070 if (cleanvar && var)
5072 ast_delete(basetype);
5076 ast_delete(basetype);
5077 if (cleanvar && var)
5079 if (me[0]) ast_member_delete(me[0]);
5080 if (me[1]) ast_member_delete(me[1]);
5081 if (me[2]) ast_member_delete(me[2]);
5085 static bool parser_global_statement(parser_t *parser)
5089 bool is_static = false;
5090 uint32_t qflags = 0;
5091 ast_value *istype = NULL;
5092 char *vstring = NULL;
5094 if (parser->tok == TOKEN_IDENT)
5095 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5097 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5099 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5101 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5103 if (cvq == CV_WRONG)
5105 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5107 else if (parser->tok == TOKEN_KEYWORD)
5109 if (!strcmp(parser_tokval(parser), "typedef")) {
5110 if (!parser_next(parser)) {
5111 parseerror(parser, "expected type definition after 'typedef'");
5114 return parse_typedef(parser);
5116 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5119 else if (parser->tok == '#')
5121 return parse_pragma(parser);
5123 else if (parser->tok == '$')
5125 if (!parser_next(parser)) {
5126 parseerror(parser, "parse error");
5132 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5138 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5140 return util_crc16(old, str, strlen(str));
5143 static void progdefs_crc_file(const char *str)
5145 /* write to progdefs.h here */
5149 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5151 old = progdefs_crc_sum(old, str);
5152 progdefs_crc_file(str);
5156 static void generate_checksum(parser_t *parser)
5158 uint16_t crc = 0xFFFF;
5162 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5163 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5165 progdefs_crc_file("\tint\tpad;\n");
5166 progdefs_crc_file("\tint\tofs_return[3];\n");
5167 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5168 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5169 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5170 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5171 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5172 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5173 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5174 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5176 for (i = 0; i < parser->crc_globals; ++i) {
5177 if (!ast_istype(parser->globals[i], ast_value))
5179 value = (ast_value*)(parser->globals[i]);
5180 switch (value->expression.vtype) {
5181 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5182 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5183 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5184 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5186 crc = progdefs_crc_both(crc, "\tint\t");
5189 crc = progdefs_crc_both(crc, value->name);
5190 crc = progdefs_crc_both(crc, ";\n");
5192 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5193 for (i = 0; i < parser->crc_fields; ++i) {
5194 if (!ast_istype(parser->fields[i], ast_value))
5196 value = (ast_value*)(parser->fields[i]);
5197 switch (value->expression.next->expression.vtype) {
5198 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5199 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5200 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5201 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5203 crc = progdefs_crc_both(crc, "\tint\t");
5206 crc = progdefs_crc_both(crc, value->name);
5207 crc = progdefs_crc_both(crc, ";\n");
5209 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5214 static parser_t *parser;
5221 parser = (parser_t*)mem_a(sizeof(parser_t));
5225 memset(parser, 0, sizeof(*parser));
5227 for (i = 0; i < operator_count; ++i) {
5228 if (operators[i].id == opid1('=')) {
5229 parser->assign_op = operators+i;
5233 if (!parser->assign_op) {
5234 printf("internal error: initializing parser: failed to find assign operator\n");
5239 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5240 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5241 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5242 vec_push(parser->_blocktypedefs, 0);
5244 empty_ctx.file = "<internal>";
5246 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5247 parser->nil->cvq = CV_CONST;
5248 if (OPTS_FLAG(UNTYPED_NIL))
5249 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5253 bool parser_compile()
5255 /* initial lexer/parser state */
5256 parser->lex->flags.noops = true;
5258 if (parser_next(parser))
5260 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5262 if (!parser_global_statement(parser)) {
5263 if (parser->tok == TOKEN_EOF)
5264 parseerror(parser, "unexpected eof");
5265 else if (compile_errors)
5266 parseerror(parser, "there have been errors, bailing out");
5267 lex_close(parser->lex);
5273 parseerror(parser, "parse error");
5274 lex_close(parser->lex);
5279 lex_close(parser->lex);
5282 return !compile_errors;
5285 bool parser_compile_file(const char *filename)
5287 parser->lex = lex_open(filename);
5289 con_err("failed to open file \"%s\"\n", filename);
5292 return parser_compile();
5295 bool parser_compile_string(const char *name, const char *str, size_t len)
5297 parser->lex = lex_open_string(str, len, name);
5299 con_err("failed to create lexer for string \"%s\"\n", name);
5302 return parser_compile();
5305 void parser_cleanup()
5308 for (i = 0; i < vec_size(parser->accessors); ++i) {
5309 ast_delete(parser->accessors[i]->constval.vfunc);
5310 parser->accessors[i]->constval.vfunc = NULL;
5311 ast_delete(parser->accessors[i]);
5313 for (i = 0; i < vec_size(parser->functions); ++i) {
5314 ast_delete(parser->functions[i]);
5316 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5317 ast_delete(parser->imm_vector[i]);
5319 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5320 ast_delete(parser->imm_string[i]);
5322 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5323 ast_delete(parser->imm_float[i]);
5325 for (i = 0; i < vec_size(parser->fields); ++i) {
5326 ast_delete(parser->fields[i]);
5328 for (i = 0; i < vec_size(parser->globals); ++i) {
5329 ast_delete(parser->globals[i]);
5331 vec_free(parser->accessors);
5332 vec_free(parser->functions);
5333 vec_free(parser->imm_vector);
5334 vec_free(parser->imm_string);
5335 vec_free(parser->imm_float);
5336 vec_free(parser->globals);
5337 vec_free(parser->fields);
5339 for (i = 0; i < vec_size(parser->variables); ++i)
5340 util_htdel(parser->variables[i]);
5341 vec_free(parser->variables);
5342 vec_free(parser->_blocklocals);
5343 vec_free(parser->_locals);
5345 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5346 ast_delete(parser->_typedefs[i]);
5347 vec_free(parser->_typedefs);
5348 for (i = 0; i < vec_size(parser->typedefs); ++i)
5349 util_htdel(parser->typedefs[i]);
5350 vec_free(parser->typedefs);
5351 vec_free(parser->_blocktypedefs);
5353 vec_free(parser->_block_ctx);
5355 vec_free(parser->labels);
5356 vec_free(parser->gotos);
5357 vec_free(parser->breaks);
5358 vec_free(parser->continues);
5360 ast_value_delete(parser->nil);
5365 bool parser_finish(const char *output)
5371 if (compile_errors) {
5372 con_out("*** there were compile errors\n");
5376 ir = ir_builder_new("gmqcc_out");
5378 con_out("failed to allocate builder\n");
5382 for (i = 0; i < vec_size(parser->fields); ++i) {
5385 if (!ast_istype(parser->fields[i], ast_value))
5387 field = (ast_value*)parser->fields[i];
5388 hasvalue = field->hasvalue;
5389 field->hasvalue = false;
5390 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5391 con_out("failed to generate field %s\n", field->name);
5392 ir_builder_delete(ir);
5397 ast_expression *subtype;
5398 field->hasvalue = true;
5399 subtype = field->expression.next;
5400 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5401 if (subtype->expression.vtype == TYPE_FIELD)
5402 ifld->fieldtype = subtype->expression.next->expression.vtype;
5403 else if (subtype->expression.vtype == TYPE_FUNCTION)
5404 ifld->outtype = subtype->expression.next->expression.vtype;
5405 (void)!ir_value_set_field(field->ir_v, ifld);
5408 for (i = 0; i < vec_size(parser->globals); ++i) {
5410 if (!ast_istype(parser->globals[i], ast_value))
5412 asvalue = (ast_value*)(parser->globals[i]);
5413 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5414 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5415 "unused global: `%s`", asvalue->name);
5417 if (!ast_global_codegen(asvalue, ir, false)) {
5418 con_out("failed to generate global %s\n", asvalue->name);
5419 ir_builder_delete(ir);
5423 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5424 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5425 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5426 ir_builder_delete(ir);
5430 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5431 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5432 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5433 ir_builder_delete(ir);
5437 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5438 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5439 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5440 ir_builder_delete(ir);
5444 for (i = 0; i < vec_size(parser->globals); ++i) {
5446 if (!ast_istype(parser->globals[i], ast_value))
5448 asvalue = (ast_value*)(parser->globals[i]);
5449 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5451 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5452 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5453 "uninitialized constant: `%s`",
5455 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5456 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5457 "uninitialized global: `%s`",
5460 if (!ast_generate_accessors(asvalue, ir)) {
5461 ir_builder_delete(ir);
5465 for (i = 0; i < vec_size(parser->fields); ++i) {
5467 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5469 if (!ast_istype((ast_expression*)asvalue, ast_value))
5471 if (asvalue->expression.vtype != TYPE_ARRAY)
5473 if (!ast_generate_accessors(asvalue, ir)) {
5474 ir_builder_delete(ir);
5478 for (i = 0; i < vec_size(parser->functions); ++i) {
5479 if (!ast_function_codegen(parser->functions[i], ir)) {
5480 con_out("failed to generate function %s\n", parser->functions[i]->name);
5481 ir_builder_delete(ir);
5486 ir_builder_dump(ir, con_out);
5487 for (i = 0; i < vec_size(parser->functions); ++i) {
5488 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5489 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5490 ir_builder_delete(ir);
5495 if (compile_Werrors) {
5496 con_out("*** there were warnings treated as errors\n");
5497 compile_show_werrors();
5503 ir_builder_dump(ir, con_out);
5505 generate_checksum(parser);
5507 if (!ir_builder_generate(ir, output)) {
5508 con_out("*** failed to generate output file\n");
5509 ir_builder_delete(ir);
5514 ir_builder_delete(ir);