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
28 #define PARSER_HT_LOCALS 2
29 #define PARSER_HT_SIZE 512
30 #define TYPEDEF_HT_SIZE 512
32 static void parser_enterblock(parser_t *parser);
33 static bool parser_leaveblock(parser_t *parser);
34 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
35 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
36 static bool parse_typedef(parser_t *parser);
37 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);
38 static ast_block* parse_block(parser_t *parser);
39 static bool parse_block_into(parser_t *parser, ast_block *block);
40 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
41 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
42 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
43 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
44 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
45 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
46 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
48 static void parseerror(parser_t *parser, const char *fmt, ...)
52 vcompile_error(parser->lex->tok.ctx, fmt, ap);
56 /* returns true if it counts as an error */
57 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
62 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
67 /**********************************************************************
71 static bool parser_next(parser_t *parser)
73 /* lex_do kills the previous token */
74 parser->tok = lex_do(parser->lex);
75 if (parser->tok == TOKEN_EOF)
77 if (parser->tok >= TOKEN_ERROR) {
78 parseerror(parser, "lex error");
84 #define parser_tokval(p) ((p)->lex->tok.value)
85 #define parser_token(p) (&((p)->lex->tok))
87 char *parser_strdup(const char *str)
90 /* actually dup empty strings */
91 char *out = (char*)mem_a(1);
95 return util_strdup(str);
98 static ast_expression* parser_find_field(parser_t *parser, const char *name)
100 return ( ast_expression*)util_htget(parser->htfields, name);
103 static ast_expression* parser_find_label(parser_t *parser, const char *name)
106 for(i = 0; i < vec_size(parser->labels); i++)
107 if (!strcmp(parser->labels[i]->name, name))
108 return (ast_expression*)parser->labels[i];
112 ast_expression* parser_find_global(parser_t *parser, const char *name)
114 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
117 return (ast_expression*)util_htget(parser->htglobals, name);
120 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->vtype;
127 for (i = 0; i < vec_size(fun->expression.params); ++i) {
128 if (!strcmp(fun->expression.params[i]->name, name))
129 return (ast_expression*)(fun->expression.params[i]);
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = vec_size(parser->variables); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_var(parser_t *parser, const char *name)
155 v = parser_find_local(parser, name, 0, &dummy);
156 if (!v) v = parser_find_global(parser, name);
160 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
164 hash = util_hthash(parser->typedefs[0], name);
166 for (i = vec_size(parser->typedefs); i > upto;) {
168 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 size_t etype; /* 0 = expression, others are operators */
180 ast_block *block; /* for commas and function calls */
199 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
210 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
214 e.out = (ast_expression*)v;
221 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
223 e.etype = 1 + (op - operators);
232 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
243 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
244 * so we need to rotate it to become ent.(foo[n]).
246 static bool rotate_entfield_array_index_nodes(ast_expression **out)
248 ast_array_index *index, *oldindex;
249 ast_entfield *entfield;
253 ast_expression *entity;
255 lex_ctx_t ctx = ast_ctx(*out);
257 if (!ast_istype(*out, ast_array_index))
259 index = (ast_array_index*)*out;
261 if (!ast_istype(index->array, ast_entfield))
263 entfield = (ast_entfield*)index->array;
265 if (!ast_istype(entfield->field, ast_value))
267 field = (ast_value*)entfield->field;
270 entity = entfield->entity;
274 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
275 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
276 *out = (ast_expression*)entfield;
278 oldindex->array = NULL;
279 oldindex->index = NULL;
280 ast_delete(oldindex);
285 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
287 if (ast_istype(expr, ast_value)) {
288 ast_value *val = (ast_value*)expr;
289 if (val->cvq == CV_CONST) {
290 if (val->name[0] == '#') {
291 compile_error(ctx, "invalid assignment to a literal constant");
295 * To work around quakeworld we must elide the error and make it
298 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
299 compile_error(ctx, "assignment to constant `%s`", val->name);
301 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
308 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
312 ast_expression *out = NULL;
313 ast_expression *exprs[3];
314 ast_block *blocks[3];
315 ast_binstore *asbinstore;
316 size_t i, assignop, addop, subop;
317 qcint_t generated_op = 0;
322 if (!vec_size(sy->ops)) {
323 parseerror(parser, "internal error: missing operator");
327 if (vec_last(sy->ops).isparen) {
328 parseerror(parser, "unmatched parenthesis");
332 op = &operators[vec_last(sy->ops).etype - 1];
333 ctx = vec_last(sy->ops).ctx;
335 if (vec_size(sy->out) < op->operands) {
336 if (op->flags & OP_PREFIX)
337 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
338 else /* this should have errored previously already */
339 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
343 vec_shrinkby(sy->ops, 1);
345 /* op(:?) has no input and no output */
349 vec_shrinkby(sy->out, op->operands);
350 for (i = 0; i < op->operands; ++i) {
351 exprs[i] = sy->out[vec_size(sy->out)+i].out;
352 blocks[i] = sy->out[vec_size(sy->out)+i].block;
354 if (exprs[i]->vtype == TYPE_NOEXPR &&
355 !(i != 0 && op->id == opid2('?',':')) &&
356 !(i == 1 && op->id == opid1('.')))
358 if (ast_istype(exprs[i], ast_label))
359 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
361 compile_error(ast_ctx(exprs[i]), "not an expression");
362 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
366 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
367 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
371 #define NotSameType(T) \
372 (exprs[0]->vtype != exprs[1]->vtype || \
373 exprs[0]->vtype != T)
377 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
381 if (exprs[0]->vtype == TYPE_VECTOR &&
382 exprs[1]->vtype == TYPE_NOEXPR)
384 if (exprs[1] == (ast_expression*)parser->const_vec[0])
385 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
386 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
387 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
388 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
389 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
391 compile_error(ctx, "access to invalid vector component");
395 else if (exprs[0]->vtype == TYPE_ENTITY) {
396 if (exprs[1]->vtype != TYPE_FIELD) {
397 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
400 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
402 else if (exprs[0]->vtype == TYPE_VECTOR) {
403 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
407 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
413 if (exprs[0]->vtype != TYPE_ARRAY &&
414 !(exprs[0]->vtype == TYPE_FIELD &&
415 exprs[0]->next->vtype == TYPE_ARRAY))
417 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
418 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
421 if (exprs[1]->vtype != TYPE_FLOAT) {
422 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
423 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
426 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
427 if (rotate_entfield_array_index_nodes(&out))
430 /* This is not broken in fteqcc anymore */
431 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
432 /* this error doesn't need to make us bail out */
433 (void)!parsewarning(parser, WARN_EXTENSIONS,
434 "accessing array-field members of an entity without parenthesis\n"
435 " -> this is an extension from -std=gmqcc");
442 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
443 vec_push(sy->out, syexp(ctx, exprs[0]));
444 vec_push(sy->out, syexp(ctx, exprs[1]));
445 vec_last(sy->argc)++;
449 if (!ast_block_add_expr(blocks[0], exprs[1]))
452 blocks[0] = ast_block_new(ctx);
453 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
454 !ast_block_add_expr(blocks[0], exprs[1]))
459 ast_block_set_type(blocks[0], exprs[1]);
461 vec_push(sy->out, syblock(ctx, blocks[0]));
468 if (!(out = fold_op(parser->fold, op, exprs))) {
469 if (exprs[0]->vtype != TYPE_FLOAT &&
470 exprs[0]->vtype != TYPE_VECTOR) {
471 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
472 type_name[exprs[0]->vtype]);
476 * TYPE_VECTOR = TYPE_FLOAT+1,
477 * VINSTR_NEG_V = VINSTR_NEG_F+1,
478 * thus (VINSTR_NEG_F-TYPE_FLOAT) + TYPE_* = VINSTR_NEG_*.
480 out = (ast_expression*)ast_unary_new(ctx, (VINSTR_NEG_F-TYPE_FLOAT) + exprs[0]->vtype, exprs[0]);
485 if (!(out = fold_op(parser->fold, op, exprs))) {
486 switch (exprs[0]->vtype) {
488 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
491 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
494 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
495 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
497 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
499 /* we don't constant-fold NOT for these types */
501 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
504 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
507 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
508 type_name[exprs[0]->vtype]);
515 if (exprs[0]->vtype != exprs[1]->vtype ||
516 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
518 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
519 type_name[exprs[0]->vtype],
520 type_name[exprs[1]->vtype]);
523 if (!(out = fold_op(parser->fold, op, exprs))) {
524 switch (exprs[0]->vtype) {
526 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
529 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
532 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
533 type_name[exprs[0]->vtype],
534 type_name[exprs[1]->vtype]);
540 if (exprs[0]->vtype != exprs[1]->vtype ||
541 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
543 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
544 type_name[exprs[1]->vtype],
545 type_name[exprs[0]->vtype]);
548 if (!(out = fold_op(parser->fold, op, exprs))) {
549 switch (exprs[0]->vtype) {
551 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
554 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
557 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
558 type_name[exprs[1]->vtype],
559 type_name[exprs[0]->vtype]);
565 if (exprs[0]->vtype != exprs[1]->vtype &&
566 !(exprs[0]->vtype == TYPE_VECTOR &&
567 exprs[1]->vtype == TYPE_FLOAT) &&
568 !(exprs[1]->vtype == TYPE_VECTOR &&
569 exprs[0]->vtype == TYPE_FLOAT)
572 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
573 type_name[exprs[1]->vtype],
574 type_name[exprs[0]->vtype]);
577 if (!(out = fold_op(parser->fold, op, exprs))) {
578 switch (exprs[0]->vtype) {
580 if (exprs[1]->vtype == TYPE_VECTOR)
581 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
583 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
586 if (exprs[1]->vtype == TYPE_FLOAT)
587 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
589 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
592 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
593 type_name[exprs[1]->vtype],
594 type_name[exprs[0]->vtype]);
601 if (exprs[1]->vtype != TYPE_FLOAT) {
602 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
603 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
604 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
607 if (!(out = fold_op(parser->fold, op, exprs))) {
608 if (exprs[0]->vtype == TYPE_FLOAT)
609 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
611 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
612 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
613 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
620 if (NotSameType(TYPE_FLOAT)) {
621 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
622 type_name[exprs[0]->vtype],
623 type_name[exprs[1]->vtype]);
625 } else if (!(out = fold_op(parser->fold, op, exprs))) {
626 /* generate a call to __builtin_mod */
627 ast_expression *mod = intrin_func(parser->intrin, "mod");
628 ast_call *call = NULL;
629 if (!mod) return false; /* can return null for missing floor */
631 call = ast_call_new(parser_ctx(parser), mod);
632 vec_push(call->params, exprs[0]);
633 vec_push(call->params, exprs[1]);
635 out = (ast_expression*)call;
640 compile_error(ctx, "%= is unimplemented");
646 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
647 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
648 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
650 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
651 type_name[exprs[0]->vtype],
652 type_name[exprs[1]->vtype]);
656 if (!(out = fold_op(parser->fold, op, exprs))) {
658 * IF the first expression is float, the following will be too
659 * since scalar ^ vector is not allowed.
661 if (exprs[0]->vtype == TYPE_FLOAT) {
662 out = (ast_expression*)ast_binary_new(ctx,
663 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
667 * The first is a vector: vector is allowed to bitop with vector and
668 * with scalar, branch here for the second operand.
670 if (exprs[1]->vtype == TYPE_VECTOR) {
672 * Bitop all the values of the vector components against the
673 * vectors components in question.
675 out = (ast_expression*)ast_binary_new(ctx,
676 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
679 out = (ast_expression*)ast_binary_new(ctx,
680 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
689 case opid3('<','<','='):
690 case opid3('>','>','='):
691 if(!(out = fold_op(parser->fold, op, exprs))) {
692 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
698 generated_op += 1; /* INSTR_OR */
700 generated_op += INSTR_AND;
701 if (!(out = fold_op(parser->fold, op, exprs))) {
702 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
703 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
704 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
705 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
708 for (i = 0; i < 2; ++i) {
709 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
710 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
712 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
714 exprs[i] = out; out = NULL;
715 if (OPTS_FLAG(PERL_LOGIC)) {
716 /* here we want to keep the right expressions' type */
720 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
721 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
723 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
725 exprs[i] = out; out = NULL;
726 if (OPTS_FLAG(PERL_LOGIC)) {
727 /* here we want to keep the right expressions' type */
732 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
737 if (vec_last(sy->paren) != PAREN_TERNARY2) {
738 compile_error(ctx, "mismatched parenthesis/ternary");
742 if (!ast_compare_type(exprs[1], exprs[2])) {
743 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
744 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
745 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
748 if (!(out = fold_op(parser->fold, op, exprs)))
749 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
752 case opid2('*', '*'):
753 if (NotSameType(TYPE_FLOAT)) {
754 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
755 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
756 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
761 if (!(out = fold_op(parser->fold, op, exprs))) {
762 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
763 vec_push(gencall->params, exprs[0]);
764 vec_push(gencall->params, exprs[1]);
765 out = (ast_expression*)gencall;
769 case opid2('>', '<'):
770 if (NotSameType(TYPE_VECTOR)) {
771 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
772 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
773 compile_error(ctx, "invalid types used in cross product: %s and %s",
778 if (!(out = fold_op(parser->fold, op, exprs))) {
779 out = (ast_expression*)ast_binary_new(
789 case opid3('<','=','>'): /* -1, 0, or 1 */
790 if (NotSameType(TYPE_FLOAT)) {
791 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
792 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
793 compile_error(ctx, "invalid types used in comparision: %s and %s",
799 if (!(out = fold_op(parser->fold, op, exprs))) {
800 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
802 eq->refs = AST_REF_NONE;
805 out = (ast_expression*)ast_ternary_new(ctx,
806 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
808 (ast_expression*)parser->fold->imm_float[2],
811 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
813 (ast_expression*)parser->fold->imm_float[0],
816 (ast_expression*)parser->fold->imm_float[1]
826 generated_op += 1; /* INSTR_GT */
828 generated_op += 1; /* INSTR_LT */
829 case opid2('>', '='):
830 generated_op += 1; /* INSTR_GE */
831 case opid2('<', '='):
832 generated_op += INSTR_LE;
833 if (NotSameType(TYPE_FLOAT)) {
834 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
835 type_name[exprs[0]->vtype],
836 type_name[exprs[1]->vtype]);
839 if (!(out = fold_op(parser->fold, op, exprs)))
840 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
842 case opid2('!', '='):
843 if (exprs[0]->vtype != exprs[1]->vtype) {
844 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
845 type_name[exprs[0]->vtype],
846 type_name[exprs[1]->vtype]);
849 if (!(out = fold_op(parser->fold, op, exprs)))
850 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
852 case opid2('=', '='):
853 if (exprs[0]->vtype != exprs[1]->vtype) {
854 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
855 type_name[exprs[0]->vtype],
856 type_name[exprs[1]->vtype]);
859 if (!(out = fold_op(parser->fold, op, exprs)))
860 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
864 if (ast_istype(exprs[0], ast_entfield)) {
865 ast_expression *field = ((ast_entfield*)exprs[0])->field;
866 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
867 exprs[0]->vtype == TYPE_FIELD &&
868 exprs[0]->next->vtype == TYPE_VECTOR)
870 assignop = type_storep_instr[TYPE_VECTOR];
873 assignop = type_storep_instr[exprs[0]->vtype];
874 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
876 ast_type_to_string(field->next, ty1, sizeof(ty1));
877 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
878 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
879 field->next->vtype == TYPE_FUNCTION &&
880 exprs[1]->vtype == TYPE_FUNCTION)
882 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
883 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
886 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
891 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
892 exprs[0]->vtype == TYPE_FIELD &&
893 exprs[0]->next->vtype == TYPE_VECTOR)
895 assignop = type_store_instr[TYPE_VECTOR];
898 assignop = type_store_instr[exprs[0]->vtype];
901 if (assignop == VINSTR_END) {
902 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
903 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
904 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
906 else if (!ast_compare_type(exprs[0], exprs[1]))
908 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
909 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
910 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
911 exprs[0]->vtype == TYPE_FUNCTION &&
912 exprs[1]->vtype == TYPE_FUNCTION)
914 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
915 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
918 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
921 (void)check_write_to(ctx, exprs[0]);
922 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
924 case opid3('+','+','P'):
925 case opid3('-','-','P'):
927 if (exprs[0]->vtype != TYPE_FLOAT) {
928 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
929 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
932 if (op->id == opid3('+','+','P'))
936 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
937 if (ast_istype(exprs[0], ast_entfield)) {
938 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
940 (ast_expression*)parser->fold->imm_float[1]);
942 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
944 (ast_expression*)parser->fold->imm_float[1]);
947 case opid3('S','+','+'):
948 case opid3('S','-','-'):
950 if (exprs[0]->vtype != TYPE_FLOAT) {
951 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
952 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
955 if (op->id == opid3('S','+','+')) {
962 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
963 if (ast_istype(exprs[0], ast_entfield)) {
964 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
966 (ast_expression*)parser->fold->imm_float[1]);
968 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
970 (ast_expression*)parser->fold->imm_float[1]);
974 out = (ast_expression*)ast_binary_new(ctx, subop,
976 (ast_expression*)parser->fold->imm_float[1]);
980 if (exprs[0]->vtype != exprs[1]->vtype ||
981 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
983 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
984 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
985 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
989 (void)check_write_to(ctx, exprs[0]);
990 if (ast_istype(exprs[0], ast_entfield))
991 assignop = type_storep_instr[exprs[0]->vtype];
993 assignop = type_store_instr[exprs[0]->vtype];
994 switch (exprs[0]->vtype) {
996 out = (ast_expression*)ast_binstore_new(ctx, assignop,
997 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1001 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1002 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1003 exprs[0], exprs[1]);
1006 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1007 type_name[exprs[0]->vtype],
1008 type_name[exprs[1]->vtype]);
1012 case opid2('*','='):
1013 case opid2('/','='):
1014 if (exprs[1]->vtype != TYPE_FLOAT ||
1015 !(exprs[0]->vtype == TYPE_FLOAT ||
1016 exprs[0]->vtype == TYPE_VECTOR))
1018 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1019 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1020 compile_error(ctx, "invalid types used in expression: %s and %s",
1024 (void)check_write_to(ctx, exprs[0]);
1025 if (ast_istype(exprs[0], ast_entfield))
1026 assignop = type_storep_instr[exprs[0]->vtype];
1028 assignop = type_store_instr[exprs[0]->vtype];
1029 switch (exprs[0]->vtype) {
1031 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1032 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1033 exprs[0], exprs[1]);
1036 if (op->id == opid2('*','=')) {
1037 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1038 exprs[0], exprs[1]);
1040 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1041 (ast_expression*)parser->fold->imm_float[1],
1044 compile_error(ctx, "internal error: failed to generate division");
1047 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1052 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1053 type_name[exprs[0]->vtype],
1054 type_name[exprs[1]->vtype]);
1058 case opid2('&','='):
1059 case opid2('|','='):
1060 case opid2('^','='):
1061 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1062 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1063 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1064 compile_error(ctx, "invalid types used in expression: %s and %s",
1068 (void)check_write_to(ctx, exprs[0]);
1069 if (ast_istype(exprs[0], ast_entfield))
1070 assignop = type_storep_instr[exprs[0]->vtype];
1072 assignop = type_store_instr[exprs[0]->vtype];
1073 if (exprs[0]->vtype == TYPE_FLOAT)
1074 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1075 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1076 exprs[0], exprs[1]);
1078 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1079 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1080 exprs[0], exprs[1]);
1082 case opid3('&','~','='):
1083 /* This is like: a &= ~(b);
1084 * But QC has no bitwise-not, so we implement it as
1087 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1088 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1089 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1090 compile_error(ctx, "invalid types used in expression: %s and %s",
1094 if (ast_istype(exprs[0], ast_entfield))
1095 assignop = type_storep_instr[exprs[0]->vtype];
1097 assignop = type_store_instr[exprs[0]->vtype];
1098 if (exprs[0]->vtype == TYPE_FLOAT)
1099 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1101 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1104 (void)check_write_to(ctx, exprs[0]);
1105 if (exprs[0]->vtype == TYPE_FLOAT)
1106 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1108 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1109 asbinstore->keep_dest = true;
1110 out = (ast_expression*)asbinstore;
1113 case opid2('~', 'P'):
1114 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1115 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1116 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1119 if (!(out = fold_op(parser->fold, op, exprs))) {
1120 if (exprs[0]->vtype == TYPE_FLOAT) {
1121 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1123 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1130 compile_error(ctx, "failed to apply operator %s", op->op);
1134 vec_push(sy->out, syexp(ctx, out));
1138 static bool parser_close_call(parser_t *parser, shunt *sy)
1140 /* was a function call */
1141 ast_expression *fun;
1142 ast_value *funval = NULL;
1146 size_t paramcount, i;
1149 fid = vec_last(sy->ops).off;
1150 vec_shrinkby(sy->ops, 1);
1152 /* out[fid] is the function
1153 * everything above is parameters...
1155 if (!vec_size(sy->argc)) {
1156 parseerror(parser, "internal error: no argument counter available");
1160 paramcount = vec_last(sy->argc);
1163 if (vec_size(sy->out) < fid) {
1164 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1165 (unsigned long)vec_size(sy->out),
1167 (unsigned long)paramcount);
1172 * TODO handle this at the intrinsic level with an ast_intrinsic
1175 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1177 if (fid+2 != vec_size(sy->out) ||
1178 vec_last(sy->out).block)
1180 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1183 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1184 ast_unref(vec_last(sy->out).out);
1185 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1186 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1187 vec_shrinkby(sy->out, 1);
1192 * Now we need to determine if the function that is being called is
1193 * an intrinsic so we can evaluate if the arguments to it are constant
1194 * and than fruitfully fold them.
1196 #define fold_can_1(X) \
1197 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1198 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1200 if (fid + 1 < vec_size(sy->out))
1203 for (i = 0; i < paramcount; ++i) {
1204 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1211 * All is well which ends well, if we make it into here we can ignore the
1212 * intrinsic call and just evaluate it i.e constant fold it.
1214 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1215 ast_expression **exprs = NULL;
1216 ast_expression *foldval = NULL;
1218 for (i = 0; i < paramcount; i++)
1219 vec_push(exprs, sy->out[fid+1 + i].out);
1221 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1227 * Blub: what sorts of unreffing and resizing of
1228 * sy->out should I be doing here?
1230 sy->out[fid] = syexp(foldval->node.context, foldval);
1231 vec_shrinkby(sy->out, 1);
1238 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1243 if (fid+1 + paramcount != vec_size(sy->out)) {
1244 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1245 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1249 for (i = 0; i < paramcount; ++i)
1250 vec_push(call->params, sy->out[fid+1 + i].out);
1251 vec_shrinkby(sy->out, paramcount);
1252 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1253 if (parser->max_param_count < paramcount)
1254 parser->max_param_count = paramcount;
1256 if (ast_istype(fun, ast_value)) {
1257 funval = (ast_value*)fun;
1258 if ((fun->flags & AST_FLAG_VARIADIC) &&
1259 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1261 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1265 /* overwrite fid, the function, with a call */
1266 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1268 if (fun->vtype != TYPE_FUNCTION) {
1269 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1274 parseerror(parser, "could not determine function return type");
1277 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1279 if (fun->flags & AST_FLAG_DEPRECATED) {
1281 return !parsewarning(parser, WARN_DEPRECATED,
1282 "call to function (which is marked deprecated)\n",
1283 "-> it has been declared here: %s:%i",
1284 ast_ctx(fun).file, ast_ctx(fun).line);
1287 return !parsewarning(parser, WARN_DEPRECATED,
1288 "call to `%s` (which is marked deprecated)\n"
1289 "-> `%s` declared here: %s:%i",
1290 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1292 return !parsewarning(parser, WARN_DEPRECATED,
1293 "call to `%s` (deprecated: %s)\n"
1294 "-> `%s` declared here: %s:%i",
1295 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1299 if (vec_size(fun->params) != paramcount &&
1300 !((fun->flags & AST_FLAG_VARIADIC) &&
1301 vec_size(fun->params) < paramcount))
1303 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1305 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1306 "too %s parameters for call to %s: expected %i, got %i\n"
1307 " -> `%s` has been declared here: %s:%i",
1308 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1309 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1311 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1312 "too %s parameters for function call: expected %i, got %i\n"
1313 " -> it has been declared here: %s:%i",
1314 fewmany, (int)vec_size(fun->params), (int)paramcount,
1315 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1322 static bool parser_close_paren(parser_t *parser, shunt *sy)
1324 if (!vec_size(sy->ops)) {
1325 parseerror(parser, "unmatched closing paren");
1329 while (vec_size(sy->ops)) {
1330 if (vec_last(sy->ops).isparen) {
1331 if (vec_last(sy->paren) == PAREN_FUNC) {
1333 if (!parser_close_call(parser, sy))
1337 if (vec_last(sy->paren) == PAREN_EXPR) {
1339 if (!vec_size(sy->out)) {
1340 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1341 vec_shrinkby(sy->ops, 1);
1344 vec_shrinkby(sy->ops, 1);
1347 if (vec_last(sy->paren) == PAREN_INDEX) {
1349 /* pop off the parenthesis */
1350 vec_shrinkby(sy->ops, 1);
1351 /* then apply the index operator */
1352 if (!parser_sy_apply_operator(parser, sy))
1356 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1357 vec_last(sy->paren) = PAREN_TERNARY2;
1358 /* pop off the parenthesis */
1359 vec_shrinkby(sy->ops, 1);
1362 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1365 if (!parser_sy_apply_operator(parser, sy))
1371 static void parser_reclassify_token(parser_t *parser)
1374 if (parser->tok >= TOKEN_START)
1376 for (i = 0; i < operator_count; ++i) {
1377 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1378 parser->tok = TOKEN_OPERATOR;
1384 static ast_expression* parse_vararg_do(parser_t *parser)
1386 ast_expression *idx, *out;
1388 ast_value *funtype = parser->function->vtype;
1389 lex_ctx_t ctx = parser_ctx(parser);
1391 if (!parser->function->varargs) {
1392 parseerror(parser, "function has no variable argument list");
1396 if (!parser_next(parser) || parser->tok != '(') {
1397 parseerror(parser, "expected parameter index and type in parenthesis");
1400 if (!parser_next(parser)) {
1401 parseerror(parser, "error parsing parameter index");
1405 idx = parse_expression_leave(parser, true, false, false);
1409 if (parser->tok != ',') {
1410 if (parser->tok != ')') {
1412 parseerror(parser, "expected comma after parameter index");
1415 /* vararg piping: ...(start) */
1416 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1420 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1422 parseerror(parser, "expected typename for vararg");
1426 typevar = parse_typename(parser, NULL, NULL);
1432 if (parser->tok != ')') {
1434 ast_delete(typevar);
1435 parseerror(parser, "expected closing paren");
1439 if (funtype->expression.varparam &&
1440 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1444 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1445 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1446 compile_error(ast_ctx(typevar),
1447 "function was declared to take varargs of type `%s`, requested type is: %s",
1451 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1452 ast_type_adopt(out, typevar);
1453 ast_delete(typevar);
1457 static ast_expression* parse_vararg(parser_t *parser)
1459 bool old_noops = parser->lex->flags.noops;
1461 ast_expression *out;
1463 parser->lex->flags.noops = true;
1464 out = parse_vararg_do(parser);
1466 parser->lex->flags.noops = old_noops;
1470 /* not to be exposed */
1471 bool ftepp_predef_exists(const char *name);
1472 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1474 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1475 parser->tok == TOKEN_IDENT &&
1476 !strcmp(parser_tokval(parser), "_"))
1478 /* a translatable string */
1481 parser->lex->flags.noops = true;
1482 if (!parser_next(parser) || parser->tok != '(') {
1483 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1486 parser->lex->flags.noops = false;
1487 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1488 parseerror(parser, "expected a constant string in translatable-string extension");
1491 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1494 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1496 if (!parser_next(parser) || parser->tok != ')') {
1497 parseerror(parser, "expected closing paren after translatable string");
1502 else if (parser->tok == TOKEN_DOTS)
1505 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1506 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1509 va = parse_vararg(parser);
1512 vec_push(sy->out, syexp(parser_ctx(parser), va));
1515 else if (parser->tok == TOKEN_FLOATCONST) {
1516 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1519 vec_push(sy->out, syexp(parser_ctx(parser), val));
1522 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1523 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1526 vec_push(sy->out, syexp(parser_ctx(parser), val));
1529 else if (parser->tok == TOKEN_STRINGCONST) {
1530 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1533 vec_push(sy->out, syexp(parser_ctx(parser), val));
1536 else if (parser->tok == TOKEN_VECTORCONST) {
1537 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1540 vec_push(sy->out, syexp(parser_ctx(parser), val));
1543 else if (parser->tok == TOKEN_IDENT)
1545 const char *ctoken = parser_tokval(parser);
1546 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1547 ast_expression *var;
1548 /* a_vector.{x,y,z} */
1549 if (!vec_size(sy->ops) ||
1550 !vec_last(sy->ops).etype ||
1551 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1553 /* When adding more intrinsics, fix the above condition */
1556 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1558 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1560 var = parser_find_var(parser, parser_tokval(parser));
1562 var = parser_find_field(parser, parser_tokval(parser));
1564 if (!var && with_labels) {
1565 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1567 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1568 var = (ast_expression*)lbl;
1569 vec_push(parser->labels, lbl);
1572 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1573 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1576 * now we try for the real intrinsic hashtable. If the string
1577 * begins with __builtin, we simply skip past it, otherwise we
1578 * use the identifier as is.
1580 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1581 var = intrin_func(parser->intrin, parser_tokval(parser));
1585 char *correct = NULL;
1589 * sometimes people use preprocessing predefs without enabling them
1590 * i've done this thousands of times already myself. Lets check for
1591 * it in the predef table. And diagnose it better :)
1593 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1594 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1599 * TODO: determine the best score for the identifier: be it
1600 * a variable, a field.
1602 * We should also consider adding correction tables for
1603 * other things as well.
1605 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1607 correct_init(&corr);
1609 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1610 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1611 if (strcmp(correct, parser_tokval(parser))) {
1618 correct_free(&corr);
1621 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1626 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1632 if (ast_istype(var, ast_value)) {
1633 ((ast_value*)var)->uses++;
1635 else if (ast_istype(var, ast_member)) {
1636 ast_member *mem = (ast_member*)var;
1637 if (ast_istype(mem->owner, ast_value))
1638 ((ast_value*)(mem->owner))->uses++;
1641 vec_push(sy->out, syexp(parser_ctx(parser), var));
1644 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1648 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1650 ast_expression *expr = NULL;
1653 bool wantop = false;
1654 /* only warn once about an assignment in a truth value because the current code
1655 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1657 bool warn_parenthesis = true;
1659 /* count the parens because an if starts with one, so the
1660 * end of a condition is an unmatched closing paren
1664 memset(&sy, 0, sizeof(sy));
1666 parser->lex->flags.noops = false;
1668 parser_reclassify_token(parser);
1672 if (parser->tok == TOKEN_TYPENAME) {
1673 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1677 if (parser->tok == TOKEN_OPERATOR)
1679 /* classify the operator */
1680 const oper_info *op;
1681 const oper_info *olast = NULL;
1683 for (o = 0; o < operator_count; ++o) {
1684 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1685 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1686 !strcmp(parser_tokval(parser), operators[o].op))
1691 if (o == operator_count) {
1692 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1695 /* found an operator */
1698 /* when declaring variables, a comma starts a new variable */
1699 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1700 /* fixup the token */
1705 /* a colon without a pervious question mark cannot be a ternary */
1706 if (!ternaries && op->id == opid2(':','?')) {
1711 if (op->id == opid1(',')) {
1712 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1713 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1717 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1718 olast = &operators[vec_last(sy.ops).etype-1];
1720 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1721 while (olast && op->prec < olast->prec)
1723 if (!parser_sy_apply_operator(parser, &sy))
1725 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1726 olast = &operators[vec_last(sy.ops).etype-1];
1731 #define IsAssignOp(x) (\
1732 (x) == opid1('=') || \
1733 (x) == opid2('+','=') || \
1734 (x) == opid2('-','=') || \
1735 (x) == opid2('*','=') || \
1736 (x) == opid2('/','=') || \
1737 (x) == opid2('%','=') || \
1738 (x) == opid2('&','=') || \
1739 (x) == opid2('|','=') || \
1740 (x) == opid3('&','~','=') \
1742 if (warn_parenthesis) {
1743 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1744 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1745 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1748 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1749 warn_parenthesis = false;
1752 if (olast && olast->id != op->id) {
1753 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1754 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1756 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1757 warn_parenthesis = false;
1759 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1760 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1762 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1763 warn_parenthesis = false;
1769 (op->prec < olast->prec) ||
1770 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1772 if (!parser_sy_apply_operator(parser, &sy))
1774 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1775 olast = &operators[vec_last(sy.ops).etype-1];
1780 if (op->id == opid1('(')) {
1782 size_t sycount = vec_size(sy.out);
1783 /* we expected an operator, this is the function-call operator */
1784 vec_push(sy.paren, PAREN_FUNC);
1785 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1786 vec_push(sy.argc, 0);
1788 vec_push(sy.paren, PAREN_EXPR);
1789 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1792 } else if (op->id == opid1('[')) {
1794 parseerror(parser, "unexpected array subscript");
1797 vec_push(sy.paren, PAREN_INDEX);
1798 /* push both the operator and the paren, this makes life easier */
1799 vec_push(sy.ops, syop(parser_ctx(parser), op));
1800 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1802 } else if (op->id == opid2('?',':')) {
1803 vec_push(sy.ops, syop(parser_ctx(parser), op));
1804 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1807 vec_push(sy.paren, PAREN_TERNARY1);
1808 } else if (op->id == opid2(':','?')) {
1809 if (!vec_size(sy.paren)) {
1810 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1813 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1814 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1817 if (!parser_close_paren(parser, &sy))
1819 vec_push(sy.ops, syop(parser_ctx(parser), op));
1823 vec_push(sy.ops, syop(parser_ctx(parser), op));
1824 wantop = !!(op->flags & OP_SUFFIX);
1827 else if (parser->tok == ')') {
1828 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1829 if (!parser_sy_apply_operator(parser, &sy))
1832 if (!vec_size(sy.paren))
1835 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1836 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1839 if (!parser_close_paren(parser, &sy))
1842 /* must be a function call without parameters */
1843 if (vec_last(sy.paren) != PAREN_FUNC) {
1844 parseerror(parser, "closing paren in invalid position");
1847 if (!parser_close_paren(parser, &sy))
1852 else if (parser->tok == '(') {
1853 parseerror(parser, "internal error: '(' should be classified as operator");
1856 else if (parser->tok == '[') {
1857 parseerror(parser, "internal error: '[' should be classified as operator");
1860 else if (parser->tok == ']') {
1861 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1862 if (!parser_sy_apply_operator(parser, &sy))
1865 if (!vec_size(sy.paren))
1867 if (vec_last(sy.paren) != PAREN_INDEX) {
1868 parseerror(parser, "mismatched parentheses, unexpected ']'");
1871 if (!parser_close_paren(parser, &sy))
1876 if (!parse_sya_operand(parser, &sy, with_labels))
1879 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1880 vec_last(sy.argc)++;
1885 /* in this case we might want to allow constant string concatenation */
1886 bool concatenated = false;
1887 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1888 ast_expression *lexpr = vec_last(sy.out).out;
1889 if (ast_istype(lexpr, ast_value)) {
1890 ast_value *last = (ast_value*)lexpr;
1891 if (last->isimm == true && last->cvq == CV_CONST &&
1892 last->hasvalue && last->expression.vtype == TYPE_STRING)
1894 char *newstr = NULL;
1895 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1896 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1898 concatenated = true;
1902 if (!concatenated) {
1903 parseerror(parser, "expected operator or end of statement");
1908 if (!parser_next(parser)) {
1911 if (parser->tok == ';' ||
1912 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1913 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1919 while (vec_size(sy.ops)) {
1920 if (!parser_sy_apply_operator(parser, &sy))
1924 parser->lex->flags.noops = true;
1925 if (vec_size(sy.out) != 1) {
1926 parseerror(parser, "expression expected");
1929 expr = sy.out[0].out;
1932 if (vec_size(sy.paren)) {
1933 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1941 parser->lex->flags.noops = true;
1942 for (i = 0; i < vec_size(sy.out); ++i) {
1944 ast_unref(sy.out[i].out);
1953 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1955 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1958 if (parser->tok != ';') {
1959 parseerror(parser, "semicolon expected after expression");
1963 if (!parser_next(parser)) {
1970 static void parser_enterblock(parser_t *parser)
1972 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1973 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1974 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1975 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1976 vec_push(parser->_block_ctx, parser_ctx(parser));
1979 vec_push(parser->correct_variables, correct_trie_new());
1980 vec_push(parser->correct_variables_score, NULL);
1983 static bool parser_leaveblock(parser_t *parser)
1986 size_t locals, typedefs;
1988 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1989 parseerror(parser, "internal error: parser_leaveblock with no block");
1993 util_htdel(vec_last(parser->variables));
1994 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1996 vec_pop(parser->variables);
1997 vec_pop(parser->correct_variables);
1998 vec_pop(parser->correct_variables_score);
1999 if (!vec_size(parser->_blocklocals)) {
2000 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2004 locals = vec_last(parser->_blocklocals);
2005 vec_pop(parser->_blocklocals);
2006 while (vec_size(parser->_locals) != locals) {
2007 ast_expression *e = vec_last(parser->_locals);
2008 ast_value *v = (ast_value*)e;
2009 vec_pop(parser->_locals);
2010 if (ast_istype(e, ast_value) && !v->uses) {
2011 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2016 typedefs = vec_last(parser->_blocktypedefs);
2017 while (vec_size(parser->_typedefs) != typedefs) {
2018 ast_delete(vec_last(parser->_typedefs));
2019 vec_pop(parser->_typedefs);
2021 util_htdel(vec_last(parser->typedefs));
2022 vec_pop(parser->typedefs);
2024 vec_pop(parser->_block_ctx);
2029 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2031 vec_push(parser->_locals, e);
2032 util_htset(vec_last(parser->variables), name, (void*)e);
2036 vec_last(parser->correct_variables),
2037 &vec_last(parser->correct_variables_score),
2042 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2044 vec_push(parser->globals, e);
2045 util_htset(parser->htglobals, name, e);
2049 parser->correct_variables[0],
2050 &parser->correct_variables_score[0],
2055 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2059 ast_expression *prev;
2061 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2063 ast_type_to_string(cond, ty, sizeof(ty));
2064 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2067 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2070 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2073 parseerror(parser, "internal error: failed to process condition");
2078 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2080 /* vector types need to be cast to true booleans */
2081 ast_binary *bin = (ast_binary*)cond;
2082 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2084 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2086 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2089 parseerror(parser, "internal error: failed to process condition");
2096 unary = (ast_unary*)cond;
2097 /* ast_istype dereferences cond, should test here for safety */
2098 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2100 cond = unary->operand;
2101 unary->operand = NULL;
2104 unary = (ast_unary*)cond;
2108 parseerror(parser, "internal error: failed to process condition");
2110 if (ifnot) *_ifnot = !*_ifnot;
2114 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2117 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2120 lex_ctx_t ctx = parser_ctx(parser);
2122 (void)block; /* not touching */
2124 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2125 if (!parser_next(parser)) {
2126 parseerror(parser, "expected condition or 'not'");
2129 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2131 if (!parser_next(parser)) {
2132 parseerror(parser, "expected condition in parenthesis");
2136 if (parser->tok != '(') {
2137 parseerror(parser, "expected 'if' condition in parenthesis");
2140 /* parse into the expression */
2141 if (!parser_next(parser)) {
2142 parseerror(parser, "expected 'if' condition after opening paren");
2145 /* parse the condition */
2146 cond = parse_expression_leave(parser, false, true, false);
2150 if (parser->tok != ')') {
2151 parseerror(parser, "expected closing paren after 'if' condition");
2155 /* parse into the 'then' branch */
2156 if (!parser_next(parser)) {
2157 parseerror(parser, "expected statement for on-true branch of 'if'");
2161 if (!parse_statement_or_block(parser, &ontrue)) {
2166 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2167 /* check for an else */
2168 if (!strcmp(parser_tokval(parser), "else")) {
2169 /* parse into the 'else' branch */
2170 if (!parser_next(parser)) {
2171 parseerror(parser, "expected on-false branch after 'else'");
2176 if (!parse_statement_or_block(parser, &onfalse)) {
2183 cond = process_condition(parser, cond, &ifnot);
2185 if (ontrue) ast_delete(ontrue);
2186 if (onfalse) ast_delete(onfalse);
2191 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2193 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2194 *out = (ast_expression*)ifthen;
2198 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2199 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2204 /* skip the 'while' and get the body */
2205 if (!parser_next(parser)) {
2206 if (OPTS_FLAG(LOOP_LABELS))
2207 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2209 parseerror(parser, "expected 'while' condition in parenthesis");
2213 if (parser->tok == ':') {
2214 if (!OPTS_FLAG(LOOP_LABELS))
2215 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2216 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2217 parseerror(parser, "expected loop label");
2220 label = util_strdup(parser_tokval(parser));
2221 if (!parser_next(parser)) {
2223 parseerror(parser, "expected 'while' condition in parenthesis");
2228 if (parser->tok != '(') {
2229 parseerror(parser, "expected 'while' condition in parenthesis");
2233 vec_push(parser->breaks, label);
2234 vec_push(parser->continues, label);
2236 rv = parse_while_go(parser, block, out);
2239 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2240 parseerror(parser, "internal error: label stack corrupted");
2246 vec_pop(parser->breaks);
2247 vec_pop(parser->continues);
2252 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2255 ast_expression *cond, *ontrue;
2259 lex_ctx_t ctx = parser_ctx(parser);
2261 (void)block; /* not touching */
2263 /* parse into the expression */
2264 if (!parser_next(parser)) {
2265 parseerror(parser, "expected 'while' condition after opening paren");
2268 /* parse the condition */
2269 cond = parse_expression_leave(parser, false, true, false);
2273 if (parser->tok != ')') {
2274 parseerror(parser, "expected closing paren after 'while' condition");
2278 /* parse into the 'then' branch */
2279 if (!parser_next(parser)) {
2280 parseerror(parser, "expected while-loop body");
2284 if (!parse_statement_or_block(parser, &ontrue)) {
2289 cond = process_condition(parser, cond, &ifnot);
2294 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2295 *out = (ast_expression*)aloop;
2299 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2300 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2305 /* skip the 'do' and get the body */
2306 if (!parser_next(parser)) {
2307 if (OPTS_FLAG(LOOP_LABELS))
2308 parseerror(parser, "expected loop label or body");
2310 parseerror(parser, "expected loop body");
2314 if (parser->tok == ':') {
2315 if (!OPTS_FLAG(LOOP_LABELS))
2316 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2317 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2318 parseerror(parser, "expected loop label");
2321 label = util_strdup(parser_tokval(parser));
2322 if (!parser_next(parser)) {
2324 parseerror(parser, "expected loop body");
2329 vec_push(parser->breaks, label);
2330 vec_push(parser->continues, label);
2332 rv = parse_dowhile_go(parser, block, out);
2335 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2336 parseerror(parser, "internal error: label stack corrupted");
2339 * Test for NULL otherwise ast_delete dereferences null pointer
2347 vec_pop(parser->breaks);
2348 vec_pop(parser->continues);
2353 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2356 ast_expression *cond, *ontrue;
2360 lex_ctx_t ctx = parser_ctx(parser);
2362 (void)block; /* not touching */
2364 if (!parse_statement_or_block(parser, &ontrue))
2367 /* expect the "while" */
2368 if (parser->tok != TOKEN_KEYWORD ||
2369 strcmp(parser_tokval(parser), "while"))
2371 parseerror(parser, "expected 'while' and condition");
2376 /* skip the 'while' and check for opening paren */
2377 if (!parser_next(parser) || parser->tok != '(') {
2378 parseerror(parser, "expected 'while' condition in parenthesis");
2382 /* parse into the expression */
2383 if (!parser_next(parser)) {
2384 parseerror(parser, "expected 'while' condition after opening paren");
2388 /* parse the condition */
2389 cond = parse_expression_leave(parser, false, true, false);
2393 if (parser->tok != ')') {
2394 parseerror(parser, "expected closing paren after 'while' condition");
2400 if (!parser_next(parser) || parser->tok != ';') {
2401 parseerror(parser, "expected semicolon after condition");
2407 if (!parser_next(parser)) {
2408 parseerror(parser, "parse error");
2414 cond = process_condition(parser, cond, &ifnot);
2419 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2420 *out = (ast_expression*)aloop;
2424 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2425 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2430 /* skip the 'for' and check for opening paren */
2431 if (!parser_next(parser)) {
2432 if (OPTS_FLAG(LOOP_LABELS))
2433 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2435 parseerror(parser, "expected 'for' expressions in parenthesis");
2439 if (parser->tok == ':') {
2440 if (!OPTS_FLAG(LOOP_LABELS))
2441 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2442 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2443 parseerror(parser, "expected loop label");
2446 label = util_strdup(parser_tokval(parser));
2447 if (!parser_next(parser)) {
2449 parseerror(parser, "expected 'for' expressions in parenthesis");
2454 if (parser->tok != '(') {
2455 parseerror(parser, "expected 'for' expressions in parenthesis");
2459 vec_push(parser->breaks, label);
2460 vec_push(parser->continues, label);
2462 rv = parse_for_go(parser, block, out);
2465 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2466 parseerror(parser, "internal error: label stack corrupted");
2472 vec_pop(parser->breaks);
2473 vec_pop(parser->continues);
2477 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2480 ast_expression *initexpr, *cond, *increment, *ontrue;
2485 lex_ctx_t ctx = parser_ctx(parser);
2487 parser_enterblock(parser);
2494 /* parse into the expression */
2495 if (!parser_next(parser)) {
2496 parseerror(parser, "expected 'for' initializer after opening paren");
2501 if (parser->tok == TOKEN_IDENT)
2502 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2504 if (typevar || parser->tok == TOKEN_TYPENAME) {
2506 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2507 if (parsewarning(parser, WARN_EXTENSIONS,
2508 "current standard does not allow variable declarations in for-loop initializers"))
2512 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2515 else if (parser->tok != ';')
2517 initexpr = parse_expression_leave(parser, false, false, false);
2522 /* move on to condition */
2523 if (parser->tok != ';') {
2524 parseerror(parser, "expected semicolon after for-loop initializer");
2527 if (!parser_next(parser)) {
2528 parseerror(parser, "expected for-loop condition");
2532 /* parse the condition */
2533 if (parser->tok != ';') {
2534 cond = parse_expression_leave(parser, false, true, false);
2539 /* move on to incrementor */
2540 if (parser->tok != ';') {
2541 parseerror(parser, "expected semicolon after for-loop initializer");
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected for-loop condition");
2549 /* parse the incrementor */
2550 if (parser->tok != ')') {
2551 lex_ctx_t condctx = parser_ctx(parser);
2552 increment = parse_expression_leave(parser, false, false, false);
2555 if (!ast_side_effects(increment)) {
2556 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2562 if (parser->tok != ')') {
2563 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2566 /* parse into the 'then' branch */
2567 if (!parser_next(parser)) {
2568 parseerror(parser, "expected for-loop body");
2571 if (!parse_statement_or_block(parser, &ontrue))
2575 cond = process_condition(parser, cond, &ifnot);
2579 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2580 *out = (ast_expression*)aloop;
2582 if (!parser_leaveblock(parser)) {
2588 if (initexpr) ast_unref(initexpr);
2589 if (cond) ast_unref(cond);
2590 if (increment) ast_unref(increment);
2591 (void)!parser_leaveblock(parser);
2595 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2597 ast_expression *exp = NULL;
2598 ast_expression *var = NULL;
2599 ast_return *ret = NULL;
2600 ast_value *retval = parser->function->return_value;
2601 ast_value *expected = parser->function->vtype;
2603 lex_ctx_t ctx = parser_ctx(parser);
2605 (void)block; /* not touching */
2607 if (!parser_next(parser)) {
2608 parseerror(parser, "expected return expression");
2612 /* return assignments */
2613 if (parser->tok == '=') {
2614 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2615 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2619 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2621 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2622 parseerror(parser, "invalid return type: `%s'", ty1);
2626 if (!parser_next(parser)) {
2627 parseerror(parser, "expected return assignment expression");
2631 if (!(exp = parse_expression_leave(parser, false, false, false)))
2634 /* prepare the return value */
2636 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2637 ast_type_adopt(retval, expected->expression.next);
2638 parser->function->return_value = retval;
2641 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2642 char ty1[1024], ty2[1024];
2643 ast_type_to_string(exp, ty1, sizeof(ty1));
2644 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2645 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2648 /* store to 'return' local variable */
2649 var = (ast_expression*)ast_store_new(
2651 type_store_instr[expected->expression.next->vtype],
2652 (ast_expression*)retval, exp);
2659 if (parser->tok != ';')
2660 parseerror(parser, "missing semicolon after return assignment");
2661 else if (!parser_next(parser))
2662 parseerror(parser, "parse error after return assignment");
2668 if (parser->tok != ';') {
2669 exp = parse_expression(parser, false, false);
2673 if (exp->vtype != TYPE_NIL &&
2674 exp->vtype != ((ast_expression*)expected)->next->vtype)
2676 parseerror(parser, "return with invalid expression");
2679 ret = ast_return_new(ctx, exp);
2685 if (!parser_next(parser))
2686 parseerror(parser, "parse error");
2688 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2690 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2692 ret = ast_return_new(ctx, (ast_expression*)retval);
2694 *out = (ast_expression*)ret;
2698 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2701 unsigned int levels = 0;
2702 lex_ctx_t ctx = parser_ctx(parser);
2703 const char **loops = (is_continue ? parser->continues : parser->breaks);
2705 (void)block; /* not touching */
2706 if (!parser_next(parser)) {
2707 parseerror(parser, "expected semicolon or loop label");
2711 if (!vec_size(loops)) {
2713 parseerror(parser, "`continue` can only be used inside loops");
2715 parseerror(parser, "`break` can only be used inside loops or switches");
2718 if (parser->tok == TOKEN_IDENT) {
2719 if (!OPTS_FLAG(LOOP_LABELS))
2720 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2721 i = vec_size(loops);
2723 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2726 parseerror(parser, "no such loop to %s: `%s`",
2727 (is_continue ? "continue" : "break out of"),
2728 parser_tokval(parser));
2733 if (!parser_next(parser)) {
2734 parseerror(parser, "expected semicolon");
2739 if (parser->tok != ';') {
2740 parseerror(parser, "expected semicolon");
2744 if (!parser_next(parser))
2745 parseerror(parser, "parse error");
2747 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2751 /* returns true when it was a variable qualifier, false otherwise!
2752 * on error, cvq is set to CV_WRONG
2754 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2756 bool had_const = false;
2757 bool had_var = false;
2758 bool had_noref = false;
2759 bool had_attrib = false;
2760 bool had_static = false;
2765 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2767 /* parse an attribute */
2768 if (!parser_next(parser)) {
2769 parseerror(parser, "expected attribute after `[[`");
2773 if (!strcmp(parser_tokval(parser), "noreturn")) {
2774 flags |= AST_FLAG_NORETURN;
2775 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2776 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2781 else if (!strcmp(parser_tokval(parser), "noref")) {
2783 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2784 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2789 else if (!strcmp(parser_tokval(parser), "inline")) {
2790 flags |= AST_FLAG_INLINE;
2791 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2792 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2797 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2798 flags |= AST_FLAG_ERASEABLE;
2799 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2800 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2805 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2806 flags |= AST_FLAG_ALIAS;
2809 if (!parser_next(parser)) {
2810 parseerror(parser, "parse error in attribute");
2814 if (parser->tok == '(') {
2815 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2816 parseerror(parser, "`alias` attribute missing parameter");
2820 *message = util_strdup(parser_tokval(parser));
2822 if (!parser_next(parser)) {
2823 parseerror(parser, "parse error in attribute");
2827 if (parser->tok != ')') {
2828 parseerror(parser, "`alias` attribute expected `)` after parameter");
2832 if (!parser_next(parser)) {
2833 parseerror(parser, "parse error in attribute");
2838 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2839 parseerror(parser, "`alias` attribute expected `]]`");
2843 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2844 flags |= AST_FLAG_DEPRECATED;
2847 if (!parser_next(parser)) {
2848 parseerror(parser, "parse error in attribute");
2852 if (parser->tok == '(') {
2853 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2854 parseerror(parser, "`deprecated` attribute missing parameter");
2858 *message = util_strdup(parser_tokval(parser));
2860 if (!parser_next(parser)) {
2861 parseerror(parser, "parse error in attribute");
2865 if(parser->tok != ')') {
2866 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2870 if (!parser_next(parser)) {
2871 parseerror(parser, "parse error in attribute");
2876 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2877 parseerror(parser, "`deprecated` attribute expected `]]`");
2880 if (*message) mem_d(*message);
2888 /* Skip tokens until we hit a ]] */
2889 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2890 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2891 if (!parser_next(parser)) {
2892 parseerror(parser, "error inside attribute");
2899 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2901 else if (!strcmp(parser_tokval(parser), "const"))
2903 else if (!strcmp(parser_tokval(parser), "var"))
2905 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2907 else if (!strcmp(parser_tokval(parser), "noref"))
2909 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2914 if (!parser_next(parser))
2924 *is_static = had_static;
2928 parseerror(parser, "parse error after variable qualifier");
2933 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2934 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2939 /* skip the 'while' and get the body */
2940 if (!parser_next(parser)) {
2941 if (OPTS_FLAG(LOOP_LABELS))
2942 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2944 parseerror(parser, "expected 'switch' operand in parenthesis");
2948 if (parser->tok == ':') {
2949 if (!OPTS_FLAG(LOOP_LABELS))
2950 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2951 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2952 parseerror(parser, "expected loop label");
2955 label = util_strdup(parser_tokval(parser));
2956 if (!parser_next(parser)) {
2958 parseerror(parser, "expected 'switch' operand in parenthesis");
2963 if (parser->tok != '(') {
2964 parseerror(parser, "expected 'switch' operand in parenthesis");
2968 vec_push(parser->breaks, label);
2970 rv = parse_switch_go(parser, block, out);
2973 if (vec_last(parser->breaks) != label) {
2974 parseerror(parser, "internal error: label stack corrupted");
2980 vec_pop(parser->breaks);
2985 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2987 ast_expression *operand;
2990 ast_switch *switchnode;
2991 ast_switch_case swcase;
2994 bool noref, is_static;
2995 uint32_t qflags = 0;
2997 lex_ctx_t ctx = parser_ctx(parser);
2999 (void)block; /* not touching */
3002 /* parse into the expression */
3003 if (!parser_next(parser)) {
3004 parseerror(parser, "expected switch operand");
3007 /* parse the operand */
3008 operand = parse_expression_leave(parser, false, false, false);
3012 switchnode = ast_switch_new(ctx, operand);
3015 if (parser->tok != ')') {
3016 ast_delete(switchnode);
3017 parseerror(parser, "expected closing paren after 'switch' operand");
3021 /* parse over the opening paren */
3022 if (!parser_next(parser) || parser->tok != '{') {
3023 ast_delete(switchnode);
3024 parseerror(parser, "expected list of cases");
3028 if (!parser_next(parser)) {
3029 ast_delete(switchnode);
3030 parseerror(parser, "expected 'case' or 'default'");
3034 /* new block; allow some variables to be declared here */
3035 parser_enterblock(parser);
3038 if (parser->tok == TOKEN_IDENT)
3039 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3040 if (typevar || parser->tok == TOKEN_TYPENAME) {
3041 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3042 ast_delete(switchnode);
3047 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3049 if (cvq == CV_WRONG) {
3050 ast_delete(switchnode);
3053 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3054 ast_delete(switchnode);
3063 while (parser->tok != '}') {
3064 ast_block *caseblock;
3066 if (!strcmp(parser_tokval(parser), "case")) {
3067 if (!parser_next(parser)) {
3068 ast_delete(switchnode);
3069 parseerror(parser, "expected expression for case");
3072 swcase.value = parse_expression_leave(parser, false, false, false);
3073 if (!swcase.value) {
3074 ast_delete(switchnode);
3075 parseerror(parser, "expected expression for case");
3078 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3079 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3080 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3086 else if (!strcmp(parser_tokval(parser), "default")) {
3087 swcase.value = NULL;
3088 if (!parser_next(parser)) {
3089 ast_delete(switchnode);
3090 parseerror(parser, "expected colon");
3095 ast_delete(switchnode);
3096 parseerror(parser, "expected 'case' or 'default'");
3100 /* Now the colon and body */
3101 if (parser->tok != ':') {
3102 if (swcase.value) ast_unref(swcase.value);
3103 ast_delete(switchnode);
3104 parseerror(parser, "expected colon");
3108 if (!parser_next(parser)) {
3109 if (swcase.value) ast_unref(swcase.value);
3110 ast_delete(switchnode);
3111 parseerror(parser, "expected statements or case");
3114 caseblock = ast_block_new(parser_ctx(parser));
3116 if (swcase.value) ast_unref(swcase.value);
3117 ast_delete(switchnode);
3120 swcase.code = (ast_expression*)caseblock;
3121 vec_push(switchnode->cases, swcase);
3123 ast_expression *expr;
3124 if (parser->tok == '}')
3126 if (parser->tok == TOKEN_KEYWORD) {
3127 if (!strcmp(parser_tokval(parser), "case") ||
3128 !strcmp(parser_tokval(parser), "default"))
3133 if (!parse_statement(parser, caseblock, &expr, true)) {
3134 ast_delete(switchnode);
3139 if (!ast_block_add_expr(caseblock, expr)) {
3140 ast_delete(switchnode);
3146 parser_leaveblock(parser);
3149 if (parser->tok != '}') {
3150 ast_delete(switchnode);
3151 parseerror(parser, "expected closing paren of case list");
3154 if (!parser_next(parser)) {
3155 ast_delete(switchnode);
3156 parseerror(parser, "parse error after switch");
3159 *out = (ast_expression*)switchnode;
3163 /* parse computed goto sides */
3164 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3165 ast_expression *on_true;
3166 ast_expression *on_false;
3167 ast_expression *cond;
3172 if (ast_istype(*side, ast_ternary)) {
3173 ast_ternary *tern = (ast_ternary*)*side;
3174 on_true = parse_goto_computed(parser, &tern->on_true);
3175 on_false = parse_goto_computed(parser, &tern->on_false);
3177 if (!on_true || !on_false) {
3178 parseerror(parser, "expected label or expression in ternary");
3179 if (on_true) ast_unref(on_true);
3180 if (on_false) ast_unref(on_false);
3188 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3189 } else if (ast_istype(*side, ast_label)) {
3190 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3191 ast_goto_set_label(gt, ((ast_label*)*side));
3193 return (ast_expression*)gt;
3198 static bool parse_goto(parser_t *parser, ast_expression **out)
3200 ast_goto *gt = NULL;
3201 ast_expression *lbl;
3203 if (!parser_next(parser))
3206 if (parser->tok != TOKEN_IDENT) {
3207 ast_expression *expression;
3209 /* could be an expression i.e computed goto :-) */
3210 if (parser->tok != '(') {
3211 parseerror(parser, "expected label name after `goto`");
3215 /* failed to parse expression for goto */
3216 if (!(expression = parse_expression(parser, false, true)) ||
3217 !(*out = parse_goto_computed(parser, &expression))) {
3218 parseerror(parser, "invalid goto expression");
3220 ast_unref(expression);
3227 /* not computed goto */
3228 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3229 lbl = parser_find_label(parser, gt->name);
3231 if (!ast_istype(lbl, ast_label)) {
3232 parseerror(parser, "internal error: label is not an ast_label");
3236 ast_goto_set_label(gt, (ast_label*)lbl);
3239 vec_push(parser->gotos, gt);
3241 if (!parser_next(parser) || parser->tok != ';') {
3242 parseerror(parser, "semicolon expected after goto label");
3245 if (!parser_next(parser)) {
3246 parseerror(parser, "parse error after goto");
3250 *out = (ast_expression*)gt;
3254 static bool parse_skipwhite(parser_t *parser)
3257 if (!parser_next(parser))
3259 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3260 return parser->tok < TOKEN_ERROR;
3263 static bool parse_eol(parser_t *parser)
3265 if (!parse_skipwhite(parser))
3267 return parser->tok == TOKEN_EOL;
3270 static bool parse_pragma_do(parser_t *parser)
3272 if (!parser_next(parser) ||
3273 parser->tok != TOKEN_IDENT ||
3274 strcmp(parser_tokval(parser), "pragma"))
3276 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3279 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3280 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3284 if (!strcmp(parser_tokval(parser), "noref")) {
3285 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3286 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3289 parser->noref = !!parser_token(parser)->constval.i;
3290 if (!parse_eol(parser)) {
3291 parseerror(parser, "parse error after `noref` pragma");
3297 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3300 while (!parse_eol(parser)) {
3301 parser_next(parser);
3310 static bool parse_pragma(parser_t *parser)
3313 parser->lex->flags.preprocessing = true;
3314 parser->lex->flags.mergelines = true;
3315 rv = parse_pragma_do(parser);
3316 if (parser->tok != TOKEN_EOL) {
3317 parseerror(parser, "junk after pragma");
3320 parser->lex->flags.preprocessing = false;
3321 parser->lex->flags.mergelines = false;
3322 if (!parser_next(parser)) {
3323 parseerror(parser, "parse error after pragma");
3329 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3331 bool noref, is_static;
3333 uint32_t qflags = 0;
3334 ast_value *typevar = NULL;
3335 char *vstring = NULL;
3339 if (parser->tok == TOKEN_IDENT)
3340 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3342 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3344 /* local variable */
3346 parseerror(parser, "cannot declare a variable from here");
3349 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3350 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3353 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3357 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3359 if (cvq == CV_WRONG)
3361 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3363 else if (parser->tok == TOKEN_KEYWORD)
3365 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3370 if (!parser_next(parser)) {
3371 parseerror(parser, "parse error after __builtin_debug_printtype");
3375 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3377 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3378 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3379 if (!parser_next(parser)) {
3380 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3386 if (!parse_statement(parser, block, out, allow_cases))
3389 con_out("__builtin_debug_printtype: got no output node\n");
3392 ast_type_to_string(*out, ty, sizeof(ty));
3393 con_out("__builtin_debug_printtype: `%s`\n", ty);
3398 else if (!strcmp(parser_tokval(parser), "return"))
3400 return parse_return(parser, block, out);
3402 else if (!strcmp(parser_tokval(parser), "if"))
3404 return parse_if(parser, block, out);
3406 else if (!strcmp(parser_tokval(parser), "while"))
3408 return parse_while(parser, block, out);
3410 else if (!strcmp(parser_tokval(parser), "do"))
3412 return parse_dowhile(parser, block, out);
3414 else if (!strcmp(parser_tokval(parser), "for"))
3416 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3417 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3420 return parse_for(parser, block, out);
3422 else if (!strcmp(parser_tokval(parser), "break"))
3424 return parse_break_continue(parser, block, out, false);
3426 else if (!strcmp(parser_tokval(parser), "continue"))
3428 return parse_break_continue(parser, block, out, true);
3430 else if (!strcmp(parser_tokval(parser), "switch"))
3432 return parse_switch(parser, block, out);
3434 else if (!strcmp(parser_tokval(parser), "case") ||
3435 !strcmp(parser_tokval(parser), "default"))
3438 parseerror(parser, "unexpected 'case' label");
3443 else if (!strcmp(parser_tokval(parser), "goto"))
3445 return parse_goto(parser, out);
3447 else if (!strcmp(parser_tokval(parser), "typedef"))
3449 if (!parser_next(parser)) {
3450 parseerror(parser, "expected type definition after 'typedef'");
3453 return parse_typedef(parser);
3455 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3458 else if (parser->tok == '{')
3461 inner = parse_block(parser);
3464 *out = (ast_expression*)inner;
3467 else if (parser->tok == ':')
3471 if (!parser_next(parser)) {
3472 parseerror(parser, "expected label name");
3475 if (parser->tok != TOKEN_IDENT) {
3476 parseerror(parser, "label must be an identifier");
3479 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3481 if (!label->undefined) {
3482 parseerror(parser, "label `%s` already defined", label->name);
3485 label->undefined = false;
3488 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3489 vec_push(parser->labels, label);
3491 *out = (ast_expression*)label;
3492 if (!parser_next(parser)) {
3493 parseerror(parser, "parse error after label");
3496 for (i = 0; i < vec_size(parser->gotos); ++i) {
3497 if (!strcmp(parser->gotos[i]->name, label->name)) {
3498 ast_goto_set_label(parser->gotos[i], label);
3499 vec_remove(parser->gotos, i, 1);
3505 else if (parser->tok == ';')
3507 if (!parser_next(parser)) {
3508 parseerror(parser, "parse error after empty statement");
3515 lex_ctx_t ctx = parser_ctx(parser);
3516 ast_expression *exp = parse_expression(parser, false, false);
3520 if (!ast_side_effects(exp)) {
3521 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3528 static bool parse_enum(parser_t *parser)
3531 bool reverse = false;
3533 ast_value **values = NULL;
3534 ast_value *var = NULL;
3537 ast_expression *old;
3539 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3540 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3544 /* enumeration attributes (can add more later) */
3545 if (parser->tok == ':') {
3546 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3547 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3552 if (!strcmp(parser_tokval(parser), "flag")) {
3556 else if (!strcmp(parser_tokval(parser), "reverse")) {
3560 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3564 if (!parser_next(parser) || parser->tok != '{') {
3565 parseerror(parser, "expected `{` after enum attribute ");
3571 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3572 if (parser->tok == '}') {
3573 /* allow an empty enum */
3576 parseerror(parser, "expected identifier or `}`");
3580 old = parser_find_field(parser, parser_tokval(parser));
3582 old = parser_find_global(parser, parser_tokval(parser));
3584 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3585 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3589 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3590 vec_push(values, var);
3591 var->cvq = CV_CONST;
3592 var->hasvalue = true;
3594 /* for flagged enumerations increment in POTs of TWO */
3595 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3596 parser_addglobal(parser, var->name, (ast_expression*)var);
3598 if (!parser_next(parser)) {
3599 parseerror(parser, "expected `=`, `}` or comma after identifier");
3603 if (parser->tok == ',')
3605 if (parser->tok == '}')
3607 if (parser->tok != '=') {
3608 parseerror(parser, "expected `=`, `}` or comma after identifier");
3612 if (!parser_next(parser)) {
3613 parseerror(parser, "expected expression after `=`");
3617 /* We got a value! */
3618 old = parse_expression_leave(parser, true, false, false);
3619 asvalue = (ast_value*)old;
3620 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3621 compile_error(ast_ctx(var), "constant value or expression expected");
3624 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3626 if (parser->tok == '}')
3628 if (parser->tok != ',') {
3629 parseerror(parser, "expected `}` or comma after expression");
3634 /* patch them all (for reversed attribute) */
3637 for (i = 0; i < vec_size(values); i++)
3638 values[i]->constval.vfloat = vec_size(values) - i - 1;
3641 if (parser->tok != '}') {
3642 parseerror(parser, "internal error: breaking without `}`");
3646 if (!parser_next(parser) || parser->tok != ';') {
3647 parseerror(parser, "expected semicolon after enumeration");
3651 if (!parser_next(parser)) {
3652 parseerror(parser, "parse error after enumeration");
3664 static bool parse_block_into(parser_t *parser, ast_block *block)
3668 parser_enterblock(parser);
3670 if (!parser_next(parser)) { /* skip the '{' */
3671 parseerror(parser, "expected function body");
3675 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3677 ast_expression *expr = NULL;
3678 if (parser->tok == '}')
3681 if (!parse_statement(parser, block, &expr, false)) {
3682 /* parseerror(parser, "parse error"); */
3688 if (!ast_block_add_expr(block, expr)) {
3695 if (parser->tok != '}') {
3698 (void)parser_next(parser);
3702 if (!parser_leaveblock(parser))
3704 return retval && !!block;
3707 static ast_block* parse_block(parser_t *parser)
3710 block = ast_block_new(parser_ctx(parser));
3713 if (!parse_block_into(parser, block)) {
3714 ast_block_delete(block);
3720 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3722 if (parser->tok == '{') {
3723 *out = (ast_expression*)parse_block(parser);
3726 return parse_statement(parser, NULL, out, false);
3729 static bool create_vector_members(ast_value *var, ast_member **me)
3732 size_t len = strlen(var->name);
3734 for (i = 0; i < 3; ++i) {
3735 char *name = (char*)mem_a(len+3);
3736 memcpy(name, var->name, len);
3738 name[len+1] = 'x'+i;
3740 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3749 do { ast_member_delete(me[--i]); } while(i);
3753 static bool parse_function_body(parser_t *parser, ast_value *var)
3755 ast_block *block = NULL;
3760 ast_expression *framenum = NULL;
3761 ast_expression *nextthink = NULL;
3762 /* None of the following have to be deleted */
3763 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3764 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3765 bool has_frame_think;
3769 has_frame_think = false;
3770 old = parser->function;
3772 if (var->expression.flags & AST_FLAG_ALIAS) {
3773 parseerror(parser, "function aliases cannot have bodies");
3777 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3778 parseerror(parser, "gotos/labels leaking");
3782 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3783 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3784 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3790 if (parser->tok == '[') {
3791 /* got a frame definition: [ framenum, nextthink ]
3792 * this translates to:
3793 * self.frame = framenum;
3794 * self.nextthink = time + 0.1;
3795 * self.think = nextthink;
3799 fld_think = parser_find_field(parser, "think");
3800 fld_nextthink = parser_find_field(parser, "nextthink");
3801 fld_frame = parser_find_field(parser, "frame");
3802 if (!fld_think || !fld_nextthink || !fld_frame) {
3803 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3804 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3807 gbl_time = parser_find_global(parser, "time");
3808 gbl_self = parser_find_global(parser, "self");
3809 if (!gbl_time || !gbl_self) {
3810 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3811 parseerror(parser, "please declare the following globals: `time`, `self`");
3815 if (!parser_next(parser))
3818 framenum = parse_expression_leave(parser, true, false, false);
3820 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3823 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3824 ast_unref(framenum);
3825 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3829 if (parser->tok != ',') {
3830 ast_unref(framenum);
3831 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3832 parseerror(parser, "Got a %i\n", parser->tok);
3836 if (!parser_next(parser)) {
3837 ast_unref(framenum);
3841 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3843 /* qc allows the use of not-yet-declared functions here
3844 * - this automatically creates a prototype */
3845 ast_value *thinkfunc;
3846 ast_expression *functype = fld_think->next;
3848 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3849 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3850 ast_unref(framenum);
3851 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3854 ast_type_adopt(thinkfunc, functype);
3856 if (!parser_next(parser)) {
3857 ast_unref(framenum);
3858 ast_delete(thinkfunc);
3862 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3864 nextthink = (ast_expression*)thinkfunc;
3867 nextthink = parse_expression_leave(parser, true, false, false);
3869 ast_unref(framenum);
3870 parseerror(parser, "expected a think-function in [frame,think] notation");
3875 if (!ast_istype(nextthink, ast_value)) {
3876 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3880 if (retval && parser->tok != ']') {
3881 parseerror(parser, "expected closing `]` for [frame,think] notation");
3885 if (retval && !parser_next(parser)) {
3889 if (retval && parser->tok != '{') {
3890 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3895 ast_unref(nextthink);
3896 ast_unref(framenum);
3900 has_frame_think = true;
3903 block = ast_block_new(parser_ctx(parser));
3905 parseerror(parser, "failed to allocate block");
3906 if (has_frame_think) {
3907 ast_unref(nextthink);
3908 ast_unref(framenum);
3913 if (has_frame_think) {
3915 ast_expression *self_frame;
3916 ast_expression *self_nextthink;
3917 ast_expression *self_think;
3918 ast_expression *time_plus_1;
3919 ast_store *store_frame;
3920 ast_store *store_nextthink;
3921 ast_store *store_think;
3923 ctx = parser_ctx(parser);
3924 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3925 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3926 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3928 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3929 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3931 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3932 if (self_frame) ast_delete(self_frame);
3933 if (self_nextthink) ast_delete(self_nextthink);
3934 if (self_think) ast_delete(self_think);
3935 if (time_plus_1) ast_delete(time_plus_1);
3941 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3942 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3943 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3946 ast_delete(self_frame);
3949 if (!store_nextthink) {
3950 ast_delete(self_nextthink);
3954 ast_delete(self_think);
3958 if (store_frame) ast_delete(store_frame);
3959 if (store_nextthink) ast_delete(store_nextthink);
3960 if (store_think) ast_delete(store_think);
3963 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3964 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3965 !ast_block_add_expr(block, (ast_expression*)store_think))
3972 parseerror(parser, "failed to generate code for [frame,think]");
3973 ast_unref(nextthink);
3974 ast_unref(framenum);
3980 if (var->hasvalue) {
3981 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3982 ast_block_delete(block);
3986 func = ast_function_new(ast_ctx(var), var->name, var);
3988 parseerror(parser, "failed to allocate function for `%s`", var->name);
3989 ast_block_delete(block);
3992 vec_push(parser->functions, func);
3994 parser_enterblock(parser);
3996 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3998 ast_value *param = var->expression.params[parami];
4001 if (param->expression.vtype != TYPE_VECTOR &&
4002 (param->expression.vtype != TYPE_FIELD ||
4003 param->expression.next->vtype != TYPE_VECTOR))
4008 if (!create_vector_members(param, me)) {
4009 ast_block_delete(block);
4013 for (e = 0; e < 3; ++e) {
4014 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4015 ast_block_collect(block, (ast_expression*)me[e]);
4019 if (var->argcounter) {
4020 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4021 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4025 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4027 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4028 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4029 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4030 varargs->expression.count = 0;
4031 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4032 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4033 ast_delete(varargs);
4034 ast_block_delete(block);
4037 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4038 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4039 ast_delete(varargs);
4040 ast_block_delete(block);
4043 func->varargs = varargs;
4044 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4047 parser->function = func;
4048 if (!parse_block_into(parser, block)) {
4049 ast_block_delete(block);
4053 vec_push(func->blocks, block);
4056 parser->function = old;
4057 if (!parser_leaveblock(parser))
4059 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4060 parseerror(parser, "internal error: local scopes left");
4064 if (parser->tok == ';')
4065 return parser_next(parser);
4066 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4067 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4071 (void)!parser_leaveblock(parser);
4072 vec_pop(parser->functions);
4073 ast_function_delete(func);
4074 var->constval.vfunc = NULL;
4077 parser->function = old;
4081 static ast_expression *array_accessor_split(
4086 ast_expression *left,
4087 ast_expression *right
4093 lex_ctx_t ctx = ast_ctx(array);
4095 if (!left || !right) {
4096 if (left) ast_delete(left);
4097 if (right) ast_delete(right);
4101 cmp = ast_binary_new(ctx, INSTR_LT,
4102 (ast_expression*)index,
4103 (ast_expression*)fold_constgen_float(parser->fold, middle));
4107 parseerror(parser, "internal error: failed to create comparison for array setter");
4111 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4113 ast_delete(cmp); /* will delete left and right */
4114 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4118 return (ast_expression*)ifthen;
4121 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4123 lex_ctx_t ctx = ast_ctx(array);
4125 if (from+1 == afterend) {
4126 /* set this value */
4129 ast_array_index *subscript;
4131 int assignop = type_store_instr[value->expression.vtype];
4133 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4134 assignop = INSTR_STORE_V;
4136 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4140 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4142 ast_delete(subscript);
4146 block = ast_block_new(ctx);
4152 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4157 ret = ast_return_new(ctx, NULL);
4163 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4168 return (ast_expression*)block;
4170 ast_expression *left, *right;
4171 size_t diff = afterend - from;
4172 size_t middle = from + diff/2;
4173 left = array_setter_node(parser, array, index, value, from, middle);
4174 right = array_setter_node(parser, array, index, value, middle, afterend);
4175 return array_accessor_split(parser, array, index, middle, left, right);
4179 static ast_expression *array_field_setter_node(
4188 lex_ctx_t ctx = ast_ctx(array);
4190 if (from+1 == afterend) {
4191 /* set this value */
4194 ast_entfield *entfield;
4195 ast_array_index *subscript;
4197 int assignop = type_storep_instr[value->expression.vtype];
4199 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4200 assignop = INSTR_STOREP_V;
4202 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4206 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4207 subscript->expression.vtype = TYPE_FIELD;
4209 entfield = ast_entfield_new_force(ctx,
4210 (ast_expression*)entity,
4211 (ast_expression*)subscript,
4212 (ast_expression*)subscript);
4214 ast_delete(subscript);
4218 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4220 ast_delete(entfield);
4224 block = ast_block_new(ctx);
4230 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4235 ret = ast_return_new(ctx, NULL);
4241 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4246 return (ast_expression*)block;
4248 ast_expression *left, *right;
4249 size_t diff = afterend - from;
4250 size_t middle = from + diff/2;
4251 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4252 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4253 return array_accessor_split(parser, array, index, middle, left, right);
4257 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4259 lex_ctx_t ctx = ast_ctx(array);
4261 if (from+1 == afterend) {
4263 ast_array_index *subscript;
4265 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4269 ret = ast_return_new(ctx, (ast_expression*)subscript);
4271 ast_delete(subscript);
4275 return (ast_expression*)ret;
4277 ast_expression *left, *right;
4278 size_t diff = afterend - from;
4279 size_t middle = from + diff/2;
4280 left = array_getter_node(parser, array, index, from, middle);
4281 right = array_getter_node(parser, array, index, middle, afterend);
4282 return array_accessor_split(parser, array, index, middle, left, right);
4286 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4288 ast_function *func = NULL;
4289 ast_value *fval = NULL;
4290 ast_block *body = NULL;
4292 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4294 parseerror(parser, "failed to create accessor function value");
4298 func = ast_function_new(ast_ctx(array), funcname, fval);
4301 parseerror(parser, "failed to create accessor function node");
4305 body = ast_block_new(ast_ctx(array));
4307 parseerror(parser, "failed to create block for array accessor");
4313 vec_push(func->blocks, body);
4316 vec_push(parser->accessors, fval);
4321 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4323 ast_value *index = NULL;
4324 ast_value *value = NULL;
4328 if (!ast_istype(array->expression.next, ast_value)) {
4329 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4333 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4335 func = fval->constval.vfunc;
4336 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4338 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4339 value = ast_value_copy((ast_value*)array->expression.next);
4341 if (!index || !value) {
4342 parseerror(parser, "failed to create locals for array accessor");
4345 (void)!ast_value_set_name(value, "value"); /* not important */
4346 vec_push(fval->expression.params, index);
4347 vec_push(fval->expression.params, value);
4349 array->setter = fval;
4352 if (index) ast_delete(index);
4353 if (value) ast_delete(value);
4359 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4361 ast_expression *root = NULL;
4362 root = array_setter_node(parser, array,
4363 array->setter->expression.params[0],
4364 array->setter->expression.params[1],
4365 0, array->expression.count);
4367 parseerror(parser, "failed to build accessor search tree");
4370 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4377 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4379 if (!parser_create_array_setter_proto(parser, array, funcname))
4381 return parser_create_array_setter_impl(parser, array);
4384 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4386 ast_expression *root = NULL;
4387 ast_value *entity = NULL;
4388 ast_value *index = NULL;
4389 ast_value *value = NULL;
4393 if (!ast_istype(array->expression.next, ast_value)) {
4394 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4398 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4400 func = fval->constval.vfunc;
4401 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4403 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4404 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4405 value = ast_value_copy((ast_value*)array->expression.next);
4406 if (!entity || !index || !value) {
4407 parseerror(parser, "failed to create locals for array accessor");
4410 (void)!ast_value_set_name(value, "value"); /* not important */
4411 vec_push(fval->expression.params, entity);
4412 vec_push(fval->expression.params, index);
4413 vec_push(fval->expression.params, value);
4415 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4417 parseerror(parser, "failed to build accessor search tree");
4421 array->setter = fval;
4422 return ast_block_add_expr(func->blocks[0], root);
4424 if (entity) ast_delete(entity);
4425 if (index) ast_delete(index);
4426 if (value) ast_delete(value);
4427 if (root) ast_delete(root);
4433 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4435 ast_value *index = NULL;
4439 /* NOTE: checking array->expression.next rather than elemtype since
4440 * for fields elemtype is a temporary fieldtype.
4442 if (!ast_istype(array->expression.next, ast_value)) {
4443 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4447 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4449 func = fval->constval.vfunc;
4450 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4452 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4455 parseerror(parser, "failed to create locals for array accessor");
4458 vec_push(fval->expression.params, index);
4460 array->getter = fval;
4463 if (index) ast_delete(index);
4469 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4471 ast_expression *root = NULL;
4473 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4475 parseerror(parser, "failed to build accessor search tree");
4478 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4485 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4487 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4489 return parser_create_array_getter_impl(parser, array);
4492 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4493 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4501 bool variadic = false;
4502 ast_value *varparam = NULL;
4503 char *argcounter = NULL;
4505 ctx = parser_ctx(parser);
4507 /* for the sake of less code we parse-in in this function */
4508 if (!parser_next(parser)) {
4510 parseerror(parser, "expected parameter list");
4516 /* parse variables until we hit a closing paren */
4517 while (parser->tok != ')') {
4519 /* there must be commas between them */
4520 if (parser->tok != ',') {
4521 parseerror(parser, "expected comma or end of parameter list");
4524 if (!parser_next(parser)) {
4525 parseerror(parser, "expected parameter");
4531 if (parser->tok == TOKEN_DOTS) {
4532 /* '...' indicates a varargs function */
4534 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4535 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4538 if (parser->tok == TOKEN_IDENT) {
4539 argcounter = util_strdup(parser_tokval(parser));
4540 if (!parser_next(parser) || parser->tok != ')') {
4541 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4548 /* for anything else just parse a typename */
4549 param = parse_typename(parser, NULL, NULL);
4552 vec_push(params, param);
4553 if (param->expression.vtype >= TYPE_VARIANT) {
4554 char tname[1024]; /* typename is reserved in C++ */
4555 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4556 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4559 /* type-restricted varargs */
4560 if (parser->tok == TOKEN_DOTS) {
4562 varparam = vec_last(params);
4564 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4565 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4568 if (parser->tok == TOKEN_IDENT) {
4569 argcounter = util_strdup(parser_tokval(parser));
4570 if (!parser_next(parser) || parser->tok != ')') {
4571 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4579 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4583 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4584 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4587 if (!parser_next(parser)) {
4588 parseerror(parser, "parse error after typename");
4592 /* now turn 'var' into a function type */
4593 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4594 fval->expression.next = (ast_expression*)var;
4596 fval->expression.flags |= AST_FLAG_VARIADIC;
4599 var->expression.params = params;
4600 var->expression.varparam = (ast_expression*)varparam;
4601 var->argcounter = argcounter;
4610 ast_delete(varparam);
4612 for (i = 0; i < vec_size(params); ++i)
4613 ast_delete(params[i]);
4618 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4620 ast_expression *cexp;
4621 ast_value *cval, *tmp;
4624 ctx = parser_ctx(parser);
4626 if (!parser_next(parser)) {
4628 parseerror(parser, "expected array-size");
4632 if (parser->tok != ']') {
4633 cexp = parse_expression_leave(parser, true, false, false);
4635 if (!cexp || !ast_istype(cexp, ast_value)) {
4639 parseerror(parser, "expected array-size as constant positive integer");
4642 cval = (ast_value*)cexp;
4649 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4650 tmp->expression.next = (ast_expression*)var;
4654 if (cval->expression.vtype == TYPE_INTEGER)
4655 tmp->expression.count = cval->constval.vint;
4656 else if (cval->expression.vtype == TYPE_FLOAT)
4657 tmp->expression.count = cval->constval.vfloat;
4661 parseerror(parser, "array-size must be a positive integer constant");
4667 var->expression.count = -1;
4668 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4671 if (parser->tok != ']') {
4673 parseerror(parser, "expected ']' after array-size");
4676 if (!parser_next(parser)) {
4678 parseerror(parser, "error after parsing array size");
4684 /* Parse a complete typename.
4685 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4686 * but when parsing variables separated by comma
4687 * 'storebase' should point to where the base-type should be kept.
4688 * The base type makes up every bit of type information which comes *before* the
4691 * NOTE: The value must either be named, have a NULL name, or a name starting
4692 * with '<'. In the first case, this will be the actual variable or type
4693 * name, in the other cases it is assumed that the name will appear
4694 * later, and an error is generated otherwise.
4696 * The following will be parsed in its entirety:
4698 * The 'basetype' in this case is 'void()'
4699 * and if there's a comma after it, say:
4701 * then the type-information 'void()' can be stored in 'storebase'
4703 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4705 ast_value *var, *tmp;
4708 const char *name = NULL;
4709 bool isfield = false;
4710 bool wasarray = false;
4711 size_t morefields = 0;
4713 ctx = parser_ctx(parser);
4715 /* types may start with a dot */
4716 if (parser->tok == '.') {
4718 /* if we parsed a dot we need a typename now */
4719 if (!parser_next(parser)) {
4720 parseerror(parser, "expected typename for field definition");
4724 /* Further dots are handled seperately because they won't be part of the
4727 while (parser->tok == '.') {
4729 if (!parser_next(parser)) {
4730 parseerror(parser, "expected typename for field definition");
4735 if (parser->tok == TOKEN_IDENT)
4736 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4737 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4738 parseerror(parser, "expected typename");
4742 /* generate the basic type value */
4743 if (cached_typedef) {
4744 var = ast_value_copy(cached_typedef);
4745 ast_value_set_name(var, "<type(from_def)>");
4747 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4749 for (; morefields; --morefields) {
4750 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4751 tmp->expression.next = (ast_expression*)var;
4755 /* do not yet turn into a field - remember:
4756 * .void() foo; is a field too
4757 * .void()() foo; is a function
4761 if (!parser_next(parser)) {
4763 parseerror(parser, "parse error after typename");
4767 /* an opening paren now starts the parameter-list of a function
4768 * this is where original-QC has parameter lists.
4769 * We allow a single parameter list here.
4770 * Much like fteqcc we don't allow `float()() x`
4772 if (parser->tok == '(') {
4773 var = parse_parameter_list(parser, var);
4778 /* store the base if requested */
4780 *storebase = ast_value_copy(var);
4782 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4783 tmp->expression.next = (ast_expression*)*storebase;
4788 /* there may be a name now */
4789 if (parser->tok == TOKEN_IDENT) {
4790 name = util_strdup(parser_tokval(parser));
4792 if (!parser_next(parser)) {
4795 parseerror(parser, "error after variable or field declaration");
4800 /* now this may be an array */
4801 if (parser->tok == '[') {
4803 var = parse_arraysize(parser, var);
4805 if (name) mem_d(name);
4810 /* This is the point where we can turn it into a field */
4812 /* turn it into a field if desired */
4813 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4814 tmp->expression.next = (ast_expression*)var;
4818 /* now there may be function parens again */
4819 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4820 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4821 if (parser->tok == '(' && wasarray)
4822 parseerror(parser, "arrays as part of a return type is not supported");
4823 while (parser->tok == '(') {
4824 var = parse_parameter_list(parser, var);
4826 if (name) mem_d(name);
4831 /* finally name it */
4833 if (!ast_value_set_name(var, name)) {
4836 parseerror(parser, "internal error: failed to set name");
4839 /* free the name, ast_value_set_name duplicates */
4846 static bool parse_typedef(parser_t *parser)
4848 ast_value *typevar, *oldtype;
4849 ast_expression *old;
4851 typevar = parse_typename(parser, NULL, NULL);
4856 /* while parsing types, the ast_value's get named '<something>' */
4857 if (!typevar->name || typevar->name[0] == '<') {
4858 parseerror(parser, "missing name in typedef");
4859 ast_delete(typevar);
4863 if ( (old = parser_find_var(parser, typevar->name)) ) {
4864 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4865 " -> `%s` has been declared here: %s:%i",
4866 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4867 ast_delete(typevar);
4871 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4872 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4873 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4874 ast_delete(typevar);
4878 vec_push(parser->_typedefs, typevar);
4879 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4881 if (parser->tok != ';') {
4882 parseerror(parser, "expected semicolon after typedef");
4885 if (!parser_next(parser)) {
4886 parseerror(parser, "parse error after typedef");
4893 static const char *cvq_to_str(int cvq) {
4895 case CV_NONE: return "none";
4896 case CV_VAR: return "`var`";
4897 case CV_CONST: return "`const`";
4898 default: return "<INVALID>";
4902 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4905 if (proto->cvq != var->cvq) {
4906 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4907 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4908 parser->tok == '='))
4910 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4911 "`%s` declared with different qualifiers: %s\n"
4912 " -> previous declaration here: %s:%i uses %s",
4913 var->name, cvq_to_str(var->cvq),
4914 ast_ctx(proto).file, ast_ctx(proto).line,
4915 cvq_to_str(proto->cvq));
4918 av = (var ->expression.flags & AST_FLAG_NORETURN);
4919 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4921 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4922 "`%s` declared with different attributes%s\n"
4923 " -> previous declaration here: %s:%i",
4924 var->name, (av ? ": noreturn" : ""),
4925 ast_ctx(proto).file, ast_ctx(proto).line,
4926 (ao ? ": noreturn" : ""));
4931 static bool create_array_accessors(parser_t *parser, ast_value *var)
4934 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4935 if (!parser_create_array_setter(parser, var, name))
4937 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4938 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4943 static bool parse_array(parser_t *parser, ast_value *array)
4946 if (array->initlist) {
4947 parseerror(parser, "array already initialized elsewhere");
4950 if (!parser_next(parser)) {
4951 parseerror(parser, "parse error in array initializer");
4955 while (parser->tok != '}') {
4956 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4959 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4961 parseerror(parser, "initializing element must be a compile time constant");
4964 vec_push(array->initlist, v->constval);
4965 if (v->expression.vtype == TYPE_STRING) {
4966 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4970 if (parser->tok == '}')
4972 if (parser->tok != ',' || !parser_next(parser)) {
4973 parseerror(parser, "expected comma or '}' in element list");
4977 if (!parser_next(parser) || parser->tok != ';') {
4978 parseerror(parser, "expected semicolon after initializer, got %s");
4982 if (!parser_next(parser)) {
4983 parseerror(parser, "parse error after initializer");
4988 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4989 if (array->expression.count != (size_t)-1) {
4990 parseerror(parser, "array `%s' has already been initialized with %u elements",
4991 array->name, (unsigned)array->expression.count);
4993 array->expression.count = vec_size(array->initlist);
4994 if (!create_array_accessors(parser, array))
5000 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)
5004 ast_expression *old;
5008 ast_value *basetype = NULL;
5010 bool isparam = false;
5011 bool isvector = false;
5012 bool cleanvar = true;
5013 bool wasarray = false;
5015 ast_member *me[3] = { NULL, NULL, NULL };
5017 if (!localblock && is_static)
5018 parseerror(parser, "`static` qualifier is not supported in global scope");
5020 /* get the first complete variable */
5021 var = parse_typename(parser, &basetype, cached_typedef);
5024 ast_delete(basetype);
5028 /* while parsing types, the ast_value's get named '<something>' */
5029 if (!var->name || var->name[0] == '<') {
5030 parseerror(parser, "declaration does not declare anything");
5032 ast_delete(basetype);
5040 /* Part 0: finish the type */
5041 if (parser->tok == '(') {
5042 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5043 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5044 var = parse_parameter_list(parser, var);
5050 /* we only allow 1-dimensional arrays */
5051 if (parser->tok == '[') {
5053 var = parse_arraysize(parser, var);
5059 if (parser->tok == '(' && wasarray) {
5060 parseerror(parser, "arrays as part of a return type is not supported");
5061 /* we'll still parse the type completely for now */
5063 /* for functions returning functions */
5064 while (parser->tok == '(') {
5065 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5066 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5067 var = parse_parameter_list(parser, var);
5074 var->cvq = qualifier;
5075 var->expression.flags |= qflags;
5078 * store the vstring back to var for alias and
5079 * deprecation messages.
5081 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5082 var->expression.flags & AST_FLAG_ALIAS)
5083 var->desc = vstring;
5086 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5087 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5088 * is then filled with the previous definition and the parameter-names replaced.
5090 if (!strcmp(var->name, "nil")) {
5091 if (OPTS_FLAG(UNTYPED_NIL)) {
5092 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5093 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5095 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5098 /* Deal with end_sys_ vars */
5100 if (!strcmp(var->name, "end_sys_globals")) {
5102 parser->crc_globals = vec_size(parser->globals);
5105 else if (!strcmp(var->name, "end_sys_fields")) {
5107 parser->crc_fields = vec_size(parser->fields);
5110 if (was_end && var->expression.vtype == TYPE_FIELD) {
5111 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5112 "global '%s' hint should not be a field",
5113 parser_tokval(parser)))
5120 if (!nofields && var->expression.vtype == TYPE_FIELD)
5122 /* deal with field declarations */
5123 old = parser_find_field(parser, var->name);
5125 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5126 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5135 parseerror(parser, "field `%s` already declared here: %s:%i",
5136 var->name, ast_ctx(old).file, ast_ctx(old).line);
5141 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5142 (old = parser_find_global(parser, var->name)))
5144 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5145 parseerror(parser, "field `%s` already declared here: %s:%i",
5146 var->name, ast_ctx(old).file, ast_ctx(old).line);
5153 /* deal with other globals */
5154 old = parser_find_global(parser, var->name);
5155 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5157 /* This is a function which had a prototype */
5158 if (!ast_istype(old, ast_value)) {
5159 parseerror(parser, "internal error: prototype is not an ast_value");
5163 proto = (ast_value*)old;
5164 proto->desc = var->desc;
5165 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5166 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5168 ast_ctx(proto).file, ast_ctx(proto).line);
5172 /* we need the new parameter-names */
5173 for (i = 0; i < vec_size(proto->expression.params); ++i)
5174 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5175 if (!parser_check_qualifiers(parser, var, proto)) {
5182 proto->expression.flags |= var->expression.flags;
5190 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5191 "global `%s` already declared here: %s:%i",
5192 var->name, ast_ctx(old).file, ast_ctx(old).line))
5197 proto = (ast_value*)old;
5198 if (!ast_istype(old, ast_value)) {
5199 parseerror(parser, "internal error: not an ast_value");
5204 if (!parser_check_qualifiers(parser, var, proto)) {
5209 proto->expression.flags |= var->expression.flags;
5213 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5214 (old = parser_find_field(parser, var->name)))
5216 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5217 parseerror(parser, "global `%s` already declared here: %s:%i",
5218 var->name, ast_ctx(old).file, ast_ctx(old).line);
5225 else /* it's not a global */
5227 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5228 if (old && !isparam) {
5229 parseerror(parser, "local `%s` already declared here: %s:%i",
5230 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5234 /* doing this here as the above is just for a single scope */
5235 old = parser_find_local(parser, var->name, 0, &isparam);
5236 if (old && isparam) {
5237 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5238 "local `%s` is shadowing a parameter", var->name))
5240 parseerror(parser, "local `%s` already declared here: %s:%i",
5241 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5245 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5247 if (ast_istype(old, ast_value))
5248 var = proto = (ast_value*)old;
5257 /* in a noref section we simply bump the usecount */
5258 if (noref || parser->noref)
5262 * Create the global/local, and deal with vector types.
5265 if (var->expression.vtype == TYPE_VECTOR)
5267 else if (var->expression.vtype == TYPE_FIELD &&
5268 var->expression.next->vtype == TYPE_VECTOR)
5272 if (!create_vector_members(var, me)) {
5279 /* deal with global variables, fields, functions */
5280 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5281 var->isfield = true;
5282 vec_push(parser->fields, (ast_expression*)var);
5283 util_htset(parser->htfields, var->name, var);
5285 for (i = 0; i < 3; ++i) {
5286 vec_push(parser->fields, (ast_expression*)me[i]);
5287 util_htset(parser->htfields, me[i]->name, me[i]);
5292 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5293 parser_addglobal(parser, var->name, (ast_expression*)var);
5295 for (i = 0; i < 3; ++i) {
5296 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5300 ast_expression *find = parser_find_global(parser, var->desc);
5303 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5307 if (!ast_compare_type((ast_expression*)var, find)) {
5311 ast_type_to_string(find, ty1, sizeof(ty1));
5312 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5314 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5321 * add alias to aliases table and to corrector
5322 * so corrections can apply for aliases as well.
5324 util_htset(parser->aliases, var->name, find);
5327 * add to corrector so corrections can work
5328 * even for aliases too.
5331 vec_last(parser->correct_variables),
5332 &vec_last(parser->correct_variables_score),
5336 /* generate aliases for vector components */
5340 util_asprintf(&buffer[0], "%s_x", var->desc);
5341 util_asprintf(&buffer[1], "%s_y", var->desc);
5342 util_asprintf(&buffer[2], "%s_z", var->desc);
5344 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5345 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5346 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5353 * add to corrector so corrections can work
5354 * even for aliases too.
5357 vec_last(parser->correct_variables),
5358 &vec_last(parser->correct_variables_score),
5362 vec_last(parser->correct_variables),
5363 &vec_last(parser->correct_variables_score),
5367 vec_last(parser->correct_variables),
5368 &vec_last(parser->correct_variables_score),
5376 /* a static adds itself to be generated like any other global
5377 * but is added to the local namespace instead
5379 char *defname = NULL;
5380 size_t prefix_len, ln;
5382 ln = strlen(parser->function->name);
5383 vec_append(defname, ln, parser->function->name);
5385 vec_append(defname, 2, "::");
5386 /* remember the length up to here */
5387 prefix_len = vec_size(defname);
5389 /* Add it to the local scope */
5390 util_htset(vec_last(parser->variables), var->name, (void*)var);
5394 vec_last(parser->correct_variables),
5395 &vec_last(parser->correct_variables_score),
5399 /* now rename the global */
5400 ln = strlen(var->name);
5401 vec_append(defname, ln, var->name);
5402 ast_value_set_name(var, defname);
5404 /* push it to the to-be-generated globals */
5405 vec_push(parser->globals, (ast_expression*)var);
5407 /* same game for the vector members */
5409 for (i = 0; i < 3; ++i) {
5410 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5414 vec_last(parser->correct_variables),
5415 &vec_last(parser->correct_variables_score),
5419 vec_shrinkto(defname, prefix_len);
5420 ln = strlen(me[i]->name);
5421 vec_append(defname, ln, me[i]->name);
5422 ast_member_set_name(me[i], defname);
5424 vec_push(parser->globals, (ast_expression*)me[i]);
5429 vec_push(localblock->locals, var);
5430 parser_addlocal(parser, var->name, (ast_expression*)var);
5432 for (i = 0; i < 3; ++i) {
5433 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5434 ast_block_collect(localblock, (ast_expression*)me[i]);
5440 me[0] = me[1] = me[2] = NULL;
5445 if (var->expression.vtype == TYPE_ARRAY) {
5446 if (var->expression.count != (size_t)-1) {
5447 if (!create_array_accessors(parser, var))
5451 else if (!localblock && !nofields &&
5452 var->expression.vtype == TYPE_FIELD &&
5453 var->expression.next->vtype == TYPE_ARRAY)
5456 ast_expression *telem;
5458 ast_value *array = (ast_value*)var->expression.next;
5460 if (!ast_istype(var->expression.next, ast_value)) {
5461 parseerror(parser, "internal error: field element type must be an ast_value");
5465 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5466 if (!parser_create_array_field_setter(parser, array, name))
5469 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5470 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5471 tfield->expression.next = telem;
5472 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5473 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5481 if (parser->tok == ';') {
5482 ast_delete(basetype);
5483 if (!parser_next(parser)) {
5484 parseerror(parser, "error after variable declaration");
5490 if (parser->tok == ',')
5494 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5497 parseerror(parser, "missing comma or semicolon while parsing variables");
5501 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5502 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5503 "initializing expression turns variable `%s` into a constant in this standard",
5510 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5511 if (parser->tok != '=') {
5512 if (!strcmp(parser_tokval(parser), "break")) {
5513 if (!parser_next(parser)) {
5514 parseerror(parser, "error parsing break definition");
5517 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5519 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5524 if (!parser_next(parser)) {
5525 parseerror(parser, "error parsing initializer");
5529 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5530 parseerror(parser, "expected '=' before function body in this standard");
5533 if (parser->tok == '#') {
5534 ast_function *func = NULL;
5535 ast_value *number = NULL;
5541 parseerror(parser, "cannot declare builtins within functions");
5544 if (var->expression.vtype != TYPE_FUNCTION) {
5545 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5548 if (!parser_next(parser)) {
5549 parseerror(parser, "expected builtin number");
5553 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5554 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5556 parseerror(parser, "builtin number expected");
5559 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5562 parseerror(parser, "builtin number must be a compile time constant");
5565 if (number->expression.vtype == TYPE_INTEGER)
5566 builtin_num = number->constval.vint;
5567 else if (number->expression.vtype == TYPE_FLOAT)
5568 builtin_num = number->constval.vfloat;
5571 parseerror(parser, "builtin number must be an integer constant");
5576 fractional = modff(builtin_num, &integral);
5577 if (builtin_num < 0 || fractional != 0) {
5578 parseerror(parser, "builtin number must be an integer greater than zero");
5582 /* we only want the integral part anyways */
5583 builtin_num = integral;
5584 } else if (parser->tok == TOKEN_INTCONST) {
5585 builtin_num = parser_token(parser)->constval.i;
5587 parseerror(parser, "builtin number must be a compile time constant");
5591 if (var->hasvalue) {
5592 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5593 "builtin `%s` has already been defined\n"
5594 " -> previous declaration here: %s:%i",
5595 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5599 func = ast_function_new(ast_ctx(var), var->name, var);
5601 parseerror(parser, "failed to allocate function for `%s`", var->name);
5604 vec_push(parser->functions, func);
5606 func->builtin = -builtin_num-1;
5609 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5610 ? (parser->tok != ',' && parser->tok != ';')
5611 : (!parser_next(parser)))
5613 parseerror(parser, "expected comma or semicolon");
5615 ast_function_delete(func);
5616 var->constval.vfunc = NULL;
5620 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5623 /* Note that fteqcc and most others don't even *have*
5624 * local arrays, so this is not a high priority.
5626 parseerror(parser, "TODO: initializers for local arrays");
5630 var->hasvalue = true;
5631 if (!parse_array(parser, var))
5634 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5637 parseerror(parser, "cannot declare functions within functions");
5642 ast_ctx(proto) = parser_ctx(parser);
5644 if (!parse_function_body(parser, var))
5646 ast_delete(basetype);
5647 for (i = 0; i < vec_size(parser->gotos); ++i)
5648 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5649 vec_free(parser->gotos);
5650 vec_free(parser->labels);
5653 ast_expression *cexp;
5656 cexp = parse_expression_leave(parser, true, false, false);
5661 cval = (ast_value*)cexp;
5662 if (cval != parser->nil &&
5663 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5666 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5670 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5671 qualifier != CV_VAR)
5673 var->cvq = CV_CONST;
5675 if (cval == parser->nil)
5676 var->expression.flags |= AST_FLAG_INITIALIZED;
5679 var->hasvalue = true;
5680 if (cval->expression.vtype == TYPE_STRING)
5681 var->constval.vstring = parser_strdup(cval->constval.vstring);
5682 else if (cval->expression.vtype == TYPE_FIELD)
5683 var->constval.vfield = cval;
5685 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5691 shunt sy = { NULL, NULL, NULL, NULL };
5694 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5695 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5696 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5697 if (!parser_sy_apply_operator(parser, &sy))
5700 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5701 parseerror(parser, "internal error: leaked operands");
5702 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5713 if (parser->tok == ',') {
5714 if (!parser_next(parser)) {
5715 parseerror(parser, "expected another variable");
5719 if (parser->tok != TOKEN_IDENT) {
5720 parseerror(parser, "expected another variable");
5723 var = ast_value_copy(basetype);
5725 ast_value_set_name(var, parser_tokval(parser));
5726 if (!parser_next(parser)) {
5727 parseerror(parser, "error parsing variable declaration");
5733 if (parser->tok != ';') {
5734 parseerror(parser, "missing semicolon after variables");
5738 if (!parser_next(parser)) {
5739 parseerror(parser, "parse error after variable declaration");
5743 ast_delete(basetype);
5747 if (cleanvar && var)
5749 ast_delete(basetype);
5753 ast_delete(basetype);
5754 if (cleanvar && var)
5756 if (me[0]) ast_member_delete(me[0]);
5757 if (me[1]) ast_member_delete(me[1]);
5758 if (me[2]) ast_member_delete(me[2]);
5762 static bool parser_global_statement(parser_t *parser)
5766 bool is_static = false;
5767 uint32_t qflags = 0;
5768 ast_value *istype = NULL;
5769 char *vstring = NULL;
5771 if (parser->tok == TOKEN_IDENT)
5772 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5774 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5776 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5778 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5780 if (cvq == CV_WRONG)
5782 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5784 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5786 return parse_enum(parser);
5788 else if (parser->tok == TOKEN_KEYWORD)
5790 if (!strcmp(parser_tokval(parser), "typedef")) {
5791 if (!parser_next(parser)) {
5792 parseerror(parser, "expected type definition after 'typedef'");
5795 return parse_typedef(parser);
5797 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5800 else if (parser->tok == '#')
5802 return parse_pragma(parser);
5804 else if (parser->tok == '$')
5806 if (!parser_next(parser)) {
5807 parseerror(parser, "parse error");
5813 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5819 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5821 return util_crc16(old, str, strlen(str));
5824 static void progdefs_crc_file(const char *str)
5826 /* write to progdefs.h here */
5830 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5832 old = progdefs_crc_sum(old, str);
5833 progdefs_crc_file(str);
5837 static void generate_checksum(parser_t *parser, ir_builder *ir)
5839 uint16_t crc = 0xFFFF;
5843 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5844 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5846 progdefs_crc_file("\tint\tpad;\n");
5847 progdefs_crc_file("\tint\tofs_return[3];\n");
5848 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5849 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5850 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5851 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5852 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5853 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5854 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5855 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5857 for (i = 0; i < parser->crc_globals; ++i) {
5858 if (!ast_istype(parser->globals[i], ast_value))
5860 value = (ast_value*)(parser->globals[i]);
5861 switch (value->expression.vtype) {
5862 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5863 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5864 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5865 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5867 crc = progdefs_crc_both(crc, "\tint\t");
5870 crc = progdefs_crc_both(crc, value->name);
5871 crc = progdefs_crc_both(crc, ";\n");
5873 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5874 for (i = 0; i < parser->crc_fields; ++i) {
5875 if (!ast_istype(parser->fields[i], ast_value))
5877 value = (ast_value*)(parser->fields[i]);
5878 switch (value->expression.next->vtype) {
5879 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5880 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5881 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5882 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5884 crc = progdefs_crc_both(crc, "\tint\t");
5887 crc = progdefs_crc_both(crc, value->name);
5888 crc = progdefs_crc_both(crc, ";\n");
5890 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5891 ir->code->crc = crc;
5894 parser_t *parser_create()
5897 lex_ctx_t empty_ctx;
5900 parser = (parser_t*)mem_a(sizeof(parser_t));
5904 memset(parser, 0, sizeof(*parser));
5906 for (i = 0; i < operator_count; ++i) {
5907 if (operators[i].id == opid1('=')) {
5908 parser->assign_op = operators+i;
5912 if (!parser->assign_op) {
5913 printf("internal error: initializing parser: failed to find assign operator\n");
5918 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5919 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5920 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5921 vec_push(parser->_blocktypedefs, 0);
5923 parser->aliases = util_htnew(PARSER_HT_SIZE);
5926 vec_push(parser->correct_variables, correct_trie_new());
5927 vec_push(parser->correct_variables_score, NULL);
5929 empty_ctx.file = "<internal>";
5931 empty_ctx.column = 0;
5932 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5933 parser->nil->cvq = CV_CONST;
5934 if (OPTS_FLAG(UNTYPED_NIL))
5935 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5937 parser->max_param_count = 1;
5939 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5940 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5941 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5943 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5944 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5945 parser->reserved_version->cvq = CV_CONST;
5946 parser->reserved_version->hasvalue = true;
5947 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5948 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5950 parser->reserved_version = NULL;
5953 parser->fold = fold_init (parser);
5954 parser->intrin = intrin_init(parser);
5958 static bool parser_compile(parser_t *parser)
5960 /* initial lexer/parser state */
5961 parser->lex->flags.noops = true;
5963 if (parser_next(parser))
5965 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5967 if (!parser_global_statement(parser)) {
5968 if (parser->tok == TOKEN_EOF)
5969 parseerror(parser, "unexpected end of file");
5970 else if (compile_errors)
5971 parseerror(parser, "there have been errors, bailing out");
5972 lex_close(parser->lex);
5978 parseerror(parser, "parse error");
5979 lex_close(parser->lex);
5984 lex_close(parser->lex);
5987 return !compile_errors;
5990 bool parser_compile_file(parser_t *parser, const char *filename)
5992 parser->lex = lex_open(filename);
5994 con_err("failed to open file \"%s\"\n", filename);
5997 return parser_compile(parser);
6000 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6002 parser->lex = lex_open_string(str, len, name);
6004 con_err("failed to create lexer for string \"%s\"\n", name);
6007 return parser_compile(parser);
6010 static void parser_remove_ast(parser_t *parser)
6013 if (parser->ast_cleaned)
6015 parser->ast_cleaned = true;
6016 for (i = 0; i < vec_size(parser->accessors); ++i) {
6017 ast_delete(parser->accessors[i]->constval.vfunc);
6018 parser->accessors[i]->constval.vfunc = NULL;
6019 ast_delete(parser->accessors[i]);
6021 for (i = 0; i < vec_size(parser->functions); ++i) {
6022 ast_delete(parser->functions[i]);
6024 for (i = 0; i < vec_size(parser->fields); ++i) {
6025 ast_delete(parser->fields[i]);
6027 for (i = 0; i < vec_size(parser->globals); ++i) {
6028 ast_delete(parser->globals[i]);
6030 vec_free(parser->accessors);
6031 vec_free(parser->functions);
6032 vec_free(parser->globals);
6033 vec_free(parser->fields);
6035 for (i = 0; i < vec_size(parser->variables); ++i)
6036 util_htdel(parser->variables[i]);
6037 vec_free(parser->variables);
6038 vec_free(parser->_blocklocals);
6039 vec_free(parser->_locals);
6042 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6043 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6045 vec_free(parser->correct_variables);
6046 vec_free(parser->correct_variables_score);
6048 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6049 ast_delete(parser->_typedefs[i]);
6050 vec_free(parser->_typedefs);
6051 for (i = 0; i < vec_size(parser->typedefs); ++i)
6052 util_htdel(parser->typedefs[i]);
6053 vec_free(parser->typedefs);
6054 vec_free(parser->_blocktypedefs);
6056 vec_free(parser->_block_ctx);
6058 vec_free(parser->labels);
6059 vec_free(parser->gotos);
6060 vec_free(parser->breaks);
6061 vec_free(parser->continues);
6063 ast_value_delete(parser->nil);
6065 ast_value_delete(parser->const_vec[0]);
6066 ast_value_delete(parser->const_vec[1]);
6067 ast_value_delete(parser->const_vec[2]);
6069 if (parser->reserved_version)
6070 ast_value_delete(parser->reserved_version);
6072 util_htdel(parser->aliases);
6073 fold_cleanup(parser->fold);
6074 intrin_cleanup(parser->intrin);
6077 void parser_cleanup(parser_t *parser)
6079 parser_remove_ast(parser);
6083 bool parser_finish(parser_t *parser, const char *output)
6089 if (compile_errors) {
6090 con_out("*** there were compile errors\n");
6094 ir = ir_builder_new("gmqcc_out");
6096 con_out("failed to allocate builder\n");
6100 for (i = 0; i < vec_size(parser->fields); ++i) {
6103 if (!ast_istype(parser->fields[i], ast_value))
6105 field = (ast_value*)parser->fields[i];
6106 hasvalue = field->hasvalue;
6107 field->hasvalue = false;
6108 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6109 con_out("failed to generate field %s\n", field->name);
6110 ir_builder_delete(ir);
6115 ast_expression *subtype;
6116 field->hasvalue = true;
6117 subtype = field->expression.next;
6118 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6119 if (subtype->vtype == TYPE_FIELD)
6120 ifld->fieldtype = subtype->next->vtype;
6121 else if (subtype->vtype == TYPE_FUNCTION)
6122 ifld->outtype = subtype->next->vtype;
6123 (void)!ir_value_set_field(field->ir_v, ifld);
6126 for (i = 0; i < vec_size(parser->globals); ++i) {
6128 if (!ast_istype(parser->globals[i], ast_value))
6130 asvalue = (ast_value*)(parser->globals[i]);
6131 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6132 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6133 "unused global: `%s`", asvalue->name);
6135 if (!ast_global_codegen(asvalue, ir, false)) {
6136 con_out("failed to generate global %s\n", asvalue->name);
6137 ir_builder_delete(ir);
6141 /* Build function vararg accessor ast tree now before generating
6142 * immediates, because the accessors may add new immediates
6144 for (i = 0; i < vec_size(parser->functions); ++i) {
6145 ast_function *f = parser->functions[i];
6147 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6148 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6149 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6150 con_out("failed to generate vararg setter for %s\n", f->name);
6151 ir_builder_delete(ir);
6154 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6155 con_out("failed to generate vararg getter for %s\n", f->name);
6156 ir_builder_delete(ir);
6160 ast_delete(f->varargs);
6165 /* Now we can generate immediates */
6166 if (!fold_generate(parser->fold, ir))
6169 for (i = 0; i < vec_size(parser->globals); ++i) {
6171 if (!ast_istype(parser->globals[i], ast_value))
6173 asvalue = (ast_value*)(parser->globals[i]);
6174 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6176 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6177 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6178 "uninitialized constant: `%s`",
6180 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6181 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6182 "uninitialized global: `%s`",
6185 if (!ast_generate_accessors(asvalue, ir)) {
6186 ir_builder_delete(ir);
6190 for (i = 0; i < vec_size(parser->fields); ++i) {
6192 asvalue = (ast_value*)(parser->fields[i]->next);
6194 if (!ast_istype((ast_expression*)asvalue, ast_value))
6196 if (asvalue->expression.vtype != TYPE_ARRAY)
6198 if (!ast_generate_accessors(asvalue, ir)) {
6199 ir_builder_delete(ir);
6203 if (parser->reserved_version &&
6204 !ast_global_codegen(parser->reserved_version, ir, false))
6206 con_out("failed to generate reserved::version");
6207 ir_builder_delete(ir);
6210 for (i = 0; i < vec_size(parser->functions); ++i) {
6211 ast_function *f = parser->functions[i];
6212 if (!ast_function_codegen(f, ir)) {
6213 con_out("failed to generate function %s\n", f->name);
6214 ir_builder_delete(ir);
6219 generate_checksum(parser, ir);
6221 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6222 ir_builder_dump(ir, con_out);
6223 for (i = 0; i < vec_size(parser->functions); ++i) {
6224 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6225 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6226 ir_builder_delete(ir);
6230 parser_remove_ast(parser);
6232 if (compile_Werrors) {
6233 con_out("*** there were warnings treated as errors\n");
6234 compile_show_werrors();
6239 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6240 ir_builder_dump(ir, con_out);
6242 if (!ir_builder_generate(ir, output)) {
6243 con_out("*** failed to generate output file\n");
6244 ir_builder_delete(ir);
6248 ir_builder_delete(ir);