2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
37 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_vector_zero;
61 ast_function *function;
63 /* All the labels the function defined...
64 * Should they be in ast_function instead?
69 const char **continues;
71 /* A list of hashtables for each scope */
77 /* same as above but for the spelling corrector */
78 ht *correct_variables;
79 size_t ***correct_variables_score; /* vector of vector of size_t* */
81 /* not to be used directly, we use the hash table */
82 ast_expression **_locals;
84 ast_value **_typedefs;
85 size_t *_blocktypedefs;
88 /* we store the '=' operator info */
89 const oper_info *assign_op;
91 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
92 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
93 * anything else: type error
97 /* Keep track of our ternary vs parenthesis nesting state.
98 * If we reach a 'comma' operator in a ternary without a paren,
99 * we shall trigger -Wternary-precedence.
101 enum parser_pot *pot;
107 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
109 static void parser_enterblock(parser_t *parser);
110 static bool parser_leaveblock(parser_t *parser);
111 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
112 static bool parse_typedef(parser_t *parser);
113 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);
114 static ast_block* parse_block(parser_t *parser);
115 static bool parse_block_into(parser_t *parser, ast_block *block);
116 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
117 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
118 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
119 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
121 static void parseerror(parser_t *parser, const char *fmt, ...)
125 vcompile_error(parser->lex->tok.ctx, fmt, ap);
129 /* returns true if it counts as an error */
130 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
135 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
140 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
145 r = vcompile_warning(ctx, warntype, fmt, ap);
150 /**********************************************************************
151 * some maths used for constant folding
154 vector vec3_add(vector a, vector b)
163 vector vec3_sub(vector a, vector b)
172 qcfloat vec3_mulvv(vector a, vector b)
174 return (a.x * b.x + a.y * b.y + a.z * b.z);
177 vector vec3_mulvf(vector a, float b)
186 /**********************************************************************
190 bool parser_next(parser_t *parser)
192 /* lex_do kills the previous token */
193 parser->tok = lex_do(parser->lex);
194 if (parser->tok == TOKEN_EOF)
196 if (parser->tok >= TOKEN_ERROR) {
197 parseerror(parser, "lex error");
203 #define parser_tokval(p) ((p)->lex->tok.value)
204 #define parser_token(p) (&((p)->lex->tok))
205 #define parser_ctx(p) ((p)->lex->tok.ctx)
207 static ast_value* parser_const_float(parser_t *parser, double d)
211 for (i = 0; i < vec_size(parser->imm_float); ++i) {
212 const double compare = parser->imm_float[i]->constval.vfloat;
213 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
214 return parser->imm_float[i];
216 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
218 out->hasvalue = true;
219 out->constval.vfloat = d;
220 vec_push(parser->imm_float, out);
224 static ast_value* parser_const_float_0(parser_t *parser)
226 if (!parser->imm_float_zero)
227 parser->imm_float_zero = parser_const_float(parser, 0);
228 return parser->imm_float_zero;
231 static ast_value* parser_const_float_1(parser_t *parser)
233 if (!parser->imm_float_one)
234 parser->imm_float_one = parser_const_float(parser, 1);
235 return parser->imm_float_one;
238 static char *parser_strdup(const char *str)
241 /* actually dup empty strings */
242 char *out = (char*)mem_a(1);
246 return util_strdup(str);
249 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
253 for (i = 0; i < vec_size(parser->imm_string); ++i) {
254 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
255 return parser->imm_string[i];
259 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
260 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
262 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
264 out->hasvalue = true;
265 out->constval.vstring = parser_strdup(str);
266 vec_push(parser->imm_string, out);
270 static ast_value* parser_const_vector(parser_t *parser, vector v)
274 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
275 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
276 return parser->imm_vector[i];
278 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
280 out->hasvalue = true;
281 out->constval.vvec = v;
282 vec_push(parser->imm_vector, out);
286 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
292 return parser_const_vector(parser, v);
295 static ast_value* parser_const_vector_0(parser_t *parser)
297 if (!parser->imm_vector_zero)
298 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
299 return parser->imm_vector_zero;
302 static ast_expression* parser_find_field(parser_t *parser, const char *name)
304 return ( ast_expression*)util_htget(parser->htfields, name);
307 static ast_expression* parser_find_label(parser_t *parser, const char *name)
310 for(i = 0; i < vec_size(parser->labels); i++)
311 if (!strcmp(parser->labels[i]->name, name))
312 return (ast_expression*)parser->labels[i];
316 static ast_expression* parser_find_global(parser_t *parser, const char *name)
318 return (ast_expression*)util_htget(parser->htglobals, name);
321 static ast_expression* parser_find_param(parser_t *parser, const char *name)
325 if (!parser->function)
327 fun = parser->function->vtype;
328 for (i = 0; i < vec_size(fun->expression.params); ++i) {
329 if (!strcmp(fun->expression.params[i]->name, name))
330 return (ast_expression*)(fun->expression.params[i]);
335 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
340 hash = util_hthash(parser->htglobals, name);
343 for (i = vec_size(parser->variables); i > upto;) {
345 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
349 return parser_find_param(parser, name);
352 static ast_expression* parser_find_var(parser_t *parser, const char *name)
356 v = parser_find_local(parser, name, 0, &dummy);
357 if (!v) v = parser_find_global(parser, name);
361 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
365 hash = util_hthash(parser->typedefs[0], name);
367 for (i = vec_size(parser->typedefs); i > upto;) {
369 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
377 size_t etype; /* 0 = expression, others are operators */
381 ast_block *block; /* for commas and function calls */
390 #define SY_PAREN_EXPR '('
391 #define SY_PAREN_FUNC 'f'
392 #define SY_PAREN_INDEX '['
393 #define SY_PAREN_TERNARY '?'
395 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
406 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
410 e.out = (ast_expression*)v;
417 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
419 e.etype = 1 + (op - operators);
428 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
440 # define DEBUGSHUNTDO(x) x
442 # define DEBUGSHUNTDO(x)
445 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
446 * so we need to rotate it to become ent.(foo[n]).
448 static bool rotate_entfield_array_index_nodes(ast_expression **out)
450 ast_array_index *index;
451 ast_entfield *entfield;
455 ast_expression *entity;
457 lex_ctx ctx = ast_ctx(*out);
459 if (!ast_istype(*out, ast_array_index))
461 index = (ast_array_index*)*out;
463 if (!ast_istype(index->array, ast_entfield))
465 entfield = (ast_entfield*)index->array;
467 if (!ast_istype(entfield->field, ast_value))
469 field = (ast_value*)entfield->field;
472 entity = entfield->entity;
476 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
477 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
478 *out = (ast_expression*)entfield;
483 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
485 switch (v->expression.vtype) {
487 return !!v->constval.vfloat;
489 return !!v->constval.vint;
491 if (OPTS_FLAG(CORRECT_LOGIC))
492 return v->constval.vvec.x &&
493 v->constval.vvec.y &&
496 return !!(v->constval.vvec.x);
498 if (!v->constval.vstring)
500 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
502 return !!v->constval.vstring[0];
504 compile_error(ctx, "internal error: immediate_is_true on invalid type");
505 return !!v->constval.vfunc;
509 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
513 ast_expression *out = NULL;
514 ast_expression *exprs[3];
515 ast_block *blocks[3];
516 ast_value *asvalue[3];
517 ast_binstore *asbinstore;
518 size_t i, assignop, addop, subop;
519 qcint generated_op = 0;
524 if (!vec_size(sy->ops)) {
525 parseerror(parser, "internal error: missing operator");
529 if (vec_last(sy->ops).paren) {
530 parseerror(parser, "unmatched parenthesis");
534 op = &operators[vec_last(sy->ops).etype - 1];
535 ctx = vec_last(sy->ops).ctx;
537 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
539 if (vec_size(sy->out) < op->operands) {
540 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
541 op->op, (int)op->id);
545 vec_shrinkby(sy->ops, 1);
547 /* op(:?) has no input and no output */
551 vec_shrinkby(sy->out, op->operands);
552 for (i = 0; i < op->operands; ++i) {
553 exprs[i] = sy->out[vec_size(sy->out)+i].out;
554 blocks[i] = sy->out[vec_size(sy->out)+i].block;
555 asvalue[i] = (ast_value*)exprs[i];
557 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
558 !(i != 0 && op->id == opid2('?',':')))
560 if (ast_istype(exprs[i], ast_label))
561 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
563 compile_error(ast_ctx(exprs[i]), "not an expression");
564 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
568 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
569 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
573 #define NotSameType(T) \
574 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
575 exprs[0]->expression.vtype != T)
576 #define CanConstFold1(A) \
577 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
578 (A)->expression.vtype != TYPE_FUNCTION)
579 #define CanConstFold(A, B) \
580 (CanConstFold1(A) && CanConstFold1(B))
581 #define ConstV(i) (asvalue[(i)]->constval.vvec)
582 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
583 #define ConstS(i) (asvalue[(i)]->constval.vstring)
587 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
591 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
592 if (exprs[1]->expression.vtype != TYPE_FIELD) {
593 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
596 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
598 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
599 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
603 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
609 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
610 !(exprs[0]->expression.vtype == TYPE_FIELD &&
611 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
613 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
614 parseerror(parser, "cannot index value of type %s", ty1);
617 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
618 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
619 parseerror(parser, "index must be of type float, not %s", ty1);
622 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
623 if (rotate_entfield_array_index_nodes(&out))
626 /* This is not broken in fteqcc anymore */
627 if (opts.standard != COMPILER_GMQCC) {
628 /* this error doesn't need to make us bail out */
629 (void)!parsewarning(parser, WARN_EXTENSIONS,
630 "accessing array-field members of an entity without parenthesis\n"
631 " -> this is an extension from -std=gmqcc");
639 if (!ast_block_add_expr(blocks[0], exprs[1]))
642 blocks[0] = ast_block_new(ctx);
643 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
644 !ast_block_add_expr(blocks[0], exprs[1]))
649 if (!ast_block_set_type(blocks[0], exprs[1]))
652 vec_push(sy->out, syblock(ctx, blocks[0]));
659 switch (exprs[0]->expression.vtype) {
661 if (CanConstFold1(exprs[0]))
662 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
664 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
665 (ast_expression*)parser_const_float_0(parser),
669 if (CanConstFold1(exprs[0]))
670 out = (ast_expression*)parser_const_vector_f(parser,
671 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
673 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
674 (ast_expression*)parser_const_vector_0(parser),
678 parseerror(parser, "invalid types used in expression: cannot negate type %s",
679 type_name[exprs[0]->expression.vtype]);
685 switch (exprs[0]->expression.vtype) {
687 if (CanConstFold1(exprs[0]))
688 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
690 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
693 if (CanConstFold1(exprs[0]))
694 out = (ast_expression*)parser_const_float(parser,
695 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
697 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
700 if (CanConstFold1(exprs[0])) {
701 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
702 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
704 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
706 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
707 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
709 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
712 /* we don't constant-fold NOT for these types */
714 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
717 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
720 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
721 type_name[exprs[0]->expression.vtype]);
727 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
728 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
730 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
731 type_name[exprs[0]->expression.vtype],
732 type_name[exprs[1]->expression.vtype]);
735 switch (exprs[0]->expression.vtype) {
737 if (CanConstFold(exprs[0], exprs[1]))
739 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
742 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
745 if (CanConstFold(exprs[0], exprs[1]))
746 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
748 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
751 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
752 type_name[exprs[0]->expression.vtype],
753 type_name[exprs[1]->expression.vtype]);
758 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
759 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
761 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
762 type_name[exprs[1]->expression.vtype],
763 type_name[exprs[0]->expression.vtype]);
766 switch (exprs[0]->expression.vtype) {
768 if (CanConstFold(exprs[0], exprs[1]))
769 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
771 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
774 if (CanConstFold(exprs[0], exprs[1]))
775 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
777 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
780 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
781 type_name[exprs[1]->expression.vtype],
782 type_name[exprs[0]->expression.vtype]);
787 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
788 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
789 exprs[1]->expression.vtype == TYPE_FLOAT) &&
790 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
791 exprs[0]->expression.vtype == TYPE_FLOAT)
794 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
795 type_name[exprs[1]->expression.vtype],
796 type_name[exprs[0]->expression.vtype]);
799 switch (exprs[0]->expression.vtype) {
801 if (exprs[1]->expression.vtype == TYPE_VECTOR)
803 if (CanConstFold(exprs[0], exprs[1]))
804 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
806 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
810 if (CanConstFold(exprs[0], exprs[1]))
811 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
813 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
817 if (exprs[1]->expression.vtype == TYPE_FLOAT)
819 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
826 if (CanConstFold(exprs[0], exprs[1]))
827 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
828 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
829 vector vec = ConstV(0);
830 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
831 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
832 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
833 out->expression.node.keep = false;
834 ((ast_member*)out)->rvalue = true;
836 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
838 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
839 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
840 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
841 out->expression.node.keep = false;
842 ((ast_member*)out)->rvalue = true;
844 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
846 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
847 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
848 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
849 out->expression.node.keep = false;
850 ((ast_member*)out)->rvalue = true;
852 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
855 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
857 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
858 vector vec = ConstV(1);
859 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
860 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
861 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
862 out->expression.node.keep = false;
863 ((ast_member*)out)->rvalue = true;
865 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
867 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
868 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
869 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
870 out->expression.node.keep = false;
871 ((ast_member*)out)->rvalue = true;
873 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
875 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
876 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
877 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
878 out->expression.node.keep = false;
879 ((ast_member*)out)->rvalue = true;
881 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
884 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
891 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
892 type_name[exprs[1]->expression.vtype],
893 type_name[exprs[0]->expression.vtype]);
898 if (NotSameType(TYPE_FLOAT)) {
899 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
900 type_name[exprs[0]->expression.vtype],
901 type_name[exprs[1]->expression.vtype]);
904 if (CanConstFold(exprs[0], exprs[1]))
905 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
907 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
911 parseerror(parser, "qc does not have a modulo operator");
915 if (NotSameType(TYPE_FLOAT)) {
916 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
917 type_name[exprs[0]->expression.vtype],
918 type_name[exprs[1]->expression.vtype]);
921 if (CanConstFold(exprs[0], exprs[1]))
922 out = (ast_expression*)parser_const_float(parser,
923 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
924 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
926 out = (ast_expression*)ast_binary_new(ctx,
927 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
931 parseerror(parser, "TODO: bitxor");
936 case opid3('<','<','='):
937 case opid3('>','>','='):
938 parseerror(parser, "TODO: shifts");
942 generated_op += 1; /* INSTR_OR */
944 generated_op += INSTR_AND;
946 if (NotSameType(TYPE_FLOAT)) {
947 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
948 type_name[exprs[0]->expression.vtype],
949 type_name[exprs[1]->expression.vtype]);
950 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
951 parseerror(parser, "TODO: optional early out");
955 if (CanConstFold(exprs[0], exprs[1]))
957 if (OPTS_FLAG(PERL_LOGIC)) {
958 if (immediate_is_true(ctx, asvalue[0]))
962 out = (ast_expression*)parser_const_float(parser,
963 ( (generated_op == INSTR_OR)
964 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
965 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
970 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
971 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
972 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
973 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
976 for (i = 0; i < 2; ++i) {
977 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
978 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
980 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
982 exprs[i] = out; out = NULL;
983 if (OPTS_FLAG(PERL_LOGIC)) {
984 /* here we want to keep the right expressions' type */
988 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
989 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
991 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
993 exprs[i] = out; out = NULL;
994 if (OPTS_FLAG(PERL_LOGIC)) {
995 /* here we want to keep the right expressions' type */
1000 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1004 case opid2('?',':'):
1005 if (vec_last(parser->pot) != POT_TERNARY2) {
1006 parseerror(parser, "mismatched parenthesis/ternary");
1009 vec_pop(parser->pot);
1010 if (!ast_compare_type(exprs[1], exprs[2])) {
1011 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1012 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1013 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1016 if (CanConstFold1(exprs[0]))
1017 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1019 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1023 generated_op += 1; /* INSTR_GT */
1025 generated_op += 1; /* INSTR_LT */
1026 case opid2('>', '='):
1027 generated_op += 1; /* INSTR_GE */
1028 case opid2('<', '='):
1029 generated_op += INSTR_LE;
1030 if (NotSameType(TYPE_FLOAT)) {
1031 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1032 type_name[exprs[0]->expression.vtype],
1033 type_name[exprs[1]->expression.vtype]);
1036 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1038 case opid2('!', '='):
1039 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1040 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1041 type_name[exprs[0]->expression.vtype],
1042 type_name[exprs[1]->expression.vtype]);
1045 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1047 case opid2('=', '='):
1048 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1049 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
1050 type_name[exprs[0]->expression.vtype],
1051 type_name[exprs[1]->expression.vtype]);
1054 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1058 if (ast_istype(exprs[0], ast_entfield)) {
1059 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1060 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1061 exprs[0]->expression.vtype == TYPE_FIELD &&
1062 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1064 assignop = type_storep_instr[TYPE_VECTOR];
1067 assignop = type_storep_instr[exprs[0]->expression.vtype];
1068 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1070 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1071 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1072 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1073 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1074 exprs[1]->expression.vtype == TYPE_FUNCTION)
1076 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1077 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1080 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1085 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1086 exprs[0]->expression.vtype == TYPE_FIELD &&
1087 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1089 assignop = type_store_instr[TYPE_VECTOR];
1092 assignop = type_store_instr[exprs[0]->expression.vtype];
1095 if (assignop == AINSTR_END) {
1096 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1097 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1098 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1100 else if (!ast_compare_type(exprs[0], exprs[1]))
1102 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1103 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1104 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1105 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1106 exprs[1]->expression.vtype == TYPE_FUNCTION)
1108 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1109 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1112 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1115 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1116 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1118 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1120 case opid3('+','+','P'):
1121 case opid3('-','-','P'):
1123 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1124 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1125 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1128 if (op->id == opid3('+','+','P'))
1129 addop = INSTR_ADD_F;
1131 addop = INSTR_SUB_F;
1132 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1133 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1135 if (ast_istype(exprs[0], ast_entfield)) {
1136 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1138 (ast_expression*)parser_const_float_1(parser));
1140 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1142 (ast_expression*)parser_const_float_1(parser));
1145 case opid3('S','+','+'):
1146 case opid3('S','-','-'):
1148 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1149 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1150 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1153 if (op->id == opid3('S','+','+')) {
1154 addop = INSTR_ADD_F;
1155 subop = INSTR_SUB_F;
1157 addop = INSTR_SUB_F;
1158 subop = INSTR_ADD_F;
1160 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1161 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1163 if (ast_istype(exprs[0], ast_entfield)) {
1164 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1166 (ast_expression*)parser_const_float_1(parser));
1168 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1170 (ast_expression*)parser_const_float_1(parser));
1174 out = (ast_expression*)ast_binary_new(ctx, subop,
1176 (ast_expression*)parser_const_float_1(parser));
1178 case opid2('+','='):
1179 case opid2('-','='):
1180 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1181 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1183 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1184 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1185 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1189 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1190 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1192 if (ast_istype(exprs[0], ast_entfield))
1193 assignop = type_storep_instr[exprs[0]->expression.vtype];
1195 assignop = type_store_instr[exprs[0]->expression.vtype];
1196 switch (exprs[0]->expression.vtype) {
1198 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1199 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1200 exprs[0], exprs[1]);
1203 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1204 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1205 exprs[0], exprs[1]);
1208 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1209 type_name[exprs[0]->expression.vtype],
1210 type_name[exprs[1]->expression.vtype]);
1214 case opid2('*','='):
1215 case opid2('/','='):
1216 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1217 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1218 exprs[0]->expression.vtype == TYPE_VECTOR))
1220 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1221 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1222 parseerror(parser, "invalid types used in expression: %s and %s",
1226 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1227 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1229 if (ast_istype(exprs[0], ast_entfield))
1230 assignop = type_storep_instr[exprs[0]->expression.vtype];
1232 assignop = type_store_instr[exprs[0]->expression.vtype];
1233 switch (exprs[0]->expression.vtype) {
1235 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1236 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1237 exprs[0], exprs[1]);
1240 if (op->id == opid2('*','=')) {
1241 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1242 exprs[0], exprs[1]);
1244 /* there's no DIV_VF */
1245 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1246 (ast_expression*)parser_const_float_1(parser),
1250 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1255 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1256 type_name[exprs[0]->expression.vtype],
1257 type_name[exprs[1]->expression.vtype]);
1261 case opid2('&','='):
1262 case opid2('|','='):
1263 if (NotSameType(TYPE_FLOAT)) {
1264 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1265 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1266 parseerror(parser, "invalid types used in expression: %s and %s",
1270 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1271 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1273 if (ast_istype(exprs[0], ast_entfield))
1274 assignop = type_storep_instr[exprs[0]->expression.vtype];
1276 assignop = type_store_instr[exprs[0]->expression.vtype];
1277 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1278 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1279 exprs[0], exprs[1]);
1281 case opid3('&','~','='):
1282 /* This is like: a &= ~(b);
1283 * But QC has no bitwise-not, so we implement it as
1286 if (NotSameType(TYPE_FLOAT)) {
1287 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1288 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1289 parseerror(parser, "invalid types used in expression: %s and %s",
1293 if (ast_istype(exprs[0], ast_entfield))
1294 assignop = type_storep_instr[exprs[0]->expression.vtype];
1296 assignop = type_store_instr[exprs[0]->expression.vtype];
1297 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1300 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1301 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1303 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1304 asbinstore->keep_dest = true;
1305 out = (ast_expression*)asbinstore;
1311 parseerror(parser, "failed to apply operand %s", op->op);
1315 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1316 vec_push(sy->out, syexp(ctx, out));
1320 static bool parser_close_call(parser_t *parser, shunt *sy)
1322 /* was a function call */
1323 ast_expression *fun;
1329 vec_shrinkby(sy->ops, 1);
1330 fid = sy->ops[vec_size(sy->ops)].off;
1332 /* out[fid] is the function
1333 * everything above is parameters...
1334 * 0 params = nothing
1335 * 1 params = ast_expression
1339 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1340 parseerror(parser, "internal error: function call needs function and parameter list...");
1344 fun = sy->out[fid].out;
1346 if (fun == intrinsic_debug_typestring) {
1348 if (fid+2 != vec_size(sy->out) ||
1349 vec_last(sy->out).block)
1351 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1354 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1355 ast_unref(vec_last(sy->out).out);
1356 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1357 (ast_expression*)parser_const_string(parser, ty, false));
1358 vec_shrinkby(sy->out, 1);
1362 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1364 parseerror(parser, "internal error: failed to create ast_call node");
1368 if (fid+1 == vec_size(sy->out)) {
1371 } else if (fid+2 == vec_size(sy->out)) {
1373 vec_shrinkby(sy->out, 1);
1374 params = sy->out[vec_size(sy->out)].block;
1378 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1380 paramcount = vec_size(params->exprs);
1381 call->params = params->exprs;
1382 params->exprs = NULL;
1385 (void)!ast_call_check_types(call);
1387 parseerror(parser, "invalid function call");
1391 /* overwrite fid, the function, with a call */
1392 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1394 if (fun->expression.vtype != TYPE_FUNCTION) {
1395 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1399 if (!fun->expression.next) {
1400 parseerror(parser, "could not determine function return type");
1403 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1405 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1407 return !parsewarning(parser, WARN_DEPRECATED,
1408 "call to function (which is marked deprecated)\n",
1409 "-> it has been declared here: %s:%i",
1410 ast_ctx(fun).file, ast_ctx(fun).line);
1413 return !parsewarning(parser, WARN_DEPRECATED,
1414 "call to `%s` (which is marked deprecated)\n"
1415 "-> `%s` declared here: %s:%i",
1416 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1418 return !parsewarning(parser, WARN_DEPRECATED,
1419 "call to `%s` (deprecated: %s)\n"
1420 "-> `%s` declared here: %s:%i",
1421 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1425 if (vec_size(fun->expression.params) != paramcount &&
1426 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1427 vec_size(fun->expression.params) < paramcount))
1429 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1431 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1432 "too %s parameters for call to %s: expected %i, got %i\n"
1433 " -> `%s` has been declared here: %s:%i",
1434 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1435 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1437 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1438 "too %s parameters for function call: expected %i, got %i\n"
1439 " -> it has been declared here: %s:%i",
1440 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1441 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1448 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1450 if (!vec_size(sy->ops)) {
1451 parseerror(parser, "unmatched closing paren");
1454 /* this would for bit a + (x) because there are no operators inside (x)
1455 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1456 parseerror(parser, "empty parenthesis expression");
1460 while (vec_size(sy->ops)) {
1461 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1462 if (!parser_close_call(parser, sy))
1466 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1467 vec_shrinkby(sy->ops, 1);
1468 return !functions_only;
1470 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1473 /* pop off the parenthesis */
1474 vec_shrinkby(sy->ops, 1);
1475 /* then apply the index operator */
1476 if (!parser_sy_apply_operator(parser, sy))
1480 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1483 if (vec_last(parser->pot) != POT_TERNARY1) {
1484 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1487 vec_last(parser->pot) = POT_TERNARY2;
1488 /* pop off the parenthesis */
1489 vec_shrinkby(sy->ops, 1);
1492 if (!parser_sy_apply_operator(parser, sy))
1498 static void parser_reclassify_token(parser_t *parser)
1501 for (i = 0; i < operator_count; ++i) {
1502 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1503 parser->tok = TOKEN_OPERATOR;
1509 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1511 ast_expression *expr = NULL;
1513 bool wantop = false;
1514 bool gotmemberof = false;
1515 /* only warn once about an assignment in a truth value because the current code
1516 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1518 bool warn_truthvalue = true;
1520 /* count the parens because an if starts with one, so the
1521 * end of a condition is an unmatched closing paren
1529 parser->lex->flags.noops = false;
1531 parser_reclassify_token(parser);
1536 gotmemberof = false;
1538 parser->memberof = 0;
1540 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1541 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1543 /* a translatable string */
1547 parseerror(parser, "expected operator or end of statement, got constant");
1551 parser->lex->flags.noops = true;
1552 if (!parser_next(parser) || parser->tok != '(') {
1553 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1556 parser->lex->flags.noops = false;
1557 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1558 parseerror(parser, "expected a constant string in translatable-string extension");
1561 val = parser_const_string(parser, parser_tokval(parser), true);
1565 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1566 DEBUGSHUNTDO(con_out("push string\n"));
1568 if (!parser_next(parser) || parser->tok != ')') {
1569 parseerror(parser, "expected closing paren after translatable string");
1573 else if (parser->tok == TOKEN_IDENT)
1575 ast_expression *var;
1577 parseerror(parser, "expected operator or end of statement");
1582 if (opts.standard == COMPILER_GMQCC)
1584 if (parser->memberof == TYPE_ENTITY) {
1585 /* still get vars first since there could be a fieldpointer */
1586 var = parser_find_var(parser, parser_tokval(parser));
1588 var = parser_find_field(parser, parser_tokval(parser));
1590 else if (parser->memberof == TYPE_VECTOR)
1592 parseerror(parser, "TODO: implement effective vector member access");
1595 else if (parser->memberof) {
1596 parseerror(parser, "namespace for member not found");
1600 var = parser_find_var(parser, parser_tokval(parser));
1602 var = parser_find_var(parser, parser_tokval(parser));
1604 var = parser_find_field(parser, parser_tokval(parser));
1606 if (!var && with_labels) {
1607 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1609 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1610 var = (ast_expression*)lbl;
1611 vec_push(parser->labels, lbl);
1616 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1617 var = (ast_expression*)intrinsic_debug_typestring;
1622 char *correct = NULL;
1625 * sometimes people use preprocessing predefs without enabling them
1626 * i've done this thousands of times already myself. Lets check for
1627 * it in the predef table. And diagnose it better :)
1629 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1630 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1631 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1632 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1639 * TODO: determine the best score for the identifier: be it
1640 * a variable, a field.
1642 * We should also consider adding correction tables for
1643 * other things as well.
1645 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1646 correct = correct_str(parser->correct_variables[i], parser_tokval(parser));
1647 if (strcmp(correct, parser_tokval(parser))) {
1649 } else if (correct) {
1655 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1658 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1666 if (ast_istype(var, ast_value)) {
1667 ((ast_value*)var)->uses++;
1669 else if (ast_istype(var, ast_member)) {
1670 ast_member *mem = (ast_member*)var;
1671 if (ast_istype(mem->owner, ast_value))
1672 ((ast_value*)(mem->owner))->uses++;
1675 vec_push(sy.out, syexp(parser_ctx(parser), var));
1676 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1678 else if (parser->tok == TOKEN_FLOATCONST) {
1681 parseerror(parser, "expected operator or end of statement, got constant");
1685 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1688 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1689 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1691 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1694 parseerror(parser, "expected operator or end of statement, got constant");
1698 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1701 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1702 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1704 else if (parser->tok == TOKEN_STRINGCONST) {
1707 parseerror(parser, "expected operator or end of statement, got constant");
1711 val = parser_const_string(parser, parser_tokval(parser), false);
1714 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1715 DEBUGSHUNTDO(con_out("push string\n"));
1717 else if (parser->tok == TOKEN_VECTORCONST) {
1720 parseerror(parser, "expected operator or end of statement, got constant");
1724 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1727 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1728 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1729 parser_token(parser)->constval.v.x,
1730 parser_token(parser)->constval.v.y,
1731 parser_token(parser)->constval.v.z));
1733 else if (parser->tok == '(') {
1734 parseerror(parser, "internal error: '(' should be classified as operator");
1737 else if (parser->tok == '[') {
1738 parseerror(parser, "internal error: '[' should be classified as operator");
1741 else if (parser->tok == ')') {
1743 DEBUGSHUNTDO(con_out("do[op] )\n"));
1747 /* we do expect an operator next */
1748 /* closing an opening paren */
1749 if (!parser_close_paren(parser, &sy, false))
1751 if (vec_last(parser->pot) != POT_PAREN) {
1752 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1755 vec_pop(parser->pot);
1757 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1761 /* allowed for function calls */
1762 if (!parser_close_paren(parser, &sy, true))
1764 if (vec_last(parser->pot) != POT_PAREN) {
1765 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1768 vec_pop(parser->pot);
1772 else if (parser->tok == ']') {
1774 parseerror(parser, "operand expected");
1778 if (!parser_close_paren(parser, &sy, false))
1780 if (vec_last(parser->pot) != POT_PAREN) {
1781 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1784 vec_pop(parser->pot);
1787 else if (parser->tok == TOKEN_TYPENAME) {
1788 parseerror(parser, "unexpected typename");
1791 else if (parser->tok != TOKEN_OPERATOR) {
1793 parseerror(parser, "expected operator or end of statement");
1800 /* classify the operator */
1801 const oper_info *op;
1802 const oper_info *olast = NULL;
1804 for (o = 0; o < operator_count; ++o) {
1805 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1806 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1807 !strcmp(parser_tokval(parser), operators[o].op))
1812 if (o == operator_count) {
1813 /* no operator found... must be the end of the statement */
1816 /* found an operator */
1819 /* when declaring variables, a comma starts a new variable */
1820 if (op->id == opid1(',') && !parens && stopatcomma) {
1821 /* fixup the token */
1826 /* a colon without a pervious question mark cannot be a ternary */
1827 if (!ternaries && op->id == opid2(':','?')) {
1832 if (op->id == opid1(',')) {
1833 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1834 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1838 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1839 olast = &operators[vec_last(sy.ops).etype-1];
1841 #define IsAssignOp(x) (\
1842 (x) == opid1('=') || \
1843 (x) == opid2('+','=') || \
1844 (x) == opid2('-','=') || \
1845 (x) == opid2('*','=') || \
1846 (x) == opid2('/','=') || \
1847 (x) == opid2('%','=') || \
1848 (x) == opid2('&','=') || \
1849 (x) == opid2('|','=') || \
1850 (x) == opid3('&','~','=') \
1852 if (warn_truthvalue) {
1853 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1854 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1855 (truthvalue && !vec_size(parser->pot) && IsAssignOp(op->id))
1858 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1859 warn_truthvalue = false;
1864 (op->prec < olast->prec) ||
1865 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1867 if (!parser_sy_apply_operator(parser, &sy))
1869 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1870 olast = &operators[vec_last(sy.ops).etype-1];
1875 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1876 /* for gmqcc standard: open up the namespace of the previous type */
1877 ast_expression *prevex = vec_last(sy.out).out;
1879 parseerror(parser, "unexpected member operator");
1882 if (prevex->expression.vtype == TYPE_ENTITY)
1883 parser->memberof = TYPE_ENTITY;
1884 else if (prevex->expression.vtype == TYPE_VECTOR)
1885 parser->memberof = TYPE_VECTOR;
1887 parseerror(parser, "type error: type has no members");
1893 if (op->id == opid1('(')) {
1895 size_t sycount = vec_size(sy.out);
1896 DEBUGSHUNTDO(con_out("push [op] (\n"));
1897 ++parens; vec_push(parser->pot, POT_PAREN);
1898 /* we expected an operator, this is the function-call operator */
1899 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1901 ++parens; vec_push(parser->pot, POT_PAREN);
1902 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1903 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1906 } else if (op->id == opid1('[')) {
1908 parseerror(parser, "unexpected array subscript");
1911 ++parens; vec_push(parser->pot, POT_PAREN);
1912 /* push both the operator and the paren, this makes life easier */
1913 vec_push(sy.ops, syop(parser_ctx(parser), op));
1914 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1916 } else if (op->id == opid2('?',':')) {
1917 vec_push(sy.ops, syop(parser_ctx(parser), op));
1918 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1921 vec_push(parser->pot, POT_TERNARY1);
1922 } else if (op->id == opid2(':','?')) {
1923 if (!vec_size(parser->pot)) {
1924 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1927 if (vec_last(parser->pot) != POT_TERNARY1) {
1928 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1931 if (!parser_close_paren(parser, &sy, false))
1933 vec_push(sy.ops, syop(parser_ctx(parser), op));
1937 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1938 vec_push(sy.ops, syop(parser_ctx(parser), op));
1939 wantop = !!(op->flags & OP_SUFFIX);
1942 if (!parser_next(parser)) {
1945 if (parser->tok == ';' ||
1946 (!parens && parser->tok == ']'))
1952 while (vec_size(sy.ops)) {
1953 if (!parser_sy_apply_operator(parser, &sy))
1957 parser->lex->flags.noops = true;
1958 if (!vec_size(sy.out)) {
1959 parseerror(parser, "empty expression");
1962 expr = sy.out[0].out;
1965 DEBUGSHUNTDO(con_out("shunt done\n"));
1966 if (vec_size(parser->pot)) {
1967 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1970 vec_free(parser->pot);
1974 parser->lex->flags.noops = true;
1980 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1982 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1985 if (!parser_next(parser)) {
1992 static void parser_enterblock(parser_t *parser)
1994 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1995 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1996 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1997 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1998 vec_push(parser->_block_ctx, parser_ctx(parser));
2001 vec_push(parser->correct_variables, util_htnew(PARSER_HT_SIZE));
2002 vec_push(parser->correct_variables_score, NULL);
2005 static bool parser_leaveblock(parser_t *parser)
2008 size_t locals, typedefs;
2010 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2011 parseerror(parser, "internal error: parser_leaveblock with no block");
2015 util_htdel(vec_last(parser->variables));
2016 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2018 vec_pop(parser->variables);
2019 vec_pop(parser->correct_variables);
2020 vec_pop(parser->correct_variables_score);
2021 if (!vec_size(parser->_blocklocals)) {
2022 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2026 locals = vec_last(parser->_blocklocals);
2027 vec_pop(parser->_blocklocals);
2028 while (vec_size(parser->_locals) != locals) {
2029 ast_expression *e = vec_last(parser->_locals);
2030 ast_value *v = (ast_value*)e;
2031 vec_pop(parser->_locals);
2032 if (ast_istype(e, ast_value) && !v->uses) {
2033 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2038 typedefs = vec_last(parser->_blocktypedefs);
2039 while (vec_size(parser->_typedefs) != typedefs) {
2040 ast_delete(vec_last(parser->_typedefs));
2041 vec_pop(parser->_typedefs);
2043 util_htdel(vec_last(parser->typedefs));
2044 vec_pop(parser->typedefs);
2046 vec_pop(parser->_block_ctx);
2051 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2053 vec_push(parser->_locals, e);
2054 util_htset(vec_last(parser->variables), name, (void*)e);
2058 vec_last(parser->correct_variables),
2059 &vec_last(parser->correct_variables_score),
2064 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2068 ast_expression *prev;
2070 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2073 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2076 parseerror(parser, "internal error: failed to process condition");
2081 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2083 /* vector types need to be cast to true booleans */
2084 ast_binary *bin = (ast_binary*)cond;
2085 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2087 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2089 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2092 parseerror(parser, "internal error: failed to process condition");
2099 unary = (ast_unary*)cond;
2100 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2102 cond = unary->operand;
2103 unary->operand = NULL;
2106 unary = (ast_unary*)cond;
2110 parseerror(parser, "internal error: failed to process condition");
2112 if (ifnot) *_ifnot = !*_ifnot;
2116 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2119 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2122 lex_ctx ctx = parser_ctx(parser);
2124 (void)block; /* not touching */
2126 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2127 if (!parser_next(parser)) {
2128 parseerror(parser, "expected condition or 'not'");
2131 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2133 if (!parser_next(parser)) {
2134 parseerror(parser, "expected condition in parenthesis");
2138 if (parser->tok != '(') {
2139 parseerror(parser, "expected 'if' condition in parenthesis");
2142 /* parse into the expression */
2143 if (!parser_next(parser)) {
2144 parseerror(parser, "expected 'if' condition after opening paren");
2147 /* parse the condition */
2148 cond = parse_expression_leave(parser, false, true, false);
2152 if (parser->tok != ')') {
2153 parseerror(parser, "expected closing paren after 'if' condition");
2157 /* parse into the 'then' branch */
2158 if (!parser_next(parser)) {
2159 parseerror(parser, "expected statement for on-true branch of 'if'");
2163 if (!parse_statement_or_block(parser, &ontrue)) {
2167 /* check for an else */
2168 if (!strcmp(parser_tokval(parser), "else")) {
2169 /* parse into the 'else' branch */
2170 if (!parser_next(parser)) {
2171 parseerror(parser, "expected on-false branch after 'else'");
2176 if (!parse_statement_or_block(parser, &onfalse)) {
2183 cond = process_condition(parser, cond, &ifnot);
2185 if (ontrue) ast_delete(ontrue);
2186 if (onfalse) ast_delete(onfalse);
2191 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2193 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2194 *out = (ast_expression*)ifthen;
2198 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2199 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2204 /* skip the 'while' and get the body */
2205 if (!parser_next(parser)) {
2206 if (OPTS_FLAG(LOOP_LABELS))
2207 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2209 parseerror(parser, "expected 'while' condition in parenthesis");
2213 if (parser->tok == ':') {
2214 if (!OPTS_FLAG(LOOP_LABELS))
2215 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2216 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2217 parseerror(parser, "expected loop label");
2220 label = util_strdup(parser_tokval(parser));
2221 if (!parser_next(parser)) {
2223 parseerror(parser, "expected 'while' condition in parenthesis");
2228 if (parser->tok != '(') {
2229 parseerror(parser, "expected 'while' condition in parenthesis");
2233 vec_push(parser->breaks, label);
2234 vec_push(parser->continues, label);
2236 rv = parse_while_go(parser, block, out);
2239 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2240 parseerror(parser, "internal error: label stack corrupted");
2246 vec_pop(parser->breaks);
2247 vec_pop(parser->continues);
2252 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2255 ast_expression *cond, *ontrue;
2259 lex_ctx ctx = parser_ctx(parser);
2261 (void)block; /* not touching */
2263 /* parse into the expression */
2264 if (!parser_next(parser)) {
2265 parseerror(parser, "expected 'while' condition after opening paren");
2268 /* parse the condition */
2269 cond = parse_expression_leave(parser, false, true, false);
2273 if (parser->tok != ')') {
2274 parseerror(parser, "expected closing paren after 'while' condition");
2278 /* parse into the 'then' branch */
2279 if (!parser_next(parser)) {
2280 parseerror(parser, "expected while-loop body");
2284 if (!parse_statement_or_block(parser, &ontrue)) {
2289 cond = process_condition(parser, cond, &ifnot);
2294 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2295 *out = (ast_expression*)aloop;
2299 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2300 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2305 /* skip the 'do' and get the body */
2306 if (!parser_next(parser)) {
2307 if (OPTS_FLAG(LOOP_LABELS))
2308 parseerror(parser, "expected loop label or body");
2310 parseerror(parser, "expected loop body");
2314 if (parser->tok == ':') {
2315 if (!OPTS_FLAG(LOOP_LABELS))
2316 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2317 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2318 parseerror(parser, "expected loop label");
2321 label = util_strdup(parser_tokval(parser));
2322 if (!parser_next(parser)) {
2324 parseerror(parser, "expected loop body");
2329 vec_push(parser->breaks, label);
2330 vec_push(parser->continues, label);
2332 rv = parse_dowhile_go(parser, block, out);
2335 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2336 parseerror(parser, "internal error: label stack corrupted");
2342 vec_pop(parser->breaks);
2343 vec_pop(parser->continues);
2348 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2351 ast_expression *cond, *ontrue;
2355 lex_ctx ctx = parser_ctx(parser);
2357 (void)block; /* not touching */
2359 if (!parse_statement_or_block(parser, &ontrue))
2362 /* expect the "while" */
2363 if (parser->tok != TOKEN_KEYWORD ||
2364 strcmp(parser_tokval(parser), "while"))
2366 parseerror(parser, "expected 'while' and condition");
2371 /* skip the 'while' and check for opening paren */
2372 if (!parser_next(parser) || parser->tok != '(') {
2373 parseerror(parser, "expected 'while' condition in parenthesis");
2377 /* parse into the expression */
2378 if (!parser_next(parser)) {
2379 parseerror(parser, "expected 'while' condition after opening paren");
2383 /* parse the condition */
2384 cond = parse_expression_leave(parser, false, true, false);
2388 if (parser->tok != ')') {
2389 parseerror(parser, "expected closing paren after 'while' condition");
2395 if (!parser_next(parser) || parser->tok != ';') {
2396 parseerror(parser, "expected semicolon after condition");
2402 if (!parser_next(parser)) {
2403 parseerror(parser, "parse error");
2409 cond = process_condition(parser, cond, &ifnot);
2414 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2415 *out = (ast_expression*)aloop;
2419 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2420 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2425 /* skip the 'for' and check for opening paren */
2426 if (!parser_next(parser)) {
2427 if (OPTS_FLAG(LOOP_LABELS))
2428 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2430 parseerror(parser, "expected 'for' expressions in parenthesis");
2434 if (parser->tok == ':') {
2435 if (!OPTS_FLAG(LOOP_LABELS))
2436 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2437 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2438 parseerror(parser, "expected loop label");
2441 label = util_strdup(parser_tokval(parser));
2442 if (!parser_next(parser)) {
2444 parseerror(parser, "expected 'for' expressions in parenthesis");
2449 if (parser->tok != '(') {
2450 parseerror(parser, "expected 'for' expressions in parenthesis");
2454 vec_push(parser->breaks, label);
2455 vec_push(parser->continues, label);
2457 rv = parse_for_go(parser, block, out);
2460 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2461 parseerror(parser, "internal error: label stack corrupted");
2467 vec_pop(parser->breaks);
2468 vec_pop(parser->continues);
2472 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2475 ast_expression *initexpr, *cond, *increment, *ontrue;
2481 lex_ctx ctx = parser_ctx(parser);
2483 parser_enterblock(parser);
2490 /* parse into the expression */
2491 if (!parser_next(parser)) {
2492 parseerror(parser, "expected 'for' initializer after opening paren");
2497 if (parser->tok == TOKEN_IDENT)
2498 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2500 if (typevar || parser->tok == TOKEN_TYPENAME) {
2502 if (opts.standard != COMPILER_GMQCC) {
2503 if (parsewarning(parser, WARN_EXTENSIONS,
2504 "current standard does not allow variable declarations in for-loop initializers"))
2508 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2511 else if (parser->tok != ';')
2513 initexpr = parse_expression_leave(parser, false, false, false);
2518 /* move on to condition */
2519 if (parser->tok != ';') {
2520 parseerror(parser, "expected semicolon after for-loop initializer");
2523 if (!parser_next(parser)) {
2524 parseerror(parser, "expected for-loop condition");
2528 /* parse the condition */
2529 if (parser->tok != ';') {
2530 cond = parse_expression_leave(parser, false, true, false);
2535 /* move on to incrementor */
2536 if (parser->tok != ';') {
2537 parseerror(parser, "expected semicolon after for-loop initializer");
2540 if (!parser_next(parser)) {
2541 parseerror(parser, "expected for-loop condition");
2545 /* parse the incrementor */
2546 if (parser->tok != ')') {
2547 increment = parse_expression_leave(parser, false, false, false);
2550 if (!ast_side_effects(increment)) {
2551 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2557 if (parser->tok != ')') {
2558 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2561 /* parse into the 'then' branch */
2562 if (!parser_next(parser)) {
2563 parseerror(parser, "expected for-loop body");
2566 if (!parse_statement_or_block(parser, &ontrue))
2570 cond = process_condition(parser, cond, &ifnot);
2574 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2575 *out = (ast_expression*)aloop;
2577 if (!parser_leaveblock(parser))
2581 if (initexpr) ast_delete(initexpr);
2582 if (cond) ast_delete(cond);
2583 if (increment) ast_delete(increment);
2584 (void)!parser_leaveblock(parser);
2588 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2590 ast_expression *exp = NULL;
2591 ast_return *ret = NULL;
2592 ast_value *expected = parser->function->vtype;
2594 lex_ctx ctx = parser_ctx(parser);
2596 (void)block; /* not touching */
2598 if (!parser_next(parser)) {
2599 parseerror(parser, "expected return expression");
2603 if (parser->tok != ';') {
2604 exp = parse_expression(parser, false, false);
2608 if (exp->expression.vtype != TYPE_NIL &&
2609 exp->expression.vtype != expected->expression.next->expression.vtype)
2611 parseerror(parser, "return with invalid expression");
2614 ret = ast_return_new(ctx, exp);
2620 if (!parser_next(parser))
2621 parseerror(parser, "parse error");
2622 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2623 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2625 ret = ast_return_new(ctx, NULL);
2627 *out = (ast_expression*)ret;
2631 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2634 unsigned int levels = 0;
2635 lex_ctx ctx = parser_ctx(parser);
2636 const char **loops = (is_continue ? parser->continues : parser->breaks);
2638 (void)block; /* not touching */
2639 if (!parser_next(parser)) {
2640 parseerror(parser, "expected semicolon or loop label");
2644 if (parser->tok == TOKEN_IDENT) {
2645 if (!OPTS_FLAG(LOOP_LABELS))
2646 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2647 i = vec_size(loops);
2649 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2652 parseerror(parser, "no such loop to %s: `%s`",
2653 (is_continue ? "continue" : "break out of"),
2654 parser_tokval(parser));
2659 if (!parser_next(parser)) {
2660 parseerror(parser, "expected semicolon");
2665 if (parser->tok != ';') {
2666 parseerror(parser, "expected semicolon");
2670 if (!parser_next(parser))
2671 parseerror(parser, "parse error");
2673 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2677 /* returns true when it was a variable qualifier, false otherwise!
2678 * on error, cvq is set to CV_WRONG
2680 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2682 bool had_const = false;
2683 bool had_var = false;
2684 bool had_noref = false;
2685 bool had_attrib = false;
2686 bool had_static = false;
2691 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2693 /* parse an attribute */
2694 if (!parser_next(parser)) {
2695 parseerror(parser, "expected attribute after `[[`");
2699 if (!strcmp(parser_tokval(parser), "noreturn")) {
2700 flags |= AST_FLAG_NORETURN;
2701 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2702 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2707 else if (!strcmp(parser_tokval(parser), "noref")) {
2709 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2710 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2715 else if (!strcmp(parser_tokval(parser), "inline")) {
2716 flags |= AST_FLAG_INLINE;
2717 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2718 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2725 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2726 flags |= AST_FLAG_DEPRECATED;
2729 if (!parser_next(parser)) {
2730 parseerror(parser, "parse error in attribute");
2734 if (parser->tok == '(') {
2735 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2736 parseerror(parser, "`deprecated` attribute missing parameter");
2740 *message = util_strdup(parser_tokval(parser));
2742 if (!parser_next(parser)) {
2743 parseerror(parser, "parse error in attribute");
2747 if(parser->tok != ')') {
2748 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2752 if (!parser_next(parser)) {
2753 parseerror(parser, "parse error in attribute");
2758 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2759 parseerror(parser, "`deprecated` attribute expected `]]`");
2762 if (*message) mem_d(*message);
2770 /* Skip tokens until we hit a ]] */
2771 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2772 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2773 if (!parser_next(parser)) {
2774 parseerror(parser, "error inside attribute");
2781 else if (!strcmp(parser_tokval(parser), "static"))
2783 else if (!strcmp(parser_tokval(parser), "const"))
2785 else if (!strcmp(parser_tokval(parser), "var"))
2787 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2789 else if (!strcmp(parser_tokval(parser), "noref"))
2791 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2796 if (!parser_next(parser))
2806 *is_static = had_static;
2810 parseerror(parser, "parse error after variable qualifier");
2815 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2816 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2821 /* skip the 'while' and get the body */
2822 if (!parser_next(parser)) {
2823 if (OPTS_FLAG(LOOP_LABELS))
2824 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2826 parseerror(parser, "expected 'switch' operand in parenthesis");
2830 if (parser->tok == ':') {
2831 if (!OPTS_FLAG(LOOP_LABELS))
2832 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2833 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2834 parseerror(parser, "expected loop label");
2837 label = util_strdup(parser_tokval(parser));
2838 if (!parser_next(parser)) {
2840 parseerror(parser, "expected 'switch' operand in parenthesis");
2845 if (parser->tok != '(') {
2846 parseerror(parser, "expected 'switch' operand in parenthesis");
2850 vec_push(parser->breaks, label);
2852 rv = parse_switch_go(parser, block, out);
2855 if (vec_last(parser->breaks) != label) {
2856 parseerror(parser, "internal error: label stack corrupted");
2862 vec_pop(parser->breaks);
2867 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2869 ast_expression *operand;
2872 ast_switch *switchnode;
2873 ast_switch_case swcase;
2876 bool noref, is_static;
2877 uint32_t qflags = 0;
2879 lex_ctx ctx = parser_ctx(parser);
2881 (void)block; /* not touching */
2884 /* parse into the expression */
2885 if (!parser_next(parser)) {
2886 parseerror(parser, "expected switch operand");
2889 /* parse the operand */
2890 operand = parse_expression_leave(parser, false, false, false);
2894 switchnode = ast_switch_new(ctx, operand);
2897 if (parser->tok != ')') {
2898 ast_delete(switchnode);
2899 parseerror(parser, "expected closing paren after 'switch' operand");
2903 /* parse over the opening paren */
2904 if (!parser_next(parser) || parser->tok != '{') {
2905 ast_delete(switchnode);
2906 parseerror(parser, "expected list of cases");
2910 if (!parser_next(parser)) {
2911 ast_delete(switchnode);
2912 parseerror(parser, "expected 'case' or 'default'");
2916 /* new block; allow some variables to be declared here */
2917 parser_enterblock(parser);
2920 if (parser->tok == TOKEN_IDENT)
2921 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2922 if (typevar || parser->tok == TOKEN_TYPENAME) {
2923 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2924 ast_delete(switchnode);
2929 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2931 if (cvq == CV_WRONG) {
2932 ast_delete(switchnode);
2935 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2936 ast_delete(switchnode);
2945 while (parser->tok != '}') {
2946 ast_block *caseblock;
2948 if (!strcmp(parser_tokval(parser), "case")) {
2949 if (!parser_next(parser)) {
2950 ast_delete(switchnode);
2951 parseerror(parser, "expected expression for case");
2954 swcase.value = parse_expression_leave(parser, false, false, false);
2955 if (!swcase.value) {
2956 ast_delete(switchnode);
2957 parseerror(parser, "expected expression for case");
2960 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2961 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2962 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2968 else if (!strcmp(parser_tokval(parser), "default")) {
2969 swcase.value = NULL;
2970 if (!parser_next(parser)) {
2971 ast_delete(switchnode);
2972 parseerror(parser, "expected colon");
2977 ast_delete(switchnode);
2978 parseerror(parser, "expected 'case' or 'default'");
2982 /* Now the colon and body */
2983 if (parser->tok != ':') {
2984 if (swcase.value) ast_unref(swcase.value);
2985 ast_delete(switchnode);
2986 parseerror(parser, "expected colon");
2990 if (!parser_next(parser)) {
2991 if (swcase.value) ast_unref(swcase.value);
2992 ast_delete(switchnode);
2993 parseerror(parser, "expected statements or case");
2996 caseblock = ast_block_new(parser_ctx(parser));
2998 if (swcase.value) ast_unref(swcase.value);
2999 ast_delete(switchnode);
3002 swcase.code = (ast_expression*)caseblock;
3003 vec_push(switchnode->cases, swcase);
3005 ast_expression *expr;
3006 if (parser->tok == '}')
3008 if (parser->tok == TOKEN_KEYWORD) {
3009 if (!strcmp(parser_tokval(parser), "case") ||
3010 !strcmp(parser_tokval(parser), "default"))
3015 if (!parse_statement(parser, caseblock, &expr, true)) {
3016 ast_delete(switchnode);
3021 if (!ast_block_add_expr(caseblock, expr)) {
3022 ast_delete(switchnode);
3028 parser_leaveblock(parser);
3031 if (parser->tok != '}') {
3032 ast_delete(switchnode);
3033 parseerror(parser, "expected closing paren of case list");
3036 if (!parser_next(parser)) {
3037 ast_delete(switchnode);
3038 parseerror(parser, "parse error after switch");
3041 *out = (ast_expression*)switchnode;
3045 /* parse computed goto sides */
3046 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3047 ast_expression *on_true;
3048 ast_expression *on_false;
3049 ast_expression *cond;
3054 if (ast_istype(*side, ast_ternary)) {
3055 ast_ternary *tern = (ast_ternary*)*side;
3056 on_true = parse_goto_computed(parser, &tern->on_true);
3057 on_false = parse_goto_computed(parser, &tern->on_false);
3059 if (!on_true || !on_false) {
3060 parseerror(parser, "expected label or expression in ternary");
3061 if (on_true) ast_unref(on_true);
3062 if (on_false) ast_unref(on_false);
3070 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3071 } else if (ast_istype(*side, ast_label)) {
3072 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3073 ast_goto_set_label(gt, ((ast_label*)*side));
3075 return (ast_expression*)gt;
3080 static bool parse_goto(parser_t *parser, ast_expression **out)
3082 ast_goto *gt = NULL;
3083 ast_expression *lbl;
3085 if (!parser_next(parser))
3088 if (parser->tok != TOKEN_IDENT) {
3089 ast_expression *expression;
3091 /* could be an expression i.e computed goto :-) */
3092 if (parser->tok != '(') {
3093 parseerror(parser, "expected label name after `goto`");
3097 /* failed to parse expression for goto */
3098 if (!(expression = parse_expression(parser, false, true)) ||
3099 !(*out = parse_goto_computed(parser, &expression))) {
3100 parseerror(parser, "invalid goto expression");
3101 ast_unref(expression);
3108 /* not computed goto */
3109 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3110 lbl = parser_find_label(parser, gt->name);
3112 if (!ast_istype(lbl, ast_label)) {
3113 parseerror(parser, "internal error: label is not an ast_label");
3117 ast_goto_set_label(gt, (ast_label*)lbl);
3120 vec_push(parser->gotos, gt);
3122 if (!parser_next(parser) || parser->tok != ';') {
3123 parseerror(parser, "semicolon expected after goto label");
3126 if (!parser_next(parser)) {
3127 parseerror(parser, "parse error after goto");
3131 *out = (ast_expression*)gt;
3135 static bool parse_skipwhite(parser_t *parser)
3138 if (!parser_next(parser))
3140 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3141 return parser->tok < TOKEN_ERROR;
3144 static bool parse_eol(parser_t *parser)
3146 if (!parse_skipwhite(parser))
3148 return parser->tok == TOKEN_EOL;
3151 static bool parse_pragma_do(parser_t *parser)
3153 if (!parser_next(parser) ||
3154 parser->tok != TOKEN_IDENT ||
3155 strcmp(parser_tokval(parser), "pragma"))
3157 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3160 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3161 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3165 if (!strcmp(parser_tokval(parser), "noref")) {
3166 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3167 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3170 parser->noref = !!parser_token(parser)->constval.i;
3171 if (!parse_eol(parser)) {
3172 parseerror(parser, "parse error after `noref` pragma");
3178 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3185 static bool parse_pragma(parser_t *parser)
3188 parser->lex->flags.preprocessing = true;
3189 parser->lex->flags.mergelines = true;
3190 rv = parse_pragma_do(parser);
3191 if (parser->tok != TOKEN_EOL) {
3192 parseerror(parser, "junk after pragma");
3195 parser->lex->flags.preprocessing = false;
3196 parser->lex->flags.mergelines = false;
3197 if (!parser_next(parser)) {
3198 parseerror(parser, "parse error after pragma");
3204 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3206 bool noref, is_static;
3208 uint32_t qflags = 0;
3209 ast_value *typevar = NULL;
3210 char *vstring = NULL;
3214 if (parser->tok == TOKEN_IDENT)
3215 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3217 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3219 /* local variable */
3221 parseerror(parser, "cannot declare a variable from here");
3224 if (opts.standard == COMPILER_QCC) {
3225 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3228 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3232 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3234 if (cvq == CV_WRONG)
3236 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3238 else if (parser->tok == TOKEN_KEYWORD)
3240 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3245 if (!parser_next(parser)) {
3246 parseerror(parser, "parse error after __builtin_debug_printtype");
3250 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3252 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3253 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3254 if (!parser_next(parser)) {
3255 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3261 if (!parse_statement(parser, block, out, allow_cases))
3264 con_out("__builtin_debug_printtype: got no output node\n");
3267 ast_type_to_string(*out, ty, sizeof(ty));
3268 con_out("__builtin_debug_printtype: `%s`\n", ty);
3273 else if (!strcmp(parser_tokval(parser), "return"))
3275 return parse_return(parser, block, out);
3277 else if (!strcmp(parser_tokval(parser), "if"))
3279 return parse_if(parser, block, out);
3281 else if (!strcmp(parser_tokval(parser), "while"))
3283 return parse_while(parser, block, out);
3285 else if (!strcmp(parser_tokval(parser), "do"))
3287 return parse_dowhile(parser, block, out);
3289 else if (!strcmp(parser_tokval(parser), "for"))
3291 if (opts.standard == COMPILER_QCC) {
3292 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3295 return parse_for(parser, block, out);
3297 else if (!strcmp(parser_tokval(parser), "break"))
3299 return parse_break_continue(parser, block, out, false);
3301 else if (!strcmp(parser_tokval(parser), "continue"))
3303 return parse_break_continue(parser, block, out, true);
3305 else if (!strcmp(parser_tokval(parser), "switch"))
3307 return parse_switch(parser, block, out);
3309 else if (!strcmp(parser_tokval(parser), "case") ||
3310 !strcmp(parser_tokval(parser), "default"))
3313 parseerror(parser, "unexpected 'case' label");
3318 else if (!strcmp(parser_tokval(parser), "goto"))
3320 return parse_goto(parser, out);
3322 else if (!strcmp(parser_tokval(parser), "typedef"))
3324 if (!parser_next(parser)) {
3325 parseerror(parser, "expected type definition after 'typedef'");
3328 return parse_typedef(parser);
3330 parseerror(parser, "Unexpected keyword");
3333 else if (parser->tok == '{')
3336 inner = parse_block(parser);
3339 *out = (ast_expression*)inner;
3342 else if (parser->tok == ':')
3346 if (!parser_next(parser)) {
3347 parseerror(parser, "expected label name");
3350 if (parser->tok != TOKEN_IDENT) {
3351 parseerror(parser, "label must be an identifier");
3354 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3356 if (!label->undefined) {
3357 parseerror(parser, "label `%s` already defined", label->name);
3360 label->undefined = false;
3363 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3364 vec_push(parser->labels, label);
3366 *out = (ast_expression*)label;
3367 if (!parser_next(parser)) {
3368 parseerror(parser, "parse error after label");
3371 for (i = 0; i < vec_size(parser->gotos); ++i) {
3372 if (!strcmp(parser->gotos[i]->name, label->name)) {
3373 ast_goto_set_label(parser->gotos[i], label);
3374 vec_remove(parser->gotos, i, 1);
3380 else if (parser->tok == ';')
3382 if (!parser_next(parser)) {
3383 parseerror(parser, "parse error after empty statement");
3390 ast_expression *exp = parse_expression(parser, false, false);
3394 if (!ast_side_effects(exp)) {
3395 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3402 static bool parse_block_into(parser_t *parser, ast_block *block)
3406 parser_enterblock(parser);
3408 if (!parser_next(parser)) { /* skip the '{' */
3409 parseerror(parser, "expected function body");
3413 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3415 ast_expression *expr = NULL;
3416 if (parser->tok == '}')
3419 if (!parse_statement(parser, block, &expr, false)) {
3420 /* parseerror(parser, "parse error"); */
3426 if (!ast_block_add_expr(block, expr)) {
3433 if (parser->tok != '}') {
3436 (void)parser_next(parser);
3440 if (!parser_leaveblock(parser))
3442 return retval && !!block;
3445 static ast_block* parse_block(parser_t *parser)
3448 block = ast_block_new(parser_ctx(parser));
3451 if (!parse_block_into(parser, block)) {
3452 ast_block_delete(block);
3458 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3460 if (parser->tok == '{') {
3461 *out = (ast_expression*)parse_block(parser);
3464 return parse_statement(parser, NULL, out, false);
3467 static bool create_vector_members(ast_value *var, ast_member **me)
3470 size_t len = strlen(var->name);
3472 for (i = 0; i < 3; ++i) {
3473 char *name = (char*)mem_a(len+3);
3474 memcpy(name, var->name, len);
3476 name[len+1] = 'x'+i;
3478 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3487 do { ast_member_delete(me[--i]); } while(i);
3491 static bool parse_function_body(parser_t *parser, ast_value *var)
3493 ast_block *block = NULL;
3498 ast_expression *framenum = NULL;
3499 ast_expression *nextthink = NULL;
3500 /* None of the following have to be deleted */
3501 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3502 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3503 bool has_frame_think;
3507 has_frame_think = false;
3508 old = parser->function;
3510 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3511 parseerror(parser, "gotos/labels leaking");
3515 if (var->expression.flags & AST_FLAG_VARIADIC) {
3516 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3517 "variadic function with implementation will not be able to access additional parameters"))
3523 if (parser->tok == '[') {
3524 /* got a frame definition: [ framenum, nextthink ]
3525 * this translates to:
3526 * self.frame = framenum;
3527 * self.nextthink = time + 0.1;
3528 * self.think = nextthink;
3532 fld_think = parser_find_field(parser, "think");
3533 fld_nextthink = parser_find_field(parser, "nextthink");
3534 fld_frame = parser_find_field(parser, "frame");
3535 if (!fld_think || !fld_nextthink || !fld_frame) {
3536 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3537 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3540 gbl_time = parser_find_global(parser, "time");
3541 gbl_self = parser_find_global(parser, "self");
3542 if (!gbl_time || !gbl_self) {
3543 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3544 parseerror(parser, "please declare the following globals: `time`, `self`");
3548 if (!parser_next(parser))
3551 framenum = parse_expression_leave(parser, true, false, false);
3553 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3556 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3557 ast_unref(framenum);
3558 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3562 if (parser->tok != ',') {
3563 ast_unref(framenum);
3564 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3565 parseerror(parser, "Got a %i\n", parser->tok);
3569 if (!parser_next(parser)) {
3570 ast_unref(framenum);
3574 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3576 /* qc allows the use of not-yet-declared functions here
3577 * - this automatically creates a prototype */
3578 ast_value *thinkfunc;
3579 ast_expression *functype = fld_think->expression.next;
3581 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3582 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3583 ast_unref(framenum);
3584 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3588 if (!parser_next(parser)) {
3589 ast_unref(framenum);
3590 ast_delete(thinkfunc);
3594 vec_push(parser->globals, (ast_expression*)thinkfunc);
3595 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3597 nextthink = (ast_expression*)thinkfunc;
3600 nextthink = parse_expression_leave(parser, true, false, false);
3602 ast_unref(framenum);
3603 parseerror(parser, "expected a think-function in [frame,think] notation");
3608 if (!ast_istype(nextthink, ast_value)) {
3609 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3613 if (retval && parser->tok != ']') {
3614 parseerror(parser, "expected closing `]` for [frame,think] notation");
3618 if (retval && !parser_next(parser)) {
3622 if (retval && parser->tok != '{') {
3623 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3628 ast_unref(nextthink);
3629 ast_unref(framenum);
3633 has_frame_think = true;
3636 block = ast_block_new(parser_ctx(parser));
3638 parseerror(parser, "failed to allocate block");
3639 if (has_frame_think) {
3640 ast_unref(nextthink);
3641 ast_unref(framenum);
3646 if (has_frame_think) {
3648 ast_expression *self_frame;
3649 ast_expression *self_nextthink;
3650 ast_expression *self_think;
3651 ast_expression *time_plus_1;
3652 ast_store *store_frame;
3653 ast_store *store_nextthink;
3654 ast_store *store_think;
3656 ctx = parser_ctx(parser);
3657 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3658 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3659 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3661 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3662 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3664 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3665 if (self_frame) ast_delete(self_frame);
3666 if (self_nextthink) ast_delete(self_nextthink);
3667 if (self_think) ast_delete(self_think);
3668 if (time_plus_1) ast_delete(time_plus_1);
3674 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3675 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3676 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3679 ast_delete(self_frame);
3682 if (!store_nextthink) {
3683 ast_delete(self_nextthink);
3687 ast_delete(self_think);
3691 if (store_frame) ast_delete(store_frame);
3692 if (store_nextthink) ast_delete(store_nextthink);
3693 if (store_think) ast_delete(store_think);
3696 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3697 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3698 !ast_block_add_expr(block, (ast_expression*)store_think))
3705 parseerror(parser, "failed to generate code for [frame,think]");
3706 ast_unref(nextthink);
3707 ast_unref(framenum);
3713 parser_enterblock(parser);
3715 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3717 ast_value *param = var->expression.params[parami];
3720 if (param->expression.vtype != TYPE_VECTOR &&
3721 (param->expression.vtype != TYPE_FIELD ||
3722 param->expression.next->expression.vtype != TYPE_VECTOR))
3727 if (!create_vector_members(param, me)) {
3728 ast_block_delete(block);
3732 for (e = 0; e < 3; ++e) {
3733 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3734 ast_block_collect(block, (ast_expression*)me[e]);
3738 func = ast_function_new(ast_ctx(var), var->name, var);
3740 parseerror(parser, "failed to allocate function for `%s`", var->name);
3741 ast_block_delete(block);
3744 vec_push(parser->functions, func);
3746 parser->function = func;
3747 if (!parse_block_into(parser, block)) {
3748 ast_block_delete(block);
3752 vec_push(func->blocks, block);
3754 parser->function = old;
3755 if (!parser_leaveblock(parser))
3757 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3758 parseerror(parser, "internal error: local scopes left");
3762 if (parser->tok == ';')
3763 return parser_next(parser);
3764 else if (opts.standard == COMPILER_QCC)
3765 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3769 vec_pop(parser->functions);
3770 ast_function_delete(func);
3771 var->constval.vfunc = NULL;
3774 (void)!parser_leaveblock(parser);
3775 parser->function = old;
3779 static ast_expression *array_accessor_split(
3784 ast_expression *left,
3785 ast_expression *right
3791 lex_ctx ctx = ast_ctx(array);
3793 if (!left || !right) {
3794 if (left) ast_delete(left);
3795 if (right) ast_delete(right);
3799 cmp = ast_binary_new(ctx, INSTR_LT,
3800 (ast_expression*)index,
3801 (ast_expression*)parser_const_float(parser, middle));
3805 parseerror(parser, "internal error: failed to create comparison for array setter");
3809 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3811 ast_delete(cmp); /* will delete left and right */
3812 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3816 return (ast_expression*)ifthen;
3819 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3821 lex_ctx ctx = ast_ctx(array);
3823 if (from+1 == afterend) {
3824 /* set this value */
3827 ast_array_index *subscript;
3829 int assignop = type_store_instr[value->expression.vtype];
3831 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3832 assignop = INSTR_STORE_V;
3834 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3838 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3840 ast_delete(subscript);
3844 block = ast_block_new(ctx);
3850 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3855 ret = ast_return_new(ctx, NULL);
3861 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3866 return (ast_expression*)block;
3868 ast_expression *left, *right;
3869 size_t diff = afterend - from;
3870 size_t middle = from + diff/2;
3871 left = array_setter_node(parser, array, index, value, from, middle);
3872 right = array_setter_node(parser, array, index, value, middle, afterend);
3873 return array_accessor_split(parser, array, index, middle, left, right);
3877 static ast_expression *array_field_setter_node(
3886 lex_ctx ctx = ast_ctx(array);
3888 if (from+1 == afterend) {
3889 /* set this value */
3892 ast_entfield *entfield;
3893 ast_array_index *subscript;
3895 int assignop = type_storep_instr[value->expression.vtype];
3897 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3898 assignop = INSTR_STOREP_V;
3900 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3904 entfield = ast_entfield_new_force(ctx,
3905 (ast_expression*)entity,
3906 (ast_expression*)subscript,
3907 (ast_expression*)subscript);
3909 ast_delete(subscript);
3913 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3915 ast_delete(entfield);
3919 block = ast_block_new(ctx);
3925 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3930 ret = ast_return_new(ctx, NULL);
3936 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3941 return (ast_expression*)block;
3943 ast_expression *left, *right;
3944 size_t diff = afterend - from;
3945 size_t middle = from + diff/2;
3946 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3947 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3948 return array_accessor_split(parser, array, index, middle, left, right);
3952 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3954 lex_ctx ctx = ast_ctx(array);
3956 if (from+1 == afterend) {
3958 ast_array_index *subscript;
3960 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3964 ret = ast_return_new(ctx, (ast_expression*)subscript);
3966 ast_delete(subscript);
3970 return (ast_expression*)ret;
3972 ast_expression *left, *right;
3973 size_t diff = afterend - from;
3974 size_t middle = from + diff/2;
3975 left = array_getter_node(parser, array, index, from, middle);
3976 right = array_getter_node(parser, array, index, middle, afterend);
3977 return array_accessor_split(parser, array, index, middle, left, right);
3981 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3983 ast_function *func = NULL;
3984 ast_value *fval = NULL;
3985 ast_block *body = NULL;
3987 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3989 parseerror(parser, "failed to create accessor function value");
3993 func = ast_function_new(ast_ctx(array), funcname, fval);
3996 parseerror(parser, "failed to create accessor function node");
4000 body = ast_block_new(ast_ctx(array));
4002 parseerror(parser, "failed to create block for array accessor");
4008 vec_push(func->blocks, body);
4011 vec_push(parser->accessors, fval);
4016 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4018 ast_expression *root = NULL;
4019 ast_value *index = NULL;
4020 ast_value *value = NULL;
4024 if (!ast_istype(array->expression.next, ast_value)) {
4025 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4029 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4031 func = fval->constval.vfunc;
4032 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4034 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4035 value = ast_value_copy((ast_value*)array->expression.next);
4037 if (!index || !value) {
4038 parseerror(parser, "failed to create locals for array accessor");
4041 (void)!ast_value_set_name(value, "value"); /* not important */
4042 vec_push(fval->expression.params, index);
4043 vec_push(fval->expression.params, value);
4045 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
4047 parseerror(parser, "failed to build accessor search tree");
4051 array->setter = fval;
4052 return ast_block_add_expr(func->blocks[0], root);
4054 if (index) ast_delete(index);
4055 if (value) ast_delete(value);
4056 if (root) ast_delete(root);
4062 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4064 ast_expression *root = NULL;
4065 ast_value *entity = NULL;
4066 ast_value *index = NULL;
4067 ast_value *value = NULL;
4071 if (!ast_istype(array->expression.next, ast_value)) {
4072 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4076 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4078 func = fval->constval.vfunc;
4079 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4081 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4082 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4083 value = ast_value_copy((ast_value*)array->expression.next);
4084 if (!entity || !index || !value) {
4085 parseerror(parser, "failed to create locals for array accessor");
4088 (void)!ast_value_set_name(value, "value"); /* not important */
4089 vec_push(fval->expression.params, entity);
4090 vec_push(fval->expression.params, index);
4091 vec_push(fval->expression.params, value);
4093 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4095 parseerror(parser, "failed to build accessor search tree");
4099 array->setter = fval;
4100 return ast_block_add_expr(func->blocks[0], root);
4102 if (entity) ast_delete(entity);
4103 if (index) ast_delete(index);
4104 if (value) ast_delete(value);
4105 if (root) ast_delete(root);
4111 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4113 ast_expression *root = NULL;
4114 ast_value *index = NULL;
4118 /* NOTE: checking array->expression.next rather than elemtype since
4119 * for fields elemtype is a temporary fieldtype.
4121 if (!ast_istype(array->expression.next, ast_value)) {
4122 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4126 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4128 func = fval->constval.vfunc;
4129 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4131 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4134 parseerror(parser, "failed to create locals for array accessor");
4137 vec_push(fval->expression.params, index);
4139 root = array_getter_node(parser, array, index, 0, array->expression.count);
4141 parseerror(parser, "failed to build accessor search tree");
4145 array->getter = fval;
4146 return ast_block_add_expr(func->blocks[0], root);
4148 if (index) ast_delete(index);
4149 if (root) ast_delete(root);
4155 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4156 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4164 bool variadic = false;
4166 ctx = parser_ctx(parser);
4168 /* for the sake of less code we parse-in in this function */
4169 if (!parser_next(parser)) {
4170 parseerror(parser, "expected parameter list");
4176 /* parse variables until we hit a closing paren */
4177 while (parser->tok != ')') {
4179 /* there must be commas between them */
4180 if (parser->tok != ',') {
4181 parseerror(parser, "expected comma or end of parameter list");
4184 if (!parser_next(parser)) {
4185 parseerror(parser, "expected parameter");
4191 if (parser->tok == TOKEN_DOTS) {
4192 /* '...' indicates a varargs function */
4194 if (!parser_next(parser)) {
4195 parseerror(parser, "expected parameter");
4198 if (parser->tok != ')') {
4199 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4205 /* for anything else just parse a typename */
4206 param = parse_typename(parser, NULL, NULL);
4209 vec_push(params, param);
4210 if (param->expression.vtype >= TYPE_VARIANT) {
4211 char tname[1024]; /* typename is reserved in C++ */
4212 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4213 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4219 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4223 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4224 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4227 if (!parser_next(parser)) {
4228 parseerror(parser, "parse error after typename");
4232 /* now turn 'var' into a function type */
4233 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4234 fval->expression.next = (ast_expression*)var;
4236 fval->expression.flags |= AST_FLAG_VARIADIC;
4239 var->expression.params = params;
4246 for (i = 0; i < vec_size(params); ++i)
4247 ast_delete(params[i]);
4252 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4254 ast_expression *cexp;
4255 ast_value *cval, *tmp;
4258 ctx = parser_ctx(parser);
4260 if (!parser_next(parser)) {
4262 parseerror(parser, "expected array-size");
4266 cexp = parse_expression_leave(parser, true, false, false);
4268 if (!cexp || !ast_istype(cexp, ast_value)) {
4272 parseerror(parser, "expected array-size as constant positive integer");
4275 cval = (ast_value*)cexp;
4277 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4278 tmp->expression.next = (ast_expression*)var;
4281 if (cval->expression.vtype == TYPE_INTEGER)
4282 tmp->expression.count = cval->constval.vint;
4283 else if (cval->expression.vtype == TYPE_FLOAT)
4284 tmp->expression.count = cval->constval.vfloat;
4288 parseerror(parser, "array-size must be a positive integer constant");
4293 if (parser->tok != ']') {
4295 parseerror(parser, "expected ']' after array-size");
4298 if (!parser_next(parser)) {
4300 parseerror(parser, "error after parsing array size");
4306 /* Parse a complete typename.
4307 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4308 * but when parsing variables separated by comma
4309 * 'storebase' should point to where the base-type should be kept.
4310 * The base type makes up every bit of type information which comes *before* the
4313 * The following will be parsed in its entirety:
4315 * The 'basetype' in this case is 'void()'
4316 * and if there's a comma after it, say:
4318 * then the type-information 'void()' can be stored in 'storebase'
4320 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4322 ast_value *var, *tmp;
4325 const char *name = NULL;
4326 bool isfield = false;
4327 bool wasarray = false;
4328 size_t morefields = 0;
4330 ctx = parser_ctx(parser);
4332 /* types may start with a dot */
4333 if (parser->tok == '.') {
4335 /* if we parsed a dot we need a typename now */
4336 if (!parser_next(parser)) {
4337 parseerror(parser, "expected typename for field definition");
4341 /* Further dots are handled seperately because they won't be part of the
4344 while (parser->tok == '.') {
4346 if (!parser_next(parser)) {
4347 parseerror(parser, "expected typename for field definition");
4352 if (parser->tok == TOKEN_IDENT)
4353 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4354 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4355 parseerror(parser, "expected typename");
4359 /* generate the basic type value */
4360 if (cached_typedef) {
4361 var = ast_value_copy(cached_typedef);
4362 ast_value_set_name(var, "<type(from_def)>");
4364 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4366 for (; morefields; --morefields) {
4367 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4368 tmp->expression.next = (ast_expression*)var;
4372 /* do not yet turn into a field - remember:
4373 * .void() foo; is a field too
4374 * .void()() foo; is a function
4378 if (!parser_next(parser)) {
4380 parseerror(parser, "parse error after typename");
4384 /* an opening paren now starts the parameter-list of a function
4385 * this is where original-QC has parameter lists.
4386 * We allow a single parameter list here.
4387 * Much like fteqcc we don't allow `float()() x`
4389 if (parser->tok == '(') {
4390 var = parse_parameter_list(parser, var);
4395 /* store the base if requested */
4397 *storebase = ast_value_copy(var);
4399 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4400 tmp->expression.next = (ast_expression*)*storebase;
4405 /* there may be a name now */
4406 if (parser->tok == TOKEN_IDENT) {
4407 name = util_strdup(parser_tokval(parser));
4409 if (!parser_next(parser)) {
4411 parseerror(parser, "error after variable or field declaration");
4416 /* now this may be an array */
4417 if (parser->tok == '[') {
4419 var = parse_arraysize(parser, var);
4424 /* This is the point where we can turn it into a field */
4426 /* turn it into a field if desired */
4427 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4428 tmp->expression.next = (ast_expression*)var;
4432 /* now there may be function parens again */
4433 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4434 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4435 if (parser->tok == '(' && wasarray)
4436 parseerror(parser, "arrays as part of a return type is not supported");
4437 while (parser->tok == '(') {
4438 var = parse_parameter_list(parser, var);
4447 /* finally name it */
4449 if (!ast_value_set_name(var, name)) {
4451 parseerror(parser, "internal error: failed to set name");
4454 /* free the name, ast_value_set_name duplicates */
4461 static bool parse_typedef(parser_t *parser)
4463 ast_value *typevar, *oldtype;
4464 ast_expression *old;
4466 typevar = parse_typename(parser, NULL, NULL);
4471 if ( (old = parser_find_var(parser, typevar->name)) ) {
4472 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4473 " -> `%s` has been declared here: %s:%i",
4474 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4475 ast_delete(typevar);
4479 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4480 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4481 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4482 ast_delete(typevar);
4486 vec_push(parser->_typedefs, typevar);
4487 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4489 if (parser->tok != ';') {
4490 parseerror(parser, "expected semicolon after typedef");
4493 if (!parser_next(parser)) {
4494 parseerror(parser, "parse error after typedef");
4501 static const char *cvq_to_str(int cvq) {
4503 case CV_NONE: return "none";
4504 case CV_VAR: return "`var`";
4505 case CV_CONST: return "`const`";
4506 default: return "<INVALID>";
4510 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4513 if (proto->cvq != var->cvq) {
4514 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4515 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4516 parser->tok == '='))
4518 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4519 "`%s` declared with different qualifiers: %s\n"
4520 " -> previous declaration here: %s:%i uses %s",
4521 var->name, cvq_to_str(var->cvq),
4522 ast_ctx(proto).file, ast_ctx(proto).line,
4523 cvq_to_str(proto->cvq));
4526 av = (var ->expression.flags & AST_FLAG_NORETURN);
4527 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4529 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4530 "`%s` declared with different attributes%s\n"
4531 " -> previous declaration here: %s:%i",
4532 var->name, (av ? ": noreturn" : ""),
4533 ast_ctx(proto).file, ast_ctx(proto).line,
4534 (ao ? ": noreturn" : ""));
4539 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)
4543 ast_expression *old;
4547 ast_value *basetype = NULL;
4549 bool isparam = false;
4550 bool isvector = false;
4551 bool cleanvar = true;
4552 bool wasarray = false;
4556 if (!localblock && is_static)
4557 parseerror(parser, "`static` qualifier is not supported in global scope");
4559 /* get the first complete variable */
4560 var = parse_typename(parser, &basetype, cached_typedef);
4563 ast_delete(basetype);
4571 /* Part 0: finish the type */
4572 if (parser->tok == '(') {
4573 if (opts.standard == COMPILER_QCC)
4574 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4575 var = parse_parameter_list(parser, var);
4581 /* we only allow 1-dimensional arrays */
4582 if (parser->tok == '[') {
4584 var = parse_arraysize(parser, var);
4590 if (parser->tok == '(' && wasarray) {
4591 parseerror(parser, "arrays as part of a return type is not supported");
4592 /* we'll still parse the type completely for now */
4594 /* for functions returning functions */
4595 while (parser->tok == '(') {
4596 if (opts.standard == COMPILER_QCC)
4597 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4598 var = parse_parameter_list(parser, var);
4605 var->cvq = qualifier;
4606 var->expression.flags |= qflags;
4607 if (var->expression.flags & AST_FLAG_DEPRECATED)
4608 var->desc = vstring;
4611 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4612 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4613 * is then filled with the previous definition and the parameter-names replaced.
4615 if (!strcmp(var->name, "nil")) {
4616 if (OPTS_FLAG(UNTYPED_NIL)) {
4617 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4618 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4620 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4623 /* Deal with end_sys_ vars */
4625 if (!strcmp(var->name, "end_sys_globals")) {
4627 parser->crc_globals = vec_size(parser->globals);
4630 else if (!strcmp(var->name, "end_sys_fields")) {
4632 parser->crc_fields = vec_size(parser->fields);
4635 if (was_end && var->expression.vtype == TYPE_FIELD) {
4636 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4637 "global '%s' hint should not be a field",
4638 parser_tokval(parser)))
4645 if (!nofields && var->expression.vtype == TYPE_FIELD)
4647 /* deal with field declarations */
4648 old = parser_find_field(parser, var->name);
4650 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4651 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4660 parseerror(parser, "field `%s` already declared here: %s:%i",
4661 var->name, ast_ctx(old).file, ast_ctx(old).line);
4666 if (opts.standard == COMPILER_QCC &&
4667 (old = parser_find_global(parser, var->name)))
4669 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4670 parseerror(parser, "field `%s` already declared here: %s:%i",
4671 var->name, ast_ctx(old).file, ast_ctx(old).line);
4678 /* deal with other globals */
4679 old = parser_find_global(parser, var->name);
4680 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4682 /* This is a function which had a prototype */
4683 if (!ast_istype(old, ast_value)) {
4684 parseerror(parser, "internal error: prototype is not an ast_value");
4688 proto = (ast_value*)old;
4689 proto->desc = var->desc;
4690 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4691 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4693 ast_ctx(proto).file, ast_ctx(proto).line);
4697 /* we need the new parameter-names */
4698 for (i = 0; i < vec_size(proto->expression.params); ++i)
4699 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4700 if (!parser_check_qualifiers(parser, var, proto)) {
4707 proto->expression.flags |= var->expression.flags;
4715 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4716 "global `%s` already declared here: %s:%i",
4717 var->name, ast_ctx(old).file, ast_ctx(old).line))
4722 proto = (ast_value*)old;
4723 if (!ast_istype(old, ast_value)) {
4724 parseerror(parser, "internal error: not an ast_value");
4729 if (!parser_check_qualifiers(parser, var, proto)) {
4734 proto->expression.flags |= var->expression.flags;
4738 if (opts.standard == COMPILER_QCC &&
4739 (old = parser_find_field(parser, var->name)))
4741 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4742 parseerror(parser, "global `%s` already declared here: %s:%i",
4743 var->name, ast_ctx(old).file, ast_ctx(old).line);
4750 else /* it's not a global */
4752 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4753 if (old && !isparam) {
4754 parseerror(parser, "local `%s` already declared here: %s:%i",
4755 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4759 old = parser_find_local(parser, var->name, 0, &isparam);
4760 if (old && isparam) {
4761 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4762 "local `%s` is shadowing a parameter", var->name))
4764 parseerror(parser, "local `%s` already declared here: %s:%i",
4765 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4769 if (opts.standard != COMPILER_GMQCC) {
4777 /* in a noref section we simply bump the usecount */
4778 if (noref || parser->noref)
4782 * Create the global/local, and deal with vector types.
4785 if (var->expression.vtype == TYPE_VECTOR)
4787 else if (var->expression.vtype == TYPE_FIELD &&
4788 var->expression.next->expression.vtype == TYPE_VECTOR)
4792 if (!create_vector_members(var, me)) {
4799 /* deal with global variables, fields, functions */
4800 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4801 var->isfield = true;
4802 vec_push(parser->fields, (ast_expression*)var);
4803 util_htset(parser->htfields, var->name, var);
4805 for (i = 0; i < 3; ++i) {
4806 vec_push(parser->fields, (ast_expression*)me[i]);
4807 util_htset(parser->htfields, me[i]->name, me[i]);
4812 vec_push(parser->globals, (ast_expression*)var);
4813 util_htset(parser->htglobals, var->name, var);
4815 for (i = 0; i < 3; ++i) {
4816 vec_push(parser->globals, (ast_expression*)me[i]);
4817 util_htset(parser->htglobals, me[i]->name, me[i]);
4823 /* a static adds itself to be generated like any other global
4824 * but is added to the local namespace instead
4826 char *defname = NULL;
4827 size_t prefix_len, ln;
4829 ln = strlen(parser->function->name);
4830 vec_append(defname, ln, parser->function->name);
4832 vec_append(defname, 2, "::");
4833 /* remember the length up to here */
4834 prefix_len = vec_size(defname);
4836 /* Add it to the local scope */
4837 util_htset(vec_last(parser->variables), var->name, (void*)var);
4841 vec_last(parser->correct_variables),
4842 &vec_last(parser->correct_variables_score),
4846 /* now rename the global */
4847 ln = strlen(var->name);
4848 vec_append(defname, ln, var->name);
4849 ast_value_set_name(var, defname);
4851 /* push it to the to-be-generated globals */
4852 vec_push(parser->globals, (ast_expression*)var);
4854 /* same game for the vector members */
4856 for (i = 0; i < 3; ++i) {
4857 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4861 vec_last(parser->correct_variables),
4862 &vec_last(parser->correct_variables_score),
4866 vec_shrinkto(defname, prefix_len);
4867 ln = strlen(me[i]->name);
4868 vec_append(defname, ln, me[i]->name);
4869 ast_member_set_name(me[i], defname);
4871 vec_push(parser->globals, (ast_expression*)me[i]);
4876 vec_push(localblock->locals, var);
4877 parser_addlocal(parser, var->name, (ast_expression*)var);
4879 for (i = 0; i < 3; ++i) {
4880 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4881 ast_block_collect(localblock, (ast_expression*)me[i]);
4887 me[0] = me[1] = me[2] = NULL;
4892 if (var->expression.vtype == TYPE_ARRAY) {
4894 snprintf(name, sizeof(name), "%s##SET", var->name);
4895 if (!parser_create_array_setter(parser, var, name))
4897 snprintf(name, sizeof(name), "%s##GET", var->name);
4898 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4901 else if (!localblock && !nofields &&
4902 var->expression.vtype == TYPE_FIELD &&
4903 var->expression.next->expression.vtype == TYPE_ARRAY)
4906 ast_expression *telem;
4908 ast_value *array = (ast_value*)var->expression.next;
4910 if (!ast_istype(var->expression.next, ast_value)) {
4911 parseerror(parser, "internal error: field element type must be an ast_value");
4915 snprintf(name, sizeof(name), "%s##SETF", var->name);
4916 if (!parser_create_array_field_setter(parser, array, name))
4919 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4920 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4921 tfield->expression.next = telem;
4922 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4923 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4931 if (parser->tok == ';') {
4932 ast_delete(basetype);
4933 if (!parser_next(parser)) {
4934 parseerror(parser, "error after variable declaration");
4940 if (parser->tok == ',')
4944 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4947 parseerror(parser, "missing comma or semicolon while parsing variables");
4951 if (localblock && opts.standard == COMPILER_QCC) {
4952 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4953 "initializing expression turns variable `%s` into a constant in this standard",
4960 if (parser->tok != '{') {
4961 if (parser->tok != '=') {
4962 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4966 if (!parser_next(parser)) {
4967 parseerror(parser, "error parsing initializer");
4971 else if (opts.standard == COMPILER_QCC) {
4972 parseerror(parser, "expected '=' before function body in this standard");
4975 if (parser->tok == '#') {
4976 ast_function *func = NULL;
4979 parseerror(parser, "cannot declare builtins within functions");
4982 if (var->expression.vtype != TYPE_FUNCTION) {
4983 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4986 if (!parser_next(parser)) {
4987 parseerror(parser, "expected builtin number");
4990 if (parser->tok != TOKEN_INTCONST) {
4991 parseerror(parser, "builtin number must be an integer constant");
4994 if (parser_token(parser)->constval.i < 0) {
4995 parseerror(parser, "builtin number must be an integer greater than zero");
4999 if (var->hasvalue) {
5000 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5001 "builtin `%s` has already been defined\n"
5002 " -> previous declaration here: %s:%i",
5003 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5007 func = ast_function_new(ast_ctx(var), var->name, var);
5009 parseerror(parser, "failed to allocate function for `%s`", var->name);
5012 vec_push(parser->functions, func);
5014 func->builtin = -parser_token(parser)->constval.i-1;
5017 if (!parser_next(parser)) {
5018 parseerror(parser, "expected comma or semicolon");
5020 ast_function_delete(func);
5021 var->constval.vfunc = NULL;
5025 else if (parser->tok == '{' || parser->tok == '[')
5028 parseerror(parser, "cannot declare functions within functions");
5033 ast_ctx(proto) = parser_ctx(parser);
5035 if (!parse_function_body(parser, var))
5037 ast_delete(basetype);
5038 for (i = 0; i < vec_size(parser->gotos); ++i)
5039 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5040 vec_free(parser->gotos);
5041 vec_free(parser->labels);
5044 ast_expression *cexp;
5047 cexp = parse_expression_leave(parser, true, false, false);
5052 cval = (ast_value*)cexp;
5053 if (cval != parser->nil &&
5054 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5057 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5061 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5062 qualifier != CV_VAR)
5064 var->cvq = CV_CONST;
5066 if (cval == parser->nil)
5067 var->expression.flags |= AST_FLAG_INITIALIZED;
5070 var->hasvalue = true;
5071 if (cval->expression.vtype == TYPE_STRING)
5072 var->constval.vstring = parser_strdup(cval->constval.vstring);
5073 else if (cval->expression.vtype == TYPE_FIELD)
5074 var->constval.vfield = cval;
5076 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5082 shunt sy = { NULL, NULL };
5085 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5086 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5087 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5088 if (!parser_sy_apply_operator(parser, &sy))
5091 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5092 parseerror(parser, "internal error: leaked operands");
5093 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5103 if (parser->tok == ',') {
5104 if (!parser_next(parser)) {
5105 parseerror(parser, "expected another variable");
5109 if (parser->tok != TOKEN_IDENT) {
5110 parseerror(parser, "expected another variable");
5113 var = ast_value_copy(basetype);
5115 ast_value_set_name(var, parser_tokval(parser));
5116 if (!parser_next(parser)) {
5117 parseerror(parser, "error parsing variable declaration");
5123 if (parser->tok != ';') {
5124 parseerror(parser, "missing semicolon after variables");
5128 if (!parser_next(parser)) {
5129 parseerror(parser, "parse error after variable declaration");
5133 ast_delete(basetype);
5137 if (cleanvar && var)
5139 ast_delete(basetype);
5143 ast_delete(basetype);
5144 if (cleanvar && var)
5146 if (me[0]) ast_member_delete(me[0]);
5147 if (me[1]) ast_member_delete(me[1]);
5148 if (me[2]) ast_member_delete(me[2]);
5152 static bool parser_global_statement(parser_t *parser)
5156 bool is_static = false;
5157 uint32_t qflags = 0;
5158 ast_value *istype = NULL;
5159 char *vstring = NULL;
5161 if (parser->tok == TOKEN_IDENT)
5162 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5164 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5166 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5168 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5170 if (cvq == CV_WRONG)
5172 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5174 else if (parser->tok == TOKEN_KEYWORD)
5176 if (!strcmp(parser_tokval(parser), "typedef")) {
5177 if (!parser_next(parser)) {
5178 parseerror(parser, "expected type definition after 'typedef'");
5181 return parse_typedef(parser);
5183 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5186 else if (parser->tok == '#')
5188 return parse_pragma(parser);
5190 else if (parser->tok == '$')
5192 if (!parser_next(parser)) {
5193 parseerror(parser, "parse error");
5199 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5205 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5207 return util_crc16(old, str, strlen(str));
5210 static void progdefs_crc_file(const char *str)
5212 /* write to progdefs.h here */
5216 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5218 old = progdefs_crc_sum(old, str);
5219 progdefs_crc_file(str);
5223 static void generate_checksum(parser_t *parser)
5225 uint16_t crc = 0xFFFF;
5229 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5230 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5232 progdefs_crc_file("\tint\tpad;\n");
5233 progdefs_crc_file("\tint\tofs_return[3];\n");
5234 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5235 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5236 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5237 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5238 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5239 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5240 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5241 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5243 for (i = 0; i < parser->crc_globals; ++i) {
5244 if (!ast_istype(parser->globals[i], ast_value))
5246 value = (ast_value*)(parser->globals[i]);
5247 switch (value->expression.vtype) {
5248 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5249 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5250 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5251 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5253 crc = progdefs_crc_both(crc, "\tint\t");
5256 crc = progdefs_crc_both(crc, value->name);
5257 crc = progdefs_crc_both(crc, ";\n");
5259 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5260 for (i = 0; i < parser->crc_fields; ++i) {
5261 if (!ast_istype(parser->fields[i], ast_value))
5263 value = (ast_value*)(parser->fields[i]);
5264 switch (value->expression.next->expression.vtype) {
5265 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5266 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5267 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5268 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5270 crc = progdefs_crc_both(crc, "\tint\t");
5273 crc = progdefs_crc_both(crc, value->name);
5274 crc = progdefs_crc_both(crc, ";\n");
5276 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5281 static parser_t *parser;
5288 parser = (parser_t*)mem_a(sizeof(parser_t));
5292 memset(parser, 0, sizeof(*parser));
5294 for (i = 0; i < operator_count; ++i) {
5295 if (operators[i].id == opid1('=')) {
5296 parser->assign_op = operators+i;
5300 if (!parser->assign_op) {
5301 printf("internal error: initializing parser: failed to find assign operator\n");
5306 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5307 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5308 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5309 vec_push(parser->_blocktypedefs, 0);
5311 empty_ctx.file = "<internal>";
5313 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5314 parser->nil->cvq = CV_CONST;
5315 if (OPTS_FLAG(UNTYPED_NIL))
5316 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5320 bool parser_compile()
5322 /* initial lexer/parser state */
5323 parser->lex->flags.noops = true;
5325 if (parser_next(parser))
5327 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5329 if (!parser_global_statement(parser)) {
5330 if (parser->tok == TOKEN_EOF)
5331 parseerror(parser, "unexpected eof");
5332 else if (compile_errors)
5333 parseerror(parser, "there have been errors, bailing out");
5334 lex_close(parser->lex);
5340 parseerror(parser, "parse error");
5341 lex_close(parser->lex);
5346 lex_close(parser->lex);
5349 return !compile_errors;
5352 bool parser_compile_file(const char *filename)
5354 parser->lex = lex_open(filename);
5356 con_err("failed to open file \"%s\"\n", filename);
5359 return parser_compile();
5362 bool parser_compile_string(const char *name, const char *str, size_t len)
5364 parser->lex = lex_open_string(str, len, name);
5366 con_err("failed to create lexer for string \"%s\"\n", name);
5369 return parser_compile();
5372 void parser_cleanup()
5375 for (i = 0; i < vec_size(parser->accessors); ++i) {
5376 ast_delete(parser->accessors[i]->constval.vfunc);
5377 parser->accessors[i]->constval.vfunc = NULL;
5378 ast_delete(parser->accessors[i]);
5380 for (i = 0; i < vec_size(parser->functions); ++i) {
5381 ast_delete(parser->functions[i]);
5383 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5384 ast_delete(parser->imm_vector[i]);
5386 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5387 ast_delete(parser->imm_string[i]);
5389 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5390 ast_delete(parser->imm_float[i]);
5392 for (i = 0; i < vec_size(parser->fields); ++i) {
5393 ast_delete(parser->fields[i]);
5395 for (i = 0; i < vec_size(parser->globals); ++i) {
5396 ast_delete(parser->globals[i]);
5398 vec_free(parser->accessors);
5399 vec_free(parser->functions);
5400 vec_free(parser->imm_vector);
5401 vec_free(parser->imm_string);
5402 vec_free(parser->imm_float);
5403 vec_free(parser->globals);
5404 vec_free(parser->fields);
5406 for (i = 0; i < vec_size(parser->variables); ++i)
5407 util_htdel(parser->variables[i]);
5408 vec_free(parser->variables);
5409 vec_free(parser->_blocklocals);
5410 vec_free(parser->_locals);
5413 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5414 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5416 for (i = 0; i < vec_size(parser->correct_variables_score); ++i) {
5417 vec_free(parser->correct_variables_score[i]);
5419 vec_free(parser->correct_variables);
5420 vec_free(parser->correct_variables_score);
5423 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5424 ast_delete(parser->_typedefs[i]);
5425 vec_free(parser->_typedefs);
5426 for (i = 0; i < vec_size(parser->typedefs); ++i)
5427 util_htdel(parser->typedefs[i]);
5428 vec_free(parser->typedefs);
5429 vec_free(parser->_blocktypedefs);
5431 vec_free(parser->_block_ctx);
5433 vec_free(parser->labels);
5434 vec_free(parser->gotos);
5435 vec_free(parser->breaks);
5436 vec_free(parser->continues);
5438 ast_value_delete(parser->nil);
5443 bool parser_finish(const char *output)
5449 if (compile_errors) {
5450 con_out("*** there were compile errors\n");
5454 ir = ir_builder_new("gmqcc_out");
5456 con_out("failed to allocate builder\n");
5460 for (i = 0; i < vec_size(parser->fields); ++i) {
5463 if (!ast_istype(parser->fields[i], ast_value))
5465 field = (ast_value*)parser->fields[i];
5466 hasvalue = field->hasvalue;
5467 field->hasvalue = false;
5468 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5469 con_out("failed to generate field %s\n", field->name);
5470 ir_builder_delete(ir);
5475 ast_expression *subtype;
5476 field->hasvalue = true;
5477 subtype = field->expression.next;
5478 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5479 if (subtype->expression.vtype == TYPE_FIELD)
5480 ifld->fieldtype = subtype->expression.next->expression.vtype;
5481 else if (subtype->expression.vtype == TYPE_FUNCTION)
5482 ifld->outtype = subtype->expression.next->expression.vtype;
5483 (void)!ir_value_set_field(field->ir_v, ifld);
5486 for (i = 0; i < vec_size(parser->globals); ++i) {
5488 if (!ast_istype(parser->globals[i], ast_value))
5490 asvalue = (ast_value*)(parser->globals[i]);
5491 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5492 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5493 "unused global: `%s`", asvalue->name);
5495 if (!ast_global_codegen(asvalue, ir, false)) {
5496 con_out("failed to generate global %s\n", asvalue->name);
5497 ir_builder_delete(ir);
5501 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5502 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5503 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5504 ir_builder_delete(ir);
5508 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5509 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5510 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5511 ir_builder_delete(ir);
5515 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5516 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5517 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5518 ir_builder_delete(ir);
5522 for (i = 0; i < vec_size(parser->globals); ++i) {
5524 if (!ast_istype(parser->globals[i], ast_value))
5526 asvalue = (ast_value*)(parser->globals[i]);
5527 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5529 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5530 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5531 "uninitialized constant: `%s`",
5533 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5534 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5535 "uninitialized global: `%s`",
5538 if (!ast_generate_accessors(asvalue, ir)) {
5539 ir_builder_delete(ir);
5543 for (i = 0; i < vec_size(parser->fields); ++i) {
5545 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5547 if (!ast_istype((ast_expression*)asvalue, ast_value))
5549 if (asvalue->expression.vtype != TYPE_ARRAY)
5551 if (!ast_generate_accessors(asvalue, ir)) {
5552 ir_builder_delete(ir);
5556 for (i = 0; i < vec_size(parser->functions); ++i) {
5557 if (!ast_function_codegen(parser->functions[i], ir)) {
5558 con_out("failed to generate function %s\n", parser->functions[i]->name);
5559 ir_builder_delete(ir);
5564 ir_builder_dump(ir, con_out);
5565 for (i = 0; i < vec_size(parser->functions); ++i) {
5566 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5567 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5568 ir_builder_delete(ir);
5573 if (compile_Werrors) {
5574 con_out("*** there were warnings treated as errors\n");
5575 compile_show_werrors();
5581 ir_builder_dump(ir, con_out);
5583 generate_checksum(parser);
5585 if (!ir_builder_generate(ir, output)) {
5586 con_out("*** failed to generate output file\n");
5587 ir_builder_delete(ir);
5592 ir_builder_delete(ir);