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);
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 out = (ast_expression*)ast_unary_new(ctx, (VINSTR_NEG_F-TYPE_FLOAT) + exprs[0]->vtype, exprs[0]);
483 if (!(out = fold_op(parser->fold, op, exprs))) {
484 switch (exprs[0]->vtype) {
486 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
489 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
492 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
493 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
495 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
497 /* we don't constant-fold NOT for these types */
499 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
502 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
505 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
506 type_name[exprs[0]->vtype]);
513 if (exprs[0]->vtype != exprs[1]->vtype ||
514 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
516 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
517 type_name[exprs[0]->vtype],
518 type_name[exprs[1]->vtype]);
521 if (!(out = fold_op(parser->fold, op, exprs))) {
522 switch (exprs[0]->vtype) {
524 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
527 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
530 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
531 type_name[exprs[0]->vtype],
532 type_name[exprs[1]->vtype]);
538 if (exprs[0]->vtype != exprs[1]->vtype ||
539 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
541 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
542 type_name[exprs[1]->vtype],
543 type_name[exprs[0]->vtype]);
546 if (!(out = fold_op(parser->fold, op, exprs))) {
547 switch (exprs[0]->vtype) {
549 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
552 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
555 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
556 type_name[exprs[1]->vtype],
557 type_name[exprs[0]->vtype]);
563 if (exprs[0]->vtype != exprs[1]->vtype &&
564 !(exprs[0]->vtype == TYPE_VECTOR &&
565 exprs[1]->vtype == TYPE_FLOAT) &&
566 !(exprs[1]->vtype == TYPE_VECTOR &&
567 exprs[0]->vtype == TYPE_FLOAT)
570 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
571 type_name[exprs[1]->vtype],
572 type_name[exprs[0]->vtype]);
575 if (!(out = fold_op(parser->fold, op, exprs))) {
576 switch (exprs[0]->vtype) {
578 if (exprs[1]->vtype == TYPE_VECTOR)
579 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
581 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
584 if (exprs[1]->vtype == TYPE_FLOAT)
585 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
587 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
590 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
591 type_name[exprs[1]->vtype],
592 type_name[exprs[0]->vtype]);
599 if (exprs[1]->vtype != TYPE_FLOAT) {
600 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
601 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
602 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
605 if (!(out = fold_op(parser->fold, op, exprs))) {
606 if (exprs[0]->vtype == TYPE_FLOAT)
607 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
609 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
610 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
611 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
618 if (NotSameType(TYPE_FLOAT)) {
619 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
620 type_name[exprs[0]->vtype],
621 type_name[exprs[1]->vtype]);
623 } else if (!(out = fold_op(parser->fold, op, exprs))) {
624 /* generate a call to __builtin_mod */
625 ast_expression *mod = intrin_func(parser->intrin, "mod");
626 ast_call *call = NULL;
627 if (!mod) return false; /* can return null for missing floor */
629 call = ast_call_new(parser_ctx(parser), mod);
630 vec_push(call->params, exprs[0]);
631 vec_push(call->params, exprs[1]);
633 out = (ast_expression*)call;
638 compile_error(ctx, "%= is unimplemented");
644 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
645 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
646 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
648 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
649 type_name[exprs[0]->vtype],
650 type_name[exprs[1]->vtype]);
654 if (!(out = fold_op(parser->fold, op, exprs))) {
656 * IF the first expression is float, the following will be too
657 * since scalar ^ vector is not allowed.
659 if (exprs[0]->vtype == TYPE_FLOAT) {
660 out = (ast_expression*)ast_binary_new(ctx,
661 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
665 * The first is a vector: vector is allowed to bitop with vector and
666 * with scalar, branch here for the second operand.
668 if (exprs[1]->vtype == TYPE_VECTOR) {
670 * Bitop all the values of the vector components against the
671 * vectors components in question.
673 out = (ast_expression*)ast_binary_new(ctx,
674 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
677 out = (ast_expression*)ast_binary_new(ctx,
678 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
687 case opid3('<','<','='):
688 case opid3('>','>','='):
689 if(!(out = fold_op(parser->fold, op, exprs))) {
690 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
696 generated_op += 1; /* INSTR_OR */
698 generated_op += INSTR_AND;
699 if (!(out = fold_op(parser->fold, op, exprs))) {
700 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
701 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
702 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
703 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
706 for (i = 0; i < 2; ++i) {
707 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
708 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
710 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
712 exprs[i] = out; out = NULL;
713 if (OPTS_FLAG(PERL_LOGIC)) {
714 /* here we want to keep the right expressions' type */
718 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
721 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
723 exprs[i] = out; out = NULL;
724 if (OPTS_FLAG(PERL_LOGIC)) {
725 /* here we want to keep the right expressions' type */
730 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
735 if (vec_last(sy->paren) != PAREN_TERNARY2) {
736 compile_error(ctx, "mismatched parenthesis/ternary");
740 if (!ast_compare_type(exprs[1], exprs[2])) {
741 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
742 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
743 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
746 if (!(out = fold_op(parser->fold, op, exprs)))
747 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
750 case opid2('*', '*'):
751 if (NotSameType(TYPE_FLOAT)) {
752 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
753 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
754 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
759 if (!(out = fold_op(parser->fold, op, exprs))) {
760 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
761 vec_push(gencall->params, exprs[0]);
762 vec_push(gencall->params, exprs[1]);
763 out = (ast_expression*)gencall;
767 case opid2('>', '<'):
768 if (NotSameType(TYPE_VECTOR)) {
769 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
770 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
771 compile_error(ctx, "invalid types used in cross product: %s and %s",
776 if (!(out = fold_op(parser->fold, op, exprs))) {
777 out = (ast_expression*)ast_binary_new(
787 case opid3('<','=','>'): /* -1, 0, or 1 */
788 if (NotSameType(TYPE_FLOAT)) {
789 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
790 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
791 compile_error(ctx, "invalid types used in comparision: %s and %s",
797 if (!(out = fold_op(parser->fold, op, exprs))) {
798 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
800 eq->refs = AST_REF_NONE;
803 out = (ast_expression*)ast_ternary_new(ctx,
804 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
806 (ast_expression*)parser->fold->imm_float[2],
809 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
811 (ast_expression*)parser->fold->imm_float[0],
814 (ast_expression*)parser->fold->imm_float[1]
824 generated_op += 1; /* INSTR_GT */
826 generated_op += 1; /* INSTR_LT */
827 case opid2('>', '='):
828 generated_op += 1; /* INSTR_GE */
829 case opid2('<', '='):
830 generated_op += INSTR_LE;
831 if (NotSameType(TYPE_FLOAT)) {
832 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
833 type_name[exprs[0]->vtype],
834 type_name[exprs[1]->vtype]);
837 if (!(out = fold_op(parser->fold, op, exprs)))
838 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
840 case opid2('!', '='):
841 if (exprs[0]->vtype != exprs[1]->vtype) {
842 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
843 type_name[exprs[0]->vtype],
844 type_name[exprs[1]->vtype]);
847 if (!(out = fold_op(parser->fold, op, exprs)))
848 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
850 case opid2('=', '='):
851 if (exprs[0]->vtype != exprs[1]->vtype) {
852 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
853 type_name[exprs[0]->vtype],
854 type_name[exprs[1]->vtype]);
857 if (!(out = fold_op(parser->fold, op, exprs)))
858 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
862 if (ast_istype(exprs[0], ast_entfield)) {
863 ast_expression *field = ((ast_entfield*)exprs[0])->field;
864 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
865 exprs[0]->vtype == TYPE_FIELD &&
866 exprs[0]->next->vtype == TYPE_VECTOR)
868 assignop = type_storep_instr[TYPE_VECTOR];
871 assignop = type_storep_instr[exprs[0]->vtype];
872 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
874 ast_type_to_string(field->next, ty1, sizeof(ty1));
875 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
876 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
877 field->next->vtype == TYPE_FUNCTION &&
878 exprs[1]->vtype == TYPE_FUNCTION)
880 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
881 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
884 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
889 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
890 exprs[0]->vtype == TYPE_FIELD &&
891 exprs[0]->next->vtype == TYPE_VECTOR)
893 assignop = type_store_instr[TYPE_VECTOR];
896 assignop = type_store_instr[exprs[0]->vtype];
899 if (assignop == VINSTR_END) {
900 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
901 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
902 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
904 else if (!ast_compare_type(exprs[0], exprs[1]))
906 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
907 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
908 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
909 exprs[0]->vtype == TYPE_FUNCTION &&
910 exprs[1]->vtype == TYPE_FUNCTION)
912 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
913 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
916 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
919 (void)check_write_to(ctx, exprs[0]);
920 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
922 case opid3('+','+','P'):
923 case opid3('-','-','P'):
925 if (exprs[0]->vtype != TYPE_FLOAT) {
926 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
927 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
930 if (op->id == opid3('+','+','P'))
934 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
935 if (ast_istype(exprs[0], ast_entfield)) {
936 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
938 (ast_expression*)parser->fold->imm_float[1]);
940 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
942 (ast_expression*)parser->fold->imm_float[1]);
945 case opid3('S','+','+'):
946 case opid3('S','-','-'):
948 if (exprs[0]->vtype != TYPE_FLOAT) {
949 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
950 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
953 if (op->id == opid3('S','+','+')) {
960 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
961 if (ast_istype(exprs[0], ast_entfield)) {
962 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
964 (ast_expression*)parser->fold->imm_float[1]);
966 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
968 (ast_expression*)parser->fold->imm_float[1]);
972 out = (ast_expression*)ast_binary_new(ctx, subop,
974 (ast_expression*)parser->fold->imm_float[1]);
979 if (exprs[0]->vtype != exprs[1]->vtype ||
980 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
982 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
983 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
984 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
988 (void)check_write_to(ctx, exprs[0]);
989 if (ast_istype(exprs[0], ast_entfield))
990 assignop = type_storep_instr[exprs[0]->vtype];
992 assignop = type_store_instr[exprs[0]->vtype];
993 switch (exprs[0]->vtype) {
995 out = (ast_expression*)ast_binstore_new(ctx, assignop,
996 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1000 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1001 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1002 exprs[0], exprs[1]);
1005 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1006 type_name[exprs[0]->vtype],
1007 type_name[exprs[1]->vtype]);
1011 case opid2('*','='):
1012 case opid2('/','='):
1013 if (exprs[1]->vtype != TYPE_FLOAT ||
1014 !(exprs[0]->vtype == TYPE_FLOAT ||
1015 exprs[0]->vtype == TYPE_VECTOR))
1017 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1018 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1019 compile_error(ctx, "invalid types used in expression: %s and %s",
1023 (void)check_write_to(ctx, exprs[0]);
1024 if (ast_istype(exprs[0], ast_entfield))
1025 assignop = type_storep_instr[exprs[0]->vtype];
1027 assignop = type_store_instr[exprs[0]->vtype];
1028 switch (exprs[0]->vtype) {
1030 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1031 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1032 exprs[0], exprs[1]);
1035 if (op->id == opid2('*','=')) {
1036 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1037 exprs[0], exprs[1]);
1039 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1040 (ast_expression*)parser->fold->imm_float[1],
1043 compile_error(ctx, "internal error: failed to generate division");
1046 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1051 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1052 type_name[exprs[0]->vtype],
1053 type_name[exprs[1]->vtype]);
1057 case opid2('&','='):
1058 case opid2('|','='):
1059 case opid2('^','='):
1060 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1061 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1062 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1063 compile_error(ctx, "invalid types used in expression: %s and %s",
1067 (void)check_write_to(ctx, exprs[0]);
1068 if (ast_istype(exprs[0], ast_entfield))
1069 assignop = type_storep_instr[exprs[0]->vtype];
1071 assignop = type_store_instr[exprs[0]->vtype];
1072 if (exprs[0]->vtype == TYPE_FLOAT)
1073 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1074 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1075 exprs[0], exprs[1]);
1077 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1078 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1079 exprs[0], exprs[1]);
1081 case opid3('&','~','='):
1082 /* This is like: a &= ~(b);
1083 * But QC has no bitwise-not, so we implement it as
1086 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1087 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1088 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1089 compile_error(ctx, "invalid types used in expression: %s and %s",
1093 if (ast_istype(exprs[0], ast_entfield))
1094 assignop = type_storep_instr[exprs[0]->vtype];
1096 assignop = type_store_instr[exprs[0]->vtype];
1097 if (exprs[0]->vtype == TYPE_FLOAT)
1098 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1100 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1103 (void)check_write_to(ctx, exprs[0]);
1104 if (exprs[0]->vtype == TYPE_FLOAT)
1105 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1107 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1108 asbinstore->keep_dest = true;
1109 out = (ast_expression*)asbinstore;
1112 case opid2('~', 'P'):
1113 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1114 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1115 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1118 if (!(out = fold_op(parser->fold, op, exprs))) {
1119 if (exprs[0]->vtype == TYPE_FLOAT) {
1120 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1122 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1129 compile_error(ctx, "failed to apply operator %s", op->op);
1133 vec_push(sy->out, syexp(ctx, out));
1137 static bool parser_close_call(parser_t *parser, shunt *sy)
1139 /* was a function call */
1140 ast_expression *fun;
1141 ast_value *funval = NULL;
1145 size_t paramcount, i;
1148 fid = vec_last(sy->ops).off;
1149 vec_shrinkby(sy->ops, 1);
1151 /* out[fid] is the function
1152 * everything above is parameters...
1154 if (!vec_size(sy->argc)) {
1155 parseerror(parser, "internal error: no argument counter available");
1159 paramcount = vec_last(sy->argc);
1162 if (vec_size(sy->out) < fid) {
1163 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1164 (unsigned long)vec_size(sy->out),
1166 (unsigned long)paramcount);
1171 * TODO handle this at the intrinsic level with an ast_intrinsic
1174 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1176 if (fid+2 != vec_size(sy->out) ||
1177 vec_last(sy->out).block)
1179 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1182 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1183 ast_unref(vec_last(sy->out).out);
1184 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1185 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1186 vec_shrinkby(sy->out, 1);
1191 * Now we need to determine if the function that is being called is
1192 * an intrinsic so we can evaluate if the arguments to it are constant
1193 * and than fruitfully fold them.
1195 #define fold_can_1(X) \
1196 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1197 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1199 if (fid + 1 < vec_size(sy->out))
1202 for (i = 0; i < paramcount; ++i) {
1203 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1210 * All is well which ends well, if we make it into here we can ignore the
1211 * intrinsic call and just evaluate it i.e constant fold it.
1213 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1214 ast_expression **exprs = NULL;
1215 ast_expression *foldval = NULL;
1217 for (i = 0; i < paramcount; i++)
1218 vec_push(exprs, sy->out[fid+1 + i].out);
1220 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1226 * Blub: what sorts of unreffing and resizing of
1227 * sy->out should I be doing here?
1229 sy->out[fid] = syexp(foldval->node.context, foldval);
1230 vec_shrinkby(sy->out, paramcount);
1237 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1242 if (fid+1 + paramcount != vec_size(sy->out)) {
1243 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1244 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1248 for (i = 0; i < paramcount; ++i)
1249 vec_push(call->params, sy->out[fid+1 + i].out);
1250 vec_shrinkby(sy->out, paramcount);
1251 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1252 if (parser->max_param_count < paramcount)
1253 parser->max_param_count = paramcount;
1255 if (ast_istype(fun, ast_value)) {
1256 funval = (ast_value*)fun;
1257 if ((fun->flags & AST_FLAG_VARIADIC) &&
1258 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1260 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1264 /* overwrite fid, the function, with a call */
1265 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1267 if (fun->vtype != TYPE_FUNCTION) {
1268 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1273 parseerror(parser, "could not determine function return type");
1276 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1278 if (fun->flags & AST_FLAG_DEPRECATED) {
1280 return !parsewarning(parser, WARN_DEPRECATED,
1281 "call to function (which is marked deprecated)\n",
1282 "-> it has been declared here: %s:%i",
1283 ast_ctx(fun).file, ast_ctx(fun).line);
1286 return !parsewarning(parser, WARN_DEPRECATED,
1287 "call to `%s` (which is marked deprecated)\n"
1288 "-> `%s` declared here: %s:%i",
1289 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1291 return !parsewarning(parser, WARN_DEPRECATED,
1292 "call to `%s` (deprecated: %s)\n"
1293 "-> `%s` declared here: %s:%i",
1294 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1298 if (vec_size(fun->params) != paramcount &&
1299 !((fun->flags & AST_FLAG_VARIADIC) &&
1300 vec_size(fun->params) < paramcount))
1302 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1304 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1305 "too %s parameters for call to %s: expected %i, got %i\n"
1306 " -> `%s` has been declared here: %s:%i",
1307 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1308 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1310 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1311 "too %s parameters for function call: expected %i, got %i\n"
1312 " -> it has been declared here: %s:%i",
1313 fewmany, (int)vec_size(fun->params), (int)paramcount,
1314 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1321 static bool parser_close_paren(parser_t *parser, shunt *sy)
1323 if (!vec_size(sy->ops)) {
1324 parseerror(parser, "unmatched closing paren");
1328 while (vec_size(sy->ops)) {
1329 if (vec_last(sy->ops).isparen) {
1330 if (vec_last(sy->paren) == PAREN_FUNC) {
1332 if (!parser_close_call(parser, sy))
1336 if (vec_last(sy->paren) == PAREN_EXPR) {
1338 if (!vec_size(sy->out)) {
1339 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1340 vec_shrinkby(sy->ops, 1);
1343 vec_shrinkby(sy->ops, 1);
1346 if (vec_last(sy->paren) == PAREN_INDEX) {
1348 /* pop off the parenthesis */
1349 vec_shrinkby(sy->ops, 1);
1350 /* then apply the index operator */
1351 if (!parser_sy_apply_operator(parser, sy))
1355 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1356 vec_last(sy->paren) = PAREN_TERNARY2;
1357 /* pop off the parenthesis */
1358 vec_shrinkby(sy->ops, 1);
1361 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1364 if (!parser_sy_apply_operator(parser, sy))
1370 static void parser_reclassify_token(parser_t *parser)
1373 if (parser->tok >= TOKEN_START)
1375 for (i = 0; i < operator_count; ++i) {
1376 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1377 parser->tok = TOKEN_OPERATOR;
1383 static ast_expression* parse_vararg_do(parser_t *parser)
1385 ast_expression *idx, *out;
1387 ast_value *funtype = parser->function->vtype;
1388 lex_ctx_t ctx = parser_ctx(parser);
1390 if (!parser->function->varargs) {
1391 parseerror(parser, "function has no variable argument list");
1395 if (!parser_next(parser) || parser->tok != '(') {
1396 parseerror(parser, "expected parameter index and type in parenthesis");
1399 if (!parser_next(parser)) {
1400 parseerror(parser, "error parsing parameter index");
1404 idx = parse_expression_leave(parser, true, false, false);
1408 if (parser->tok != ',') {
1409 if (parser->tok != ')') {
1411 parseerror(parser, "expected comma after parameter index");
1414 /* vararg piping: ...(start) */
1415 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1419 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1421 parseerror(parser, "expected typename for vararg");
1425 typevar = parse_typename(parser, NULL, NULL);
1431 if (parser->tok != ')') {
1433 ast_delete(typevar);
1434 parseerror(parser, "expected closing paren");
1438 if (funtype->expression.varparam &&
1439 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1443 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1444 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1445 compile_error(ast_ctx(typevar),
1446 "function was declared to take varargs of type `%s`, requested type is: %s",
1450 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1451 ast_type_adopt(out, typevar);
1452 ast_delete(typevar);
1456 static ast_expression* parse_vararg(parser_t *parser)
1458 bool old_noops = parser->lex->flags.noops;
1460 ast_expression *out;
1462 parser->lex->flags.noops = true;
1463 out = parse_vararg_do(parser);
1465 parser->lex->flags.noops = old_noops;
1469 /* not to be exposed */
1470 bool ftepp_predef_exists(const char *name);
1471 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1473 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1474 parser->tok == TOKEN_IDENT &&
1475 !strcmp(parser_tokval(parser), "_"))
1477 /* a translatable string */
1480 parser->lex->flags.noops = true;
1481 if (!parser_next(parser) || parser->tok != '(') {
1482 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1485 parser->lex->flags.noops = false;
1486 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1487 parseerror(parser, "expected a constant string in translatable-string extension");
1490 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1493 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1495 if (!parser_next(parser) || parser->tok != ')') {
1496 parseerror(parser, "expected closing paren after translatable string");
1501 else if (parser->tok == TOKEN_DOTS)
1504 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1505 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1508 va = parse_vararg(parser);
1511 vec_push(sy->out, syexp(parser_ctx(parser), va));
1514 else if (parser->tok == TOKEN_FLOATCONST) {
1515 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1518 vec_push(sy->out, syexp(parser_ctx(parser), val));
1521 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1522 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1525 vec_push(sy->out, syexp(parser_ctx(parser), val));
1528 else if (parser->tok == TOKEN_STRINGCONST) {
1529 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1532 vec_push(sy->out, syexp(parser_ctx(parser), val));
1535 else if (parser->tok == TOKEN_VECTORCONST) {
1536 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1539 vec_push(sy->out, syexp(parser_ctx(parser), val));
1542 else if (parser->tok == TOKEN_IDENT)
1544 const char *ctoken = parser_tokval(parser);
1545 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1546 ast_expression *var;
1547 /* a_vector.{x,y,z} */
1548 if (!vec_size(sy->ops) ||
1549 !vec_last(sy->ops).etype ||
1550 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1552 /* When adding more intrinsics, fix the above condition */
1555 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1557 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1559 var = parser_find_var(parser, parser_tokval(parser));
1561 var = parser_find_field(parser, parser_tokval(parser));
1563 if (!var && with_labels) {
1564 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1566 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1567 var = (ast_expression*)lbl;
1568 vec_push(parser->labels, lbl);
1571 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1572 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1575 * now we try for the real intrinsic hashtable. If the string
1576 * begins with __builtin, we simply skip past it, otherwise we
1577 * use the identifier as is.
1579 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1580 var = intrin_func(parser->intrin, parser_tokval(parser));
1584 char *correct = NULL;
1588 * sometimes people use preprocessing predefs without enabling them
1589 * i've done this thousands of times already myself. Lets check for
1590 * it in the predef table. And diagnose it better :)
1592 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1593 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1598 * TODO: determine the best score for the identifier: be it
1599 * a variable, a field.
1601 * We should also consider adding correction tables for
1602 * other things as well.
1604 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1606 correct_init(&corr);
1608 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1609 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1610 if (strcmp(correct, parser_tokval(parser))) {
1617 correct_free(&corr);
1620 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1625 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1631 if (ast_istype(var, ast_value)) {
1632 ((ast_value*)var)->uses++;
1634 else if (ast_istype(var, ast_member)) {
1635 ast_member *mem = (ast_member*)var;
1636 if (ast_istype(mem->owner, ast_value))
1637 ((ast_value*)(mem->owner))->uses++;
1640 vec_push(sy->out, syexp(parser_ctx(parser), var));
1643 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1647 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1649 ast_expression *expr = NULL;
1652 bool wantop = false;
1653 /* only warn once about an assignment in a truth value because the current code
1654 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1656 bool warn_parenthesis = true;
1658 /* count the parens because an if starts with one, so the
1659 * end of a condition is an unmatched closing paren
1663 memset(&sy, 0, sizeof(sy));
1665 parser->lex->flags.noops = false;
1667 parser_reclassify_token(parser);
1671 if (parser->tok == TOKEN_TYPENAME) {
1672 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1676 if (parser->tok == TOKEN_OPERATOR)
1678 /* classify the operator */
1679 const oper_info *op;
1680 const oper_info *olast = NULL;
1682 for (o = 0; o < operator_count; ++o) {
1683 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1684 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1685 !strcmp(parser_tokval(parser), operators[o].op))
1690 if (o == operator_count) {
1691 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1694 /* found an operator */
1697 /* when declaring variables, a comma starts a new variable */
1698 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1699 /* fixup the token */
1704 /* a colon without a pervious question mark cannot be a ternary */
1705 if (!ternaries && op->id == opid2(':','?')) {
1710 if (op->id == opid1(',')) {
1711 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1712 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1716 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1717 olast = &operators[vec_last(sy.ops).etype-1];
1719 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1720 while (olast && op->prec < olast->prec)
1722 if (!parser_sy_apply_operator(parser, &sy))
1724 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1725 olast = &operators[vec_last(sy.ops).etype-1];
1730 #define IsAssignOp(x) (\
1731 (x) == opid1('=') || \
1732 (x) == opid2('+','=') || \
1733 (x) == opid2('-','=') || \
1734 (x) == opid2('*','=') || \
1735 (x) == opid2('/','=') || \
1736 (x) == opid2('%','=') || \
1737 (x) == opid2('&','=') || \
1738 (x) == opid2('|','=') || \
1739 (x) == opid3('&','~','=') \
1741 if (warn_parenthesis) {
1742 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1743 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1744 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1747 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1748 warn_parenthesis = false;
1751 if (olast && olast->id != op->id) {
1752 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1753 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1755 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1756 warn_parenthesis = false;
1758 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1759 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1761 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1762 warn_parenthesis = false;
1768 (op->prec < olast->prec) ||
1769 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1771 if (!parser_sy_apply_operator(parser, &sy))
1773 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1774 olast = &operators[vec_last(sy.ops).etype-1];
1779 if (op->id == opid1('(')) {
1781 size_t sycount = vec_size(sy.out);
1782 /* we expected an operator, this is the function-call operator */
1783 vec_push(sy.paren, PAREN_FUNC);
1784 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1785 vec_push(sy.argc, 0);
1787 vec_push(sy.paren, PAREN_EXPR);
1788 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1791 } else if (op->id == opid1('[')) {
1793 parseerror(parser, "unexpected array subscript");
1796 vec_push(sy.paren, PAREN_INDEX);
1797 /* push both the operator and the paren, this makes life easier */
1798 vec_push(sy.ops, syop(parser_ctx(parser), op));
1799 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1801 } else if (op->id == opid2('?',':')) {
1802 vec_push(sy.ops, syop(parser_ctx(parser), op));
1803 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1806 vec_push(sy.paren, PAREN_TERNARY1);
1807 } else if (op->id == opid2(':','?')) {
1808 if (!vec_size(sy.paren)) {
1809 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1812 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1813 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1816 if (!parser_close_paren(parser, &sy))
1818 vec_push(sy.ops, syop(parser_ctx(parser), op));
1822 vec_push(sy.ops, syop(parser_ctx(parser), op));
1823 wantop = !!(op->flags & OP_SUFFIX);
1826 else if (parser->tok == ')') {
1827 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1828 if (!parser_sy_apply_operator(parser, &sy))
1831 if (!vec_size(sy.paren))
1834 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1835 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1838 if (!parser_close_paren(parser, &sy))
1841 /* must be a function call without parameters */
1842 if (vec_last(sy.paren) != PAREN_FUNC) {
1843 parseerror(parser, "closing paren in invalid position");
1846 if (!parser_close_paren(parser, &sy))
1851 else if (parser->tok == '(') {
1852 parseerror(parser, "internal error: '(' should be classified as operator");
1855 else if (parser->tok == '[') {
1856 parseerror(parser, "internal error: '[' should be classified as operator");
1859 else if (parser->tok == ']') {
1860 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1861 if (!parser_sy_apply_operator(parser, &sy))
1864 if (!vec_size(sy.paren))
1866 if (vec_last(sy.paren) != PAREN_INDEX) {
1867 parseerror(parser, "mismatched parentheses, unexpected ']'");
1870 if (!parser_close_paren(parser, &sy))
1875 if (!parse_sya_operand(parser, &sy, with_labels))
1878 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1879 vec_last(sy.argc)++;
1884 /* in this case we might want to allow constant string concatenation */
1885 bool concatenated = false;
1886 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1887 ast_expression *lexpr = vec_last(sy.out).out;
1888 if (ast_istype(lexpr, ast_value)) {
1889 ast_value *last = (ast_value*)lexpr;
1890 if (last->isimm == true && last->cvq == CV_CONST &&
1891 last->hasvalue && last->expression.vtype == TYPE_STRING)
1893 char *newstr = NULL;
1894 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1895 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1897 concatenated = true;
1901 if (!concatenated) {
1902 parseerror(parser, "expected operator or end of statement");
1907 if (!parser_next(parser)) {
1910 if (parser->tok == ';' ||
1911 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1912 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1918 while (vec_size(sy.ops)) {
1919 if (!parser_sy_apply_operator(parser, &sy))
1923 parser->lex->flags.noops = true;
1924 if (vec_size(sy.out) != 1) {
1925 parseerror(parser, "expression expected");
1928 expr = sy.out[0].out;
1931 if (vec_size(sy.paren)) {
1932 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1940 parser->lex->flags.noops = true;
1941 for (i = 0; i < vec_size(sy.out); ++i) {
1943 ast_unref(sy.out[i].out);
1952 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1954 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1957 if (parser->tok != ';') {
1958 parseerror(parser, "semicolon expected after expression");
1962 if (!parser_next(parser)) {
1969 static void parser_enterblock(parser_t *parser)
1971 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1972 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1973 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1974 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1975 vec_push(parser->_block_ctx, parser_ctx(parser));
1978 vec_push(parser->correct_variables, correct_trie_new());
1979 vec_push(parser->correct_variables_score, NULL);
1982 static bool parser_leaveblock(parser_t *parser)
1985 size_t locals, typedefs;
1987 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1988 parseerror(parser, "internal error: parser_leaveblock with no block");
1992 util_htdel(vec_last(parser->variables));
1993 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1995 vec_pop(parser->variables);
1996 vec_pop(parser->correct_variables);
1997 vec_pop(parser->correct_variables_score);
1998 if (!vec_size(parser->_blocklocals)) {
1999 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2003 locals = vec_last(parser->_blocklocals);
2004 vec_pop(parser->_blocklocals);
2005 while (vec_size(parser->_locals) != locals) {
2006 ast_expression *e = vec_last(parser->_locals);
2007 ast_value *v = (ast_value*)e;
2008 vec_pop(parser->_locals);
2009 if (ast_istype(e, ast_value) && !v->uses) {
2010 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2015 typedefs = vec_last(parser->_blocktypedefs);
2016 while (vec_size(parser->_typedefs) != typedefs) {
2017 ast_delete(vec_last(parser->_typedefs));
2018 vec_pop(parser->_typedefs);
2020 util_htdel(vec_last(parser->typedefs));
2021 vec_pop(parser->typedefs);
2023 vec_pop(parser->_block_ctx);
2028 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2030 vec_push(parser->_locals, e);
2031 util_htset(vec_last(parser->variables), name, (void*)e);
2035 vec_last(parser->correct_variables),
2036 &vec_last(parser->correct_variables_score),
2041 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2043 vec_push(parser->globals, e);
2044 util_htset(parser->htglobals, name, e);
2048 parser->correct_variables[0],
2049 &parser->correct_variables_score[0],
2054 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2058 ast_expression *prev;
2060 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2062 ast_type_to_string(cond, ty, sizeof(ty));
2063 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2066 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2069 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2072 parseerror(parser, "internal error: failed to process condition");
2077 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2079 /* vector types need to be cast to true booleans */
2080 ast_binary *bin = (ast_binary*)cond;
2081 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2083 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2085 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2088 parseerror(parser, "internal error: failed to process condition");
2095 unary = (ast_unary*)cond;
2096 /* ast_istype dereferences cond, should test here for safety */
2097 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2099 cond = unary->operand;
2100 unary->operand = NULL;
2103 unary = (ast_unary*)cond;
2107 parseerror(parser, "internal error: failed to process condition");
2109 if (ifnot) *_ifnot = !*_ifnot;
2113 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2116 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2119 lex_ctx_t ctx = parser_ctx(parser);
2121 (void)block; /* not touching */
2123 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2124 if (!parser_next(parser)) {
2125 parseerror(parser, "expected condition or 'not'");
2128 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2130 if (!parser_next(parser)) {
2131 parseerror(parser, "expected condition in parenthesis");
2135 if (parser->tok != '(') {
2136 parseerror(parser, "expected 'if' condition in parenthesis");
2139 /* parse into the expression */
2140 if (!parser_next(parser)) {
2141 parseerror(parser, "expected 'if' condition after opening paren");
2144 /* parse the condition */
2145 cond = parse_expression_leave(parser, false, true, false);
2149 if (parser->tok != ')') {
2150 parseerror(parser, "expected closing paren after 'if' condition");
2154 /* parse into the 'then' branch */
2155 if (!parser_next(parser)) {
2156 parseerror(parser, "expected statement for on-true branch of 'if'");
2160 if (!parse_statement_or_block(parser, &ontrue)) {
2165 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2166 /* check for an else */
2167 if (!strcmp(parser_tokval(parser), "else")) {
2168 /* parse into the 'else' branch */
2169 if (!parser_next(parser)) {
2170 parseerror(parser, "expected on-false branch after 'else'");
2175 if (!parse_statement_or_block(parser, &onfalse)) {
2182 cond = process_condition(parser, cond, &ifnot);
2184 if (ontrue) ast_delete(ontrue);
2185 if (onfalse) ast_delete(onfalse);
2190 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2192 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2193 *out = (ast_expression*)ifthen;
2197 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2198 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2203 /* skip the 'while' and get the body */
2204 if (!parser_next(parser)) {
2205 if (OPTS_FLAG(LOOP_LABELS))
2206 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2208 parseerror(parser, "expected 'while' condition in parenthesis");
2212 if (parser->tok == ':') {
2213 if (!OPTS_FLAG(LOOP_LABELS))
2214 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2215 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2216 parseerror(parser, "expected loop label");
2219 label = util_strdup(parser_tokval(parser));
2220 if (!parser_next(parser)) {
2222 parseerror(parser, "expected 'while' condition in parenthesis");
2227 if (parser->tok != '(') {
2228 parseerror(parser, "expected 'while' condition in parenthesis");
2232 vec_push(parser->breaks, label);
2233 vec_push(parser->continues, label);
2235 rv = parse_while_go(parser, block, out);
2238 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2239 parseerror(parser, "internal error: label stack corrupted");
2245 vec_pop(parser->breaks);
2246 vec_pop(parser->continues);
2251 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2254 ast_expression *cond, *ontrue;
2258 lex_ctx_t ctx = parser_ctx(parser);
2260 (void)block; /* not touching */
2262 /* parse into the expression */
2263 if (!parser_next(parser)) {
2264 parseerror(parser, "expected 'while' condition after opening paren");
2267 /* parse the condition */
2268 cond = parse_expression_leave(parser, false, true, false);
2272 if (parser->tok != ')') {
2273 parseerror(parser, "expected closing paren after 'while' condition");
2277 /* parse into the 'then' branch */
2278 if (!parser_next(parser)) {
2279 parseerror(parser, "expected while-loop body");
2283 if (!parse_statement_or_block(parser, &ontrue)) {
2288 cond = process_condition(parser, cond, &ifnot);
2293 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2294 *out = (ast_expression*)aloop;
2298 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2299 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2304 /* skip the 'do' and get the body */
2305 if (!parser_next(parser)) {
2306 if (OPTS_FLAG(LOOP_LABELS))
2307 parseerror(parser, "expected loop label or body");
2309 parseerror(parser, "expected loop body");
2313 if (parser->tok == ':') {
2314 if (!OPTS_FLAG(LOOP_LABELS))
2315 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2316 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2317 parseerror(parser, "expected loop label");
2320 label = util_strdup(parser_tokval(parser));
2321 if (!parser_next(parser)) {
2323 parseerror(parser, "expected loop body");
2328 vec_push(parser->breaks, label);
2329 vec_push(parser->continues, label);
2331 rv = parse_dowhile_go(parser, block, out);
2334 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2335 parseerror(parser, "internal error: label stack corrupted");
2338 * Test for NULL otherwise ast_delete dereferences null pointer
2346 vec_pop(parser->breaks);
2347 vec_pop(parser->continues);
2352 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2355 ast_expression *cond, *ontrue;
2359 lex_ctx_t ctx = parser_ctx(parser);
2361 (void)block; /* not touching */
2363 if (!parse_statement_or_block(parser, &ontrue))
2366 /* expect the "while" */
2367 if (parser->tok != TOKEN_KEYWORD ||
2368 strcmp(parser_tokval(parser), "while"))
2370 parseerror(parser, "expected 'while' and condition");
2375 /* skip the 'while' and check for opening paren */
2376 if (!parser_next(parser) || parser->tok != '(') {
2377 parseerror(parser, "expected 'while' condition in parenthesis");
2381 /* parse into the expression */
2382 if (!parser_next(parser)) {
2383 parseerror(parser, "expected 'while' condition after opening paren");
2387 /* parse the condition */
2388 cond = parse_expression_leave(parser, false, true, false);
2392 if (parser->tok != ')') {
2393 parseerror(parser, "expected closing paren after 'while' condition");
2399 if (!parser_next(parser) || parser->tok != ';') {
2400 parseerror(parser, "expected semicolon after condition");
2406 if (!parser_next(parser)) {
2407 parseerror(parser, "parse error");
2413 cond = process_condition(parser, cond, &ifnot);
2418 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2419 *out = (ast_expression*)aloop;
2423 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2424 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2429 /* skip the 'for' and check for opening paren */
2430 if (!parser_next(parser)) {
2431 if (OPTS_FLAG(LOOP_LABELS))
2432 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2434 parseerror(parser, "expected 'for' expressions in parenthesis");
2438 if (parser->tok == ':') {
2439 if (!OPTS_FLAG(LOOP_LABELS))
2440 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2441 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2442 parseerror(parser, "expected loop label");
2445 label = util_strdup(parser_tokval(parser));
2446 if (!parser_next(parser)) {
2448 parseerror(parser, "expected 'for' expressions in parenthesis");
2453 if (parser->tok != '(') {
2454 parseerror(parser, "expected 'for' expressions in parenthesis");
2458 vec_push(parser->breaks, label);
2459 vec_push(parser->continues, label);
2461 rv = parse_for_go(parser, block, out);
2464 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2465 parseerror(parser, "internal error: label stack corrupted");
2471 vec_pop(parser->breaks);
2472 vec_pop(parser->continues);
2476 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2479 ast_expression *initexpr, *cond, *increment, *ontrue;
2484 lex_ctx_t ctx = parser_ctx(parser);
2486 parser_enterblock(parser);
2493 /* parse into the expression */
2494 if (!parser_next(parser)) {
2495 parseerror(parser, "expected 'for' initializer after opening paren");
2500 if (parser->tok == TOKEN_IDENT)
2501 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2503 if (typevar || parser->tok == TOKEN_TYPENAME) {
2505 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2506 if (parsewarning(parser, WARN_EXTENSIONS,
2507 "current standard does not allow variable declarations in for-loop initializers"))
2511 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2514 else if (parser->tok != ';')
2516 initexpr = parse_expression_leave(parser, false, false, false);
2521 /* move on to condition */
2522 if (parser->tok != ';') {
2523 parseerror(parser, "expected semicolon after for-loop initializer");
2526 if (!parser_next(parser)) {
2527 parseerror(parser, "expected for-loop condition");
2531 /* parse the condition */
2532 if (parser->tok != ';') {
2533 cond = parse_expression_leave(parser, false, true, false);
2538 /* move on to incrementor */
2539 if (parser->tok != ';') {
2540 parseerror(parser, "expected semicolon after for-loop initializer");
2543 if (!parser_next(parser)) {
2544 parseerror(parser, "expected for-loop condition");
2548 /* parse the incrementor */
2549 if (parser->tok != ')') {
2550 lex_ctx_t condctx = parser_ctx(parser);
2551 increment = parse_expression_leave(parser, false, false, false);
2554 if (!ast_side_effects(increment)) {
2555 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2561 if (parser->tok != ')') {
2562 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2565 /* parse into the 'then' branch */
2566 if (!parser_next(parser)) {
2567 parseerror(parser, "expected for-loop body");
2570 if (!parse_statement_or_block(parser, &ontrue))
2574 cond = process_condition(parser, cond, &ifnot);
2578 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2579 *out = (ast_expression*)aloop;
2581 if (!parser_leaveblock(parser)) {
2587 if (initexpr) ast_unref(initexpr);
2588 if (cond) ast_unref(cond);
2589 if (increment) ast_unref(increment);
2590 (void)!parser_leaveblock(parser);
2594 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2596 ast_expression *exp = NULL;
2597 ast_expression *var = NULL;
2598 ast_return *ret = NULL;
2599 ast_value *retval = parser->function->return_value;
2600 ast_value *expected = parser->function->vtype;
2602 lex_ctx_t ctx = parser_ctx(parser);
2604 (void)block; /* not touching */
2606 if (!parser_next(parser)) {
2607 parseerror(parser, "expected return expression");
2611 /* return assignments */
2612 if (parser->tok == '=') {
2613 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2614 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2618 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2620 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2621 parseerror(parser, "invalid return type: `%s'", ty1);
2625 if (!parser_next(parser)) {
2626 parseerror(parser, "expected return assignment expression");
2630 if (!(exp = parse_expression_leave(parser, false, false, false)))
2633 /* prepare the return value */
2635 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2636 ast_type_adopt(retval, expected->expression.next);
2637 parser->function->return_value = retval;
2640 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2641 char ty1[1024], ty2[1024];
2642 ast_type_to_string(exp, ty1, sizeof(ty1));
2643 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2644 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2647 /* store to 'return' local variable */
2648 var = (ast_expression*)ast_store_new(
2650 type_store_instr[expected->expression.next->vtype],
2651 (ast_expression*)retval, exp);
2658 if (parser->tok != ';')
2659 parseerror(parser, "missing semicolon after return assignment");
2660 else if (!parser_next(parser))
2661 parseerror(parser, "parse error after return assignment");
2667 if (parser->tok != ';') {
2668 exp = parse_expression(parser, false, false);
2672 if (exp->vtype != TYPE_NIL &&
2673 exp->vtype != ((ast_expression*)expected)->next->vtype)
2675 parseerror(parser, "return with invalid expression");
2678 ret = ast_return_new(ctx, exp);
2684 if (!parser_next(parser))
2685 parseerror(parser, "parse error");
2687 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2689 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2691 ret = ast_return_new(ctx, (ast_expression*)retval);
2693 *out = (ast_expression*)ret;
2697 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2700 unsigned int levels = 0;
2701 lex_ctx_t ctx = parser_ctx(parser);
2702 const char **loops = (is_continue ? parser->continues : parser->breaks);
2704 (void)block; /* not touching */
2705 if (!parser_next(parser)) {
2706 parseerror(parser, "expected semicolon or loop label");
2710 if (!vec_size(loops)) {
2712 parseerror(parser, "`continue` can only be used inside loops");
2714 parseerror(parser, "`break` can only be used inside loops or switches");
2717 if (parser->tok == TOKEN_IDENT) {
2718 if (!OPTS_FLAG(LOOP_LABELS))
2719 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2720 i = vec_size(loops);
2722 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2725 parseerror(parser, "no such loop to %s: `%s`",
2726 (is_continue ? "continue" : "break out of"),
2727 parser_tokval(parser));
2732 if (!parser_next(parser)) {
2733 parseerror(parser, "expected semicolon");
2738 if (parser->tok != ';') {
2739 parseerror(parser, "expected semicolon");
2743 if (!parser_next(parser))
2744 parseerror(parser, "parse error");
2746 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2750 /* returns true when it was a variable qualifier, false otherwise!
2751 * on error, cvq is set to CV_WRONG
2753 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2755 bool had_const = false;
2756 bool had_var = false;
2757 bool had_noref = false;
2758 bool had_attrib = false;
2759 bool had_static = false;
2764 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2766 /* parse an attribute */
2767 if (!parser_next(parser)) {
2768 parseerror(parser, "expected attribute after `[[`");
2772 if (!strcmp(parser_tokval(parser), "noreturn")) {
2773 flags |= AST_FLAG_NORETURN;
2774 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2775 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2780 else if (!strcmp(parser_tokval(parser), "noref")) {
2782 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2783 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2788 else if (!strcmp(parser_tokval(parser), "inline")) {
2789 flags |= AST_FLAG_INLINE;
2790 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2791 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2796 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2797 flags |= AST_FLAG_ERASEABLE;
2798 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2799 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2804 else if (!strcmp(parser_tokval(parser), "accumulate")) {
2805 flags |= AST_FLAG_ACCUMULATE;
2806 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2807 parseerror(parser, "`accumulate` attribute has no parameters, expected `]]`");
2812 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2813 flags |= AST_FLAG_ALIAS;
2816 if (!parser_next(parser)) {
2817 parseerror(parser, "parse error in attribute");
2821 if (parser->tok == '(') {
2822 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2823 parseerror(parser, "`alias` attribute missing parameter");
2827 *message = util_strdup(parser_tokval(parser));
2829 if (!parser_next(parser)) {
2830 parseerror(parser, "parse error in attribute");
2834 if (parser->tok != ')') {
2835 parseerror(parser, "`alias` attribute expected `)` after parameter");
2839 if (!parser_next(parser)) {
2840 parseerror(parser, "parse error in attribute");
2845 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2846 parseerror(parser, "`alias` attribute expected `]]`");
2850 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2851 flags |= AST_FLAG_DEPRECATED;
2854 if (!parser_next(parser)) {
2855 parseerror(parser, "parse error in attribute");
2859 if (parser->tok == '(') {
2860 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2861 parseerror(parser, "`deprecated` attribute missing parameter");
2865 *message = util_strdup(parser_tokval(parser));
2867 if (!parser_next(parser)) {
2868 parseerror(parser, "parse error in attribute");
2872 if(parser->tok != ')') {
2873 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2877 if (!parser_next(parser)) {
2878 parseerror(parser, "parse error in attribute");
2883 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2884 parseerror(parser, "`deprecated` attribute expected `]]`");
2887 if (*message) mem_d(*message);
2895 /* Skip tokens until we hit a ]] */
2896 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2897 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2898 if (!parser_next(parser)) {
2899 parseerror(parser, "error inside attribute");
2906 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2908 else if (!strcmp(parser_tokval(parser), "const"))
2910 else if (!strcmp(parser_tokval(parser), "var"))
2912 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2914 else if (!strcmp(parser_tokval(parser), "noref"))
2916 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2921 if (!parser_next(parser))
2931 *is_static = had_static;
2935 parseerror(parser, "parse error after variable qualifier");
2940 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2941 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2946 /* skip the 'while' and get the body */
2947 if (!parser_next(parser)) {
2948 if (OPTS_FLAG(LOOP_LABELS))
2949 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2951 parseerror(parser, "expected 'switch' operand in parenthesis");
2955 if (parser->tok == ':') {
2956 if (!OPTS_FLAG(LOOP_LABELS))
2957 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2958 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2959 parseerror(parser, "expected loop label");
2962 label = util_strdup(parser_tokval(parser));
2963 if (!parser_next(parser)) {
2965 parseerror(parser, "expected 'switch' operand in parenthesis");
2970 if (parser->tok != '(') {
2971 parseerror(parser, "expected 'switch' operand in parenthesis");
2975 vec_push(parser->breaks, label);
2977 rv = parse_switch_go(parser, block, out);
2980 if (vec_last(parser->breaks) != label) {
2981 parseerror(parser, "internal error: label stack corrupted");
2987 vec_pop(parser->breaks);
2992 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2994 ast_expression *operand;
2997 ast_switch *switchnode;
2998 ast_switch_case swcase;
3001 bool noref, is_static;
3002 uint32_t qflags = 0;
3004 lex_ctx_t ctx = parser_ctx(parser);
3006 (void)block; /* not touching */
3009 /* parse into the expression */
3010 if (!parser_next(parser)) {
3011 parseerror(parser, "expected switch operand");
3014 /* parse the operand */
3015 operand = parse_expression_leave(parser, false, false, false);
3019 switchnode = ast_switch_new(ctx, operand);
3022 if (parser->tok != ')') {
3023 ast_delete(switchnode);
3024 parseerror(parser, "expected closing paren after 'switch' operand");
3028 /* parse over the opening paren */
3029 if (!parser_next(parser) || parser->tok != '{') {
3030 ast_delete(switchnode);
3031 parseerror(parser, "expected list of cases");
3035 if (!parser_next(parser)) {
3036 ast_delete(switchnode);
3037 parseerror(parser, "expected 'case' or 'default'");
3041 /* new block; allow some variables to be declared here */
3042 parser_enterblock(parser);
3045 if (parser->tok == TOKEN_IDENT)
3046 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3047 if (typevar || parser->tok == TOKEN_TYPENAME) {
3048 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3049 ast_delete(switchnode);
3054 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3056 if (cvq == CV_WRONG) {
3057 ast_delete(switchnode);
3060 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3061 ast_delete(switchnode);
3070 while (parser->tok != '}') {
3071 ast_block *caseblock;
3073 if (!strcmp(parser_tokval(parser), "case")) {
3074 if (!parser_next(parser)) {
3075 ast_delete(switchnode);
3076 parseerror(parser, "expected expression for case");
3079 swcase.value = parse_expression_leave(parser, false, false, false);
3080 if (!swcase.value) {
3081 ast_delete(switchnode);
3082 parseerror(parser, "expected expression for case");
3085 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3086 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3087 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3093 else if (!strcmp(parser_tokval(parser), "default")) {
3094 swcase.value = NULL;
3095 if (!parser_next(parser)) {
3096 ast_delete(switchnode);
3097 parseerror(parser, "expected colon");
3102 ast_delete(switchnode);
3103 parseerror(parser, "expected 'case' or 'default'");
3107 /* Now the colon and body */
3108 if (parser->tok != ':') {
3109 if (swcase.value) ast_unref(swcase.value);
3110 ast_delete(switchnode);
3111 parseerror(parser, "expected colon");
3115 if (!parser_next(parser)) {
3116 if (swcase.value) ast_unref(swcase.value);
3117 ast_delete(switchnode);
3118 parseerror(parser, "expected statements or case");
3121 caseblock = ast_block_new(parser_ctx(parser));
3123 if (swcase.value) ast_unref(swcase.value);
3124 ast_delete(switchnode);
3127 swcase.code = (ast_expression*)caseblock;
3128 vec_push(switchnode->cases, swcase);
3130 ast_expression *expr;
3131 if (parser->tok == '}')
3133 if (parser->tok == TOKEN_KEYWORD) {
3134 if (!strcmp(parser_tokval(parser), "case") ||
3135 !strcmp(parser_tokval(parser), "default"))
3140 if (!parse_statement(parser, caseblock, &expr, true)) {
3141 ast_delete(switchnode);
3146 if (!ast_block_add_expr(caseblock, expr)) {
3147 ast_delete(switchnode);
3153 parser_leaveblock(parser);
3156 if (parser->tok != '}') {
3157 ast_delete(switchnode);
3158 parseerror(parser, "expected closing paren of case list");
3161 if (!parser_next(parser)) {
3162 ast_delete(switchnode);
3163 parseerror(parser, "parse error after switch");
3166 *out = (ast_expression*)switchnode;
3170 /* parse computed goto sides */
3171 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3172 ast_expression *on_true;
3173 ast_expression *on_false;
3174 ast_expression *cond;
3179 if (ast_istype(*side, ast_ternary)) {
3180 ast_ternary *tern = (ast_ternary*)*side;
3181 on_true = parse_goto_computed(parser, &tern->on_true);
3182 on_false = parse_goto_computed(parser, &tern->on_false);
3184 if (!on_true || !on_false) {
3185 parseerror(parser, "expected label or expression in ternary");
3186 if (on_true) ast_unref(on_true);
3187 if (on_false) ast_unref(on_false);
3195 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3196 } else if (ast_istype(*side, ast_label)) {
3197 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3198 ast_goto_set_label(gt, ((ast_label*)*side));
3200 return (ast_expression*)gt;
3205 static bool parse_goto(parser_t *parser, ast_expression **out)
3207 ast_goto *gt = NULL;
3208 ast_expression *lbl;
3210 if (!parser_next(parser))
3213 if (parser->tok != TOKEN_IDENT) {
3214 ast_expression *expression;
3216 /* could be an expression i.e computed goto :-) */
3217 if (parser->tok != '(') {
3218 parseerror(parser, "expected label name after `goto`");
3222 /* failed to parse expression for goto */
3223 if (!(expression = parse_expression(parser, false, true)) ||
3224 !(*out = parse_goto_computed(parser, &expression))) {
3225 parseerror(parser, "invalid goto expression");
3227 ast_unref(expression);
3234 /* not computed goto */
3235 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3236 lbl = parser_find_label(parser, gt->name);
3238 if (!ast_istype(lbl, ast_label)) {
3239 parseerror(parser, "internal error: label is not an ast_label");
3243 ast_goto_set_label(gt, (ast_label*)lbl);
3246 vec_push(parser->gotos, gt);
3248 if (!parser_next(parser) || parser->tok != ';') {
3249 parseerror(parser, "semicolon expected after goto label");
3252 if (!parser_next(parser)) {
3253 parseerror(parser, "parse error after goto");
3257 *out = (ast_expression*)gt;
3261 static bool parse_skipwhite(parser_t *parser)
3264 if (!parser_next(parser))
3266 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3267 return parser->tok < TOKEN_ERROR;
3270 static bool parse_eol(parser_t *parser)
3272 if (!parse_skipwhite(parser))
3274 return parser->tok == TOKEN_EOL;
3277 static bool parse_pragma_do(parser_t *parser)
3279 if (!parser_next(parser) ||
3280 parser->tok != TOKEN_IDENT ||
3281 strcmp(parser_tokval(parser), "pragma"))
3283 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3286 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3287 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3291 if (!strcmp(parser_tokval(parser), "noref")) {
3292 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3293 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3296 parser->noref = !!parser_token(parser)->constval.i;
3297 if (!parse_eol(parser)) {
3298 parseerror(parser, "parse error after `noref` pragma");
3304 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3307 while (!parse_eol(parser)) {
3308 parser_next(parser);
3317 static bool parse_pragma(parser_t *parser)
3320 parser->lex->flags.preprocessing = true;
3321 parser->lex->flags.mergelines = true;
3322 rv = parse_pragma_do(parser);
3323 if (parser->tok != TOKEN_EOL) {
3324 parseerror(parser, "junk after pragma");
3327 parser->lex->flags.preprocessing = false;
3328 parser->lex->flags.mergelines = false;
3329 if (!parser_next(parser)) {
3330 parseerror(parser, "parse error after pragma");
3336 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3338 bool noref, is_static;
3340 uint32_t qflags = 0;
3341 ast_value *typevar = NULL;
3342 char *vstring = NULL;
3346 if (parser->tok == TOKEN_IDENT)
3347 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3349 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3351 /* local variable */
3353 parseerror(parser, "cannot declare a variable from here");
3356 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3357 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3360 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3364 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3366 if (cvq == CV_WRONG)
3368 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3370 else if (parser->tok == TOKEN_KEYWORD)
3372 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3377 if (!parser_next(parser)) {
3378 parseerror(parser, "parse error after __builtin_debug_printtype");
3382 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3384 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3385 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3386 if (!parser_next(parser)) {
3387 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3393 if (!parse_statement(parser, block, out, allow_cases))
3396 con_out("__builtin_debug_printtype: got no output node\n");
3399 ast_type_to_string(*out, ty, sizeof(ty));
3400 con_out("__builtin_debug_printtype: `%s`\n", ty);
3405 else if (!strcmp(parser_tokval(parser), "return"))
3407 return parse_return(parser, block, out);
3409 else if (!strcmp(parser_tokval(parser), "if"))
3411 return parse_if(parser, block, out);
3413 else if (!strcmp(parser_tokval(parser), "while"))
3415 return parse_while(parser, block, out);
3417 else if (!strcmp(parser_tokval(parser), "do"))
3419 return parse_dowhile(parser, block, out);
3421 else if (!strcmp(parser_tokval(parser), "for"))
3423 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3424 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3427 return parse_for(parser, block, out);
3429 else if (!strcmp(parser_tokval(parser), "break"))
3431 return parse_break_continue(parser, block, out, false);
3433 else if (!strcmp(parser_tokval(parser), "continue"))
3435 return parse_break_continue(parser, block, out, true);
3437 else if (!strcmp(parser_tokval(parser), "switch"))
3439 return parse_switch(parser, block, out);
3441 else if (!strcmp(parser_tokval(parser), "case") ||
3442 !strcmp(parser_tokval(parser), "default"))
3445 parseerror(parser, "unexpected 'case' label");
3450 else if (!strcmp(parser_tokval(parser), "goto"))
3452 return parse_goto(parser, out);
3454 else if (!strcmp(parser_tokval(parser), "typedef"))
3456 if (!parser_next(parser)) {
3457 parseerror(parser, "expected type definition after 'typedef'");
3460 return parse_typedef(parser);
3462 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3465 else if (parser->tok == '{')
3468 inner = parse_block(parser);
3471 *out = (ast_expression*)inner;
3474 else if (parser->tok == ':')
3478 if (!parser_next(parser)) {
3479 parseerror(parser, "expected label name");
3482 if (parser->tok != TOKEN_IDENT) {
3483 parseerror(parser, "label must be an identifier");
3486 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3488 if (!label->undefined) {
3489 parseerror(parser, "label `%s` already defined", label->name);
3492 label->undefined = false;
3495 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3496 vec_push(parser->labels, label);
3498 *out = (ast_expression*)label;
3499 if (!parser_next(parser)) {
3500 parseerror(parser, "parse error after label");
3503 for (i = 0; i < vec_size(parser->gotos); ++i) {
3504 if (!strcmp(parser->gotos[i]->name, label->name)) {
3505 ast_goto_set_label(parser->gotos[i], label);
3506 vec_remove(parser->gotos, i, 1);
3512 else if (parser->tok == ';')
3514 if (!parser_next(parser)) {
3515 parseerror(parser, "parse error after empty statement");
3522 lex_ctx_t ctx = parser_ctx(parser);
3523 ast_expression *exp = parse_expression(parser, false, false);
3527 if (!ast_side_effects(exp)) {
3528 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3535 static bool parse_enum(parser_t *parser)
3538 bool reverse = false;
3540 ast_value **values = NULL;
3541 ast_value *var = NULL;
3544 ast_expression *old;
3546 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3547 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3551 /* enumeration attributes (can add more later) */
3552 if (parser->tok == ':') {
3553 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3554 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3559 if (!strcmp(parser_tokval(parser), "flag")) {
3563 else if (!strcmp(parser_tokval(parser), "reverse")) {
3567 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3571 if (!parser_next(parser) || parser->tok != '{') {
3572 parseerror(parser, "expected `{` after enum attribute ");
3578 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3579 if (parser->tok == '}') {
3580 /* allow an empty enum */
3583 parseerror(parser, "expected identifier or `}`");
3587 old = parser_find_field(parser, parser_tokval(parser));
3589 old = parser_find_global(parser, parser_tokval(parser));
3591 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3592 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3596 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3597 vec_push(values, var);
3598 var->cvq = CV_CONST;
3599 var->hasvalue = true;
3601 /* for flagged enumerations increment in POTs of TWO */
3602 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3603 parser_addglobal(parser, var->name, (ast_expression*)var);
3605 if (!parser_next(parser)) {
3606 parseerror(parser, "expected `=`, `}` or comma after identifier");
3610 if (parser->tok == ',')
3612 if (parser->tok == '}')
3614 if (parser->tok != '=') {
3615 parseerror(parser, "expected `=`, `}` or comma after identifier");
3619 if (!parser_next(parser)) {
3620 parseerror(parser, "expected expression after `=`");
3624 /* We got a value! */
3625 old = parse_expression_leave(parser, true, false, false);
3626 asvalue = (ast_value*)old;
3627 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3628 compile_error(ast_ctx(var), "constant value or expression expected");
3631 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3633 if (parser->tok == '}')
3635 if (parser->tok != ',') {
3636 parseerror(parser, "expected `}` or comma after expression");
3641 /* patch them all (for reversed attribute) */
3644 for (i = 0; i < vec_size(values); i++)
3645 values[i]->constval.vfloat = vec_size(values) - i - 1;
3648 if (parser->tok != '}') {
3649 parseerror(parser, "internal error: breaking without `}`");
3653 if (!parser_next(parser) || parser->tok != ';') {
3654 parseerror(parser, "expected semicolon after enumeration");
3658 if (!parser_next(parser)) {
3659 parseerror(parser, "parse error after enumeration");
3671 static bool parse_block_into(parser_t *parser, ast_block *block)
3675 parser_enterblock(parser);
3677 if (!parser_next(parser)) { /* skip the '{' */
3678 parseerror(parser, "expected function body");
3682 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3684 ast_expression *expr = NULL;
3685 if (parser->tok == '}')
3688 if (!parse_statement(parser, block, &expr, false)) {
3689 /* parseerror(parser, "parse error"); */
3695 if (!ast_block_add_expr(block, expr)) {
3702 if (parser->tok != '}') {
3705 (void)parser_next(parser);
3709 if (!parser_leaveblock(parser))
3711 return retval && !!block;
3714 static ast_block* parse_block(parser_t *parser)
3717 block = ast_block_new(parser_ctx(parser));
3720 if (!parse_block_into(parser, block)) {
3721 ast_block_delete(block);
3727 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3729 if (parser->tok == '{') {
3730 *out = (ast_expression*)parse_block(parser);
3733 return parse_statement(parser, NULL, out, false);
3736 static bool create_vector_members(ast_value *var, ast_member **me)
3739 size_t len = strlen(var->name);
3741 for (i = 0; i < 3; ++i) {
3742 char *name = (char*)mem_a(len+3);
3743 memcpy(name, var->name, len);
3745 name[len+1] = 'x'+i;
3747 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3756 do { ast_member_delete(me[--i]); } while(i);
3760 static bool parse_function_body(parser_t *parser, ast_value *var)
3762 ast_block *block = NULL;
3767 ast_expression *framenum = NULL;
3768 ast_expression *nextthink = NULL;
3769 /* None of the following have to be deleted */
3770 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3771 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3772 bool has_frame_think;
3776 has_frame_think = false;
3777 old = parser->function;
3779 if (var->expression.flags & AST_FLAG_ALIAS) {
3780 parseerror(parser, "function aliases cannot have bodies");
3784 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3785 parseerror(parser, "gotos/labels leaking");
3789 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3790 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3791 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3797 if (parser->tok == '[') {
3798 /* got a frame definition: [ framenum, nextthink ]
3799 * this translates to:
3800 * self.frame = framenum;
3801 * self.nextthink = time + 0.1;
3802 * self.think = nextthink;
3806 fld_think = parser_find_field(parser, "think");
3807 fld_nextthink = parser_find_field(parser, "nextthink");
3808 fld_frame = parser_find_field(parser, "frame");
3809 if (!fld_think || !fld_nextthink || !fld_frame) {
3810 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3811 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3814 gbl_time = parser_find_global(parser, "time");
3815 gbl_self = parser_find_global(parser, "self");
3816 if (!gbl_time || !gbl_self) {
3817 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3818 parseerror(parser, "please declare the following globals: `time`, `self`");
3822 if (!parser_next(parser))
3825 framenum = parse_expression_leave(parser, true, false, false);
3827 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3830 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3831 ast_unref(framenum);
3832 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3836 if (parser->tok != ',') {
3837 ast_unref(framenum);
3838 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3839 parseerror(parser, "Got a %i\n", parser->tok);
3843 if (!parser_next(parser)) {
3844 ast_unref(framenum);
3848 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3850 /* qc allows the use of not-yet-declared functions here
3851 * - this automatically creates a prototype */
3852 ast_value *thinkfunc;
3853 ast_expression *functype = fld_think->next;
3855 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3856 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3857 ast_unref(framenum);
3858 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3861 ast_type_adopt(thinkfunc, functype);
3863 if (!parser_next(parser)) {
3864 ast_unref(framenum);
3865 ast_delete(thinkfunc);
3869 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3871 nextthink = (ast_expression*)thinkfunc;
3874 nextthink = parse_expression_leave(parser, true, false, false);
3876 ast_unref(framenum);
3877 parseerror(parser, "expected a think-function in [frame,think] notation");
3882 if (!ast_istype(nextthink, ast_value)) {
3883 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3887 if (retval && parser->tok != ']') {
3888 parseerror(parser, "expected closing `]` for [frame,think] notation");
3892 if (retval && !parser_next(parser)) {
3896 if (retval && parser->tok != '{') {
3897 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3902 ast_unref(nextthink);
3903 ast_unref(framenum);
3907 has_frame_think = true;
3910 block = ast_block_new(parser_ctx(parser));
3912 parseerror(parser, "failed to allocate block");
3913 if (has_frame_think) {
3914 ast_unref(nextthink);
3915 ast_unref(framenum);
3920 if (has_frame_think) {
3922 ast_expression *self_frame;
3923 ast_expression *self_nextthink;
3924 ast_expression *self_think;
3925 ast_expression *time_plus_1;
3926 ast_store *store_frame;
3927 ast_store *store_nextthink;
3928 ast_store *store_think;
3930 ctx = parser_ctx(parser);
3931 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3932 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3933 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3935 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3936 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3938 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3939 if (self_frame) ast_delete(self_frame);
3940 if (self_nextthink) ast_delete(self_nextthink);
3941 if (self_think) ast_delete(self_think);
3942 if (time_plus_1) ast_delete(time_plus_1);
3948 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3949 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3950 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3953 ast_delete(self_frame);
3956 if (!store_nextthink) {
3957 ast_delete(self_nextthink);
3961 ast_delete(self_think);
3965 if (store_frame) ast_delete(store_frame);
3966 if (store_nextthink) ast_delete(store_nextthink);
3967 if (store_think) ast_delete(store_think);
3970 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3971 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3972 !ast_block_add_expr(block, (ast_expression*)store_think))
3979 parseerror(parser, "failed to generate code for [frame,think]");
3980 ast_unref(nextthink);
3981 ast_unref(framenum);
3987 if (var->hasvalue && !(var->expression.flags & AST_FLAG_ACCUMULATE)) {
3988 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3989 ast_block_delete(block);
3994 if (var->hasvalue && var->expression.vtype == TYPE_FUNCTION) {
3995 ast_value *accum = NULL;
3996 ast_function *previous = NULL;
3999 /* only void please */
4000 if (var->expression.next->vtype != TYPE_VOID) {
4001 parseerror(parser, "accumulated function `%s` declared with return type `%s` (accumulated functions must return void)",
4003 type_name[var->expression.next->vtype]
4005 ast_block_delete(block);
4009 /* generate a new name increasing the accumulation count*/
4010 util_snprintf(acname, sizeof(acname), "##ACCUMULATE_%s_%d", var->name, var->constval.vfunc->accumulation++);
4011 accum = ast_value_new(parser_ctx(parser), acname, ((ast_expression*)var)->vtype);
4015 ast_type_adopt(accum, var);
4016 func = ast_function_new(ast_ctx(var), NULL, accum);
4020 parser_addglobal(parser, acname, (ast_expression*)accum);
4021 vec_push(parser->functions, func);
4023 /* update the previous calls accumulate pointer for the codegen */
4024 previous = var->constval.vfunc;
4025 while (previous->accumulate)
4026 previous = previous->accumulate;
4028 if (ast_istype(previous, ast_function))
4029 previous->accumulate = func;
4032 func = ast_function_new(ast_ctx(var), var->name, var);
4033 vec_push(parser->functions, func);
4037 parseerror(parser, "failed to allocate function for `%s`", var->name);
4038 ast_block_delete(block);
4042 parser_enterblock(parser);
4044 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4046 ast_value *param = var->expression.params[parami];
4049 if (param->expression.vtype != TYPE_VECTOR &&
4050 (param->expression.vtype != TYPE_FIELD ||
4051 param->expression.next->vtype != TYPE_VECTOR))
4056 if (!create_vector_members(param, me)) {
4057 ast_block_delete(block);
4061 for (e = 0; e < 3; ++e) {
4062 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4063 ast_block_collect(block, (ast_expression*)me[e]);
4067 if (var->argcounter) {
4068 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4069 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4073 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4075 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4076 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4077 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4078 varargs->expression.count = 0;
4079 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4080 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4081 ast_delete(varargs);
4082 ast_block_delete(block);
4085 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4086 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4087 ast_delete(varargs);
4088 ast_block_delete(block);
4091 func->varargs = varargs;
4092 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4095 parser->function = func;
4096 if (!parse_block_into(parser, block)) {
4097 ast_block_delete(block);
4101 vec_push(func->blocks, block);
4104 parser->function = old;
4105 if (!parser_leaveblock(parser))
4107 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4108 parseerror(parser, "internal error: local scopes left");
4112 if (parser->tok == ';')
4113 return parser_next(parser);
4114 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4115 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4119 (void)!parser_leaveblock(parser);
4120 vec_pop(parser->functions);
4121 ast_function_delete(func);
4122 var->constval.vfunc = NULL;
4125 parser->function = old;
4129 static ast_expression *array_accessor_split(
4134 ast_expression *left,
4135 ast_expression *right
4141 lex_ctx_t ctx = ast_ctx(array);
4143 if (!left || !right) {
4144 if (left) ast_delete(left);
4145 if (right) ast_delete(right);
4149 cmp = ast_binary_new(ctx, INSTR_LT,
4150 (ast_expression*)index,
4151 (ast_expression*)fold_constgen_float(parser->fold, middle));
4155 parseerror(parser, "internal error: failed to create comparison for array setter");
4159 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4161 ast_delete(cmp); /* will delete left and right */
4162 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4166 return (ast_expression*)ifthen;
4169 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4171 lex_ctx_t ctx = ast_ctx(array);
4173 if (from+1 == afterend) {
4174 /* set this value */
4177 ast_array_index *subscript;
4179 int assignop = type_store_instr[value->expression.vtype];
4181 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4182 assignop = INSTR_STORE_V;
4184 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4188 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4190 ast_delete(subscript);
4194 block = ast_block_new(ctx);
4200 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4205 ret = ast_return_new(ctx, NULL);
4211 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4216 return (ast_expression*)block;
4218 ast_expression *left, *right;
4219 size_t diff = afterend - from;
4220 size_t middle = from + diff/2;
4221 left = array_setter_node(parser, array, index, value, from, middle);
4222 right = array_setter_node(parser, array, index, value, middle, afterend);
4223 return array_accessor_split(parser, array, index, middle, left, right);
4227 static ast_expression *array_field_setter_node(
4236 lex_ctx_t ctx = ast_ctx(array);
4238 if (from+1 == afterend) {
4239 /* set this value */
4242 ast_entfield *entfield;
4243 ast_array_index *subscript;
4245 int assignop = type_storep_instr[value->expression.vtype];
4247 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4248 assignop = INSTR_STOREP_V;
4250 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4254 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4255 subscript->expression.vtype = TYPE_FIELD;
4257 entfield = ast_entfield_new_force(ctx,
4258 (ast_expression*)entity,
4259 (ast_expression*)subscript,
4260 (ast_expression*)subscript);
4262 ast_delete(subscript);
4266 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4268 ast_delete(entfield);
4272 block = ast_block_new(ctx);
4278 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4283 ret = ast_return_new(ctx, NULL);
4289 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4294 return (ast_expression*)block;
4296 ast_expression *left, *right;
4297 size_t diff = afterend - from;
4298 size_t middle = from + diff/2;
4299 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4300 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4301 return array_accessor_split(parser, array, index, middle, left, right);
4305 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4307 lex_ctx_t ctx = ast_ctx(array);
4309 if (from+1 == afterend) {
4311 ast_array_index *subscript;
4313 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4317 ret = ast_return_new(ctx, (ast_expression*)subscript);
4319 ast_delete(subscript);
4323 return (ast_expression*)ret;
4325 ast_expression *left, *right;
4326 size_t diff = afterend - from;
4327 size_t middle = from + diff/2;
4328 left = array_getter_node(parser, array, index, from, middle);
4329 right = array_getter_node(parser, array, index, middle, afterend);
4330 return array_accessor_split(parser, array, index, middle, left, right);
4334 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4336 ast_function *func = NULL;
4337 ast_value *fval = NULL;
4338 ast_block *body = NULL;
4340 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4342 parseerror(parser, "failed to create accessor function value");
4346 func = ast_function_new(ast_ctx(array), funcname, fval);
4349 parseerror(parser, "failed to create accessor function node");
4353 body = ast_block_new(ast_ctx(array));
4355 parseerror(parser, "failed to create block for array accessor");
4361 vec_push(func->blocks, body);
4364 vec_push(parser->accessors, fval);
4369 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4371 ast_value *index = NULL;
4372 ast_value *value = NULL;
4376 if (!ast_istype(array->expression.next, ast_value)) {
4377 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4381 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4383 func = fval->constval.vfunc;
4384 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4386 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4387 value = ast_value_copy((ast_value*)array->expression.next);
4389 if (!index || !value) {
4390 parseerror(parser, "failed to create locals for array accessor");
4393 (void)!ast_value_set_name(value, "value"); /* not important */
4394 vec_push(fval->expression.params, index);
4395 vec_push(fval->expression.params, value);
4397 array->setter = fval;
4400 if (index) ast_delete(index);
4401 if (value) ast_delete(value);
4407 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4409 ast_expression *root = NULL;
4410 root = array_setter_node(parser, array,
4411 array->setter->expression.params[0],
4412 array->setter->expression.params[1],
4413 0, array->expression.count);
4415 parseerror(parser, "failed to build accessor search tree");
4418 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4425 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4427 if (!parser_create_array_setter_proto(parser, array, funcname))
4429 return parser_create_array_setter_impl(parser, array);
4432 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4434 ast_expression *root = NULL;
4435 ast_value *entity = NULL;
4436 ast_value *index = NULL;
4437 ast_value *value = NULL;
4441 if (!ast_istype(array->expression.next, ast_value)) {
4442 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4446 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4448 func = fval->constval.vfunc;
4449 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4451 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4452 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4453 value = ast_value_copy((ast_value*)array->expression.next);
4454 if (!entity || !index || !value) {
4455 parseerror(parser, "failed to create locals for array accessor");
4458 (void)!ast_value_set_name(value, "value"); /* not important */
4459 vec_push(fval->expression.params, entity);
4460 vec_push(fval->expression.params, index);
4461 vec_push(fval->expression.params, value);
4463 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4465 parseerror(parser, "failed to build accessor search tree");
4469 array->setter = fval;
4470 return ast_block_add_expr(func->blocks[0], root);
4472 if (entity) ast_delete(entity);
4473 if (index) ast_delete(index);
4474 if (value) ast_delete(value);
4475 if (root) ast_delete(root);
4481 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4483 ast_value *index = NULL;
4487 /* NOTE: checking array->expression.next rather than elemtype since
4488 * for fields elemtype is a temporary fieldtype.
4490 if (!ast_istype(array->expression.next, ast_value)) {
4491 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4495 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4497 func = fval->constval.vfunc;
4498 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4500 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4503 parseerror(parser, "failed to create locals for array accessor");
4506 vec_push(fval->expression.params, index);
4508 array->getter = fval;
4511 if (index) ast_delete(index);
4517 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4519 ast_expression *root = NULL;
4521 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4523 parseerror(parser, "failed to build accessor search tree");
4526 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4533 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4535 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4537 return parser_create_array_getter_impl(parser, array);
4540 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4541 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4549 bool variadic = false;
4550 ast_value *varparam = NULL;
4551 char *argcounter = NULL;
4553 ctx = parser_ctx(parser);
4555 /* for the sake of less code we parse-in in this function */
4556 if (!parser_next(parser)) {
4558 parseerror(parser, "expected parameter list");
4564 /* parse variables until we hit a closing paren */
4565 while (parser->tok != ')') {
4567 /* there must be commas between them */
4568 if (parser->tok != ',') {
4569 parseerror(parser, "expected comma or end of parameter list");
4572 if (!parser_next(parser)) {
4573 parseerror(parser, "expected parameter");
4579 if (parser->tok == TOKEN_DOTS) {
4580 /* '...' indicates a varargs function */
4582 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4583 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4586 if (parser->tok == TOKEN_IDENT) {
4587 argcounter = util_strdup(parser_tokval(parser));
4588 if (!parser_next(parser) || parser->tok != ')') {
4589 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4596 /* for anything else just parse a typename */
4597 param = parse_typename(parser, NULL, NULL);
4600 vec_push(params, param);
4601 if (param->expression.vtype >= TYPE_VARIANT) {
4602 char tname[1024]; /* typename is reserved in C++ */
4603 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4604 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4607 /* type-restricted varargs */
4608 if (parser->tok == TOKEN_DOTS) {
4610 varparam = vec_last(params);
4612 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4613 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4616 if (parser->tok == TOKEN_IDENT) {
4617 argcounter = util_strdup(parser_tokval(parser));
4618 if (!parser_next(parser) || parser->tok != ')') {
4619 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4627 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4631 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4632 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4635 if (!parser_next(parser)) {
4636 parseerror(parser, "parse error after typename");
4640 /* now turn 'var' into a function type */
4641 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4642 fval->expression.next = (ast_expression*)var;
4644 fval->expression.flags |= AST_FLAG_VARIADIC;
4647 var->expression.params = params;
4648 var->expression.varparam = (ast_expression*)varparam;
4649 var->argcounter = argcounter;
4658 ast_delete(varparam);
4660 for (i = 0; i < vec_size(params); ++i)
4661 ast_delete(params[i]);
4666 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4668 ast_expression *cexp;
4669 ast_value *cval, *tmp;
4672 ctx = parser_ctx(parser);
4674 if (!parser_next(parser)) {
4676 parseerror(parser, "expected array-size");
4680 if (parser->tok != ']') {
4681 cexp = parse_expression_leave(parser, true, false, false);
4683 if (!cexp || !ast_istype(cexp, ast_value)) {
4687 parseerror(parser, "expected array-size as constant positive integer");
4690 cval = (ast_value*)cexp;
4697 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4698 tmp->expression.next = (ast_expression*)var;
4702 if (cval->expression.vtype == TYPE_INTEGER)
4703 tmp->expression.count = cval->constval.vint;
4704 else if (cval->expression.vtype == TYPE_FLOAT)
4705 tmp->expression.count = cval->constval.vfloat;
4709 parseerror(parser, "array-size must be a positive integer constant");
4715 var->expression.count = -1;
4716 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4719 if (parser->tok != ']') {
4721 parseerror(parser, "expected ']' after array-size");
4724 if (!parser_next(parser)) {
4726 parseerror(parser, "error after parsing array size");
4732 /* Parse a complete typename.
4733 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4734 * but when parsing variables separated by comma
4735 * 'storebase' should point to where the base-type should be kept.
4736 * The base type makes up every bit of type information which comes *before* the
4739 * NOTE: The value must either be named, have a NULL name, or a name starting
4740 * with '<'. In the first case, this will be the actual variable or type
4741 * name, in the other cases it is assumed that the name will appear
4742 * later, and an error is generated otherwise.
4744 * The following will be parsed in its entirety:
4746 * The 'basetype' in this case is 'void()'
4747 * and if there's a comma after it, say:
4749 * then the type-information 'void()' can be stored in 'storebase'
4751 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4753 ast_value *var, *tmp;
4756 const char *name = NULL;
4757 bool isfield = false;
4758 bool wasarray = false;
4759 size_t morefields = 0;
4761 ctx = parser_ctx(parser);
4763 /* types may start with a dot */
4764 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4766 if (parser->tok == TOKEN_DOTS)
4768 /* if we parsed a dot we need a typename now */
4769 if (!parser_next(parser)) {
4770 parseerror(parser, "expected typename for field definition");
4774 /* Further dots are handled seperately because they won't be part of the
4778 if (parser->tok == '.')
4780 else if (parser->tok == TOKEN_DOTS)
4784 if (!parser_next(parser)) {
4785 parseerror(parser, "expected typename for field definition");
4790 if (parser->tok == TOKEN_IDENT)
4791 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4792 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4793 parseerror(parser, "expected typename");
4797 /* generate the basic type value */
4798 if (cached_typedef) {
4799 var = ast_value_copy(cached_typedef);
4800 ast_value_set_name(var, "<type(from_def)>");
4802 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4804 for (; morefields; --morefields) {
4805 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4806 tmp->expression.next = (ast_expression*)var;
4810 /* do not yet turn into a field - remember:
4811 * .void() foo; is a field too
4812 * .void()() foo; is a function
4816 if (!parser_next(parser)) {
4818 parseerror(parser, "parse error after typename");
4822 /* an opening paren now starts the parameter-list of a function
4823 * this is where original-QC has parameter lists.
4824 * We allow a single parameter list here.
4825 * Much like fteqcc we don't allow `float()() x`
4827 if (parser->tok == '(') {
4828 var = parse_parameter_list(parser, var);
4833 /* store the base if requested */
4835 *storebase = ast_value_copy(var);
4837 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4838 tmp->expression.next = (ast_expression*)*storebase;
4843 /* there may be a name now */
4844 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4845 if (!strcmp(parser_tokval(parser), "break"))
4846 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4847 else if (parser->tok == TOKEN_KEYWORD)
4850 name = util_strdup(parser_tokval(parser));
4853 if (!parser_next(parser)) {
4856 parseerror(parser, "error after variable or field declaration");
4862 /* now this may be an array */
4863 if (parser->tok == '[') {
4865 var = parse_arraysize(parser, var);
4867 if (name) mem_d(name);
4872 /* This is the point where we can turn it into a field */
4874 /* turn it into a field if desired */
4875 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4876 tmp->expression.next = (ast_expression*)var;
4880 /* now there may be function parens again */
4881 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4882 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4883 if (parser->tok == '(' && wasarray)
4884 parseerror(parser, "arrays as part of a return type is not supported");
4885 while (parser->tok == '(') {
4886 var = parse_parameter_list(parser, var);
4888 if (name) mem_d(name);
4893 /* finally name it */
4895 if (!ast_value_set_name(var, name)) {
4898 parseerror(parser, "internal error: failed to set name");
4901 /* free the name, ast_value_set_name duplicates */
4908 static bool parse_typedef(parser_t *parser)
4910 ast_value *typevar, *oldtype;
4911 ast_expression *old;
4913 typevar = parse_typename(parser, NULL, NULL);
4918 /* while parsing types, the ast_value's get named '<something>' */
4919 if (!typevar->name || typevar->name[0] == '<') {
4920 parseerror(parser, "missing name in typedef");
4921 ast_delete(typevar);
4925 if ( (old = parser_find_var(parser, typevar->name)) ) {
4926 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4927 " -> `%s` has been declared here: %s:%i",
4928 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4929 ast_delete(typevar);
4933 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4934 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4935 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4936 ast_delete(typevar);
4940 vec_push(parser->_typedefs, typevar);
4941 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4943 if (parser->tok != ';') {
4944 parseerror(parser, "expected semicolon after typedef");
4947 if (!parser_next(parser)) {
4948 parseerror(parser, "parse error after typedef");
4955 static const char *cvq_to_str(int cvq) {
4957 case CV_NONE: return "none";
4958 case CV_VAR: return "`var`";
4959 case CV_CONST: return "`const`";
4960 default: return "<INVALID>";
4964 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4967 if (proto->cvq != var->cvq) {
4968 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4969 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4970 parser->tok == '='))
4972 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4973 "`%s` declared with different qualifiers: %s\n"
4974 " -> previous declaration here: %s:%i uses %s",
4975 var->name, cvq_to_str(var->cvq),
4976 ast_ctx(proto).file, ast_ctx(proto).line,
4977 cvq_to_str(proto->cvq));
4980 av = (var ->expression.flags & AST_FLAG_NORETURN);
4981 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4983 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4984 "`%s` declared with different attributes%s\n"
4985 " -> previous declaration here: %s:%i",
4986 var->name, (av ? ": noreturn" : ""),
4987 ast_ctx(proto).file, ast_ctx(proto).line,
4988 (ao ? ": noreturn" : ""));
4993 static bool create_array_accessors(parser_t *parser, ast_value *var)
4996 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4997 if (!parser_create_array_setter(parser, var, name))
4999 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5000 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5005 static bool parse_array(parser_t *parser, ast_value *array)
5008 if (array->initlist) {
5009 parseerror(parser, "array already initialized elsewhere");
5012 if (!parser_next(parser)) {
5013 parseerror(parser, "parse error in array initializer");
5017 while (parser->tok != '}') {
5018 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5021 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5023 parseerror(parser, "initializing element must be a compile time constant");
5026 vec_push(array->initlist, v->constval);
5027 if (v->expression.vtype == TYPE_STRING) {
5028 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5032 if (parser->tok == '}')
5034 if (parser->tok != ',' || !parser_next(parser)) {
5035 parseerror(parser, "expected comma or '}' in element list");
5039 if (!parser_next(parser) || parser->tok != ';') {
5040 parseerror(parser, "expected semicolon after initializer, got %s");
5044 if (!parser_next(parser)) {
5045 parseerror(parser, "parse error after initializer");
5050 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5051 if (array->expression.count != (size_t)-1) {
5052 parseerror(parser, "array `%s' has already been initialized with %u elements",
5053 array->name, (unsigned)array->expression.count);
5055 array->expression.count = vec_size(array->initlist);
5056 if (!create_array_accessors(parser, array))
5062 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)
5066 ast_expression *old;
5070 ast_value *basetype = NULL;
5072 bool isparam = false;
5073 bool isvector = false;
5074 bool cleanvar = true;
5075 bool wasarray = false;
5077 ast_member *me[3] = { NULL, NULL, NULL };
5079 if (!localblock && is_static)
5080 parseerror(parser, "`static` qualifier is not supported in global scope");
5082 /* get the first complete variable */
5083 var = parse_typename(parser, &basetype, cached_typedef);
5086 ast_delete(basetype);
5090 /* while parsing types, the ast_value's get named '<something>' */
5091 if (!var->name || var->name[0] == '<') {
5092 parseerror(parser, "declaration does not declare anything");
5094 ast_delete(basetype);
5102 /* Part 0: finish the type */
5103 if (parser->tok == '(') {
5104 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5105 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5106 var = parse_parameter_list(parser, var);
5112 /* we only allow 1-dimensional arrays */
5113 if (parser->tok == '[') {
5115 var = parse_arraysize(parser, var);
5121 if (parser->tok == '(' && wasarray) {
5122 parseerror(parser, "arrays as part of a return type is not supported");
5123 /* we'll still parse the type completely for now */
5125 /* for functions returning functions */
5126 while (parser->tok == '(') {
5127 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5128 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5129 var = parse_parameter_list(parser, var);
5136 var->cvq = qualifier;
5137 var->expression.flags |= qflags;
5140 * store the vstring back to var for alias and
5141 * deprecation messages.
5143 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5144 var->expression.flags & AST_FLAG_ALIAS)
5145 var->desc = vstring;
5147 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5148 parseerror(parser, "function aliases cannot be forward declared");
5155 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5156 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5157 * is then filled with the previous definition and the parameter-names replaced.
5159 if (!strcmp(var->name, "nil")) {
5160 if (OPTS_FLAG(UNTYPED_NIL)) {
5161 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5162 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5164 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5167 /* Deal with end_sys_ vars */
5169 if (!strcmp(var->name, "end_sys_globals")) {
5171 parser->crc_globals = vec_size(parser->globals);
5174 else if (!strcmp(var->name, "end_sys_fields")) {
5176 parser->crc_fields = vec_size(parser->fields);
5179 if (was_end && var->expression.vtype == TYPE_FIELD) {
5180 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5181 "global '%s' hint should not be a field",
5182 parser_tokval(parser)))
5189 if (!nofields && var->expression.vtype == TYPE_FIELD)
5191 /* deal with field declarations */
5192 old = parser_find_field(parser, var->name);
5194 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5195 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5204 parseerror(parser, "field `%s` already declared here: %s:%i",
5205 var->name, ast_ctx(old).file, ast_ctx(old).line);
5210 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5211 (old = parser_find_global(parser, var->name)))
5213 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5214 parseerror(parser, "field `%s` already declared here: %s:%i",
5215 var->name, ast_ctx(old).file, ast_ctx(old).line);
5222 /* deal with other globals */
5223 old = parser_find_global(parser, var->name);
5224 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5226 /* This is a function which had a prototype */
5227 if (!ast_istype(old, ast_value)) {
5228 parseerror(parser, "internal error: prototype is not an ast_value");
5232 proto = (ast_value*)old;
5233 proto->desc = var->desc;
5234 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5235 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5237 ast_ctx(proto).file, ast_ctx(proto).line);
5241 /* we need the new parameter-names */
5242 for (i = 0; i < vec_size(proto->expression.params); ++i)
5243 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5244 if (!parser_check_qualifiers(parser, var, proto)) {
5251 proto->expression.flags |= var->expression.flags;
5259 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5260 "global `%s` already declared here: %s:%i",
5261 var->name, ast_ctx(old).file, ast_ctx(old).line))
5266 proto = (ast_value*)old;
5267 if (!ast_istype(old, ast_value)) {
5268 parseerror(parser, "internal error: not an ast_value");
5273 if (!parser_check_qualifiers(parser, var, proto)) {
5278 proto->expression.flags |= var->expression.flags;
5282 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5283 (old = parser_find_field(parser, var->name)))
5285 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5286 parseerror(parser, "global `%s` already declared here: %s:%i",
5287 var->name, ast_ctx(old).file, ast_ctx(old).line);
5294 else /* it's not a global */
5296 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5297 if (old && !isparam) {
5298 parseerror(parser, "local `%s` already declared here: %s:%i",
5299 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5303 /* doing this here as the above is just for a single scope */
5304 old = parser_find_local(parser, var->name, 0, &isparam);
5305 if (old && isparam) {
5306 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5307 "local `%s` is shadowing a parameter", var->name))
5309 parseerror(parser, "local `%s` already declared here: %s:%i",
5310 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5314 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5316 if (ast_istype(old, ast_value))
5317 var = proto = (ast_value*)old;
5326 /* in a noref section we simply bump the usecount */
5327 if (noref || parser->noref)
5331 * Create the global/local, and deal with vector types.
5334 if (var->expression.vtype == TYPE_VECTOR)
5336 else if (var->expression.vtype == TYPE_FIELD &&
5337 var->expression.next->vtype == TYPE_VECTOR)
5341 if (!create_vector_members(var, me)) {
5348 /* deal with global variables, fields, functions */
5349 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5350 var->isfield = true;
5351 vec_push(parser->fields, (ast_expression*)var);
5352 util_htset(parser->htfields, var->name, var);
5354 for (i = 0; i < 3; ++i) {
5355 vec_push(parser->fields, (ast_expression*)me[i]);
5356 util_htset(parser->htfields, me[i]->name, me[i]);
5361 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5362 parser_addglobal(parser, var->name, (ast_expression*)var);
5364 for (i = 0; i < 3; ++i) {
5365 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5369 ast_expression *find = parser_find_global(parser, var->desc);
5372 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5376 if (!ast_compare_type((ast_expression*)var, find)) {
5380 ast_type_to_string(find, ty1, sizeof(ty1));
5381 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5383 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5390 * add alias to aliases table and to corrector
5391 * so corrections can apply for aliases as well.
5393 util_htset(parser->aliases, var->name, find);
5396 * add to corrector so corrections can work
5397 * even for aliases too.
5400 vec_last(parser->correct_variables),
5401 &vec_last(parser->correct_variables_score),
5405 /* generate aliases for vector components */
5409 util_asprintf(&buffer[0], "%s_x", var->desc);
5410 util_asprintf(&buffer[1], "%s_y", var->desc);
5411 util_asprintf(&buffer[2], "%s_z", var->desc);
5413 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5414 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5415 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5422 * add to corrector so corrections can work
5423 * even for aliases too.
5426 vec_last(parser->correct_variables),
5427 &vec_last(parser->correct_variables_score),
5431 vec_last(parser->correct_variables),
5432 &vec_last(parser->correct_variables_score),
5436 vec_last(parser->correct_variables),
5437 &vec_last(parser->correct_variables_score),
5445 /* a static adds itself to be generated like any other global
5446 * but is added to the local namespace instead
5448 char *defname = NULL;
5449 size_t prefix_len, ln;
5451 ln = strlen(parser->function->name);
5452 vec_append(defname, ln, parser->function->name);
5454 vec_append(defname, 2, "::");
5455 /* remember the length up to here */
5456 prefix_len = vec_size(defname);
5458 /* Add it to the local scope */
5459 util_htset(vec_last(parser->variables), var->name, (void*)var);
5463 vec_last(parser->correct_variables),
5464 &vec_last(parser->correct_variables_score),
5468 /* now rename the global */
5469 ln = strlen(var->name);
5470 vec_append(defname, ln, var->name);
5471 ast_value_set_name(var, defname);
5473 /* push it to the to-be-generated globals */
5474 vec_push(parser->globals, (ast_expression*)var);
5476 /* same game for the vector members */
5478 for (i = 0; i < 3; ++i) {
5479 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5483 vec_last(parser->correct_variables),
5484 &vec_last(parser->correct_variables_score),
5488 vec_shrinkto(defname, prefix_len);
5489 ln = strlen(me[i]->name);
5490 vec_append(defname, ln, me[i]->name);
5491 ast_member_set_name(me[i], defname);
5493 vec_push(parser->globals, (ast_expression*)me[i]);
5498 vec_push(localblock->locals, var);
5499 parser_addlocal(parser, var->name, (ast_expression*)var);
5501 for (i = 0; i < 3; ++i) {
5502 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5503 ast_block_collect(localblock, (ast_expression*)me[i]);
5509 me[0] = me[1] = me[2] = NULL;
5514 if (var->expression.vtype == TYPE_ARRAY) {
5515 if (var->expression.count != (size_t)-1) {
5516 if (!create_array_accessors(parser, var))
5520 else if (!localblock && !nofields &&
5521 var->expression.vtype == TYPE_FIELD &&
5522 var->expression.next->vtype == TYPE_ARRAY)
5525 ast_expression *telem;
5527 ast_value *array = (ast_value*)var->expression.next;
5529 if (!ast_istype(var->expression.next, ast_value)) {
5530 parseerror(parser, "internal error: field element type must be an ast_value");
5534 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5535 if (!parser_create_array_field_setter(parser, array, name))
5538 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5539 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5540 tfield->expression.next = telem;
5541 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5542 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5550 if (parser->tok == ';') {
5551 ast_delete(basetype);
5552 if (!parser_next(parser)) {
5553 parseerror(parser, "error after variable declaration");
5559 if (parser->tok == ',')
5563 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5566 parseerror(parser, "missing comma or semicolon while parsing variables");
5570 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5571 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5572 "initializing expression turns variable `%s` into a constant in this standard",
5579 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5580 if (parser->tok != '=') {
5581 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5585 if (!parser_next(parser)) {
5586 parseerror(parser, "error parsing initializer");
5590 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5591 parseerror(parser, "expected '=' before function body in this standard");
5594 if (parser->tok == '#') {
5595 ast_function *func = NULL;
5596 ast_value *number = NULL;
5602 parseerror(parser, "cannot declare builtins within functions");
5605 if (var->expression.vtype != TYPE_FUNCTION) {
5606 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5609 if (!parser_next(parser)) {
5610 parseerror(parser, "expected builtin number");
5614 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5615 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5617 parseerror(parser, "builtin number expected");
5620 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5623 parseerror(parser, "builtin number must be a compile time constant");
5626 if (number->expression.vtype == TYPE_INTEGER)
5627 builtin_num = number->constval.vint;
5628 else if (number->expression.vtype == TYPE_FLOAT)
5629 builtin_num = number->constval.vfloat;
5632 parseerror(parser, "builtin number must be an integer constant");
5637 fractional = modff(builtin_num, &integral);
5638 if (builtin_num < 0 || fractional != 0) {
5639 parseerror(parser, "builtin number must be an integer greater than zero");
5643 /* we only want the integral part anyways */
5644 builtin_num = integral;
5645 } else if (parser->tok == TOKEN_INTCONST) {
5646 builtin_num = parser_token(parser)->constval.i;
5648 parseerror(parser, "builtin number must be a compile time constant");
5652 if (var->hasvalue) {
5653 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5654 "builtin `%s` has already been defined\n"
5655 " -> previous declaration here: %s:%i",
5656 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5660 func = ast_function_new(ast_ctx(var), var->name, var);
5662 parseerror(parser, "failed to allocate function for `%s`", var->name);
5665 vec_push(parser->functions, func);
5667 func->builtin = -builtin_num-1;
5670 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5671 ? (parser->tok != ',' && parser->tok != ';')
5672 : (!parser_next(parser)))
5674 parseerror(parser, "expected comma or semicolon");
5676 ast_function_delete(func);
5677 var->constval.vfunc = NULL;
5681 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5684 /* Note that fteqcc and most others don't even *have*
5685 * local arrays, so this is not a high priority.
5687 parseerror(parser, "TODO: initializers for local arrays");
5691 var->hasvalue = true;
5692 if (!parse_array(parser, var))
5695 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5698 parseerror(parser, "cannot declare functions within functions");
5703 ast_ctx(proto) = parser_ctx(parser);
5705 if (!parse_function_body(parser, var))
5707 ast_delete(basetype);
5708 for (i = 0; i < vec_size(parser->gotos); ++i)
5709 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5710 vec_free(parser->gotos);
5711 vec_free(parser->labels);
5714 ast_expression *cexp;
5717 cexp = parse_expression_leave(parser, true, false, false);
5722 cval = (ast_value*)cexp;
5723 if (cval != parser->nil &&
5724 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5727 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5731 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5732 qualifier != CV_VAR)
5734 var->cvq = CV_CONST;
5736 if (cval == parser->nil)
5737 var->expression.flags |= AST_FLAG_INITIALIZED;
5740 var->hasvalue = true;
5741 if (cval->expression.vtype == TYPE_STRING)
5742 var->constval.vstring = parser_strdup(cval->constval.vstring);
5743 else if (cval->expression.vtype == TYPE_FIELD)
5744 var->constval.vfield = cval;
5746 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5752 shunt sy = { NULL, NULL, NULL, NULL };
5755 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5756 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5757 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5758 if (!parser_sy_apply_operator(parser, &sy))
5761 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5762 parseerror(parser, "internal error: leaked operands");
5763 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5774 if (parser->tok == ',') {
5775 if (!parser_next(parser)) {
5776 parseerror(parser, "expected another variable");
5780 if (parser->tok != TOKEN_IDENT) {
5781 parseerror(parser, "expected another variable");
5784 var = ast_value_copy(basetype);
5786 ast_value_set_name(var, parser_tokval(parser));
5787 if (!parser_next(parser)) {
5788 parseerror(parser, "error parsing variable declaration");
5794 if (parser->tok != ';') {
5795 parseerror(parser, "missing semicolon after variables");
5799 if (!parser_next(parser)) {
5800 parseerror(parser, "parse error after variable declaration");
5804 ast_delete(basetype);
5808 if (cleanvar && var)
5810 ast_delete(basetype);
5814 ast_delete(basetype);
5815 if (cleanvar && var)
5817 if (me[0]) ast_member_delete(me[0]);
5818 if (me[1]) ast_member_delete(me[1]);
5819 if (me[2]) ast_member_delete(me[2]);
5823 static bool parser_global_statement(parser_t *parser)
5827 bool is_static = false;
5828 uint32_t qflags = 0;
5829 ast_value *istype = NULL;
5830 char *vstring = NULL;
5832 if (parser->tok == TOKEN_IDENT)
5833 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5835 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5837 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5839 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5841 if (cvq == CV_WRONG)
5843 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5845 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5847 return parse_enum(parser);
5849 else if (parser->tok == TOKEN_KEYWORD)
5851 if (!strcmp(parser_tokval(parser), "typedef")) {
5852 if (!parser_next(parser)) {
5853 parseerror(parser, "expected type definition after 'typedef'");
5856 return parse_typedef(parser);
5858 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5861 else if (parser->tok == '#')
5863 return parse_pragma(parser);
5865 else if (parser->tok == '$')
5867 if (!parser_next(parser)) {
5868 parseerror(parser, "parse error");
5874 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5880 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5882 return util_crc16(old, str, strlen(str));
5885 static void progdefs_crc_file(const char *str)
5887 /* write to progdefs.h here */
5891 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5893 old = progdefs_crc_sum(old, str);
5894 progdefs_crc_file(str);
5898 static void generate_checksum(parser_t *parser, ir_builder *ir)
5900 uint16_t crc = 0xFFFF;
5904 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5905 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5907 progdefs_crc_file("\tint\tpad;\n");
5908 progdefs_crc_file("\tint\tofs_return[3];\n");
5909 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5910 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5911 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5912 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5913 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5914 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5915 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5916 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5918 for (i = 0; i < parser->crc_globals; ++i) {
5919 if (!ast_istype(parser->globals[i], ast_value))
5921 value = (ast_value*)(parser->globals[i]);
5922 switch (value->expression.vtype) {
5923 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5924 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5925 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5926 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5928 crc = progdefs_crc_both(crc, "\tint\t");
5931 crc = progdefs_crc_both(crc, value->name);
5932 crc = progdefs_crc_both(crc, ";\n");
5934 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5935 for (i = 0; i < parser->crc_fields; ++i) {
5936 if (!ast_istype(parser->fields[i], ast_value))
5938 value = (ast_value*)(parser->fields[i]);
5939 switch (value->expression.next->vtype) {
5940 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5941 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5942 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5943 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5945 crc = progdefs_crc_both(crc, "\tint\t");
5948 crc = progdefs_crc_both(crc, value->name);
5949 crc = progdefs_crc_both(crc, ";\n");
5951 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5952 ir->code->crc = crc;
5955 parser_t *parser_create()
5958 lex_ctx_t empty_ctx;
5961 parser = (parser_t*)mem_a(sizeof(parser_t));
5965 memset(parser, 0, sizeof(*parser));
5967 for (i = 0; i < operator_count; ++i) {
5968 if (operators[i].id == opid1('=')) {
5969 parser->assign_op = operators+i;
5973 if (!parser->assign_op) {
5974 con_err("internal error: initializing parser: failed to find assign operator\n");
5979 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5980 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5981 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5982 vec_push(parser->_blocktypedefs, 0);
5984 parser->aliases = util_htnew(PARSER_HT_SIZE);
5987 vec_push(parser->correct_variables, correct_trie_new());
5988 vec_push(parser->correct_variables_score, NULL);
5990 empty_ctx.file = "<internal>";
5992 empty_ctx.column = 0;
5993 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5994 parser->nil->cvq = CV_CONST;
5995 if (OPTS_FLAG(UNTYPED_NIL))
5996 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5998 parser->max_param_count = 1;
6000 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6001 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6002 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6004 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6005 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6006 parser->reserved_version->cvq = CV_CONST;
6007 parser->reserved_version->hasvalue = true;
6008 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6009 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6011 parser->reserved_version = NULL;
6014 parser->fold = fold_init (parser);
6015 parser->intrin = intrin_init(parser);
6019 static bool parser_compile(parser_t *parser)
6021 /* initial lexer/parser state */
6022 parser->lex->flags.noops = true;
6024 if (parser_next(parser))
6026 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6028 if (!parser_global_statement(parser)) {
6029 if (parser->tok == TOKEN_EOF)
6030 parseerror(parser, "unexpected end of file");
6031 else if (compile_errors)
6032 parseerror(parser, "there have been errors, bailing out");
6033 lex_close(parser->lex);
6039 parseerror(parser, "parse error");
6040 lex_close(parser->lex);
6045 lex_close(parser->lex);
6048 return !compile_errors;
6051 bool parser_compile_file(parser_t *parser, const char *filename)
6053 parser->lex = lex_open(filename);
6055 con_err("failed to open file \"%s\"\n", filename);
6058 return parser_compile(parser);
6061 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6063 parser->lex = lex_open_string(str, len, name);
6065 con_err("failed to create lexer for string \"%s\"\n", name);
6068 return parser_compile(parser);
6071 static void parser_remove_ast(parser_t *parser)
6074 if (parser->ast_cleaned)
6076 parser->ast_cleaned = true;
6077 for (i = 0; i < vec_size(parser->accessors); ++i) {
6078 ast_delete(parser->accessors[i]->constval.vfunc);
6079 parser->accessors[i]->constval.vfunc = NULL;
6080 ast_delete(parser->accessors[i]);
6082 for (i = 0; i < vec_size(parser->functions); ++i) {
6083 ast_delete(parser->functions[i]);
6085 for (i = 0; i < vec_size(parser->fields); ++i) {
6086 ast_delete(parser->fields[i]);
6088 for (i = 0; i < vec_size(parser->globals); ++i) {
6089 ast_delete(parser->globals[i]);
6091 vec_free(parser->accessors);
6092 vec_free(parser->functions);
6093 vec_free(parser->globals);
6094 vec_free(parser->fields);
6096 for (i = 0; i < vec_size(parser->variables); ++i)
6097 util_htdel(parser->variables[i]);
6098 vec_free(parser->variables);
6099 vec_free(parser->_blocklocals);
6100 vec_free(parser->_locals);
6103 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6104 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6106 vec_free(parser->correct_variables);
6107 vec_free(parser->correct_variables_score);
6109 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6110 ast_delete(parser->_typedefs[i]);
6111 vec_free(parser->_typedefs);
6112 for (i = 0; i < vec_size(parser->typedefs); ++i)
6113 util_htdel(parser->typedefs[i]);
6114 vec_free(parser->typedefs);
6115 vec_free(parser->_blocktypedefs);
6117 vec_free(parser->_block_ctx);
6119 vec_free(parser->labels);
6120 vec_free(parser->gotos);
6121 vec_free(parser->breaks);
6122 vec_free(parser->continues);
6124 ast_value_delete(parser->nil);
6126 ast_value_delete(parser->const_vec[0]);
6127 ast_value_delete(parser->const_vec[1]);
6128 ast_value_delete(parser->const_vec[2]);
6130 if (parser->reserved_version)
6131 ast_value_delete(parser->reserved_version);
6133 util_htdel(parser->aliases);
6134 fold_cleanup(parser->fold);
6135 intrin_cleanup(parser->intrin);
6138 void parser_cleanup(parser_t *parser)
6140 parser_remove_ast(parser);
6144 bool parser_finish(parser_t *parser, const char *output)
6150 if (compile_errors) {
6151 con_out("*** there were compile errors\n");
6155 ir = ir_builder_new("gmqcc_out");
6157 con_out("failed to allocate builder\n");
6161 for (i = 0; i < vec_size(parser->fields); ++i) {
6164 if (!ast_istype(parser->fields[i], ast_value))
6166 field = (ast_value*)parser->fields[i];
6167 hasvalue = field->hasvalue;
6168 field->hasvalue = false;
6169 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6170 con_out("failed to generate field %s\n", field->name);
6171 ir_builder_delete(ir);
6176 ast_expression *subtype;
6177 field->hasvalue = true;
6178 subtype = field->expression.next;
6179 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6180 if (subtype->vtype == TYPE_FIELD)
6181 ifld->fieldtype = subtype->next->vtype;
6182 else if (subtype->vtype == TYPE_FUNCTION)
6183 ifld->outtype = subtype->next->vtype;
6184 (void)!ir_value_set_field(field->ir_v, ifld);
6187 for (i = 0; i < vec_size(parser->globals); ++i) {
6189 if (!ast_istype(parser->globals[i], ast_value))
6191 asvalue = (ast_value*)(parser->globals[i]);
6192 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6193 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6194 "unused global: `%s`", asvalue->name);
6196 if (!ast_global_codegen(asvalue, ir, false)) {
6197 con_out("failed to generate global %s\n", asvalue->name);
6198 ir_builder_delete(ir);
6202 /* Build function vararg accessor ast tree now before generating
6203 * immediates, because the accessors may add new immediates
6205 for (i = 0; i < vec_size(parser->functions); ++i) {
6206 ast_function *f = parser->functions[i];
6208 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6209 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6210 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6211 con_out("failed to generate vararg setter for %s\n", f->name);
6212 ir_builder_delete(ir);
6215 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6216 con_out("failed to generate vararg getter for %s\n", f->name);
6217 ir_builder_delete(ir);
6221 ast_delete(f->varargs);
6226 /* Now we can generate immediates */
6227 if (!fold_generate(parser->fold, ir))
6230 for (i = 0; i < vec_size(parser->globals); ++i) {
6232 if (!ast_istype(parser->globals[i], ast_value))
6234 asvalue = (ast_value*)(parser->globals[i]);
6235 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6237 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6238 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6239 "uninitialized constant: `%s`",
6241 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6242 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6243 "uninitialized global: `%s`",
6246 if (!ast_generate_accessors(asvalue, ir)) {
6247 ir_builder_delete(ir);
6251 for (i = 0; i < vec_size(parser->fields); ++i) {
6253 asvalue = (ast_value*)(parser->fields[i]->next);
6255 if (!ast_istype((ast_expression*)asvalue, ast_value))
6257 if (asvalue->expression.vtype != TYPE_ARRAY)
6259 if (!ast_generate_accessors(asvalue, ir)) {
6260 ir_builder_delete(ir);
6264 if (parser->reserved_version &&
6265 !ast_global_codegen(parser->reserved_version, ir, false))
6267 con_out("failed to generate reserved::version");
6268 ir_builder_delete(ir);
6271 for (i = 0; i < vec_size(parser->functions); ++i) {
6272 ast_function *f = parser->functions[i];
6273 if (!ast_function_codegen(f, ir)) {
6274 con_out("failed to generate function %s\n", f->name);
6275 ir_builder_delete(ir);
6280 generate_checksum(parser, ir);
6282 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6283 ir_builder_dump(ir, con_out);
6284 for (i = 0; i < vec_size(parser->functions); ++i) {
6285 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6286 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6287 ir_builder_delete(ir);
6291 parser_remove_ast(parser);
6293 if (compile_Werrors) {
6294 con_out("*** there were warnings treated as errors\n");
6295 compile_show_werrors();
6300 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6301 ir_builder_dump(ir, con_out);
6303 if (!ir_builder_generate(ir, output)) {
6304 con_out("*** failed to generate output file\n");
6305 ir_builder_delete(ir);
6309 ir_builder_delete(ir);