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)
378 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
382 if (exprs[0]->vtype == TYPE_VECTOR &&
383 exprs[1]->vtype == TYPE_NOEXPR)
385 if (exprs[1] == (ast_expression*)parser->const_vec[0])
386 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
387 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
388 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
389 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
390 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
392 compile_error(ctx, "access to invalid vector component");
396 else if (exprs[0]->vtype == TYPE_ENTITY) {
397 if (exprs[1]->vtype != TYPE_FIELD) {
398 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
401 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
403 else if (exprs[0]->vtype == TYPE_VECTOR) {
404 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
408 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
414 if (exprs[0]->vtype != TYPE_ARRAY &&
415 !(exprs[0]->vtype == TYPE_FIELD &&
416 exprs[0]->next->vtype == TYPE_ARRAY))
418 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
419 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
422 if (exprs[1]->vtype != TYPE_FLOAT) {
423 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
424 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
427 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
428 if (rotate_entfield_array_index_nodes(&out))
431 /* This is not broken in fteqcc anymore */
432 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
433 /* this error doesn't need to make us bail out */
434 (void)!parsewarning(parser, WARN_EXTENSIONS,
435 "accessing array-field members of an entity without parenthesis\n"
436 " -> this is an extension from -std=gmqcc");
443 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
444 vec_push(sy->out, syexp(ctx, exprs[0]));
445 vec_push(sy->out, syexp(ctx, exprs[1]));
446 vec_last(sy->argc)++;
450 if (!ast_block_add_expr(blocks[0], exprs[1]))
453 blocks[0] = ast_block_new(ctx);
454 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
455 !ast_block_add_expr(blocks[0], exprs[1]))
460 ast_block_set_type(blocks[0], exprs[1]);
462 vec_push(sy->out, syblock(ctx, blocks[0]));
469 if ((out = fold_op(parser->fold, op, exprs)))
471 if (exprs[0]->vtype != TYPE_FLOAT &&
472 exprs[0]->vtype != TYPE_VECTOR) {
473 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
474 type_name[exprs[0]->vtype]);
477 out = (ast_expression*)ast_unary_new(ctx, (VINSTR_NEG_F-TYPE_FLOAT) + exprs[0]->vtype, exprs[0]);
481 if (!(out = fold_op(parser->fold, op, exprs))) {
482 switch (exprs[0]->vtype) {
484 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
487 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
490 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
491 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
493 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
495 /* we don't constant-fold NOT for these types */
497 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
500 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
503 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
504 type_name[exprs[0]->vtype]);
511 if (exprs[0]->vtype != exprs[1]->vtype ||
512 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
514 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
515 type_name[exprs[0]->vtype],
516 type_name[exprs[1]->vtype]);
519 if (!(out = fold_op(parser->fold, op, exprs))) {
520 switch (exprs[0]->vtype) {
522 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
525 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
528 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
529 type_name[exprs[0]->vtype],
530 type_name[exprs[1]->vtype]);
536 if (exprs[0]->vtype != exprs[1]->vtype ||
537 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
539 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
540 type_name[exprs[1]->vtype],
541 type_name[exprs[0]->vtype]);
544 if (!(out = fold_op(parser->fold, op, exprs))) {
545 switch (exprs[0]->vtype) {
547 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
550 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
553 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
554 type_name[exprs[1]->vtype],
555 type_name[exprs[0]->vtype]);
561 if (exprs[0]->vtype != exprs[1]->vtype &&
562 !(exprs[0]->vtype == TYPE_VECTOR &&
563 exprs[1]->vtype == TYPE_FLOAT) &&
564 !(exprs[1]->vtype == TYPE_VECTOR &&
565 exprs[0]->vtype == TYPE_FLOAT)
568 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
569 type_name[exprs[1]->vtype],
570 type_name[exprs[0]->vtype]);
573 if (!(out = fold_op(parser->fold, op, exprs))) {
574 switch (exprs[0]->vtype) {
576 if (exprs[1]->vtype == TYPE_VECTOR)
577 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
579 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
582 if (exprs[1]->vtype == TYPE_FLOAT)
583 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
585 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
588 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
589 type_name[exprs[1]->vtype],
590 type_name[exprs[0]->vtype]);
597 if (exprs[1]->vtype != TYPE_FLOAT) {
598 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
599 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
600 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
603 if (!(out = fold_op(parser->fold, op, exprs))) {
604 if (exprs[0]->vtype == TYPE_FLOAT)
605 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
607 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
608 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
609 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
616 if (NotSameType(TYPE_FLOAT)) {
617 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
618 type_name[exprs[0]->vtype],
619 type_name[exprs[1]->vtype]);
621 } else if (!(out = fold_op(parser->fold, op, exprs))) {
622 /* generate a call to __builtin_mod */
623 ast_expression *mod = intrin_func(parser->intrin, "mod");
624 ast_call *call = NULL;
625 if (!mod) return false; /* can return null for missing floor */
627 call = ast_call_new(parser_ctx(parser), mod);
628 vec_push(call->params, exprs[0]);
629 vec_push(call->params, exprs[1]);
631 out = (ast_expression*)call;
636 compile_error(ctx, "%= is unimplemented");
642 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
643 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
644 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
646 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
647 type_name[exprs[0]->vtype],
648 type_name[exprs[1]->vtype]);
652 if (!(out = fold_op(parser->fold, op, exprs))) {
654 * IF the first expression is float, the following will be too
655 * since scalar ^ vector is not allowed.
657 if (exprs[0]->vtype == TYPE_FLOAT) {
658 out = (ast_expression*)ast_binary_new(ctx,
659 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
663 * The first is a vector: vector is allowed to bitop with vector and
664 * with scalar, branch here for the second operand.
666 if (exprs[1]->vtype == TYPE_VECTOR) {
668 * Bitop all the values of the vector components against the
669 * vectors components in question.
671 out = (ast_expression*)ast_binary_new(ctx,
672 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
675 out = (ast_expression*)ast_binary_new(ctx,
676 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
685 case opid3('<','<','='):
686 case opid3('>','>','='):
687 if(!(out = fold_op(parser->fold, op, exprs))) {
688 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
694 generated_op += 1; /* INSTR_OR */
696 generated_op += INSTR_AND;
697 if (!(out = fold_op(parser->fold, op, exprs))) {
698 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
699 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
700 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
701 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
704 for (i = 0; i < 2; ++i) {
705 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
706 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
708 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
710 exprs[i] = out; out = NULL;
711 if (OPTS_FLAG(PERL_LOGIC)) {
712 /* here we want to keep the right expressions' type */
716 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
717 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
721 exprs[i] = out; out = NULL;
722 if (OPTS_FLAG(PERL_LOGIC)) {
723 /* here we want to keep the right expressions' type */
728 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
733 if (vec_last(sy->paren) != PAREN_TERNARY2) {
734 compile_error(ctx, "mismatched parenthesis/ternary");
738 if (!ast_compare_type(exprs[1], exprs[2])) {
739 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
740 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
741 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
744 if (!(out = fold_op(parser->fold, op, exprs)))
745 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
748 case opid2('*', '*'):
749 if (NotSameType(TYPE_FLOAT)) {
750 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
751 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
752 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
757 if (!(out = fold_op(parser->fold, op, exprs))) {
758 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
759 vec_push(gencall->params, exprs[0]);
760 vec_push(gencall->params, exprs[1]);
761 out = (ast_expression*)gencall;
765 case opid2('>', '<'):
766 if (NotSameType(TYPE_VECTOR)) {
767 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
768 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
769 compile_error(ctx, "invalid types used in cross product: %s and %s",
774 if (!(out = fold_op(parser->fold, op, exprs))) {
775 out = (ast_expression*)ast_binary_new(
785 case opid3('<','=','>'): /* -1, 0, or 1 */
786 if (NotSameType(TYPE_FLOAT)) {
787 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
788 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
789 compile_error(ctx, "invalid types used in comparision: %s and %s",
795 if (!(out = fold_op(parser->fold, op, exprs))) {
796 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
798 eq->refs = AST_REF_NONE;
801 out = (ast_expression*)ast_ternary_new(ctx,
802 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
804 (ast_expression*)parser->fold->imm_float[2],
807 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
809 (ast_expression*)parser->fold->imm_float[0],
812 (ast_expression*)parser->fold->imm_float[1]
822 generated_op += 1; /* INSTR_GT */
824 generated_op += 1; /* INSTR_LT */
825 case opid2('>', '='):
826 generated_op += 1; /* INSTR_GE */
827 case opid2('<', '='):
828 generated_op += INSTR_LE;
829 if (NotSameType(TYPE_FLOAT)) {
830 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
831 type_name[exprs[0]->vtype],
832 type_name[exprs[1]->vtype]);
835 if (!(out = fold_op(parser->fold, op, exprs)))
836 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
838 case opid2('!', '='):
839 if (exprs[0]->vtype != exprs[1]->vtype) {
840 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
841 type_name[exprs[0]->vtype],
842 type_name[exprs[1]->vtype]);
845 if (!(out = fold_op(parser->fold, op, exprs)))
846 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
848 case opid2('=', '='):
849 if (exprs[0]->vtype != exprs[1]->vtype) {
850 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
851 type_name[exprs[0]->vtype],
852 type_name[exprs[1]->vtype]);
855 if (!(out = fold_op(parser->fold, op, exprs)))
856 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
860 if (ast_istype(exprs[0], ast_entfield)) {
861 ast_expression *field = ((ast_entfield*)exprs[0])->field;
862 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
863 exprs[0]->vtype == TYPE_FIELD &&
864 exprs[0]->next->vtype == TYPE_VECTOR)
866 assignop = type_storep_instr[TYPE_VECTOR];
869 assignop = type_storep_instr[exprs[0]->vtype];
870 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
872 ast_type_to_string(field->next, ty1, sizeof(ty1));
873 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
874 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
875 field->next->vtype == TYPE_FUNCTION &&
876 exprs[1]->vtype == TYPE_FUNCTION)
878 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
879 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
882 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
887 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
888 exprs[0]->vtype == TYPE_FIELD &&
889 exprs[0]->next->vtype == TYPE_VECTOR)
891 assignop = type_store_instr[TYPE_VECTOR];
894 assignop = type_store_instr[exprs[0]->vtype];
897 if (assignop == VINSTR_END) {
898 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
899 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
900 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
902 else if (!ast_compare_type(exprs[0], exprs[1]))
904 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
905 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
906 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
907 exprs[0]->vtype == TYPE_FUNCTION &&
908 exprs[1]->vtype == TYPE_FUNCTION)
910 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
911 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
914 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
917 (void)check_write_to(ctx, exprs[0]);
918 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
920 case opid3('+','+','P'):
921 case opid3('-','-','P'):
923 if (exprs[0]->vtype != TYPE_FLOAT) {
924 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
925 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
928 if (op->id == opid3('+','+','P'))
932 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
933 if (ast_istype(exprs[0], ast_entfield)) {
934 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
936 (ast_expression*)parser->fold->imm_float[1]);
938 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
940 (ast_expression*)parser->fold->imm_float[1]);
943 case opid3('S','+','+'):
944 case opid3('S','-','-'):
946 if (exprs[0]->vtype != TYPE_FLOAT) {
947 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
948 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
951 if (op->id == opid3('S','+','+')) {
958 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
959 if (ast_istype(exprs[0], ast_entfield)) {
960 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
962 (ast_expression*)parser->fold->imm_float[1]);
964 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
966 (ast_expression*)parser->fold->imm_float[1]);
970 out = (ast_expression*)ast_binary_new(ctx, subop,
972 (ast_expression*)parser->fold->imm_float[1]);
976 if (exprs[0]->vtype != exprs[1]->vtype ||
977 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
979 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
980 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
981 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
985 (void)check_write_to(ctx, exprs[0]);
986 if (ast_istype(exprs[0], ast_entfield))
987 assignop = type_storep_instr[exprs[0]->vtype];
989 assignop = type_store_instr[exprs[0]->vtype];
990 switch (exprs[0]->vtype) {
992 out = (ast_expression*)ast_binstore_new(ctx, assignop,
993 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
997 out = (ast_expression*)ast_binstore_new(ctx, assignop,
998 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1002 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1003 type_name[exprs[0]->vtype],
1004 type_name[exprs[1]->vtype]);
1008 case opid2('*','='):
1009 case opid2('/','='):
1010 if (exprs[1]->vtype != TYPE_FLOAT ||
1011 !(exprs[0]->vtype == TYPE_FLOAT ||
1012 exprs[0]->vtype == TYPE_VECTOR))
1014 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1015 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1016 compile_error(ctx, "invalid types used in expression: %s and %s",
1020 (void)check_write_to(ctx, exprs[0]);
1021 if (ast_istype(exprs[0], ast_entfield))
1022 assignop = type_storep_instr[exprs[0]->vtype];
1024 assignop = type_store_instr[exprs[0]->vtype];
1025 switch (exprs[0]->vtype) {
1027 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1028 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1029 exprs[0], exprs[1]);
1032 if (op->id == opid2('*','=')) {
1033 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1034 exprs[0], exprs[1]);
1036 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1037 (ast_expression*)parser->fold->imm_float[1],
1040 compile_error(ctx, "internal error: failed to generate division");
1043 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1048 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1049 type_name[exprs[0]->vtype],
1050 type_name[exprs[1]->vtype]);
1054 case opid2('&','='):
1055 case opid2('|','='):
1056 case opid2('^','='):
1057 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1058 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1059 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1060 compile_error(ctx, "invalid types used in expression: %s and %s",
1064 (void)check_write_to(ctx, exprs[0]);
1065 if (ast_istype(exprs[0], ast_entfield))
1066 assignop = type_storep_instr[exprs[0]->vtype];
1068 assignop = type_store_instr[exprs[0]->vtype];
1069 if (exprs[0]->vtype == TYPE_FLOAT)
1070 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1071 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1072 exprs[0], exprs[1]);
1074 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1075 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1076 exprs[0], exprs[1]);
1078 case opid3('&','~','='):
1079 /* This is like: a &= ~(b);
1080 * But QC has no bitwise-not, so we implement it as
1083 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1084 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1085 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1086 compile_error(ctx, "invalid types used in expression: %s and %s",
1090 if (ast_istype(exprs[0], ast_entfield))
1091 assignop = type_storep_instr[exprs[0]->vtype];
1093 assignop = type_store_instr[exprs[0]->vtype];
1094 if (exprs[0]->vtype == TYPE_FLOAT)
1095 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1097 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1100 (void)check_write_to(ctx, exprs[0]);
1101 if (exprs[0]->vtype == TYPE_FLOAT)
1102 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1104 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1105 asbinstore->keep_dest = true;
1106 out = (ast_expression*)asbinstore;
1109 case opid2('~', 'P'):
1110 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1111 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1112 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1115 if (!(out = fold_op(parser->fold, op, exprs))) {
1116 if (exprs[0]->vtype == TYPE_FLOAT) {
1117 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1119 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1126 compile_error(ctx, "failed to apply operator %s", op->op);
1130 vec_push(sy->out, syexp(ctx, out));
1134 static bool parser_close_call(parser_t *parser, shunt *sy)
1136 /* was a function call */
1137 ast_expression *fun;
1138 ast_value *funval = NULL;
1142 size_t paramcount, i;
1145 fid = vec_last(sy->ops).off;
1146 vec_shrinkby(sy->ops, 1);
1148 /* out[fid] is the function
1149 * everything above is parameters...
1151 if (!vec_size(sy->argc)) {
1152 parseerror(parser, "internal error: no argument counter available");
1156 paramcount = vec_last(sy->argc);
1159 if (vec_size(sy->out) < fid) {
1160 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1161 (unsigned long)vec_size(sy->out),
1163 (unsigned long)paramcount);
1168 * TODO handle this at the intrinsic level with an ast_intrinsic
1171 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1173 if (fid+2 != vec_size(sy->out) ||
1174 vec_last(sy->out).block)
1176 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1179 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1180 ast_unref(vec_last(sy->out).out);
1181 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1182 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1183 vec_shrinkby(sy->out, 1);
1188 * Now we need to determine if the function that is being called is
1189 * an intrinsic so we can evaluate if the arguments to it are constant
1190 * and than fruitfully fold them.
1192 #define fold_can_1(X) \
1193 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1194 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1196 if (fid + 1 < vec_size(sy->out))
1199 for (i = 0; i < paramcount; ++i) {
1200 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1207 * All is well which ends well, if we make it into here we can ignore the
1208 * intrinsic call and just evaluate it i.e constant fold it.
1210 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1211 ast_expression **exprs = NULL;
1212 ast_expression *foldval = NULL;
1214 for (i = 0; i < paramcount; i++)
1215 vec_push(exprs, sy->out[fid+1 + i].out);
1217 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1223 * Blub: what sorts of unreffing and resizing of
1224 * sy->out should I be doing here?
1226 sy->out[fid] = syexp(foldval->node.context, foldval);
1227 vec_shrinkby(sy->out, 1);
1234 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1239 if (fid+1 + paramcount != vec_size(sy->out)) {
1240 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1241 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1245 for (i = 0; i < paramcount; ++i)
1246 vec_push(call->params, sy->out[fid+1 + i].out);
1247 vec_shrinkby(sy->out, paramcount);
1248 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1249 if (parser->max_param_count < paramcount)
1250 parser->max_param_count = paramcount;
1252 if (ast_istype(fun, ast_value)) {
1253 funval = (ast_value*)fun;
1254 if ((fun->flags & AST_FLAG_VARIADIC) &&
1255 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1257 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1261 /* overwrite fid, the function, with a call */
1262 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1264 if (fun->vtype != TYPE_FUNCTION) {
1265 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1270 parseerror(parser, "could not determine function return type");
1273 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1275 if (fun->flags & AST_FLAG_DEPRECATED) {
1277 return !parsewarning(parser, WARN_DEPRECATED,
1278 "call to function (which is marked deprecated)\n",
1279 "-> it has been declared here: %s:%i",
1280 ast_ctx(fun).file, ast_ctx(fun).line);
1283 return !parsewarning(parser, WARN_DEPRECATED,
1284 "call to `%s` (which is marked deprecated)\n"
1285 "-> `%s` declared here: %s:%i",
1286 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1288 return !parsewarning(parser, WARN_DEPRECATED,
1289 "call to `%s` (deprecated: %s)\n"
1290 "-> `%s` declared here: %s:%i",
1291 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1295 if (vec_size(fun->params) != paramcount &&
1296 !((fun->flags & AST_FLAG_VARIADIC) &&
1297 vec_size(fun->params) < paramcount))
1299 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1301 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1302 "too %s parameters for call to %s: expected %i, got %i\n"
1303 " -> `%s` has been declared here: %s:%i",
1304 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1305 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1307 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1308 "too %s parameters for function call: expected %i, got %i\n"
1309 " -> it has been declared here: %s:%i",
1310 fewmany, (int)vec_size(fun->params), (int)paramcount,
1311 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1318 static bool parser_close_paren(parser_t *parser, shunt *sy)
1320 if (!vec_size(sy->ops)) {
1321 parseerror(parser, "unmatched closing paren");
1325 while (vec_size(sy->ops)) {
1326 if (vec_last(sy->ops).isparen) {
1327 if (vec_last(sy->paren) == PAREN_FUNC) {
1329 if (!parser_close_call(parser, sy))
1333 if (vec_last(sy->paren) == PAREN_EXPR) {
1335 if (!vec_size(sy->out)) {
1336 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1337 vec_shrinkby(sy->ops, 1);
1340 vec_shrinkby(sy->ops, 1);
1343 if (vec_last(sy->paren) == PAREN_INDEX) {
1345 /* pop off the parenthesis */
1346 vec_shrinkby(sy->ops, 1);
1347 /* then apply the index operator */
1348 if (!parser_sy_apply_operator(parser, sy))
1352 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1353 vec_last(sy->paren) = PAREN_TERNARY2;
1354 /* pop off the parenthesis */
1355 vec_shrinkby(sy->ops, 1);
1358 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1361 if (!parser_sy_apply_operator(parser, sy))
1367 static void parser_reclassify_token(parser_t *parser)
1370 if (parser->tok >= TOKEN_START)
1372 for (i = 0; i < operator_count; ++i) {
1373 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1374 parser->tok = TOKEN_OPERATOR;
1380 static ast_expression* parse_vararg_do(parser_t *parser)
1382 ast_expression *idx, *out;
1384 ast_value *funtype = parser->function->vtype;
1385 lex_ctx_t ctx = parser_ctx(parser);
1387 if (!parser->function->varargs) {
1388 parseerror(parser, "function has no variable argument list");
1392 if (!parser_next(parser) || parser->tok != '(') {
1393 parseerror(parser, "expected parameter index and type in parenthesis");
1396 if (!parser_next(parser)) {
1397 parseerror(parser, "error parsing parameter index");
1401 idx = parse_expression_leave(parser, true, false, false);
1405 if (parser->tok != ',') {
1406 if (parser->tok != ')') {
1408 parseerror(parser, "expected comma after parameter index");
1411 /* vararg piping: ...(start) */
1412 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1416 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1418 parseerror(parser, "expected typename for vararg");
1422 typevar = parse_typename(parser, NULL, NULL);
1428 if (parser->tok != ')') {
1430 ast_delete(typevar);
1431 parseerror(parser, "expected closing paren");
1435 if (funtype->expression.varparam &&
1436 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1440 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1441 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1442 compile_error(ast_ctx(typevar),
1443 "function was declared to take varargs of type `%s`, requested type is: %s",
1447 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1448 ast_type_adopt(out, typevar);
1449 ast_delete(typevar);
1453 static ast_expression* parse_vararg(parser_t *parser)
1455 bool old_noops = parser->lex->flags.noops;
1457 ast_expression *out;
1459 parser->lex->flags.noops = true;
1460 out = parse_vararg_do(parser);
1462 parser->lex->flags.noops = old_noops;
1466 /* not to be exposed */
1467 bool ftepp_predef_exists(const char *name);
1468 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1470 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1471 parser->tok == TOKEN_IDENT &&
1472 !strcmp(parser_tokval(parser), "_"))
1474 /* a translatable string */
1477 parser->lex->flags.noops = true;
1478 if (!parser_next(parser) || parser->tok != '(') {
1479 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1482 parser->lex->flags.noops = false;
1483 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1484 parseerror(parser, "expected a constant string in translatable-string extension");
1487 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1490 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1492 if (!parser_next(parser) || parser->tok != ')') {
1493 parseerror(parser, "expected closing paren after translatable string");
1498 else if (parser->tok == TOKEN_DOTS)
1501 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1502 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1505 va = parse_vararg(parser);
1508 vec_push(sy->out, syexp(parser_ctx(parser), va));
1511 else if (parser->tok == TOKEN_FLOATCONST) {
1512 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1515 vec_push(sy->out, syexp(parser_ctx(parser), val));
1518 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1519 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1522 vec_push(sy->out, syexp(parser_ctx(parser), val));
1525 else if (parser->tok == TOKEN_STRINGCONST) {
1526 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1529 vec_push(sy->out, syexp(parser_ctx(parser), val));
1532 else if (parser->tok == TOKEN_VECTORCONST) {
1533 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1536 vec_push(sy->out, syexp(parser_ctx(parser), val));
1539 else if (parser->tok == TOKEN_IDENT)
1541 const char *ctoken = parser_tokval(parser);
1542 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1543 ast_expression *var;
1544 /* a_vector.{x,y,z} */
1545 if (!vec_size(sy->ops) ||
1546 !vec_last(sy->ops).etype ||
1547 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1549 /* When adding more intrinsics, fix the above condition */
1552 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1554 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1556 var = parser_find_var(parser, parser_tokval(parser));
1558 var = parser_find_field(parser, parser_tokval(parser));
1560 if (!var && with_labels) {
1561 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1563 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1564 var = (ast_expression*)lbl;
1565 vec_push(parser->labels, lbl);
1568 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1569 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1572 * now we try for the real intrinsic hashtable. If the string
1573 * begins with __builtin, we simply skip past it, otherwise we
1574 * use the identifier as is.
1576 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1577 var = intrin_func(parser->intrin, parser_tokval(parser));
1581 char *correct = NULL;
1585 * sometimes people use preprocessing predefs without enabling them
1586 * i've done this thousands of times already myself. Lets check for
1587 * it in the predef table. And diagnose it better :)
1589 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1590 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1595 * TODO: determine the best score for the identifier: be it
1596 * a variable, a field.
1598 * We should also consider adding correction tables for
1599 * other things as well.
1601 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1603 correct_init(&corr);
1605 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1606 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1607 if (strcmp(correct, parser_tokval(parser))) {
1614 correct_free(&corr);
1617 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1622 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1628 if (ast_istype(var, ast_value)) {
1629 ((ast_value*)var)->uses++;
1631 else if (ast_istype(var, ast_member)) {
1632 ast_member *mem = (ast_member*)var;
1633 if (ast_istype(mem->owner, ast_value))
1634 ((ast_value*)(mem->owner))->uses++;
1637 vec_push(sy->out, syexp(parser_ctx(parser), var));
1640 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1644 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1646 ast_expression *expr = NULL;
1649 bool wantop = false;
1650 /* only warn once about an assignment in a truth value because the current code
1651 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1653 bool warn_parenthesis = true;
1655 /* count the parens because an if starts with one, so the
1656 * end of a condition is an unmatched closing paren
1660 memset(&sy, 0, sizeof(sy));
1662 parser->lex->flags.noops = false;
1664 parser_reclassify_token(parser);
1668 if (parser->tok == TOKEN_TYPENAME) {
1669 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1673 if (parser->tok == TOKEN_OPERATOR)
1675 /* classify the operator */
1676 const oper_info *op;
1677 const oper_info *olast = NULL;
1679 for (o = 0; o < operator_count; ++o) {
1680 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1681 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1682 !strcmp(parser_tokval(parser), operators[o].op))
1687 if (o == operator_count) {
1688 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1691 /* found an operator */
1694 /* when declaring variables, a comma starts a new variable */
1695 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1696 /* fixup the token */
1701 /* a colon without a pervious question mark cannot be a ternary */
1702 if (!ternaries && op->id == opid2(':','?')) {
1707 if (op->id == opid1(',')) {
1708 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1709 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1713 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1714 olast = &operators[vec_last(sy.ops).etype-1];
1716 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1717 while (olast && op->prec < olast->prec)
1719 if (!parser_sy_apply_operator(parser, &sy))
1721 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1722 olast = &operators[vec_last(sy.ops).etype-1];
1727 #define IsAssignOp(x) (\
1728 (x) == opid1('=') || \
1729 (x) == opid2('+','=') || \
1730 (x) == opid2('-','=') || \
1731 (x) == opid2('*','=') || \
1732 (x) == opid2('/','=') || \
1733 (x) == opid2('%','=') || \
1734 (x) == opid2('&','=') || \
1735 (x) == opid2('|','=') || \
1736 (x) == opid3('&','~','=') \
1738 if (warn_parenthesis) {
1739 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1740 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1741 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1744 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1745 warn_parenthesis = false;
1748 if (olast && olast->id != op->id) {
1749 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1750 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1752 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1753 warn_parenthesis = false;
1755 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1756 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1758 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1759 warn_parenthesis = false;
1765 (op->prec < olast->prec) ||
1766 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1768 if (!parser_sy_apply_operator(parser, &sy))
1770 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1771 olast = &operators[vec_last(sy.ops).etype-1];
1776 if (op->id == opid1('(')) {
1778 size_t sycount = vec_size(sy.out);
1779 /* we expected an operator, this is the function-call operator */
1780 vec_push(sy.paren, PAREN_FUNC);
1781 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1782 vec_push(sy.argc, 0);
1784 vec_push(sy.paren, PAREN_EXPR);
1785 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1788 } else if (op->id == opid1('[')) {
1790 parseerror(parser, "unexpected array subscript");
1793 vec_push(sy.paren, PAREN_INDEX);
1794 /* push both the operator and the paren, this makes life easier */
1795 vec_push(sy.ops, syop(parser_ctx(parser), op));
1796 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1798 } else if (op->id == opid2('?',':')) {
1799 vec_push(sy.ops, syop(parser_ctx(parser), op));
1800 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1803 vec_push(sy.paren, PAREN_TERNARY1);
1804 } else if (op->id == opid2(':','?')) {
1805 if (!vec_size(sy.paren)) {
1806 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1809 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1810 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1813 if (!parser_close_paren(parser, &sy))
1815 vec_push(sy.ops, syop(parser_ctx(parser), op));
1819 vec_push(sy.ops, syop(parser_ctx(parser), op));
1820 wantop = !!(op->flags & OP_SUFFIX);
1823 else if (parser->tok == ')') {
1824 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1825 if (!parser_sy_apply_operator(parser, &sy))
1828 if (!vec_size(sy.paren))
1831 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1832 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1835 if (!parser_close_paren(parser, &sy))
1838 /* must be a function call without parameters */
1839 if (vec_last(sy.paren) != PAREN_FUNC) {
1840 parseerror(parser, "closing paren in invalid position");
1843 if (!parser_close_paren(parser, &sy))
1848 else if (parser->tok == '(') {
1849 parseerror(parser, "internal error: '(' should be classified as operator");
1852 else if (parser->tok == '[') {
1853 parseerror(parser, "internal error: '[' should be classified as operator");
1856 else if (parser->tok == ']') {
1857 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1858 if (!parser_sy_apply_operator(parser, &sy))
1861 if (!vec_size(sy.paren))
1863 if (vec_last(sy.paren) != PAREN_INDEX) {
1864 parseerror(parser, "mismatched parentheses, unexpected ']'");
1867 if (!parser_close_paren(parser, &sy))
1872 if (!parse_sya_operand(parser, &sy, with_labels))
1875 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1876 vec_last(sy.argc)++;
1881 /* in this case we might want to allow constant string concatenation */
1882 bool concatenated = false;
1883 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1884 ast_expression *lexpr = vec_last(sy.out).out;
1885 if (ast_istype(lexpr, ast_value)) {
1886 ast_value *last = (ast_value*)lexpr;
1887 if (last->isimm == true && last->cvq == CV_CONST &&
1888 last->hasvalue && last->expression.vtype == TYPE_STRING)
1890 char *newstr = NULL;
1891 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1892 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1894 concatenated = true;
1898 if (!concatenated) {
1899 parseerror(parser, "expected operator or end of statement");
1904 if (!parser_next(parser)) {
1907 if (parser->tok == ';' ||
1908 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1909 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1915 while (vec_size(sy.ops)) {
1916 if (!parser_sy_apply_operator(parser, &sy))
1920 parser->lex->flags.noops = true;
1921 if (vec_size(sy.out) != 1) {
1922 parseerror(parser, "expression expected");
1925 expr = sy.out[0].out;
1928 if (vec_size(sy.paren)) {
1929 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1937 parser->lex->flags.noops = true;
1938 for (i = 0; i < vec_size(sy.out); ++i) {
1940 ast_unref(sy.out[i].out);
1949 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1951 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1954 if (parser->tok != ';') {
1955 parseerror(parser, "semicolon expected after expression");
1959 if (!parser_next(parser)) {
1966 static void parser_enterblock(parser_t *parser)
1968 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1969 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1970 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1971 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1972 vec_push(parser->_block_ctx, parser_ctx(parser));
1975 vec_push(parser->correct_variables, correct_trie_new());
1976 vec_push(parser->correct_variables_score, NULL);
1979 static bool parser_leaveblock(parser_t *parser)
1982 size_t locals, typedefs;
1984 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1985 parseerror(parser, "internal error: parser_leaveblock with no block");
1989 util_htdel(vec_last(parser->variables));
1990 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1992 vec_pop(parser->variables);
1993 vec_pop(parser->correct_variables);
1994 vec_pop(parser->correct_variables_score);
1995 if (!vec_size(parser->_blocklocals)) {
1996 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2000 locals = vec_last(parser->_blocklocals);
2001 vec_pop(parser->_blocklocals);
2002 while (vec_size(parser->_locals) != locals) {
2003 ast_expression *e = vec_last(parser->_locals);
2004 ast_value *v = (ast_value*)e;
2005 vec_pop(parser->_locals);
2006 if (ast_istype(e, ast_value) && !v->uses) {
2007 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2012 typedefs = vec_last(parser->_blocktypedefs);
2013 while (vec_size(parser->_typedefs) != typedefs) {
2014 ast_delete(vec_last(parser->_typedefs));
2015 vec_pop(parser->_typedefs);
2017 util_htdel(vec_last(parser->typedefs));
2018 vec_pop(parser->typedefs);
2020 vec_pop(parser->_block_ctx);
2025 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2027 vec_push(parser->_locals, e);
2028 util_htset(vec_last(parser->variables), name, (void*)e);
2032 vec_last(parser->correct_variables),
2033 &vec_last(parser->correct_variables_score),
2038 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2040 vec_push(parser->globals, e);
2041 util_htset(parser->htglobals, name, e);
2045 parser->correct_variables[0],
2046 &parser->correct_variables_score[0],
2051 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2055 ast_expression *prev;
2057 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2059 ast_type_to_string(cond, ty, sizeof(ty));
2060 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2063 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2066 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2069 parseerror(parser, "internal error: failed to process condition");
2074 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2076 /* vector types need to be cast to true booleans */
2077 ast_binary *bin = (ast_binary*)cond;
2078 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2080 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2082 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2085 parseerror(parser, "internal error: failed to process condition");
2092 unary = (ast_unary*)cond;
2093 /* ast_istype dereferences cond, should test here for safety */
2094 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2096 cond = unary->operand;
2097 unary->operand = NULL;
2100 unary = (ast_unary*)cond;
2104 parseerror(parser, "internal error: failed to process condition");
2106 if (ifnot) *_ifnot = !*_ifnot;
2110 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2113 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2116 lex_ctx_t ctx = parser_ctx(parser);
2118 (void)block; /* not touching */
2120 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2121 if (!parser_next(parser)) {
2122 parseerror(parser, "expected condition or 'not'");
2125 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2127 if (!parser_next(parser)) {
2128 parseerror(parser, "expected condition in parenthesis");
2132 if (parser->tok != '(') {
2133 parseerror(parser, "expected 'if' condition in parenthesis");
2136 /* parse into the expression */
2137 if (!parser_next(parser)) {
2138 parseerror(parser, "expected 'if' condition after opening paren");
2141 /* parse the condition */
2142 cond = parse_expression_leave(parser, false, true, false);
2146 if (parser->tok != ')') {
2147 parseerror(parser, "expected closing paren after 'if' condition");
2151 /* parse into the 'then' branch */
2152 if (!parser_next(parser)) {
2153 parseerror(parser, "expected statement for on-true branch of 'if'");
2157 if (!parse_statement_or_block(parser, &ontrue)) {
2162 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2163 /* check for an else */
2164 if (!strcmp(parser_tokval(parser), "else")) {
2165 /* parse into the 'else' branch */
2166 if (!parser_next(parser)) {
2167 parseerror(parser, "expected on-false branch after 'else'");
2172 if (!parse_statement_or_block(parser, &onfalse)) {
2179 cond = process_condition(parser, cond, &ifnot);
2181 if (ontrue) ast_delete(ontrue);
2182 if (onfalse) ast_delete(onfalse);
2187 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2189 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2190 *out = (ast_expression*)ifthen;
2194 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2195 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2200 /* skip the 'while' and get the body */
2201 if (!parser_next(parser)) {
2202 if (OPTS_FLAG(LOOP_LABELS))
2203 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2205 parseerror(parser, "expected 'while' condition in parenthesis");
2209 if (parser->tok == ':') {
2210 if (!OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2212 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2213 parseerror(parser, "expected loop label");
2216 label = util_strdup(parser_tokval(parser));
2217 if (!parser_next(parser)) {
2219 parseerror(parser, "expected 'while' condition in parenthesis");
2224 if (parser->tok != '(') {
2225 parseerror(parser, "expected 'while' condition in parenthesis");
2229 vec_push(parser->breaks, label);
2230 vec_push(parser->continues, label);
2232 rv = parse_while_go(parser, block, out);
2235 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2236 parseerror(parser, "internal error: label stack corrupted");
2242 vec_pop(parser->breaks);
2243 vec_pop(parser->continues);
2248 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2251 ast_expression *cond, *ontrue;
2255 lex_ctx_t ctx = parser_ctx(parser);
2257 (void)block; /* not touching */
2259 /* parse into the expression */
2260 if (!parser_next(parser)) {
2261 parseerror(parser, "expected 'while' condition after opening paren");
2264 /* parse the condition */
2265 cond = parse_expression_leave(parser, false, true, false);
2269 if (parser->tok != ')') {
2270 parseerror(parser, "expected closing paren after 'while' condition");
2274 /* parse into the 'then' branch */
2275 if (!parser_next(parser)) {
2276 parseerror(parser, "expected while-loop body");
2280 if (!parse_statement_or_block(parser, &ontrue)) {
2285 cond = process_condition(parser, cond, &ifnot);
2290 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2291 *out = (ast_expression*)aloop;
2295 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2296 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2301 /* skip the 'do' and get the body */
2302 if (!parser_next(parser)) {
2303 if (OPTS_FLAG(LOOP_LABELS))
2304 parseerror(parser, "expected loop label or body");
2306 parseerror(parser, "expected loop body");
2310 if (parser->tok == ':') {
2311 if (!OPTS_FLAG(LOOP_LABELS))
2312 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2313 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2314 parseerror(parser, "expected loop label");
2317 label = util_strdup(parser_tokval(parser));
2318 if (!parser_next(parser)) {
2320 parseerror(parser, "expected loop body");
2325 vec_push(parser->breaks, label);
2326 vec_push(parser->continues, label);
2328 rv = parse_dowhile_go(parser, block, out);
2331 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2332 parseerror(parser, "internal error: label stack corrupted");
2335 * Test for NULL otherwise ast_delete dereferences null pointer
2343 vec_pop(parser->breaks);
2344 vec_pop(parser->continues);
2349 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2352 ast_expression *cond, *ontrue;
2356 lex_ctx_t ctx = parser_ctx(parser);
2358 (void)block; /* not touching */
2360 if (!parse_statement_or_block(parser, &ontrue))
2363 /* expect the "while" */
2364 if (parser->tok != TOKEN_KEYWORD ||
2365 strcmp(parser_tokval(parser), "while"))
2367 parseerror(parser, "expected 'while' and condition");
2372 /* skip the 'while' and check for opening paren */
2373 if (!parser_next(parser) || parser->tok != '(') {
2374 parseerror(parser, "expected 'while' condition in parenthesis");
2378 /* parse into the expression */
2379 if (!parser_next(parser)) {
2380 parseerror(parser, "expected 'while' condition after opening paren");
2384 /* parse the condition */
2385 cond = parse_expression_leave(parser, false, true, false);
2389 if (parser->tok != ')') {
2390 parseerror(parser, "expected closing paren after 'while' condition");
2396 if (!parser_next(parser) || parser->tok != ';') {
2397 parseerror(parser, "expected semicolon after condition");
2403 if (!parser_next(parser)) {
2404 parseerror(parser, "parse error");
2410 cond = process_condition(parser, cond, &ifnot);
2415 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2416 *out = (ast_expression*)aloop;
2420 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2421 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2426 /* skip the 'for' and check for opening paren */
2427 if (!parser_next(parser)) {
2428 if (OPTS_FLAG(LOOP_LABELS))
2429 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2431 parseerror(parser, "expected 'for' expressions in parenthesis");
2435 if (parser->tok == ':') {
2436 if (!OPTS_FLAG(LOOP_LABELS))
2437 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2438 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2439 parseerror(parser, "expected loop label");
2442 label = util_strdup(parser_tokval(parser));
2443 if (!parser_next(parser)) {
2445 parseerror(parser, "expected 'for' expressions in parenthesis");
2450 if (parser->tok != '(') {
2451 parseerror(parser, "expected 'for' expressions in parenthesis");
2455 vec_push(parser->breaks, label);
2456 vec_push(parser->continues, label);
2458 rv = parse_for_go(parser, block, out);
2461 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2462 parseerror(parser, "internal error: label stack corrupted");
2468 vec_pop(parser->breaks);
2469 vec_pop(parser->continues);
2473 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2476 ast_expression *initexpr, *cond, *increment, *ontrue;
2481 lex_ctx_t ctx = parser_ctx(parser);
2483 parser_enterblock(parser);
2490 /* parse into the expression */
2491 if (!parser_next(parser)) {
2492 parseerror(parser, "expected 'for' initializer after opening paren");
2497 if (parser->tok == TOKEN_IDENT)
2498 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2500 if (typevar || parser->tok == TOKEN_TYPENAME) {
2502 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2503 if (parsewarning(parser, WARN_EXTENSIONS,
2504 "current standard does not allow variable declarations in for-loop initializers"))
2508 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2511 else if (parser->tok != ';')
2513 initexpr = parse_expression_leave(parser, false, false, false);
2518 /* move on to condition */
2519 if (parser->tok != ';') {
2520 parseerror(parser, "expected semicolon after for-loop initializer");
2523 if (!parser_next(parser)) {
2524 parseerror(parser, "expected for-loop condition");
2528 /* parse the condition */
2529 if (parser->tok != ';') {
2530 cond = parse_expression_leave(parser, false, true, false);
2535 /* move on to incrementor */
2536 if (parser->tok != ';') {
2537 parseerror(parser, "expected semicolon after for-loop initializer");
2540 if (!parser_next(parser)) {
2541 parseerror(parser, "expected for-loop condition");
2545 /* parse the incrementor */
2546 if (parser->tok != ')') {
2547 lex_ctx_t condctx = parser_ctx(parser);
2548 increment = parse_expression_leave(parser, false, false, false);
2551 if (!ast_side_effects(increment)) {
2552 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2558 if (parser->tok != ')') {
2559 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2562 /* parse into the 'then' branch */
2563 if (!parser_next(parser)) {
2564 parseerror(parser, "expected for-loop body");
2567 if (!parse_statement_or_block(parser, &ontrue))
2571 cond = process_condition(parser, cond, &ifnot);
2575 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2576 *out = (ast_expression*)aloop;
2578 if (!parser_leaveblock(parser)) {
2584 if (initexpr) ast_unref(initexpr);
2585 if (cond) ast_unref(cond);
2586 if (increment) ast_unref(increment);
2587 (void)!parser_leaveblock(parser);
2591 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2593 ast_expression *exp = NULL;
2594 ast_expression *var = NULL;
2595 ast_return *ret = NULL;
2596 ast_value *retval = parser->function->return_value;
2597 ast_value *expected = parser->function->vtype;
2599 lex_ctx_t ctx = parser_ctx(parser);
2601 (void)block; /* not touching */
2603 if (!parser_next(parser)) {
2604 parseerror(parser, "expected return expression");
2608 /* return assignments */
2609 if (parser->tok == '=') {
2610 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2611 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2615 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2617 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2618 parseerror(parser, "invalid return type: `%s'", ty1);
2622 if (!parser_next(parser)) {
2623 parseerror(parser, "expected return assignment expression");
2627 if (!(exp = parse_expression_leave(parser, false, false, false)))
2630 /* prepare the return value */
2632 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2633 ast_type_adopt(retval, expected->expression.next);
2634 parser->function->return_value = retval;
2637 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2638 char ty1[1024], ty2[1024];
2639 ast_type_to_string(exp, ty1, sizeof(ty1));
2640 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2641 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2644 /* store to 'return' local variable */
2645 var = (ast_expression*)ast_store_new(
2647 type_store_instr[expected->expression.next->vtype],
2648 (ast_expression*)retval, exp);
2655 if (parser->tok != ';')
2656 parseerror(parser, "missing semicolon after return assignment");
2657 else if (!parser_next(parser))
2658 parseerror(parser, "parse error after return assignment");
2664 if (parser->tok != ';') {
2665 exp = parse_expression(parser, false, false);
2669 if (exp->vtype != TYPE_NIL &&
2670 exp->vtype != ((ast_expression*)expected)->next->vtype)
2672 parseerror(parser, "return with invalid expression");
2675 ret = ast_return_new(ctx, exp);
2681 if (!parser_next(parser))
2682 parseerror(parser, "parse error");
2684 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2686 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2688 ret = ast_return_new(ctx, (ast_expression*)retval);
2690 *out = (ast_expression*)ret;
2694 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2697 unsigned int levels = 0;
2698 lex_ctx_t ctx = parser_ctx(parser);
2699 const char **loops = (is_continue ? parser->continues : parser->breaks);
2701 (void)block; /* not touching */
2702 if (!parser_next(parser)) {
2703 parseerror(parser, "expected semicolon or loop label");
2707 if (!vec_size(loops)) {
2709 parseerror(parser, "`continue` can only be used inside loops");
2711 parseerror(parser, "`break` can only be used inside loops or switches");
2714 if (parser->tok == TOKEN_IDENT) {
2715 if (!OPTS_FLAG(LOOP_LABELS))
2716 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717 i = vec_size(loops);
2719 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2722 parseerror(parser, "no such loop to %s: `%s`",
2723 (is_continue ? "continue" : "break out of"),
2724 parser_tokval(parser));
2729 if (!parser_next(parser)) {
2730 parseerror(parser, "expected semicolon");
2735 if (parser->tok != ';') {
2736 parseerror(parser, "expected semicolon");
2740 if (!parser_next(parser))
2741 parseerror(parser, "parse error");
2743 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2747 /* returns true when it was a variable qualifier, false otherwise!
2748 * on error, cvq is set to CV_WRONG
2750 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2752 bool had_const = false;
2753 bool had_var = false;
2754 bool had_noref = false;
2755 bool had_attrib = false;
2756 bool had_static = false;
2761 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2763 /* parse an attribute */
2764 if (!parser_next(parser)) {
2765 parseerror(parser, "expected attribute after `[[`");
2769 if (!strcmp(parser_tokval(parser), "noreturn")) {
2770 flags |= AST_FLAG_NORETURN;
2771 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2772 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2777 else if (!strcmp(parser_tokval(parser), "noref")) {
2779 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2780 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2785 else if (!strcmp(parser_tokval(parser), "inline")) {
2786 flags |= AST_FLAG_INLINE;
2787 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2788 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2793 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2794 flags |= AST_FLAG_ERASEABLE;
2795 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2796 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2801 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2802 flags |= AST_FLAG_ALIAS;
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "parse error in attribute");
2810 if (parser->tok == '(') {
2811 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2812 parseerror(parser, "`alias` attribute missing parameter");
2816 *message = util_strdup(parser_tokval(parser));
2818 if (!parser_next(parser)) {
2819 parseerror(parser, "parse error in attribute");
2823 if (parser->tok != ')') {
2824 parseerror(parser, "`alias` attribute expected `)` after parameter");
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "parse error in attribute");
2834 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2835 parseerror(parser, "`alias` attribute expected `]]`");
2839 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2840 flags |= AST_FLAG_DEPRECATED;
2843 if (!parser_next(parser)) {
2844 parseerror(parser, "parse error in attribute");
2848 if (parser->tok == '(') {
2849 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2850 parseerror(parser, "`deprecated` attribute missing parameter");
2854 *message = util_strdup(parser_tokval(parser));
2856 if (!parser_next(parser)) {
2857 parseerror(parser, "parse error in attribute");
2861 if(parser->tok != ')') {
2862 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2866 if (!parser_next(parser)) {
2867 parseerror(parser, "parse error in attribute");
2872 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2873 parseerror(parser, "`deprecated` attribute expected `]]`");
2876 if (*message) mem_d(*message);
2884 /* Skip tokens until we hit a ]] */
2885 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2886 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2887 if (!parser_next(parser)) {
2888 parseerror(parser, "error inside attribute");
2895 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2897 else if (!strcmp(parser_tokval(parser), "const"))
2899 else if (!strcmp(parser_tokval(parser), "var"))
2901 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2903 else if (!strcmp(parser_tokval(parser), "noref"))
2905 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2910 if (!parser_next(parser))
2920 *is_static = had_static;
2924 parseerror(parser, "parse error after variable qualifier");
2929 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2930 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2935 /* skip the 'while' and get the body */
2936 if (!parser_next(parser)) {
2937 if (OPTS_FLAG(LOOP_LABELS))
2938 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2940 parseerror(parser, "expected 'switch' operand in parenthesis");
2944 if (parser->tok == ':') {
2945 if (!OPTS_FLAG(LOOP_LABELS))
2946 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2947 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2948 parseerror(parser, "expected loop label");
2951 label = util_strdup(parser_tokval(parser));
2952 if (!parser_next(parser)) {
2954 parseerror(parser, "expected 'switch' operand in parenthesis");
2959 if (parser->tok != '(') {
2960 parseerror(parser, "expected 'switch' operand in parenthesis");
2964 vec_push(parser->breaks, label);
2966 rv = parse_switch_go(parser, block, out);
2969 if (vec_last(parser->breaks) != label) {
2970 parseerror(parser, "internal error: label stack corrupted");
2976 vec_pop(parser->breaks);
2981 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2983 ast_expression *operand;
2986 ast_switch *switchnode;
2987 ast_switch_case swcase;
2990 bool noref, is_static;
2991 uint32_t qflags = 0;
2993 lex_ctx_t ctx = parser_ctx(parser);
2995 (void)block; /* not touching */
2998 /* parse into the expression */
2999 if (!parser_next(parser)) {
3000 parseerror(parser, "expected switch operand");
3003 /* parse the operand */
3004 operand = parse_expression_leave(parser, false, false, false);
3008 switchnode = ast_switch_new(ctx, operand);
3011 if (parser->tok != ')') {
3012 ast_delete(switchnode);
3013 parseerror(parser, "expected closing paren after 'switch' operand");
3017 /* parse over the opening paren */
3018 if (!parser_next(parser) || parser->tok != '{') {
3019 ast_delete(switchnode);
3020 parseerror(parser, "expected list of cases");
3024 if (!parser_next(parser)) {
3025 ast_delete(switchnode);
3026 parseerror(parser, "expected 'case' or 'default'");
3030 /* new block; allow some variables to be declared here */
3031 parser_enterblock(parser);
3034 if (parser->tok == TOKEN_IDENT)
3035 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3036 if (typevar || parser->tok == TOKEN_TYPENAME) {
3037 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3038 ast_delete(switchnode);
3043 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3045 if (cvq == CV_WRONG) {
3046 ast_delete(switchnode);
3049 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3050 ast_delete(switchnode);
3059 while (parser->tok != '}') {
3060 ast_block *caseblock;
3062 if (!strcmp(parser_tokval(parser), "case")) {
3063 if (!parser_next(parser)) {
3064 ast_delete(switchnode);
3065 parseerror(parser, "expected expression for case");
3068 swcase.value = parse_expression_leave(parser, false, false, false);
3069 if (!swcase.value) {
3070 ast_delete(switchnode);
3071 parseerror(parser, "expected expression for case");
3074 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3075 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3076 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3082 else if (!strcmp(parser_tokval(parser), "default")) {
3083 swcase.value = NULL;
3084 if (!parser_next(parser)) {
3085 ast_delete(switchnode);
3086 parseerror(parser, "expected colon");
3091 ast_delete(switchnode);
3092 parseerror(parser, "expected 'case' or 'default'");
3096 /* Now the colon and body */
3097 if (parser->tok != ':') {
3098 if (swcase.value) ast_unref(swcase.value);
3099 ast_delete(switchnode);
3100 parseerror(parser, "expected colon");
3104 if (!parser_next(parser)) {
3105 if (swcase.value) ast_unref(swcase.value);
3106 ast_delete(switchnode);
3107 parseerror(parser, "expected statements or case");
3110 caseblock = ast_block_new(parser_ctx(parser));
3112 if (swcase.value) ast_unref(swcase.value);
3113 ast_delete(switchnode);
3116 swcase.code = (ast_expression*)caseblock;
3117 vec_push(switchnode->cases, swcase);
3119 ast_expression *expr;
3120 if (parser->tok == '}')
3122 if (parser->tok == TOKEN_KEYWORD) {
3123 if (!strcmp(parser_tokval(parser), "case") ||
3124 !strcmp(parser_tokval(parser), "default"))
3129 if (!parse_statement(parser, caseblock, &expr, true)) {
3130 ast_delete(switchnode);
3135 if (!ast_block_add_expr(caseblock, expr)) {
3136 ast_delete(switchnode);
3142 parser_leaveblock(parser);
3145 if (parser->tok != '}') {
3146 ast_delete(switchnode);
3147 parseerror(parser, "expected closing paren of case list");
3150 if (!parser_next(parser)) {
3151 ast_delete(switchnode);
3152 parseerror(parser, "parse error after switch");
3155 *out = (ast_expression*)switchnode;
3159 /* parse computed goto sides */
3160 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3161 ast_expression *on_true;
3162 ast_expression *on_false;
3163 ast_expression *cond;
3168 if (ast_istype(*side, ast_ternary)) {
3169 ast_ternary *tern = (ast_ternary*)*side;
3170 on_true = parse_goto_computed(parser, &tern->on_true);
3171 on_false = parse_goto_computed(parser, &tern->on_false);
3173 if (!on_true || !on_false) {
3174 parseerror(parser, "expected label or expression in ternary");
3175 if (on_true) ast_unref(on_true);
3176 if (on_false) ast_unref(on_false);
3184 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3185 } else if (ast_istype(*side, ast_label)) {
3186 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3187 ast_goto_set_label(gt, ((ast_label*)*side));
3189 return (ast_expression*)gt;
3194 static bool parse_goto(parser_t *parser, ast_expression **out)
3196 ast_goto *gt = NULL;
3197 ast_expression *lbl;
3199 if (!parser_next(parser))
3202 if (parser->tok != TOKEN_IDENT) {
3203 ast_expression *expression;
3205 /* could be an expression i.e computed goto :-) */
3206 if (parser->tok != '(') {
3207 parseerror(parser, "expected label name after `goto`");
3211 /* failed to parse expression for goto */
3212 if (!(expression = parse_expression(parser, false, true)) ||
3213 !(*out = parse_goto_computed(parser, &expression))) {
3214 parseerror(parser, "invalid goto expression");
3216 ast_unref(expression);
3223 /* not computed goto */
3224 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3225 lbl = parser_find_label(parser, gt->name);
3227 if (!ast_istype(lbl, ast_label)) {
3228 parseerror(parser, "internal error: label is not an ast_label");
3232 ast_goto_set_label(gt, (ast_label*)lbl);
3235 vec_push(parser->gotos, gt);
3237 if (!parser_next(parser) || parser->tok != ';') {
3238 parseerror(parser, "semicolon expected after goto label");
3241 if (!parser_next(parser)) {
3242 parseerror(parser, "parse error after goto");
3246 *out = (ast_expression*)gt;
3250 static bool parse_skipwhite(parser_t *parser)
3253 if (!parser_next(parser))
3255 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3256 return parser->tok < TOKEN_ERROR;
3259 static bool parse_eol(parser_t *parser)
3261 if (!parse_skipwhite(parser))
3263 return parser->tok == TOKEN_EOL;
3266 static bool parse_pragma_do(parser_t *parser)
3268 if (!parser_next(parser) ||
3269 parser->tok != TOKEN_IDENT ||
3270 strcmp(parser_tokval(parser), "pragma"))
3272 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3275 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3276 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3280 if (!strcmp(parser_tokval(parser), "noref")) {
3281 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3282 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3285 parser->noref = !!parser_token(parser)->constval.i;
3286 if (!parse_eol(parser)) {
3287 parseerror(parser, "parse error after `noref` pragma");
3293 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3296 while (!parse_eol(parser)) {
3297 parser_next(parser);
3306 static bool parse_pragma(parser_t *parser)
3309 parser->lex->flags.preprocessing = true;
3310 parser->lex->flags.mergelines = true;
3311 rv = parse_pragma_do(parser);
3312 if (parser->tok != TOKEN_EOL) {
3313 parseerror(parser, "junk after pragma");
3316 parser->lex->flags.preprocessing = false;
3317 parser->lex->flags.mergelines = false;
3318 if (!parser_next(parser)) {
3319 parseerror(parser, "parse error after pragma");
3325 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3327 bool noref, is_static;
3329 uint32_t qflags = 0;
3330 ast_value *typevar = NULL;
3331 char *vstring = NULL;
3335 if (parser->tok == TOKEN_IDENT)
3336 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3338 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3340 /* local variable */
3342 parseerror(parser, "cannot declare a variable from here");
3345 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3346 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3349 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3353 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3355 if (cvq == CV_WRONG)
3357 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3359 else if (parser->tok == TOKEN_KEYWORD)
3361 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3366 if (!parser_next(parser)) {
3367 parseerror(parser, "parse error after __builtin_debug_printtype");
3371 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3373 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3374 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3375 if (!parser_next(parser)) {
3376 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3382 if (!parse_statement(parser, block, out, allow_cases))
3385 con_out("__builtin_debug_printtype: got no output node\n");
3388 ast_type_to_string(*out, ty, sizeof(ty));
3389 con_out("__builtin_debug_printtype: `%s`\n", ty);
3394 else if (!strcmp(parser_tokval(parser), "return"))
3396 return parse_return(parser, block, out);
3398 else if (!strcmp(parser_tokval(parser), "if"))
3400 return parse_if(parser, block, out);
3402 else if (!strcmp(parser_tokval(parser), "while"))
3404 return parse_while(parser, block, out);
3406 else if (!strcmp(parser_tokval(parser), "do"))
3408 return parse_dowhile(parser, block, out);
3410 else if (!strcmp(parser_tokval(parser), "for"))
3412 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3413 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3416 return parse_for(parser, block, out);
3418 else if (!strcmp(parser_tokval(parser), "break"))
3420 return parse_break_continue(parser, block, out, false);
3422 else if (!strcmp(parser_tokval(parser), "continue"))
3424 return parse_break_continue(parser, block, out, true);
3426 else if (!strcmp(parser_tokval(parser), "switch"))
3428 return parse_switch(parser, block, out);
3430 else if (!strcmp(parser_tokval(parser), "case") ||
3431 !strcmp(parser_tokval(parser), "default"))
3434 parseerror(parser, "unexpected 'case' label");
3439 else if (!strcmp(parser_tokval(parser), "goto"))
3441 return parse_goto(parser, out);
3443 else if (!strcmp(parser_tokval(parser), "typedef"))
3445 if (!parser_next(parser)) {
3446 parseerror(parser, "expected type definition after 'typedef'");
3449 return parse_typedef(parser);
3451 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3454 else if (parser->tok == '{')
3457 inner = parse_block(parser);
3460 *out = (ast_expression*)inner;
3463 else if (parser->tok == ':')
3467 if (!parser_next(parser)) {
3468 parseerror(parser, "expected label name");
3471 if (parser->tok != TOKEN_IDENT) {
3472 parseerror(parser, "label must be an identifier");
3475 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3477 if (!label->undefined) {
3478 parseerror(parser, "label `%s` already defined", label->name);
3481 label->undefined = false;
3484 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3485 vec_push(parser->labels, label);
3487 *out = (ast_expression*)label;
3488 if (!parser_next(parser)) {
3489 parseerror(parser, "parse error after label");
3492 for (i = 0; i < vec_size(parser->gotos); ++i) {
3493 if (!strcmp(parser->gotos[i]->name, label->name)) {
3494 ast_goto_set_label(parser->gotos[i], label);
3495 vec_remove(parser->gotos, i, 1);
3501 else if (parser->tok == ';')
3503 if (!parser_next(parser)) {
3504 parseerror(parser, "parse error after empty statement");
3511 lex_ctx_t ctx = parser_ctx(parser);
3512 ast_expression *exp = parse_expression(parser, false, false);
3516 if (!ast_side_effects(exp)) {
3517 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3524 static bool parse_enum(parser_t *parser)
3527 bool reverse = false;
3529 ast_value **values = NULL;
3530 ast_value *var = NULL;
3533 ast_expression *old;
3535 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3536 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3540 /* enumeration attributes (can add more later) */
3541 if (parser->tok == ':') {
3542 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3543 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3548 if (!strcmp(parser_tokval(parser), "flag")) {
3552 else if (!strcmp(parser_tokval(parser), "reverse")) {
3556 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3560 if (!parser_next(parser) || parser->tok != '{') {
3561 parseerror(parser, "expected `{` after enum attribute ");
3567 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3568 if (parser->tok == '}') {
3569 /* allow an empty enum */
3572 parseerror(parser, "expected identifier or `}`");
3576 old = parser_find_field(parser, parser_tokval(parser));
3578 old = parser_find_global(parser, parser_tokval(parser));
3580 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3581 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3585 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3586 vec_push(values, var);
3587 var->cvq = CV_CONST;
3588 var->hasvalue = true;
3590 /* for flagged enumerations increment in POTs of TWO */
3591 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3592 parser_addglobal(parser, var->name, (ast_expression*)var);
3594 if (!parser_next(parser)) {
3595 parseerror(parser, "expected `=`, `}` or comma after identifier");
3599 if (parser->tok == ',')
3601 if (parser->tok == '}')
3603 if (parser->tok != '=') {
3604 parseerror(parser, "expected `=`, `}` or comma after identifier");
3608 if (!parser_next(parser)) {
3609 parseerror(parser, "expected expression after `=`");
3613 /* We got a value! */
3614 old = parse_expression_leave(parser, true, false, false);
3615 asvalue = (ast_value*)old;
3616 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3617 compile_error(ast_ctx(var), "constant value or expression expected");
3620 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3622 if (parser->tok == '}')
3624 if (parser->tok != ',') {
3625 parseerror(parser, "expected `}` or comma after expression");
3630 /* patch them all (for reversed attribute) */
3633 for (i = 0; i < vec_size(values); i++)
3634 values[i]->constval.vfloat = vec_size(values) - i - 1;
3637 if (parser->tok != '}') {
3638 parseerror(parser, "internal error: breaking without `}`");
3642 if (!parser_next(parser) || parser->tok != ';') {
3643 parseerror(parser, "expected semicolon after enumeration");
3647 if (!parser_next(parser)) {
3648 parseerror(parser, "parse error after enumeration");
3660 static bool parse_block_into(parser_t *parser, ast_block *block)
3664 parser_enterblock(parser);
3666 if (!parser_next(parser)) { /* skip the '{' */
3667 parseerror(parser, "expected function body");
3671 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3673 ast_expression *expr = NULL;
3674 if (parser->tok == '}')
3677 if (!parse_statement(parser, block, &expr, false)) {
3678 /* parseerror(parser, "parse error"); */
3684 if (!ast_block_add_expr(block, expr)) {
3691 if (parser->tok != '}') {
3694 (void)parser_next(parser);
3698 if (!parser_leaveblock(parser))
3700 return retval && !!block;
3703 static ast_block* parse_block(parser_t *parser)
3706 block = ast_block_new(parser_ctx(parser));
3709 if (!parse_block_into(parser, block)) {
3710 ast_block_delete(block);
3716 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3718 if (parser->tok == '{') {
3719 *out = (ast_expression*)parse_block(parser);
3722 return parse_statement(parser, NULL, out, false);
3725 static bool create_vector_members(ast_value *var, ast_member **me)
3728 size_t len = strlen(var->name);
3730 for (i = 0; i < 3; ++i) {
3731 char *name = (char*)mem_a(len+3);
3732 memcpy(name, var->name, len);
3734 name[len+1] = 'x'+i;
3736 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3745 do { ast_member_delete(me[--i]); } while(i);
3749 static bool parse_function_body(parser_t *parser, ast_value *var)
3751 ast_block *block = NULL;
3756 ast_expression *framenum = NULL;
3757 ast_expression *nextthink = NULL;
3758 /* None of the following have to be deleted */
3759 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3760 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3761 bool has_frame_think;
3765 has_frame_think = false;
3766 old = parser->function;
3768 if (var->expression.flags & AST_FLAG_ALIAS) {
3769 parseerror(parser, "function aliases cannot have bodies");
3773 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3774 parseerror(parser, "gotos/labels leaking");
3778 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3779 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3780 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3786 if (parser->tok == '[') {
3787 /* got a frame definition: [ framenum, nextthink ]
3788 * this translates to:
3789 * self.frame = framenum;
3790 * self.nextthink = time + 0.1;
3791 * self.think = nextthink;
3795 fld_think = parser_find_field(parser, "think");
3796 fld_nextthink = parser_find_field(parser, "nextthink");
3797 fld_frame = parser_find_field(parser, "frame");
3798 if (!fld_think || !fld_nextthink || !fld_frame) {
3799 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3800 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3803 gbl_time = parser_find_global(parser, "time");
3804 gbl_self = parser_find_global(parser, "self");
3805 if (!gbl_time || !gbl_self) {
3806 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3807 parseerror(parser, "please declare the following globals: `time`, `self`");
3811 if (!parser_next(parser))
3814 framenum = parse_expression_leave(parser, true, false, false);
3816 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3819 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3820 ast_unref(framenum);
3821 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3825 if (parser->tok != ',') {
3826 ast_unref(framenum);
3827 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3828 parseerror(parser, "Got a %i\n", parser->tok);
3832 if (!parser_next(parser)) {
3833 ast_unref(framenum);
3837 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3839 /* qc allows the use of not-yet-declared functions here
3840 * - this automatically creates a prototype */
3841 ast_value *thinkfunc;
3842 ast_expression *functype = fld_think->next;
3844 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3845 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3846 ast_unref(framenum);
3847 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3850 ast_type_adopt(thinkfunc, functype);
3852 if (!parser_next(parser)) {
3853 ast_unref(framenum);
3854 ast_delete(thinkfunc);
3858 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3860 nextthink = (ast_expression*)thinkfunc;
3863 nextthink = parse_expression_leave(parser, true, false, false);
3865 ast_unref(framenum);
3866 parseerror(parser, "expected a think-function in [frame,think] notation");
3871 if (!ast_istype(nextthink, ast_value)) {
3872 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3876 if (retval && parser->tok != ']') {
3877 parseerror(parser, "expected closing `]` for [frame,think] notation");
3881 if (retval && !parser_next(parser)) {
3885 if (retval && parser->tok != '{') {
3886 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3891 ast_unref(nextthink);
3892 ast_unref(framenum);
3896 has_frame_think = true;
3899 block = ast_block_new(parser_ctx(parser));
3901 parseerror(parser, "failed to allocate block");
3902 if (has_frame_think) {
3903 ast_unref(nextthink);
3904 ast_unref(framenum);
3909 if (has_frame_think) {
3911 ast_expression *self_frame;
3912 ast_expression *self_nextthink;
3913 ast_expression *self_think;
3914 ast_expression *time_plus_1;
3915 ast_store *store_frame;
3916 ast_store *store_nextthink;
3917 ast_store *store_think;
3919 ctx = parser_ctx(parser);
3920 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3921 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3922 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3924 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3925 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3927 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3928 if (self_frame) ast_delete(self_frame);
3929 if (self_nextthink) ast_delete(self_nextthink);
3930 if (self_think) ast_delete(self_think);
3931 if (time_plus_1) ast_delete(time_plus_1);
3937 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3938 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3939 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3942 ast_delete(self_frame);
3945 if (!store_nextthink) {
3946 ast_delete(self_nextthink);
3950 ast_delete(self_think);
3954 if (store_frame) ast_delete(store_frame);
3955 if (store_nextthink) ast_delete(store_nextthink);
3956 if (store_think) ast_delete(store_think);
3959 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3960 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3961 !ast_block_add_expr(block, (ast_expression*)store_think))
3968 parseerror(parser, "failed to generate code for [frame,think]");
3969 ast_unref(nextthink);
3970 ast_unref(framenum);
3976 if (var->hasvalue) {
3977 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3978 ast_block_delete(block);
3982 func = ast_function_new(ast_ctx(var), var->name, var);
3984 parseerror(parser, "failed to allocate function for `%s`", var->name);
3985 ast_block_delete(block);
3988 vec_push(parser->functions, func);
3990 parser_enterblock(parser);
3992 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3994 ast_value *param = var->expression.params[parami];
3997 if (param->expression.vtype != TYPE_VECTOR &&
3998 (param->expression.vtype != TYPE_FIELD ||
3999 param->expression.next->vtype != TYPE_VECTOR))
4004 if (!create_vector_members(param, me)) {
4005 ast_block_delete(block);
4009 for (e = 0; e < 3; ++e) {
4010 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4011 ast_block_collect(block, (ast_expression*)me[e]);
4015 if (var->argcounter) {
4016 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4017 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4021 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4023 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4024 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4025 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4026 varargs->expression.count = 0;
4027 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4028 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4029 ast_delete(varargs);
4030 ast_block_delete(block);
4033 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4034 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4035 ast_delete(varargs);
4036 ast_block_delete(block);
4039 func->varargs = varargs;
4040 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4043 parser->function = func;
4044 if (!parse_block_into(parser, block)) {
4045 ast_block_delete(block);
4049 vec_push(func->blocks, block);
4052 parser->function = old;
4053 if (!parser_leaveblock(parser))
4055 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4056 parseerror(parser, "internal error: local scopes left");
4060 if (parser->tok == ';')
4061 return parser_next(parser);
4062 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4063 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4067 (void)!parser_leaveblock(parser);
4068 vec_pop(parser->functions);
4069 ast_function_delete(func);
4070 var->constval.vfunc = NULL;
4073 parser->function = old;
4077 static ast_expression *array_accessor_split(
4082 ast_expression *left,
4083 ast_expression *right
4089 lex_ctx_t ctx = ast_ctx(array);
4091 if (!left || !right) {
4092 if (left) ast_delete(left);
4093 if (right) ast_delete(right);
4097 cmp = ast_binary_new(ctx, INSTR_LT,
4098 (ast_expression*)index,
4099 (ast_expression*)fold_constgen_float(parser->fold, middle));
4103 parseerror(parser, "internal error: failed to create comparison for array setter");
4107 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4109 ast_delete(cmp); /* will delete left and right */
4110 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4114 return (ast_expression*)ifthen;
4117 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4119 lex_ctx_t ctx = ast_ctx(array);
4121 if (from+1 == afterend) {
4122 /* set this value */
4125 ast_array_index *subscript;
4127 int assignop = type_store_instr[value->expression.vtype];
4129 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4130 assignop = INSTR_STORE_V;
4132 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4136 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4138 ast_delete(subscript);
4142 block = ast_block_new(ctx);
4148 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4153 ret = ast_return_new(ctx, NULL);
4159 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4164 return (ast_expression*)block;
4166 ast_expression *left, *right;
4167 size_t diff = afterend - from;
4168 size_t middle = from + diff/2;
4169 left = array_setter_node(parser, array, index, value, from, middle);
4170 right = array_setter_node(parser, array, index, value, middle, afterend);
4171 return array_accessor_split(parser, array, index, middle, left, right);
4175 static ast_expression *array_field_setter_node(
4184 lex_ctx_t ctx = ast_ctx(array);
4186 if (from+1 == afterend) {
4187 /* set this value */
4190 ast_entfield *entfield;
4191 ast_array_index *subscript;
4193 int assignop = type_storep_instr[value->expression.vtype];
4195 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4196 assignop = INSTR_STOREP_V;
4198 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4202 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4203 subscript->expression.vtype = TYPE_FIELD;
4205 entfield = ast_entfield_new_force(ctx,
4206 (ast_expression*)entity,
4207 (ast_expression*)subscript,
4208 (ast_expression*)subscript);
4210 ast_delete(subscript);
4214 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4216 ast_delete(entfield);
4220 block = ast_block_new(ctx);
4226 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4231 ret = ast_return_new(ctx, NULL);
4237 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4242 return (ast_expression*)block;
4244 ast_expression *left, *right;
4245 size_t diff = afterend - from;
4246 size_t middle = from + diff/2;
4247 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4248 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4249 return array_accessor_split(parser, array, index, middle, left, right);
4253 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4255 lex_ctx_t ctx = ast_ctx(array);
4257 if (from+1 == afterend) {
4259 ast_array_index *subscript;
4261 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4265 ret = ast_return_new(ctx, (ast_expression*)subscript);
4267 ast_delete(subscript);
4271 return (ast_expression*)ret;
4273 ast_expression *left, *right;
4274 size_t diff = afterend - from;
4275 size_t middle = from + diff/2;
4276 left = array_getter_node(parser, array, index, from, middle);
4277 right = array_getter_node(parser, array, index, middle, afterend);
4278 return array_accessor_split(parser, array, index, middle, left, right);
4282 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4284 ast_function *func = NULL;
4285 ast_value *fval = NULL;
4286 ast_block *body = NULL;
4288 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4290 parseerror(parser, "failed to create accessor function value");
4294 func = ast_function_new(ast_ctx(array), funcname, fval);
4297 parseerror(parser, "failed to create accessor function node");
4301 body = ast_block_new(ast_ctx(array));
4303 parseerror(parser, "failed to create block for array accessor");
4309 vec_push(func->blocks, body);
4312 vec_push(parser->accessors, fval);
4317 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4319 ast_value *index = NULL;
4320 ast_value *value = NULL;
4324 if (!ast_istype(array->expression.next, ast_value)) {
4325 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4329 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4331 func = fval->constval.vfunc;
4332 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4334 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4335 value = ast_value_copy((ast_value*)array->expression.next);
4337 if (!index || !value) {
4338 parseerror(parser, "failed to create locals for array accessor");
4341 (void)!ast_value_set_name(value, "value"); /* not important */
4342 vec_push(fval->expression.params, index);
4343 vec_push(fval->expression.params, value);
4345 array->setter = fval;
4348 if (index) ast_delete(index);
4349 if (value) ast_delete(value);
4355 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4357 ast_expression *root = NULL;
4358 root = array_setter_node(parser, array,
4359 array->setter->expression.params[0],
4360 array->setter->expression.params[1],
4361 0, array->expression.count);
4363 parseerror(parser, "failed to build accessor search tree");
4366 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4373 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4375 if (!parser_create_array_setter_proto(parser, array, funcname))
4377 return parser_create_array_setter_impl(parser, array);
4380 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4382 ast_expression *root = NULL;
4383 ast_value *entity = NULL;
4384 ast_value *index = NULL;
4385 ast_value *value = NULL;
4389 if (!ast_istype(array->expression.next, ast_value)) {
4390 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4394 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4396 func = fval->constval.vfunc;
4397 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4399 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4400 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4401 value = ast_value_copy((ast_value*)array->expression.next);
4402 if (!entity || !index || !value) {
4403 parseerror(parser, "failed to create locals for array accessor");
4406 (void)!ast_value_set_name(value, "value"); /* not important */
4407 vec_push(fval->expression.params, entity);
4408 vec_push(fval->expression.params, index);
4409 vec_push(fval->expression.params, value);
4411 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4413 parseerror(parser, "failed to build accessor search tree");
4417 array->setter = fval;
4418 return ast_block_add_expr(func->blocks[0], root);
4420 if (entity) ast_delete(entity);
4421 if (index) ast_delete(index);
4422 if (value) ast_delete(value);
4423 if (root) ast_delete(root);
4429 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4431 ast_value *index = NULL;
4435 /* NOTE: checking array->expression.next rather than elemtype since
4436 * for fields elemtype is a temporary fieldtype.
4438 if (!ast_istype(array->expression.next, ast_value)) {
4439 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4443 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4445 func = fval->constval.vfunc;
4446 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4448 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4451 parseerror(parser, "failed to create locals for array accessor");
4454 vec_push(fval->expression.params, index);
4456 array->getter = fval;
4459 if (index) ast_delete(index);
4465 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4467 ast_expression *root = NULL;
4469 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4471 parseerror(parser, "failed to build accessor search tree");
4474 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4481 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4483 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4485 return parser_create_array_getter_impl(parser, array);
4488 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4489 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4497 bool variadic = false;
4498 ast_value *varparam = NULL;
4499 char *argcounter = NULL;
4501 ctx = parser_ctx(parser);
4503 /* for the sake of less code we parse-in in this function */
4504 if (!parser_next(parser)) {
4506 parseerror(parser, "expected parameter list");
4512 /* parse variables until we hit a closing paren */
4513 while (parser->tok != ')') {
4515 /* there must be commas between them */
4516 if (parser->tok != ',') {
4517 parseerror(parser, "expected comma or end of parameter list");
4520 if (!parser_next(parser)) {
4521 parseerror(parser, "expected parameter");
4527 if (parser->tok == TOKEN_DOTS) {
4528 /* '...' indicates a varargs function */
4530 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4531 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4534 if (parser->tok == TOKEN_IDENT) {
4535 argcounter = util_strdup(parser_tokval(parser));
4536 if (!parser_next(parser) || parser->tok != ')') {
4537 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4544 /* for anything else just parse a typename */
4545 param = parse_typename(parser, NULL, NULL);
4548 vec_push(params, param);
4549 if (param->expression.vtype >= TYPE_VARIANT) {
4550 char tname[1024]; /* typename is reserved in C++ */
4551 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4552 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4555 /* type-restricted varargs */
4556 if (parser->tok == TOKEN_DOTS) {
4558 varparam = vec_last(params);
4560 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4561 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4564 if (parser->tok == TOKEN_IDENT) {
4565 argcounter = util_strdup(parser_tokval(parser));
4566 if (!parser_next(parser) || parser->tok != ')') {
4567 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4575 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4579 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4580 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4583 if (!parser_next(parser)) {
4584 parseerror(parser, "parse error after typename");
4588 /* now turn 'var' into a function type */
4589 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4590 fval->expression.next = (ast_expression*)var;
4592 fval->expression.flags |= AST_FLAG_VARIADIC;
4595 var->expression.params = params;
4596 var->expression.varparam = (ast_expression*)varparam;
4597 var->argcounter = argcounter;
4606 ast_delete(varparam);
4608 for (i = 0; i < vec_size(params); ++i)
4609 ast_delete(params[i]);
4614 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4616 ast_expression *cexp;
4617 ast_value *cval, *tmp;
4620 ctx = parser_ctx(parser);
4622 if (!parser_next(parser)) {
4624 parseerror(parser, "expected array-size");
4628 if (parser->tok != ']') {
4629 cexp = parse_expression_leave(parser, true, false, false);
4631 if (!cexp || !ast_istype(cexp, ast_value)) {
4635 parseerror(parser, "expected array-size as constant positive integer");
4638 cval = (ast_value*)cexp;
4645 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4646 tmp->expression.next = (ast_expression*)var;
4650 if (cval->expression.vtype == TYPE_INTEGER)
4651 tmp->expression.count = cval->constval.vint;
4652 else if (cval->expression.vtype == TYPE_FLOAT)
4653 tmp->expression.count = cval->constval.vfloat;
4657 parseerror(parser, "array-size must be a positive integer constant");
4663 var->expression.count = -1;
4664 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4667 if (parser->tok != ']') {
4669 parseerror(parser, "expected ']' after array-size");
4672 if (!parser_next(parser)) {
4674 parseerror(parser, "error after parsing array size");
4680 /* Parse a complete typename.
4681 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4682 * but when parsing variables separated by comma
4683 * 'storebase' should point to where the base-type should be kept.
4684 * The base type makes up every bit of type information which comes *before* the
4687 * NOTE: The value must either be named, have a NULL name, or a name starting
4688 * with '<'. In the first case, this will be the actual variable or type
4689 * name, in the other cases it is assumed that the name will appear
4690 * later, and an error is generated otherwise.
4692 * The following will be parsed in its entirety:
4694 * The 'basetype' in this case is 'void()'
4695 * and if there's a comma after it, say:
4697 * then the type-information 'void()' can be stored in 'storebase'
4699 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4701 ast_value *var, *tmp;
4704 const char *name = NULL;
4705 bool isfield = false;
4706 bool wasarray = false;
4707 size_t morefields = 0;
4709 ctx = parser_ctx(parser);
4711 /* types may start with a dot */
4712 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4714 if (parser->tok == TOKEN_DOTS)
4716 /* if we parsed a dot we need a typename now */
4717 if (!parser_next(parser)) {
4718 parseerror(parser, "expected typename for field definition");
4722 /* Further dots are handled seperately because they won't be part of the
4726 if (parser->tok == '.')
4728 else if (parser->tok == TOKEN_DOTS)
4732 if (!parser_next(parser)) {
4733 parseerror(parser, "expected typename for field definition");
4738 if (parser->tok == TOKEN_IDENT)
4739 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4740 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4741 parseerror(parser, "expected typename");
4745 /* generate the basic type value */
4746 if (cached_typedef) {
4747 var = ast_value_copy(cached_typedef);
4748 ast_value_set_name(var, "<type(from_def)>");
4750 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4752 for (; morefields; --morefields) {
4753 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4754 tmp->expression.next = (ast_expression*)var;
4758 /* do not yet turn into a field - remember:
4759 * .void() foo; is a field too
4760 * .void()() foo; is a function
4764 if (!parser_next(parser)) {
4766 parseerror(parser, "parse error after typename");
4770 /* an opening paren now starts the parameter-list of a function
4771 * this is where original-QC has parameter lists.
4772 * We allow a single parameter list here.
4773 * Much like fteqcc we don't allow `float()() x`
4775 if (parser->tok == '(') {
4776 var = parse_parameter_list(parser, var);
4781 /* store the base if requested */
4783 *storebase = ast_value_copy(var);
4785 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4786 tmp->expression.next = (ast_expression*)*storebase;
4791 /* there may be a name now */
4792 if (parser->tok == TOKEN_IDENT) {
4793 name = util_strdup(parser_tokval(parser));
4795 if (!parser_next(parser)) {
4798 parseerror(parser, "error after variable or field declaration");
4803 /* now this may be an array */
4804 if (parser->tok == '[') {
4806 var = parse_arraysize(parser, var);
4808 if (name) mem_d(name);
4813 /* This is the point where we can turn it into a field */
4815 /* turn it into a field if desired */
4816 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4817 tmp->expression.next = (ast_expression*)var;
4821 /* now there may be function parens again */
4822 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4823 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4824 if (parser->tok == '(' && wasarray)
4825 parseerror(parser, "arrays as part of a return type is not supported");
4826 while (parser->tok == '(') {
4827 var = parse_parameter_list(parser, var);
4829 if (name) mem_d(name);
4834 /* finally name it */
4836 if (!ast_value_set_name(var, name)) {
4839 parseerror(parser, "internal error: failed to set name");
4842 /* free the name, ast_value_set_name duplicates */
4849 static bool parse_typedef(parser_t *parser)
4851 ast_value *typevar, *oldtype;
4852 ast_expression *old;
4854 typevar = parse_typename(parser, NULL, NULL);
4859 /* while parsing types, the ast_value's get named '<something>' */
4860 if (!typevar->name || typevar->name[0] == '<') {
4861 parseerror(parser, "missing name in typedef");
4862 ast_delete(typevar);
4866 if ( (old = parser_find_var(parser, typevar->name)) ) {
4867 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4868 " -> `%s` has been declared here: %s:%i",
4869 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4870 ast_delete(typevar);
4874 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4875 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4876 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4877 ast_delete(typevar);
4881 vec_push(parser->_typedefs, typevar);
4882 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4884 if (parser->tok != ';') {
4885 parseerror(parser, "expected semicolon after typedef");
4888 if (!parser_next(parser)) {
4889 parseerror(parser, "parse error after typedef");
4896 static const char *cvq_to_str(int cvq) {
4898 case CV_NONE: return "none";
4899 case CV_VAR: return "`var`";
4900 case CV_CONST: return "`const`";
4901 default: return "<INVALID>";
4905 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4908 if (proto->cvq != var->cvq) {
4909 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4910 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4911 parser->tok == '='))
4913 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4914 "`%s` declared with different qualifiers: %s\n"
4915 " -> previous declaration here: %s:%i uses %s",
4916 var->name, cvq_to_str(var->cvq),
4917 ast_ctx(proto).file, ast_ctx(proto).line,
4918 cvq_to_str(proto->cvq));
4921 av = (var ->expression.flags & AST_FLAG_NORETURN);
4922 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4924 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4925 "`%s` declared with different attributes%s\n"
4926 " -> previous declaration here: %s:%i",
4927 var->name, (av ? ": noreturn" : ""),
4928 ast_ctx(proto).file, ast_ctx(proto).line,
4929 (ao ? ": noreturn" : ""));
4934 static bool create_array_accessors(parser_t *parser, ast_value *var)
4937 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4938 if (!parser_create_array_setter(parser, var, name))
4940 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4941 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4946 static bool parse_array(parser_t *parser, ast_value *array)
4949 if (array->initlist) {
4950 parseerror(parser, "array already initialized elsewhere");
4953 if (!parser_next(parser)) {
4954 parseerror(parser, "parse error in array initializer");
4958 while (parser->tok != '}') {
4959 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4962 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4964 parseerror(parser, "initializing element must be a compile time constant");
4967 vec_push(array->initlist, v->constval);
4968 if (v->expression.vtype == TYPE_STRING) {
4969 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4973 if (parser->tok == '}')
4975 if (parser->tok != ',' || !parser_next(parser)) {
4976 parseerror(parser, "expected comma or '}' in element list");
4980 if (!parser_next(parser) || parser->tok != ';') {
4981 parseerror(parser, "expected semicolon after initializer, got %s");
4985 if (!parser_next(parser)) {
4986 parseerror(parser, "parse error after initializer");
4991 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4992 if (array->expression.count != (size_t)-1) {
4993 parseerror(parser, "array `%s' has already been initialized with %u elements",
4994 array->name, (unsigned)array->expression.count);
4996 array->expression.count = vec_size(array->initlist);
4997 if (!create_array_accessors(parser, array))
5003 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)
5007 ast_expression *old;
5011 ast_value *basetype = NULL;
5013 bool isparam = false;
5014 bool isvector = false;
5015 bool cleanvar = true;
5016 bool wasarray = false;
5018 ast_member *me[3] = { NULL, NULL, NULL };
5020 if (!localblock && is_static)
5021 parseerror(parser, "`static` qualifier is not supported in global scope");
5023 /* get the first complete variable */
5024 var = parse_typename(parser, &basetype, cached_typedef);
5027 ast_delete(basetype);
5031 /* while parsing types, the ast_value's get named '<something>' */
5032 if (!var->name || var->name[0] == '<') {
5033 parseerror(parser, "declaration does not declare anything");
5035 ast_delete(basetype);
5043 /* Part 0: finish the type */
5044 if (parser->tok == '(') {
5045 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5046 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5047 var = parse_parameter_list(parser, var);
5053 /* we only allow 1-dimensional arrays */
5054 if (parser->tok == '[') {
5056 var = parse_arraysize(parser, var);
5062 if (parser->tok == '(' && wasarray) {
5063 parseerror(parser, "arrays as part of a return type is not supported");
5064 /* we'll still parse the type completely for now */
5066 /* for functions returning functions */
5067 while (parser->tok == '(') {
5068 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5069 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5070 var = parse_parameter_list(parser, var);
5077 var->cvq = qualifier;
5078 var->expression.flags |= qflags;
5081 * store the vstring back to var for alias and
5082 * deprecation messages.
5084 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5085 var->expression.flags & AST_FLAG_ALIAS)
5086 var->desc = vstring;
5089 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5090 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5091 * is then filled with the previous definition and the parameter-names replaced.
5093 if (!strcmp(var->name, "nil")) {
5094 if (OPTS_FLAG(UNTYPED_NIL)) {
5095 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5096 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5098 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5101 /* Deal with end_sys_ vars */
5103 if (!strcmp(var->name, "end_sys_globals")) {
5105 parser->crc_globals = vec_size(parser->globals);
5108 else if (!strcmp(var->name, "end_sys_fields")) {
5110 parser->crc_fields = vec_size(parser->fields);
5113 if (was_end && var->expression.vtype == TYPE_FIELD) {
5114 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5115 "global '%s' hint should not be a field",
5116 parser_tokval(parser)))
5123 if (!nofields && var->expression.vtype == TYPE_FIELD)
5125 /* deal with field declarations */
5126 old = parser_find_field(parser, var->name);
5128 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5129 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5138 parseerror(parser, "field `%s` already declared here: %s:%i",
5139 var->name, ast_ctx(old).file, ast_ctx(old).line);
5144 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5145 (old = parser_find_global(parser, var->name)))
5147 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5148 parseerror(parser, "field `%s` already declared here: %s:%i",
5149 var->name, ast_ctx(old).file, ast_ctx(old).line);
5156 /* deal with other globals */
5157 old = parser_find_global(parser, var->name);
5158 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5160 /* This is a function which had a prototype */
5161 if (!ast_istype(old, ast_value)) {
5162 parseerror(parser, "internal error: prototype is not an ast_value");
5166 proto = (ast_value*)old;
5167 proto->desc = var->desc;
5168 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5169 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5171 ast_ctx(proto).file, ast_ctx(proto).line);
5175 /* we need the new parameter-names */
5176 for (i = 0; i < vec_size(proto->expression.params); ++i)
5177 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5178 if (!parser_check_qualifiers(parser, var, proto)) {
5185 proto->expression.flags |= var->expression.flags;
5193 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5194 "global `%s` already declared here: %s:%i",
5195 var->name, ast_ctx(old).file, ast_ctx(old).line))
5200 proto = (ast_value*)old;
5201 if (!ast_istype(old, ast_value)) {
5202 parseerror(parser, "internal error: not an ast_value");
5207 if (!parser_check_qualifiers(parser, var, proto)) {
5212 proto->expression.flags |= var->expression.flags;
5216 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5217 (old = parser_find_field(parser, var->name)))
5219 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5220 parseerror(parser, "global `%s` already declared here: %s:%i",
5221 var->name, ast_ctx(old).file, ast_ctx(old).line);
5228 else /* it's not a global */
5230 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5231 if (old && !isparam) {
5232 parseerror(parser, "local `%s` already declared here: %s:%i",
5233 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5237 /* doing this here as the above is just for a single scope */
5238 old = parser_find_local(parser, var->name, 0, &isparam);
5239 if (old && isparam) {
5240 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5241 "local `%s` is shadowing a parameter", var->name))
5243 parseerror(parser, "local `%s` already declared here: %s:%i",
5244 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5248 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5250 if (ast_istype(old, ast_value))
5251 var = proto = (ast_value*)old;
5260 /* in a noref section we simply bump the usecount */
5261 if (noref || parser->noref)
5265 * Create the global/local, and deal with vector types.
5268 if (var->expression.vtype == TYPE_VECTOR)
5270 else if (var->expression.vtype == TYPE_FIELD &&
5271 var->expression.next->vtype == TYPE_VECTOR)
5275 if (!create_vector_members(var, me)) {
5282 /* deal with global variables, fields, functions */
5283 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5284 var->isfield = true;
5285 vec_push(parser->fields, (ast_expression*)var);
5286 util_htset(parser->htfields, var->name, var);
5288 for (i = 0; i < 3; ++i) {
5289 vec_push(parser->fields, (ast_expression*)me[i]);
5290 util_htset(parser->htfields, me[i]->name, me[i]);
5295 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5296 parser_addglobal(parser, var->name, (ast_expression*)var);
5298 for (i = 0; i < 3; ++i) {
5299 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5303 ast_expression *find = parser_find_global(parser, var->desc);
5306 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5310 if (!ast_compare_type((ast_expression*)var, find)) {
5314 ast_type_to_string(find, ty1, sizeof(ty1));
5315 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5317 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5324 * add alias to aliases table and to corrector
5325 * so corrections can apply for aliases as well.
5327 util_htset(parser->aliases, var->name, find);
5330 * add to corrector so corrections can work
5331 * even for aliases too.
5334 vec_last(parser->correct_variables),
5335 &vec_last(parser->correct_variables_score),
5339 /* generate aliases for vector components */
5343 util_asprintf(&buffer[0], "%s_x", var->desc);
5344 util_asprintf(&buffer[1], "%s_y", var->desc);
5345 util_asprintf(&buffer[2], "%s_z", var->desc);
5347 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5348 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5349 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5356 * add to corrector so corrections can work
5357 * even for aliases too.
5360 vec_last(parser->correct_variables),
5361 &vec_last(parser->correct_variables_score),
5365 vec_last(parser->correct_variables),
5366 &vec_last(parser->correct_variables_score),
5370 vec_last(parser->correct_variables),
5371 &vec_last(parser->correct_variables_score),
5379 /* a static adds itself to be generated like any other global
5380 * but is added to the local namespace instead
5382 char *defname = NULL;
5383 size_t prefix_len, ln;
5385 ln = strlen(parser->function->name);
5386 vec_append(defname, ln, parser->function->name);
5388 vec_append(defname, 2, "::");
5389 /* remember the length up to here */
5390 prefix_len = vec_size(defname);
5392 /* Add it to the local scope */
5393 util_htset(vec_last(parser->variables), var->name, (void*)var);
5397 vec_last(parser->correct_variables),
5398 &vec_last(parser->correct_variables_score),
5402 /* now rename the global */
5403 ln = strlen(var->name);
5404 vec_append(defname, ln, var->name);
5405 ast_value_set_name(var, defname);
5407 /* push it to the to-be-generated globals */
5408 vec_push(parser->globals, (ast_expression*)var);
5410 /* same game for the vector members */
5412 for (i = 0; i < 3; ++i) {
5413 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5417 vec_last(parser->correct_variables),
5418 &vec_last(parser->correct_variables_score),
5422 vec_shrinkto(defname, prefix_len);
5423 ln = strlen(me[i]->name);
5424 vec_append(defname, ln, me[i]->name);
5425 ast_member_set_name(me[i], defname);
5427 vec_push(parser->globals, (ast_expression*)me[i]);
5432 vec_push(localblock->locals, var);
5433 parser_addlocal(parser, var->name, (ast_expression*)var);
5435 for (i = 0; i < 3; ++i) {
5436 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5437 ast_block_collect(localblock, (ast_expression*)me[i]);
5443 me[0] = me[1] = me[2] = NULL;
5448 if (var->expression.vtype == TYPE_ARRAY) {
5449 if (var->expression.count != (size_t)-1) {
5450 if (!create_array_accessors(parser, var))
5454 else if (!localblock && !nofields &&
5455 var->expression.vtype == TYPE_FIELD &&
5456 var->expression.next->vtype == TYPE_ARRAY)
5459 ast_expression *telem;
5461 ast_value *array = (ast_value*)var->expression.next;
5463 if (!ast_istype(var->expression.next, ast_value)) {
5464 parseerror(parser, "internal error: field element type must be an ast_value");
5468 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5469 if (!parser_create_array_field_setter(parser, array, name))
5472 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5473 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5474 tfield->expression.next = telem;
5475 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5476 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5484 if (parser->tok == ';') {
5485 ast_delete(basetype);
5486 if (!parser_next(parser)) {
5487 parseerror(parser, "error after variable declaration");
5493 if (parser->tok == ',')
5497 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5500 parseerror(parser, "missing comma or semicolon while parsing variables");
5504 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5505 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5506 "initializing expression turns variable `%s` into a constant in this standard",
5513 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5514 if (parser->tok != '=') {
5515 if (!strcmp(parser_tokval(parser), "break")) {
5516 if (!parser_next(parser)) {
5517 parseerror(parser, "error parsing break definition");
5520 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5522 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5527 if (!parser_next(parser)) {
5528 parseerror(parser, "error parsing initializer");
5532 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5533 parseerror(parser, "expected '=' before function body in this standard");
5536 if (parser->tok == '#') {
5537 ast_function *func = NULL;
5538 ast_value *number = NULL;
5544 parseerror(parser, "cannot declare builtins within functions");
5547 if (var->expression.vtype != TYPE_FUNCTION) {
5548 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5551 if (!parser_next(parser)) {
5552 parseerror(parser, "expected builtin number");
5556 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5557 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5559 parseerror(parser, "builtin number expected");
5562 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5565 parseerror(parser, "builtin number must be a compile time constant");
5568 if (number->expression.vtype == TYPE_INTEGER)
5569 builtin_num = number->constval.vint;
5570 else if (number->expression.vtype == TYPE_FLOAT)
5571 builtin_num = number->constval.vfloat;
5574 parseerror(parser, "builtin number must be an integer constant");
5579 fractional = modff(builtin_num, &integral);
5580 if (builtin_num < 0 || fractional != 0) {
5581 parseerror(parser, "builtin number must be an integer greater than zero");
5585 /* we only want the integral part anyways */
5586 builtin_num = integral;
5587 } else if (parser->tok == TOKEN_INTCONST) {
5588 builtin_num = parser_token(parser)->constval.i;
5590 parseerror(parser, "builtin number must be a compile time constant");
5594 if (var->hasvalue) {
5595 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5596 "builtin `%s` has already been defined\n"
5597 " -> previous declaration here: %s:%i",
5598 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5602 func = ast_function_new(ast_ctx(var), var->name, var);
5604 parseerror(parser, "failed to allocate function for `%s`", var->name);
5607 vec_push(parser->functions, func);
5609 func->builtin = -builtin_num-1;
5612 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5613 ? (parser->tok != ',' && parser->tok != ';')
5614 : (!parser_next(parser)))
5616 parseerror(parser, "expected comma or semicolon");
5618 ast_function_delete(func);
5619 var->constval.vfunc = NULL;
5623 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5626 /* Note that fteqcc and most others don't even *have*
5627 * local arrays, so this is not a high priority.
5629 parseerror(parser, "TODO: initializers for local arrays");
5633 var->hasvalue = true;
5634 if (!parse_array(parser, var))
5637 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5640 parseerror(parser, "cannot declare functions within functions");
5645 ast_ctx(proto) = parser_ctx(parser);
5647 if (!parse_function_body(parser, var))
5649 ast_delete(basetype);
5650 for (i = 0; i < vec_size(parser->gotos); ++i)
5651 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5652 vec_free(parser->gotos);
5653 vec_free(parser->labels);
5656 ast_expression *cexp;
5659 cexp = parse_expression_leave(parser, true, false, false);
5664 cval = (ast_value*)cexp;
5665 if (cval != parser->nil &&
5666 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5669 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5673 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5674 qualifier != CV_VAR)
5676 var->cvq = CV_CONST;
5678 if (cval == parser->nil)
5679 var->expression.flags |= AST_FLAG_INITIALIZED;
5682 var->hasvalue = true;
5683 if (cval->expression.vtype == TYPE_STRING)
5684 var->constval.vstring = parser_strdup(cval->constval.vstring);
5685 else if (cval->expression.vtype == TYPE_FIELD)
5686 var->constval.vfield = cval;
5688 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5694 shunt sy = { NULL, NULL, NULL, NULL };
5697 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5698 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5699 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5700 if (!parser_sy_apply_operator(parser, &sy))
5703 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5704 parseerror(parser, "internal error: leaked operands");
5705 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5716 if (parser->tok == ',') {
5717 if (!parser_next(parser)) {
5718 parseerror(parser, "expected another variable");
5722 if (parser->tok != TOKEN_IDENT) {
5723 parseerror(parser, "expected another variable");
5726 var = ast_value_copy(basetype);
5728 ast_value_set_name(var, parser_tokval(parser));
5729 if (!parser_next(parser)) {
5730 parseerror(parser, "error parsing variable declaration");
5736 if (parser->tok != ';') {
5737 parseerror(parser, "missing semicolon after variables");
5741 if (!parser_next(parser)) {
5742 parseerror(parser, "parse error after variable declaration");
5746 ast_delete(basetype);
5750 if (cleanvar && var)
5752 ast_delete(basetype);
5756 ast_delete(basetype);
5757 if (cleanvar && var)
5759 if (me[0]) ast_member_delete(me[0]);
5760 if (me[1]) ast_member_delete(me[1]);
5761 if (me[2]) ast_member_delete(me[2]);
5765 static bool parser_global_statement(parser_t *parser)
5769 bool is_static = false;
5770 uint32_t qflags = 0;
5771 ast_value *istype = NULL;
5772 char *vstring = NULL;
5774 if (parser->tok == TOKEN_IDENT)
5775 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5777 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5779 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5781 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5783 if (cvq == CV_WRONG)
5785 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5787 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5789 return parse_enum(parser);
5791 else if (parser->tok == TOKEN_KEYWORD)
5793 if (!strcmp(parser_tokval(parser), "typedef")) {
5794 if (!parser_next(parser)) {
5795 parseerror(parser, "expected type definition after 'typedef'");
5798 return parse_typedef(parser);
5800 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5803 else if (parser->tok == '#')
5805 return parse_pragma(parser);
5807 else if (parser->tok == '$')
5809 if (!parser_next(parser)) {
5810 parseerror(parser, "parse error");
5816 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5822 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5824 return util_crc16(old, str, strlen(str));
5827 static void progdefs_crc_file(const char *str)
5829 /* write to progdefs.h here */
5833 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5835 old = progdefs_crc_sum(old, str);
5836 progdefs_crc_file(str);
5840 static void generate_checksum(parser_t *parser, ir_builder *ir)
5842 uint16_t crc = 0xFFFF;
5846 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5847 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5849 progdefs_crc_file("\tint\tpad;\n");
5850 progdefs_crc_file("\tint\tofs_return[3];\n");
5851 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5852 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5853 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5854 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5855 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5856 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5857 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5858 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5860 for (i = 0; i < parser->crc_globals; ++i) {
5861 if (!ast_istype(parser->globals[i], ast_value))
5863 value = (ast_value*)(parser->globals[i]);
5864 switch (value->expression.vtype) {
5865 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5866 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5867 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5868 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5870 crc = progdefs_crc_both(crc, "\tint\t");
5873 crc = progdefs_crc_both(crc, value->name);
5874 crc = progdefs_crc_both(crc, ";\n");
5876 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5877 for (i = 0; i < parser->crc_fields; ++i) {
5878 if (!ast_istype(parser->fields[i], ast_value))
5880 value = (ast_value*)(parser->fields[i]);
5881 switch (value->expression.next->vtype) {
5882 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5883 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5884 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5885 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5887 crc = progdefs_crc_both(crc, "\tint\t");
5890 crc = progdefs_crc_both(crc, value->name);
5891 crc = progdefs_crc_both(crc, ";\n");
5893 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5894 ir->code->crc = crc;
5897 parser_t *parser_create()
5900 lex_ctx_t empty_ctx;
5903 parser = (parser_t*)mem_a(sizeof(parser_t));
5907 memset(parser, 0, sizeof(*parser));
5909 for (i = 0; i < operator_count; ++i) {
5910 if (operators[i].id == opid1('=')) {
5911 parser->assign_op = operators+i;
5915 if (!parser->assign_op) {
5916 con_err("internal error: initializing parser: failed to find assign operator\n");
5921 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5922 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5923 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5924 vec_push(parser->_blocktypedefs, 0);
5926 parser->aliases = util_htnew(PARSER_HT_SIZE);
5929 vec_push(parser->correct_variables, correct_trie_new());
5930 vec_push(parser->correct_variables_score, NULL);
5932 empty_ctx.file = "<internal>";
5934 empty_ctx.column = 0;
5935 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5936 parser->nil->cvq = CV_CONST;
5937 if (OPTS_FLAG(UNTYPED_NIL))
5938 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5940 parser->max_param_count = 1;
5942 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5943 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5944 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5946 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5947 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5948 parser->reserved_version->cvq = CV_CONST;
5949 parser->reserved_version->hasvalue = true;
5950 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5951 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5953 parser->reserved_version = NULL;
5956 parser->fold = fold_init (parser);
5957 parser->intrin = intrin_init(parser);
5961 static bool parser_compile(parser_t *parser)
5963 /* initial lexer/parser state */
5964 parser->lex->flags.noops = true;
5966 if (parser_next(parser))
5968 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5970 if (!parser_global_statement(parser)) {
5971 if (parser->tok == TOKEN_EOF)
5972 parseerror(parser, "unexpected end of file");
5973 else if (compile_errors)
5974 parseerror(parser, "there have been errors, bailing out");
5975 lex_close(parser->lex);
5981 parseerror(parser, "parse error");
5982 lex_close(parser->lex);
5987 lex_close(parser->lex);
5990 return !compile_errors;
5993 bool parser_compile_file(parser_t *parser, const char *filename)
5995 parser->lex = lex_open(filename);
5997 con_err("failed to open file \"%s\"\n", filename);
6000 return parser_compile(parser);
6003 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6005 parser->lex = lex_open_string(str, len, name);
6007 con_err("failed to create lexer for string \"%s\"\n", name);
6010 return parser_compile(parser);
6013 static void parser_remove_ast(parser_t *parser)
6016 if (parser->ast_cleaned)
6018 parser->ast_cleaned = true;
6019 for (i = 0; i < vec_size(parser->accessors); ++i) {
6020 ast_delete(parser->accessors[i]->constval.vfunc);
6021 parser->accessors[i]->constval.vfunc = NULL;
6022 ast_delete(parser->accessors[i]);
6024 for (i = 0; i < vec_size(parser->functions); ++i) {
6025 ast_delete(parser->functions[i]);
6027 for (i = 0; i < vec_size(parser->fields); ++i) {
6028 ast_delete(parser->fields[i]);
6030 for (i = 0; i < vec_size(parser->globals); ++i) {
6031 ast_delete(parser->globals[i]);
6033 vec_free(parser->accessors);
6034 vec_free(parser->functions);
6035 vec_free(parser->globals);
6036 vec_free(parser->fields);
6038 for (i = 0; i < vec_size(parser->variables); ++i)
6039 util_htdel(parser->variables[i]);
6040 vec_free(parser->variables);
6041 vec_free(parser->_blocklocals);
6042 vec_free(parser->_locals);
6045 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6046 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6048 vec_free(parser->correct_variables);
6049 vec_free(parser->correct_variables_score);
6051 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6052 ast_delete(parser->_typedefs[i]);
6053 vec_free(parser->_typedefs);
6054 for (i = 0; i < vec_size(parser->typedefs); ++i)
6055 util_htdel(parser->typedefs[i]);
6056 vec_free(parser->typedefs);
6057 vec_free(parser->_blocktypedefs);
6059 vec_free(parser->_block_ctx);
6061 vec_free(parser->labels);
6062 vec_free(parser->gotos);
6063 vec_free(parser->breaks);
6064 vec_free(parser->continues);
6066 ast_value_delete(parser->nil);
6068 ast_value_delete(parser->const_vec[0]);
6069 ast_value_delete(parser->const_vec[1]);
6070 ast_value_delete(parser->const_vec[2]);
6072 if (parser->reserved_version)
6073 ast_value_delete(parser->reserved_version);
6075 util_htdel(parser->aliases);
6076 fold_cleanup(parser->fold);
6077 intrin_cleanup(parser->intrin);
6080 void parser_cleanup(parser_t *parser)
6082 parser_remove_ast(parser);
6086 bool parser_finish(parser_t *parser, const char *output)
6092 if (compile_errors) {
6093 con_out("*** there were compile errors\n");
6097 ir = ir_builder_new("gmqcc_out");
6099 con_out("failed to allocate builder\n");
6103 for (i = 0; i < vec_size(parser->fields); ++i) {
6106 if (!ast_istype(parser->fields[i], ast_value))
6108 field = (ast_value*)parser->fields[i];
6109 hasvalue = field->hasvalue;
6110 field->hasvalue = false;
6111 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6112 con_out("failed to generate field %s\n", field->name);
6113 ir_builder_delete(ir);
6118 ast_expression *subtype;
6119 field->hasvalue = true;
6120 subtype = field->expression.next;
6121 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6122 if (subtype->vtype == TYPE_FIELD)
6123 ifld->fieldtype = subtype->next->vtype;
6124 else if (subtype->vtype == TYPE_FUNCTION)
6125 ifld->outtype = subtype->next->vtype;
6126 (void)!ir_value_set_field(field->ir_v, ifld);
6129 for (i = 0; i < vec_size(parser->globals); ++i) {
6131 if (!ast_istype(parser->globals[i], ast_value))
6133 asvalue = (ast_value*)(parser->globals[i]);
6134 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6135 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6136 "unused global: `%s`", asvalue->name);
6138 if (!ast_global_codegen(asvalue, ir, false)) {
6139 con_out("failed to generate global %s\n", asvalue->name);
6140 ir_builder_delete(ir);
6144 /* Build function vararg accessor ast tree now before generating
6145 * immediates, because the accessors may add new immediates
6147 for (i = 0; i < vec_size(parser->functions); ++i) {
6148 ast_function *f = parser->functions[i];
6150 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6151 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6152 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6153 con_out("failed to generate vararg setter for %s\n", f->name);
6154 ir_builder_delete(ir);
6157 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6158 con_out("failed to generate vararg getter for %s\n", f->name);
6159 ir_builder_delete(ir);
6163 ast_delete(f->varargs);
6168 /* Now we can generate immediates */
6169 if (!fold_generate(parser->fold, ir))
6172 for (i = 0; i < vec_size(parser->globals); ++i) {
6174 if (!ast_istype(parser->globals[i], ast_value))
6176 asvalue = (ast_value*)(parser->globals[i]);
6177 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6179 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6180 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6181 "uninitialized constant: `%s`",
6183 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6184 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6185 "uninitialized global: `%s`",
6188 if (!ast_generate_accessors(asvalue, ir)) {
6189 ir_builder_delete(ir);
6193 for (i = 0; i < vec_size(parser->fields); ++i) {
6195 asvalue = (ast_value*)(parser->fields[i]->next);
6197 if (!ast_istype((ast_expression*)asvalue, ast_value))
6199 if (asvalue->expression.vtype != TYPE_ARRAY)
6201 if (!ast_generate_accessors(asvalue, ir)) {
6202 ir_builder_delete(ir);
6206 if (parser->reserved_version &&
6207 !ast_global_codegen(parser->reserved_version, ir, false))
6209 con_out("failed to generate reserved::version");
6210 ir_builder_delete(ir);
6213 for (i = 0; i < vec_size(parser->functions); ++i) {
6214 ast_function *f = parser->functions[i];
6215 if (!ast_function_codegen(f, ir)) {
6216 con_out("failed to generate function %s\n", f->name);
6217 ir_builder_delete(ir);
6222 generate_checksum(parser, ir);
6224 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6225 ir_builder_dump(ir, con_out);
6226 for (i = 0; i < vec_size(parser->functions); ++i) {
6227 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6228 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6229 ir_builder_delete(ir);
6233 parser_remove_ast(parser);
6235 if (compile_Werrors) {
6236 con_out("*** there were warnings treated as errors\n");
6237 compile_show_werrors();
6242 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6243 ir_builder_dump(ir, con_out);
6245 if (!ir_builder_generate(ir, output)) {
6246 con_out("*** failed to generate output file\n");
6247 ir_builder_delete(ir);
6251 ir_builder_delete(ir);