2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define PARSER_HT_LOCALS 2
30 #define PARSER_HT_SIZE 512
31 #define TYPEDEF_HT_SIZE 512
33 static void parser_enterblock(parser_t *parser);
34 static bool parser_leaveblock(parser_t *parser);
35 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
36 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
37 static bool parse_typedef(parser_t *parser);
38 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
39 static ast_block* parse_block(parser_t *parser);
40 static bool parse_block_into(parser_t *parser, ast_block *block);
41 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
42 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
43 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
44 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
45 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
46 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
47 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
49 static void parseerror(parser_t *parser, const char *fmt, ...)
53 vcompile_error(parser->lex->tok.ctx, fmt, ap);
57 /* returns true if it counts as an error */
58 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
63 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
68 /**********************************************************************
72 static bool parser_next(parser_t *parser)
74 /* lex_do kills the previous token */
75 parser->tok = lex_do(parser->lex);
76 if (parser->tok == TOKEN_EOF)
78 if (parser->tok >= TOKEN_ERROR) {
79 parseerror(parser, "lex error");
85 #define parser_tokval(p) ((p)->lex->tok.value)
86 #define parser_token(p) (&((p)->lex->tok))
88 char *parser_strdup(const char *str)
91 /* actually dup empty strings */
92 char *out = (char*)mem_a(1);
96 return util_strdup(str);
99 static ast_expression* parser_find_field(parser_t *parser, const char *name)
101 return ( ast_expression*)util_htget(parser->htfields, name);
104 static ast_expression* parser_find_label(parser_t *parser, const char *name)
107 for(i = 0; i < vec_size(parser->labels); i++)
108 if (!strcmp(parser->labels[i]->name, name))
109 return (ast_expression*)parser->labels[i];
113 ast_expression* parser_find_global(parser_t *parser, const char *name)
115 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
118 return (ast_expression*)util_htget(parser->htglobals, name);
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
125 if (!parser->function)
127 fun = parser->function->vtype;
128 for (i = 0; i < vec_size(fun->expression.params); ++i) {
129 if (!strcmp(fun->expression.params[i]->name, name))
130 return (ast_expression*)(fun->expression.params[i]);
135 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
140 hash = util_hthash(parser->htglobals, name);
143 for (i = vec_size(parser->variables); i > upto;) {
145 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
149 return parser_find_param(parser, name);
152 static ast_expression* parser_find_var(parser_t *parser, const char *name)
156 v = parser_find_local(parser, name, 0, &dummy);
157 if (!v) v = parser_find_global(parser, name);
161 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
165 hash = util_hthash(parser->typedefs[0], name);
167 for (i = vec_size(parser->typedefs); i > upto;) {
169 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
177 size_t etype; /* 0 = expression, others are operators */
181 ast_block *block; /* for commas and function calls */
200 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
211 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
215 e.out = (ast_expression*)v;
222 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
224 e.etype = 1 + (op - operators);
233 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
244 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
245 * so we need to rotate it to become ent.(foo[n]).
247 static bool rotate_entfield_array_index_nodes(ast_expression **out)
249 ast_array_index *index, *oldindex;
250 ast_entfield *entfield;
254 ast_expression *entity;
256 lex_ctx_t ctx = ast_ctx(*out);
258 if (!ast_istype(*out, ast_array_index))
260 index = (ast_array_index*)*out;
262 if (!ast_istype(index->array, ast_entfield))
264 entfield = (ast_entfield*)index->array;
266 if (!ast_istype(entfield->field, ast_value))
268 field = (ast_value*)entfield->field;
271 entity = entfield->entity;
275 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
276 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
277 *out = (ast_expression*)entfield;
279 oldindex->array = NULL;
280 oldindex->index = NULL;
281 ast_delete(oldindex);
286 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
288 if (ast_istype(expr, ast_value)) {
289 ast_value *val = (ast_value*)expr;
290 if (val->cvq == CV_CONST) {
291 if (val->name[0] == '#') {
292 compile_error(ctx, "invalid assignment to a literal constant");
296 * To work around quakeworld we must elide the error and make it
299 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
300 compile_error(ctx, "assignment to constant `%s`", val->name);
302 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
309 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
313 ast_expression *out = NULL;
314 ast_expression *exprs[3];
315 ast_block *blocks[3];
316 ast_binstore *asbinstore;
317 size_t i, assignop, addop, subop;
318 qcint_t generated_op = 0;
323 if (!vec_size(sy->ops)) {
324 parseerror(parser, "internal error: missing operator");
328 if (vec_last(sy->ops).isparen) {
329 parseerror(parser, "unmatched parenthesis");
333 op = &operators[vec_last(sy->ops).etype - 1];
334 ctx = vec_last(sy->ops).ctx;
336 if (vec_size(sy->out) < op->operands) {
337 if (op->flags & OP_PREFIX)
338 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
339 else /* this should have errored previously already */
340 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
344 vec_shrinkby(sy->ops, 1);
346 /* op(:?) has no input and no output */
350 vec_shrinkby(sy->out, op->operands);
351 for (i = 0; i < op->operands; ++i) {
352 exprs[i] = sy->out[vec_size(sy->out)+i].out;
353 blocks[i] = sy->out[vec_size(sy->out)+i].block;
355 if (exprs[i]->vtype == TYPE_NOEXPR &&
356 !(i != 0 && op->id == opid2('?',':')) &&
357 !(i == 1 && op->id == opid1('.')))
359 if (ast_istype(exprs[i], ast_label))
360 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
362 compile_error(ast_ctx(exprs[i]), "not an expression");
363 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
367 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
368 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
372 #define NotSameType(T) \
373 (exprs[0]->vtype != exprs[1]->vtype || \
374 exprs[0]->vtype != T)
379 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
383 if (exprs[0]->vtype == TYPE_VECTOR &&
384 exprs[1]->vtype == TYPE_NOEXPR)
386 if (exprs[1] == (ast_expression*)parser->const_vec[0])
387 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
388 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
389 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
390 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
391 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
393 compile_error(ctx, "access to invalid vector component");
397 else if (exprs[0]->vtype == TYPE_ENTITY) {
398 if (exprs[1]->vtype != TYPE_FIELD) {
399 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
402 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
404 else if (exprs[0]->vtype == TYPE_VECTOR) {
405 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
409 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
415 if (exprs[0]->vtype != TYPE_ARRAY &&
416 !(exprs[0]->vtype == TYPE_FIELD &&
417 exprs[0]->next->vtype == TYPE_ARRAY))
419 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
420 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
423 if (exprs[1]->vtype != TYPE_FLOAT) {
424 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
425 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
428 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
429 if (rotate_entfield_array_index_nodes(&out))
432 /* This is not broken in fteqcc anymore */
433 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
434 /* this error doesn't need to make us bail out */
435 (void)!parsewarning(parser, WARN_EXTENSIONS,
436 "accessing array-field members of an entity without parenthesis\n"
437 " -> this is an extension from -std=gmqcc");
444 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
445 vec_push(sy->out, syexp(ctx, exprs[0]));
446 vec_push(sy->out, syexp(ctx, exprs[1]));
447 vec_last(sy->argc)++;
451 if (!ast_block_add_expr(blocks[0], exprs[1]))
454 blocks[0] = ast_block_new(ctx);
455 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
456 !ast_block_add_expr(blocks[0], exprs[1]))
461 ast_block_set_type(blocks[0], exprs[1]);
463 vec_push(sy->out, syblock(ctx, blocks[0]));
470 if ((out = fold_op(parser->fold, op, exprs)))
473 if (exprs[0]->vtype != TYPE_FLOAT &&
474 exprs[0]->vtype != TYPE_VECTOR) {
475 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
476 type_name[exprs[0]->vtype]);
479 if (exprs[0]->vtype == TYPE_FLOAT)
480 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
482 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
486 if (!(out = fold_op(parser->fold, op, exprs))) {
487 switch (exprs[0]->vtype) {
489 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
495 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
496 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
498 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
500 /* we don't constant-fold NOT for these types */
502 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
505 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
508 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
509 type_name[exprs[0]->vtype]);
516 if (exprs[0]->vtype != exprs[1]->vtype ||
517 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
519 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
520 type_name[exprs[0]->vtype],
521 type_name[exprs[1]->vtype]);
524 if (!(out = fold_op(parser->fold, op, exprs))) {
525 switch (exprs[0]->vtype) {
527 out = fold_binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
530 out = fold_binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
533 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
534 type_name[exprs[0]->vtype],
535 type_name[exprs[1]->vtype]);
541 if (exprs[0]->vtype != exprs[1]->vtype ||
542 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
544 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
545 type_name[exprs[1]->vtype],
546 type_name[exprs[0]->vtype]);
549 if (!(out = fold_op(parser->fold, op, exprs))) {
550 switch (exprs[0]->vtype) {
552 out = fold_binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
555 out = fold_binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
558 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
559 type_name[exprs[1]->vtype],
560 type_name[exprs[0]->vtype]);
566 if (exprs[0]->vtype != exprs[1]->vtype &&
567 !(exprs[0]->vtype == TYPE_VECTOR &&
568 exprs[1]->vtype == TYPE_FLOAT) &&
569 !(exprs[1]->vtype == TYPE_VECTOR &&
570 exprs[0]->vtype == TYPE_FLOAT)
573 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
574 type_name[exprs[1]->vtype],
575 type_name[exprs[0]->vtype]);
578 if (!(out = fold_op(parser->fold, op, exprs))) {
579 switch (exprs[0]->vtype) {
581 if (exprs[1]->vtype == TYPE_VECTOR)
582 out = fold_binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
584 out = fold_binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
587 if (exprs[1]->vtype == TYPE_FLOAT)
588 out = fold_binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
590 out = fold_binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
593 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
594 type_name[exprs[1]->vtype],
595 type_name[exprs[0]->vtype]);
602 if (exprs[1]->vtype != TYPE_FLOAT) {
603 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
604 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
605 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
608 if (!(out = fold_op(parser->fold, op, exprs))) {
609 if (exprs[0]->vtype == TYPE_FLOAT)
610 out = fold_binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
612 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
613 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
614 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
621 if (NotSameType(TYPE_FLOAT)) {
622 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
623 type_name[exprs[0]->vtype],
624 type_name[exprs[1]->vtype]);
626 } else if (!(out = fold_op(parser->fold, op, exprs))) {
627 /* generate a call to __builtin_mod */
628 ast_expression *mod = intrin_func(parser->intrin, "mod");
629 ast_call *call = NULL;
630 if (!mod) return false; /* can return null for missing floor */
632 call = ast_call_new(parser_ctx(parser), mod);
633 vec_push(call->params, exprs[0]);
634 vec_push(call->params, exprs[1]);
636 out = (ast_expression*)call;
641 compile_error(ctx, "%= is unimplemented");
647 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
648 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
649 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
651 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
652 type_name[exprs[0]->vtype],
653 type_name[exprs[1]->vtype]);
657 if (!(out = fold_op(parser->fold, op, exprs))) {
659 * IF the first expression is float, the following will be too
660 * since scalar ^ vector is not allowed.
662 if (exprs[0]->vtype == TYPE_FLOAT) {
663 out = fold_binary(ctx,
664 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
668 * The first is a vector: vector is allowed to bitop with vector and
669 * with scalar, branch here for the second operand.
671 if (exprs[1]->vtype == TYPE_VECTOR) {
673 * Bitop all the values of the vector components against the
674 * vectors components in question.
676 out = fold_binary(ctx,
677 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
680 out = fold_binary(ctx,
681 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
690 case opid3('<','<','='):
691 case opid3('>','>','='):
692 if(!(out = fold_op(parser->fold, op, exprs))) {
693 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
699 generated_op += 1; /* INSTR_OR */
701 generated_op += INSTR_AND;
702 if (!(out = fold_op(parser->fold, op, exprs))) {
703 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
704 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
705 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
706 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
709 for (i = 0; i < 2; ++i) {
710 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
711 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
713 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
715 exprs[i] = out; out = NULL;
716 if (OPTS_FLAG(PERL_LOGIC)) {
717 /* here we want to keep the right expressions' type */
721 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
724 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
726 exprs[i] = out; out = NULL;
727 if (OPTS_FLAG(PERL_LOGIC)) {
728 /* here we want to keep the right expressions' type */
733 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
738 if (vec_last(sy->paren) != PAREN_TERNARY2) {
739 compile_error(ctx, "mismatched parenthesis/ternary");
743 if (!ast_compare_type(exprs[1], exprs[2])) {
744 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
745 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
746 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
749 if (!(out = fold_op(parser->fold, op, exprs)))
750 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
753 case opid2('*', '*'):
754 if (NotSameType(TYPE_FLOAT)) {
755 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
756 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
757 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
762 if (!(out = fold_op(parser->fold, op, exprs))) {
763 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
764 vec_push(gencall->params, exprs[0]);
765 vec_push(gencall->params, exprs[1]);
766 out = (ast_expression*)gencall;
770 case opid2('>', '<'):
771 if (NotSameType(TYPE_VECTOR)) {
772 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
773 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
774 compile_error(ctx, "invalid types used in cross product: %s and %s",
779 if (!(out = fold_op(parser->fold, op, exprs))) {
790 case opid3('<','=','>'): /* -1, 0, or 1 */
791 if (NotSameType(TYPE_FLOAT)) {
792 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
793 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
794 compile_error(ctx, "invalid types used in comparision: %s and %s",
800 if (!(out = fold_op(parser->fold, op, exprs))) {
801 /* This whole block is NOT fold_binary safe */
802 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
804 eq->refs = AST_REF_NONE;
807 out = (ast_expression*)ast_ternary_new(ctx,
808 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
810 (ast_expression*)parser->fold->imm_float[2],
813 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
815 (ast_expression*)parser->fold->imm_float[0],
818 (ast_expression*)parser->fold->imm_float[1]
828 generated_op += 1; /* INSTR_GT */
830 generated_op += 1; /* INSTR_LT */
831 case opid2('>', '='):
832 generated_op += 1; /* INSTR_GE */
833 case opid2('<', '='):
834 generated_op += INSTR_LE;
835 if (NotSameType(TYPE_FLOAT)) {
836 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
837 type_name[exprs[0]->vtype],
838 type_name[exprs[1]->vtype]);
841 if (!(out = fold_op(parser->fold, op, exprs)))
842 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
844 case opid2('!', '='):
845 if (exprs[0]->vtype != exprs[1]->vtype) {
846 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
847 type_name[exprs[0]->vtype],
848 type_name[exprs[1]->vtype]);
851 if (!(out = fold_op(parser->fold, op, exprs)))
852 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
854 case opid2('=', '='):
855 if (exprs[0]->vtype != exprs[1]->vtype) {
856 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
857 type_name[exprs[0]->vtype],
858 type_name[exprs[1]->vtype]);
861 if (!(out = fold_op(parser->fold, op, exprs)))
862 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
866 if (ast_istype(exprs[0], ast_entfield)) {
867 ast_expression *field = ((ast_entfield*)exprs[0])->field;
868 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
869 exprs[0]->vtype == TYPE_FIELD &&
870 exprs[0]->next->vtype == TYPE_VECTOR)
872 assignop = type_storep_instr[TYPE_VECTOR];
875 assignop = type_storep_instr[exprs[0]->vtype];
876 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
878 ast_type_to_string(field->next, ty1, sizeof(ty1));
879 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
880 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
881 field->next->vtype == TYPE_FUNCTION &&
882 exprs[1]->vtype == TYPE_FUNCTION)
884 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
885 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
888 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
893 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
894 exprs[0]->vtype == TYPE_FIELD &&
895 exprs[0]->next->vtype == TYPE_VECTOR)
897 assignop = type_store_instr[TYPE_VECTOR];
900 assignop = type_store_instr[exprs[0]->vtype];
903 if (assignop == VINSTR_END) {
904 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
905 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
906 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
908 else if (!ast_compare_type(exprs[0], exprs[1]))
910 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
911 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
912 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
913 exprs[0]->vtype == TYPE_FUNCTION &&
914 exprs[1]->vtype == TYPE_FUNCTION)
916 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
917 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
920 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
923 (void)check_write_to(ctx, exprs[0]);
924 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
926 case opid3('+','+','P'):
927 case opid3('-','-','P'):
929 if (exprs[0]->vtype != TYPE_FLOAT) {
930 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
931 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
934 if (op->id == opid3('+','+','P'))
938 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
939 if (ast_istype(exprs[0], ast_entfield)) {
940 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
942 (ast_expression*)parser->fold->imm_float[1]);
944 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
946 (ast_expression*)parser->fold->imm_float[1]);
949 case opid3('S','+','+'):
950 case opid3('S','-','-'):
952 if (exprs[0]->vtype != TYPE_FLOAT) {
953 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
954 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
957 if (op->id == opid3('S','+','+')) {
964 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
965 if (ast_istype(exprs[0], ast_entfield)) {
966 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
968 (ast_expression*)parser->fold->imm_float[1]);
970 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
972 (ast_expression*)parser->fold->imm_float[1]);
976 out = fold_binary(ctx, subop,
978 (ast_expression*)parser->fold->imm_float[1]);
983 if (exprs[0]->vtype != exprs[1]->vtype ||
984 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
986 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
987 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
988 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
992 (void)check_write_to(ctx, exprs[0]);
993 if (ast_istype(exprs[0], ast_entfield))
994 assignop = type_storep_instr[exprs[0]->vtype];
996 assignop = type_store_instr[exprs[0]->vtype];
997 switch (exprs[0]->vtype) {
999 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1000 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1001 exprs[0], exprs[1]);
1004 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1005 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1006 exprs[0], exprs[1]);
1009 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1010 type_name[exprs[0]->vtype],
1011 type_name[exprs[1]->vtype]);
1015 case opid2('*','='):
1016 case opid2('/','='):
1017 if (exprs[1]->vtype != TYPE_FLOAT ||
1018 !(exprs[0]->vtype == TYPE_FLOAT ||
1019 exprs[0]->vtype == TYPE_VECTOR))
1021 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1022 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1023 compile_error(ctx, "invalid types used in expression: %s and %s",
1027 (void)check_write_to(ctx, exprs[0]);
1028 if (ast_istype(exprs[0], ast_entfield))
1029 assignop = type_storep_instr[exprs[0]->vtype];
1031 assignop = type_store_instr[exprs[0]->vtype];
1032 switch (exprs[0]->vtype) {
1034 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1035 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1036 exprs[0], exprs[1]);
1039 if (op->id == opid2('*','=')) {
1040 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1041 exprs[0], exprs[1]);
1043 out = fold_binary(ctx, INSTR_DIV_F,
1044 (ast_expression*)parser->fold->imm_float[1],
1047 compile_error(ctx, "internal error: failed to generate division");
1050 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1055 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1056 type_name[exprs[0]->vtype],
1057 type_name[exprs[1]->vtype]);
1061 case opid2('&','='):
1062 case opid2('|','='):
1063 case opid2('^','='):
1064 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1065 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1066 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1067 compile_error(ctx, "invalid types used in expression: %s and %s",
1071 (void)check_write_to(ctx, exprs[0]);
1072 if (ast_istype(exprs[0], ast_entfield))
1073 assignop = type_storep_instr[exprs[0]->vtype];
1075 assignop = type_store_instr[exprs[0]->vtype];
1076 if (exprs[0]->vtype == TYPE_FLOAT)
1077 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1078 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1079 exprs[0], exprs[1]);
1081 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1082 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1083 exprs[0], exprs[1]);
1085 case opid3('&','~','='):
1086 /* This is like: a &= ~(b);
1087 * But QC has no bitwise-not, so we implement it as
1090 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1091 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1092 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1093 compile_error(ctx, "invalid types used in expression: %s and %s",
1097 if (ast_istype(exprs[0], ast_entfield))
1098 assignop = type_storep_instr[exprs[0]->vtype];
1100 assignop = type_store_instr[exprs[0]->vtype];
1101 if (exprs[0]->vtype == TYPE_FLOAT)
1102 out = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1104 out = fold_binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1107 (void)check_write_to(ctx, exprs[0]);
1108 if (exprs[0]->vtype == TYPE_FLOAT)
1109 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1111 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1112 asbinstore->keep_dest = true;
1113 out = (ast_expression*)asbinstore;
1116 case opid2('~', 'P'):
1117 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1118 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1119 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1122 if (!(out = fold_op(parser->fold, op, exprs))) {
1123 if (exprs[0]->vtype == TYPE_FLOAT) {
1124 out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1126 out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1133 compile_error(ctx, "failed to apply operator %s", op->op);
1137 vec_push(sy->out, syexp(ctx, out));
1141 static bool parser_close_call(parser_t *parser, shunt *sy)
1143 /* was a function call */
1144 ast_expression *fun;
1145 ast_value *funval = NULL;
1149 size_t paramcount, i;
1152 fid = vec_last(sy->ops).off;
1153 vec_shrinkby(sy->ops, 1);
1155 /* out[fid] is the function
1156 * everything above is parameters...
1158 if (!vec_size(sy->argc)) {
1159 parseerror(parser, "internal error: no argument counter available");
1163 paramcount = vec_last(sy->argc);
1166 if (vec_size(sy->out) < fid) {
1167 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1168 (unsigned long)vec_size(sy->out),
1170 (unsigned long)paramcount);
1175 * TODO handle this at the intrinsic level with an ast_intrinsic
1178 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1180 if (fid+2 != vec_size(sy->out) ||
1181 vec_last(sy->out).block)
1183 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1186 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1187 ast_unref(vec_last(sy->out).out);
1188 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1189 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1190 vec_shrinkby(sy->out, 1);
1195 * Now we need to determine if the function that is being called is
1196 * an intrinsic so we can evaluate if the arguments to it are constant
1197 * and than fruitfully fold them.
1199 #define fold_can_1(X) \
1200 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1201 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1203 if (fid + 1 < vec_size(sy->out))
1206 for (i = 0; i < paramcount; ++i) {
1207 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1214 * All is well which ends well, if we make it into here we can ignore the
1215 * intrinsic call and just evaluate it i.e constant fold it.
1217 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1218 ast_expression **exprs = NULL;
1219 ast_expression *foldval = NULL;
1221 for (i = 0; i < paramcount; i++)
1222 vec_push(exprs, sy->out[fid+1 + i].out);
1224 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1230 * Blub: what sorts of unreffing and resizing of
1231 * sy->out should I be doing here?
1233 sy->out[fid] = syexp(foldval->node.context, foldval);
1234 vec_shrinkby(sy->out, paramcount);
1241 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1246 if (fid+1 + paramcount != vec_size(sy->out)) {
1247 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1248 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1252 for (i = 0; i < paramcount; ++i)
1253 vec_push(call->params, sy->out[fid+1 + i].out);
1254 vec_shrinkby(sy->out, paramcount);
1255 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1256 if (parser->max_param_count < paramcount)
1257 parser->max_param_count = paramcount;
1259 if (ast_istype(fun, ast_value)) {
1260 funval = (ast_value*)fun;
1261 if ((fun->flags & AST_FLAG_VARIADIC) &&
1262 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1264 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1268 /* overwrite fid, the function, with a call */
1269 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1271 if (fun->vtype != TYPE_FUNCTION) {
1272 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1277 parseerror(parser, "could not determine function return type");
1280 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1282 if (fun->flags & AST_FLAG_DEPRECATED) {
1284 return !parsewarning(parser, WARN_DEPRECATED,
1285 "call to function (which is marked deprecated)\n",
1286 "-> it has been declared here: %s:%i",
1287 ast_ctx(fun).file, ast_ctx(fun).line);
1290 return !parsewarning(parser, WARN_DEPRECATED,
1291 "call to `%s` (which is marked deprecated)\n"
1292 "-> `%s` declared here: %s:%i",
1293 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1295 return !parsewarning(parser, WARN_DEPRECATED,
1296 "call to `%s` (deprecated: %s)\n"
1297 "-> `%s` declared here: %s:%i",
1298 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1302 if (vec_size(fun->params) != paramcount &&
1303 !((fun->flags & AST_FLAG_VARIADIC) &&
1304 vec_size(fun->params) < paramcount))
1306 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1308 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1309 "too %s parameters for call to %s: expected %i, got %i\n"
1310 " -> `%s` has been declared here: %s:%i",
1311 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1312 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1314 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1315 "too %s parameters for function call: expected %i, got %i\n"
1316 " -> it has been declared here: %s:%i",
1317 fewmany, (int)vec_size(fun->params), (int)paramcount,
1318 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1325 static bool parser_close_paren(parser_t *parser, shunt *sy)
1327 if (!vec_size(sy->ops)) {
1328 parseerror(parser, "unmatched closing paren");
1332 while (vec_size(sy->ops)) {
1333 if (vec_last(sy->ops).isparen) {
1334 if (vec_last(sy->paren) == PAREN_FUNC) {
1336 if (!parser_close_call(parser, sy))
1340 if (vec_last(sy->paren) == PAREN_EXPR) {
1342 if (!vec_size(sy->out)) {
1343 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1344 vec_shrinkby(sy->ops, 1);
1347 vec_shrinkby(sy->ops, 1);
1350 if (vec_last(sy->paren) == PAREN_INDEX) {
1352 /* pop off the parenthesis */
1353 vec_shrinkby(sy->ops, 1);
1354 /* then apply the index operator */
1355 if (!parser_sy_apply_operator(parser, sy))
1359 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1360 vec_last(sy->paren) = PAREN_TERNARY2;
1361 /* pop off the parenthesis */
1362 vec_shrinkby(sy->ops, 1);
1365 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1368 if (!parser_sy_apply_operator(parser, sy))
1374 static void parser_reclassify_token(parser_t *parser)
1377 if (parser->tok >= TOKEN_START)
1379 for (i = 0; i < operator_count; ++i) {
1380 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1381 parser->tok = TOKEN_OPERATOR;
1387 static ast_expression* parse_vararg_do(parser_t *parser)
1389 ast_expression *idx, *out;
1391 ast_value *funtype = parser->function->vtype;
1392 lex_ctx_t ctx = parser_ctx(parser);
1394 if (!parser->function->varargs) {
1395 parseerror(parser, "function has no variable argument list");
1399 if (!parser_next(parser) || parser->tok != '(') {
1400 parseerror(parser, "expected parameter index and type in parenthesis");
1403 if (!parser_next(parser)) {
1404 parseerror(parser, "error parsing parameter index");
1408 idx = parse_expression_leave(parser, true, false, false);
1412 if (parser->tok != ',') {
1413 if (parser->tok != ')') {
1415 parseerror(parser, "expected comma after parameter index");
1418 /* vararg piping: ...(start) */
1419 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1423 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1425 parseerror(parser, "expected typename for vararg");
1429 typevar = parse_typename(parser, NULL, NULL, NULL);
1435 if (parser->tok != ')') {
1437 ast_delete(typevar);
1438 parseerror(parser, "expected closing paren");
1442 if (funtype->expression.varparam &&
1443 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1447 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1448 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1449 compile_error(ast_ctx(typevar),
1450 "function was declared to take varargs of type `%s`, requested type is: %s",
1454 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1455 ast_type_adopt(out, typevar);
1456 ast_delete(typevar);
1460 static ast_expression* parse_vararg(parser_t *parser)
1462 bool old_noops = parser->lex->flags.noops;
1464 ast_expression *out;
1466 parser->lex->flags.noops = true;
1467 out = parse_vararg_do(parser);
1469 parser->lex->flags.noops = old_noops;
1473 /* not to be exposed */
1474 bool ftepp_predef_exists(const char *name);
1475 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1477 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1478 parser->tok == TOKEN_IDENT &&
1479 !strcmp(parser_tokval(parser), "_"))
1481 /* a translatable string */
1484 parser->lex->flags.noops = true;
1485 if (!parser_next(parser) || parser->tok != '(') {
1486 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1489 parser->lex->flags.noops = false;
1490 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1491 parseerror(parser, "expected a constant string in translatable-string extension");
1494 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1497 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1499 if (!parser_next(parser) || parser->tok != ')') {
1500 parseerror(parser, "expected closing paren after translatable string");
1505 else if (parser->tok == TOKEN_DOTS)
1508 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1509 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1512 va = parse_vararg(parser);
1515 vec_push(sy->out, syexp(parser_ctx(parser), va));
1518 else if (parser->tok == TOKEN_FLOATCONST) {
1519 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1522 vec_push(sy->out, syexp(parser_ctx(parser), val));
1525 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1526 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1529 vec_push(sy->out, syexp(parser_ctx(parser), val));
1532 else if (parser->tok == TOKEN_STRINGCONST) {
1533 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1536 vec_push(sy->out, syexp(parser_ctx(parser), val));
1539 else if (parser->tok == TOKEN_VECTORCONST) {
1540 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1543 vec_push(sy->out, syexp(parser_ctx(parser), val));
1546 else if (parser->tok == TOKEN_IDENT)
1548 const char *ctoken = parser_tokval(parser);
1549 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1550 ast_expression *var;
1551 /* a_vector.{x,y,z} */
1552 if (!vec_size(sy->ops) ||
1553 !vec_last(sy->ops).etype ||
1554 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1556 /* When adding more intrinsics, fix the above condition */
1559 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1561 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1563 var = parser_find_var(parser, parser_tokval(parser));
1565 var = parser_find_field(parser, parser_tokval(parser));
1567 if (!var && with_labels) {
1568 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1570 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1571 var = (ast_expression*)lbl;
1572 vec_push(parser->labels, lbl);
1575 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1576 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1579 * now we try for the real intrinsic hashtable. If the string
1580 * begins with __builtin, we simply skip past it, otherwise we
1581 * use the identifier as is.
1583 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1584 var = intrin_func(parser->intrin, parser_tokval(parser));
1588 * Try it again, intrin_func deals with the alias method as well
1589 * the first one masks for __builtin though, we emit warning here.
1592 if ((var = intrin_func(parser->intrin, parser_tokval(parser)))) {
1593 (void)!compile_warning(
1596 "using implicitly defined builtin `__builtin_%s' for `%s'",
1597 parser_tokval(parser),
1598 parser_tokval(parser)
1605 char *correct = NULL;
1609 * sometimes people use preprocessing predefs without enabling them
1610 * i've done this thousands of times already myself. Lets check for
1611 * it in the predef table. And diagnose it better :)
1613 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1614 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1619 * TODO: determine the best score for the identifier: be it
1620 * a variable, a field.
1622 * We should also consider adding correction tables for
1623 * other things as well.
1625 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1627 correct_init(&corr);
1629 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1630 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1631 if (strcmp(correct, parser_tokval(parser))) {
1638 correct_free(&corr);
1641 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1646 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1652 if (ast_istype(var, ast_value)) {
1653 ((ast_value*)var)->uses++;
1655 else if (ast_istype(var, ast_member)) {
1656 ast_member *mem = (ast_member*)var;
1657 if (ast_istype(mem->owner, ast_value))
1658 ((ast_value*)(mem->owner))->uses++;
1661 vec_push(sy->out, syexp(parser_ctx(parser), var));
1664 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1668 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1670 ast_expression *expr = NULL;
1673 bool wantop = false;
1674 /* only warn once about an assignment in a truth value because the current code
1675 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1677 bool warn_parenthesis = true;
1679 /* count the parens because an if starts with one, so the
1680 * end of a condition is an unmatched closing paren
1684 memset(&sy, 0, sizeof(sy));
1686 parser->lex->flags.noops = false;
1688 parser_reclassify_token(parser);
1692 if (parser->tok == TOKEN_TYPENAME) {
1693 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1697 if (parser->tok == TOKEN_OPERATOR)
1699 /* classify the operator */
1700 const oper_info *op;
1701 const oper_info *olast = NULL;
1703 for (o = 0; o < operator_count; ++o) {
1704 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1705 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1706 !strcmp(parser_tokval(parser), operators[o].op))
1711 if (o == operator_count) {
1712 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1715 /* found an operator */
1718 /* when declaring variables, a comma starts a new variable */
1719 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1720 /* fixup the token */
1725 /* a colon without a pervious question mark cannot be a ternary */
1726 if (!ternaries && op->id == opid2(':','?')) {
1731 if (op->id == opid1(',')) {
1732 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1733 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1737 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1738 olast = &operators[vec_last(sy.ops).etype-1];
1740 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1741 while (olast && op->prec < olast->prec)
1743 if (!parser_sy_apply_operator(parser, &sy))
1745 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1746 olast = &operators[vec_last(sy.ops).etype-1];
1751 #define IsAssignOp(x) (\
1752 (x) == opid1('=') || \
1753 (x) == opid2('+','=') || \
1754 (x) == opid2('-','=') || \
1755 (x) == opid2('*','=') || \
1756 (x) == opid2('/','=') || \
1757 (x) == opid2('%','=') || \
1758 (x) == opid2('&','=') || \
1759 (x) == opid2('|','=') || \
1760 (x) == opid3('&','~','=') \
1762 if (warn_parenthesis) {
1763 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1764 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1765 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1768 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1769 warn_parenthesis = false;
1772 if (olast && olast->id != op->id) {
1773 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1774 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1776 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1777 warn_parenthesis = false;
1779 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1780 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1782 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1783 warn_parenthesis = false;
1789 (op->prec < olast->prec) ||
1790 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1792 if (!parser_sy_apply_operator(parser, &sy))
1794 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1795 olast = &operators[vec_last(sy.ops).etype-1];
1800 if (op->id == opid1('(')) {
1802 size_t sycount = vec_size(sy.out);
1803 /* we expected an operator, this is the function-call operator */
1804 vec_push(sy.paren, PAREN_FUNC);
1805 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1806 vec_push(sy.argc, 0);
1808 vec_push(sy.paren, PAREN_EXPR);
1809 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1812 } else if (op->id == opid1('[')) {
1814 parseerror(parser, "unexpected array subscript");
1817 vec_push(sy.paren, PAREN_INDEX);
1818 /* push both the operator and the paren, this makes life easier */
1819 vec_push(sy.ops, syop(parser_ctx(parser), op));
1820 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1822 } else if (op->id == opid2('?',':')) {
1823 vec_push(sy.ops, syop(parser_ctx(parser), op));
1824 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1827 vec_push(sy.paren, PAREN_TERNARY1);
1828 } else if (op->id == opid2(':','?')) {
1829 if (!vec_size(sy.paren)) {
1830 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1833 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1834 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1837 if (!parser_close_paren(parser, &sy))
1839 vec_push(sy.ops, syop(parser_ctx(parser), op));
1843 vec_push(sy.ops, syop(parser_ctx(parser), op));
1844 wantop = !!(op->flags & OP_SUFFIX);
1847 else if (parser->tok == ')') {
1848 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1849 if (!parser_sy_apply_operator(parser, &sy))
1852 if (!vec_size(sy.paren))
1855 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1856 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1859 if (!parser_close_paren(parser, &sy))
1862 /* must be a function call without parameters */
1863 if (vec_last(sy.paren) != PAREN_FUNC) {
1864 parseerror(parser, "closing paren in invalid position");
1867 if (!parser_close_paren(parser, &sy))
1872 else if (parser->tok == '(') {
1873 parseerror(parser, "internal error: '(' should be classified as operator");
1876 else if (parser->tok == '[') {
1877 parseerror(parser, "internal error: '[' should be classified as operator");
1880 else if (parser->tok == ']') {
1881 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1882 if (!parser_sy_apply_operator(parser, &sy))
1885 if (!vec_size(sy.paren))
1887 if (vec_last(sy.paren) != PAREN_INDEX) {
1888 parseerror(parser, "mismatched parentheses, unexpected ']'");
1891 if (!parser_close_paren(parser, &sy))
1896 if (!parse_sya_operand(parser, &sy, with_labels))
1899 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1900 vec_last(sy.argc)++;
1905 /* in this case we might want to allow constant string concatenation */
1906 bool concatenated = false;
1907 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1908 ast_expression *lexpr = vec_last(sy.out).out;
1909 if (ast_istype(lexpr, ast_value)) {
1910 ast_value *last = (ast_value*)lexpr;
1911 if (last->isimm == true && last->cvq == CV_CONST &&
1912 last->hasvalue && last->expression.vtype == TYPE_STRING)
1914 char *newstr = NULL;
1915 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1916 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1918 concatenated = true;
1922 if (!concatenated) {
1923 parseerror(parser, "expected operator or end of statement");
1928 if (!parser_next(parser)) {
1931 if (parser->tok == ';' ||
1932 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1933 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1939 while (vec_size(sy.ops)) {
1940 if (!parser_sy_apply_operator(parser, &sy))
1944 parser->lex->flags.noops = true;
1945 if (vec_size(sy.out) != 1) {
1946 parseerror(parser, "expression expected");
1949 expr = sy.out[0].out;
1952 if (vec_size(sy.paren)) {
1953 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1961 parser->lex->flags.noops = true;
1962 for (i = 0; i < vec_size(sy.out); ++i) {
1964 ast_unref(sy.out[i].out);
1973 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1975 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1978 if (parser->tok != ';') {
1979 parseerror(parser, "semicolon expected after expression");
1983 if (!parser_next(parser)) {
1990 static void parser_enterblock(parser_t *parser)
1992 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1993 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1994 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1995 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1996 vec_push(parser->_block_ctx, parser_ctx(parser));
1999 vec_push(parser->correct_variables, correct_trie_new());
2000 vec_push(parser->correct_variables_score, NULL);
2003 static bool parser_leaveblock(parser_t *parser)
2006 size_t locals, typedefs;
2008 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2009 parseerror(parser, "internal error: parser_leaveblock with no block");
2013 util_htdel(vec_last(parser->variables));
2014 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2016 vec_pop(parser->variables);
2017 vec_pop(parser->correct_variables);
2018 vec_pop(parser->correct_variables_score);
2019 if (!vec_size(parser->_blocklocals)) {
2020 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2024 locals = vec_last(parser->_blocklocals);
2025 vec_pop(parser->_blocklocals);
2026 while (vec_size(parser->_locals) != locals) {
2027 ast_expression *e = vec_last(parser->_locals);
2028 ast_value *v = (ast_value*)e;
2029 vec_pop(parser->_locals);
2030 if (ast_istype(e, ast_value) && !v->uses) {
2031 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2036 typedefs = vec_last(parser->_blocktypedefs);
2037 while (vec_size(parser->_typedefs) != typedefs) {
2038 ast_delete(vec_last(parser->_typedefs));
2039 vec_pop(parser->_typedefs);
2041 util_htdel(vec_last(parser->typedefs));
2042 vec_pop(parser->typedefs);
2044 vec_pop(parser->_block_ctx);
2049 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2051 vec_push(parser->_locals, e);
2052 util_htset(vec_last(parser->variables), name, (void*)e);
2056 vec_last(parser->correct_variables),
2057 &vec_last(parser->correct_variables_score),
2062 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2064 vec_push(parser->globals, e);
2065 util_htset(parser->htglobals, name, e);
2069 parser->correct_variables[0],
2070 &parser->correct_variables_score[0],
2075 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2079 ast_expression *prev;
2081 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2083 ast_type_to_string(cond, ty, sizeof(ty));
2084 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2087 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2090 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2093 parseerror(parser, "internal error: failed to process condition");
2098 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2100 /* vector types need to be cast to true booleans */
2101 ast_binary *bin = (ast_binary*)cond;
2102 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2104 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2106 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2109 parseerror(parser, "internal error: failed to process condition");
2116 unary = (ast_unary*)cond;
2117 /* ast_istype dereferences cond, should test here for safety */
2118 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2120 cond = unary->operand;
2121 unary->operand = NULL;
2124 unary = (ast_unary*)cond;
2128 parseerror(parser, "internal error: failed to process condition");
2130 if (ifnot) *_ifnot = !*_ifnot;
2134 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2137 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2140 lex_ctx_t ctx = parser_ctx(parser);
2142 (void)block; /* not touching */
2144 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "expected condition or 'not'");
2149 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2151 if (!parser_next(parser)) {
2152 parseerror(parser, "expected condition in parenthesis");
2156 if (parser->tok != '(') {
2157 parseerror(parser, "expected 'if' condition in parenthesis");
2160 /* parse into the expression */
2161 if (!parser_next(parser)) {
2162 parseerror(parser, "expected 'if' condition after opening paren");
2165 /* parse the condition */
2166 cond = parse_expression_leave(parser, false, true, false);
2170 if (parser->tok != ')') {
2171 parseerror(parser, "expected closing paren after 'if' condition");
2175 /* parse into the 'then' branch */
2176 if (!parser_next(parser)) {
2177 parseerror(parser, "expected statement for on-true branch of 'if'");
2181 if (!parse_statement_or_block(parser, &ontrue)) {
2186 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2187 /* check for an else */
2188 if (!strcmp(parser_tokval(parser), "else")) {
2189 /* parse into the 'else' branch */
2190 if (!parser_next(parser)) {
2191 parseerror(parser, "expected on-false branch after 'else'");
2196 if (!parse_statement_or_block(parser, &onfalse)) {
2203 cond = process_condition(parser, cond, &ifnot);
2205 if (ontrue) ast_delete(ontrue);
2206 if (onfalse) ast_delete(onfalse);
2211 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2213 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2214 *out = (ast_expression*)ifthen;
2218 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2219 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2224 /* skip the 'while' and get the body */
2225 if (!parser_next(parser)) {
2226 if (OPTS_FLAG(LOOP_LABELS))
2227 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2229 parseerror(parser, "expected 'while' condition in parenthesis");
2233 if (parser->tok == ':') {
2234 if (!OPTS_FLAG(LOOP_LABELS))
2235 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2236 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2237 parseerror(parser, "expected loop label");
2240 label = util_strdup(parser_tokval(parser));
2241 if (!parser_next(parser)) {
2243 parseerror(parser, "expected 'while' condition in parenthesis");
2248 if (parser->tok != '(') {
2249 parseerror(parser, "expected 'while' condition in parenthesis");
2253 vec_push(parser->breaks, label);
2254 vec_push(parser->continues, label);
2256 rv = parse_while_go(parser, block, out);
2259 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2260 parseerror(parser, "internal error: label stack corrupted");
2266 vec_pop(parser->breaks);
2267 vec_pop(parser->continues);
2272 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2275 ast_expression *cond, *ontrue;
2279 lex_ctx_t ctx = parser_ctx(parser);
2281 (void)block; /* not touching */
2283 /* parse into the expression */
2284 if (!parser_next(parser)) {
2285 parseerror(parser, "expected 'while' condition after opening paren");
2288 /* parse the condition */
2289 cond = parse_expression_leave(parser, false, true, false);
2293 if (parser->tok != ')') {
2294 parseerror(parser, "expected closing paren after 'while' condition");
2298 /* parse into the 'then' branch */
2299 if (!parser_next(parser)) {
2300 parseerror(parser, "expected while-loop body");
2304 if (!parse_statement_or_block(parser, &ontrue)) {
2309 cond = process_condition(parser, cond, &ifnot);
2314 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2315 *out = (ast_expression*)aloop;
2319 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2320 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2325 /* skip the 'do' and get the body */
2326 if (!parser_next(parser)) {
2327 if (OPTS_FLAG(LOOP_LABELS))
2328 parseerror(parser, "expected loop label or body");
2330 parseerror(parser, "expected loop body");
2334 if (parser->tok == ':') {
2335 if (!OPTS_FLAG(LOOP_LABELS))
2336 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2337 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2338 parseerror(parser, "expected loop label");
2341 label = util_strdup(parser_tokval(parser));
2342 if (!parser_next(parser)) {
2344 parseerror(parser, "expected loop body");
2349 vec_push(parser->breaks, label);
2350 vec_push(parser->continues, label);
2352 rv = parse_dowhile_go(parser, block, out);
2355 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2356 parseerror(parser, "internal error: label stack corrupted");
2359 * Test for NULL otherwise ast_delete dereferences null pointer
2367 vec_pop(parser->breaks);
2368 vec_pop(parser->continues);
2373 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2376 ast_expression *cond, *ontrue;
2380 lex_ctx_t ctx = parser_ctx(parser);
2382 (void)block; /* not touching */
2384 if (!parse_statement_or_block(parser, &ontrue))
2387 /* expect the "while" */
2388 if (parser->tok != TOKEN_KEYWORD ||
2389 strcmp(parser_tokval(parser), "while"))
2391 parseerror(parser, "expected 'while' and condition");
2396 /* skip the 'while' and check for opening paren */
2397 if (!parser_next(parser) || parser->tok != '(') {
2398 parseerror(parser, "expected 'while' condition in parenthesis");
2402 /* parse into the expression */
2403 if (!parser_next(parser)) {
2404 parseerror(parser, "expected 'while' condition after opening paren");
2408 /* parse the condition */
2409 cond = parse_expression_leave(parser, false, true, false);
2413 if (parser->tok != ')') {
2414 parseerror(parser, "expected closing paren after 'while' condition");
2420 if (!parser_next(parser) || parser->tok != ';') {
2421 parseerror(parser, "expected semicolon after condition");
2427 if (!parser_next(parser)) {
2428 parseerror(parser, "parse error");
2434 cond = process_condition(parser, cond, &ifnot);
2439 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2440 *out = (ast_expression*)aloop;
2444 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2445 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2450 /* skip the 'for' and check for opening paren */
2451 if (!parser_next(parser)) {
2452 if (OPTS_FLAG(LOOP_LABELS))
2453 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2455 parseerror(parser, "expected 'for' expressions in parenthesis");
2459 if (parser->tok == ':') {
2460 if (!OPTS_FLAG(LOOP_LABELS))
2461 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2462 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2463 parseerror(parser, "expected loop label");
2466 label = util_strdup(parser_tokval(parser));
2467 if (!parser_next(parser)) {
2469 parseerror(parser, "expected 'for' expressions in parenthesis");
2474 if (parser->tok != '(') {
2475 parseerror(parser, "expected 'for' expressions in parenthesis");
2479 vec_push(parser->breaks, label);
2480 vec_push(parser->continues, label);
2482 rv = parse_for_go(parser, block, out);
2485 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2486 parseerror(parser, "internal error: label stack corrupted");
2492 vec_pop(parser->breaks);
2493 vec_pop(parser->continues);
2497 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2500 ast_expression *initexpr, *cond, *increment, *ontrue;
2505 lex_ctx_t ctx = parser_ctx(parser);
2507 parser_enterblock(parser);
2514 /* parse into the expression */
2515 if (!parser_next(parser)) {
2516 parseerror(parser, "expected 'for' initializer after opening paren");
2521 if (parser->tok == TOKEN_IDENT)
2522 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2524 if (typevar || parser->tok == TOKEN_TYPENAME) {
2526 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2527 if (parsewarning(parser, WARN_EXTENSIONS,
2528 "current standard does not allow variable declarations in for-loop initializers"))
2532 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2535 else if (parser->tok != ';')
2537 initexpr = parse_expression_leave(parser, false, false, false);
2542 /* move on to condition */
2543 if (parser->tok != ';') {
2544 parseerror(parser, "expected semicolon after for-loop initializer");
2547 if (!parser_next(parser)) {
2548 parseerror(parser, "expected for-loop condition");
2552 /* parse the condition */
2553 if (parser->tok != ';') {
2554 cond = parse_expression_leave(parser, false, true, false);
2559 /* move on to incrementor */
2560 if (parser->tok != ';') {
2561 parseerror(parser, "expected semicolon after for-loop initializer");
2564 if (!parser_next(parser)) {
2565 parseerror(parser, "expected for-loop condition");
2569 /* parse the incrementor */
2570 if (parser->tok != ')') {
2571 lex_ctx_t condctx = parser_ctx(parser);
2572 increment = parse_expression_leave(parser, false, false, false);
2575 if (!ast_side_effects(increment)) {
2576 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2582 if (parser->tok != ')') {
2583 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2586 /* parse into the 'then' branch */
2587 if (!parser_next(parser)) {
2588 parseerror(parser, "expected for-loop body");
2591 if (!parse_statement_or_block(parser, &ontrue))
2595 cond = process_condition(parser, cond, &ifnot);
2599 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2600 *out = (ast_expression*)aloop;
2602 if (!parser_leaveblock(parser)) {
2608 if (initexpr) ast_unref(initexpr);
2609 if (cond) ast_unref(cond);
2610 if (increment) ast_unref(increment);
2611 (void)!parser_leaveblock(parser);
2615 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2617 ast_expression *exp = NULL;
2618 ast_expression *var = NULL;
2619 ast_return *ret = NULL;
2620 ast_value *retval = parser->function->return_value;
2621 ast_value *expected = parser->function->vtype;
2623 lex_ctx_t ctx = parser_ctx(parser);
2625 (void)block; /* not touching */
2627 if (!parser_next(parser)) {
2628 parseerror(parser, "expected return expression");
2632 /* return assignments */
2633 if (parser->tok == '=') {
2634 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2635 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2639 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2641 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2642 parseerror(parser, "invalid return type: `%s'", ty1);
2646 if (!parser_next(parser)) {
2647 parseerror(parser, "expected return assignment expression");
2651 if (!(exp = parse_expression_leave(parser, false, false, false)))
2654 /* prepare the return value */
2656 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2657 ast_type_adopt(retval, expected->expression.next);
2658 parser->function->return_value = retval;
2661 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2662 char ty1[1024], ty2[1024];
2663 ast_type_to_string(exp, ty1, sizeof(ty1));
2664 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2665 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2668 /* store to 'return' local variable */
2669 var = (ast_expression*)ast_store_new(
2671 type_store_instr[expected->expression.next->vtype],
2672 (ast_expression*)retval, exp);
2679 if (parser->tok != ';')
2680 parseerror(parser, "missing semicolon after return assignment");
2681 else if (!parser_next(parser))
2682 parseerror(parser, "parse error after return assignment");
2688 if (parser->tok != ';') {
2689 exp = parse_expression(parser, false, false);
2693 if (exp->vtype != TYPE_NIL &&
2694 exp->vtype != ((ast_expression*)expected)->next->vtype)
2696 parseerror(parser, "return with invalid expression");
2699 ret = ast_return_new(ctx, exp);
2705 if (!parser_next(parser))
2706 parseerror(parser, "parse error");
2708 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2710 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2712 ret = ast_return_new(ctx, (ast_expression*)retval);
2714 *out = (ast_expression*)ret;
2718 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2721 unsigned int levels = 0;
2722 lex_ctx_t ctx = parser_ctx(parser);
2723 const char **loops = (is_continue ? parser->continues : parser->breaks);
2725 (void)block; /* not touching */
2726 if (!parser_next(parser)) {
2727 parseerror(parser, "expected semicolon or loop label");
2731 if (!vec_size(loops)) {
2733 parseerror(parser, "`continue` can only be used inside loops");
2735 parseerror(parser, "`break` can only be used inside loops or switches");
2738 if (parser->tok == TOKEN_IDENT) {
2739 if (!OPTS_FLAG(LOOP_LABELS))
2740 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2741 i = vec_size(loops);
2743 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2746 parseerror(parser, "no such loop to %s: `%s`",
2747 (is_continue ? "continue" : "break out of"),
2748 parser_tokval(parser));
2753 if (!parser_next(parser)) {
2754 parseerror(parser, "expected semicolon");
2759 if (parser->tok != ';') {
2760 parseerror(parser, "expected semicolon");
2764 if (!parser_next(parser))
2765 parseerror(parser, "parse error");
2767 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2771 /* returns true when it was a variable qualifier, false otherwise!
2772 * on error, cvq is set to CV_WRONG
2774 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2776 bool had_const = false;
2777 bool had_var = false;
2778 bool had_noref = false;
2779 bool had_attrib = false;
2780 bool had_static = false;
2785 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2787 /* parse an attribute */
2788 if (!parser_next(parser)) {
2789 parseerror(parser, "expected attribute after `[[`");
2793 if (!strcmp(parser_tokval(parser), "noreturn")) {
2794 flags |= AST_FLAG_NORETURN;
2795 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2796 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2801 else if (!strcmp(parser_tokval(parser), "noref")) {
2803 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2804 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2809 else if (!strcmp(parser_tokval(parser), "inline")) {
2810 flags |= AST_FLAG_INLINE;
2811 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2812 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2817 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2818 flags |= AST_FLAG_ERASEABLE;
2819 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2820 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2825 else if (!strcmp(parser_tokval(parser), "accumulate")) {
2826 flags |= AST_FLAG_ACCUMULATE;
2827 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2828 parseerror(parser, "`accumulate` attribute has no parameters, expected `]]`");
2833 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2834 flags |= AST_FLAG_ALIAS;
2837 if (!parser_next(parser)) {
2838 parseerror(parser, "parse error in attribute");
2842 if (parser->tok == '(') {
2843 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2844 parseerror(parser, "`alias` attribute missing parameter");
2848 *message = util_strdup(parser_tokval(parser));
2850 if (!parser_next(parser)) {
2851 parseerror(parser, "parse error in attribute");
2855 if (parser->tok != ')') {
2856 parseerror(parser, "`alias` attribute expected `)` after parameter");
2860 if (!parser_next(parser)) {
2861 parseerror(parser, "parse error in attribute");
2866 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2867 parseerror(parser, "`alias` attribute expected `]]`");
2871 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2872 flags |= AST_FLAG_DEPRECATED;
2875 if (!parser_next(parser)) {
2876 parseerror(parser, "parse error in attribute");
2880 if (parser->tok == '(') {
2881 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2882 parseerror(parser, "`deprecated` attribute missing parameter");
2886 *message = util_strdup(parser_tokval(parser));
2888 if (!parser_next(parser)) {
2889 parseerror(parser, "parse error in attribute");
2893 if(parser->tok != ')') {
2894 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2898 if (!parser_next(parser)) {
2899 parseerror(parser, "parse error in attribute");
2904 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2905 parseerror(parser, "`deprecated` attribute expected `]]`");
2908 if (*message) mem_d(*message);
2916 /* Skip tokens until we hit a ]] */
2917 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2918 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2919 if (!parser_next(parser)) {
2920 parseerror(parser, "error inside attribute");
2927 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2929 else if (!strcmp(parser_tokval(parser), "const"))
2931 else if (!strcmp(parser_tokval(parser), "var"))
2933 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2935 else if (!strcmp(parser_tokval(parser), "noref"))
2937 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2942 if (!parser_next(parser))
2952 *is_static = had_static;
2956 parseerror(parser, "parse error after variable qualifier");
2961 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2962 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2967 /* skip the 'while' and get the body */
2968 if (!parser_next(parser)) {
2969 if (OPTS_FLAG(LOOP_LABELS))
2970 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2972 parseerror(parser, "expected 'switch' operand in parenthesis");
2976 if (parser->tok == ':') {
2977 if (!OPTS_FLAG(LOOP_LABELS))
2978 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2979 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2980 parseerror(parser, "expected loop label");
2983 label = util_strdup(parser_tokval(parser));
2984 if (!parser_next(parser)) {
2986 parseerror(parser, "expected 'switch' operand in parenthesis");
2991 if (parser->tok != '(') {
2992 parseerror(parser, "expected 'switch' operand in parenthesis");
2996 vec_push(parser->breaks, label);
2998 rv = parse_switch_go(parser, block, out);
3001 if (vec_last(parser->breaks) != label) {
3002 parseerror(parser, "internal error: label stack corrupted");
3008 vec_pop(parser->breaks);
3013 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3015 ast_expression *operand;
3018 ast_switch *switchnode;
3019 ast_switch_case swcase;
3022 bool noref, is_static;
3023 uint32_t qflags = 0;
3025 lex_ctx_t ctx = parser_ctx(parser);
3027 (void)block; /* not touching */
3030 /* parse into the expression */
3031 if (!parser_next(parser)) {
3032 parseerror(parser, "expected switch operand");
3035 /* parse the operand */
3036 operand = parse_expression_leave(parser, false, false, false);
3040 switchnode = ast_switch_new(ctx, operand);
3043 if (parser->tok != ')') {
3044 ast_delete(switchnode);
3045 parseerror(parser, "expected closing paren after 'switch' operand");
3049 /* parse over the opening paren */
3050 if (!parser_next(parser) || parser->tok != '{') {
3051 ast_delete(switchnode);
3052 parseerror(parser, "expected list of cases");
3056 if (!parser_next(parser)) {
3057 ast_delete(switchnode);
3058 parseerror(parser, "expected 'case' or 'default'");
3062 /* new block; allow some variables to be declared here */
3063 parser_enterblock(parser);
3066 if (parser->tok == TOKEN_IDENT)
3067 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3068 if (typevar || parser->tok == TOKEN_TYPENAME) {
3069 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3070 ast_delete(switchnode);
3075 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3077 if (cvq == CV_WRONG) {
3078 ast_delete(switchnode);
3081 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3082 ast_delete(switchnode);
3091 while (parser->tok != '}') {
3092 ast_block *caseblock;
3094 if (!strcmp(parser_tokval(parser), "case")) {
3095 if (!parser_next(parser)) {
3096 ast_delete(switchnode);
3097 parseerror(parser, "expected expression for case");
3100 swcase.value = parse_expression_leave(parser, false, false, false);
3101 if (!swcase.value) {
3102 ast_delete(switchnode);
3103 parseerror(parser, "expected expression for case");
3106 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3107 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3108 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3114 else if (!strcmp(parser_tokval(parser), "default")) {
3115 swcase.value = NULL;
3116 if (!parser_next(parser)) {
3117 ast_delete(switchnode);
3118 parseerror(parser, "expected colon");
3123 ast_delete(switchnode);
3124 parseerror(parser, "expected 'case' or 'default'");
3128 /* Now the colon and body */
3129 if (parser->tok != ':') {
3130 if (swcase.value) ast_unref(swcase.value);
3131 ast_delete(switchnode);
3132 parseerror(parser, "expected colon");
3136 if (!parser_next(parser)) {
3137 if (swcase.value) ast_unref(swcase.value);
3138 ast_delete(switchnode);
3139 parseerror(parser, "expected statements or case");
3142 caseblock = ast_block_new(parser_ctx(parser));
3144 if (swcase.value) ast_unref(swcase.value);
3145 ast_delete(switchnode);
3148 swcase.code = (ast_expression*)caseblock;
3149 vec_push(switchnode->cases, swcase);
3151 ast_expression *expr;
3152 if (parser->tok == '}')
3154 if (parser->tok == TOKEN_KEYWORD) {
3155 if (!strcmp(parser_tokval(parser), "case") ||
3156 !strcmp(parser_tokval(parser), "default"))
3161 if (!parse_statement(parser, caseblock, &expr, true)) {
3162 ast_delete(switchnode);
3167 if (!ast_block_add_expr(caseblock, expr)) {
3168 ast_delete(switchnode);
3174 parser_leaveblock(parser);
3177 if (parser->tok != '}') {
3178 ast_delete(switchnode);
3179 parseerror(parser, "expected closing paren of case list");
3182 if (!parser_next(parser)) {
3183 ast_delete(switchnode);
3184 parseerror(parser, "parse error after switch");
3187 *out = (ast_expression*)switchnode;
3191 /* parse computed goto sides */
3192 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3193 ast_expression *on_true;
3194 ast_expression *on_false;
3195 ast_expression *cond;
3200 if (ast_istype(*side, ast_ternary)) {
3201 ast_ternary *tern = (ast_ternary*)*side;
3202 on_true = parse_goto_computed(parser, &tern->on_true);
3203 on_false = parse_goto_computed(parser, &tern->on_false);
3205 if (!on_true || !on_false) {
3206 parseerror(parser, "expected label or expression in ternary");
3207 if (on_true) ast_unref(on_true);
3208 if (on_false) ast_unref(on_false);
3216 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3217 } else if (ast_istype(*side, ast_label)) {
3218 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3219 ast_goto_set_label(gt, ((ast_label*)*side));
3221 return (ast_expression*)gt;
3226 static bool parse_goto(parser_t *parser, ast_expression **out)
3228 ast_goto *gt = NULL;
3229 ast_expression *lbl;
3231 if (!parser_next(parser))
3234 if (parser->tok != TOKEN_IDENT) {
3235 ast_expression *expression;
3237 /* could be an expression i.e computed goto :-) */
3238 if (parser->tok != '(') {
3239 parseerror(parser, "expected label name after `goto`");
3243 /* failed to parse expression for goto */
3244 if (!(expression = parse_expression(parser, false, true)) ||
3245 !(*out = parse_goto_computed(parser, &expression))) {
3246 parseerror(parser, "invalid goto expression");
3248 ast_unref(expression);
3255 /* not computed goto */
3256 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3257 lbl = parser_find_label(parser, gt->name);
3259 if (!ast_istype(lbl, ast_label)) {
3260 parseerror(parser, "internal error: label is not an ast_label");
3264 ast_goto_set_label(gt, (ast_label*)lbl);
3267 vec_push(parser->gotos, gt);
3269 if (!parser_next(parser) || parser->tok != ';') {
3270 parseerror(parser, "semicolon expected after goto label");
3273 if (!parser_next(parser)) {
3274 parseerror(parser, "parse error after goto");
3278 *out = (ast_expression*)gt;
3282 static bool parse_skipwhite(parser_t *parser)
3285 if (!parser_next(parser))
3287 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3288 return parser->tok < TOKEN_ERROR;
3291 static bool parse_eol(parser_t *parser)
3293 if (!parse_skipwhite(parser))
3295 return parser->tok == TOKEN_EOL;
3298 static bool parse_pragma_do(parser_t *parser)
3300 if (!parser_next(parser) ||
3301 parser->tok != TOKEN_IDENT ||
3302 strcmp(parser_tokval(parser), "pragma"))
3304 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3307 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3308 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3312 if (!strcmp(parser_tokval(parser), "noref")) {
3313 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3314 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3317 parser->noref = !!parser_token(parser)->constval.i;
3318 if (!parse_eol(parser)) {
3319 parseerror(parser, "parse error after `noref` pragma");
3325 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3328 while (!parse_eol(parser)) {
3329 parser_next(parser);
3338 static bool parse_pragma(parser_t *parser)
3341 parser->lex->flags.preprocessing = true;
3342 parser->lex->flags.mergelines = true;
3343 rv = parse_pragma_do(parser);
3344 if (parser->tok != TOKEN_EOL) {
3345 parseerror(parser, "junk after pragma");
3348 parser->lex->flags.preprocessing = false;
3349 parser->lex->flags.mergelines = false;
3350 if (!parser_next(parser)) {
3351 parseerror(parser, "parse error after pragma");
3357 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3359 bool noref, is_static;
3361 uint32_t qflags = 0;
3362 ast_value *typevar = NULL;
3363 char *vstring = NULL;
3367 if (parser->tok == TOKEN_IDENT)
3368 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3370 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3372 /* local variable */
3374 parseerror(parser, "cannot declare a variable from here");
3377 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3378 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3381 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3385 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3387 if (cvq == CV_WRONG)
3389 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3391 else if (parser->tok == TOKEN_KEYWORD)
3393 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3398 if (!parser_next(parser)) {
3399 parseerror(parser, "parse error after __builtin_debug_printtype");
3403 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3405 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3406 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3407 if (!parser_next(parser)) {
3408 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3414 if (!parse_statement(parser, block, out, allow_cases))
3417 con_out("__builtin_debug_printtype: got no output node\n");
3420 ast_type_to_string(*out, ty, sizeof(ty));
3421 con_out("__builtin_debug_printtype: `%s`\n", ty);
3426 else if (!strcmp(parser_tokval(parser), "return"))
3428 return parse_return(parser, block, out);
3430 else if (!strcmp(parser_tokval(parser), "if"))
3432 return parse_if(parser, block, out);
3434 else if (!strcmp(parser_tokval(parser), "while"))
3436 return parse_while(parser, block, out);
3438 else if (!strcmp(parser_tokval(parser), "do"))
3440 return parse_dowhile(parser, block, out);
3442 else if (!strcmp(parser_tokval(parser), "for"))
3444 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3445 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3448 return parse_for(parser, block, out);
3450 else if (!strcmp(parser_tokval(parser), "break"))
3452 return parse_break_continue(parser, block, out, false);
3454 else if (!strcmp(parser_tokval(parser), "continue"))
3456 return parse_break_continue(parser, block, out, true);
3458 else if (!strcmp(parser_tokval(parser), "switch"))
3460 return parse_switch(parser, block, out);
3462 else if (!strcmp(parser_tokval(parser), "case") ||
3463 !strcmp(parser_tokval(parser), "default"))
3466 parseerror(parser, "unexpected 'case' label");
3471 else if (!strcmp(parser_tokval(parser), "goto"))
3473 return parse_goto(parser, out);
3475 else if (!strcmp(parser_tokval(parser), "typedef"))
3477 if (!parser_next(parser)) {
3478 parseerror(parser, "expected type definition after 'typedef'");
3481 return parse_typedef(parser);
3483 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3486 else if (parser->tok == '{')
3489 inner = parse_block(parser);
3492 *out = (ast_expression*)inner;
3495 else if (parser->tok == ':')
3499 if (!parser_next(parser)) {
3500 parseerror(parser, "expected label name");
3503 if (parser->tok != TOKEN_IDENT) {
3504 parseerror(parser, "label must be an identifier");
3507 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3509 if (!label->undefined) {
3510 parseerror(parser, "label `%s` already defined", label->name);
3513 label->undefined = false;
3516 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3517 vec_push(parser->labels, label);
3519 *out = (ast_expression*)label;
3520 if (!parser_next(parser)) {
3521 parseerror(parser, "parse error after label");
3524 for (i = 0; i < vec_size(parser->gotos); ++i) {
3525 if (!strcmp(parser->gotos[i]->name, label->name)) {
3526 ast_goto_set_label(parser->gotos[i], label);
3527 vec_remove(parser->gotos, i, 1);
3533 else if (parser->tok == ';')
3535 if (!parser_next(parser)) {
3536 parseerror(parser, "parse error after empty statement");
3543 lex_ctx_t ctx = parser_ctx(parser);
3544 ast_expression *exp = parse_expression(parser, false, false);
3548 if (!ast_side_effects(exp)) {
3549 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3556 static bool parse_enum(parser_t *parser)
3559 bool reverse = false;
3561 ast_value **values = NULL;
3562 ast_value *var = NULL;
3565 ast_expression *old;
3567 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3568 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3572 /* enumeration attributes (can add more later) */
3573 if (parser->tok == ':') {
3574 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3575 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3580 if (!strcmp(parser_tokval(parser), "flag")) {
3584 else if (!strcmp(parser_tokval(parser), "reverse")) {
3588 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3592 if (!parser_next(parser) || parser->tok != '{') {
3593 parseerror(parser, "expected `{` after enum attribute ");
3599 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3600 if (parser->tok == '}') {
3601 /* allow an empty enum */
3604 parseerror(parser, "expected identifier or `}`");
3608 old = parser_find_field(parser, parser_tokval(parser));
3610 old = parser_find_global(parser, parser_tokval(parser));
3612 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3613 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3617 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3618 vec_push(values, var);
3619 var->cvq = CV_CONST;
3620 var->hasvalue = true;
3622 /* for flagged enumerations increment in POTs of TWO */
3623 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3624 parser_addglobal(parser, var->name, (ast_expression*)var);
3626 if (!parser_next(parser)) {
3627 parseerror(parser, "expected `=`, `}` or comma after identifier");
3631 if (parser->tok == ',')
3633 if (parser->tok == '}')
3635 if (parser->tok != '=') {
3636 parseerror(parser, "expected `=`, `}` or comma after identifier");
3640 if (!parser_next(parser)) {
3641 parseerror(parser, "expected expression after `=`");
3645 /* We got a value! */
3646 old = parse_expression_leave(parser, true, false, false);
3647 asvalue = (ast_value*)old;
3648 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3649 compile_error(ast_ctx(var), "constant value or expression expected");
3652 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3654 if (parser->tok == '}')
3656 if (parser->tok != ',') {
3657 parseerror(parser, "expected `}` or comma after expression");
3662 /* patch them all (for reversed attribute) */
3665 for (i = 0; i < vec_size(values); i++)
3666 values[i]->constval.vfloat = vec_size(values) - i - 1;
3669 if (parser->tok != '}') {
3670 parseerror(parser, "internal error: breaking without `}`");
3674 if (!parser_next(parser) || parser->tok != ';') {
3675 parseerror(parser, "expected semicolon after enumeration");
3679 if (!parser_next(parser)) {
3680 parseerror(parser, "parse error after enumeration");
3692 static bool parse_block_into(parser_t *parser, ast_block *block)
3696 parser_enterblock(parser);
3698 if (!parser_next(parser)) { /* skip the '{' */
3699 parseerror(parser, "expected function body");
3703 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3705 ast_expression *expr = NULL;
3706 if (parser->tok == '}')
3709 if (!parse_statement(parser, block, &expr, false)) {
3710 /* parseerror(parser, "parse error"); */
3716 if (!ast_block_add_expr(block, expr)) {
3723 if (parser->tok != '}') {
3726 (void)parser_next(parser);
3730 if (!parser_leaveblock(parser))
3732 return retval && !!block;
3735 static ast_block* parse_block(parser_t *parser)
3738 block = ast_block_new(parser_ctx(parser));
3741 if (!parse_block_into(parser, block)) {
3742 ast_block_delete(block);
3748 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3750 if (parser->tok == '{') {
3751 *out = (ast_expression*)parse_block(parser);
3754 return parse_statement(parser, NULL, out, false);
3757 static bool create_vector_members(ast_value *var, ast_member **me)
3760 size_t len = strlen(var->name);
3762 for (i = 0; i < 3; ++i) {
3763 char *name = (char*)mem_a(len+3);
3764 memcpy(name, var->name, len);
3766 name[len+1] = 'x'+i;
3768 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3777 do { ast_member_delete(me[--i]); } while(i);
3781 static bool parse_function_body(parser_t *parser, ast_value *var)
3783 ast_block *block = NULL;
3788 ast_expression *framenum = NULL;
3789 ast_expression *nextthink = NULL;
3790 /* None of the following have to be deleted */
3791 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3792 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3793 bool has_frame_think;
3797 has_frame_think = false;
3798 old = parser->function;
3800 if (var->expression.flags & AST_FLAG_ALIAS) {
3801 parseerror(parser, "function aliases cannot have bodies");
3805 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3806 parseerror(parser, "gotos/labels leaking");
3810 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3811 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3812 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3818 if (parser->tok == '[') {
3819 /* got a frame definition: [ framenum, nextthink ]
3820 * this translates to:
3821 * self.frame = framenum;
3822 * self.nextthink = time + 0.1;
3823 * self.think = nextthink;
3827 fld_think = parser_find_field(parser, "think");
3828 fld_nextthink = parser_find_field(parser, "nextthink");
3829 fld_frame = parser_find_field(parser, "frame");
3830 if (!fld_think || !fld_nextthink || !fld_frame) {
3831 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3832 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3835 gbl_time = parser_find_global(parser, "time");
3836 gbl_self = parser_find_global(parser, "self");
3837 if (!gbl_time || !gbl_self) {
3838 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3839 parseerror(parser, "please declare the following globals: `time`, `self`");
3843 if (!parser_next(parser))
3846 framenum = parse_expression_leave(parser, true, false, false);
3848 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3851 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3852 ast_unref(framenum);
3853 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3857 if (parser->tok != ',') {
3858 ast_unref(framenum);
3859 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3860 parseerror(parser, "Got a %i\n", parser->tok);
3864 if (!parser_next(parser)) {
3865 ast_unref(framenum);
3869 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3871 /* qc allows the use of not-yet-declared functions here
3872 * - this automatically creates a prototype */
3873 ast_value *thinkfunc;
3874 ast_expression *functype = fld_think->next;
3876 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3877 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3878 ast_unref(framenum);
3879 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3882 ast_type_adopt(thinkfunc, functype);
3884 if (!parser_next(parser)) {
3885 ast_unref(framenum);
3886 ast_delete(thinkfunc);
3890 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3892 nextthink = (ast_expression*)thinkfunc;
3895 nextthink = parse_expression_leave(parser, true, false, false);
3897 ast_unref(framenum);
3898 parseerror(parser, "expected a think-function in [frame,think] notation");
3903 if (!ast_istype(nextthink, ast_value)) {
3904 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3908 if (retval && parser->tok != ']') {
3909 parseerror(parser, "expected closing `]` for [frame,think] notation");
3913 if (retval && !parser_next(parser)) {
3917 if (retval && parser->tok != '{') {
3918 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3923 ast_unref(nextthink);
3924 ast_unref(framenum);
3928 has_frame_think = true;
3931 block = ast_block_new(parser_ctx(parser));
3933 parseerror(parser, "failed to allocate block");
3934 if (has_frame_think) {
3935 ast_unref(nextthink);
3936 ast_unref(framenum);
3941 if (has_frame_think) {
3943 ast_expression *self_frame;
3944 ast_expression *self_nextthink;
3945 ast_expression *self_think;
3946 ast_expression *time_plus_1;
3947 ast_store *store_frame;
3948 ast_store *store_nextthink;
3949 ast_store *store_think;
3951 ctx = parser_ctx(parser);
3952 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3953 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3954 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3956 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3957 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3959 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3960 if (self_frame) ast_delete(self_frame);
3961 if (self_nextthink) ast_delete(self_nextthink);
3962 if (self_think) ast_delete(self_think);
3963 if (time_plus_1) ast_delete(time_plus_1);
3969 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3970 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3971 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3974 ast_delete(self_frame);
3977 if (!store_nextthink) {
3978 ast_delete(self_nextthink);
3982 ast_delete(self_think);
3986 if (store_frame) ast_delete(store_frame);
3987 if (store_nextthink) ast_delete(store_nextthink);
3988 if (store_think) ast_delete(store_think);
3991 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3992 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3993 !ast_block_add_expr(block, (ast_expression*)store_think))
4000 parseerror(parser, "failed to generate code for [frame,think]");
4001 ast_unref(nextthink);
4002 ast_unref(framenum);
4008 if (var->hasvalue) {
4009 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4010 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4011 ast_block_delete(block);
4014 func = var->constval.vfunc;
4017 parseerror(parser, "internal error: NULL function: `%s`", var->name);
4018 ast_block_delete(block);
4022 func = ast_function_new(ast_ctx(var), var->name, var);
4025 parseerror(parser, "failed to allocate function for `%s`", var->name);
4026 ast_block_delete(block);
4029 vec_push(parser->functions, func);
4032 parser_enterblock(parser);
4034 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4036 ast_value *param = var->expression.params[parami];
4039 if (param->expression.vtype != TYPE_VECTOR &&
4040 (param->expression.vtype != TYPE_FIELD ||
4041 param->expression.next->vtype != TYPE_VECTOR))
4046 if (!create_vector_members(param, me)) {
4047 ast_block_delete(block);
4051 for (e = 0; e < 3; ++e) {
4052 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4053 ast_block_collect(block, (ast_expression*)me[e]);
4057 if (var->argcounter && !func->argc) {
4058 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4059 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4063 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4065 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4066 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4067 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4068 varargs->expression.count = 0;
4069 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4070 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4071 ast_delete(varargs);
4072 ast_block_delete(block);
4075 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4076 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4077 ast_delete(varargs);
4078 ast_block_delete(block);
4081 func->varargs = varargs;
4082 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4085 parser->function = func;
4086 if (!parse_block_into(parser, block)) {
4087 ast_block_delete(block);
4091 vec_push(func->blocks, block);
4093 parser->function = old;
4094 if (!parser_leaveblock(parser))
4096 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4097 parseerror(parser, "internal error: local scopes left");
4101 if (parser->tok == ';')
4102 return parser_next(parser);
4103 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4104 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4108 (void)!parser_leaveblock(parser);
4109 vec_pop(parser->functions);
4110 ast_function_delete(func);
4111 var->constval.vfunc = NULL;
4114 parser->function = old;
4118 static ast_expression *array_accessor_split(
4123 ast_expression *left,
4124 ast_expression *right
4130 lex_ctx_t ctx = ast_ctx(array);
4132 if (!left || !right) {
4133 if (left) ast_delete(left);
4134 if (right) ast_delete(right);
4138 cmp = ast_binary_new(ctx, INSTR_LT,
4139 (ast_expression*)index,
4140 (ast_expression*)fold_constgen_float(parser->fold, middle));
4144 parseerror(parser, "internal error: failed to create comparison for array setter");
4148 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4150 ast_delete(cmp); /* will delete left and right */
4151 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4155 return (ast_expression*)ifthen;
4158 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4160 lex_ctx_t ctx = ast_ctx(array);
4162 if (from+1 == afterend) {
4163 /* set this value */
4166 ast_array_index *subscript;
4168 int assignop = type_store_instr[value->expression.vtype];
4170 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4171 assignop = INSTR_STORE_V;
4173 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4177 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4179 ast_delete(subscript);
4183 block = ast_block_new(ctx);
4189 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4194 ret = ast_return_new(ctx, NULL);
4200 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4205 return (ast_expression*)block;
4207 ast_expression *left, *right;
4208 size_t diff = afterend - from;
4209 size_t middle = from + diff/2;
4210 left = array_setter_node(parser, array, index, value, from, middle);
4211 right = array_setter_node(parser, array, index, value, middle, afterend);
4212 return array_accessor_split(parser, array, index, middle, left, right);
4216 static ast_expression *array_field_setter_node(
4225 lex_ctx_t ctx = ast_ctx(array);
4227 if (from+1 == afterend) {
4228 /* set this value */
4231 ast_entfield *entfield;
4232 ast_array_index *subscript;
4234 int assignop = type_storep_instr[value->expression.vtype];
4236 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4237 assignop = INSTR_STOREP_V;
4239 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4243 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4244 subscript->expression.vtype = TYPE_FIELD;
4246 entfield = ast_entfield_new_force(ctx,
4247 (ast_expression*)entity,
4248 (ast_expression*)subscript,
4249 (ast_expression*)subscript);
4251 ast_delete(subscript);
4255 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4257 ast_delete(entfield);
4261 block = ast_block_new(ctx);
4267 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4272 ret = ast_return_new(ctx, NULL);
4278 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4283 return (ast_expression*)block;
4285 ast_expression *left, *right;
4286 size_t diff = afterend - from;
4287 size_t middle = from + diff/2;
4288 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4289 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4290 return array_accessor_split(parser, array, index, middle, left, right);
4294 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4296 lex_ctx_t ctx = ast_ctx(array);
4298 if (from+1 == afterend) {
4300 ast_array_index *subscript;
4302 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4306 ret = ast_return_new(ctx, (ast_expression*)subscript);
4308 ast_delete(subscript);
4312 return (ast_expression*)ret;
4314 ast_expression *left, *right;
4315 size_t diff = afterend - from;
4316 size_t middle = from + diff/2;
4317 left = array_getter_node(parser, array, index, from, middle);
4318 right = array_getter_node(parser, array, index, middle, afterend);
4319 return array_accessor_split(parser, array, index, middle, left, right);
4323 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4325 ast_function *func = NULL;
4326 ast_value *fval = NULL;
4327 ast_block *body = NULL;
4329 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4331 parseerror(parser, "failed to create accessor function value");
4335 func = ast_function_new(ast_ctx(array), funcname, fval);
4338 parseerror(parser, "failed to create accessor function node");
4342 body = ast_block_new(ast_ctx(array));
4344 parseerror(parser, "failed to create block for array accessor");
4350 vec_push(func->blocks, body);
4353 vec_push(parser->accessors, fval);
4358 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4360 ast_value *index = NULL;
4361 ast_value *value = NULL;
4365 if (!ast_istype(array->expression.next, ast_value)) {
4366 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4370 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4372 func = fval->constval.vfunc;
4373 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4375 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4376 value = ast_value_copy((ast_value*)array->expression.next);
4378 if (!index || !value) {
4379 parseerror(parser, "failed to create locals for array accessor");
4382 (void)!ast_value_set_name(value, "value"); /* not important */
4383 vec_push(fval->expression.params, index);
4384 vec_push(fval->expression.params, value);
4386 array->setter = fval;
4389 if (index) ast_delete(index);
4390 if (value) ast_delete(value);
4396 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4398 ast_expression *root = NULL;
4399 root = array_setter_node(parser, array,
4400 array->setter->expression.params[0],
4401 array->setter->expression.params[1],
4402 0, array->expression.count);
4404 parseerror(parser, "failed to build accessor search tree");
4407 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4414 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4416 if (!parser_create_array_setter_proto(parser, array, funcname))
4418 return parser_create_array_setter_impl(parser, array);
4421 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4423 ast_expression *root = NULL;
4424 ast_value *entity = NULL;
4425 ast_value *index = NULL;
4426 ast_value *value = NULL;
4430 if (!ast_istype(array->expression.next, ast_value)) {
4431 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4435 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4437 func = fval->constval.vfunc;
4438 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4440 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4441 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4442 value = ast_value_copy((ast_value*)array->expression.next);
4443 if (!entity || !index || !value) {
4444 parseerror(parser, "failed to create locals for array accessor");
4447 (void)!ast_value_set_name(value, "value"); /* not important */
4448 vec_push(fval->expression.params, entity);
4449 vec_push(fval->expression.params, index);
4450 vec_push(fval->expression.params, value);
4452 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4454 parseerror(parser, "failed to build accessor search tree");
4458 array->setter = fval;
4459 return ast_block_add_expr(func->blocks[0], root);
4461 if (entity) ast_delete(entity);
4462 if (index) ast_delete(index);
4463 if (value) ast_delete(value);
4464 if (root) ast_delete(root);
4470 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4472 ast_value *index = NULL;
4476 /* NOTE: checking array->expression.next rather than elemtype since
4477 * for fields elemtype is a temporary fieldtype.
4479 if (!ast_istype(array->expression.next, ast_value)) {
4480 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4484 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4486 func = fval->constval.vfunc;
4487 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4489 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4492 parseerror(parser, "failed to create locals for array accessor");
4495 vec_push(fval->expression.params, index);
4497 array->getter = fval;
4500 if (index) ast_delete(index);
4506 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4508 ast_expression *root = NULL;
4510 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4512 parseerror(parser, "failed to build accessor search tree");
4515 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4522 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4524 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4526 return parser_create_array_getter_impl(parser, array);
4529 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4537 bool variadic = false;
4538 ast_value *varparam = NULL;
4539 char *argcounter = NULL;
4541 ctx = parser_ctx(parser);
4543 /* for the sake of less code we parse-in in this function */
4544 if (!parser_next(parser)) {
4546 parseerror(parser, "expected parameter list");
4552 /* parse variables until we hit a closing paren */
4553 while (parser->tok != ')') {
4554 bool is_varargs = false;
4557 /* there must be commas between them */
4558 if (parser->tok != ',') {
4559 parseerror(parser, "expected comma or end of parameter list");
4562 if (!parser_next(parser)) {
4563 parseerror(parser, "expected parameter");
4569 param = parse_typename(parser, NULL, NULL, &is_varargs);
4570 if (!param && !is_varargs)
4573 /* '...' indicates a varargs function */
4575 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4576 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4579 if (parser->tok == TOKEN_IDENT) {
4580 argcounter = util_strdup(parser_tokval(parser));
4581 if (!parser_next(parser) || parser->tok != ')') {
4582 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4587 vec_push(params, param);
4588 if (param->expression.vtype >= TYPE_VARIANT) {
4589 char tname[1024]; /* typename is reserved in C++ */
4590 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4591 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4594 /* type-restricted varargs */
4595 if (parser->tok == TOKEN_DOTS) {
4597 varparam = vec_last(params);
4599 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4600 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4603 if (parser->tok == TOKEN_IDENT) {
4604 argcounter = util_strdup(parser_tokval(parser));
4605 if (!parser_next(parser) || parser->tok != ')') {
4606 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4614 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4618 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4619 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4622 if (!parser_next(parser)) {
4623 parseerror(parser, "parse error after typename");
4627 /* now turn 'var' into a function type */
4628 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4629 fval->expression.next = (ast_expression*)var;
4631 fval->expression.flags |= AST_FLAG_VARIADIC;
4634 var->expression.params = params;
4635 var->expression.varparam = (ast_expression*)varparam;
4636 var->argcounter = argcounter;
4645 ast_delete(varparam);
4647 for (i = 0; i < vec_size(params); ++i)
4648 ast_delete(params[i]);
4653 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4655 ast_expression *cexp;
4656 ast_value *cval, *tmp;
4659 ctx = parser_ctx(parser);
4661 if (!parser_next(parser)) {
4663 parseerror(parser, "expected array-size");
4667 if (parser->tok != ']') {
4668 cexp = parse_expression_leave(parser, true, false, false);
4670 if (!cexp || !ast_istype(cexp, ast_value)) {
4674 parseerror(parser, "expected array-size as constant positive integer");
4677 cval = (ast_value*)cexp;
4684 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4685 tmp->expression.next = (ast_expression*)var;
4689 if (cval->expression.vtype == TYPE_INTEGER)
4690 tmp->expression.count = cval->constval.vint;
4691 else if (cval->expression.vtype == TYPE_FLOAT)
4692 tmp->expression.count = cval->constval.vfloat;
4696 parseerror(parser, "array-size must be a positive integer constant");
4702 var->expression.count = -1;
4703 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4706 if (parser->tok != ']') {
4708 parseerror(parser, "expected ']' after array-size");
4711 if (!parser_next(parser)) {
4713 parseerror(parser, "error after parsing array size");
4719 /* Parse a complete typename.
4720 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4721 * but when parsing variables separated by comma
4722 * 'storebase' should point to where the base-type should be kept.
4723 * The base type makes up every bit of type information which comes *before* the
4726 * NOTE: The value must either be named, have a NULL name, or a name starting
4727 * with '<'. In the first case, this will be the actual variable or type
4728 * name, in the other cases it is assumed that the name will appear
4729 * later, and an error is generated otherwise.
4731 * The following will be parsed in its entirety:
4733 * The 'basetype' in this case is 'void()'
4734 * and if there's a comma after it, say:
4736 * then the type-information 'void()' can be stored in 'storebase'
4738 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4740 ast_value *var, *tmp;
4743 const char *name = NULL;
4744 bool isfield = false;
4745 bool wasarray = false;
4746 size_t morefields = 0;
4748 bool vararg = (parser->tok == TOKEN_DOTS);
4750 ctx = parser_ctx(parser);
4752 /* types may start with a dot */
4753 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4755 if (parser->tok == TOKEN_DOTS)
4757 /* if we parsed a dot we need a typename now */
4758 if (!parser_next(parser)) {
4759 parseerror(parser, "expected typename for field definition");
4763 /* Further dots are handled seperately because they won't be part of the
4767 if (parser->tok == '.')
4769 else if (parser->tok == TOKEN_DOTS)
4774 if (!parser_next(parser)) {
4775 parseerror(parser, "expected typename for field definition");
4780 if (parser->tok == TOKEN_IDENT)
4781 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4782 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4783 if (vararg && is_vararg) {
4787 parseerror(parser, "expected typename");
4791 /* generate the basic type value */
4792 if (cached_typedef) {
4793 var = ast_value_copy(cached_typedef);
4794 ast_value_set_name(var, "<type(from_def)>");
4796 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4798 for (; morefields; --morefields) {
4799 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4800 tmp->expression.next = (ast_expression*)var;
4804 /* do not yet turn into a field - remember:
4805 * .void() foo; is a field too
4806 * .void()() foo; is a function
4810 if (!parser_next(parser)) {
4812 parseerror(parser, "parse error after typename");
4816 /* an opening paren now starts the parameter-list of a function
4817 * this is where original-QC has parameter lists.
4818 * We allow a single parameter list here.
4819 * Much like fteqcc we don't allow `float()() x`
4821 if (parser->tok == '(') {
4822 var = parse_parameter_list(parser, var);
4827 /* store the base if requested */
4829 *storebase = ast_value_copy(var);
4831 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4832 tmp->expression.next = (ast_expression*)*storebase;
4837 /* there may be a name now */
4838 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4839 if (!strcmp(parser_tokval(parser), "break"))
4840 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4841 else if (parser->tok == TOKEN_KEYWORD)
4844 name = util_strdup(parser_tokval(parser));
4847 if (!parser_next(parser)) {
4850 parseerror(parser, "error after variable or field declaration");
4856 /* now this may be an array */
4857 if (parser->tok == '[') {
4859 var = parse_arraysize(parser, var);
4861 if (name) mem_d(name);
4866 /* This is the point where we can turn it into a field */
4868 /* turn it into a field if desired */
4869 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4870 tmp->expression.next = (ast_expression*)var;
4874 /* now there may be function parens again */
4875 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4876 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4877 if (parser->tok == '(' && wasarray)
4878 parseerror(parser, "arrays as part of a return type is not supported");
4879 while (parser->tok == '(') {
4880 var = parse_parameter_list(parser, var);
4882 if (name) mem_d(name);
4887 /* finally name it */
4889 if (!ast_value_set_name(var, name)) {
4892 parseerror(parser, "internal error: failed to set name");
4895 /* free the name, ast_value_set_name duplicates */
4902 static bool parse_typedef(parser_t *parser)
4904 ast_value *typevar, *oldtype;
4905 ast_expression *old;
4907 typevar = parse_typename(parser, NULL, NULL, NULL);
4912 /* while parsing types, the ast_value's get named '<something>' */
4913 if (!typevar->name || typevar->name[0] == '<') {
4914 parseerror(parser, "missing name in typedef");
4915 ast_delete(typevar);
4919 if ( (old = parser_find_var(parser, typevar->name)) ) {
4920 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4921 " -> `%s` has been declared here: %s:%i",
4922 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4923 ast_delete(typevar);
4927 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4928 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4929 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4930 ast_delete(typevar);
4934 vec_push(parser->_typedefs, typevar);
4935 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4937 if (parser->tok != ';') {
4938 parseerror(parser, "expected semicolon after typedef");
4941 if (!parser_next(parser)) {
4942 parseerror(parser, "parse error after typedef");
4949 static const char *cvq_to_str(int cvq) {
4951 case CV_NONE: return "none";
4952 case CV_VAR: return "`var`";
4953 case CV_CONST: return "`const`";
4954 default: return "<INVALID>";
4958 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4961 if (proto->cvq != var->cvq) {
4962 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4963 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4964 parser->tok == '='))
4966 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4967 "`%s` declared with different qualifiers: %s\n"
4968 " -> previous declaration here: %s:%i uses %s",
4969 var->name, cvq_to_str(var->cvq),
4970 ast_ctx(proto).file, ast_ctx(proto).line,
4971 cvq_to_str(proto->cvq));
4974 av = (var ->expression.flags & AST_FLAG_NORETURN);
4975 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4977 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4978 "`%s` declared with different attributes%s\n"
4979 " -> previous declaration here: %s:%i",
4980 var->name, (av ? ": noreturn" : ""),
4981 ast_ctx(proto).file, ast_ctx(proto).line,
4982 (ao ? ": noreturn" : ""));
4987 static bool create_array_accessors(parser_t *parser, ast_value *var)
4990 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4991 if (!parser_create_array_setter(parser, var, name))
4993 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4994 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4999 static bool parse_array(parser_t *parser, ast_value *array)
5002 if (array->initlist) {
5003 parseerror(parser, "array already initialized elsewhere");
5006 if (!parser_next(parser)) {
5007 parseerror(parser, "parse error in array initializer");
5011 while (parser->tok != '}') {
5012 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5015 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5017 parseerror(parser, "initializing element must be a compile time constant");
5020 vec_push(array->initlist, v->constval);
5021 if (v->expression.vtype == TYPE_STRING) {
5022 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5026 if (parser->tok == '}')
5028 if (parser->tok != ',' || !parser_next(parser)) {
5029 parseerror(parser, "expected comma or '}' in element list");
5033 if (!parser_next(parser) || parser->tok != ';') {
5034 parseerror(parser, "expected semicolon after initializer, got %s");
5038 if (!parser_next(parser)) {
5039 parseerror(parser, "parse error after initializer");
5044 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5045 if (array->expression.count != (size_t)-1) {
5046 parseerror(parser, "array `%s' has already been initialized with %u elements",
5047 array->name, (unsigned)array->expression.count);
5049 array->expression.count = vec_size(array->initlist);
5050 if (!create_array_accessors(parser, array))
5056 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring)
5060 ast_expression *old;
5064 ast_value *basetype = NULL;
5066 bool isparam = false;
5067 bool isvector = false;
5068 bool cleanvar = true;
5069 bool wasarray = false;
5071 ast_member *me[3] = { NULL, NULL, NULL };
5073 if (!localblock && is_static)
5074 parseerror(parser, "`static` qualifier is not supported in global scope");
5076 /* get the first complete variable */
5077 var = parse_typename(parser, &basetype, cached_typedef, NULL);
5080 ast_delete(basetype);
5084 /* while parsing types, the ast_value's get named '<something>' */
5085 if (!var->name || var->name[0] == '<') {
5086 parseerror(parser, "declaration does not declare anything");
5088 ast_delete(basetype);
5096 /* Part 0: finish the type */
5097 if (parser->tok == '(') {
5098 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5099 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5100 var = parse_parameter_list(parser, var);
5106 /* we only allow 1-dimensional arrays */
5107 if (parser->tok == '[') {
5109 var = parse_arraysize(parser, var);
5115 if (parser->tok == '(' && wasarray) {
5116 parseerror(parser, "arrays as part of a return type is not supported");
5117 /* we'll still parse the type completely for now */
5119 /* for functions returning functions */
5120 while (parser->tok == '(') {
5121 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5122 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5123 var = parse_parameter_list(parser, var);
5130 var->cvq = qualifier;
5131 var->expression.flags |= qflags;
5134 * store the vstring back to var for alias and
5135 * deprecation messages.
5137 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5138 var->expression.flags & AST_FLAG_ALIAS)
5139 var->desc = vstring;
5141 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5142 parseerror(parser, "function aliases cannot be forward declared");
5149 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5150 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5151 * is then filled with the previous definition and the parameter-names replaced.
5153 if (!strcmp(var->name, "nil")) {
5154 if (OPTS_FLAG(UNTYPED_NIL)) {
5155 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5156 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5158 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5161 /* Deal with end_sys_ vars */
5163 if (!strcmp(var->name, "end_sys_globals")) {
5165 parser->crc_globals = vec_size(parser->globals);
5168 else if (!strcmp(var->name, "end_sys_fields")) {
5170 parser->crc_fields = vec_size(parser->fields);
5173 if (was_end && var->expression.vtype == TYPE_FIELD) {
5174 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5175 "global '%s' hint should not be a field",
5176 parser_tokval(parser)))
5183 if (!nofields && var->expression.vtype == TYPE_FIELD)
5185 /* deal with field declarations */
5186 old = parser_find_field(parser, var->name);
5188 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5189 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5198 parseerror(parser, "field `%s` already declared here: %s:%i",
5199 var->name, ast_ctx(old).file, ast_ctx(old).line);
5204 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5205 (old = parser_find_global(parser, var->name)))
5207 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5208 parseerror(parser, "field `%s` already declared here: %s:%i",
5209 var->name, ast_ctx(old).file, ast_ctx(old).line);
5216 /* deal with other globals */
5217 old = parser_find_global(parser, var->name);
5218 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5220 /* This is a function which had a prototype */
5221 if (!ast_istype(old, ast_value)) {
5222 parseerror(parser, "internal error: prototype is not an ast_value");
5226 proto = (ast_value*)old;
5227 proto->desc = var->desc;
5228 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5229 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5231 ast_ctx(proto).file, ast_ctx(proto).line);
5235 /* we need the new parameter-names */
5236 for (i = 0; i < vec_size(proto->expression.params); ++i)
5237 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5238 if (!parser_check_qualifiers(parser, var, proto)) {
5245 proto->expression.flags |= var->expression.flags;
5253 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5254 "global `%s` already declared here: %s:%i",
5255 var->name, ast_ctx(old).file, ast_ctx(old).line))
5260 proto = (ast_value*)old;
5261 if (!ast_istype(old, ast_value)) {
5262 parseerror(parser, "internal error: not an ast_value");
5267 if (!parser_check_qualifiers(parser, var, proto)) {
5272 proto->expression.flags |= var->expression.flags;
5276 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5277 (old = parser_find_field(parser, var->name)))
5279 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5280 parseerror(parser, "global `%s` already declared here: %s:%i",
5281 var->name, ast_ctx(old).file, ast_ctx(old).line);
5288 else /* it's not a global */
5290 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5291 if (old && !isparam) {
5292 parseerror(parser, "local `%s` already declared here: %s:%i",
5293 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5297 /* doing this here as the above is just for a single scope */
5298 old = parser_find_local(parser, var->name, 0, &isparam);
5299 if (old && isparam) {
5300 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5301 "local `%s` is shadowing a parameter", var->name))
5303 parseerror(parser, "local `%s` already declared here: %s:%i",
5304 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5308 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5310 if (ast_istype(old, ast_value))
5311 var = proto = (ast_value*)old;
5320 /* in a noref section we simply bump the usecount */
5321 if (noref || parser->noref)
5325 * Create the global/local, and deal with vector types.
5328 if (var->expression.vtype == TYPE_VECTOR)
5330 else if (var->expression.vtype == TYPE_FIELD &&
5331 var->expression.next->vtype == TYPE_VECTOR)
5335 if (!create_vector_members(var, me)) {
5342 /* deal with global variables, fields, functions */
5343 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5344 var->isfield = true;
5345 vec_push(parser->fields, (ast_expression*)var);
5346 util_htset(parser->htfields, var->name, var);
5348 for (i = 0; i < 3; ++i) {
5349 vec_push(parser->fields, (ast_expression*)me[i]);
5350 util_htset(parser->htfields, me[i]->name, me[i]);
5355 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5356 parser_addglobal(parser, var->name, (ast_expression*)var);
5358 for (i = 0; i < 3; ++i) {
5359 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5363 ast_expression *find = parser_find_global(parser, var->desc);
5366 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5370 if (!ast_compare_type((ast_expression*)var, find)) {
5374 ast_type_to_string(find, ty1, sizeof(ty1));
5375 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5377 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5384 * add alias to aliases table and to corrector
5385 * so corrections can apply for aliases as well.
5387 util_htset(parser->aliases, var->name, find);
5390 * add to corrector so corrections can work
5391 * even for aliases too.
5394 vec_last(parser->correct_variables),
5395 &vec_last(parser->correct_variables_score),
5399 /* generate aliases for vector components */
5403 util_asprintf(&buffer[0], "%s_x", var->desc);
5404 util_asprintf(&buffer[1], "%s_y", var->desc);
5405 util_asprintf(&buffer[2], "%s_z", var->desc);
5407 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5408 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5409 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5416 * add to corrector so corrections can work
5417 * even for aliases too.
5420 vec_last(parser->correct_variables),
5421 &vec_last(parser->correct_variables_score),
5425 vec_last(parser->correct_variables),
5426 &vec_last(parser->correct_variables_score),
5430 vec_last(parser->correct_variables),
5431 &vec_last(parser->correct_variables_score),
5439 /* a static adds itself to be generated like any other global
5440 * but is added to the local namespace instead
5442 char *defname = NULL;
5443 size_t prefix_len, ln;
5446 ln = strlen(parser->function->name);
5447 vec_append(defname, ln, parser->function->name);
5449 vec_append(defname, 2, "::");
5450 /* remember the length up to here */
5451 prefix_len = vec_size(defname);
5453 /* Add it to the local scope */
5454 util_htset(vec_last(parser->variables), var->name, (void*)var);
5458 vec_last(parser->correct_variables),
5459 &vec_last(parser->correct_variables_score),
5463 /* now rename the global */
5464 ln = strlen(var->name);
5465 vec_append(defname, ln, var->name);
5466 /* if a variable of that name already existed, add the
5468 * The counter is incremented either way.
5470 sn_size = vec_size(parser->function->static_names);
5471 for (sn = 0; sn != sn_size; ++sn) {
5472 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5475 if (sn != sn_size) {
5477 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5478 vec_append(defname, len, num);
5482 vec_push(parser->function->static_names, util_strdup(var->name));
5483 parser->function->static_count++;
5484 ast_value_set_name(var, defname);
5486 /* push it to the to-be-generated globals */
5487 vec_push(parser->globals, (ast_expression*)var);
5489 /* same game for the vector members */
5491 for (i = 0; i < 3; ++i) {
5492 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5496 vec_last(parser->correct_variables),
5497 &vec_last(parser->correct_variables_score),
5501 vec_shrinkto(defname, prefix_len);
5502 ln = strlen(me[i]->name);
5503 vec_append(defname, ln, me[i]->name);
5504 ast_member_set_name(me[i], defname);
5506 vec_push(parser->globals, (ast_expression*)me[i]);
5511 vec_push(localblock->locals, var);
5512 parser_addlocal(parser, var->name, (ast_expression*)var);
5514 for (i = 0; i < 3; ++i) {
5515 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5516 ast_block_collect(localblock, (ast_expression*)me[i]);
5522 me[0] = me[1] = me[2] = NULL;
5527 if (var->expression.vtype == TYPE_ARRAY) {
5528 if (var->expression.count != (size_t)-1) {
5529 if (!create_array_accessors(parser, var))
5533 else if (!localblock && !nofields &&
5534 var->expression.vtype == TYPE_FIELD &&
5535 var->expression.next->vtype == TYPE_ARRAY)
5538 ast_expression *telem;
5540 ast_value *array = (ast_value*)var->expression.next;
5542 if (!ast_istype(var->expression.next, ast_value)) {
5543 parseerror(parser, "internal error: field element type must be an ast_value");
5547 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5548 if (!parser_create_array_field_setter(parser, array, name))
5551 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5552 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5553 tfield->expression.next = telem;
5554 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5555 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5563 if (parser->tok == ';') {
5564 ast_delete(basetype);
5565 if (!parser_next(parser)) {
5566 parseerror(parser, "error after variable declaration");
5572 if (parser->tok == ',')
5576 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5579 parseerror(parser, "missing comma or semicolon while parsing variables");
5583 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5584 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5585 "initializing expression turns variable `%s` into a constant in this standard",
5592 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5593 if (parser->tok != '=') {
5594 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5598 if (!parser_next(parser)) {
5599 parseerror(parser, "error parsing initializer");
5603 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5604 parseerror(parser, "expected '=' before function body in this standard");
5607 if (parser->tok == '#') {
5608 ast_function *func = NULL;
5609 ast_value *number = NULL;
5615 parseerror(parser, "cannot declare builtins within functions");
5618 if (var->expression.vtype != TYPE_FUNCTION) {
5619 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5622 if (!parser_next(parser)) {
5623 parseerror(parser, "expected builtin number");
5627 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5628 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5630 parseerror(parser, "builtin number expected");
5633 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5636 parseerror(parser, "builtin number must be a compile time constant");
5639 if (number->expression.vtype == TYPE_INTEGER)
5640 builtin_num = number->constval.vint;
5641 else if (number->expression.vtype == TYPE_FLOAT)
5642 builtin_num = number->constval.vfloat;
5645 parseerror(parser, "builtin number must be an integer constant");
5650 fractional = modff(builtin_num, &integral);
5651 if (builtin_num < 0 || fractional != 0) {
5652 parseerror(parser, "builtin number must be an integer greater than zero");
5656 /* we only want the integral part anyways */
5657 builtin_num = integral;
5658 } else if (parser->tok == TOKEN_INTCONST) {
5659 builtin_num = parser_token(parser)->constval.i;
5661 parseerror(parser, "builtin number must be a compile time constant");
5665 if (var->hasvalue) {
5666 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5667 "builtin `%s` has already been defined\n"
5668 " -> previous declaration here: %s:%i",
5669 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5673 func = ast_function_new(ast_ctx(var), var->name, var);
5675 parseerror(parser, "failed to allocate function for `%s`", var->name);
5678 vec_push(parser->functions, func);
5680 func->builtin = -builtin_num-1;
5683 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5684 ? (parser->tok != ',' && parser->tok != ';')
5685 : (!parser_next(parser)))
5687 parseerror(parser, "expected comma or semicolon");
5689 ast_function_delete(func);
5690 var->constval.vfunc = NULL;
5694 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5697 /* Note that fteqcc and most others don't even *have*
5698 * local arrays, so this is not a high priority.
5700 parseerror(parser, "TODO: initializers for local arrays");
5704 var->hasvalue = true;
5705 if (!parse_array(parser, var))
5708 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5711 parseerror(parser, "cannot declare functions within functions");
5716 ast_ctx(proto) = parser_ctx(parser);
5718 if (!parse_function_body(parser, var))
5720 ast_delete(basetype);
5721 for (i = 0; i < vec_size(parser->gotos); ++i)
5722 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5723 vec_free(parser->gotos);
5724 vec_free(parser->labels);
5727 ast_expression *cexp;
5730 cexp = parse_expression_leave(parser, true, false, false);
5734 if (!localblock || is_static) {
5735 cval = (ast_value*)cexp;
5736 if (cval != parser->nil &&
5737 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5740 parseerror(parser, "initializer is non constant");
5745 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5746 qualifier != CV_VAR)
5748 var->cvq = CV_CONST;
5750 if (cval == parser->nil)
5751 var->expression.flags |= AST_FLAG_INITIALIZED;
5754 var->hasvalue = true;
5755 if (cval->expression.vtype == TYPE_STRING)
5756 var->constval.vstring = parser_strdup(cval->constval.vstring);
5757 else if (cval->expression.vtype == TYPE_FIELD)
5758 var->constval.vfield = cval;
5760 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5766 shunt sy = { NULL, NULL, NULL, NULL };
5769 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5770 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5771 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5772 if (!parser_sy_apply_operator(parser, &sy))
5775 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5776 parseerror(parser, "internal error: leaked operands");
5777 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5788 if (parser->tok == ',') {
5789 if (!parser_next(parser)) {
5790 parseerror(parser, "expected another variable");
5794 if (parser->tok != TOKEN_IDENT) {
5795 parseerror(parser, "expected another variable");
5798 var = ast_value_copy(basetype);
5800 ast_value_set_name(var, parser_tokval(parser));
5801 if (!parser_next(parser)) {
5802 parseerror(parser, "error parsing variable declaration");
5808 if (parser->tok != ';') {
5809 parseerror(parser, "missing semicolon after variables");
5813 if (!parser_next(parser)) {
5814 parseerror(parser, "parse error after variable declaration");
5818 ast_delete(basetype);
5822 if (cleanvar && var)
5824 ast_delete(basetype);
5828 ast_delete(basetype);
5829 if (cleanvar && var)
5831 if (me[0]) ast_member_delete(me[0]);
5832 if (me[1]) ast_member_delete(me[1]);
5833 if (me[2]) ast_member_delete(me[2]);
5837 static bool parser_global_statement(parser_t *parser)
5841 bool is_static = false;
5842 uint32_t qflags = 0;
5843 ast_value *istype = NULL;
5844 char *vstring = NULL;
5846 if (parser->tok == TOKEN_IDENT)
5847 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5849 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5851 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5853 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5855 if (cvq == CV_WRONG)
5857 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5859 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5861 return parse_enum(parser);
5863 else if (parser->tok == TOKEN_KEYWORD)
5865 if (!strcmp(parser_tokval(parser), "typedef")) {
5866 if (!parser_next(parser)) {
5867 parseerror(parser, "expected type definition after 'typedef'");
5870 return parse_typedef(parser);
5872 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5875 else if (parser->tok == '#')
5877 return parse_pragma(parser);
5879 else if (parser->tok == '$')
5881 if (!parser_next(parser)) {
5882 parseerror(parser, "parse error");
5888 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5894 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5896 return util_crc16(old, str, strlen(str));
5899 static void progdefs_crc_file(const char *str)
5901 /* write to progdefs.h here */
5905 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5907 old = progdefs_crc_sum(old, str);
5908 progdefs_crc_file(str);
5912 static void generate_checksum(parser_t *parser, ir_builder *ir)
5914 uint16_t crc = 0xFFFF;
5918 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5919 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5921 progdefs_crc_file("\tint\tpad;\n");
5922 progdefs_crc_file("\tint\tofs_return[3];\n");
5923 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5924 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5925 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5926 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5927 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5928 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5929 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5930 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5932 for (i = 0; i < parser->crc_globals; ++i) {
5933 if (!ast_istype(parser->globals[i], ast_value))
5935 value = (ast_value*)(parser->globals[i]);
5936 switch (value->expression.vtype) {
5937 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5938 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5939 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5940 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5942 crc = progdefs_crc_both(crc, "\tint\t");
5945 crc = progdefs_crc_both(crc, value->name);
5946 crc = progdefs_crc_both(crc, ";\n");
5948 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5949 for (i = 0; i < parser->crc_fields; ++i) {
5950 if (!ast_istype(parser->fields[i], ast_value))
5952 value = (ast_value*)(parser->fields[i]);
5953 switch (value->expression.next->vtype) {
5954 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5955 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5956 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5957 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5959 crc = progdefs_crc_both(crc, "\tint\t");
5962 crc = progdefs_crc_both(crc, value->name);
5963 crc = progdefs_crc_both(crc, ";\n");
5965 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5966 ir->code->crc = crc;
5969 parser_t *parser_create()
5972 lex_ctx_t empty_ctx;
5975 parser = (parser_t*)mem_a(sizeof(parser_t));
5979 memset(parser, 0, sizeof(*parser));
5981 for (i = 0; i < operator_count; ++i) {
5982 if (operators[i].id == opid1('=')) {
5983 parser->assign_op = operators+i;
5987 if (!parser->assign_op) {
5988 con_err("internal error: initializing parser: failed to find assign operator\n");
5993 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5994 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5995 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5996 vec_push(parser->_blocktypedefs, 0);
5998 parser->aliases = util_htnew(PARSER_HT_SIZE);
6001 vec_push(parser->correct_variables, correct_trie_new());
6002 vec_push(parser->correct_variables_score, NULL);
6004 empty_ctx.file = "<internal>";
6006 empty_ctx.column = 0;
6007 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6008 parser->nil->cvq = CV_CONST;
6009 if (OPTS_FLAG(UNTYPED_NIL))
6010 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6012 parser->max_param_count = 1;
6014 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6015 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6016 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6018 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6019 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6020 parser->reserved_version->cvq = CV_CONST;
6021 parser->reserved_version->hasvalue = true;
6022 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6023 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6025 parser->reserved_version = NULL;
6028 parser->fold = fold_init (parser);
6029 parser->intrin = intrin_init(parser);
6033 static bool parser_compile(parser_t *parser)
6035 /* initial lexer/parser state */
6036 parser->lex->flags.noops = true;
6038 if (parser_next(parser))
6040 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6042 if (!parser_global_statement(parser)) {
6043 if (parser->tok == TOKEN_EOF)
6044 parseerror(parser, "unexpected end of file");
6045 else if (compile_errors)
6046 parseerror(parser, "there have been errors, bailing out");
6047 lex_close(parser->lex);
6053 parseerror(parser, "parse error");
6054 lex_close(parser->lex);
6059 lex_close(parser->lex);
6062 return !compile_errors;
6065 bool parser_compile_file(parser_t *parser, const char *filename)
6067 parser->lex = lex_open(filename);
6069 con_err("failed to open file \"%s\"\n", filename);
6072 return parser_compile(parser);
6075 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6077 parser->lex = lex_open_string(str, len, name);
6079 con_err("failed to create lexer for string \"%s\"\n", name);
6082 return parser_compile(parser);
6085 static void parser_remove_ast(parser_t *parser)
6088 if (parser->ast_cleaned)
6090 parser->ast_cleaned = true;
6091 for (i = 0; i < vec_size(parser->accessors); ++i) {
6092 ast_delete(parser->accessors[i]->constval.vfunc);
6093 parser->accessors[i]->constval.vfunc = NULL;
6094 ast_delete(parser->accessors[i]);
6096 for (i = 0; i < vec_size(parser->functions); ++i) {
6097 ast_delete(parser->functions[i]);
6099 for (i = 0; i < vec_size(parser->fields); ++i) {
6100 ast_delete(parser->fields[i]);
6102 for (i = 0; i < vec_size(parser->globals); ++i) {
6103 ast_delete(parser->globals[i]);
6105 vec_free(parser->accessors);
6106 vec_free(parser->functions);
6107 vec_free(parser->globals);
6108 vec_free(parser->fields);
6110 for (i = 0; i < vec_size(parser->variables); ++i)
6111 util_htdel(parser->variables[i]);
6112 vec_free(parser->variables);
6113 vec_free(parser->_blocklocals);
6114 vec_free(parser->_locals);
6117 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6118 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6120 vec_free(parser->correct_variables);
6121 vec_free(parser->correct_variables_score);
6123 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6124 ast_delete(parser->_typedefs[i]);
6125 vec_free(parser->_typedefs);
6126 for (i = 0; i < vec_size(parser->typedefs); ++i)
6127 util_htdel(parser->typedefs[i]);
6128 vec_free(parser->typedefs);
6129 vec_free(parser->_blocktypedefs);
6131 vec_free(parser->_block_ctx);
6133 vec_free(parser->labels);
6134 vec_free(parser->gotos);
6135 vec_free(parser->breaks);
6136 vec_free(parser->continues);
6138 ast_value_delete(parser->nil);
6140 ast_value_delete(parser->const_vec[0]);
6141 ast_value_delete(parser->const_vec[1]);
6142 ast_value_delete(parser->const_vec[2]);
6144 if (parser->reserved_version)
6145 ast_value_delete(parser->reserved_version);
6147 util_htdel(parser->aliases);
6148 fold_cleanup(parser->fold);
6149 intrin_cleanup(parser->intrin);
6152 void parser_cleanup(parser_t *parser)
6154 parser_remove_ast(parser);
6158 bool parser_finish(parser_t *parser, const char *output)
6164 if (compile_errors) {
6165 con_out("*** there were compile errors\n");
6169 ir = ir_builder_new("gmqcc_out");
6171 con_out("failed to allocate builder\n");
6175 for (i = 0; i < vec_size(parser->fields); ++i) {
6178 if (!ast_istype(parser->fields[i], ast_value))
6180 field = (ast_value*)parser->fields[i];
6181 hasvalue = field->hasvalue;
6182 field->hasvalue = false;
6183 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6184 con_out("failed to generate field %s\n", field->name);
6185 ir_builder_delete(ir);
6190 ast_expression *subtype;
6191 field->hasvalue = true;
6192 subtype = field->expression.next;
6193 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6194 if (subtype->vtype == TYPE_FIELD)
6195 ifld->fieldtype = subtype->next->vtype;
6196 else if (subtype->vtype == TYPE_FUNCTION)
6197 ifld->outtype = subtype->next->vtype;
6198 (void)!ir_value_set_field(field->ir_v, ifld);
6201 for (i = 0; i < vec_size(parser->globals); ++i) {
6203 if (!ast_istype(parser->globals[i], ast_value))
6205 asvalue = (ast_value*)(parser->globals[i]);
6206 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6207 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6208 "unused global: `%s`", asvalue->name);
6210 if (!ast_global_codegen(asvalue, ir, false)) {
6211 con_out("failed to generate global %s\n", asvalue->name);
6212 ir_builder_delete(ir);
6216 /* Build function vararg accessor ast tree now before generating
6217 * immediates, because the accessors may add new immediates
6219 for (i = 0; i < vec_size(parser->functions); ++i) {
6220 ast_function *f = parser->functions[i];
6222 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6223 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6224 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6225 con_out("failed to generate vararg setter for %s\n", f->name);
6226 ir_builder_delete(ir);
6229 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6230 con_out("failed to generate vararg getter for %s\n", f->name);
6231 ir_builder_delete(ir);
6235 ast_delete(f->varargs);
6240 /* Now we can generate immediates */
6241 if (!fold_generate(parser->fold, ir))
6244 for (i = 0; i < vec_size(parser->globals); ++i) {
6246 if (!ast_istype(parser->globals[i], ast_value))
6248 asvalue = (ast_value*)(parser->globals[i]);
6249 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6251 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6252 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6253 "uninitialized constant: `%s`",
6255 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6256 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6257 "uninitialized global: `%s`",
6260 if (!ast_generate_accessors(asvalue, ir)) {
6261 ir_builder_delete(ir);
6265 for (i = 0; i < vec_size(parser->fields); ++i) {
6267 asvalue = (ast_value*)(parser->fields[i]->next);
6269 if (!ast_istype((ast_expression*)asvalue, ast_value))
6271 if (asvalue->expression.vtype != TYPE_ARRAY)
6273 if (!ast_generate_accessors(asvalue, ir)) {
6274 ir_builder_delete(ir);
6278 if (parser->reserved_version &&
6279 !ast_global_codegen(parser->reserved_version, ir, false))
6281 con_out("failed to generate reserved::version");
6282 ir_builder_delete(ir);
6285 for (i = 0; i < vec_size(parser->functions); ++i) {
6286 ast_function *f = parser->functions[i];
6287 if (!ast_function_codegen(f, ir)) {
6288 con_out("failed to generate function %s\n", f->name);
6289 ir_builder_delete(ir);
6294 generate_checksum(parser, ir);
6296 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6297 ir_builder_dump(ir, con_out);
6298 for (i = 0; i < vec_size(parser->functions); ++i) {
6299 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6300 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6301 ir_builder_delete(ir);
6305 parser_remove_ast(parser);
6307 if (compile_Werrors) {
6308 con_out("*** there were warnings treated as errors\n");
6309 compile_show_werrors();
6314 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6315 ir_builder_dump(ir, con_out);
6317 if (!ir_builder_generate(ir, output)) {
6318 con_out("*** failed to generate output file\n");
6319 ir_builder_delete(ir);
6323 ir_builder_delete(ir);