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");
293 compile_error(ctx, "assignment to constant `%s`", val->name);
300 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
304 ast_expression *out = NULL;
305 ast_expression *exprs[3];
306 ast_block *blocks[3];
307 ast_binstore *asbinstore;
308 size_t i, assignop, addop, subop;
309 qcint_t generated_op = 0;
314 if (!vec_size(sy->ops)) {
315 parseerror(parser, "internal error: missing operator");
319 if (vec_last(sy->ops).isparen) {
320 parseerror(parser, "unmatched parenthesis");
324 op = &operators[vec_last(sy->ops).etype - 1];
325 ctx = vec_last(sy->ops).ctx;
327 if (vec_size(sy->out) < op->operands) {
328 if (op->flags & OP_PREFIX)
329 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
330 else /* this should have errored previously already */
331 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
335 vec_shrinkby(sy->ops, 1);
337 /* op(:?) has no input and no output */
341 vec_shrinkby(sy->out, op->operands);
342 for (i = 0; i < op->operands; ++i) {
343 exprs[i] = sy->out[vec_size(sy->out)+i].out;
344 blocks[i] = sy->out[vec_size(sy->out)+i].block;
346 if (exprs[i]->vtype == TYPE_NOEXPR &&
347 !(i != 0 && op->id == opid2('?',':')) &&
348 !(i == 1 && op->id == opid1('.')))
350 if (ast_istype(exprs[i], ast_label))
351 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
353 compile_error(ast_ctx(exprs[i]), "not an expression");
354 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
358 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
359 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
363 #define NotSameType(T) \
364 (exprs[0]->vtype != exprs[1]->vtype || \
365 exprs[0]->vtype != T)
369 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
373 if (exprs[0]->vtype == TYPE_VECTOR &&
374 exprs[1]->vtype == TYPE_NOEXPR)
376 if (exprs[1] == (ast_expression*)parser->const_vec[0])
377 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
378 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
379 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
380 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
381 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
383 compile_error(ctx, "access to invalid vector component");
387 else if (exprs[0]->vtype == TYPE_ENTITY) {
388 if (exprs[1]->vtype != TYPE_FIELD) {
389 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
392 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
394 else if (exprs[0]->vtype == TYPE_VECTOR) {
395 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
399 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
405 if (exprs[0]->vtype != TYPE_ARRAY &&
406 !(exprs[0]->vtype == TYPE_FIELD &&
407 exprs[0]->next->vtype == TYPE_ARRAY))
409 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
410 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
413 if (exprs[1]->vtype != TYPE_FLOAT) {
414 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
415 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
418 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
419 if (rotate_entfield_array_index_nodes(&out))
422 /* This is not broken in fteqcc anymore */
423 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
424 /* this error doesn't need to make us bail out */
425 (void)!parsewarning(parser, WARN_EXTENSIONS,
426 "accessing array-field members of an entity without parenthesis\n"
427 " -> this is an extension from -std=gmqcc");
434 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
435 vec_push(sy->out, syexp(ctx, exprs[0]));
436 vec_push(sy->out, syexp(ctx, exprs[1]));
437 vec_last(sy->argc)++;
441 if (!ast_block_add_expr(blocks[0], exprs[1]))
444 blocks[0] = ast_block_new(ctx);
445 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
446 !ast_block_add_expr(blocks[0], exprs[1]))
451 ast_block_set_type(blocks[0], exprs[1]);
453 vec_push(sy->out, syblock(ctx, blocks[0]));
460 if (!(out = fold_op(parser->fold, op, exprs))) {
461 switch (exprs[0]->vtype) {
463 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
464 (ast_expression*)parser->fold->imm_float[0],
468 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
469 (ast_expression*)parser->fold->imm_vector[0],
473 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
474 type_name[exprs[0]->vtype]);
481 if (!(out = fold_op(parser->fold, op, exprs))) {
482 switch (exprs[0]->vtype) {
484 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
487 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
490 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
491 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
493 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
495 /* we don't constant-fold NOT for these types */
497 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
500 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
503 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
504 type_name[exprs[0]->vtype]);
511 if (exprs[0]->vtype != exprs[1]->vtype ||
512 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
514 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
515 type_name[exprs[0]->vtype],
516 type_name[exprs[1]->vtype]);
519 if (!(out = fold_op(parser->fold, op, exprs))) {
520 switch (exprs[0]->vtype) {
522 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
525 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
528 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
529 type_name[exprs[0]->vtype],
530 type_name[exprs[1]->vtype]);
536 if (exprs[0]->vtype != exprs[1]->vtype ||
537 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
539 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
540 type_name[exprs[1]->vtype],
541 type_name[exprs[0]->vtype]);
544 if (!(out = fold_op(parser->fold, op, exprs))) {
545 switch (exprs[0]->vtype) {
547 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
550 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
553 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
554 type_name[exprs[1]->vtype],
555 type_name[exprs[0]->vtype]);
561 if (exprs[0]->vtype != exprs[1]->vtype &&
562 !(exprs[0]->vtype == TYPE_VECTOR &&
563 exprs[1]->vtype == TYPE_FLOAT) &&
564 !(exprs[1]->vtype == TYPE_VECTOR &&
565 exprs[0]->vtype == TYPE_FLOAT)
568 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
569 type_name[exprs[1]->vtype],
570 type_name[exprs[0]->vtype]);
573 if (!(out = fold_op(parser->fold, op, exprs))) {
574 switch (exprs[0]->vtype) {
576 if (exprs[1]->vtype == TYPE_VECTOR)
577 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
579 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
582 if (exprs[1]->vtype == TYPE_FLOAT)
583 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
585 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
588 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
589 type_name[exprs[1]->vtype],
590 type_name[exprs[0]->vtype]);
597 if (exprs[1]->vtype != TYPE_FLOAT) {
598 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
599 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
600 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
603 if (!(out = fold_op(parser->fold, op, exprs))) {
604 if (exprs[0]->vtype == TYPE_FLOAT)
605 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
607 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
608 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
609 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
616 if (NotSameType(TYPE_FLOAT)) {
617 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
618 type_name[exprs[0]->vtype],
619 type_name[exprs[1]->vtype]);
621 } else if (!(out = fold_op(parser->fold, op, exprs))) {
622 /* generate a call to __builtin_mod */
623 ast_expression *mod = intrin_func(parser->intrin, "mod");
624 ast_call *call = NULL;
625 if (!mod) return false; /* can return null for missing floor */
627 call = ast_call_new(parser_ctx(parser), mod);
628 vec_push(call->params, exprs[0]);
629 vec_push(call->params, exprs[1]);
631 out = (ast_expression*)call;
636 compile_error(ctx, "%= is unimplemented");
642 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
643 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
644 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
646 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
647 type_name[exprs[0]->vtype],
648 type_name[exprs[1]->vtype]);
652 if (!(out = fold_op(parser->fold, op, exprs))) {
654 * IF the first expression is float, the following will be too
655 * since scalar ^ vector is not allowed.
657 if (exprs[0]->vtype == TYPE_FLOAT) {
658 out = (ast_expression*)ast_binary_new(ctx,
659 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
663 * The first is a vector: vector is allowed to bitop with vector and
664 * with scalar, branch here for the second operand.
666 if (exprs[1]->vtype == TYPE_VECTOR) {
668 * Bitop all the values of the vector components against the
669 * vectors components in question.
671 out = (ast_expression*)ast_binary_new(ctx,
672 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
675 out = (ast_expression*)ast_binary_new(ctx,
676 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
685 case opid3('<','<','='):
686 case opid3('>','>','='):
687 if(!(out = fold_op(parser->fold, op, exprs))) {
688 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
694 generated_op += 1; /* INSTR_OR */
696 generated_op += INSTR_AND;
697 if (!(out = fold_op(parser->fold, op, exprs))) {
698 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
699 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
700 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
701 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
704 for (i = 0; i < 2; ++i) {
705 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
706 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
708 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
710 exprs[i] = out; out = NULL;
711 if (OPTS_FLAG(PERL_LOGIC)) {
712 /* here we want to keep the right expressions' type */
716 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
717 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
721 exprs[i] = out; out = NULL;
722 if (OPTS_FLAG(PERL_LOGIC)) {
723 /* here we want to keep the right expressions' type */
728 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
733 if (vec_last(sy->paren) != PAREN_TERNARY2) {
734 compile_error(ctx, "mismatched parenthesis/ternary");
738 if (!ast_compare_type(exprs[1], exprs[2])) {
739 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
740 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
741 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
744 if (!(out = fold_op(parser->fold, op, exprs)))
745 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
748 case opid2('*', '*'):
749 if (NotSameType(TYPE_FLOAT)) {
750 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
751 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
752 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
757 if (!(out = fold_op(parser->fold, op, exprs))) {
758 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
759 vec_push(gencall->params, exprs[0]);
760 vec_push(gencall->params, exprs[1]);
761 out = (ast_expression*)gencall;
765 case opid2('>', '<'):
766 if (NotSameType(TYPE_VECTOR)) {
767 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
768 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
769 compile_error(ctx, "invalid types used in cross product: %s and %s",
774 if (!(out = fold_op(parser->fold, op, exprs))) {
775 out = (ast_expression*)ast_binary_new(
785 case opid3('<','=','>'): /* -1, 0, or 1 */
786 if (NotSameType(TYPE_FLOAT)) {
787 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
788 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
789 compile_error(ctx, "invalid types used in comparision: %s and %s",
795 if (!(out = fold_op(parser->fold, op, exprs))) {
796 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
798 eq->refs = AST_REF_NONE;
801 out = (ast_expression*)ast_ternary_new(ctx,
802 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
804 (ast_expression*)parser->fold->imm_float[2],
807 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
809 (ast_expression*)parser->fold->imm_float[0],
812 (ast_expression*)parser->fold->imm_float[1]
822 generated_op += 1; /* INSTR_GT */
824 generated_op += 1; /* INSTR_LT */
825 case opid2('>', '='):
826 generated_op += 1; /* INSTR_GE */
827 case opid2('<', '='):
828 generated_op += INSTR_LE;
829 if (NotSameType(TYPE_FLOAT)) {
830 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
831 type_name[exprs[0]->vtype],
832 type_name[exprs[1]->vtype]);
835 if (!(out = fold_op(parser->fold, op, exprs)))
836 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
838 case opid2('!', '='):
839 if (exprs[0]->vtype != exprs[1]->vtype) {
840 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
841 type_name[exprs[0]->vtype],
842 type_name[exprs[1]->vtype]);
845 if (!(out = fold_op(parser->fold, op, exprs)))
846 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
848 case opid2('=', '='):
849 if (exprs[0]->vtype != exprs[1]->vtype) {
850 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
851 type_name[exprs[0]->vtype],
852 type_name[exprs[1]->vtype]);
855 if (!(out = fold_op(parser->fold, op, exprs)))
856 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
860 if (ast_istype(exprs[0], ast_entfield)) {
861 ast_expression *field = ((ast_entfield*)exprs[0])->field;
862 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
863 exprs[0]->vtype == TYPE_FIELD &&
864 exprs[0]->next->vtype == TYPE_VECTOR)
866 assignop = type_storep_instr[TYPE_VECTOR];
869 assignop = type_storep_instr[exprs[0]->vtype];
870 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
872 ast_type_to_string(field->next, ty1, sizeof(ty1));
873 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
874 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
875 field->next->vtype == TYPE_FUNCTION &&
876 exprs[1]->vtype == TYPE_FUNCTION)
878 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
879 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
882 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
887 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
888 exprs[0]->vtype == TYPE_FIELD &&
889 exprs[0]->next->vtype == TYPE_VECTOR)
891 assignop = type_store_instr[TYPE_VECTOR];
894 assignop = type_store_instr[exprs[0]->vtype];
897 if (assignop == VINSTR_END) {
898 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
899 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
900 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
902 else if (!ast_compare_type(exprs[0], exprs[1]))
904 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
905 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
906 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
907 exprs[0]->vtype == TYPE_FUNCTION &&
908 exprs[1]->vtype == TYPE_FUNCTION)
910 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
911 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
914 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
917 (void)check_write_to(ctx, exprs[0]);
918 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
920 case opid3('+','+','P'):
921 case opid3('-','-','P'):
923 if (exprs[0]->vtype != TYPE_FLOAT) {
924 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
925 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
928 if (op->id == opid3('+','+','P'))
932 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
933 if (ast_istype(exprs[0], ast_entfield)) {
934 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
936 (ast_expression*)parser->fold->imm_float[1]);
938 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
940 (ast_expression*)parser->fold->imm_float[1]);
943 case opid3('S','+','+'):
944 case opid3('S','-','-'):
946 if (exprs[0]->vtype != TYPE_FLOAT) {
947 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
948 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
951 if (op->id == opid3('S','+','+')) {
958 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
959 if (ast_istype(exprs[0], ast_entfield)) {
960 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
962 (ast_expression*)parser->fold->imm_float[1]);
964 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
966 (ast_expression*)parser->fold->imm_float[1]);
970 out = (ast_expression*)ast_binary_new(ctx, subop,
972 (ast_expression*)parser->fold->imm_float[1]);
976 if (exprs[0]->vtype != exprs[1]->vtype ||
977 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
979 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
980 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
981 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
985 (void)check_write_to(ctx, exprs[0]);
986 if (ast_istype(exprs[0], ast_entfield))
987 assignop = type_storep_instr[exprs[0]->vtype];
989 assignop = type_store_instr[exprs[0]->vtype];
990 switch (exprs[0]->vtype) {
992 out = (ast_expression*)ast_binstore_new(ctx, assignop,
993 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
997 out = (ast_expression*)ast_binstore_new(ctx, assignop,
998 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1002 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1003 type_name[exprs[0]->vtype],
1004 type_name[exprs[1]->vtype]);
1008 case opid2('*','='):
1009 case opid2('/','='):
1010 if (exprs[1]->vtype != TYPE_FLOAT ||
1011 !(exprs[0]->vtype == TYPE_FLOAT ||
1012 exprs[0]->vtype == TYPE_VECTOR))
1014 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1015 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1016 compile_error(ctx, "invalid types used in expression: %s and %s",
1020 (void)check_write_to(ctx, exprs[0]);
1021 if (ast_istype(exprs[0], ast_entfield))
1022 assignop = type_storep_instr[exprs[0]->vtype];
1024 assignop = type_store_instr[exprs[0]->vtype];
1025 switch (exprs[0]->vtype) {
1027 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1028 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1029 exprs[0], exprs[1]);
1032 if (op->id == opid2('*','=')) {
1033 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1034 exprs[0], exprs[1]);
1036 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1037 (ast_expression*)parser->fold->imm_float[1],
1040 compile_error(ctx, "internal error: failed to generate division");
1043 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1048 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1049 type_name[exprs[0]->vtype],
1050 type_name[exprs[1]->vtype]);
1054 case opid2('&','='):
1055 case opid2('|','='):
1056 case opid2('^','='):
1057 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1058 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1059 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1060 compile_error(ctx, "invalid types used in expression: %s and %s",
1064 (void)check_write_to(ctx, exprs[0]);
1065 if (ast_istype(exprs[0], ast_entfield))
1066 assignop = type_storep_instr[exprs[0]->vtype];
1068 assignop = type_store_instr[exprs[0]->vtype];
1069 if (exprs[0]->vtype == TYPE_FLOAT)
1070 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1071 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1072 exprs[0], exprs[1]);
1074 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1075 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1076 exprs[0], exprs[1]);
1078 case opid3('&','~','='):
1079 /* This is like: a &= ~(b);
1080 * But QC has no bitwise-not, so we implement it as
1083 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1084 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1085 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1086 compile_error(ctx, "invalid types used in expression: %s and %s",
1090 if (ast_istype(exprs[0], ast_entfield))
1091 assignop = type_storep_instr[exprs[0]->vtype];
1093 assignop = type_store_instr[exprs[0]->vtype];
1094 if (exprs[0]->vtype == TYPE_FLOAT)
1095 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1097 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1100 (void)check_write_to(ctx, exprs[0]);
1101 if (exprs[0]->vtype == TYPE_FLOAT)
1102 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1104 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1105 asbinstore->keep_dest = true;
1106 out = (ast_expression*)asbinstore;
1109 case opid2('~', 'P'):
1110 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1111 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1112 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1115 if (!(out = fold_op(parser->fold, op, exprs))) {
1116 if (exprs[0]->vtype == TYPE_FLOAT) {
1117 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1119 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1126 compile_error(ctx, "failed to apply operator %s", op->op);
1130 vec_push(sy->out, syexp(ctx, out));
1134 static bool parser_close_call(parser_t *parser, shunt *sy)
1136 /* was a function call */
1137 ast_expression *fun;
1138 ast_value *funval = NULL;
1142 size_t paramcount, i;
1145 fid = vec_last(sy->ops).off;
1146 vec_shrinkby(sy->ops, 1);
1148 /* out[fid] is the function
1149 * everything above is parameters...
1151 if (!vec_size(sy->argc)) {
1152 parseerror(parser, "internal error: no argument counter available");
1156 paramcount = vec_last(sy->argc);
1159 if (vec_size(sy->out) < fid) {
1160 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1161 (unsigned long)vec_size(sy->out),
1163 (unsigned long)paramcount);
1168 * TODO handle this at the intrinsic level with an ast_intrinsic
1171 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1173 if (fid+2 != vec_size(sy->out) ||
1174 vec_last(sy->out).block)
1176 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1179 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1180 ast_unref(vec_last(sy->out).out);
1181 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1182 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1183 vec_shrinkby(sy->out, 1);
1188 * Now we need to determine if the function that is being called is
1189 * an intrinsic so we can evaluate if the arguments to it are constant
1190 * and than fruitfully fold them.
1192 #define fold_can_1(X) \
1193 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1194 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1196 if (fid + 1 < vec_size(sy->out))
1199 for (i = 0; i < paramcount; ++i) {
1200 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1207 * All is well which ends well, if we make it into here we can ignore the
1208 * intrinsic call and just evaluate it i.e constant fold it.
1210 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1211 ast_expression **exprs = NULL;
1212 ast_expression *foldval = NULL;
1214 for (i = 0; i < paramcount; i++)
1215 vec_push(exprs, sy->out[fid+1 + i].out);
1217 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1223 * Blub: what sorts of unreffing and resizing of
1224 * sy->out should I be doing here?
1226 sy->out[fid] = syexp(foldval->node.context, foldval);
1227 vec_shrinkby(sy->out, 1);
1234 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1239 if (fid+1 + paramcount != vec_size(sy->out)) {
1240 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1241 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1245 for (i = 0; i < paramcount; ++i)
1246 vec_push(call->params, sy->out[fid+1 + i].out);
1247 vec_shrinkby(sy->out, paramcount);
1248 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1249 if (parser->max_param_count < paramcount)
1250 parser->max_param_count = paramcount;
1252 if (ast_istype(fun, ast_value)) {
1253 funval = (ast_value*)fun;
1254 if ((fun->flags & AST_FLAG_VARIADIC) &&
1255 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1257 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1261 /* overwrite fid, the function, with a call */
1262 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1264 if (fun->vtype != TYPE_FUNCTION) {
1265 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1270 parseerror(parser, "could not determine function return type");
1273 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1275 if (fun->flags & AST_FLAG_DEPRECATED) {
1277 return !parsewarning(parser, WARN_DEPRECATED,
1278 "call to function (which is marked deprecated)\n",
1279 "-> it has been declared here: %s:%i",
1280 ast_ctx(fun).file, ast_ctx(fun).line);
1283 return !parsewarning(parser, WARN_DEPRECATED,
1284 "call to `%s` (which is marked deprecated)\n"
1285 "-> `%s` declared here: %s:%i",
1286 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1288 return !parsewarning(parser, WARN_DEPRECATED,
1289 "call to `%s` (deprecated: %s)\n"
1290 "-> `%s` declared here: %s:%i",
1291 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1295 if (vec_size(fun->params) != paramcount &&
1296 !((fun->flags & AST_FLAG_VARIADIC) &&
1297 vec_size(fun->params) < paramcount))
1299 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1301 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1302 "too %s parameters for call to %s: expected %i, got %i\n"
1303 " -> `%s` has been declared here: %s:%i",
1304 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1305 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1307 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1308 "too %s parameters for function call: expected %i, got %i\n"
1309 " -> it has been declared here: %s:%i",
1310 fewmany, (int)vec_size(fun->params), (int)paramcount,
1311 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1318 static bool parser_close_paren(parser_t *parser, shunt *sy)
1320 if (!vec_size(sy->ops)) {
1321 parseerror(parser, "unmatched closing paren");
1325 while (vec_size(sy->ops)) {
1326 if (vec_last(sy->ops).isparen) {
1327 if (vec_last(sy->paren) == PAREN_FUNC) {
1329 if (!parser_close_call(parser, sy))
1333 if (vec_last(sy->paren) == PAREN_EXPR) {
1335 if (!vec_size(sy->out)) {
1336 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1337 vec_shrinkby(sy->ops, 1);
1340 vec_shrinkby(sy->ops, 1);
1343 if (vec_last(sy->paren) == PAREN_INDEX) {
1345 /* pop off the parenthesis */
1346 vec_shrinkby(sy->ops, 1);
1347 /* then apply the index operator */
1348 if (!parser_sy_apply_operator(parser, sy))
1352 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1353 vec_last(sy->paren) = PAREN_TERNARY2;
1354 /* pop off the parenthesis */
1355 vec_shrinkby(sy->ops, 1);
1358 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1361 if (!parser_sy_apply_operator(parser, sy))
1367 static void parser_reclassify_token(parser_t *parser)
1370 if (parser->tok >= TOKEN_START)
1372 for (i = 0; i < operator_count; ++i) {
1373 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1374 parser->tok = TOKEN_OPERATOR;
1380 static ast_expression* parse_vararg_do(parser_t *parser)
1382 ast_expression *idx, *out;
1384 ast_value *funtype = parser->function->vtype;
1385 lex_ctx_t ctx = parser_ctx(parser);
1387 if (!parser->function->varargs) {
1388 parseerror(parser, "function has no variable argument list");
1392 if (!parser_next(parser) || parser->tok != '(') {
1393 parseerror(parser, "expected parameter index and type in parenthesis");
1396 if (!parser_next(parser)) {
1397 parseerror(parser, "error parsing parameter index");
1401 idx = parse_expression_leave(parser, true, false, false);
1405 if (parser->tok != ',') {
1406 if (parser->tok != ')') {
1408 parseerror(parser, "expected comma after parameter index");
1411 /* vararg piping: ...(start) */
1412 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1416 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1418 parseerror(parser, "expected typename for vararg");
1422 typevar = parse_typename(parser, NULL, NULL);
1428 if (parser->tok != ')') {
1430 ast_delete(typevar);
1431 parseerror(parser, "expected closing paren");
1435 if (funtype->expression.varparam &&
1436 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1440 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1441 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1442 compile_error(ast_ctx(typevar),
1443 "function was declared to take varargs of type `%s`, requested type is: %s",
1447 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1448 ast_type_adopt(out, typevar);
1449 ast_delete(typevar);
1453 static ast_expression* parse_vararg(parser_t *parser)
1455 bool old_noops = parser->lex->flags.noops;
1457 ast_expression *out;
1459 parser->lex->flags.noops = true;
1460 out = parse_vararg_do(parser);
1462 parser->lex->flags.noops = old_noops;
1466 /* not to be exposed */
1467 bool ftepp_predef_exists(const char *name);
1468 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1470 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1471 parser->tok == TOKEN_IDENT &&
1472 !strcmp(parser_tokval(parser), "_"))
1474 /* a translatable string */
1477 parser->lex->flags.noops = true;
1478 if (!parser_next(parser) || parser->tok != '(') {
1479 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1482 parser->lex->flags.noops = false;
1483 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1484 parseerror(parser, "expected a constant string in translatable-string extension");
1487 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1490 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1492 if (!parser_next(parser) || parser->tok != ')') {
1493 parseerror(parser, "expected closing paren after translatable string");
1498 else if (parser->tok == TOKEN_DOTS)
1501 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1502 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1505 va = parse_vararg(parser);
1508 vec_push(sy->out, syexp(parser_ctx(parser), va));
1511 else if (parser->tok == TOKEN_FLOATCONST) {
1512 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1515 vec_push(sy->out, syexp(parser_ctx(parser), val));
1518 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1519 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1522 vec_push(sy->out, syexp(parser_ctx(parser), val));
1525 else if (parser->tok == TOKEN_STRINGCONST) {
1526 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1529 vec_push(sy->out, syexp(parser_ctx(parser), val));
1532 else if (parser->tok == TOKEN_VECTORCONST) {
1533 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1536 vec_push(sy->out, syexp(parser_ctx(parser), val));
1539 else if (parser->tok == TOKEN_IDENT)
1541 const char *ctoken = parser_tokval(parser);
1542 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1543 ast_expression *var;
1544 /* a_vector.{x,y,z} */
1545 if (!vec_size(sy->ops) ||
1546 !vec_last(sy->ops).etype ||
1547 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1549 /* When adding more intrinsics, fix the above condition */
1552 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1554 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1556 var = parser_find_var(parser, parser_tokval(parser));
1558 var = parser_find_field(parser, parser_tokval(parser));
1560 if (!var && with_labels) {
1561 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1563 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1564 var = (ast_expression*)lbl;
1565 vec_push(parser->labels, lbl);
1568 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1569 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1572 * now we try for the real intrinsic hashtable. If the string
1573 * begins with __builtin, we simply skip past it, otherwise we
1574 * use the identifier as is.
1576 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1577 var = intrin_func(parser->intrin, parser_tokval(parser));
1581 char *correct = NULL;
1585 * sometimes people use preprocessing predefs without enabling them
1586 * i've done this thousands of times already myself. Lets check for
1587 * it in the predef table. And diagnose it better :)
1589 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1590 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1595 * TODO: determine the best score for the identifier: be it
1596 * a variable, a field.
1598 * We should also consider adding correction tables for
1599 * other things as well.
1601 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1603 correct_init(&corr);
1605 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1606 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1607 if (strcmp(correct, parser_tokval(parser))) {
1614 correct_free(&corr);
1617 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1622 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1628 if (ast_istype(var, ast_value)) {
1629 ((ast_value*)var)->uses++;
1631 else if (ast_istype(var, ast_member)) {
1632 ast_member *mem = (ast_member*)var;
1633 if (ast_istype(mem->owner, ast_value))
1634 ((ast_value*)(mem->owner))->uses++;
1637 vec_push(sy->out, syexp(parser_ctx(parser), var));
1640 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1644 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1646 ast_expression *expr = NULL;
1649 bool wantop = false;
1650 /* only warn once about an assignment in a truth value because the current code
1651 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1653 bool warn_parenthesis = true;
1655 /* count the parens because an if starts with one, so the
1656 * end of a condition is an unmatched closing paren
1660 memset(&sy, 0, sizeof(sy));
1662 parser->lex->flags.noops = false;
1664 parser_reclassify_token(parser);
1668 if (parser->tok == TOKEN_TYPENAME) {
1669 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1673 if (parser->tok == TOKEN_OPERATOR)
1675 /* classify the operator */
1676 const oper_info *op;
1677 const oper_info *olast = NULL;
1679 for (o = 0; o < operator_count; ++o) {
1680 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1681 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1682 !strcmp(parser_tokval(parser), operators[o].op))
1687 if (o == operator_count) {
1688 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1691 /* found an operator */
1694 /* when declaring variables, a comma starts a new variable */
1695 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1696 /* fixup the token */
1701 /* a colon without a pervious question mark cannot be a ternary */
1702 if (!ternaries && op->id == opid2(':','?')) {
1707 if (op->id == opid1(',')) {
1708 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1709 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1713 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1714 olast = &operators[vec_last(sy.ops).etype-1];
1716 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1717 while (olast && op->prec < olast->prec)
1719 if (!parser_sy_apply_operator(parser, &sy))
1721 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1722 olast = &operators[vec_last(sy.ops).etype-1];
1727 #define IsAssignOp(x) (\
1728 (x) == opid1('=') || \
1729 (x) == opid2('+','=') || \
1730 (x) == opid2('-','=') || \
1731 (x) == opid2('*','=') || \
1732 (x) == opid2('/','=') || \
1733 (x) == opid2('%','=') || \
1734 (x) == opid2('&','=') || \
1735 (x) == opid2('|','=') || \
1736 (x) == opid3('&','~','=') \
1738 if (warn_parenthesis) {
1739 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1740 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1741 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1744 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1745 warn_parenthesis = false;
1748 if (olast && olast->id != op->id) {
1749 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1750 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1752 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1753 warn_parenthesis = false;
1755 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1756 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1758 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1759 warn_parenthesis = false;
1765 (op->prec < olast->prec) ||
1766 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1768 if (!parser_sy_apply_operator(parser, &sy))
1770 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1771 olast = &operators[vec_last(sy.ops).etype-1];
1776 if (op->id == opid1('(')) {
1778 size_t sycount = vec_size(sy.out);
1779 /* we expected an operator, this is the function-call operator */
1780 vec_push(sy.paren, PAREN_FUNC);
1781 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1782 vec_push(sy.argc, 0);
1784 vec_push(sy.paren, PAREN_EXPR);
1785 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1788 } else if (op->id == opid1('[')) {
1790 parseerror(parser, "unexpected array subscript");
1793 vec_push(sy.paren, PAREN_INDEX);
1794 /* push both the operator and the paren, this makes life easier */
1795 vec_push(sy.ops, syop(parser_ctx(parser), op));
1796 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1798 } else if (op->id == opid2('?',':')) {
1799 vec_push(sy.ops, syop(parser_ctx(parser), op));
1800 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1803 vec_push(sy.paren, PAREN_TERNARY1);
1804 } else if (op->id == opid2(':','?')) {
1805 if (!vec_size(sy.paren)) {
1806 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1809 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1810 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1813 if (!parser_close_paren(parser, &sy))
1815 vec_push(sy.ops, syop(parser_ctx(parser), op));
1819 vec_push(sy.ops, syop(parser_ctx(parser), op));
1820 wantop = !!(op->flags & OP_SUFFIX);
1823 else if (parser->tok == ')') {
1824 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1825 if (!parser_sy_apply_operator(parser, &sy))
1828 if (!vec_size(sy.paren))
1831 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1832 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1835 if (!parser_close_paren(parser, &sy))
1838 /* must be a function call without parameters */
1839 if (vec_last(sy.paren) != PAREN_FUNC) {
1840 parseerror(parser, "closing paren in invalid position");
1843 if (!parser_close_paren(parser, &sy))
1848 else if (parser->tok == '(') {
1849 parseerror(parser, "internal error: '(' should be classified as operator");
1852 else if (parser->tok == '[') {
1853 parseerror(parser, "internal error: '[' should be classified as operator");
1856 else if (parser->tok == ']') {
1857 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1858 if (!parser_sy_apply_operator(parser, &sy))
1861 if (!vec_size(sy.paren))
1863 if (vec_last(sy.paren) != PAREN_INDEX) {
1864 parseerror(parser, "mismatched parentheses, unexpected ']'");
1867 if (!parser_close_paren(parser, &sy))
1872 if (!parse_sya_operand(parser, &sy, with_labels))
1875 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1876 vec_last(sy.argc)++;
1881 /* in this case we might want to allow constant string concatenation */
1882 bool concatenated = false;
1883 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1884 ast_expression *lexpr = vec_last(sy.out).out;
1885 if (ast_istype(lexpr, ast_value)) {
1886 ast_value *last = (ast_value*)lexpr;
1887 if (last->isimm == true && last->cvq == CV_CONST &&
1888 last->hasvalue && last->expression.vtype == TYPE_STRING)
1890 char *newstr = NULL;
1891 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1892 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1894 concatenated = true;
1898 if (!concatenated) {
1899 parseerror(parser, "expected operator or end of statement");
1904 if (!parser_next(parser)) {
1907 if (parser->tok == ';' ||
1908 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1909 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1915 while (vec_size(sy.ops)) {
1916 if (!parser_sy_apply_operator(parser, &sy))
1920 parser->lex->flags.noops = true;
1921 if (vec_size(sy.out) != 1) {
1922 parseerror(parser, "expression expected");
1925 expr = sy.out[0].out;
1928 if (vec_size(sy.paren)) {
1929 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1937 parser->lex->flags.noops = true;
1938 for (i = 0; i < vec_size(sy.out); ++i) {
1940 ast_unref(sy.out[i].out);
1949 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1951 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1954 if (parser->tok != ';') {
1955 parseerror(parser, "semicolon expected after expression");
1959 if (!parser_next(parser)) {
1966 static void parser_enterblock(parser_t *parser)
1968 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1969 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1970 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1971 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1972 vec_push(parser->_block_ctx, parser_ctx(parser));
1975 vec_push(parser->correct_variables, correct_trie_new());
1976 vec_push(parser->correct_variables_score, NULL);
1979 static bool parser_leaveblock(parser_t *parser)
1982 size_t locals, typedefs;
1984 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1985 parseerror(parser, "internal error: parser_leaveblock with no block");
1989 util_htdel(vec_last(parser->variables));
1990 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1992 vec_pop(parser->variables);
1993 vec_pop(parser->correct_variables);
1994 vec_pop(parser->correct_variables_score);
1995 if (!vec_size(parser->_blocklocals)) {
1996 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2000 locals = vec_last(parser->_blocklocals);
2001 vec_pop(parser->_blocklocals);
2002 while (vec_size(parser->_locals) != locals) {
2003 ast_expression *e = vec_last(parser->_locals);
2004 ast_value *v = (ast_value*)e;
2005 vec_pop(parser->_locals);
2006 if (ast_istype(e, ast_value) && !v->uses) {
2007 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2012 typedefs = vec_last(parser->_blocktypedefs);
2013 while (vec_size(parser->_typedefs) != typedefs) {
2014 ast_delete(vec_last(parser->_typedefs));
2015 vec_pop(parser->_typedefs);
2017 util_htdel(vec_last(parser->typedefs));
2018 vec_pop(parser->typedefs);
2020 vec_pop(parser->_block_ctx);
2025 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2027 vec_push(parser->_locals, e);
2028 util_htset(vec_last(parser->variables), name, (void*)e);
2032 vec_last(parser->correct_variables),
2033 &vec_last(parser->correct_variables_score),
2038 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2040 vec_push(parser->globals, e);
2041 util_htset(parser->htglobals, name, e);
2045 parser->correct_variables[0],
2046 &parser->correct_variables_score[0],
2051 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2055 ast_expression *prev;
2057 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2059 ast_type_to_string(cond, ty, sizeof(ty));
2060 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2063 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2066 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2069 parseerror(parser, "internal error: failed to process condition");
2074 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2076 /* vector types need to be cast to true booleans */
2077 ast_binary *bin = (ast_binary*)cond;
2078 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2080 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2082 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2085 parseerror(parser, "internal error: failed to process condition");
2092 unary = (ast_unary*)cond;
2093 /* ast_istype dereferences cond, should test here for safety */
2094 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2096 cond = unary->operand;
2097 unary->operand = NULL;
2100 unary = (ast_unary*)cond;
2104 parseerror(parser, "internal error: failed to process condition");
2106 if (ifnot) *_ifnot = !*_ifnot;
2110 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2113 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2116 lex_ctx_t ctx = parser_ctx(parser);
2118 (void)block; /* not touching */
2120 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2121 if (!parser_next(parser)) {
2122 parseerror(parser, "expected condition or 'not'");
2125 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2127 if (!parser_next(parser)) {
2128 parseerror(parser, "expected condition in parenthesis");
2132 if (parser->tok != '(') {
2133 parseerror(parser, "expected 'if' condition in parenthesis");
2136 /* parse into the expression */
2137 if (!parser_next(parser)) {
2138 parseerror(parser, "expected 'if' condition after opening paren");
2141 /* parse the condition */
2142 cond = parse_expression_leave(parser, false, true, false);
2146 if (parser->tok != ')') {
2147 parseerror(parser, "expected closing paren after 'if' condition");
2151 /* parse into the 'then' branch */
2152 if (!parser_next(parser)) {
2153 parseerror(parser, "expected statement for on-true branch of 'if'");
2157 if (!parse_statement_or_block(parser, &ontrue)) {
2162 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2163 /* check for an else */
2164 if (!strcmp(parser_tokval(parser), "else")) {
2165 /* parse into the 'else' branch */
2166 if (!parser_next(parser)) {
2167 parseerror(parser, "expected on-false branch after 'else'");
2172 if (!parse_statement_or_block(parser, &onfalse)) {
2179 cond = process_condition(parser, cond, &ifnot);
2181 if (ontrue) ast_delete(ontrue);
2182 if (onfalse) ast_delete(onfalse);
2187 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2189 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2190 *out = (ast_expression*)ifthen;
2194 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2195 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2200 /* skip the 'while' and get the body */
2201 if (!parser_next(parser)) {
2202 if (OPTS_FLAG(LOOP_LABELS))
2203 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2205 parseerror(parser, "expected 'while' condition in parenthesis");
2209 if (parser->tok == ':') {
2210 if (!OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2212 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2213 parseerror(parser, "expected loop label");
2216 label = util_strdup(parser_tokval(parser));
2217 if (!parser_next(parser)) {
2219 parseerror(parser, "expected 'while' condition in parenthesis");
2224 if (parser->tok != '(') {
2225 parseerror(parser, "expected 'while' condition in parenthesis");
2229 vec_push(parser->breaks, label);
2230 vec_push(parser->continues, label);
2232 rv = parse_while_go(parser, block, out);
2235 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2236 parseerror(parser, "internal error: label stack corrupted");
2242 vec_pop(parser->breaks);
2243 vec_pop(parser->continues);
2248 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2251 ast_expression *cond, *ontrue;
2255 lex_ctx_t ctx = parser_ctx(parser);
2257 (void)block; /* not touching */
2259 /* parse into the expression */
2260 if (!parser_next(parser)) {
2261 parseerror(parser, "expected 'while' condition after opening paren");
2264 /* parse the condition */
2265 cond = parse_expression_leave(parser, false, true, false);
2269 if (parser->tok != ')') {
2270 parseerror(parser, "expected closing paren after 'while' condition");
2274 /* parse into the 'then' branch */
2275 if (!parser_next(parser)) {
2276 parseerror(parser, "expected while-loop body");
2280 if (!parse_statement_or_block(parser, &ontrue)) {
2285 cond = process_condition(parser, cond, &ifnot);
2290 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2291 *out = (ast_expression*)aloop;
2295 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2296 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2301 /* skip the 'do' and get the body */
2302 if (!parser_next(parser)) {
2303 if (OPTS_FLAG(LOOP_LABELS))
2304 parseerror(parser, "expected loop label or body");
2306 parseerror(parser, "expected loop body");
2310 if (parser->tok == ':') {
2311 if (!OPTS_FLAG(LOOP_LABELS))
2312 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2313 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2314 parseerror(parser, "expected loop label");
2317 label = util_strdup(parser_tokval(parser));
2318 if (!parser_next(parser)) {
2320 parseerror(parser, "expected loop body");
2325 vec_push(parser->breaks, label);
2326 vec_push(parser->continues, label);
2328 rv = parse_dowhile_go(parser, block, out);
2331 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2332 parseerror(parser, "internal error: label stack corrupted");
2335 * Test for NULL otherwise ast_delete dereferences null pointer
2343 vec_pop(parser->breaks);
2344 vec_pop(parser->continues);
2349 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2352 ast_expression *cond, *ontrue;
2356 lex_ctx_t ctx = parser_ctx(parser);
2358 (void)block; /* not touching */
2360 if (!parse_statement_or_block(parser, &ontrue))
2363 /* expect the "while" */
2364 if (parser->tok != TOKEN_KEYWORD ||
2365 strcmp(parser_tokval(parser), "while"))
2367 parseerror(parser, "expected 'while' and condition");
2372 /* skip the 'while' and check for opening paren */
2373 if (!parser_next(parser) || parser->tok != '(') {
2374 parseerror(parser, "expected 'while' condition in parenthesis");
2378 /* parse into the expression */
2379 if (!parser_next(parser)) {
2380 parseerror(parser, "expected 'while' condition after opening paren");
2384 /* parse the condition */
2385 cond = parse_expression_leave(parser, false, true, false);
2389 if (parser->tok != ')') {
2390 parseerror(parser, "expected closing paren after 'while' condition");
2396 if (!parser_next(parser) || parser->tok != ';') {
2397 parseerror(parser, "expected semicolon after condition");
2403 if (!parser_next(parser)) {
2404 parseerror(parser, "parse error");
2410 cond = process_condition(parser, cond, &ifnot);
2415 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2416 *out = (ast_expression*)aloop;
2420 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2421 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2426 /* skip the 'for' and check for opening paren */
2427 if (!parser_next(parser)) {
2428 if (OPTS_FLAG(LOOP_LABELS))
2429 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2431 parseerror(parser, "expected 'for' expressions in parenthesis");
2435 if (parser->tok == ':') {
2436 if (!OPTS_FLAG(LOOP_LABELS))
2437 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2438 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2439 parseerror(parser, "expected loop label");
2442 label = util_strdup(parser_tokval(parser));
2443 if (!parser_next(parser)) {
2445 parseerror(parser, "expected 'for' expressions in parenthesis");
2450 if (parser->tok != '(') {
2451 parseerror(parser, "expected 'for' expressions in parenthesis");
2455 vec_push(parser->breaks, label);
2456 vec_push(parser->continues, label);
2458 rv = parse_for_go(parser, block, out);
2461 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2462 parseerror(parser, "internal error: label stack corrupted");
2468 vec_pop(parser->breaks);
2469 vec_pop(parser->continues);
2473 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2476 ast_expression *initexpr, *cond, *increment, *ontrue;
2481 lex_ctx_t ctx = parser_ctx(parser);
2483 parser_enterblock(parser);
2490 /* parse into the expression */
2491 if (!parser_next(parser)) {
2492 parseerror(parser, "expected 'for' initializer after opening paren");
2497 if (parser->tok == TOKEN_IDENT)
2498 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2500 if (typevar || parser->tok == TOKEN_TYPENAME) {
2502 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2503 if (parsewarning(parser, WARN_EXTENSIONS,
2504 "current standard does not allow variable declarations in for-loop initializers"))
2508 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2511 else if (parser->tok != ';')
2513 initexpr = parse_expression_leave(parser, false, false, false);
2518 /* move on to condition */
2519 if (parser->tok != ';') {
2520 parseerror(parser, "expected semicolon after for-loop initializer");
2523 if (!parser_next(parser)) {
2524 parseerror(parser, "expected for-loop condition");
2528 /* parse the condition */
2529 if (parser->tok != ';') {
2530 cond = parse_expression_leave(parser, false, true, false);
2535 /* move on to incrementor */
2536 if (parser->tok != ';') {
2537 parseerror(parser, "expected semicolon after for-loop initializer");
2540 if (!parser_next(parser)) {
2541 parseerror(parser, "expected for-loop condition");
2545 /* parse the incrementor */
2546 if (parser->tok != ')') {
2547 lex_ctx_t condctx = parser_ctx(parser);
2548 increment = parse_expression_leave(parser, false, false, false);
2551 if (!ast_side_effects(increment)) {
2552 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2558 if (parser->tok != ')') {
2559 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2562 /* parse into the 'then' branch */
2563 if (!parser_next(parser)) {
2564 parseerror(parser, "expected for-loop body");
2567 if (!parse_statement_or_block(parser, &ontrue))
2571 cond = process_condition(parser, cond, &ifnot);
2575 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2576 *out = (ast_expression*)aloop;
2578 if (!parser_leaveblock(parser)) {
2584 if (initexpr) ast_unref(initexpr);
2585 if (cond) ast_unref(cond);
2586 if (increment) ast_unref(increment);
2587 (void)!parser_leaveblock(parser);
2591 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2593 ast_expression *exp = NULL;
2594 ast_expression *var = NULL;
2595 ast_return *ret = NULL;
2596 ast_value *retval = parser->function->return_value;
2597 ast_value *expected = parser->function->vtype;
2599 lex_ctx_t ctx = parser_ctx(parser);
2601 (void)block; /* not touching */
2603 if (!parser_next(parser)) {
2604 parseerror(parser, "expected return expression");
2608 /* return assignments */
2609 if (parser->tok == '=') {
2610 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2611 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2615 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2617 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2618 parseerror(parser, "invalid return type: `%s'", ty1);
2622 if (!parser_next(parser)) {
2623 parseerror(parser, "expected return assignment expression");
2627 if (!(exp = parse_expression_leave(parser, false, false, false)))
2630 /* prepare the return value */
2632 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2633 ast_type_adopt(retval, expected->expression.next);
2634 parser->function->return_value = retval;
2637 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2638 char ty1[1024], ty2[1024];
2639 ast_type_to_string(exp, ty1, sizeof(ty1));
2640 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2641 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2644 /* store to 'return' local variable */
2645 var = (ast_expression*)ast_store_new(
2647 type_store_instr[expected->expression.next->vtype],
2648 (ast_expression*)retval, exp);
2655 if (parser->tok != ';')
2656 parseerror(parser, "missing semicolon after return assignment");
2657 else if (!parser_next(parser))
2658 parseerror(parser, "parse error after return assignment");
2664 if (parser->tok != ';') {
2665 exp = parse_expression(parser, false, false);
2669 if (exp->vtype != TYPE_NIL &&
2670 exp->vtype != ((ast_expression*)expected)->next->vtype)
2672 parseerror(parser, "return with invalid expression");
2675 ret = ast_return_new(ctx, exp);
2681 if (!parser_next(parser))
2682 parseerror(parser, "parse error");
2684 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2686 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2688 ret = ast_return_new(ctx, (ast_expression*)retval);
2690 *out = (ast_expression*)ret;
2694 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2697 unsigned int levels = 0;
2698 lex_ctx_t ctx = parser_ctx(parser);
2699 const char **loops = (is_continue ? parser->continues : parser->breaks);
2701 (void)block; /* not touching */
2702 if (!parser_next(parser)) {
2703 parseerror(parser, "expected semicolon or loop label");
2707 if (!vec_size(loops)) {
2709 parseerror(parser, "`continue` can only be used inside loops");
2711 parseerror(parser, "`break` can only be used inside loops or switches");
2714 if (parser->tok == TOKEN_IDENT) {
2715 if (!OPTS_FLAG(LOOP_LABELS))
2716 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717 i = vec_size(loops);
2719 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2722 parseerror(parser, "no such loop to %s: `%s`",
2723 (is_continue ? "continue" : "break out of"),
2724 parser_tokval(parser));
2729 if (!parser_next(parser)) {
2730 parseerror(parser, "expected semicolon");
2735 if (parser->tok != ';') {
2736 parseerror(parser, "expected semicolon");
2740 if (!parser_next(parser))
2741 parseerror(parser, "parse error");
2743 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2747 /* returns true when it was a variable qualifier, false otherwise!
2748 * on error, cvq is set to CV_WRONG
2750 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2752 bool had_const = false;
2753 bool had_var = false;
2754 bool had_noref = false;
2755 bool had_attrib = false;
2756 bool had_static = false;
2761 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2763 /* parse an attribute */
2764 if (!parser_next(parser)) {
2765 parseerror(parser, "expected attribute after `[[`");
2769 if (!strcmp(parser_tokval(parser), "noreturn")) {
2770 flags |= AST_FLAG_NORETURN;
2771 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2772 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2777 else if (!strcmp(parser_tokval(parser), "noref")) {
2779 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2780 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2785 else if (!strcmp(parser_tokval(parser), "inline")) {
2786 flags |= AST_FLAG_INLINE;
2787 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2788 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2793 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2794 flags |= AST_FLAG_ERASEABLE;
2795 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2796 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2801 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2802 flags |= AST_FLAG_ALIAS;
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "parse error in attribute");
2810 if (parser->tok == '(') {
2811 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2812 parseerror(parser, "`alias` attribute missing parameter");
2816 *message = util_strdup(parser_tokval(parser));
2818 if (!parser_next(parser)) {
2819 parseerror(parser, "parse error in attribute");
2823 if (parser->tok != ')') {
2824 parseerror(parser, "`alias` attribute expected `)` after parameter");
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "parse error in attribute");
2834 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2835 parseerror(parser, "`alias` attribute expected `]]`");
2839 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2840 flags |= AST_FLAG_DEPRECATED;
2843 if (!parser_next(parser)) {
2844 parseerror(parser, "parse error in attribute");
2848 if (parser->tok == '(') {
2849 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2850 parseerror(parser, "`deprecated` attribute missing parameter");
2854 *message = util_strdup(parser_tokval(parser));
2856 if (!parser_next(parser)) {
2857 parseerror(parser, "parse error in attribute");
2861 if(parser->tok != ')') {
2862 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2866 if (!parser_next(parser)) {
2867 parseerror(parser, "parse error in attribute");
2872 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2873 parseerror(parser, "`deprecated` attribute expected `]]`");
2876 if (*message) mem_d(*message);
2884 /* Skip tokens until we hit a ]] */
2885 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2886 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2887 if (!parser_next(parser)) {
2888 parseerror(parser, "error inside attribute");
2895 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2897 else if (!strcmp(parser_tokval(parser), "const"))
2899 else if (!strcmp(parser_tokval(parser), "var"))
2901 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2903 else if (!strcmp(parser_tokval(parser), "noref"))
2905 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2910 if (!parser_next(parser))
2920 *is_static = had_static;
2924 parseerror(parser, "parse error after variable qualifier");
2929 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2930 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2935 /* skip the 'while' and get the body */
2936 if (!parser_next(parser)) {
2937 if (OPTS_FLAG(LOOP_LABELS))
2938 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2940 parseerror(parser, "expected 'switch' operand in parenthesis");
2944 if (parser->tok == ':') {
2945 if (!OPTS_FLAG(LOOP_LABELS))
2946 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2947 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2948 parseerror(parser, "expected loop label");
2951 label = util_strdup(parser_tokval(parser));
2952 if (!parser_next(parser)) {
2954 parseerror(parser, "expected 'switch' operand in parenthesis");
2959 if (parser->tok != '(') {
2960 parseerror(parser, "expected 'switch' operand in parenthesis");
2964 vec_push(parser->breaks, label);
2966 rv = parse_switch_go(parser, block, out);
2969 if (vec_last(parser->breaks) != label) {
2970 parseerror(parser, "internal error: label stack corrupted");
2976 vec_pop(parser->breaks);
2981 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2983 ast_expression *operand;
2986 ast_switch *switchnode;
2987 ast_switch_case swcase;
2990 bool noref, is_static;
2991 uint32_t qflags = 0;
2993 lex_ctx_t ctx = parser_ctx(parser);
2995 (void)block; /* not touching */
2998 /* parse into the expression */
2999 if (!parser_next(parser)) {
3000 parseerror(parser, "expected switch operand");
3003 /* parse the operand */
3004 operand = parse_expression_leave(parser, false, false, false);
3008 switchnode = ast_switch_new(ctx, operand);
3011 if (parser->tok != ')') {
3012 ast_delete(switchnode);
3013 parseerror(parser, "expected closing paren after 'switch' operand");
3017 /* parse over the opening paren */
3018 if (!parser_next(parser) || parser->tok != '{') {
3019 ast_delete(switchnode);
3020 parseerror(parser, "expected list of cases");
3024 if (!parser_next(parser)) {
3025 ast_delete(switchnode);
3026 parseerror(parser, "expected 'case' or 'default'");
3030 /* new block; allow some variables to be declared here */
3031 parser_enterblock(parser);
3034 if (parser->tok == TOKEN_IDENT)
3035 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3036 if (typevar || parser->tok == TOKEN_TYPENAME) {
3037 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3038 ast_delete(switchnode);
3043 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3045 if (cvq == CV_WRONG) {
3046 ast_delete(switchnode);
3049 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3050 ast_delete(switchnode);
3059 while (parser->tok != '}') {
3060 ast_block *caseblock;
3062 if (!strcmp(parser_tokval(parser), "case")) {
3063 if (!parser_next(parser)) {
3064 ast_delete(switchnode);
3065 parseerror(parser, "expected expression for case");
3068 swcase.value = parse_expression_leave(parser, false, false, false);
3069 if (!swcase.value) {
3070 ast_delete(switchnode);
3071 parseerror(parser, "expected expression for case");
3074 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3075 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3076 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3082 else if (!strcmp(parser_tokval(parser), "default")) {
3083 swcase.value = NULL;
3084 if (!parser_next(parser)) {
3085 ast_delete(switchnode);
3086 parseerror(parser, "expected colon");
3091 ast_delete(switchnode);
3092 parseerror(parser, "expected 'case' or 'default'");
3096 /* Now the colon and body */
3097 if (parser->tok != ':') {
3098 if (swcase.value) ast_unref(swcase.value);
3099 ast_delete(switchnode);
3100 parseerror(parser, "expected colon");
3104 if (!parser_next(parser)) {
3105 if (swcase.value) ast_unref(swcase.value);
3106 ast_delete(switchnode);
3107 parseerror(parser, "expected statements or case");
3110 caseblock = ast_block_new(parser_ctx(parser));
3112 if (swcase.value) ast_unref(swcase.value);
3113 ast_delete(switchnode);
3116 swcase.code = (ast_expression*)caseblock;
3117 vec_push(switchnode->cases, swcase);
3119 ast_expression *expr;
3120 if (parser->tok == '}')
3122 if (parser->tok == TOKEN_KEYWORD) {
3123 if (!strcmp(parser_tokval(parser), "case") ||
3124 !strcmp(parser_tokval(parser), "default"))
3129 if (!parse_statement(parser, caseblock, &expr, true)) {
3130 ast_delete(switchnode);
3135 if (!ast_block_add_expr(caseblock, expr)) {
3136 ast_delete(switchnode);
3142 parser_leaveblock(parser);
3145 if (parser->tok != '}') {
3146 ast_delete(switchnode);
3147 parseerror(parser, "expected closing paren of case list");
3150 if (!parser_next(parser)) {
3151 ast_delete(switchnode);
3152 parseerror(parser, "parse error after switch");
3155 *out = (ast_expression*)switchnode;
3159 /* parse computed goto sides */
3160 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3161 ast_expression *on_true;
3162 ast_expression *on_false;
3163 ast_expression *cond;
3168 if (ast_istype(*side, ast_ternary)) {
3169 ast_ternary *tern = (ast_ternary*)*side;
3170 on_true = parse_goto_computed(parser, &tern->on_true);
3171 on_false = parse_goto_computed(parser, &tern->on_false);
3173 if (!on_true || !on_false) {
3174 parseerror(parser, "expected label or expression in ternary");
3175 if (on_true) ast_unref(on_true);
3176 if (on_false) ast_unref(on_false);
3184 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3185 } else if (ast_istype(*side, ast_label)) {
3186 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3187 ast_goto_set_label(gt, ((ast_label*)*side));
3189 return (ast_expression*)gt;
3194 static bool parse_goto(parser_t *parser, ast_expression **out)
3196 ast_goto *gt = NULL;
3197 ast_expression *lbl;
3199 if (!parser_next(parser))
3202 if (parser->tok != TOKEN_IDENT) {
3203 ast_expression *expression;
3205 /* could be an expression i.e computed goto :-) */
3206 if (parser->tok != '(') {
3207 parseerror(parser, "expected label name after `goto`");
3211 /* failed to parse expression for goto */
3212 if (!(expression = parse_expression(parser, false, true)) ||
3213 !(*out = parse_goto_computed(parser, &expression))) {
3214 parseerror(parser, "invalid goto expression");
3216 ast_unref(expression);
3223 /* not computed goto */
3224 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3225 lbl = parser_find_label(parser, gt->name);
3227 if (!ast_istype(lbl, ast_label)) {
3228 parseerror(parser, "internal error: label is not an ast_label");
3232 ast_goto_set_label(gt, (ast_label*)lbl);
3235 vec_push(parser->gotos, gt);
3237 if (!parser_next(parser) || parser->tok != ';') {
3238 parseerror(parser, "semicolon expected after goto label");
3241 if (!parser_next(parser)) {
3242 parseerror(parser, "parse error after goto");
3246 *out = (ast_expression*)gt;
3250 static bool parse_skipwhite(parser_t *parser)
3253 if (!parser_next(parser))
3255 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3256 return parser->tok < TOKEN_ERROR;
3259 static bool parse_eol(parser_t *parser)
3261 if (!parse_skipwhite(parser))
3263 return parser->tok == TOKEN_EOL;
3266 static bool parse_pragma_do(parser_t *parser)
3268 if (!parser_next(parser) ||
3269 parser->tok != TOKEN_IDENT ||
3270 strcmp(parser_tokval(parser), "pragma"))
3272 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3275 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3276 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3280 if (!strcmp(parser_tokval(parser), "noref")) {
3281 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3282 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3285 parser->noref = !!parser_token(parser)->constval.i;
3286 if (!parse_eol(parser)) {
3287 parseerror(parser, "parse error after `noref` pragma");
3293 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3300 static bool parse_pragma(parser_t *parser)
3303 parser->lex->flags.preprocessing = true;
3304 parser->lex->flags.mergelines = true;
3305 rv = parse_pragma_do(parser);
3306 if (parser->tok != TOKEN_EOL) {
3307 parseerror(parser, "junk after pragma");
3310 parser->lex->flags.preprocessing = false;
3311 parser->lex->flags.mergelines = false;
3312 if (!parser_next(parser)) {
3313 parseerror(parser, "parse error after pragma");
3319 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3321 bool noref, is_static;
3323 uint32_t qflags = 0;
3324 ast_value *typevar = NULL;
3325 char *vstring = NULL;
3329 if (parser->tok == TOKEN_IDENT)
3330 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3332 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3334 /* local variable */
3336 parseerror(parser, "cannot declare a variable from here");
3339 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3340 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3343 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3347 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3349 if (cvq == CV_WRONG)
3351 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3353 else if (parser->tok == TOKEN_KEYWORD)
3355 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3360 if (!parser_next(parser)) {
3361 parseerror(parser, "parse error after __builtin_debug_printtype");
3365 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3367 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3368 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3369 if (!parser_next(parser)) {
3370 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3376 if (!parse_statement(parser, block, out, allow_cases))
3379 con_out("__builtin_debug_printtype: got no output node\n");
3382 ast_type_to_string(*out, ty, sizeof(ty));
3383 con_out("__builtin_debug_printtype: `%s`\n", ty);
3388 else if (!strcmp(parser_tokval(parser), "return"))
3390 return parse_return(parser, block, out);
3392 else if (!strcmp(parser_tokval(parser), "if"))
3394 return parse_if(parser, block, out);
3396 else if (!strcmp(parser_tokval(parser), "while"))
3398 return parse_while(parser, block, out);
3400 else if (!strcmp(parser_tokval(parser), "do"))
3402 return parse_dowhile(parser, block, out);
3404 else if (!strcmp(parser_tokval(parser), "for"))
3406 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3407 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3410 return parse_for(parser, block, out);
3412 else if (!strcmp(parser_tokval(parser), "break"))
3414 return parse_break_continue(parser, block, out, false);
3416 else if (!strcmp(parser_tokval(parser), "continue"))
3418 return parse_break_continue(parser, block, out, true);
3420 else if (!strcmp(parser_tokval(parser), "switch"))
3422 return parse_switch(parser, block, out);
3424 else if (!strcmp(parser_tokval(parser), "case") ||
3425 !strcmp(parser_tokval(parser), "default"))
3428 parseerror(parser, "unexpected 'case' label");
3433 else if (!strcmp(parser_tokval(parser), "goto"))
3435 return parse_goto(parser, out);
3437 else if (!strcmp(parser_tokval(parser), "typedef"))
3439 if (!parser_next(parser)) {
3440 parseerror(parser, "expected type definition after 'typedef'");
3443 return parse_typedef(parser);
3445 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3448 else if (parser->tok == '{')
3451 inner = parse_block(parser);
3454 *out = (ast_expression*)inner;
3457 else if (parser->tok == ':')
3461 if (!parser_next(parser)) {
3462 parseerror(parser, "expected label name");
3465 if (parser->tok != TOKEN_IDENT) {
3466 parseerror(parser, "label must be an identifier");
3469 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3471 if (!label->undefined) {
3472 parseerror(parser, "label `%s` already defined", label->name);
3475 label->undefined = false;
3478 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3479 vec_push(parser->labels, label);
3481 *out = (ast_expression*)label;
3482 if (!parser_next(parser)) {
3483 parseerror(parser, "parse error after label");
3486 for (i = 0; i < vec_size(parser->gotos); ++i) {
3487 if (!strcmp(parser->gotos[i]->name, label->name)) {
3488 ast_goto_set_label(parser->gotos[i], label);
3489 vec_remove(parser->gotos, i, 1);
3495 else if (parser->tok == ';')
3497 if (!parser_next(parser)) {
3498 parseerror(parser, "parse error after empty statement");
3505 lex_ctx_t ctx = parser_ctx(parser);
3506 ast_expression *exp = parse_expression(parser, false, false);
3510 if (!ast_side_effects(exp)) {
3511 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3518 static bool parse_enum(parser_t *parser)
3521 bool reverse = false;
3523 ast_value **values = NULL;
3524 ast_value *var = NULL;
3527 ast_expression *old;
3529 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3530 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3534 /* enumeration attributes (can add more later) */
3535 if (parser->tok == ':') {
3536 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3537 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3542 if (!strcmp(parser_tokval(parser), "flag")) {
3546 else if (!strcmp(parser_tokval(parser), "reverse")) {
3550 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3554 if (!parser_next(parser) || parser->tok != '{') {
3555 parseerror(parser, "expected `{` after enum attribute ");
3561 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3562 if (parser->tok == '}') {
3563 /* allow an empty enum */
3566 parseerror(parser, "expected identifier or `}`");
3570 old = parser_find_field(parser, parser_tokval(parser));
3572 old = parser_find_global(parser, parser_tokval(parser));
3574 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3575 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3579 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3580 vec_push(values, var);
3581 var->cvq = CV_CONST;
3582 var->hasvalue = true;
3584 /* for flagged enumerations increment in POTs of TWO */
3585 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3586 parser_addglobal(parser, var->name, (ast_expression*)var);
3588 if (!parser_next(parser)) {
3589 parseerror(parser, "expected `=`, `}` or comma after identifier");
3593 if (parser->tok == ',')
3595 if (parser->tok == '}')
3597 if (parser->tok != '=') {
3598 parseerror(parser, "expected `=`, `}` or comma after identifier");
3602 if (!parser_next(parser)) {
3603 parseerror(parser, "expected expression after `=`");
3607 /* We got a value! */
3608 old = parse_expression_leave(parser, true, false, false);
3609 asvalue = (ast_value*)old;
3610 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3611 compile_error(ast_ctx(var), "constant value or expression expected");
3614 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3616 if (parser->tok == '}')
3618 if (parser->tok != ',') {
3619 parseerror(parser, "expected `}` or comma after expression");
3624 /* patch them all (for reversed attribute) */
3627 for (i = 0; i < vec_size(values); i++)
3628 values[i]->constval.vfloat = vec_size(values) - i - 1;
3631 if (parser->tok != '}') {
3632 parseerror(parser, "internal error: breaking without `}`");
3636 if (!parser_next(parser) || parser->tok != ';') {
3637 parseerror(parser, "expected semicolon after enumeration");
3641 if (!parser_next(parser)) {
3642 parseerror(parser, "parse error after enumeration");
3654 static bool parse_block_into(parser_t *parser, ast_block *block)
3658 parser_enterblock(parser);
3660 if (!parser_next(parser)) { /* skip the '{' */
3661 parseerror(parser, "expected function body");
3665 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3667 ast_expression *expr = NULL;
3668 if (parser->tok == '}')
3671 if (!parse_statement(parser, block, &expr, false)) {
3672 /* parseerror(parser, "parse error"); */
3678 if (!ast_block_add_expr(block, expr)) {
3685 if (parser->tok != '}') {
3688 (void)parser_next(parser);
3692 if (!parser_leaveblock(parser))
3694 return retval && !!block;
3697 static ast_block* parse_block(parser_t *parser)
3700 block = ast_block_new(parser_ctx(parser));
3703 if (!parse_block_into(parser, block)) {
3704 ast_block_delete(block);
3710 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3712 if (parser->tok == '{') {
3713 *out = (ast_expression*)parse_block(parser);
3716 return parse_statement(parser, NULL, out, false);
3719 static bool create_vector_members(ast_value *var, ast_member **me)
3722 size_t len = strlen(var->name);
3724 for (i = 0; i < 3; ++i) {
3725 char *name = (char*)mem_a(len+3);
3726 memcpy(name, var->name, len);
3728 name[len+1] = 'x'+i;
3730 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3739 do { ast_member_delete(me[--i]); } while(i);
3743 static bool parse_function_body(parser_t *parser, ast_value *var)
3745 ast_block *block = NULL;
3750 ast_expression *framenum = NULL;
3751 ast_expression *nextthink = NULL;
3752 /* None of the following have to be deleted */
3753 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3754 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3755 bool has_frame_think;
3759 has_frame_think = false;
3760 old = parser->function;
3762 if (var->expression.flags & AST_FLAG_ALIAS) {
3763 parseerror(parser, "function aliases cannot have bodies");
3767 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3768 parseerror(parser, "gotos/labels leaking");
3772 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3773 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3774 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3780 if (parser->tok == '[') {
3781 /* got a frame definition: [ framenum, nextthink ]
3782 * this translates to:
3783 * self.frame = framenum;
3784 * self.nextthink = time + 0.1;
3785 * self.think = nextthink;
3789 fld_think = parser_find_field(parser, "think");
3790 fld_nextthink = parser_find_field(parser, "nextthink");
3791 fld_frame = parser_find_field(parser, "frame");
3792 if (!fld_think || !fld_nextthink || !fld_frame) {
3793 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3794 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3797 gbl_time = parser_find_global(parser, "time");
3798 gbl_self = parser_find_global(parser, "self");
3799 if (!gbl_time || !gbl_self) {
3800 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3801 parseerror(parser, "please declare the following globals: `time`, `self`");
3805 if (!parser_next(parser))
3808 framenum = parse_expression_leave(parser, true, false, false);
3810 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3813 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3814 ast_unref(framenum);
3815 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3819 if (parser->tok != ',') {
3820 ast_unref(framenum);
3821 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3822 parseerror(parser, "Got a %i\n", parser->tok);
3826 if (!parser_next(parser)) {
3827 ast_unref(framenum);
3831 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3833 /* qc allows the use of not-yet-declared functions here
3834 * - this automatically creates a prototype */
3835 ast_value *thinkfunc;
3836 ast_expression *functype = fld_think->next;
3838 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3839 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3840 ast_unref(framenum);
3841 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3844 ast_type_adopt(thinkfunc, functype);
3846 if (!parser_next(parser)) {
3847 ast_unref(framenum);
3848 ast_delete(thinkfunc);
3852 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3854 nextthink = (ast_expression*)thinkfunc;
3857 nextthink = parse_expression_leave(parser, true, false, false);
3859 ast_unref(framenum);
3860 parseerror(parser, "expected a think-function in [frame,think] notation");
3865 if (!ast_istype(nextthink, ast_value)) {
3866 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3870 if (retval && parser->tok != ']') {
3871 parseerror(parser, "expected closing `]` for [frame,think] notation");
3875 if (retval && !parser_next(parser)) {
3879 if (retval && parser->tok != '{') {
3880 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3885 ast_unref(nextthink);
3886 ast_unref(framenum);
3890 has_frame_think = true;
3893 block = ast_block_new(parser_ctx(parser));
3895 parseerror(parser, "failed to allocate block");
3896 if (has_frame_think) {
3897 ast_unref(nextthink);
3898 ast_unref(framenum);
3903 if (has_frame_think) {
3905 ast_expression *self_frame;
3906 ast_expression *self_nextthink;
3907 ast_expression *self_think;
3908 ast_expression *time_plus_1;
3909 ast_store *store_frame;
3910 ast_store *store_nextthink;
3911 ast_store *store_think;
3913 ctx = parser_ctx(parser);
3914 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3915 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3916 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3918 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3919 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3921 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3922 if (self_frame) ast_delete(self_frame);
3923 if (self_nextthink) ast_delete(self_nextthink);
3924 if (self_think) ast_delete(self_think);
3925 if (time_plus_1) ast_delete(time_plus_1);
3931 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3932 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3933 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3936 ast_delete(self_frame);
3939 if (!store_nextthink) {
3940 ast_delete(self_nextthink);
3944 ast_delete(self_think);
3948 if (store_frame) ast_delete(store_frame);
3949 if (store_nextthink) ast_delete(store_nextthink);
3950 if (store_think) ast_delete(store_think);
3953 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3954 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3955 !ast_block_add_expr(block, (ast_expression*)store_think))
3962 parseerror(parser, "failed to generate code for [frame,think]");
3963 ast_unref(nextthink);
3964 ast_unref(framenum);
3970 if (var->hasvalue) {
3971 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3972 ast_block_delete(block);
3976 func = ast_function_new(ast_ctx(var), var->name, var);
3978 parseerror(parser, "failed to allocate function for `%s`", var->name);
3979 ast_block_delete(block);
3982 vec_push(parser->functions, func);
3984 parser_enterblock(parser);
3986 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3988 ast_value *param = var->expression.params[parami];
3991 if (param->expression.vtype != TYPE_VECTOR &&
3992 (param->expression.vtype != TYPE_FIELD ||
3993 param->expression.next->vtype != TYPE_VECTOR))
3998 if (!create_vector_members(param, me)) {
3999 ast_block_delete(block);
4003 for (e = 0; e < 3; ++e) {
4004 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4005 ast_block_collect(block, (ast_expression*)me[e]);
4009 if (var->argcounter) {
4010 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4011 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4015 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4017 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4018 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4019 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4020 varargs->expression.count = 0;
4021 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4022 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4023 ast_delete(varargs);
4024 ast_block_delete(block);
4027 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4028 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4029 ast_delete(varargs);
4030 ast_block_delete(block);
4033 func->varargs = varargs;
4034 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4037 parser->function = func;
4038 if (!parse_block_into(parser, block)) {
4039 ast_block_delete(block);
4043 vec_push(func->blocks, block);
4046 parser->function = old;
4047 if (!parser_leaveblock(parser))
4049 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4050 parseerror(parser, "internal error: local scopes left");
4054 if (parser->tok == ';')
4055 return parser_next(parser);
4056 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4057 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4061 (void)!parser_leaveblock(parser);
4062 vec_pop(parser->functions);
4063 ast_function_delete(func);
4064 var->constval.vfunc = NULL;
4067 parser->function = old;
4071 static ast_expression *array_accessor_split(
4076 ast_expression *left,
4077 ast_expression *right
4083 lex_ctx_t ctx = ast_ctx(array);
4085 if (!left || !right) {
4086 if (left) ast_delete(left);
4087 if (right) ast_delete(right);
4091 cmp = ast_binary_new(ctx, INSTR_LT,
4092 (ast_expression*)index,
4093 (ast_expression*)fold_constgen_float(parser->fold, middle));
4097 parseerror(parser, "internal error: failed to create comparison for array setter");
4101 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4103 ast_delete(cmp); /* will delete left and right */
4104 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4108 return (ast_expression*)ifthen;
4111 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4113 lex_ctx_t ctx = ast_ctx(array);
4115 if (from+1 == afterend) {
4116 /* set this value */
4119 ast_array_index *subscript;
4121 int assignop = type_store_instr[value->expression.vtype];
4123 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4124 assignop = INSTR_STORE_V;
4126 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4130 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4132 ast_delete(subscript);
4136 block = ast_block_new(ctx);
4142 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4147 ret = ast_return_new(ctx, NULL);
4153 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4158 return (ast_expression*)block;
4160 ast_expression *left, *right;
4161 size_t diff = afterend - from;
4162 size_t middle = from + diff/2;
4163 left = array_setter_node(parser, array, index, value, from, middle);
4164 right = array_setter_node(parser, array, index, value, middle, afterend);
4165 return array_accessor_split(parser, array, index, middle, left, right);
4169 static ast_expression *array_field_setter_node(
4178 lex_ctx_t ctx = ast_ctx(array);
4180 if (from+1 == afterend) {
4181 /* set this value */
4184 ast_entfield *entfield;
4185 ast_array_index *subscript;
4187 int assignop = type_storep_instr[value->expression.vtype];
4189 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4190 assignop = INSTR_STOREP_V;
4192 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4196 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4197 subscript->expression.vtype = TYPE_FIELD;
4199 entfield = ast_entfield_new_force(ctx,
4200 (ast_expression*)entity,
4201 (ast_expression*)subscript,
4202 (ast_expression*)subscript);
4204 ast_delete(subscript);
4208 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4210 ast_delete(entfield);
4214 block = ast_block_new(ctx);
4220 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4225 ret = ast_return_new(ctx, NULL);
4231 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4236 return (ast_expression*)block;
4238 ast_expression *left, *right;
4239 size_t diff = afterend - from;
4240 size_t middle = from + diff/2;
4241 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4242 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4243 return array_accessor_split(parser, array, index, middle, left, right);
4247 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4249 lex_ctx_t ctx = ast_ctx(array);
4251 if (from+1 == afterend) {
4253 ast_array_index *subscript;
4255 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4259 ret = ast_return_new(ctx, (ast_expression*)subscript);
4261 ast_delete(subscript);
4265 return (ast_expression*)ret;
4267 ast_expression *left, *right;
4268 size_t diff = afterend - from;
4269 size_t middle = from + diff/2;
4270 left = array_getter_node(parser, array, index, from, middle);
4271 right = array_getter_node(parser, array, index, middle, afterend);
4272 return array_accessor_split(parser, array, index, middle, left, right);
4276 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4278 ast_function *func = NULL;
4279 ast_value *fval = NULL;
4280 ast_block *body = NULL;
4282 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4284 parseerror(parser, "failed to create accessor function value");
4288 func = ast_function_new(ast_ctx(array), funcname, fval);
4291 parseerror(parser, "failed to create accessor function node");
4295 body = ast_block_new(ast_ctx(array));
4297 parseerror(parser, "failed to create block for array accessor");
4303 vec_push(func->blocks, body);
4306 vec_push(parser->accessors, fval);
4311 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4313 ast_value *index = NULL;
4314 ast_value *value = NULL;
4318 if (!ast_istype(array->expression.next, ast_value)) {
4319 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4323 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4325 func = fval->constval.vfunc;
4326 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4328 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4329 value = ast_value_copy((ast_value*)array->expression.next);
4331 if (!index || !value) {
4332 parseerror(parser, "failed to create locals for array accessor");
4335 (void)!ast_value_set_name(value, "value"); /* not important */
4336 vec_push(fval->expression.params, index);
4337 vec_push(fval->expression.params, value);
4339 array->setter = fval;
4342 if (index) ast_delete(index);
4343 if (value) ast_delete(value);
4349 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4351 ast_expression *root = NULL;
4352 root = array_setter_node(parser, array,
4353 array->setter->expression.params[0],
4354 array->setter->expression.params[1],
4355 0, array->expression.count);
4357 parseerror(parser, "failed to build accessor search tree");
4360 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4367 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4369 if (!parser_create_array_setter_proto(parser, array, funcname))
4371 return parser_create_array_setter_impl(parser, array);
4374 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4376 ast_expression *root = NULL;
4377 ast_value *entity = NULL;
4378 ast_value *index = NULL;
4379 ast_value *value = NULL;
4383 if (!ast_istype(array->expression.next, ast_value)) {
4384 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4388 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4390 func = fval->constval.vfunc;
4391 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4393 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4394 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4395 value = ast_value_copy((ast_value*)array->expression.next);
4396 if (!entity || !index || !value) {
4397 parseerror(parser, "failed to create locals for array accessor");
4400 (void)!ast_value_set_name(value, "value"); /* not important */
4401 vec_push(fval->expression.params, entity);
4402 vec_push(fval->expression.params, index);
4403 vec_push(fval->expression.params, value);
4405 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4407 parseerror(parser, "failed to build accessor search tree");
4411 array->setter = fval;
4412 return ast_block_add_expr(func->blocks[0], root);
4414 if (entity) ast_delete(entity);
4415 if (index) ast_delete(index);
4416 if (value) ast_delete(value);
4417 if (root) ast_delete(root);
4423 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4425 ast_value *index = NULL;
4429 /* NOTE: checking array->expression.next rather than elemtype since
4430 * for fields elemtype is a temporary fieldtype.
4432 if (!ast_istype(array->expression.next, ast_value)) {
4433 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4437 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4439 func = fval->constval.vfunc;
4440 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4442 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4445 parseerror(parser, "failed to create locals for array accessor");
4448 vec_push(fval->expression.params, index);
4450 array->getter = fval;
4453 if (index) ast_delete(index);
4459 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4461 ast_expression *root = NULL;
4463 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4465 parseerror(parser, "failed to build accessor search tree");
4468 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4475 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4477 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4479 return parser_create_array_getter_impl(parser, array);
4482 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4483 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4491 bool variadic = false;
4492 ast_value *varparam = NULL;
4493 char *argcounter = NULL;
4495 ctx = parser_ctx(parser);
4497 /* for the sake of less code we parse-in in this function */
4498 if (!parser_next(parser)) {
4500 parseerror(parser, "expected parameter list");
4506 /* parse variables until we hit a closing paren */
4507 while (parser->tok != ')') {
4509 /* there must be commas between them */
4510 if (parser->tok != ',') {
4511 parseerror(parser, "expected comma or end of parameter list");
4514 if (!parser_next(parser)) {
4515 parseerror(parser, "expected parameter");
4521 if (parser->tok == TOKEN_DOTS) {
4522 /* '...' indicates a varargs function */
4524 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4525 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4528 if (parser->tok == TOKEN_IDENT) {
4529 argcounter = util_strdup(parser_tokval(parser));
4530 if (!parser_next(parser) || parser->tok != ')') {
4531 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4538 /* for anything else just parse a typename */
4539 param = parse_typename(parser, NULL, NULL);
4542 vec_push(params, param);
4543 if (param->expression.vtype >= TYPE_VARIANT) {
4544 char tname[1024]; /* typename is reserved in C++ */
4545 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4546 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4549 /* type-restricted varargs */
4550 if (parser->tok == TOKEN_DOTS) {
4552 varparam = vec_last(params);
4554 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4555 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4558 if (parser->tok == TOKEN_IDENT) {
4559 argcounter = util_strdup(parser_tokval(parser));
4560 if (!parser_next(parser) || parser->tok != ')') {
4561 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4569 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4573 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4574 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4577 if (!parser_next(parser)) {
4578 parseerror(parser, "parse error after typename");
4582 /* now turn 'var' into a function type */
4583 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4584 fval->expression.next = (ast_expression*)var;
4586 fval->expression.flags |= AST_FLAG_VARIADIC;
4589 var->expression.params = params;
4590 var->expression.varparam = (ast_expression*)varparam;
4591 var->argcounter = argcounter;
4600 ast_delete(varparam);
4602 for (i = 0; i < vec_size(params); ++i)
4603 ast_delete(params[i]);
4608 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4610 ast_expression *cexp;
4611 ast_value *cval, *tmp;
4614 ctx = parser_ctx(parser);
4616 if (!parser_next(parser)) {
4618 parseerror(parser, "expected array-size");
4622 if (parser->tok != ']') {
4623 cexp = parse_expression_leave(parser, true, false, false);
4625 if (!cexp || !ast_istype(cexp, ast_value)) {
4629 parseerror(parser, "expected array-size as constant positive integer");
4632 cval = (ast_value*)cexp;
4639 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4640 tmp->expression.next = (ast_expression*)var;
4644 if (cval->expression.vtype == TYPE_INTEGER)
4645 tmp->expression.count = cval->constval.vint;
4646 else if (cval->expression.vtype == TYPE_FLOAT)
4647 tmp->expression.count = cval->constval.vfloat;
4651 parseerror(parser, "array-size must be a positive integer constant");
4657 var->expression.count = -1;
4658 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4661 if (parser->tok != ']') {
4663 parseerror(parser, "expected ']' after array-size");
4666 if (!parser_next(parser)) {
4668 parseerror(parser, "error after parsing array size");
4674 /* Parse a complete typename.
4675 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4676 * but when parsing variables separated by comma
4677 * 'storebase' should point to where the base-type should be kept.
4678 * The base type makes up every bit of type information which comes *before* the
4681 * NOTE: The value must either be named, have a NULL name, or a name starting
4682 * with '<'. In the first case, this will be the actual variable or type
4683 * name, in the other cases it is assumed that the name will appear
4684 * later, and an error is generated otherwise.
4686 * The following will be parsed in its entirety:
4688 * The 'basetype' in this case is 'void()'
4689 * and if there's a comma after it, say:
4691 * then the type-information 'void()' can be stored in 'storebase'
4693 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4695 ast_value *var, *tmp;
4698 const char *name = NULL;
4699 bool isfield = false;
4700 bool wasarray = false;
4701 size_t morefields = 0;
4703 ctx = parser_ctx(parser);
4705 /* types may start with a dot */
4706 if (parser->tok == '.') {
4708 /* if we parsed a dot we need a typename now */
4709 if (!parser_next(parser)) {
4710 parseerror(parser, "expected typename for field definition");
4714 /* Further dots are handled seperately because they won't be part of the
4717 while (parser->tok == '.') {
4719 if (!parser_next(parser)) {
4720 parseerror(parser, "expected typename for field definition");
4725 if (parser->tok == TOKEN_IDENT)
4726 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4727 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4728 parseerror(parser, "expected typename");
4732 /* generate the basic type value */
4733 if (cached_typedef) {
4734 var = ast_value_copy(cached_typedef);
4735 ast_value_set_name(var, "<type(from_def)>");
4737 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4739 for (; morefields; --morefields) {
4740 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4741 tmp->expression.next = (ast_expression*)var;
4745 /* do not yet turn into a field - remember:
4746 * .void() foo; is a field too
4747 * .void()() foo; is a function
4751 if (!parser_next(parser)) {
4753 parseerror(parser, "parse error after typename");
4757 /* an opening paren now starts the parameter-list of a function
4758 * this is where original-QC has parameter lists.
4759 * We allow a single parameter list here.
4760 * Much like fteqcc we don't allow `float()() x`
4762 if (parser->tok == '(') {
4763 var = parse_parameter_list(parser, var);
4768 /* store the base if requested */
4770 *storebase = ast_value_copy(var);
4772 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4773 tmp->expression.next = (ast_expression*)*storebase;
4778 /* there may be a name now */
4779 if (parser->tok == TOKEN_IDENT) {
4780 name = util_strdup(parser_tokval(parser));
4782 if (!parser_next(parser)) {
4785 parseerror(parser, "error after variable or field declaration");
4790 /* now this may be an array */
4791 if (parser->tok == '[') {
4793 var = parse_arraysize(parser, var);
4795 if (name) mem_d(name);
4800 /* This is the point where we can turn it into a field */
4802 /* turn it into a field if desired */
4803 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4804 tmp->expression.next = (ast_expression*)var;
4808 /* now there may be function parens again */
4809 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4810 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4811 if (parser->tok == '(' && wasarray)
4812 parseerror(parser, "arrays as part of a return type is not supported");
4813 while (parser->tok == '(') {
4814 var = parse_parameter_list(parser, var);
4816 if (name) mem_d(name);
4821 /* finally name it */
4823 if (!ast_value_set_name(var, name)) {
4826 parseerror(parser, "internal error: failed to set name");
4829 /* free the name, ast_value_set_name duplicates */
4836 static bool parse_typedef(parser_t *parser)
4838 ast_value *typevar, *oldtype;
4839 ast_expression *old;
4841 typevar = parse_typename(parser, NULL, NULL);
4846 /* while parsing types, the ast_value's get named '<something>' */
4847 if (!typevar->name || typevar->name[0] == '<') {
4848 parseerror(parser, "missing name in typedef");
4849 ast_delete(typevar);
4853 if ( (old = parser_find_var(parser, typevar->name)) ) {
4854 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4855 " -> `%s` has been declared here: %s:%i",
4856 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4857 ast_delete(typevar);
4861 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4862 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4863 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4864 ast_delete(typevar);
4868 vec_push(parser->_typedefs, typevar);
4869 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4871 if (parser->tok != ';') {
4872 parseerror(parser, "expected semicolon after typedef");
4875 if (!parser_next(parser)) {
4876 parseerror(parser, "parse error after typedef");
4883 static const char *cvq_to_str(int cvq) {
4885 case CV_NONE: return "none";
4886 case CV_VAR: return "`var`";
4887 case CV_CONST: return "`const`";
4888 default: return "<INVALID>";
4892 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4895 if (proto->cvq != var->cvq) {
4896 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4897 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4898 parser->tok == '='))
4900 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4901 "`%s` declared with different qualifiers: %s\n"
4902 " -> previous declaration here: %s:%i uses %s",
4903 var->name, cvq_to_str(var->cvq),
4904 ast_ctx(proto).file, ast_ctx(proto).line,
4905 cvq_to_str(proto->cvq));
4908 av = (var ->expression.flags & AST_FLAG_NORETURN);
4909 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4911 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4912 "`%s` declared with different attributes%s\n"
4913 " -> previous declaration here: %s:%i",
4914 var->name, (av ? ": noreturn" : ""),
4915 ast_ctx(proto).file, ast_ctx(proto).line,
4916 (ao ? ": noreturn" : ""));
4921 static bool create_array_accessors(parser_t *parser, ast_value *var)
4924 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4925 if (!parser_create_array_setter(parser, var, name))
4927 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4928 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4933 static bool parse_array(parser_t *parser, ast_value *array)
4936 if (array->initlist) {
4937 parseerror(parser, "array already initialized elsewhere");
4940 if (!parser_next(parser)) {
4941 parseerror(parser, "parse error in array initializer");
4945 while (parser->tok != '}') {
4946 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4949 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4951 parseerror(parser, "initializing element must be a compile time constant");
4954 vec_push(array->initlist, v->constval);
4955 if (v->expression.vtype == TYPE_STRING) {
4956 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4960 if (parser->tok == '}')
4962 if (parser->tok != ',' || !parser_next(parser)) {
4963 parseerror(parser, "expected comma or '}' in element list");
4967 if (!parser_next(parser) || parser->tok != ';') {
4968 parseerror(parser, "expected semicolon after initializer, got %s");
4972 if (!parser_next(parser)) {
4973 parseerror(parser, "parse error after initializer");
4978 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4979 if (array->expression.count != (size_t)-1) {
4980 parseerror(parser, "array `%s' has already been initialized with %u elements",
4981 array->name, (unsigned)array->expression.count);
4983 array->expression.count = vec_size(array->initlist);
4984 if (!create_array_accessors(parser, array))
4990 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)
4994 ast_expression *old;
4998 ast_value *basetype = NULL;
5000 bool isparam = false;
5001 bool isvector = false;
5002 bool cleanvar = true;
5003 bool wasarray = false;
5005 ast_member *me[3] = { NULL, NULL, NULL };
5007 if (!localblock && is_static)
5008 parseerror(parser, "`static` qualifier is not supported in global scope");
5010 /* get the first complete variable */
5011 var = parse_typename(parser, &basetype, cached_typedef);
5014 ast_delete(basetype);
5018 /* while parsing types, the ast_value's get named '<something>' */
5019 if (!var->name || var->name[0] == '<') {
5020 parseerror(parser, "declaration does not declare anything");
5022 ast_delete(basetype);
5030 /* Part 0: finish the type */
5031 if (parser->tok == '(') {
5032 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5033 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5034 var = parse_parameter_list(parser, var);
5040 /* we only allow 1-dimensional arrays */
5041 if (parser->tok == '[') {
5043 var = parse_arraysize(parser, var);
5049 if (parser->tok == '(' && wasarray) {
5050 parseerror(parser, "arrays as part of a return type is not supported");
5051 /* we'll still parse the type completely for now */
5053 /* for functions returning functions */
5054 while (parser->tok == '(') {
5055 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5056 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5057 var = parse_parameter_list(parser, var);
5064 var->cvq = qualifier;
5065 var->expression.flags |= qflags;
5068 * store the vstring back to var for alias and
5069 * deprecation messages.
5071 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5072 var->expression.flags & AST_FLAG_ALIAS)
5073 var->desc = vstring;
5076 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5077 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5078 * is then filled with the previous definition and the parameter-names replaced.
5080 if (!strcmp(var->name, "nil")) {
5081 if (OPTS_FLAG(UNTYPED_NIL)) {
5082 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5083 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5085 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5088 /* Deal with end_sys_ vars */
5090 if (!strcmp(var->name, "end_sys_globals")) {
5092 parser->crc_globals = vec_size(parser->globals);
5095 else if (!strcmp(var->name, "end_sys_fields")) {
5097 parser->crc_fields = vec_size(parser->fields);
5100 if (was_end && var->expression.vtype == TYPE_FIELD) {
5101 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5102 "global '%s' hint should not be a field",
5103 parser_tokval(parser)))
5110 if (!nofields && var->expression.vtype == TYPE_FIELD)
5112 /* deal with field declarations */
5113 old = parser_find_field(parser, var->name);
5115 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5116 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5125 parseerror(parser, "field `%s` already declared here: %s:%i",
5126 var->name, ast_ctx(old).file, ast_ctx(old).line);
5131 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5132 (old = parser_find_global(parser, var->name)))
5134 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5135 parseerror(parser, "field `%s` already declared here: %s:%i",
5136 var->name, ast_ctx(old).file, ast_ctx(old).line);
5143 /* deal with other globals */
5144 old = parser_find_global(parser, var->name);
5145 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5147 /* This is a function which had a prototype */
5148 if (!ast_istype(old, ast_value)) {
5149 parseerror(parser, "internal error: prototype is not an ast_value");
5153 proto = (ast_value*)old;
5154 proto->desc = var->desc;
5155 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5156 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5158 ast_ctx(proto).file, ast_ctx(proto).line);
5162 /* we need the new parameter-names */
5163 for (i = 0; i < vec_size(proto->expression.params); ++i)
5164 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5165 if (!parser_check_qualifiers(parser, var, proto)) {
5172 proto->expression.flags |= var->expression.flags;
5180 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5181 "global `%s` already declared here: %s:%i",
5182 var->name, ast_ctx(old).file, ast_ctx(old).line))
5187 proto = (ast_value*)old;
5188 if (!ast_istype(old, ast_value)) {
5189 parseerror(parser, "internal error: not an ast_value");
5194 if (!parser_check_qualifiers(parser, var, proto)) {
5199 proto->expression.flags |= var->expression.flags;
5203 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5204 (old = parser_find_field(parser, var->name)))
5206 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5207 parseerror(parser, "global `%s` already declared here: %s:%i",
5208 var->name, ast_ctx(old).file, ast_ctx(old).line);
5215 else /* it's not a global */
5217 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5218 if (old && !isparam) {
5219 parseerror(parser, "local `%s` already declared here: %s:%i",
5220 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5224 old = parser_find_local(parser, var->name, 0, &isparam);
5225 if (old && isparam) {
5226 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5227 "local `%s` is shadowing a parameter", var->name))
5229 parseerror(parser, "local `%s` already declared here: %s:%i",
5230 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5234 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5236 if (ast_istype(old, ast_value))
5237 var = (ast_value*)old;
5246 /* in a noref section we simply bump the usecount */
5247 if (noref || parser->noref)
5251 * Create the global/local, and deal with vector types.
5254 if (var->expression.vtype == TYPE_VECTOR)
5256 else if (var->expression.vtype == TYPE_FIELD &&
5257 var->expression.next->vtype == TYPE_VECTOR)
5261 if (!create_vector_members(var, me)) {
5268 /* deal with global variables, fields, functions */
5269 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5270 var->isfield = true;
5271 vec_push(parser->fields, (ast_expression*)var);
5272 util_htset(parser->htfields, var->name, var);
5274 for (i = 0; i < 3; ++i) {
5275 vec_push(parser->fields, (ast_expression*)me[i]);
5276 util_htset(parser->htfields, me[i]->name, me[i]);
5281 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5282 parser_addglobal(parser, var->name, (ast_expression*)var);
5284 for (i = 0; i < 3; ++i) {
5285 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5289 ast_expression *find = parser_find_global(parser, var->desc);
5292 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5296 if (var->expression.vtype != find->vtype) {
5300 ast_type_to_string(find, ty1, sizeof(ty1));
5301 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5303 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5310 * add alias to aliases table and to corrector
5311 * so corrections can apply for aliases as well.
5313 util_htset(parser->aliases, var->name, find);
5316 * add to corrector so corrections can work
5317 * even for aliases too.
5320 vec_last(parser->correct_variables),
5321 &vec_last(parser->correct_variables_score),
5325 /* generate aliases for vector components */
5329 util_asprintf(&buffer[0], "%s_x", var->desc);
5330 util_asprintf(&buffer[1], "%s_y", var->desc);
5331 util_asprintf(&buffer[2], "%s_z", var->desc);
5333 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5334 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5335 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5342 * add to corrector so corrections can work
5343 * even for aliases too.
5346 vec_last(parser->correct_variables),
5347 &vec_last(parser->correct_variables_score),
5351 vec_last(parser->correct_variables),
5352 &vec_last(parser->correct_variables_score),
5356 vec_last(parser->correct_variables),
5357 &vec_last(parser->correct_variables_score),
5365 /* a static adds itself to be generated like any other global
5366 * but is added to the local namespace instead
5368 char *defname = NULL;
5369 size_t prefix_len, ln;
5371 ln = strlen(parser->function->name);
5372 vec_append(defname, ln, parser->function->name);
5374 vec_append(defname, 2, "::");
5375 /* remember the length up to here */
5376 prefix_len = vec_size(defname);
5378 /* Add it to the local scope */
5379 util_htset(vec_last(parser->variables), var->name, (void*)var);
5383 vec_last(parser->correct_variables),
5384 &vec_last(parser->correct_variables_score),
5388 /* now rename the global */
5389 ln = strlen(var->name);
5390 vec_append(defname, ln, var->name);
5391 ast_value_set_name(var, defname);
5393 /* push it to the to-be-generated globals */
5394 vec_push(parser->globals, (ast_expression*)var);
5396 /* same game for the vector members */
5398 for (i = 0; i < 3; ++i) {
5399 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5403 vec_last(parser->correct_variables),
5404 &vec_last(parser->correct_variables_score),
5408 vec_shrinkto(defname, prefix_len);
5409 ln = strlen(me[i]->name);
5410 vec_append(defname, ln, me[i]->name);
5411 ast_member_set_name(me[i], defname);
5413 vec_push(parser->globals, (ast_expression*)me[i]);
5418 vec_push(localblock->locals, var);
5419 parser_addlocal(parser, var->name, (ast_expression*)var);
5421 for (i = 0; i < 3; ++i) {
5422 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5423 ast_block_collect(localblock, (ast_expression*)me[i]);
5429 me[0] = me[1] = me[2] = NULL;
5434 if (var->expression.vtype == TYPE_ARRAY) {
5435 if (var->expression.count != (size_t)-1) {
5436 if (!create_array_accessors(parser, var))
5440 else if (!localblock && !nofields &&
5441 var->expression.vtype == TYPE_FIELD &&
5442 var->expression.next->vtype == TYPE_ARRAY)
5445 ast_expression *telem;
5447 ast_value *array = (ast_value*)var->expression.next;
5449 if (!ast_istype(var->expression.next, ast_value)) {
5450 parseerror(parser, "internal error: field element type must be an ast_value");
5454 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5455 if (!parser_create_array_field_setter(parser, array, name))
5458 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5459 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5460 tfield->expression.next = telem;
5461 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5462 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5470 if (parser->tok == ';') {
5471 ast_delete(basetype);
5472 if (!parser_next(parser)) {
5473 parseerror(parser, "error after variable declaration");
5479 if (parser->tok == ',')
5483 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5486 parseerror(parser, "missing comma or semicolon while parsing variables");
5490 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5491 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5492 "initializing expression turns variable `%s` into a constant in this standard",
5499 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5500 if (parser->tok != '=') {
5501 if (!strcmp(parser_tokval(parser), "break")) {
5502 if (!parser_next(parser)) {
5503 parseerror(parser, "error parsing break definition");
5506 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5508 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5513 if (!parser_next(parser)) {
5514 parseerror(parser, "error parsing initializer");
5518 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5519 parseerror(parser, "expected '=' before function body in this standard");
5522 if (parser->tok == '#') {
5523 ast_function *func = NULL;
5524 ast_value *number = NULL;
5530 parseerror(parser, "cannot declare builtins within functions");
5533 if (var->expression.vtype != TYPE_FUNCTION) {
5534 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5537 if (!parser_next(parser)) {
5538 parseerror(parser, "expected builtin number");
5542 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5543 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5545 parseerror(parser, "builtin number expected");
5548 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5551 parseerror(parser, "builtin number must be a compile time constant");
5554 if (number->expression.vtype == TYPE_INTEGER)
5555 builtin_num = number->constval.vint;
5556 else if (number->expression.vtype == TYPE_FLOAT)
5557 builtin_num = number->constval.vfloat;
5560 parseerror(parser, "builtin number must be an integer constant");
5565 fractional = modff(builtin_num, &integral);
5566 if (builtin_num < 0 || fractional != 0) {
5567 parseerror(parser, "builtin number must be an integer greater than zero");
5571 /* we only want the integral part anyways */
5572 builtin_num = integral;
5573 } else if (parser->tok == TOKEN_INTCONST) {
5574 builtin_num = parser_token(parser)->constval.i;
5576 parseerror(parser, "builtin number must be a compile time constant");
5580 if (var->hasvalue) {
5581 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5582 "builtin `%s` has already been defined\n"
5583 " -> previous declaration here: %s:%i",
5584 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5588 func = ast_function_new(ast_ctx(var), var->name, var);
5590 parseerror(parser, "failed to allocate function for `%s`", var->name);
5593 vec_push(parser->functions, func);
5595 func->builtin = -builtin_num-1;
5598 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5599 ? (parser->tok != ',' && parser->tok != ';')
5600 : (!parser_next(parser)))
5602 parseerror(parser, "expected comma or semicolon");
5604 ast_function_delete(func);
5605 var->constval.vfunc = NULL;
5609 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5612 /* Note that fteqcc and most others don't even *have*
5613 * local arrays, so this is not a high priority.
5615 parseerror(parser, "TODO: initializers for local arrays");
5619 var->hasvalue = true;
5620 if (!parse_array(parser, var))
5623 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5626 parseerror(parser, "cannot declare functions within functions");
5631 ast_ctx(proto) = parser_ctx(parser);
5633 if (!parse_function_body(parser, var))
5635 ast_delete(basetype);
5636 for (i = 0; i < vec_size(parser->gotos); ++i)
5637 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5638 vec_free(parser->gotos);
5639 vec_free(parser->labels);
5642 ast_expression *cexp;
5645 cexp = parse_expression_leave(parser, true, false, false);
5650 cval = (ast_value*)cexp;
5651 if (cval != parser->nil &&
5652 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5655 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5659 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5660 qualifier != CV_VAR)
5662 var->cvq = CV_CONST;
5664 if (cval == parser->nil)
5665 var->expression.flags |= AST_FLAG_INITIALIZED;
5668 var->hasvalue = true;
5669 if (cval->expression.vtype == TYPE_STRING)
5670 var->constval.vstring = parser_strdup(cval->constval.vstring);
5671 else if (cval->expression.vtype == TYPE_FIELD)
5672 var->constval.vfield = cval;
5674 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5680 shunt sy = { NULL, NULL, NULL, NULL };
5683 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5684 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5685 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5686 if (!parser_sy_apply_operator(parser, &sy))
5689 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5690 parseerror(parser, "internal error: leaked operands");
5691 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5702 if (parser->tok == ',') {
5703 if (!parser_next(parser)) {
5704 parseerror(parser, "expected another variable");
5708 if (parser->tok != TOKEN_IDENT) {
5709 parseerror(parser, "expected another variable");
5712 var = ast_value_copy(basetype);
5714 ast_value_set_name(var, parser_tokval(parser));
5715 if (!parser_next(parser)) {
5716 parseerror(parser, "error parsing variable declaration");
5722 if (parser->tok != ';') {
5723 parseerror(parser, "missing semicolon after variables");
5727 if (!parser_next(parser)) {
5728 parseerror(parser, "parse error after variable declaration");
5732 ast_delete(basetype);
5736 if (cleanvar && var)
5738 ast_delete(basetype);
5742 ast_delete(basetype);
5743 if (cleanvar && var)
5745 if (me[0]) ast_member_delete(me[0]);
5746 if (me[1]) ast_member_delete(me[1]);
5747 if (me[2]) ast_member_delete(me[2]);
5751 static bool parser_global_statement(parser_t *parser)
5755 bool is_static = false;
5756 uint32_t qflags = 0;
5757 ast_value *istype = NULL;
5758 char *vstring = NULL;
5760 if (parser->tok == TOKEN_IDENT)
5761 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5763 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5765 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5767 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5769 if (cvq == CV_WRONG)
5771 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5773 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5775 return parse_enum(parser);
5777 else if (parser->tok == TOKEN_KEYWORD)
5779 if (!strcmp(parser_tokval(parser), "typedef")) {
5780 if (!parser_next(parser)) {
5781 parseerror(parser, "expected type definition after 'typedef'");
5784 return parse_typedef(parser);
5786 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5789 else if (parser->tok == '#')
5791 return parse_pragma(parser);
5793 else if (parser->tok == '$')
5795 if (!parser_next(parser)) {
5796 parseerror(parser, "parse error");
5802 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5808 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5810 return util_crc16(old, str, strlen(str));
5813 static void progdefs_crc_file(const char *str)
5815 /* write to progdefs.h here */
5819 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5821 old = progdefs_crc_sum(old, str);
5822 progdefs_crc_file(str);
5826 static void generate_checksum(parser_t *parser, ir_builder *ir)
5828 uint16_t crc = 0xFFFF;
5832 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5833 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5835 progdefs_crc_file("\tint\tpad;\n");
5836 progdefs_crc_file("\tint\tofs_return[3];\n");
5837 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5838 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5839 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5840 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5841 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5842 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5843 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5844 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5846 for (i = 0; i < parser->crc_globals; ++i) {
5847 if (!ast_istype(parser->globals[i], ast_value))
5849 value = (ast_value*)(parser->globals[i]);
5850 switch (value->expression.vtype) {
5851 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5852 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5853 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5854 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5856 crc = progdefs_crc_both(crc, "\tint\t");
5859 crc = progdefs_crc_both(crc, value->name);
5860 crc = progdefs_crc_both(crc, ";\n");
5862 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5863 for (i = 0; i < parser->crc_fields; ++i) {
5864 if (!ast_istype(parser->fields[i], ast_value))
5866 value = (ast_value*)(parser->fields[i]);
5867 switch (value->expression.next->vtype) {
5868 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5869 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5870 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5871 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5873 crc = progdefs_crc_both(crc, "\tint\t");
5876 crc = progdefs_crc_both(crc, value->name);
5877 crc = progdefs_crc_both(crc, ";\n");
5879 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5880 ir->code->crc = crc;
5883 parser_t *parser_create()
5886 lex_ctx_t empty_ctx;
5889 parser = (parser_t*)mem_a(sizeof(parser_t));
5893 memset(parser, 0, sizeof(*parser));
5895 for (i = 0; i < operator_count; ++i) {
5896 if (operators[i].id == opid1('=')) {
5897 parser->assign_op = operators+i;
5901 if (!parser->assign_op) {
5902 printf("internal error: initializing parser: failed to find assign operator\n");
5907 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5908 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5909 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5910 vec_push(parser->_blocktypedefs, 0);
5912 parser->aliases = util_htnew(PARSER_HT_SIZE);
5915 vec_push(parser->correct_variables, correct_trie_new());
5916 vec_push(parser->correct_variables_score, NULL);
5918 empty_ctx.file = "<internal>";
5920 empty_ctx.column = 0;
5921 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5922 parser->nil->cvq = CV_CONST;
5923 if (OPTS_FLAG(UNTYPED_NIL))
5924 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5926 parser->max_param_count = 1;
5928 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5929 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5930 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5932 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5933 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5934 parser->reserved_version->cvq = CV_CONST;
5935 parser->reserved_version->hasvalue = true;
5936 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5937 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5939 parser->reserved_version = NULL;
5942 parser->fold = fold_init (parser);
5943 parser->intrin = intrin_init(parser);
5947 static bool parser_compile(parser_t *parser)
5949 /* initial lexer/parser state */
5950 parser->lex->flags.noops = true;
5952 if (parser_next(parser))
5954 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5956 if (!parser_global_statement(parser)) {
5957 if (parser->tok == TOKEN_EOF)
5958 parseerror(parser, "unexpected end of file");
5959 else if (compile_errors)
5960 parseerror(parser, "there have been errors, bailing out");
5961 lex_close(parser->lex);
5967 parseerror(parser, "parse error");
5968 lex_close(parser->lex);
5973 lex_close(parser->lex);
5976 return !compile_errors;
5979 bool parser_compile_file(parser_t *parser, const char *filename)
5981 parser->lex = lex_open(filename);
5983 con_err("failed to open file \"%s\"\n", filename);
5986 return parser_compile(parser);
5989 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5991 parser->lex = lex_open_string(str, len, name);
5993 con_err("failed to create lexer for string \"%s\"\n", name);
5996 return parser_compile(parser);
5999 static void parser_remove_ast(parser_t *parser)
6002 if (parser->ast_cleaned)
6004 parser->ast_cleaned = true;
6005 for (i = 0; i < vec_size(parser->accessors); ++i) {
6006 ast_delete(parser->accessors[i]->constval.vfunc);
6007 parser->accessors[i]->constval.vfunc = NULL;
6008 ast_delete(parser->accessors[i]);
6010 for (i = 0; i < vec_size(parser->functions); ++i) {
6011 ast_delete(parser->functions[i]);
6013 for (i = 0; i < vec_size(parser->fields); ++i) {
6014 ast_delete(parser->fields[i]);
6016 for (i = 0; i < vec_size(parser->globals); ++i) {
6017 ast_delete(parser->globals[i]);
6019 vec_free(parser->accessors);
6020 vec_free(parser->functions);
6021 vec_free(parser->globals);
6022 vec_free(parser->fields);
6024 for (i = 0; i < vec_size(parser->variables); ++i)
6025 util_htdel(parser->variables[i]);
6026 vec_free(parser->variables);
6027 vec_free(parser->_blocklocals);
6028 vec_free(parser->_locals);
6031 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6032 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6034 vec_free(parser->correct_variables);
6035 vec_free(parser->correct_variables_score);
6037 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6038 ast_delete(parser->_typedefs[i]);
6039 vec_free(parser->_typedefs);
6040 for (i = 0; i < vec_size(parser->typedefs); ++i)
6041 util_htdel(parser->typedefs[i]);
6042 vec_free(parser->typedefs);
6043 vec_free(parser->_blocktypedefs);
6045 vec_free(parser->_block_ctx);
6047 vec_free(parser->labels);
6048 vec_free(parser->gotos);
6049 vec_free(parser->breaks);
6050 vec_free(parser->continues);
6052 ast_value_delete(parser->nil);
6054 ast_value_delete(parser->const_vec[0]);
6055 ast_value_delete(parser->const_vec[1]);
6056 ast_value_delete(parser->const_vec[2]);
6058 if (parser->reserved_version)
6059 ast_value_delete(parser->reserved_version);
6061 util_htdel(parser->aliases);
6062 fold_cleanup(parser->fold);
6063 intrin_cleanup(parser->intrin);
6066 void parser_cleanup(parser_t *parser)
6068 parser_remove_ast(parser);
6072 bool parser_finish(parser_t *parser, const char *output)
6078 if (compile_errors) {
6079 con_out("*** there were compile errors\n");
6083 ir = ir_builder_new("gmqcc_out");
6085 con_out("failed to allocate builder\n");
6089 for (i = 0; i < vec_size(parser->fields); ++i) {
6092 if (!ast_istype(parser->fields[i], ast_value))
6094 field = (ast_value*)parser->fields[i];
6095 hasvalue = field->hasvalue;
6096 field->hasvalue = false;
6097 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6098 con_out("failed to generate field %s\n", field->name);
6099 ir_builder_delete(ir);
6104 ast_expression *subtype;
6105 field->hasvalue = true;
6106 subtype = field->expression.next;
6107 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6108 if (subtype->vtype == TYPE_FIELD)
6109 ifld->fieldtype = subtype->next->vtype;
6110 else if (subtype->vtype == TYPE_FUNCTION)
6111 ifld->outtype = subtype->next->vtype;
6112 (void)!ir_value_set_field(field->ir_v, ifld);
6115 for (i = 0; i < vec_size(parser->globals); ++i) {
6117 if (!ast_istype(parser->globals[i], ast_value))
6119 asvalue = (ast_value*)(parser->globals[i]);
6120 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6121 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6122 "unused global: `%s`", asvalue->name);
6124 if (!ast_global_codegen(asvalue, ir, false)) {
6125 con_out("failed to generate global %s\n", asvalue->name);
6126 ir_builder_delete(ir);
6130 /* Build function vararg accessor ast tree now before generating
6131 * immediates, because the accessors may add new immediates
6133 for (i = 0; i < vec_size(parser->functions); ++i) {
6134 ast_function *f = parser->functions[i];
6136 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6137 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6138 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6139 con_out("failed to generate vararg setter for %s\n", f->name);
6140 ir_builder_delete(ir);
6143 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6144 con_out("failed to generate vararg getter for %s\n", f->name);
6145 ir_builder_delete(ir);
6149 ast_delete(f->varargs);
6154 /* Now we can generate immediates */
6155 if (!fold_generate(parser->fold, ir))
6158 for (i = 0; i < vec_size(parser->globals); ++i) {
6160 if (!ast_istype(parser->globals[i], ast_value))
6162 asvalue = (ast_value*)(parser->globals[i]);
6163 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6165 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6166 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6167 "uninitialized constant: `%s`",
6169 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6170 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6171 "uninitialized global: `%s`",
6174 if (!ast_generate_accessors(asvalue, ir)) {
6175 ir_builder_delete(ir);
6179 for (i = 0; i < vec_size(parser->fields); ++i) {
6181 asvalue = (ast_value*)(parser->fields[i]->next);
6183 if (!ast_istype((ast_expression*)asvalue, ast_value))
6185 if (asvalue->expression.vtype != TYPE_ARRAY)
6187 if (!ast_generate_accessors(asvalue, ir)) {
6188 ir_builder_delete(ir);
6192 if (parser->reserved_version &&
6193 !ast_global_codegen(parser->reserved_version, ir, false))
6195 con_out("failed to generate reserved::version");
6196 ir_builder_delete(ir);
6199 for (i = 0; i < vec_size(parser->functions); ++i) {
6200 ast_function *f = parser->functions[i];
6201 if (!ast_function_codegen(f, ir)) {
6202 con_out("failed to generate function %s\n", f->name);
6203 ir_builder_delete(ir);
6208 generate_checksum(parser, ir);
6210 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6211 ir_builder_dump(ir, con_out);
6212 for (i = 0; i < vec_size(parser->functions); ++i) {
6213 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6214 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6215 ir_builder_delete(ir);
6219 parser_remove_ast(parser);
6221 if (compile_Werrors) {
6222 con_out("*** there were warnings treated as errors\n");
6223 compile_show_werrors();
6228 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6229 ir_builder_dump(ir, con_out);
6231 if (!ir_builder_generate(ir, output)) {
6232 con_out("*** failed to generate output file\n");
6233 ir_builder_delete(ir);
6237 ir_builder_delete(ir);