5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define PARSER_HT_FIELDS 0
30 #define PARSER_HT_GLOBALS 1
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 1024
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
59 ast_function *function;
61 /* All the labels the function defined...
62 * Should they be in ast_function instead?
67 /* A list of hashtables for each scope */
73 /* not to be used directly, we use the hash table */
74 ast_expression **_locals;
76 ast_value **_typedefs;
77 size_t *_blocktypedefs;
82 /* we store the '=' operator info */
83 const oper_info *assign_op;
85 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
86 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
87 * anything else: type error
91 /* Keep track of our ternary vs parenthesis nesting state.
92 * If we reach a 'comma' operator in a ternary without a paren,
93 * we shall trigger -Wternary-precedence.
95 enum { POT_PAREN, POT_TERNARY1, POT_TERNARY2 } *pot;
101 static void parser_enterblock(parser_t *parser);
102 static bool parser_leaveblock(parser_t *parser);
103 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
104 static bool parse_typedef(parser_t *parser);
105 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref);
106 static ast_block* parse_block(parser_t *parser);
107 static bool parse_block_into(parser_t *parser, ast_block *block);
108 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
109 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
110 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
111 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
113 static void parseerror(parser_t *parser, const char *fmt, ...)
120 con_vprintmsg(LVL_ERROR, parser->lex->tok.ctx.file, parser->lex->tok.ctx.line, "parse error", fmt, ap);
124 /* returns true if it counts as an error */
125 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
130 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
135 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
140 r = vcompile_warning(ctx, warntype, fmt, ap);
145 /**********************************************************************
146 * some maths used for constant folding
149 vector vec3_add(vector a, vector b)
158 vector vec3_sub(vector a, vector b)
167 qcfloat vec3_mulvv(vector a, vector b)
169 return (a.x * b.x + a.y * b.y + a.z * b.z);
172 vector vec3_mulvf(vector a, float b)
181 /**********************************************************************
185 bool parser_next(parser_t *parser)
187 /* lex_do kills the previous token */
188 parser->tok = lex_do(parser->lex);
189 if (parser->tok == TOKEN_EOF)
191 if (parser->tok >= TOKEN_ERROR) {
192 parseerror(parser, "lex error");
198 #define parser_tokval(p) ((p)->lex->tok.value)
199 #define parser_token(p) (&((p)->lex->tok))
200 #define parser_ctx(p) ((p)->lex->tok.ctx)
202 static ast_value* parser_const_float(parser_t *parser, double d)
206 for (i = 0; i < vec_size(parser->imm_float); ++i) {
207 const double compare = parser->imm_float[i]->constval.vfloat;
208 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
209 return parser->imm_float[i];
211 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
213 out->hasvalue = true;
214 out->constval.vfloat = d;
215 vec_push(parser->imm_float, out);
219 static ast_value* parser_const_float_0(parser_t *parser)
221 if (!parser->imm_float_zero)
222 parser->imm_float_zero = parser_const_float(parser, 0);
223 return parser->imm_float_zero;
226 static ast_value* parser_const_float_1(parser_t *parser)
228 if (!parser->imm_float_one)
229 parser->imm_float_one = parser_const_float(parser, 1);
230 return parser->imm_float_one;
233 static char *parser_strdup(const char *str)
236 /* actually dup empty strings */
237 char *out = mem_a(1);
241 return util_strdup(str);
244 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
248 for (i = 0; i < vec_size(parser->imm_string); ++i) {
249 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
250 return parser->imm_string[i];
254 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
255 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
257 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
259 out->hasvalue = true;
260 out->constval.vstring = parser_strdup(str);
261 vec_push(parser->imm_string, out);
265 static ast_value* parser_const_vector(parser_t *parser, vector v)
269 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
270 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
271 return parser->imm_vector[i];
273 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
275 out->hasvalue = true;
276 out->constval.vvec = v;
277 vec_push(parser->imm_vector, out);
281 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
287 return parser_const_vector(parser, v);
290 static ast_value* parser_const_vector_0(parser_t *parser)
292 if (!parser->imm_vector_zero)
293 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
294 return parser->imm_vector_zero;
297 static ast_expression* parser_find_field(parser_t *parser, const char *name)
299 return util_htget(parser->htfields, name);
302 static ast_expression* parser_find_global(parser_t *parser, const char *name)
304 return util_htget(parser->htglobals, name);
307 static ast_expression* parser_find_param(parser_t *parser, const char *name)
311 if (!parser->function)
313 fun = parser->function->vtype;
314 for (i = 0; i < vec_size(fun->expression.params); ++i) {
315 if (!strcmp(fun->expression.params[i]->name, name))
316 return (ast_expression*)(fun->expression.params[i]);
321 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
326 hash = util_hthash(parser->htglobals, name);
329 for (i = vec_size(parser->variables); i > upto;) {
331 if ( (e = util_htgeth(parser->variables[i], name, hash)) )
335 return parser_find_param(parser, name);
338 static ast_expression* parser_find_var(parser_t *parser, const char *name)
342 v = parser_find_local(parser, name, 0, &dummy);
343 if (!v) v = parser_find_global(parser, name);
347 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
351 hash = util_hthash(parser->typedefs[0], name);
353 for (i = vec_size(parser->typedefs); i > upto;) {
355 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
363 size_t etype; /* 0 = expression, others are operators */
367 ast_block *block; /* for commas and function calls */
376 #define SY_PAREN_EXPR '('
377 #define SY_PAREN_FUNC 'f'
378 #define SY_PAREN_INDEX '['
379 #define SY_PAREN_TERNARY '?'
381 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
392 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
396 e.out = (ast_expression*)v;
403 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
405 e.etype = 1 + (op - operators);
414 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
426 # define DEBUGSHUNTDO(x) x
428 # define DEBUGSHUNTDO(x)
431 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
432 * so we need to rotate it to become ent.(foo[n]).
434 static bool rotate_entfield_array_index_nodes(ast_expression **out)
436 ast_array_index *index;
437 ast_entfield *entfield;
441 ast_expression *entity;
443 lex_ctx ctx = ast_ctx(*out);
445 if (!ast_istype(*out, ast_array_index))
447 index = (ast_array_index*)*out;
449 if (!ast_istype(index->array, ast_entfield))
451 entfield = (ast_entfield*)index->array;
453 if (!ast_istype(entfield->field, ast_value))
455 field = (ast_value*)entfield->field;
458 entity = entfield->entity;
462 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
463 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
464 *out = (ast_expression*)entfield;
469 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
473 ast_expression *out = NULL;
474 ast_expression *exprs[3];
475 ast_block *blocks[3];
476 ast_value *asvalue[3];
477 ast_binstore *asbinstore;
478 size_t i, assignop, addop, subop;
479 qcint generated_op = 0;
484 if (!vec_size(sy->ops)) {
485 parseerror(parser, "internal error: missing operator");
489 if (vec_last(sy->ops).paren) {
490 parseerror(parser, "unmatched parenthesis");
494 op = &operators[vec_last(sy->ops).etype - 1];
495 ctx = vec_last(sy->ops).ctx;
497 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
499 if (vec_size(sy->out) < op->operands) {
500 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
501 op->op, (int)op->id);
505 vec_shrinkby(sy->ops, 1);
507 /* op(:?) has no input and no output */
511 vec_shrinkby(sy->out, op->operands);
512 for (i = 0; i < op->operands; ++i) {
513 exprs[i] = sy->out[vec_size(sy->out)+i].out;
514 blocks[i] = sy->out[vec_size(sy->out)+i].block;
515 asvalue[i] = (ast_value*)exprs[i];
518 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
519 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
523 #define NotSameType(T) \
524 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
525 exprs[0]->expression.vtype != T)
526 #define CanConstFold1(A) \
527 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST))
528 #define CanConstFold(A, B) \
529 (CanConstFold1(A) && CanConstFold1(B))
530 #define ConstV(i) (asvalue[(i)]->constval.vvec)
531 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
532 #define ConstS(i) (asvalue[(i)]->constval.vstring)
536 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
540 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
541 if (exprs[1]->expression.vtype != TYPE_FIELD) {
542 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
545 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
547 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
548 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
552 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
558 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
559 !(exprs[0]->expression.vtype == TYPE_FIELD &&
560 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
562 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
563 parseerror(parser, "cannot index value of type %s", ty1);
566 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
567 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
568 parseerror(parser, "index must be of type float, not %s", ty1);
571 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
572 if (rotate_entfield_array_index_nodes(&out))
575 /* This is not broken in fteqcc anymore */
576 if (opts.standard != COMPILER_GMQCC) {
577 /* this error doesn't need to make us bail out */
578 (void)!parsewarning(parser, WARN_EXTENSIONS,
579 "accessing array-field members of an entity without parenthesis\n"
580 " -> this is an extension from -std=gmqcc");
588 if (!ast_block_add_expr(blocks[0], exprs[1]))
591 blocks[0] = ast_block_new(ctx);
592 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
593 !ast_block_add_expr(blocks[0], exprs[1]))
598 if (!ast_block_set_type(blocks[0], exprs[1]))
601 vec_push(sy->out, syblock(ctx, blocks[0]));
608 switch (exprs[0]->expression.vtype) {
610 if (CanConstFold1(exprs[0]))
611 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
613 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
614 (ast_expression*)parser_const_float_0(parser),
618 if (CanConstFold1(exprs[0]))
619 out = (ast_expression*)parser_const_vector_f(parser,
620 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
622 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
623 (ast_expression*)parser_const_vector_0(parser),
627 parseerror(parser, "invalid types used in expression: cannot negate type %s",
628 type_name[exprs[0]->expression.vtype]);
634 switch (exprs[0]->expression.vtype) {
636 if (CanConstFold1(exprs[0]))
637 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
639 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
642 if (CanConstFold1(exprs[0]))
643 out = (ast_expression*)parser_const_float(parser,
644 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
646 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
649 if (CanConstFold1(exprs[0]))
650 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
652 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
654 /* we don't constant-fold NOT for these types */
656 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
659 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
662 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
663 type_name[exprs[0]->expression.vtype]);
669 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
670 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
672 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
673 type_name[exprs[0]->expression.vtype],
674 type_name[exprs[1]->expression.vtype]);
677 switch (exprs[0]->expression.vtype) {
679 if (CanConstFold(exprs[0], exprs[1]))
681 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
684 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
687 if (CanConstFold(exprs[0], exprs[1]))
688 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
690 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
693 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
694 type_name[exprs[0]->expression.vtype],
695 type_name[exprs[1]->expression.vtype]);
700 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
701 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
703 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
704 type_name[exprs[1]->expression.vtype],
705 type_name[exprs[0]->expression.vtype]);
708 switch (exprs[0]->expression.vtype) {
710 if (CanConstFold(exprs[0], exprs[1]))
711 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
713 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
716 if (CanConstFold(exprs[0], exprs[1]))
717 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
719 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
722 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
723 type_name[exprs[1]->expression.vtype],
724 type_name[exprs[0]->expression.vtype]);
729 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
730 exprs[0]->expression.vtype != TYPE_VECTOR &&
731 exprs[0]->expression.vtype != TYPE_FLOAT &&
732 exprs[1]->expression.vtype != TYPE_VECTOR &&
733 exprs[1]->expression.vtype != TYPE_FLOAT)
735 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
736 type_name[exprs[1]->expression.vtype],
737 type_name[exprs[0]->expression.vtype]);
740 switch (exprs[0]->expression.vtype) {
742 if (exprs[1]->expression.vtype == TYPE_VECTOR)
744 if (CanConstFold(exprs[0], exprs[1]))
745 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
747 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
751 if (CanConstFold(exprs[0], exprs[1]))
752 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
754 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
758 if (exprs[1]->expression.vtype == TYPE_FLOAT)
760 if (CanConstFold(exprs[0], exprs[1]))
761 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
763 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
767 if (CanConstFold(exprs[0], exprs[1]))
768 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
770 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
774 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
775 type_name[exprs[1]->expression.vtype],
776 type_name[exprs[0]->expression.vtype]);
781 if (NotSameType(TYPE_FLOAT)) {
782 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
783 type_name[exprs[0]->expression.vtype],
784 type_name[exprs[1]->expression.vtype]);
787 if (CanConstFold(exprs[0], exprs[1]))
788 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
790 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
794 parseerror(parser, "qc does not have a modulo operator");
798 if (NotSameType(TYPE_FLOAT)) {
799 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
800 type_name[exprs[0]->expression.vtype],
801 type_name[exprs[1]->expression.vtype]);
804 if (CanConstFold(exprs[0], exprs[1]))
805 out = (ast_expression*)parser_const_float(parser,
806 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
807 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
809 out = (ast_expression*)ast_binary_new(ctx,
810 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
814 parseerror(parser, "TODO: bitxor");
819 case opid3('<','<','='):
820 case opid3('>','>','='):
821 parseerror(parser, "TODO: shifts");
825 generated_op += 1; /* INSTR_OR */
827 generated_op += INSTR_AND;
829 if (NotSameType(TYPE_FLOAT)) {
830 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
831 type_name[exprs[0]->expression.vtype],
832 type_name[exprs[1]->expression.vtype]);
833 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
834 parseerror(parser, "TODO: optional early out");
838 if (opts.standard == COMPILER_GMQCC)
839 con_out("TODO: early out logic\n");
840 if (CanConstFold(exprs[0], exprs[1]))
841 out = (ast_expression*)parser_const_float(parser,
842 (generated_op == INSTR_OR ? (ConstF(0) || ConstF(1)) : (ConstF(0) && ConstF(1))));
844 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
848 if (vec_last(parser->pot) != POT_TERNARY2) {
849 parseerror(parser, "mismatched parenthesis/ternary");
852 vec_pop(parser->pot);
853 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
854 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
855 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
856 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
859 if (CanConstFold1(exprs[0]))
860 out = (ConstF(0) ? exprs[1] : exprs[2]);
862 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
866 generated_op += 1; /* INSTR_GT */
868 generated_op += 1; /* INSTR_LT */
869 case opid2('>', '='):
870 generated_op += 1; /* INSTR_GE */
871 case opid2('<', '='):
872 generated_op += INSTR_LE;
873 if (NotSameType(TYPE_FLOAT)) {
874 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
875 type_name[exprs[0]->expression.vtype],
876 type_name[exprs[1]->expression.vtype]);
879 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
881 case opid2('!', '='):
882 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
883 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
884 type_name[exprs[0]->expression.vtype],
885 type_name[exprs[1]->expression.vtype]);
888 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
890 case opid2('=', '='):
891 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
892 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
893 type_name[exprs[0]->expression.vtype],
894 type_name[exprs[1]->expression.vtype]);
897 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
901 if (ast_istype(exprs[0], ast_entfield)) {
902 ast_expression *field = ((ast_entfield*)exprs[0])->field;
903 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
904 exprs[0]->expression.vtype == TYPE_FIELD &&
905 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
907 assignop = type_storep_instr[TYPE_VECTOR];
910 assignop = type_storep_instr[exprs[0]->expression.vtype];
911 if (assignop == AINSTR_END ||
912 !ast_compare_type(field->expression.next, exprs[1]))
914 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
915 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
916 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
917 field->expression.next->expression.vtype == TYPE_FUNCTION &&
918 exprs[1]->expression.vtype == TYPE_FUNCTION)
920 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
921 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
927 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
932 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
933 exprs[0]->expression.vtype == TYPE_FIELD &&
934 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
936 assignop = type_store_instr[TYPE_VECTOR];
939 assignop = type_store_instr[exprs[0]->expression.vtype];
942 if (assignop == AINSTR_END) {
943 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
944 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
945 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
947 else if (!ast_compare_type(exprs[0], exprs[1])) {
948 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
949 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
950 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
951 exprs[0]->expression.vtype == TYPE_FUNCTION &&
952 exprs[1]->expression.vtype == TYPE_FUNCTION)
954 if (parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
955 "invalid types in assignment: cannot assign %s to %s", ty2, ty1))
961 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
964 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
965 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
967 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
969 case opid3('+','+','P'):
970 case opid3('-','-','P'):
972 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
973 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
974 parseerror(parser, "invalid type for prefix increment: %s", ty1);
977 if (op->id == opid3('+','+','P'))
981 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
982 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
984 if (ast_istype(exprs[0], ast_entfield)) {
985 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
987 (ast_expression*)parser_const_float_1(parser));
989 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
991 (ast_expression*)parser_const_float_1(parser));
994 case opid3('S','+','+'):
995 case opid3('S','-','-'):
997 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
998 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
999 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1002 if (op->id == opid3('S','+','+')) {
1003 addop = INSTR_ADD_F;
1004 subop = INSTR_SUB_F;
1006 addop = INSTR_SUB_F;
1007 subop = INSTR_ADD_F;
1009 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1010 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1012 if (ast_istype(exprs[0], ast_entfield)) {
1013 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1015 (ast_expression*)parser_const_float_1(parser));
1017 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1019 (ast_expression*)parser_const_float_1(parser));
1023 out = (ast_expression*)ast_binary_new(ctx, subop,
1025 (ast_expression*)parser_const_float_1(parser));
1027 case opid2('+','='):
1028 case opid2('-','='):
1029 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1030 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1032 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1033 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1034 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1038 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1039 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1041 if (ast_istype(exprs[0], ast_entfield))
1042 assignop = type_storep_instr[exprs[0]->expression.vtype];
1044 assignop = type_store_instr[exprs[0]->expression.vtype];
1045 switch (exprs[0]->expression.vtype) {
1047 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1048 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1049 exprs[0], exprs[1]);
1052 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1053 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1054 exprs[0], exprs[1]);
1057 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1058 type_name[exprs[0]->expression.vtype],
1059 type_name[exprs[1]->expression.vtype]);
1063 case opid2('*','='):
1064 case opid2('/','='):
1065 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1066 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1067 exprs[0]->expression.vtype == TYPE_VECTOR))
1069 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1070 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1071 parseerror(parser, "invalid types used in expression: %s and %s",
1075 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1076 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1078 if (ast_istype(exprs[0], ast_entfield))
1079 assignop = type_storep_instr[exprs[0]->expression.vtype];
1081 assignop = type_store_instr[exprs[0]->expression.vtype];
1082 switch (exprs[0]->expression.vtype) {
1084 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1085 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1086 exprs[0], exprs[1]);
1089 if (op->id == opid2('*','=')) {
1090 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1091 exprs[0], exprs[1]);
1093 /* there's no DIV_VF */
1094 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1095 (ast_expression*)parser_const_float_1(parser),
1099 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1104 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1105 type_name[exprs[0]->expression.vtype],
1106 type_name[exprs[1]->expression.vtype]);
1110 case opid2('&','='):
1111 case opid2('|','='):
1112 if (NotSameType(TYPE_FLOAT)) {
1113 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1114 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1115 parseerror(parser, "invalid types used in expression: %s and %s",
1119 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1120 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1122 if (ast_istype(exprs[0], ast_entfield))
1123 assignop = type_storep_instr[exprs[0]->expression.vtype];
1125 assignop = type_store_instr[exprs[0]->expression.vtype];
1126 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1127 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1128 exprs[0], exprs[1]);
1130 case opid3('&','~','='):
1131 /* This is like: a &= ~(b);
1132 * But QC has no bitwise-not, so we implement it as
1135 if (NotSameType(TYPE_FLOAT)) {
1136 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1137 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1138 parseerror(parser, "invalid types used in expression: %s and %s",
1142 if (ast_istype(exprs[0], ast_entfield))
1143 assignop = type_storep_instr[exprs[0]->expression.vtype];
1145 assignop = type_store_instr[exprs[0]->expression.vtype];
1146 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1149 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1150 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1152 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1153 asbinstore->keep_dest = true;
1154 out = (ast_expression*)asbinstore;
1160 parseerror(parser, "failed to apply operand %s", op->op);
1164 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1165 vec_push(sy->out, syexp(ctx, out));
1169 static bool parser_close_call(parser_t *parser, shunt *sy)
1171 /* was a function call */
1172 ast_expression *fun;
1178 vec_shrinkby(sy->ops, 1);
1179 fid = sy->ops[vec_size(sy->ops)].off;
1181 /* out[fid] is the function
1182 * everything above is parameters...
1183 * 0 params = nothing
1184 * 1 params = ast_expression
1188 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1189 parseerror(parser, "internal error: function call needs function and parameter list...");
1193 fun = sy->out[fid].out;
1195 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1197 parseerror(parser, "out of memory");
1201 if (fid+1 == vec_size(sy->out)) {
1204 } else if (fid+2 == vec_size(sy->out)) {
1206 vec_shrinkby(sy->out, 1);
1207 params = sy->out[vec_size(sy->out)].block;
1211 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1213 paramcount = vec_size(params->exprs);
1214 call->params = params->exprs;
1215 params->exprs = NULL;
1218 if (!ast_call_check_types(call))
1221 parseerror(parser, "invalid function call");
1225 /* overwrite fid, the function, with a call */
1226 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1228 if (fun->expression.vtype != TYPE_FUNCTION) {
1229 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1233 if (!fun->expression.next) {
1234 parseerror(parser, "could not determine function return type");
1237 if (vec_size(fun->expression.params) != paramcount &&
1238 !(fun->expression.variadic &&
1239 vec_size(fun->expression.params) < paramcount))
1242 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1244 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1245 if (opts.standard == COMPILER_GMQCC)
1248 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1249 " -> `%s` has been declared here: %s:%i",
1250 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1251 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1253 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1254 " -> `%s` has been declared here: %s:%i",
1255 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1256 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1262 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1263 "too %s parameters for call to %s: expected %i, got %i\n"
1264 " -> `%s` has been declared here: %s:%i",
1265 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1266 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1268 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1269 "too %s parameters for function call: expected %i, got %i\n"
1270 " -> `%s` has been declared here: %s:%i",
1271 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1272 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1280 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1282 if (!vec_size(sy->ops)) {
1283 parseerror(parser, "unmatched closing paren");
1286 /* this would for bit a + (x) because there are no operators inside (x)
1287 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1288 parseerror(parser, "empty parenthesis expression");
1292 while (vec_size(sy->ops)) {
1293 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1294 if (!parser_close_call(parser, sy))
1298 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1299 vec_shrinkby(sy->ops, 1);
1300 return !functions_only;
1302 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1305 /* pop off the parenthesis */
1306 vec_shrinkby(sy->ops, 1);
1307 /* then apply the index operator */
1308 if (!parser_sy_apply_operator(parser, sy))
1312 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1315 if (vec_last(parser->pot) != POT_TERNARY1) {
1316 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1319 vec_last(parser->pot) = POT_TERNARY2;
1320 /* pop off the parenthesis */
1321 vec_shrinkby(sy->ops, 1);
1324 if (!parser_sy_apply_operator(parser, sy))
1330 static void parser_reclassify_token(parser_t *parser)
1333 for (i = 0; i < operator_count; ++i) {
1334 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1335 parser->tok = TOKEN_OPERATOR;
1341 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1343 ast_expression *expr = NULL;
1345 bool wantop = false;
1346 bool gotmemberof = false;
1348 /* count the parens because an if starts with one, so the
1349 * end of a condition is an unmatched closing paren
1357 parser->lex->flags.noops = false;
1359 parser_reclassify_token(parser);
1364 gotmemberof = false;
1366 parser->memberof = 0;
1368 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1369 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1371 /* a translatable string */
1375 parseerror(parser, "expected operator or end of statement, got constant");
1379 parser->lex->flags.noops = true;
1380 if (!parser_next(parser) || parser->tok != '(') {
1381 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1384 parser->lex->flags.noops = false;
1385 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1386 parseerror(parser, "expected a constant string in translatable-string extension");
1389 val = parser_const_string(parser, parser_tokval(parser), true);
1393 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1394 DEBUGSHUNTDO(con_out("push string\n"));
1396 if (!parser_next(parser) || parser->tok != ')') {
1397 parseerror(parser, "expected closing paren after translatable string");
1401 else if (parser->tok == TOKEN_IDENT)
1403 ast_expression *var;
1405 parseerror(parser, "expected operator or end of statement");
1410 if (opts.standard == COMPILER_GMQCC)
1412 if (parser->memberof == TYPE_ENTITY) {
1413 /* still get vars first since there could be a fieldpointer */
1414 var = parser_find_var(parser, parser_tokval(parser));
1416 var = parser_find_field(parser, parser_tokval(parser));
1418 else if (parser->memberof == TYPE_VECTOR)
1420 parseerror(parser, "TODO: implement effective vector member access");
1423 else if (parser->memberof) {
1424 parseerror(parser, "namespace for member not found");
1428 var = parser_find_var(parser, parser_tokval(parser));
1430 var = parser_find_var(parser, parser_tokval(parser));
1432 var = parser_find_field(parser, parser_tokval(parser));
1435 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1438 if (ast_istype(var, ast_value)) {
1439 ((ast_value*)var)->uses++;
1441 else if (ast_istype(var, ast_member)) {
1442 ast_member *mem = (ast_member*)var;
1443 if (ast_istype(mem->owner, ast_value))
1444 ((ast_value*)(mem->owner))->uses++;
1446 vec_push(sy.out, syexp(parser_ctx(parser), var));
1447 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1449 else if (parser->tok == TOKEN_FLOATCONST) {
1452 parseerror(parser, "expected operator or end of statement, got constant");
1456 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1459 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1460 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1462 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1465 parseerror(parser, "expected operator or end of statement, got constant");
1469 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1472 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1473 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1475 else if (parser->tok == TOKEN_STRINGCONST) {
1478 parseerror(parser, "expected operator or end of statement, got constant");
1482 val = parser_const_string(parser, parser_tokval(parser), false);
1485 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1486 DEBUGSHUNTDO(con_out("push string\n"));
1488 else if (parser->tok == TOKEN_VECTORCONST) {
1491 parseerror(parser, "expected operator or end of statement, got constant");
1495 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1498 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1499 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1500 parser_token(parser)->constval.v.x,
1501 parser_token(parser)->constval.v.y,
1502 parser_token(parser)->constval.v.z));
1504 else if (parser->tok == '(') {
1505 parseerror(parser, "internal error: '(' should be classified as operator");
1508 else if (parser->tok == '[') {
1509 parseerror(parser, "internal error: '[' should be classified as operator");
1512 else if (parser->tok == ')') {
1514 DEBUGSHUNTDO(con_out("do[op] )\n"));
1518 /* we do expect an operator next */
1519 /* closing an opening paren */
1520 if (!parser_close_paren(parser, &sy, false))
1522 if (vec_last(parser->pot) != POT_PAREN) {
1523 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1526 vec_pop(parser->pot);
1528 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1532 /* allowed for function calls */
1533 if (!parser_close_paren(parser, &sy, true))
1535 if (vec_last(parser->pot) != POT_PAREN) {
1536 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1539 vec_pop(parser->pot);
1543 else if (parser->tok == ']') {
1545 parseerror(parser, "operand expected");
1549 if (!parser_close_paren(parser, &sy, false))
1551 if (vec_last(parser->pot) != POT_PAREN) {
1552 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1555 vec_pop(parser->pot);
1558 else if (parser->tok == TOKEN_TYPENAME) {
1559 parseerror(parser, "unexpected typename");
1562 else if (parser->tok != TOKEN_OPERATOR) {
1564 parseerror(parser, "expected operator or end of statement");
1571 /* classify the operator */
1572 const oper_info *op;
1573 const oper_info *olast = NULL;
1575 for (o = 0; o < operator_count; ++o) {
1576 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1577 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1578 !strcmp(parser_tokval(parser), operators[o].op))
1583 if (o == operator_count) {
1584 /* no operator found... must be the end of the statement */
1587 /* found an operator */
1590 /* when declaring variables, a comma starts a new variable */
1591 if (op->id == opid1(',') && !parens && stopatcomma) {
1592 /* fixup the token */
1597 /* a colon without a pervious question mark cannot be a ternary */
1598 if (!ternaries && op->id == opid2(':','?')) {
1603 if (op->id == opid1(',')) {
1604 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1605 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1609 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1610 olast = &operators[vec_last(sy.ops).etype-1];
1613 (op->prec < olast->prec) ||
1614 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1616 if (!parser_sy_apply_operator(parser, &sy))
1618 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1619 olast = &operators[vec_last(sy.ops).etype-1];
1624 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1625 /* for gmqcc standard: open up the namespace of the previous type */
1626 ast_expression *prevex = vec_last(sy.out).out;
1628 parseerror(parser, "unexpected member operator");
1631 if (prevex->expression.vtype == TYPE_ENTITY)
1632 parser->memberof = TYPE_ENTITY;
1633 else if (prevex->expression.vtype == TYPE_VECTOR)
1634 parser->memberof = TYPE_VECTOR;
1636 parseerror(parser, "type error: type has no members");
1642 if (op->id == opid1('(')) {
1644 size_t sycount = vec_size(sy.out);
1645 DEBUGSHUNTDO(con_out("push [op] (\n"));
1646 ++parens; vec_push(parser->pot, POT_PAREN);
1647 /* we expected an operator, this is the function-call operator */
1648 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1650 ++parens; vec_push(parser->pot, POT_PAREN);
1651 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1652 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1655 } else if (op->id == opid1('[')) {
1657 parseerror(parser, "unexpected array subscript");
1660 ++parens; vec_push(parser->pot, POT_PAREN);
1661 /* push both the operator and the paren, this makes life easier */
1662 vec_push(sy.ops, syop(parser_ctx(parser), op));
1663 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1665 } else if (op->id == opid2('?',':')) {
1667 vec_push(sy.ops, syop(parser_ctx(parser), op));
1668 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1671 vec_push(parser->pot, POT_TERNARY1);
1672 } else if (op->id == opid2(':','?')) {
1673 if (!vec_size(parser->pot)) {
1674 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1677 if (vec_last(parser->pot) != POT_TERNARY1) {
1678 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1681 if (!parser_close_paren(parser, &sy, false))
1683 vec_push(sy.ops, syop(parser_ctx(parser), op));
1687 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1688 vec_push(sy.ops, syop(parser_ctx(parser), op));
1689 wantop = !!(op->flags & OP_SUFFIX);
1692 if (!parser_next(parser)) {
1695 if (parser->tok == ';' ||
1696 (!parens && parser->tok == ']'))
1702 while (vec_size(sy.ops)) {
1703 if (!parser_sy_apply_operator(parser, &sy))
1707 parser->lex->flags.noops = true;
1708 if (!vec_size(sy.out)) {
1709 parseerror(parser, "empty expression");
1712 expr = sy.out[0].out;
1715 DEBUGSHUNTDO(con_out("shunt done\n"));
1716 if (vec_size(parser->pot)) {
1717 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1720 vec_free(parser->pot);
1724 parser->lex->flags.noops = true;
1730 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1732 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1735 if (!parser_next(parser)) {
1742 static void parser_enterblock(parser_t *parser)
1744 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1745 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1746 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1747 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1748 vec_push(parser->_block_ctx, parser_ctx(parser));
1751 static bool parser_leaveblock(parser_t *parser)
1754 size_t locals, typedefs;
1756 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1757 parseerror(parser, "internal error: parser_leaveblock with no block");
1761 util_htdel(vec_last(parser->variables));
1762 vec_pop(parser->variables);
1763 if (!vec_size(parser->_blocklocals)) {
1764 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1768 locals = vec_last(parser->_blocklocals);
1769 vec_pop(parser->_blocklocals);
1770 while (vec_size(parser->_locals) != locals) {
1771 ast_expression *e = vec_last(parser->_locals);
1772 ast_value *v = (ast_value*)e;
1773 vec_pop(parser->_locals);
1774 if (ast_istype(e, ast_value) && !v->uses) {
1775 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name)) {
1782 typedefs = vec_last(parser->_blocktypedefs);
1783 while (vec_size(parser->_typedefs) != typedefs) {
1784 ast_delete(vec_last(parser->_typedefs));
1785 vec_pop(parser->_typedefs);
1787 util_htdel(vec_last(parser->typedefs));
1788 vec_pop(parser->typedefs);
1790 vec_pop(parser->_block_ctx);
1794 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1796 vec_push(parser->_locals, e);
1797 util_htset(vec_last(parser->variables), name, (void*)e);
1800 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1803 ast_expression *cond, *ontrue, *onfalse = NULL;
1806 lex_ctx ctx = parser_ctx(parser);
1808 (void)block; /* not touching */
1810 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1811 if (!parser_next(parser)) {
1812 parseerror(parser, "expected condition or 'not'");
1815 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1817 if (!parser_next(parser)) {
1818 parseerror(parser, "expected condition in parenthesis");
1822 if (parser->tok != '(') {
1823 parseerror(parser, "expected 'if' condition in parenthesis");
1826 /* parse into the expression */
1827 if (!parser_next(parser)) {
1828 parseerror(parser, "expected 'if' condition after opening paren");
1831 /* parse the condition */
1832 cond = parse_expression_leave(parser, false);
1836 if (parser->tok != ')') {
1837 parseerror(parser, "expected closing paren after 'if' condition");
1841 /* parse into the 'then' branch */
1842 if (!parser_next(parser)) {
1843 parseerror(parser, "expected statement for on-true branch of 'if'");
1847 if (!parse_statement_or_block(parser, &ontrue)) {
1851 /* check for an else */
1852 if (!strcmp(parser_tokval(parser), "else")) {
1853 /* parse into the 'else' branch */
1854 if (!parser_next(parser)) {
1855 parseerror(parser, "expected on-false branch after 'else'");
1860 if (!parse_statement_or_block(parser, &onfalse)) {
1868 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
1870 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
1871 *out = (ast_expression*)ifthen;
1875 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
1878 ast_expression *cond, *ontrue;
1880 lex_ctx ctx = parser_ctx(parser);
1882 (void)block; /* not touching */
1884 /* skip the 'while' and check for opening paren */
1885 if (!parser_next(parser) || parser->tok != '(') {
1886 parseerror(parser, "expected 'while' condition in parenthesis");
1889 /* parse into the expression */
1890 if (!parser_next(parser)) {
1891 parseerror(parser, "expected 'while' condition after opening paren");
1894 /* parse the condition */
1895 cond = parse_expression_leave(parser, false);
1899 if (parser->tok != ')') {
1900 parseerror(parser, "expected closing paren after 'while' condition");
1904 /* parse into the 'then' branch */
1905 if (!parser_next(parser)) {
1906 parseerror(parser, "expected while-loop body");
1910 if (!parse_statement_or_block(parser, &ontrue)) {
1915 aloop = ast_loop_new(ctx, NULL, cond, NULL, NULL, ontrue);
1916 *out = (ast_expression*)aloop;
1920 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
1923 ast_expression *cond, *ontrue;
1925 lex_ctx ctx = parser_ctx(parser);
1927 (void)block; /* not touching */
1929 /* skip the 'do' and get the body */
1930 if (!parser_next(parser)) {
1931 parseerror(parser, "expected loop body");
1934 if (!parse_statement_or_block(parser, &ontrue))
1937 /* expect the "while" */
1938 if (parser->tok != TOKEN_KEYWORD ||
1939 strcmp(parser_tokval(parser), "while"))
1941 parseerror(parser, "expected 'while' and condition");
1946 /* skip the 'while' and check for opening paren */
1947 if (!parser_next(parser) || parser->tok != '(') {
1948 parseerror(parser, "expected 'while' condition in parenthesis");
1952 /* parse into the expression */
1953 if (!parser_next(parser)) {
1954 parseerror(parser, "expected 'while' condition after opening paren");
1958 /* parse the condition */
1959 cond = parse_expression_leave(parser, false);
1963 if (parser->tok != ')') {
1964 parseerror(parser, "expected closing paren after 'while' condition");
1970 if (!parser_next(parser) || parser->tok != ';') {
1971 parseerror(parser, "expected semicolon after condition");
1977 if (!parser_next(parser)) {
1978 parseerror(parser, "parse error");
1984 aloop = ast_loop_new(ctx, NULL, NULL, cond, NULL, ontrue);
1985 *out = (ast_expression*)aloop;
1989 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
1992 ast_expression *initexpr, *cond, *increment, *ontrue;
1996 lex_ctx ctx = parser_ctx(parser);
1998 parser_enterblock(parser);
2005 /* skip the 'while' and check for opening paren */
2006 if (!parser_next(parser) || parser->tok != '(') {
2007 parseerror(parser, "expected 'for' expressions in parenthesis");
2010 /* parse into the expression */
2011 if (!parser_next(parser)) {
2012 parseerror(parser, "expected 'for' initializer after opening paren");
2017 if (parser->tok == TOKEN_IDENT)
2018 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2020 if (typevar || parser->tok == TOKEN_TYPENAME) {
2021 if (opts.standard != COMPILER_GMQCC) {
2022 if (parsewarning(parser, WARN_EXTENSIONS,
2023 "current standard does not allow variable declarations in for-loop initializers"))
2026 if (!parse_variable(parser, block, true, CV_VAR, typevar, false))
2029 else if (parser->tok != ';')
2031 initexpr = parse_expression_leave(parser, false);
2036 /* move on to condition */
2037 if (parser->tok != ';') {
2038 parseerror(parser, "expected semicolon after for-loop initializer");
2041 if (!parser_next(parser)) {
2042 parseerror(parser, "expected for-loop condition");
2046 /* parse the condition */
2047 if (parser->tok != ';') {
2048 cond = parse_expression_leave(parser, false);
2053 /* move on to incrementor */
2054 if (parser->tok != ';') {
2055 parseerror(parser, "expected semicolon after for-loop initializer");
2058 if (!parser_next(parser)) {
2059 parseerror(parser, "expected for-loop condition");
2063 /* parse the incrementor */
2064 if (parser->tok != ')') {
2065 increment = parse_expression_leave(parser, false);
2068 if (!ast_side_effects(increment)) {
2069 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2075 if (parser->tok != ')') {
2076 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2079 /* parse into the 'then' branch */
2080 if (!parser_next(parser)) {
2081 parseerror(parser, "expected for-loop body");
2084 if (!parse_statement_or_block(parser, &ontrue))
2087 aloop = ast_loop_new(ctx, initexpr, cond, NULL, increment, ontrue);
2088 *out = (ast_expression*)aloop;
2090 if (!parser_leaveblock(parser))
2094 if (initexpr) ast_delete(initexpr);
2095 if (cond) ast_delete(cond);
2096 if (increment) ast_delete(increment);
2097 (void)!parser_leaveblock(parser);
2101 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2103 ast_expression *exp = NULL;
2104 ast_return *ret = NULL;
2105 ast_value *expected = parser->function->vtype;
2107 lex_ctx ctx = parser_ctx(parser);
2109 (void)block; /* not touching */
2111 if (!parser_next(parser)) {
2112 parseerror(parser, "expected return expression");
2116 if (parser->tok != ';') {
2117 exp = parse_expression(parser, false);
2121 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2122 parseerror(parser, "return with invalid expression");
2125 ret = ast_return_new(exp->expression.node.context, exp);
2131 if (!parser_next(parser))
2132 parseerror(parser, "parse error");
2133 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2134 if (opts.standard != COMPILER_GMQCC)
2135 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2137 parseerror(parser, "return without value");
2139 ret = ast_return_new(ctx, NULL);
2141 *out = (ast_expression*)ret;
2145 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2147 lex_ctx ctx = parser_ctx(parser);
2149 (void)block; /* not touching */
2151 if (!parser_next(parser) || parser->tok != ';') {
2152 parseerror(parser, "expected semicolon");
2156 if (!parser_next(parser))
2157 parseerror(parser, "parse error");
2159 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue);
2163 /* returns true when it was a variable qualifier, false otherwise!
2164 * on error, cvq is set to CV_WRONG
2166 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref)
2168 bool had_const = false;
2169 bool had_var = false;
2170 bool had_noref = false;
2173 if (!strcmp(parser_tokval(parser), "const"))
2175 else if (!strcmp(parser_tokval(parser), "var"))
2177 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2179 else if (!strcmp(parser_tokval(parser), "noref"))
2181 else if (!had_const && !had_var && !had_noref) {
2186 if (!parser_next(parser))
2198 parseerror(parser, "parse error after variable qualifier");
2203 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2205 ast_expression *operand;
2208 ast_switch *switchnode;
2209 ast_switch_case swcase;
2214 lex_ctx ctx = parser_ctx(parser);
2216 (void)block; /* not touching */
2219 /* parse over the opening paren */
2220 if (!parser_next(parser) || parser->tok != '(') {
2221 parseerror(parser, "expected switch operand in parenthesis");
2225 /* parse into the expression */
2226 if (!parser_next(parser)) {
2227 parseerror(parser, "expected switch operand");
2230 /* parse the operand */
2231 operand = parse_expression_leave(parser, false);
2235 switchnode = ast_switch_new(ctx, operand);
2238 if (parser->tok != ')') {
2239 ast_delete(switchnode);
2240 parseerror(parser, "expected closing paren after 'switch' operand");
2244 /* parse over the opening paren */
2245 if (!parser_next(parser) || parser->tok != '{') {
2246 ast_delete(switchnode);
2247 parseerror(parser, "expected list of cases");
2251 if (!parser_next(parser)) {
2252 ast_delete(switchnode);
2253 parseerror(parser, "expected 'case' or 'default'");
2257 /* new block; allow some variables to be declared here */
2258 parser_enterblock(parser);
2261 if (parser->tok == TOKEN_IDENT)
2262 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2263 if (typevar || parser->tok == TOKEN_TYPENAME) {
2264 if (!parse_variable(parser, block, false, CV_NONE, typevar, false)) {
2265 ast_delete(switchnode);
2270 if (parse_var_qualifiers(parser, true, &cvq, &noref))
2272 if (cvq == CV_WRONG) {
2273 ast_delete(switchnode);
2276 if (!parse_variable(parser, block, false, cvq, NULL, noref)) {
2277 ast_delete(switchnode);
2286 while (parser->tok != '}') {
2287 ast_block *caseblock;
2289 if (parser->tok != TOKEN_KEYWORD) {
2290 ast_delete(switchnode);
2291 parseerror(parser, "expected 'case' or 'default'");
2294 if (!strcmp(parser_tokval(parser), "case")) {
2295 if (!parser_next(parser)) {
2296 ast_delete(switchnode);
2297 parseerror(parser, "expected expression for case");
2300 swcase.value = parse_expression_leave(parser, false);
2301 if (!swcase.value) {
2302 ast_delete(switchnode);
2303 parseerror(parser, "expected expression for case");
2306 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2307 opval = (ast_value*)swcase.value;
2308 if (!ast_istype(swcase.value, ast_value)) { /* || opval->cvq != CV_CONST) { */
2309 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2315 else if (!strcmp(parser_tokval(parser), "default")) {
2316 swcase.value = NULL;
2317 if (!parser_next(parser)) {
2318 ast_delete(switchnode);
2319 parseerror(parser, "expected colon");
2324 /* Now the colon and body */
2325 if (parser->tok != ':') {
2326 if (swcase.value) ast_unref(swcase.value);
2327 ast_delete(switchnode);
2328 parseerror(parser, "expected colon");
2332 if (!parser_next(parser)) {
2333 if (swcase.value) ast_unref(swcase.value);
2334 ast_delete(switchnode);
2335 parseerror(parser, "expected statements or case");
2338 caseblock = ast_block_new(parser_ctx(parser));
2340 if (swcase.value) ast_unref(swcase.value);
2341 ast_delete(switchnode);
2344 swcase.code = (ast_expression*)caseblock;
2345 vec_push(switchnode->cases, swcase);
2347 ast_expression *expr;
2348 if (parser->tok == '}')
2350 if (parser->tok == TOKEN_KEYWORD) {
2351 if (!strcmp(parser_tokval(parser), "case") ||
2352 !strcmp(parser_tokval(parser), "default"))
2357 if (!parse_statement(parser, caseblock, &expr, true)) {
2358 ast_delete(switchnode);
2363 if (!ast_block_add_expr(caseblock, expr)) {
2364 ast_delete(switchnode);
2370 parser_leaveblock(parser);
2373 if (parser->tok != '}') {
2374 ast_delete(switchnode);
2375 parseerror(parser, "expected closing paren of case list");
2378 if (!parser_next(parser)) {
2379 ast_delete(switchnode);
2380 parseerror(parser, "parse error after switch");
2383 *out = (ast_expression*)switchnode;
2387 static bool parse_goto(parser_t *parser, ast_expression **out)
2392 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2393 parseerror(parser, "expected label name after `goto`");
2397 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2399 for (i = 0; i < vec_size(parser->labels); ++i) {
2400 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2401 ast_goto_set_label(gt, parser->labels[i]);
2405 if (i == vec_size(parser->labels))
2406 vec_push(parser->gotos, gt);
2408 if (!parser_next(parser) || parser->tok != ';') {
2409 parseerror(parser, "semicolon expected after goto label");
2412 if (!parser_next(parser)) {
2413 parseerror(parser, "parse error after goto");
2417 *out = (ast_expression*)gt;
2421 static bool parse_skipwhite(parser_t *parser)
2424 if (!parser_next(parser))
2426 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2427 return parser->tok < TOKEN_ERROR;
2430 static bool parse_eol(parser_t *parser)
2432 if (!parse_skipwhite(parser))
2434 return parser->tok == TOKEN_EOL;
2437 static bool parse_pragma_do(parser_t *parser)
2439 if (!parser_next(parser) ||
2440 parser->tok != TOKEN_IDENT ||
2441 strcmp(parser_tokval(parser), "pragma"))
2443 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2446 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2447 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2451 if (!strcmp(parser_tokval(parser), "noref")) {
2452 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2453 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2456 parser->noref = !!parser_token(parser)->constval.i;
2457 if (!parse_eol(parser)) {
2458 parseerror(parser, "parse error after `noref` pragma");
2464 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2471 static bool parse_pragma(parser_t *parser)
2474 parser->lex->flags.preprocessing = true;
2475 parser->lex->flags.mergelines = true;
2476 rv = parse_pragma_do(parser);
2477 if (parser->tok != TOKEN_EOL) {
2478 parseerror(parser, "junk after pragma");
2481 parser->lex->flags.preprocessing = false;
2482 parser->lex->flags.mergelines = false;
2483 if (!parser_next(parser)) {
2484 parseerror(parser, "parse error after pragma");
2490 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2494 ast_value *typevar = NULL;
2498 if (parser->tok == TOKEN_IDENT)
2499 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2501 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2503 /* local variable */
2505 parseerror(parser, "cannot declare a variable from here");
2508 if (opts.standard == COMPILER_QCC) {
2509 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2512 if (!parse_variable(parser, block, false, CV_NONE, typevar, false))
2516 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref))
2518 if (cvq == CV_WRONG)
2520 return parse_variable(parser, block, true, cvq, NULL, noref);
2522 else if (parser->tok == TOKEN_KEYWORD)
2524 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2529 if (!parser_next(parser)) {
2530 parseerror(parser, "parse error after __builtin_debug_printtype");
2534 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2536 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2537 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2538 if (!parser_next(parser)) {
2539 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2545 if (!parse_statement(parser, block, out, allow_cases))
2548 con_out("__builtin_debug_printtype: got no output node\n");
2551 ast_type_to_string(*out, ty, sizeof(ty));
2552 con_out("__builtin_debug_printtype: `%s`\n", ty);
2557 else if (!strcmp(parser_tokval(parser), "return"))
2559 return parse_return(parser, block, out);
2561 else if (!strcmp(parser_tokval(parser), "if"))
2563 return parse_if(parser, block, out);
2565 else if (!strcmp(parser_tokval(parser), "while"))
2567 return parse_while(parser, block, out);
2569 else if (!strcmp(parser_tokval(parser), "do"))
2571 return parse_dowhile(parser, block, out);
2573 else if (!strcmp(parser_tokval(parser), "for"))
2575 if (opts.standard == COMPILER_QCC) {
2576 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
2579 return parse_for(parser, block, out);
2581 else if (!strcmp(parser_tokval(parser), "break"))
2583 return parse_break_continue(parser, block, out, false);
2585 else if (!strcmp(parser_tokval(parser), "continue"))
2587 return parse_break_continue(parser, block, out, true);
2589 else if (!strcmp(parser_tokval(parser), "switch"))
2591 return parse_switch(parser, block, out);
2593 else if (!strcmp(parser_tokval(parser), "case") ||
2594 !strcmp(parser_tokval(parser), "default"))
2597 parseerror(parser, "unexpected 'case' label");
2602 else if (!strcmp(parser_tokval(parser), "goto"))
2604 return parse_goto(parser, out);
2606 else if (!strcmp(parser_tokval(parser), "typedef"))
2608 if (!parser_next(parser)) {
2609 parseerror(parser, "expected type definition after 'typedef'");
2612 return parse_typedef(parser);
2614 parseerror(parser, "Unexpected keyword");
2617 else if (parser->tok == '{')
2620 inner = parse_block(parser);
2623 *out = (ast_expression*)inner;
2626 else if (parser->tok == ':')
2630 if (!parser_next(parser)) {
2631 parseerror(parser, "expected label name");
2634 if (parser->tok != TOKEN_IDENT) {
2635 parseerror(parser, "label must be an identifier");
2638 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
2641 vec_push(parser->labels, label);
2642 *out = (ast_expression*)label;
2643 if (!parser_next(parser)) {
2644 parseerror(parser, "parse error after label");
2647 for (i = 0; i < vec_size(parser->gotos); ++i) {
2648 if (!strcmp(parser->gotos[i]->name, label->name)) {
2649 ast_goto_set_label(parser->gotos[i], label);
2650 vec_remove(parser->gotos, i, 1);
2656 else if (parser->tok == ';')
2658 if (!parser_next(parser)) {
2659 parseerror(parser, "parse error after empty statement");
2666 ast_expression *exp = parse_expression(parser, false);
2670 if (!ast_side_effects(exp)) {
2671 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2678 static bool parse_block_into(parser_t *parser, ast_block *block)
2682 parser_enterblock(parser);
2684 if (!parser_next(parser)) { /* skip the '{' */
2685 parseerror(parser, "expected function body");
2689 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
2691 ast_expression *expr = NULL;
2692 if (parser->tok == '}')
2695 if (!parse_statement(parser, block, &expr, false)) {
2696 /* parseerror(parser, "parse error"); */
2702 if (!ast_block_add_expr(block, expr)) {
2709 if (parser->tok != '}') {
2712 (void)parser_next(parser);
2716 if (!parser_leaveblock(parser))
2718 return retval && !!block;
2721 static ast_block* parse_block(parser_t *parser)
2724 block = ast_block_new(parser_ctx(parser));
2727 if (!parse_block_into(parser, block)) {
2728 ast_block_delete(block);
2734 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
2736 if (parser->tok == '{') {
2737 *out = (ast_expression*)parse_block(parser);
2740 return parse_statement(parser, NULL, out, false);
2743 static bool create_vector_members(ast_value *var, ast_member **me)
2746 size_t len = strlen(var->name);
2748 for (i = 0; i < 3; ++i) {
2749 char *name = mem_a(len+3);
2750 memcpy(name, var->name, len);
2752 name[len+1] = 'x'+i;
2754 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
2763 do { ast_member_delete(me[--i]); } while(i);
2767 static bool parse_function_body(parser_t *parser, ast_value *var)
2769 ast_block *block = NULL;
2774 ast_expression *framenum = NULL;
2775 ast_expression *nextthink = NULL;
2776 /* None of the following have to be deleted */
2777 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
2778 ast_expression *gbl_time = NULL, *gbl_self = NULL;
2779 bool has_frame_think;
2783 has_frame_think = false;
2784 old = parser->function;
2786 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
2787 parseerror(parser, "gotos/labels leaking");
2791 if (var->expression.variadic) {
2792 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
2793 "variadic function with implementation will not be able to access additional parameters"))
2799 if (parser->tok == '[') {
2800 /* got a frame definition: [ framenum, nextthink ]
2801 * this translates to:
2802 * self.frame = framenum;
2803 * self.nextthink = time + 0.1;
2804 * self.think = nextthink;
2808 fld_think = parser_find_field(parser, "think");
2809 fld_nextthink = parser_find_field(parser, "nextthink");
2810 fld_frame = parser_find_field(parser, "frame");
2811 if (!fld_think || !fld_nextthink || !fld_frame) {
2812 parseerror(parser, "cannot use [frame,think] notation without the required fields");
2813 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
2816 gbl_time = parser_find_global(parser, "time");
2817 gbl_self = parser_find_global(parser, "self");
2818 if (!gbl_time || !gbl_self) {
2819 parseerror(parser, "cannot use [frame,think] notation without the required globals");
2820 parseerror(parser, "please declare the following globals: `time`, `self`");
2824 if (!parser_next(parser))
2827 framenum = parse_expression_leave(parser, true);
2829 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
2832 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
2833 ast_unref(framenum);
2834 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
2838 if (parser->tok != ',') {
2839 ast_unref(framenum);
2840 parseerror(parser, "expected comma after frame number in [frame,think] notation");
2841 parseerror(parser, "Got a %i\n", parser->tok);
2845 if (!parser_next(parser)) {
2846 ast_unref(framenum);
2850 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
2852 /* qc allows the use of not-yet-declared functions here
2853 * - this automatically creates a prototype */
2854 ast_value *thinkfunc;
2855 ast_expression *functype = fld_think->expression.next;
2857 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
2858 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
2859 ast_unref(framenum);
2860 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
2864 if (!parser_next(parser)) {
2865 ast_unref(framenum);
2866 ast_delete(thinkfunc);
2870 vec_push(parser->globals, (ast_expression*)thinkfunc);
2871 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
2872 nextthink = (ast_expression*)thinkfunc;
2875 nextthink = parse_expression_leave(parser, true);
2877 ast_unref(framenum);
2878 parseerror(parser, "expected a think-function in [frame,think] notation");
2883 if (!ast_istype(nextthink, ast_value)) {
2884 parseerror(parser, "think-function in [frame,think] notation must be a constant");
2888 if (retval && parser->tok != ']') {
2889 parseerror(parser, "expected closing `]` for [frame,think] notation");
2893 if (retval && !parser_next(parser)) {
2897 if (retval && parser->tok != '{') {
2898 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
2903 ast_unref(nextthink);
2904 ast_unref(framenum);
2908 has_frame_think = true;
2911 block = ast_block_new(parser_ctx(parser));
2913 parseerror(parser, "failed to allocate block");
2914 if (has_frame_think) {
2915 ast_unref(nextthink);
2916 ast_unref(framenum);
2921 if (has_frame_think) {
2923 ast_expression *self_frame;
2924 ast_expression *self_nextthink;
2925 ast_expression *self_think;
2926 ast_expression *time_plus_1;
2927 ast_store *store_frame;
2928 ast_store *store_nextthink;
2929 ast_store *store_think;
2931 ctx = parser_ctx(parser);
2932 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
2933 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
2934 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
2936 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
2937 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
2939 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
2940 if (self_frame) ast_delete(self_frame);
2941 if (self_nextthink) ast_delete(self_nextthink);
2942 if (self_think) ast_delete(self_think);
2943 if (time_plus_1) ast_delete(time_plus_1);
2949 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
2950 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
2951 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
2954 ast_delete(self_frame);
2957 if (!store_nextthink) {
2958 ast_delete(self_nextthink);
2962 ast_delete(self_think);
2966 if (store_frame) ast_delete(store_frame);
2967 if (store_nextthink) ast_delete(store_nextthink);
2968 if (store_think) ast_delete(store_think);
2971 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
2972 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
2973 !ast_block_add_expr(block, (ast_expression*)store_think))
2980 parseerror(parser, "failed to generate code for [frame,think]");
2981 ast_unref(nextthink);
2982 ast_unref(framenum);
2988 parser_enterblock(parser);
2990 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
2992 ast_value *param = var->expression.params[parami];
2995 if (param->expression.vtype != TYPE_VECTOR &&
2996 (param->expression.vtype != TYPE_FIELD ||
2997 param->expression.next->expression.vtype != TYPE_VECTOR))
3002 if (!create_vector_members(param, me)) {
3003 ast_block_delete(block);
3007 for (e = 0; e < 3; ++e) {
3008 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3009 ast_block_collect(block, (ast_expression*)me[e]);
3013 func = ast_function_new(ast_ctx(var), var->name, var);
3015 parseerror(parser, "failed to allocate function for `%s`", var->name);
3016 ast_block_delete(block);
3019 vec_push(parser->functions, func);
3021 parser->function = func;
3022 if (!parse_block_into(parser, block)) {
3023 ast_block_delete(block);
3027 vec_push(func->blocks, block);
3029 parser->function = old;
3030 if (!parser_leaveblock(parser))
3032 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3033 parseerror(parser, "internal error: local scopes left");
3037 if (parser->tok == ';')
3038 return parser_next(parser);
3039 else if (opts.standard == COMPILER_QCC)
3040 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3044 vec_pop(parser->functions);
3045 ast_function_delete(func);
3046 var->constval.vfunc = NULL;
3049 (void)!parser_leaveblock(parser);
3050 parser->function = old;
3054 static ast_expression *array_accessor_split(
3059 ast_expression *left,
3060 ast_expression *right
3066 lex_ctx ctx = ast_ctx(array);
3068 if (!left || !right) {
3069 if (left) ast_delete(left);
3070 if (right) ast_delete(right);
3074 cmp = ast_binary_new(ctx, INSTR_LT,
3075 (ast_expression*)index,
3076 (ast_expression*)parser_const_float(parser, middle));
3080 parseerror(parser, "internal error: failed to create comparison for array setter");
3084 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3086 ast_delete(cmp); /* will delete left and right */
3087 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3091 return (ast_expression*)ifthen;
3094 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3096 lex_ctx ctx = ast_ctx(array);
3098 if (from+1 == afterend) {
3099 /* set this value */
3102 ast_array_index *subscript;
3104 int assignop = type_store_instr[value->expression.vtype];
3106 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3107 assignop = INSTR_STORE_V;
3109 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3113 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3115 ast_delete(subscript);
3119 block = ast_block_new(ctx);
3125 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3130 ret = ast_return_new(ctx, NULL);
3136 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3141 return (ast_expression*)block;
3143 ast_expression *left, *right;
3144 size_t diff = afterend - from;
3145 size_t middle = from + diff/2;
3146 left = array_setter_node(parser, array, index, value, from, middle);
3147 right = array_setter_node(parser, array, index, value, middle, afterend);
3148 return array_accessor_split(parser, array, index, middle, left, right);
3152 static ast_expression *array_field_setter_node(
3161 lex_ctx ctx = ast_ctx(array);
3163 if (from+1 == afterend) {
3164 /* set this value */
3167 ast_entfield *entfield;
3168 ast_array_index *subscript;
3170 int assignop = type_storep_instr[value->expression.vtype];
3172 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3173 assignop = INSTR_STOREP_V;
3175 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3179 entfield = ast_entfield_new_force(ctx,
3180 (ast_expression*)entity,
3181 (ast_expression*)subscript,
3182 (ast_expression*)subscript);
3184 ast_delete(subscript);
3188 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3190 ast_delete(entfield);
3194 block = ast_block_new(ctx);
3200 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3205 ret = ast_return_new(ctx, NULL);
3211 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3216 return (ast_expression*)block;
3218 ast_expression *left, *right;
3219 size_t diff = afterend - from;
3220 size_t middle = from + diff/2;
3221 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3222 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3223 return array_accessor_split(parser, array, index, middle, left, right);
3227 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3229 lex_ctx ctx = ast_ctx(array);
3231 if (from+1 == afterend) {
3233 ast_array_index *subscript;
3235 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3239 ret = ast_return_new(ctx, (ast_expression*)subscript);
3241 ast_delete(subscript);
3245 return (ast_expression*)ret;
3247 ast_expression *left, *right;
3248 size_t diff = afterend - from;
3249 size_t middle = from + diff/2;
3250 left = array_getter_node(parser, array, index, from, middle);
3251 right = array_getter_node(parser, array, index, middle, afterend);
3252 return array_accessor_split(parser, array, index, middle, left, right);
3256 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3258 ast_function *func = NULL;
3259 ast_value *fval = NULL;
3260 ast_block *body = NULL;
3262 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3264 parseerror(parser, "failed to create accessor function value");
3268 func = ast_function_new(ast_ctx(array), funcname, fval);
3271 parseerror(parser, "failed to create accessor function node");
3275 body = ast_block_new(ast_ctx(array));
3277 parseerror(parser, "failed to create block for array accessor");
3283 vec_push(func->blocks, body);
3286 vec_push(parser->accessors, fval);
3291 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3293 ast_expression *root = NULL;
3294 ast_value *index = NULL;
3295 ast_value *value = NULL;
3299 if (!ast_istype(array->expression.next, ast_value)) {
3300 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3304 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3306 func = fval->constval.vfunc;
3307 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3309 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3310 value = ast_value_copy((ast_value*)array->expression.next);
3312 if (!index || !value) {
3313 parseerror(parser, "failed to create locals for array accessor");
3316 (void)!ast_value_set_name(value, "value"); /* not important */
3317 vec_push(fval->expression.params, index);
3318 vec_push(fval->expression.params, value);
3320 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3322 parseerror(parser, "failed to build accessor search tree");
3326 array->setter = fval;
3327 return ast_block_add_expr(func->blocks[0], root);
3329 if (index) ast_delete(index);
3330 if (value) ast_delete(value);
3331 if (root) ast_delete(root);
3337 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3339 ast_expression *root = NULL;
3340 ast_value *entity = NULL;
3341 ast_value *index = NULL;
3342 ast_value *value = NULL;
3346 if (!ast_istype(array->expression.next, ast_value)) {
3347 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3351 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3353 func = fval->constval.vfunc;
3354 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3356 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3357 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3358 value = ast_value_copy((ast_value*)array->expression.next);
3359 if (!entity || !index || !value) {
3360 parseerror(parser, "failed to create locals for array accessor");
3363 (void)!ast_value_set_name(value, "value"); /* not important */
3364 vec_push(fval->expression.params, entity);
3365 vec_push(fval->expression.params, index);
3366 vec_push(fval->expression.params, value);
3368 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3370 parseerror(parser, "failed to build accessor search tree");
3374 array->setter = fval;
3375 return ast_block_add_expr(func->blocks[0], root);
3377 if (entity) ast_delete(entity);
3378 if (index) ast_delete(index);
3379 if (value) ast_delete(value);
3380 if (root) ast_delete(root);
3386 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3388 ast_expression *root = NULL;
3389 ast_value *index = NULL;
3393 /* NOTE: checking array->expression.next rather than elemtype since
3394 * for fields elemtype is a temporary fieldtype.
3396 if (!ast_istype(array->expression.next, ast_value)) {
3397 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3401 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3403 func = fval->constval.vfunc;
3404 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3406 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3409 parseerror(parser, "failed to create locals for array accessor");
3412 vec_push(fval->expression.params, index);
3414 root = array_getter_node(parser, array, index, 0, array->expression.count);
3416 parseerror(parser, "failed to build accessor search tree");
3420 array->getter = fval;
3421 return ast_block_add_expr(func->blocks[0], root);
3423 if (index) ast_delete(index);
3424 if (root) ast_delete(root);
3430 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3431 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3439 bool variadic = false;
3441 ctx = parser_ctx(parser);
3443 /* for the sake of less code we parse-in in this function */
3444 if (!parser_next(parser)) {
3445 parseerror(parser, "expected parameter list");
3451 /* parse variables until we hit a closing paren */
3452 while (parser->tok != ')') {
3454 /* there must be commas between them */
3455 if (parser->tok != ',') {
3456 parseerror(parser, "expected comma or end of parameter list");
3459 if (!parser_next(parser)) {
3460 parseerror(parser, "expected parameter");
3466 if (parser->tok == TOKEN_DOTS) {
3467 /* '...' indicates a varargs function */
3469 if (!parser_next(parser)) {
3470 parseerror(parser, "expected parameter");
3473 if (parser->tok != ')') {
3474 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3480 /* for anything else just parse a typename */
3481 param = parse_typename(parser, NULL, NULL);
3484 vec_push(params, param);
3485 if (param->expression.vtype >= TYPE_VARIANT) {
3486 char typename[1024];
3487 ast_type_to_string((ast_expression*)param, typename, sizeof(typename));
3488 parseerror(parser, "type not supported as part of a parameter list: %s", typename);
3494 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3498 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3499 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3502 if (!parser_next(parser)) {
3503 parseerror(parser, "parse error after typename");
3507 /* now turn 'var' into a function type */
3508 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3509 fval->expression.next = (ast_expression*)var;
3510 fval->expression.variadic = variadic;
3513 var->expression.params = params;
3520 for (i = 0; i < vec_size(params); ++i)
3521 ast_delete(params[i]);
3526 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3528 ast_expression *cexp;
3529 ast_value *cval, *tmp;
3532 ctx = parser_ctx(parser);
3534 if (!parser_next(parser)) {
3536 parseerror(parser, "expected array-size");
3540 cexp = parse_expression_leave(parser, true);
3542 if (!cexp || !ast_istype(cexp, ast_value)) {
3546 parseerror(parser, "expected array-size as constant positive integer");
3549 cval = (ast_value*)cexp;
3551 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3552 tmp->expression.next = (ast_expression*)var;
3555 if (cval->expression.vtype == TYPE_INTEGER)
3556 tmp->expression.count = cval->constval.vint;
3557 else if (cval->expression.vtype == TYPE_FLOAT)
3558 tmp->expression.count = cval->constval.vfloat;
3562 parseerror(parser, "array-size must be a positive integer constant");
3567 if (parser->tok != ']') {
3569 parseerror(parser, "expected ']' after array-size");
3572 if (!parser_next(parser)) {
3574 parseerror(parser, "error after parsing array size");
3580 /* Parse a complete typename.
3581 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
3582 * but when parsing variables separated by comma
3583 * 'storebase' should point to where the base-type should be kept.
3584 * The base type makes up every bit of type information which comes *before* the
3587 * The following will be parsed in its entirety:
3589 * The 'basetype' in this case is 'void()'
3590 * and if there's a comma after it, say:
3592 * then the type-information 'void()' can be stored in 'storebase'
3594 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
3596 ast_value *var, *tmp;
3599 const char *name = NULL;
3600 bool isfield = false;
3601 bool wasarray = false;
3602 size_t morefields = 0;
3604 ctx = parser_ctx(parser);
3606 /* types may start with a dot */
3607 if (parser->tok == '.') {
3609 /* if we parsed a dot we need a typename now */
3610 if (!parser_next(parser)) {
3611 parseerror(parser, "expected typename for field definition");
3615 /* Further dots are handled seperately because they won't be part of the
3618 while (parser->tok == '.') {
3620 if (!parser_next(parser)) {
3621 parseerror(parser, "expected typename for field definition");
3626 if (parser->tok == TOKEN_IDENT)
3627 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
3628 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
3629 parseerror(parser, "expected typename");
3633 /* generate the basic type value */
3634 if (cached_typedef) {
3635 var = ast_value_copy(cached_typedef);
3636 ast_value_set_name(var, "<type(from_def)>");
3638 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
3640 for (; morefields; --morefields) {
3641 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
3642 tmp->expression.next = (ast_expression*)var;
3646 /* do not yet turn into a field - remember:
3647 * .void() foo; is a field too
3648 * .void()() foo; is a function
3652 if (!parser_next(parser)) {
3654 parseerror(parser, "parse error after typename");
3658 /* an opening paren now starts the parameter-list of a function
3659 * this is where original-QC has parameter lists.
3660 * We allow a single parameter list here.
3661 * Much like fteqcc we don't allow `float()() x`
3663 if (parser->tok == '(') {
3664 var = parse_parameter_list(parser, var);
3669 /* store the base if requested */
3671 *storebase = ast_value_copy(var);
3673 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3674 tmp->expression.next = (ast_expression*)*storebase;
3679 /* there may be a name now */
3680 if (parser->tok == TOKEN_IDENT) {
3681 name = util_strdup(parser_tokval(parser));
3683 if (!parser_next(parser)) {
3685 parseerror(parser, "error after variable or field declaration");
3690 /* now this may be an array */
3691 if (parser->tok == '[') {
3693 var = parse_arraysize(parser, var);
3698 /* This is the point where we can turn it into a field */
3700 /* turn it into a field if desired */
3701 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
3702 tmp->expression.next = (ast_expression*)var;
3706 /* now there may be function parens again */
3707 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
3708 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3709 if (parser->tok == '(' && wasarray)
3710 parseerror(parser, "arrays as part of a return type is not supported");
3711 while (parser->tok == '(') {
3712 var = parse_parameter_list(parser, var);
3721 /* finally name it */
3723 if (!ast_value_set_name(var, name)) {
3725 parseerror(parser, "internal error: failed to set name");
3728 /* free the name, ast_value_set_name duplicates */
3735 static bool parse_typedef(parser_t *parser)
3737 ast_value *typevar, *oldtype;
3738 ast_expression *old;
3740 typevar = parse_typename(parser, NULL, NULL);
3745 if ( (old = parser_find_var(parser, typevar->name)) ) {
3746 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
3747 " -> `%s` has been declared here: %s:%i",
3748 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
3749 ast_delete(typevar);
3753 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
3754 parseerror(parser, "type `%s` has already been declared here: %s:%i",
3755 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
3756 ast_delete(typevar);
3760 vec_push(parser->_typedefs, typevar);
3761 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
3763 if (parser->tok != ';') {
3764 parseerror(parser, "expected semicolon after typedef");
3767 if (!parser_next(parser)) {
3768 parseerror(parser, "parse error after typedef");
3775 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref)
3779 ast_expression *old;
3783 ast_value *basetype = NULL;
3785 bool isparam = false;
3786 bool isvector = false;
3787 bool cleanvar = true;
3788 bool wasarray = false;
3792 /* get the first complete variable */
3793 var = parse_typename(parser, &basetype, cached_typedef);
3796 ast_delete(basetype);
3804 /* Part 0: finish the type */
3805 if (parser->tok == '(') {
3806 if (opts.standard == COMPILER_QCC)
3807 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3808 var = parse_parameter_list(parser, var);
3814 /* we only allow 1-dimensional arrays */
3815 if (parser->tok == '[') {
3817 var = parse_arraysize(parser, var);
3823 if (parser->tok == '(' && wasarray) {
3824 parseerror(parser, "arrays as part of a return type is not supported");
3825 /* we'll still parse the type completely for now */
3827 /* for functions returning functions */
3828 while (parser->tok == '(') {
3829 if (opts.standard == COMPILER_QCC)
3830 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
3831 var = parse_parameter_list(parser, var);
3838 var->cvq = qualifier;
3839 /* in a noref section we simply bump the usecount */
3840 if (noref || parser->noref)
3844 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
3845 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
3846 * is then filled with the previous definition and the parameter-names replaced.
3849 /* Deal with end_sys_ vars */
3851 if (!strcmp(var->name, "end_sys_globals")) {
3853 parser->crc_globals = vec_size(parser->globals);
3856 else if (!strcmp(var->name, "end_sys_fields")) {
3858 parser->crc_fields = vec_size(parser->fields);
3861 if (was_end && var->expression.vtype == TYPE_FIELD) {
3862 if (parsewarning(parser, WARN_END_SYS_FIELDS,
3863 "global '%s' hint should not be a field",
3864 parser_tokval(parser)))
3871 if (!nofields && var->expression.vtype == TYPE_FIELD)
3873 /* deal with field declarations */
3874 old = parser_find_field(parser, var->name);
3876 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
3877 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
3886 parseerror(parser, "field `%s` already declared here: %s:%i",
3887 var->name, ast_ctx(old).file, ast_ctx(old).line);
3892 if (opts.standard == COMPILER_QCC &&
3893 (old = parser_find_global(parser, var->name)))
3895 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3896 parseerror(parser, "field `%s` already declared here: %s:%i",
3897 var->name, ast_ctx(old).file, ast_ctx(old).line);
3904 /* deal with other globals */
3905 old = parser_find_global(parser, var->name);
3906 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
3908 /* This is a function which had a prototype */
3909 if (!ast_istype(old, ast_value)) {
3910 parseerror(parser, "internal error: prototype is not an ast_value");
3914 proto = (ast_value*)old;
3915 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
3916 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
3918 ast_ctx(proto).file, ast_ctx(proto).line);
3922 /* we need the new parameter-names */
3923 for (i = 0; i < vec_size(proto->expression.params); ++i)
3924 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
3932 if (opts.standard == COMPILER_GMQCC) {
3933 parseerror(parser, "global `%s` already declared here: %s:%i",
3934 var->name, ast_ctx(old).file, ast_ctx(old).line);
3938 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
3939 "global `%s` already declared here: %s:%i",
3940 var->name, ast_ctx(old).file, ast_ctx(old).line))
3945 proto = (ast_value*)old;
3946 if (!ast_istype(old, ast_value)) {
3947 parseerror(parser, "internal error: not an ast_value");
3956 if (opts.standard == COMPILER_QCC &&
3957 (old = parser_find_field(parser, var->name)))
3959 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
3960 parseerror(parser, "global `%s` already declared here: %s:%i",
3961 var->name, ast_ctx(old).file, ast_ctx(old).line);
3968 else /* it's not a global */
3970 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
3971 if (old && !isparam) {
3972 parseerror(parser, "local `%s` already declared here: %s:%i",
3973 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3977 old = parser_find_local(parser, var->name, 0, &isparam);
3978 if (old && isparam) {
3979 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
3980 "local `%s` is shadowing a parameter", var->name))
3982 parseerror(parser, "local `%s` already declared here: %s:%i",
3983 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
3987 if (opts.standard != COMPILER_GMQCC) {
3996 * Create the global/local, and deal with vector types.
3999 if (var->expression.vtype == TYPE_VECTOR)
4001 else if (var->expression.vtype == TYPE_FIELD &&
4002 var->expression.next->expression.vtype == TYPE_VECTOR)
4006 if (!create_vector_members(var, me)) {
4013 /* deal with global variables, fields, functions */
4014 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4015 var->isfield = true;
4016 vec_push(parser->fields, (ast_expression*)var);
4017 util_htset(parser->htfields, var->name, var);
4019 for (i = 0; i < 3; ++i) {
4020 vec_push(parser->fields, (ast_expression*)me[i]);
4021 util_htset(parser->htfields, me[i]->name, me[i]);
4026 vec_push(parser->globals, (ast_expression*)var);
4027 util_htset(parser->htglobals, var->name, var);
4029 for (i = 0; i < 3; ++i) {
4030 vec_push(parser->globals, (ast_expression*)me[i]);
4031 util_htset(parser->htglobals, me[i]->name, me[i]);
4036 vec_push(localblock->locals, var);
4037 parser_addlocal(parser, var->name, (ast_expression*)var);
4039 for (i = 0; i < 3; ++i) {
4040 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4041 ast_block_collect(localblock, (ast_expression*)me[i]);
4047 me[0] = me[1] = me[2] = NULL;
4052 if (var->expression.vtype == TYPE_ARRAY) {
4054 snprintf(name, sizeof(name), "%s##SET", var->name);
4055 if (!parser_create_array_setter(parser, var, name))
4057 snprintf(name, sizeof(name), "%s##GET", var->name);
4058 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4061 else if (!localblock && !nofields &&
4062 var->expression.vtype == TYPE_FIELD &&
4063 var->expression.next->expression.vtype == TYPE_ARRAY)
4066 ast_expression *telem;
4068 ast_value *array = (ast_value*)var->expression.next;
4070 if (!ast_istype(var->expression.next, ast_value)) {
4071 parseerror(parser, "internal error: field element type must be an ast_value");
4075 snprintf(name, sizeof(name), "%s##SETF", var->name);
4076 if (!parser_create_array_field_setter(parser, array, name))
4079 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4080 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4081 tfield->expression.next = telem;
4082 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4083 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4091 if (parser->tok == ';') {
4092 ast_delete(basetype);
4093 if (!parser_next(parser)) {
4094 parseerror(parser, "error after variable declaration");
4100 if (parser->tok == ',')
4104 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4107 parseerror(parser, "missing comma or semicolon while parsing variables");
4111 if (localblock && opts.standard == COMPILER_QCC) {
4112 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4113 "initializing expression turns variable `%s` into a constant in this standard",
4120 if (parser->tok != '{') {
4121 if (parser->tok != '=') {
4122 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4126 if (!parser_next(parser)) {
4127 parseerror(parser, "error parsing initializer");
4131 else if (opts.standard == COMPILER_QCC) {
4132 parseerror(parser, "expected '=' before function body in this standard");
4135 if (parser->tok == '#') {
4136 ast_function *func = NULL;
4139 parseerror(parser, "cannot declare builtins within functions");
4142 if (var->expression.vtype != TYPE_FUNCTION) {
4143 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4146 if (!parser_next(parser)) {
4147 parseerror(parser, "expected builtin number");
4150 if (parser->tok != TOKEN_INTCONST) {
4151 parseerror(parser, "builtin number must be an integer constant");
4154 if (parser_token(parser)->constval.i < 0) {
4155 parseerror(parser, "builtin number must be an integer greater than zero");
4159 if (var->hasvalue) {
4160 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4161 "builtin `%s` has already been defined\n"
4162 " -> previous declaration here: %s:%i",
4163 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4167 func = ast_function_new(ast_ctx(var), var->name, var);
4169 parseerror(parser, "failed to allocate function for `%s`", var->name);
4172 vec_push(parser->functions, func);
4174 func->builtin = -parser_token(parser)->constval.i-1;
4177 if (!parser_next(parser)) {
4178 parseerror(parser, "expected comma or semicolon");
4180 ast_function_delete(func);
4181 var->constval.vfunc = NULL;
4185 else if (parser->tok == '{' || parser->tok == '[')
4189 parseerror(parser, "cannot declare functions within functions");
4194 ast_ctx(proto) = parser_ctx(parser);
4196 if (!parse_function_body(parser, var))
4198 ast_delete(basetype);
4199 for (i = 0; i < vec_size(parser->gotos); ++i)
4200 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4201 vec_free(parser->gotos);
4202 vec_free(parser->labels);
4205 ast_expression *cexp;
4208 cexp = parse_expression_leave(parser, true);
4213 cval = (ast_value*)cexp;
4214 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4215 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4218 if (opts.standard != COMPILER_GMQCC &&
4219 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4220 qualifier != CV_VAR)
4222 var->cvq = CV_CONST;
4224 var->hasvalue = true;
4225 if (cval->expression.vtype == TYPE_STRING)
4226 var->constval.vstring = parser_strdup(cval->constval.vstring);
4227 else if (cval->expression.vtype == TYPE_FIELD)
4228 var->constval.vfield = cval;
4230 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4235 shunt sy = { NULL, NULL };
4238 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4239 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4240 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4241 if (!parser_sy_apply_operator(parser, &sy))
4244 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4245 parseerror(parser, "internal error: leaked operands");
4246 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4256 if (parser->tok == ',') {
4257 if (!parser_next(parser)) {
4258 parseerror(parser, "expected another variable");
4262 if (parser->tok != TOKEN_IDENT) {
4263 parseerror(parser, "expected another variable");
4266 var = ast_value_copy(basetype);
4268 ast_value_set_name(var, parser_tokval(parser));
4269 if (!parser_next(parser)) {
4270 parseerror(parser, "error parsing variable declaration");
4276 if (parser->tok != ';') {
4277 parseerror(parser, "missing semicolon after variables");
4281 if (!parser_next(parser)) {
4282 parseerror(parser, "parse error after variable declaration");
4286 ast_delete(basetype);
4290 if (cleanvar && var)
4292 ast_delete(basetype);
4296 ast_delete(basetype);
4297 if (cleanvar && var)
4299 if (me[0]) ast_member_delete(me[0]);
4300 if (me[1]) ast_member_delete(me[1]);
4301 if (me[2]) ast_member_delete(me[2]);
4305 static bool parser_global_statement(parser_t *parser)
4309 ast_value *istype = NULL;
4311 if (parser->tok == TOKEN_IDENT)
4312 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4314 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4316 return parse_variable(parser, NULL, false, CV_NONE, istype, false);
4318 else if (parse_var_qualifiers(parser, false, &cvq, &noref))
4320 if (cvq == CV_WRONG)
4322 return parse_variable(parser, NULL, true, cvq, NULL, noref);
4324 else if (parser->tok == TOKEN_KEYWORD)
4326 if (!strcmp(parser_tokval(parser), "typedef")) {
4327 if (!parser_next(parser)) {
4328 parseerror(parser, "expected type definition after 'typedef'");
4331 return parse_typedef(parser);
4333 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4336 else if (parser->tok == '#')
4338 return parse_pragma(parser);
4340 else if (parser->tok == '$')
4342 if (!parser_next(parser)) {
4343 parseerror(parser, "parse error");
4349 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4355 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4357 return util_crc16(old, str, strlen(str));
4360 static void progdefs_crc_file(const char *str)
4362 /* write to progdefs.h here */
4366 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4368 old = progdefs_crc_sum(old, str);
4369 progdefs_crc_file(str);
4373 static void generate_checksum(parser_t *parser)
4375 uint16_t crc = 0xFFFF;
4379 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4380 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4382 progdefs_crc_file("\tint\tpad;\n");
4383 progdefs_crc_file("\tint\tofs_return[3];\n");
4384 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4385 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4386 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4387 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4388 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4389 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4390 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4391 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4393 for (i = 0; i < parser->crc_globals; ++i) {
4394 if (!ast_istype(parser->globals[i], ast_value))
4396 value = (ast_value*)(parser->globals[i]);
4397 switch (value->expression.vtype) {
4398 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4399 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4400 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4401 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4403 crc = progdefs_crc_both(crc, "\tint\t");
4406 crc = progdefs_crc_both(crc, value->name);
4407 crc = progdefs_crc_both(crc, ";\n");
4409 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4410 for (i = 0; i < parser->crc_fields; ++i) {
4411 if (!ast_istype(parser->fields[i], ast_value))
4413 value = (ast_value*)(parser->fields[i]);
4414 switch (value->expression.next->expression.vtype) {
4415 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4416 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4417 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4418 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4420 crc = progdefs_crc_both(crc, "\tint\t");
4423 crc = progdefs_crc_both(crc, value->name);
4424 crc = progdefs_crc_both(crc, ";\n");
4426 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4431 static parser_t *parser;
4437 parser = (parser_t*)mem_a(sizeof(parser_t));
4441 memset(parser, 0, sizeof(*parser));
4443 for (i = 0; i < operator_count; ++i) {
4444 if (operators[i].id == opid1('=')) {
4445 parser->assign_op = operators+i;
4449 if (!parser->assign_op) {
4450 printf("internal error: initializing parser: failed to find assign operator\n");
4455 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4456 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4457 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4458 vec_push(parser->_blocktypedefs, 0);
4462 bool parser_compile()
4464 /* initial lexer/parser state */
4465 parser->lex->flags.noops = true;
4467 if (parser_next(parser))
4469 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4471 if (!parser_global_statement(parser)) {
4472 if (parser->tok == TOKEN_EOF)
4473 parseerror(parser, "unexpected eof");
4474 else if (!parser->errors)
4475 parseerror(parser, "there have been errors, bailing out");
4476 lex_close(parser->lex);
4482 parseerror(parser, "parse error");
4483 lex_close(parser->lex);
4488 lex_close(parser->lex);
4491 return !parser->errors;
4494 bool parser_compile_file(const char *filename)
4496 parser->lex = lex_open(filename);
4498 con_err("failed to open file \"%s\"\n", filename);
4501 return parser_compile();
4504 bool parser_compile_string_len(const char *name, const char *str, size_t len)
4506 parser->lex = lex_open_string(str, len, name);
4508 con_err("failed to create lexer for string \"%s\"\n", name);
4511 return parser_compile();
4514 bool parser_compile_string(const char *name, const char *str)
4516 parser->lex = lex_open_string(str, strlen(str), name);
4518 con_err("failed to create lexer for string \"%s\"\n", name);
4521 return parser_compile();
4524 void parser_cleanup()
4527 for (i = 0; i < vec_size(parser->accessors); ++i) {
4528 ast_delete(parser->accessors[i]->constval.vfunc);
4529 parser->accessors[i]->constval.vfunc = NULL;
4530 ast_delete(parser->accessors[i]);
4532 for (i = 0; i < vec_size(parser->functions); ++i) {
4533 ast_delete(parser->functions[i]);
4535 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4536 ast_delete(parser->imm_vector[i]);
4538 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4539 ast_delete(parser->imm_string[i]);
4541 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4542 ast_delete(parser->imm_float[i]);
4544 for (i = 0; i < vec_size(parser->fields); ++i) {
4545 ast_delete(parser->fields[i]);
4547 for (i = 0; i < vec_size(parser->globals); ++i) {
4548 ast_delete(parser->globals[i]);
4550 vec_free(parser->accessors);
4551 vec_free(parser->functions);
4552 vec_free(parser->imm_vector);
4553 vec_free(parser->imm_string);
4554 vec_free(parser->imm_float);
4555 vec_free(parser->globals);
4556 vec_free(parser->fields);
4558 for (i = 0; i < vec_size(parser->variables); ++i)
4559 util_htdel(parser->variables[i]);
4560 vec_free(parser->variables);
4561 vec_free(parser->_blocklocals);
4562 vec_free(parser->_locals);
4564 for (i = 0; i < vec_size(parser->_typedefs); ++i)
4565 ast_delete(parser->_typedefs[i]);
4566 vec_free(parser->_typedefs);
4567 for (i = 0; i < vec_size(parser->typedefs); ++i)
4568 util_htdel(parser->typedefs[i]);
4569 vec_free(parser->typedefs);
4570 vec_free(parser->_blocktypedefs);
4572 vec_free(parser->_block_ctx);
4574 vec_free(parser->labels);
4575 vec_free(parser->gotos);
4580 bool parser_finish(const char *output)
4586 if (!parser->errors)
4588 ir = ir_builder_new("gmqcc_out");
4590 con_out("failed to allocate builder\n");
4594 for (i = 0; i < vec_size(parser->fields); ++i) {
4597 if (!ast_istype(parser->fields[i], ast_value))
4599 field = (ast_value*)parser->fields[i];
4600 hasvalue = field->hasvalue;
4601 field->hasvalue = false;
4602 if (!ast_global_codegen((ast_value*)field, ir, true)) {
4603 con_out("failed to generate field %s\n", field->name);
4604 ir_builder_delete(ir);
4609 ast_expression *subtype;
4610 field->hasvalue = true;
4611 subtype = field->expression.next;
4612 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
4613 if (subtype->expression.vtype == TYPE_FIELD)
4614 ifld->fieldtype = subtype->expression.next->expression.vtype;
4615 else if (subtype->expression.vtype == TYPE_FUNCTION)
4616 ifld->outtype = subtype->expression.next->expression.vtype;
4617 (void)!ir_value_set_field(field->ir_v, ifld);
4620 for (i = 0; i < vec_size(parser->globals); ++i) {
4622 if (!ast_istype(parser->globals[i], ast_value))
4624 asvalue = (ast_value*)(parser->globals[i]);
4625 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
4626 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
4627 "unused global: `%s`", asvalue->name);
4629 if (!ast_global_codegen(asvalue, ir, false)) {
4630 con_out("failed to generate global %s\n", asvalue->name);
4631 ir_builder_delete(ir);
4635 for (i = 0; i < vec_size(parser->imm_float); ++i) {
4636 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
4637 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
4638 ir_builder_delete(ir);
4642 for (i = 0; i < vec_size(parser->imm_string); ++i) {
4643 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
4644 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
4645 ir_builder_delete(ir);
4649 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
4650 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
4651 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
4652 ir_builder_delete(ir);
4656 for (i = 0; i < vec_size(parser->globals); ++i) {
4658 if (!ast_istype(parser->globals[i], ast_value))
4660 asvalue = (ast_value*)(parser->globals[i]);
4661 if (!ast_generate_accessors(asvalue, ir)) {
4662 ir_builder_delete(ir);
4666 for (i = 0; i < vec_size(parser->fields); ++i) {
4668 asvalue = (ast_value*)(parser->fields[i]->expression.next);
4670 if (!ast_istype((ast_expression*)asvalue, ast_value))
4672 if (asvalue->expression.vtype != TYPE_ARRAY)
4674 if (!ast_generate_accessors(asvalue, ir)) {
4675 ir_builder_delete(ir);
4679 for (i = 0; i < vec_size(parser->functions); ++i) {
4680 if (!ast_function_codegen(parser->functions[i], ir)) {
4681 con_out("failed to generate function %s\n", parser->functions[i]->name);
4682 ir_builder_delete(ir);
4687 ir_builder_dump(ir, con_out);
4688 for (i = 0; i < vec_size(parser->functions); ++i) {
4689 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
4690 con_out("failed to finalize function %s\n", parser->functions[i]->name);
4691 ir_builder_delete(ir);
4698 ir_builder_dump(ir, con_out);
4700 generate_checksum(parser);
4702 if (!ir_builder_generate(ir, output)) {
4703 con_out("*** failed to generate output file\n");
4704 ir_builder_delete(ir);
4709 ir_builder_delete(ir);
4713 con_out("*** there were compile errors\n");