2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 #define PARSER_HT_LOCALS 2
29 #define PARSER_HT_SIZE 512
30 #define TYPEDEF_HT_SIZE 512
32 static void parser_enterblock(parser_t *parser);
33 static bool parser_leaveblock(parser_t *parser);
34 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
35 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
36 static bool parse_typedef(parser_t *parser);
37 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
38 static ast_block* parse_block(parser_t *parser);
39 static bool parse_block_into(parser_t *parser, ast_block *block);
40 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
41 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
42 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
43 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
44 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
45 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
46 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
48 static void parseerror(parser_t *parser, const char *fmt, ...)
52 vcompile_error(parser->lex->tok.ctx, fmt, ap);
56 /* returns true if it counts as an error */
57 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
62 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
67 /**********************************************************************
71 static bool parser_next(parser_t *parser)
73 /* lex_do kills the previous token */
74 parser->tok = lex_do(parser->lex);
75 if (parser->tok == TOKEN_EOF)
77 if (parser->tok >= TOKEN_ERROR) {
78 parseerror(parser, "lex error");
84 #define parser_tokval(p) ((p)->lex->tok.value)
85 #define parser_token(p) (&((p)->lex->tok))
87 char *parser_strdup(const char *str)
90 /* actually dup empty strings */
91 char *out = (char*)mem_a(1);
95 return util_strdup(str);
98 static ast_expression* parser_find_field(parser_t *parser, const char *name)
100 return ( ast_expression*)util_htget(parser->htfields, name);
103 static ast_expression* parser_find_label(parser_t *parser, const char *name)
106 for(i = 0; i < vec_size(parser->labels); i++)
107 if (!strcmp(parser->labels[i]->name, name))
108 return (ast_expression*)parser->labels[i];
112 ast_expression* parser_find_global(parser_t *parser, const char *name)
114 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
117 return (ast_expression*)util_htget(parser->htglobals, name);
120 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->vtype;
127 for (i = 0; i < vec_size(fun->expression.params); ++i) {
128 if (!strcmp(fun->expression.params[i]->name, name))
129 return (ast_expression*)(fun->expression.params[i]);
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = vec_size(parser->variables); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_var(parser_t *parser, const char *name)
155 v = parser_find_local(parser, name, 0, &dummy);
156 if (!v) v = parser_find_global(parser, name);
160 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
164 hash = util_hthash(parser->typedefs[0], name);
166 for (i = vec_size(parser->typedefs); i > upto;) {
168 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 size_t etype; /* 0 = expression, others are operators */
180 ast_block *block; /* for commas and function calls */
199 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
210 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
214 e.out = (ast_expression*)v;
221 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
223 e.etype = 1 + (op - operators);
232 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
243 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
244 * so we need to rotate it to become ent.(foo[n]).
246 static bool rotate_entfield_array_index_nodes(ast_expression **out)
248 ast_array_index *index, *oldindex;
249 ast_entfield *entfield;
253 ast_expression *entity;
255 lex_ctx_t ctx = ast_ctx(*out);
257 if (!ast_istype(*out, ast_array_index))
259 index = (ast_array_index*)*out;
261 if (!ast_istype(index->array, ast_entfield))
263 entfield = (ast_entfield*)index->array;
265 if (!ast_istype(entfield->field, ast_value))
267 field = (ast_value*)entfield->field;
270 entity = entfield->entity;
274 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
275 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
276 *out = (ast_expression*)entfield;
278 oldindex->array = NULL;
279 oldindex->index = NULL;
280 ast_delete(oldindex);
285 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
287 if (ast_istype(expr, ast_value)) {
288 ast_value *val = (ast_value*)expr;
289 if (val->cvq == CV_CONST) {
290 if (val->name[0] == '#') {
291 compile_error(ctx, "invalid assignment to a literal constant");
295 * To work around quakeworld we must elide the error and make it
298 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
299 compile_error(ctx, "assignment to constant `%s`", val->name);
301 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
308 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
312 ast_expression *out = NULL;
313 ast_expression *exprs[3];
314 ast_block *blocks[3];
315 ast_binstore *asbinstore;
316 size_t i, assignop, addop, subop;
317 qcint_t generated_op = 0;
322 if (!vec_size(sy->ops)) {
323 parseerror(parser, "internal error: missing operator");
327 if (vec_last(sy->ops).isparen) {
328 parseerror(parser, "unmatched parenthesis");
332 op = &operators[vec_last(sy->ops).etype - 1];
333 ctx = vec_last(sy->ops).ctx;
335 if (vec_size(sy->out) < op->operands) {
336 if (op->flags & OP_PREFIX)
337 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
338 else /* this should have errored previously already */
339 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
343 vec_shrinkby(sy->ops, 1);
345 /* op(:?) has no input and no output */
349 vec_shrinkby(sy->out, op->operands);
350 for (i = 0; i < op->operands; ++i) {
351 exprs[i] = sy->out[vec_size(sy->out)+i].out;
352 blocks[i] = sy->out[vec_size(sy->out)+i].block;
354 if (exprs[i]->vtype == TYPE_NOEXPR &&
355 !(i != 0 && op->id == opid2('?',':')) &&
356 !(i == 1 && op->id == opid1('.')))
358 if (ast_istype(exprs[i], ast_label))
359 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
361 compile_error(ast_ctx(exprs[i]), "not an expression");
362 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
366 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
367 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
371 #define NotSameType(T) \
372 (exprs[0]->vtype != exprs[1]->vtype || \
373 exprs[0]->vtype != T)
377 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
381 if (exprs[0]->vtype == TYPE_VECTOR &&
382 exprs[1]->vtype == TYPE_NOEXPR)
384 if (exprs[1] == (ast_expression*)parser->const_vec[0])
385 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
386 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
387 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
388 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
389 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
391 compile_error(ctx, "access to invalid vector component");
395 else if (exprs[0]->vtype == TYPE_ENTITY) {
396 if (exprs[1]->vtype != TYPE_FIELD) {
397 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
400 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
402 else if (exprs[0]->vtype == TYPE_VECTOR) {
403 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
407 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
413 if (exprs[0]->vtype != TYPE_ARRAY &&
414 !(exprs[0]->vtype == TYPE_FIELD &&
415 exprs[0]->next->vtype == TYPE_ARRAY))
417 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
418 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
421 if (exprs[1]->vtype != TYPE_FLOAT) {
422 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
423 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
426 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
427 if (rotate_entfield_array_index_nodes(&out))
430 /* This is not broken in fteqcc anymore */
431 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
432 /* this error doesn't need to make us bail out */
433 (void)!parsewarning(parser, WARN_EXTENSIONS,
434 "accessing array-field members of an entity without parenthesis\n"
435 " -> this is an extension from -std=gmqcc");
442 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
443 vec_push(sy->out, syexp(ctx, exprs[0]));
444 vec_push(sy->out, syexp(ctx, exprs[1]));
445 vec_last(sy->argc)++;
449 if (!ast_block_add_expr(blocks[0], exprs[1]))
452 blocks[0] = ast_block_new(ctx);
453 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
454 !ast_block_add_expr(blocks[0], exprs[1]))
459 ast_block_set_type(blocks[0], exprs[1]);
461 vec_push(sy->out, syblock(ctx, blocks[0]));
468 if (!(out = fold_op(parser->fold, op, exprs))) {
469 switch (exprs[0]->vtype) {
471 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
472 (ast_expression*)parser->fold->imm_float[0],
476 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
477 (ast_expression*)parser->fold->imm_vector[0],
481 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
482 type_name[exprs[0]->vtype]);
489 if (!(out = fold_op(parser->fold, op, exprs))) {
490 switch (exprs[0]->vtype) {
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
495 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
498 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
499 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
501 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
503 /* we don't constant-fold NOT for these types */
505 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
508 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
511 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
512 type_name[exprs[0]->vtype]);
519 if (exprs[0]->vtype != exprs[1]->vtype ||
520 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
522 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
523 type_name[exprs[0]->vtype],
524 type_name[exprs[1]->vtype]);
527 if (!(out = fold_op(parser->fold, op, exprs))) {
528 switch (exprs[0]->vtype) {
530 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
533 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
536 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
537 type_name[exprs[0]->vtype],
538 type_name[exprs[1]->vtype]);
544 if (exprs[0]->vtype != exprs[1]->vtype ||
545 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
547 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
548 type_name[exprs[1]->vtype],
549 type_name[exprs[0]->vtype]);
552 if (!(out = fold_op(parser->fold, op, exprs))) {
553 switch (exprs[0]->vtype) {
555 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
558 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
561 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
562 type_name[exprs[1]->vtype],
563 type_name[exprs[0]->vtype]);
569 if (exprs[0]->vtype != exprs[1]->vtype &&
570 !(exprs[0]->vtype == TYPE_VECTOR &&
571 exprs[1]->vtype == TYPE_FLOAT) &&
572 !(exprs[1]->vtype == TYPE_VECTOR &&
573 exprs[0]->vtype == TYPE_FLOAT)
576 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
577 type_name[exprs[1]->vtype],
578 type_name[exprs[0]->vtype]);
581 if (!(out = fold_op(parser->fold, op, exprs))) {
582 switch (exprs[0]->vtype) {
584 if (exprs[1]->vtype == TYPE_VECTOR)
585 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
587 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
590 if (exprs[1]->vtype == TYPE_FLOAT)
591 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
593 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
596 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
597 type_name[exprs[1]->vtype],
598 type_name[exprs[0]->vtype]);
605 if (exprs[1]->vtype != TYPE_FLOAT) {
606 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
607 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
608 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
611 if (!(out = fold_op(parser->fold, op, exprs))) {
612 if (exprs[0]->vtype == TYPE_FLOAT)
613 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
615 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
616 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
617 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
624 if (NotSameType(TYPE_FLOAT)) {
625 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
626 type_name[exprs[0]->vtype],
627 type_name[exprs[1]->vtype]);
629 } else if (!(out = fold_op(parser->fold, op, exprs))) {
630 /* generate a call to __builtin_mod */
631 ast_expression *mod = intrin_func(parser->intrin, "mod");
632 ast_call *call = NULL;
633 if (!mod) return false; /* can return null for missing floor */
635 call = ast_call_new(parser_ctx(parser), mod);
636 vec_push(call->params, exprs[0]);
637 vec_push(call->params, exprs[1]);
639 out = (ast_expression*)call;
644 compile_error(ctx, "%= is unimplemented");
650 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
651 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
652 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
654 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
655 type_name[exprs[0]->vtype],
656 type_name[exprs[1]->vtype]);
660 if (!(out = fold_op(parser->fold, op, exprs))) {
662 * IF the first expression is float, the following will be too
663 * since scalar ^ vector is not allowed.
665 if (exprs[0]->vtype == TYPE_FLOAT) {
666 out = (ast_expression*)ast_binary_new(ctx,
667 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
671 * The first is a vector: vector is allowed to bitop with vector and
672 * with scalar, branch here for the second operand.
674 if (exprs[1]->vtype == TYPE_VECTOR) {
676 * Bitop all the values of the vector components against the
677 * vectors components in question.
679 out = (ast_expression*)ast_binary_new(ctx,
680 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
683 out = (ast_expression*)ast_binary_new(ctx,
684 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
693 case opid3('<','<','='):
694 case opid3('>','>','='):
695 if(!(out = fold_op(parser->fold, op, exprs))) {
696 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
702 generated_op += 1; /* INSTR_OR */
704 generated_op += INSTR_AND;
705 if (!(out = fold_op(parser->fold, op, exprs))) {
706 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
707 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
708 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
709 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
712 for (i = 0; i < 2; ++i) {
713 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
714 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
716 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
718 exprs[i] = out; out = NULL;
719 if (OPTS_FLAG(PERL_LOGIC)) {
720 /* here we want to keep the right expressions' type */
724 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
725 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
727 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
729 exprs[i] = out; out = NULL;
730 if (OPTS_FLAG(PERL_LOGIC)) {
731 /* here we want to keep the right expressions' type */
736 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
741 if (vec_last(sy->paren) != PAREN_TERNARY2) {
742 compile_error(ctx, "mismatched parenthesis/ternary");
746 if (!ast_compare_type(exprs[1], exprs[2])) {
747 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
748 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
749 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
752 if (!(out = fold_op(parser->fold, op, exprs)))
753 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
756 case opid2('*', '*'):
757 if (NotSameType(TYPE_FLOAT)) {
758 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
759 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
760 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
765 if (!(out = fold_op(parser->fold, op, exprs))) {
766 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
767 vec_push(gencall->params, exprs[0]);
768 vec_push(gencall->params, exprs[1]);
769 out = (ast_expression*)gencall;
773 case opid2('>', '<'):
774 if (NotSameType(TYPE_VECTOR)) {
775 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
776 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
777 compile_error(ctx, "invalid types used in cross product: %s and %s",
782 if (!(out = fold_op(parser->fold, op, exprs))) {
783 out = (ast_expression*)ast_binary_new(
793 case opid3('<','=','>'): /* -1, 0, or 1 */
794 if (NotSameType(TYPE_FLOAT)) {
795 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
796 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
797 compile_error(ctx, "invalid types used in comparision: %s and %s",
803 if (!(out = fold_op(parser->fold, op, exprs))) {
804 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
806 eq->refs = AST_REF_NONE;
809 out = (ast_expression*)ast_ternary_new(ctx,
810 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
812 (ast_expression*)parser->fold->imm_float[2],
815 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
817 (ast_expression*)parser->fold->imm_float[0],
820 (ast_expression*)parser->fold->imm_float[1]
830 generated_op += 1; /* INSTR_GT */
832 generated_op += 1; /* INSTR_LT */
833 case opid2('>', '='):
834 generated_op += 1; /* INSTR_GE */
835 case opid2('<', '='):
836 generated_op += INSTR_LE;
837 if (NotSameType(TYPE_FLOAT)) {
838 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
839 type_name[exprs[0]->vtype],
840 type_name[exprs[1]->vtype]);
843 if (!(out = fold_op(parser->fold, op, exprs)))
844 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
846 case opid2('!', '='):
847 if (exprs[0]->vtype != exprs[1]->vtype) {
848 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
849 type_name[exprs[0]->vtype],
850 type_name[exprs[1]->vtype]);
853 if (!(out = fold_op(parser->fold, op, exprs)))
854 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
856 case opid2('=', '='):
857 if (exprs[0]->vtype != exprs[1]->vtype) {
858 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
859 type_name[exprs[0]->vtype],
860 type_name[exprs[1]->vtype]);
863 if (!(out = fold_op(parser->fold, op, exprs)))
864 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
868 if (ast_istype(exprs[0], ast_entfield)) {
869 ast_expression *field = ((ast_entfield*)exprs[0])->field;
870 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
871 exprs[0]->vtype == TYPE_FIELD &&
872 exprs[0]->next->vtype == TYPE_VECTOR)
874 assignop = type_storep_instr[TYPE_VECTOR];
877 assignop = type_storep_instr[exprs[0]->vtype];
878 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
880 ast_type_to_string(field->next, ty1, sizeof(ty1));
881 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
882 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
883 field->next->vtype == TYPE_FUNCTION &&
884 exprs[1]->vtype == TYPE_FUNCTION)
886 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
887 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
890 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
895 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
896 exprs[0]->vtype == TYPE_FIELD &&
897 exprs[0]->next->vtype == TYPE_VECTOR)
899 assignop = type_store_instr[TYPE_VECTOR];
902 assignop = type_store_instr[exprs[0]->vtype];
905 if (assignop == VINSTR_END) {
906 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
907 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
908 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
910 else if (!ast_compare_type(exprs[0], exprs[1]))
912 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
913 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
914 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
915 exprs[0]->vtype == TYPE_FUNCTION &&
916 exprs[1]->vtype == TYPE_FUNCTION)
918 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
919 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
922 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
925 (void)check_write_to(ctx, exprs[0]);
926 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
928 case opid3('+','+','P'):
929 case opid3('-','-','P'):
931 if (exprs[0]->vtype != TYPE_FLOAT) {
932 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
933 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
936 if (op->id == opid3('+','+','P'))
940 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
941 if (ast_istype(exprs[0], ast_entfield)) {
942 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
944 (ast_expression*)parser->fold->imm_float[1]);
946 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
948 (ast_expression*)parser->fold->imm_float[1]);
951 case opid3('S','+','+'):
952 case opid3('S','-','-'):
954 if (exprs[0]->vtype != TYPE_FLOAT) {
955 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
956 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
959 if (op->id == opid3('S','+','+')) {
966 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
967 if (ast_istype(exprs[0], ast_entfield)) {
968 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
970 (ast_expression*)parser->fold->imm_float[1]);
972 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
974 (ast_expression*)parser->fold->imm_float[1]);
978 out = (ast_expression*)ast_binary_new(ctx, subop,
980 (ast_expression*)parser->fold->imm_float[1]);
984 if (exprs[0]->vtype != exprs[1]->vtype ||
985 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
987 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
988 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
989 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
993 (void)check_write_to(ctx, exprs[0]);
994 if (ast_istype(exprs[0], ast_entfield))
995 assignop = type_storep_instr[exprs[0]->vtype];
997 assignop = type_store_instr[exprs[0]->vtype];
998 switch (exprs[0]->vtype) {
1000 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1001 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1002 exprs[0], exprs[1]);
1005 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1006 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1007 exprs[0], exprs[1]);
1010 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1011 type_name[exprs[0]->vtype],
1012 type_name[exprs[1]->vtype]);
1016 case opid2('*','='):
1017 case opid2('/','='):
1018 if (exprs[1]->vtype != TYPE_FLOAT ||
1019 !(exprs[0]->vtype == TYPE_FLOAT ||
1020 exprs[0]->vtype == TYPE_VECTOR))
1022 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1023 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1024 compile_error(ctx, "invalid types used in expression: %s and %s",
1028 (void)check_write_to(ctx, exprs[0]);
1029 if (ast_istype(exprs[0], ast_entfield))
1030 assignop = type_storep_instr[exprs[0]->vtype];
1032 assignop = type_store_instr[exprs[0]->vtype];
1033 switch (exprs[0]->vtype) {
1035 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1036 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1037 exprs[0], exprs[1]);
1040 if (op->id == opid2('*','=')) {
1041 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1042 exprs[0], exprs[1]);
1044 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1045 (ast_expression*)parser->fold->imm_float[1],
1048 compile_error(ctx, "internal error: failed to generate division");
1051 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1056 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1057 type_name[exprs[0]->vtype],
1058 type_name[exprs[1]->vtype]);
1062 case opid2('&','='):
1063 case opid2('|','='):
1064 case opid2('^','='):
1065 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1066 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1067 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1068 compile_error(ctx, "invalid types used in expression: %s and %s",
1072 (void)check_write_to(ctx, exprs[0]);
1073 if (ast_istype(exprs[0], ast_entfield))
1074 assignop = type_storep_instr[exprs[0]->vtype];
1076 assignop = type_store_instr[exprs[0]->vtype];
1077 if (exprs[0]->vtype == TYPE_FLOAT)
1078 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1079 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1080 exprs[0], exprs[1]);
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1083 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1084 exprs[0], exprs[1]);
1086 case opid3('&','~','='):
1087 /* This is like: a &= ~(b);
1088 * But QC has no bitwise-not, so we implement it as
1091 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1092 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1094 compile_error(ctx, "invalid types used in expression: %s and %s",
1098 if (ast_istype(exprs[0], ast_entfield))
1099 assignop = type_storep_instr[exprs[0]->vtype];
1101 assignop = type_store_instr[exprs[0]->vtype];
1102 if (exprs[0]->vtype == TYPE_FLOAT)
1103 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1105 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1108 (void)check_write_to(ctx, exprs[0]);
1109 if (exprs[0]->vtype == TYPE_FLOAT)
1110 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1112 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1113 asbinstore->keep_dest = true;
1114 out = (ast_expression*)asbinstore;
1117 case opid2('~', 'P'):
1118 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1119 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1120 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1123 if (!(out = fold_op(parser->fold, op, exprs))) {
1124 if (exprs[0]->vtype == TYPE_FLOAT) {
1125 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1127 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1134 compile_error(ctx, "failed to apply operator %s", op->op);
1138 vec_push(sy->out, syexp(ctx, out));
1142 static bool parser_close_call(parser_t *parser, shunt *sy)
1144 /* was a function call */
1145 ast_expression *fun;
1146 ast_value *funval = NULL;
1150 size_t paramcount, i;
1153 fid = vec_last(sy->ops).off;
1154 vec_shrinkby(sy->ops, 1);
1156 /* out[fid] is the function
1157 * everything above is parameters...
1159 if (!vec_size(sy->argc)) {
1160 parseerror(parser, "internal error: no argument counter available");
1164 paramcount = vec_last(sy->argc);
1167 if (vec_size(sy->out) < fid) {
1168 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1169 (unsigned long)vec_size(sy->out),
1171 (unsigned long)paramcount);
1176 * TODO handle this at the intrinsic level with an ast_intrinsic
1179 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1181 if (fid+2 != vec_size(sy->out) ||
1182 vec_last(sy->out).block)
1184 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1187 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1188 ast_unref(vec_last(sy->out).out);
1189 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1190 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1191 vec_shrinkby(sy->out, 1);
1196 * Now we need to determine if the function that is being called is
1197 * an intrinsic so we can evaluate if the arguments to it are constant
1198 * and than fruitfully fold them.
1200 #define fold_can_1(X) \
1201 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1202 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1204 if (fid + 1 < vec_size(sy->out))
1207 for (i = 0; i < paramcount; ++i) {
1208 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1215 * All is well which ends well, if we make it into here we can ignore the
1216 * intrinsic call and just evaluate it i.e constant fold it.
1218 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1219 ast_expression **exprs = NULL;
1220 ast_expression *foldval = NULL;
1222 for (i = 0; i < paramcount; i++)
1223 vec_push(exprs, sy->out[fid+1 + i].out);
1225 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1231 * Blub: what sorts of unreffing and resizing of
1232 * sy->out should I be doing here?
1234 sy->out[fid] = syexp(foldval->node.context, foldval);
1235 vec_shrinkby(sy->out, 1);
1242 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1247 if (fid+1 + paramcount != vec_size(sy->out)) {
1248 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1249 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1253 for (i = 0; i < paramcount; ++i)
1254 vec_push(call->params, sy->out[fid+1 + i].out);
1255 vec_shrinkby(sy->out, paramcount);
1256 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1257 if (parser->max_param_count < paramcount)
1258 parser->max_param_count = paramcount;
1260 if (ast_istype(fun, ast_value)) {
1261 funval = (ast_value*)fun;
1262 if ((fun->flags & AST_FLAG_VARIADIC) &&
1263 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1265 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1269 /* overwrite fid, the function, with a call */
1270 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1272 if (fun->vtype != TYPE_FUNCTION) {
1273 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1278 parseerror(parser, "could not determine function return type");
1281 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1283 if (fun->flags & AST_FLAG_DEPRECATED) {
1285 return !parsewarning(parser, WARN_DEPRECATED,
1286 "call to function (which is marked deprecated)\n",
1287 "-> it has been declared here: %s:%i",
1288 ast_ctx(fun).file, ast_ctx(fun).line);
1291 return !parsewarning(parser, WARN_DEPRECATED,
1292 "call to `%s` (which is marked deprecated)\n"
1293 "-> `%s` declared here: %s:%i",
1294 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1296 return !parsewarning(parser, WARN_DEPRECATED,
1297 "call to `%s` (deprecated: %s)\n"
1298 "-> `%s` declared here: %s:%i",
1299 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1303 if (vec_size(fun->params) != paramcount &&
1304 !((fun->flags & AST_FLAG_VARIADIC) &&
1305 vec_size(fun->params) < paramcount))
1307 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1309 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1310 "too %s parameters for call to %s: expected %i, got %i\n"
1311 " -> `%s` has been declared here: %s:%i",
1312 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1313 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1315 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1316 "too %s parameters for function call: expected %i, got %i\n"
1317 " -> it has been declared here: %s:%i",
1318 fewmany, (int)vec_size(fun->params), (int)paramcount,
1319 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1326 static bool parser_close_paren(parser_t *parser, shunt *sy)
1328 if (!vec_size(sy->ops)) {
1329 parseerror(parser, "unmatched closing paren");
1333 while (vec_size(sy->ops)) {
1334 if (vec_last(sy->ops).isparen) {
1335 if (vec_last(sy->paren) == PAREN_FUNC) {
1337 if (!parser_close_call(parser, sy))
1341 if (vec_last(sy->paren) == PAREN_EXPR) {
1343 if (!vec_size(sy->out)) {
1344 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1345 vec_shrinkby(sy->ops, 1);
1348 vec_shrinkby(sy->ops, 1);
1351 if (vec_last(sy->paren) == PAREN_INDEX) {
1353 /* pop off the parenthesis */
1354 vec_shrinkby(sy->ops, 1);
1355 /* then apply the index operator */
1356 if (!parser_sy_apply_operator(parser, sy))
1360 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1361 vec_last(sy->paren) = PAREN_TERNARY2;
1362 /* pop off the parenthesis */
1363 vec_shrinkby(sy->ops, 1);
1366 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1369 if (!parser_sy_apply_operator(parser, sy))
1375 static void parser_reclassify_token(parser_t *parser)
1378 if (parser->tok >= TOKEN_START)
1380 for (i = 0; i < operator_count; ++i) {
1381 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1382 parser->tok = TOKEN_OPERATOR;
1388 static ast_expression* parse_vararg_do(parser_t *parser)
1390 ast_expression *idx, *out;
1392 ast_value *funtype = parser->function->vtype;
1393 lex_ctx_t ctx = parser_ctx(parser);
1395 if (!parser->function->varargs) {
1396 parseerror(parser, "function has no variable argument list");
1400 if (!parser_next(parser) || parser->tok != '(') {
1401 parseerror(parser, "expected parameter index and type in parenthesis");
1404 if (!parser_next(parser)) {
1405 parseerror(parser, "error parsing parameter index");
1409 idx = parse_expression_leave(parser, true, false, false);
1413 if (parser->tok != ',') {
1414 if (parser->tok != ')') {
1416 parseerror(parser, "expected comma after parameter index");
1419 /* vararg piping: ...(start) */
1420 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1424 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1426 parseerror(parser, "expected typename for vararg");
1430 typevar = parse_typename(parser, NULL, NULL);
1436 if (parser->tok != ')') {
1438 ast_delete(typevar);
1439 parseerror(parser, "expected closing paren");
1443 if (funtype->expression.varparam &&
1444 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1448 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1449 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1450 compile_error(ast_ctx(typevar),
1451 "function was declared to take varargs of type `%s`, requested type is: %s",
1455 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1456 ast_type_adopt(out, typevar);
1457 ast_delete(typevar);
1461 static ast_expression* parse_vararg(parser_t *parser)
1463 bool old_noops = parser->lex->flags.noops;
1465 ast_expression *out;
1467 parser->lex->flags.noops = true;
1468 out = parse_vararg_do(parser);
1470 parser->lex->flags.noops = old_noops;
1474 /* not to be exposed */
1475 bool ftepp_predef_exists(const char *name);
1476 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1478 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1479 parser->tok == TOKEN_IDENT &&
1480 !strcmp(parser_tokval(parser), "_"))
1482 /* a translatable string */
1485 parser->lex->flags.noops = true;
1486 if (!parser_next(parser) || parser->tok != '(') {
1487 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1490 parser->lex->flags.noops = false;
1491 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1492 parseerror(parser, "expected a constant string in translatable-string extension");
1495 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1498 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1500 if (!parser_next(parser) || parser->tok != ')') {
1501 parseerror(parser, "expected closing paren after translatable string");
1506 else if (parser->tok == TOKEN_DOTS)
1509 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1510 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1513 va = parse_vararg(parser);
1516 vec_push(sy->out, syexp(parser_ctx(parser), va));
1519 else if (parser->tok == TOKEN_FLOATCONST) {
1520 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1523 vec_push(sy->out, syexp(parser_ctx(parser), val));
1526 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1527 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1530 vec_push(sy->out, syexp(parser_ctx(parser), val));
1533 else if (parser->tok == TOKEN_STRINGCONST) {
1534 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1537 vec_push(sy->out, syexp(parser_ctx(parser), val));
1540 else if (parser->tok == TOKEN_VECTORCONST) {
1541 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1544 vec_push(sy->out, syexp(parser_ctx(parser), val));
1547 else if (parser->tok == TOKEN_IDENT)
1549 const char *ctoken = parser_tokval(parser);
1550 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1551 ast_expression *var;
1552 /* a_vector.{x,y,z} */
1553 if (!vec_size(sy->ops) ||
1554 !vec_last(sy->ops).etype ||
1555 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1557 /* When adding more intrinsics, fix the above condition */
1560 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1562 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1564 var = parser_find_var(parser, parser_tokval(parser));
1566 var = parser_find_field(parser, parser_tokval(parser));
1568 if (!var && with_labels) {
1569 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1571 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1572 var = (ast_expression*)lbl;
1573 vec_push(parser->labels, lbl);
1576 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1577 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1580 * now we try for the real intrinsic hashtable. If the string
1581 * begins with __builtin, we simply skip past it, otherwise we
1582 * use the identifier as is.
1584 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1585 var = intrin_func(parser->intrin, parser_tokval(parser));
1589 char *correct = NULL;
1593 * sometimes people use preprocessing predefs without enabling them
1594 * i've done this thousands of times already myself. Lets check for
1595 * it in the predef table. And diagnose it better :)
1597 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1598 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1603 * TODO: determine the best score for the identifier: be it
1604 * a variable, a field.
1606 * We should also consider adding correction tables for
1607 * other things as well.
1609 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1611 correct_init(&corr);
1613 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1614 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1615 if (strcmp(correct, parser_tokval(parser))) {
1622 correct_free(&corr);
1625 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1630 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1636 if (ast_istype(var, ast_value)) {
1637 ((ast_value*)var)->uses++;
1639 else if (ast_istype(var, ast_member)) {
1640 ast_member *mem = (ast_member*)var;
1641 if (ast_istype(mem->owner, ast_value))
1642 ((ast_value*)(mem->owner))->uses++;
1645 vec_push(sy->out, syexp(parser_ctx(parser), var));
1648 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1652 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1654 ast_expression *expr = NULL;
1657 bool wantop = false;
1658 /* only warn once about an assignment in a truth value because the current code
1659 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1661 bool warn_parenthesis = true;
1663 /* count the parens because an if starts with one, so the
1664 * end of a condition is an unmatched closing paren
1668 memset(&sy, 0, sizeof(sy));
1670 parser->lex->flags.noops = false;
1672 parser_reclassify_token(parser);
1676 if (parser->tok == TOKEN_TYPENAME) {
1677 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1681 if (parser->tok == TOKEN_OPERATOR)
1683 /* classify the operator */
1684 const oper_info *op;
1685 const oper_info *olast = NULL;
1687 for (o = 0; o < operator_count; ++o) {
1688 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1689 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1690 !strcmp(parser_tokval(parser), operators[o].op))
1695 if (o == operator_count) {
1696 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1699 /* found an operator */
1702 /* when declaring variables, a comma starts a new variable */
1703 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1704 /* fixup the token */
1709 /* a colon without a pervious question mark cannot be a ternary */
1710 if (!ternaries && op->id == opid2(':','?')) {
1715 if (op->id == opid1(',')) {
1716 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1717 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1721 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1722 olast = &operators[vec_last(sy.ops).etype-1];
1724 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1725 while (olast && op->prec < olast->prec)
1727 if (!parser_sy_apply_operator(parser, &sy))
1729 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1730 olast = &operators[vec_last(sy.ops).etype-1];
1735 #define IsAssignOp(x) (\
1736 (x) == opid1('=') || \
1737 (x) == opid2('+','=') || \
1738 (x) == opid2('-','=') || \
1739 (x) == opid2('*','=') || \
1740 (x) == opid2('/','=') || \
1741 (x) == opid2('%','=') || \
1742 (x) == opid2('&','=') || \
1743 (x) == opid2('|','=') || \
1744 (x) == opid3('&','~','=') \
1746 if (warn_parenthesis) {
1747 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1748 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1749 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1752 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1753 warn_parenthesis = false;
1756 if (olast && olast->id != op->id) {
1757 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1758 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1760 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1761 warn_parenthesis = false;
1763 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1764 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1766 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1767 warn_parenthesis = false;
1773 (op->prec < olast->prec) ||
1774 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1776 if (!parser_sy_apply_operator(parser, &sy))
1778 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1779 olast = &operators[vec_last(sy.ops).etype-1];
1784 if (op->id == opid1('(')) {
1786 size_t sycount = vec_size(sy.out);
1787 /* we expected an operator, this is the function-call operator */
1788 vec_push(sy.paren, PAREN_FUNC);
1789 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1790 vec_push(sy.argc, 0);
1792 vec_push(sy.paren, PAREN_EXPR);
1793 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1796 } else if (op->id == opid1('[')) {
1798 parseerror(parser, "unexpected array subscript");
1801 vec_push(sy.paren, PAREN_INDEX);
1802 /* push both the operator and the paren, this makes life easier */
1803 vec_push(sy.ops, syop(parser_ctx(parser), op));
1804 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1806 } else if (op->id == opid2('?',':')) {
1807 vec_push(sy.ops, syop(parser_ctx(parser), op));
1808 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1811 vec_push(sy.paren, PAREN_TERNARY1);
1812 } else if (op->id == opid2(':','?')) {
1813 if (!vec_size(sy.paren)) {
1814 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1817 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1818 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1821 if (!parser_close_paren(parser, &sy))
1823 vec_push(sy.ops, syop(parser_ctx(parser), op));
1827 vec_push(sy.ops, syop(parser_ctx(parser), op));
1828 wantop = !!(op->flags & OP_SUFFIX);
1831 else if (parser->tok == ')') {
1832 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1833 if (!parser_sy_apply_operator(parser, &sy))
1836 if (!vec_size(sy.paren))
1839 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1840 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1843 if (!parser_close_paren(parser, &sy))
1846 /* must be a function call without parameters */
1847 if (vec_last(sy.paren) != PAREN_FUNC) {
1848 parseerror(parser, "closing paren in invalid position");
1851 if (!parser_close_paren(parser, &sy))
1856 else if (parser->tok == '(') {
1857 parseerror(parser, "internal error: '(' should be classified as operator");
1860 else if (parser->tok == '[') {
1861 parseerror(parser, "internal error: '[' should be classified as operator");
1864 else if (parser->tok == ']') {
1865 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1866 if (!parser_sy_apply_operator(parser, &sy))
1869 if (!vec_size(sy.paren))
1871 if (vec_last(sy.paren) != PAREN_INDEX) {
1872 parseerror(parser, "mismatched parentheses, unexpected ']'");
1875 if (!parser_close_paren(parser, &sy))
1880 if (!parse_sya_operand(parser, &sy, with_labels))
1883 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1884 vec_last(sy.argc)++;
1889 /* in this case we might want to allow constant string concatenation */
1890 bool concatenated = false;
1891 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1892 ast_expression *lexpr = vec_last(sy.out).out;
1893 if (ast_istype(lexpr, ast_value)) {
1894 ast_value *last = (ast_value*)lexpr;
1895 if (last->isimm == true && last->cvq == CV_CONST &&
1896 last->hasvalue && last->expression.vtype == TYPE_STRING)
1898 char *newstr = NULL;
1899 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1900 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1902 concatenated = true;
1906 if (!concatenated) {
1907 parseerror(parser, "expected operator or end of statement");
1912 if (!parser_next(parser)) {
1915 if (parser->tok == ';' ||
1916 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1917 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1923 while (vec_size(sy.ops)) {
1924 if (!parser_sy_apply_operator(parser, &sy))
1928 parser->lex->flags.noops = true;
1929 if (vec_size(sy.out) != 1) {
1930 parseerror(parser, "expression expected");
1933 expr = sy.out[0].out;
1936 if (vec_size(sy.paren)) {
1937 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1945 parser->lex->flags.noops = true;
1946 for (i = 0; i < vec_size(sy.out); ++i) {
1948 ast_unref(sy.out[i].out);
1957 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1959 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1962 if (parser->tok != ';') {
1963 parseerror(parser, "semicolon expected after expression");
1967 if (!parser_next(parser)) {
1974 static void parser_enterblock(parser_t *parser)
1976 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1977 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1978 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1979 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1980 vec_push(parser->_block_ctx, parser_ctx(parser));
1983 vec_push(parser->correct_variables, correct_trie_new());
1984 vec_push(parser->correct_variables_score, NULL);
1987 static bool parser_leaveblock(parser_t *parser)
1990 size_t locals, typedefs;
1992 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1993 parseerror(parser, "internal error: parser_leaveblock with no block");
1997 util_htdel(vec_last(parser->variables));
1998 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2000 vec_pop(parser->variables);
2001 vec_pop(parser->correct_variables);
2002 vec_pop(parser->correct_variables_score);
2003 if (!vec_size(parser->_blocklocals)) {
2004 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2008 locals = vec_last(parser->_blocklocals);
2009 vec_pop(parser->_blocklocals);
2010 while (vec_size(parser->_locals) != locals) {
2011 ast_expression *e = vec_last(parser->_locals);
2012 ast_value *v = (ast_value*)e;
2013 vec_pop(parser->_locals);
2014 if (ast_istype(e, ast_value) && !v->uses) {
2015 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2020 typedefs = vec_last(parser->_blocktypedefs);
2021 while (vec_size(parser->_typedefs) != typedefs) {
2022 ast_delete(vec_last(parser->_typedefs));
2023 vec_pop(parser->_typedefs);
2025 util_htdel(vec_last(parser->typedefs));
2026 vec_pop(parser->typedefs);
2028 vec_pop(parser->_block_ctx);
2033 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2035 vec_push(parser->_locals, e);
2036 util_htset(vec_last(parser->variables), name, (void*)e);
2040 vec_last(parser->correct_variables),
2041 &vec_last(parser->correct_variables_score),
2046 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2048 vec_push(parser->globals, e);
2049 util_htset(parser->htglobals, name, e);
2053 parser->correct_variables[0],
2054 &parser->correct_variables_score[0],
2059 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2063 ast_expression *prev;
2065 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2067 ast_type_to_string(cond, ty, sizeof(ty));
2068 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2071 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2074 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2077 parseerror(parser, "internal error: failed to process condition");
2082 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2084 /* vector types need to be cast to true booleans */
2085 ast_binary *bin = (ast_binary*)cond;
2086 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2088 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2090 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2093 parseerror(parser, "internal error: failed to process condition");
2100 unary = (ast_unary*)cond;
2101 /* ast_istype dereferences cond, should test here for safety */
2102 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2104 cond = unary->operand;
2105 unary->operand = NULL;
2108 unary = (ast_unary*)cond;
2112 parseerror(parser, "internal error: failed to process condition");
2114 if (ifnot) *_ifnot = !*_ifnot;
2118 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2121 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2124 lex_ctx_t ctx = parser_ctx(parser);
2126 (void)block; /* not touching */
2128 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2129 if (!parser_next(parser)) {
2130 parseerror(parser, "expected condition or 'not'");
2133 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2135 if (!parser_next(parser)) {
2136 parseerror(parser, "expected condition in parenthesis");
2140 if (parser->tok != '(') {
2141 parseerror(parser, "expected 'if' condition in parenthesis");
2144 /* parse into the expression */
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "expected 'if' condition after opening paren");
2149 /* parse the condition */
2150 cond = parse_expression_leave(parser, false, true, false);
2154 if (parser->tok != ')') {
2155 parseerror(parser, "expected closing paren after 'if' condition");
2159 /* parse into the 'then' branch */
2160 if (!parser_next(parser)) {
2161 parseerror(parser, "expected statement for on-true branch of 'if'");
2165 if (!parse_statement_or_block(parser, &ontrue)) {
2170 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2171 /* check for an else */
2172 if (!strcmp(parser_tokval(parser), "else")) {
2173 /* parse into the 'else' branch */
2174 if (!parser_next(parser)) {
2175 parseerror(parser, "expected on-false branch after 'else'");
2180 if (!parse_statement_or_block(parser, &onfalse)) {
2187 cond = process_condition(parser, cond, &ifnot);
2189 if (ontrue) ast_delete(ontrue);
2190 if (onfalse) ast_delete(onfalse);
2195 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2197 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2198 *out = (ast_expression*)ifthen;
2202 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2203 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2208 /* skip the 'while' and get the body */
2209 if (!parser_next(parser)) {
2210 if (OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2213 parseerror(parser, "expected 'while' condition in parenthesis");
2217 if (parser->tok == ':') {
2218 if (!OPTS_FLAG(LOOP_LABELS))
2219 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2220 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2221 parseerror(parser, "expected loop label");
2224 label = util_strdup(parser_tokval(parser));
2225 if (!parser_next(parser)) {
2227 parseerror(parser, "expected 'while' condition in parenthesis");
2232 if (parser->tok != '(') {
2233 parseerror(parser, "expected 'while' condition in parenthesis");
2237 vec_push(parser->breaks, label);
2238 vec_push(parser->continues, label);
2240 rv = parse_while_go(parser, block, out);
2243 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2244 parseerror(parser, "internal error: label stack corrupted");
2250 vec_pop(parser->breaks);
2251 vec_pop(parser->continues);
2256 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2259 ast_expression *cond, *ontrue;
2263 lex_ctx_t ctx = parser_ctx(parser);
2265 (void)block; /* not touching */
2267 /* parse into the expression */
2268 if (!parser_next(parser)) {
2269 parseerror(parser, "expected 'while' condition after opening paren");
2272 /* parse the condition */
2273 cond = parse_expression_leave(parser, false, true, false);
2277 if (parser->tok != ')') {
2278 parseerror(parser, "expected closing paren after 'while' condition");
2282 /* parse into the 'then' branch */
2283 if (!parser_next(parser)) {
2284 parseerror(parser, "expected while-loop body");
2288 if (!parse_statement_or_block(parser, &ontrue)) {
2293 cond = process_condition(parser, cond, &ifnot);
2298 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2299 *out = (ast_expression*)aloop;
2303 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2304 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2309 /* skip the 'do' and get the body */
2310 if (!parser_next(parser)) {
2311 if (OPTS_FLAG(LOOP_LABELS))
2312 parseerror(parser, "expected loop label or body");
2314 parseerror(parser, "expected loop body");
2318 if (parser->tok == ':') {
2319 if (!OPTS_FLAG(LOOP_LABELS))
2320 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2321 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2322 parseerror(parser, "expected loop label");
2325 label = util_strdup(parser_tokval(parser));
2326 if (!parser_next(parser)) {
2328 parseerror(parser, "expected loop body");
2333 vec_push(parser->breaks, label);
2334 vec_push(parser->continues, label);
2336 rv = parse_dowhile_go(parser, block, out);
2339 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2340 parseerror(parser, "internal error: label stack corrupted");
2343 * Test for NULL otherwise ast_delete dereferences null pointer
2351 vec_pop(parser->breaks);
2352 vec_pop(parser->continues);
2357 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2360 ast_expression *cond, *ontrue;
2364 lex_ctx_t ctx = parser_ctx(parser);
2366 (void)block; /* not touching */
2368 if (!parse_statement_or_block(parser, &ontrue))
2371 /* expect the "while" */
2372 if (parser->tok != TOKEN_KEYWORD ||
2373 strcmp(parser_tokval(parser), "while"))
2375 parseerror(parser, "expected 'while' and condition");
2380 /* skip the 'while' and check for opening paren */
2381 if (!parser_next(parser) || parser->tok != '(') {
2382 parseerror(parser, "expected 'while' condition in parenthesis");
2386 /* parse into the expression */
2387 if (!parser_next(parser)) {
2388 parseerror(parser, "expected 'while' condition after opening paren");
2392 /* parse the condition */
2393 cond = parse_expression_leave(parser, false, true, false);
2397 if (parser->tok != ')') {
2398 parseerror(parser, "expected closing paren after 'while' condition");
2404 if (!parser_next(parser) || parser->tok != ';') {
2405 parseerror(parser, "expected semicolon after condition");
2411 if (!parser_next(parser)) {
2412 parseerror(parser, "parse error");
2418 cond = process_condition(parser, cond, &ifnot);
2423 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2424 *out = (ast_expression*)aloop;
2428 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2429 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2434 /* skip the 'for' and check for opening paren */
2435 if (!parser_next(parser)) {
2436 if (OPTS_FLAG(LOOP_LABELS))
2437 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2439 parseerror(parser, "expected 'for' expressions in parenthesis");
2443 if (parser->tok == ':') {
2444 if (!OPTS_FLAG(LOOP_LABELS))
2445 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2446 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2447 parseerror(parser, "expected loop label");
2450 label = util_strdup(parser_tokval(parser));
2451 if (!parser_next(parser)) {
2453 parseerror(parser, "expected 'for' expressions in parenthesis");
2458 if (parser->tok != '(') {
2459 parseerror(parser, "expected 'for' expressions in parenthesis");
2463 vec_push(parser->breaks, label);
2464 vec_push(parser->continues, label);
2466 rv = parse_for_go(parser, block, out);
2469 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2470 parseerror(parser, "internal error: label stack corrupted");
2476 vec_pop(parser->breaks);
2477 vec_pop(parser->continues);
2481 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2484 ast_expression *initexpr, *cond, *increment, *ontrue;
2489 lex_ctx_t ctx = parser_ctx(parser);
2491 parser_enterblock(parser);
2498 /* parse into the expression */
2499 if (!parser_next(parser)) {
2500 parseerror(parser, "expected 'for' initializer after opening paren");
2505 if (parser->tok == TOKEN_IDENT)
2506 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2508 if (typevar || parser->tok == TOKEN_TYPENAME) {
2510 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2511 if (parsewarning(parser, WARN_EXTENSIONS,
2512 "current standard does not allow variable declarations in for-loop initializers"))
2516 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2519 else if (parser->tok != ';')
2521 initexpr = parse_expression_leave(parser, false, false, false);
2526 /* move on to condition */
2527 if (parser->tok != ';') {
2528 parseerror(parser, "expected semicolon after for-loop initializer");
2531 if (!parser_next(parser)) {
2532 parseerror(parser, "expected for-loop condition");
2536 /* parse the condition */
2537 if (parser->tok != ';') {
2538 cond = parse_expression_leave(parser, false, true, false);
2543 /* move on to incrementor */
2544 if (parser->tok != ';') {
2545 parseerror(parser, "expected semicolon after for-loop initializer");
2548 if (!parser_next(parser)) {
2549 parseerror(parser, "expected for-loop condition");
2553 /* parse the incrementor */
2554 if (parser->tok != ')') {
2555 lex_ctx_t condctx = parser_ctx(parser);
2556 increment = parse_expression_leave(parser, false, false, false);
2559 if (!ast_side_effects(increment)) {
2560 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2566 if (parser->tok != ')') {
2567 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2570 /* parse into the 'then' branch */
2571 if (!parser_next(parser)) {
2572 parseerror(parser, "expected for-loop body");
2575 if (!parse_statement_or_block(parser, &ontrue))
2579 cond = process_condition(parser, cond, &ifnot);
2583 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2584 *out = (ast_expression*)aloop;
2586 if (!parser_leaveblock(parser)) {
2592 if (initexpr) ast_unref(initexpr);
2593 if (cond) ast_unref(cond);
2594 if (increment) ast_unref(increment);
2595 (void)!parser_leaveblock(parser);
2599 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2601 ast_expression *exp = NULL;
2602 ast_expression *var = NULL;
2603 ast_return *ret = NULL;
2604 ast_value *retval = parser->function->return_value;
2605 ast_value *expected = parser->function->vtype;
2607 lex_ctx_t ctx = parser_ctx(parser);
2609 (void)block; /* not touching */
2611 if (!parser_next(parser)) {
2612 parseerror(parser, "expected return expression");
2616 /* return assignments */
2617 if (parser->tok == '=') {
2618 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2619 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2623 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2625 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2626 parseerror(parser, "invalid return type: `%s'", ty1);
2630 if (!parser_next(parser)) {
2631 parseerror(parser, "expected return assignment expression");
2635 if (!(exp = parse_expression_leave(parser, false, false, false)))
2638 /* prepare the return value */
2640 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2641 ast_type_adopt(retval, expected->expression.next);
2642 parser->function->return_value = retval;
2645 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2646 char ty1[1024], ty2[1024];
2647 ast_type_to_string(exp, ty1, sizeof(ty1));
2648 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2649 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2652 /* store to 'return' local variable */
2653 var = (ast_expression*)ast_store_new(
2655 type_store_instr[expected->expression.next->vtype],
2656 (ast_expression*)retval, exp);
2663 if (parser->tok != ';')
2664 parseerror(parser, "missing semicolon after return assignment");
2665 else if (!parser_next(parser))
2666 parseerror(parser, "parse error after return assignment");
2672 if (parser->tok != ';') {
2673 exp = parse_expression(parser, false, false);
2677 if (exp->vtype != TYPE_NIL &&
2678 exp->vtype != ((ast_expression*)expected)->next->vtype)
2680 parseerror(parser, "return with invalid expression");
2683 ret = ast_return_new(ctx, exp);
2689 if (!parser_next(parser))
2690 parseerror(parser, "parse error");
2692 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2694 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2696 ret = ast_return_new(ctx, (ast_expression*)retval);
2698 *out = (ast_expression*)ret;
2702 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2705 unsigned int levels = 0;
2706 lex_ctx_t ctx = parser_ctx(parser);
2707 const char **loops = (is_continue ? parser->continues : parser->breaks);
2709 (void)block; /* not touching */
2710 if (!parser_next(parser)) {
2711 parseerror(parser, "expected semicolon or loop label");
2715 if (!vec_size(loops)) {
2717 parseerror(parser, "`continue` can only be used inside loops");
2719 parseerror(parser, "`break` can only be used inside loops or switches");
2722 if (parser->tok == TOKEN_IDENT) {
2723 if (!OPTS_FLAG(LOOP_LABELS))
2724 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2725 i = vec_size(loops);
2727 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2730 parseerror(parser, "no such loop to %s: `%s`",
2731 (is_continue ? "continue" : "break out of"),
2732 parser_tokval(parser));
2737 if (!parser_next(parser)) {
2738 parseerror(parser, "expected semicolon");
2743 if (parser->tok != ';') {
2744 parseerror(parser, "expected semicolon");
2748 if (!parser_next(parser))
2749 parseerror(parser, "parse error");
2751 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2755 /* returns true when it was a variable qualifier, false otherwise!
2756 * on error, cvq is set to CV_WRONG
2758 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2760 bool had_const = false;
2761 bool had_var = false;
2762 bool had_noref = false;
2763 bool had_attrib = false;
2764 bool had_static = false;
2769 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2771 /* parse an attribute */
2772 if (!parser_next(parser)) {
2773 parseerror(parser, "expected attribute after `[[`");
2777 if (!strcmp(parser_tokval(parser), "noreturn")) {
2778 flags |= AST_FLAG_NORETURN;
2779 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2780 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2785 else if (!strcmp(parser_tokval(parser), "noref")) {
2787 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2788 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2793 else if (!strcmp(parser_tokval(parser), "inline")) {
2794 flags |= AST_FLAG_INLINE;
2795 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2796 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2801 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2802 flags |= AST_FLAG_ERASEABLE;
2803 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2804 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2809 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2810 flags |= AST_FLAG_ALIAS;
2813 if (!parser_next(parser)) {
2814 parseerror(parser, "parse error in attribute");
2818 if (parser->tok == '(') {
2819 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2820 parseerror(parser, "`alias` attribute missing parameter");
2824 *message = util_strdup(parser_tokval(parser));
2826 if (!parser_next(parser)) {
2827 parseerror(parser, "parse error in attribute");
2831 if (parser->tok != ')') {
2832 parseerror(parser, "`alias` attribute expected `)` after parameter");
2836 if (!parser_next(parser)) {
2837 parseerror(parser, "parse error in attribute");
2842 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2843 parseerror(parser, "`alias` attribute expected `]]`");
2847 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2848 flags |= AST_FLAG_DEPRECATED;
2851 if (!parser_next(parser)) {
2852 parseerror(parser, "parse error in attribute");
2856 if (parser->tok == '(') {
2857 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2858 parseerror(parser, "`deprecated` attribute missing parameter");
2862 *message = util_strdup(parser_tokval(parser));
2864 if (!parser_next(parser)) {
2865 parseerror(parser, "parse error in attribute");
2869 if(parser->tok != ')') {
2870 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2874 if (!parser_next(parser)) {
2875 parseerror(parser, "parse error in attribute");
2880 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2881 parseerror(parser, "`deprecated` attribute expected `]]`");
2884 if (*message) mem_d(*message);
2892 /* Skip tokens until we hit a ]] */
2893 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2894 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2895 if (!parser_next(parser)) {
2896 parseerror(parser, "error inside attribute");
2903 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2905 else if (!strcmp(parser_tokval(parser), "const"))
2907 else if (!strcmp(parser_tokval(parser), "var"))
2909 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2911 else if (!strcmp(parser_tokval(parser), "noref"))
2913 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2918 if (!parser_next(parser))
2928 *is_static = had_static;
2932 parseerror(parser, "parse error after variable qualifier");
2937 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2938 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2943 /* skip the 'while' and get the body */
2944 if (!parser_next(parser)) {
2945 if (OPTS_FLAG(LOOP_LABELS))
2946 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2948 parseerror(parser, "expected 'switch' operand in parenthesis");
2952 if (parser->tok == ':') {
2953 if (!OPTS_FLAG(LOOP_LABELS))
2954 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2955 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2956 parseerror(parser, "expected loop label");
2959 label = util_strdup(parser_tokval(parser));
2960 if (!parser_next(parser)) {
2962 parseerror(parser, "expected 'switch' operand in parenthesis");
2967 if (parser->tok != '(') {
2968 parseerror(parser, "expected 'switch' operand in parenthesis");
2972 vec_push(parser->breaks, label);
2974 rv = parse_switch_go(parser, block, out);
2977 if (vec_last(parser->breaks) != label) {
2978 parseerror(parser, "internal error: label stack corrupted");
2984 vec_pop(parser->breaks);
2989 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2991 ast_expression *operand;
2994 ast_switch *switchnode;
2995 ast_switch_case swcase;
2998 bool noref, is_static;
2999 uint32_t qflags = 0;
3001 lex_ctx_t ctx = parser_ctx(parser);
3003 (void)block; /* not touching */
3006 /* parse into the expression */
3007 if (!parser_next(parser)) {
3008 parseerror(parser, "expected switch operand");
3011 /* parse the operand */
3012 operand = parse_expression_leave(parser, false, false, false);
3016 switchnode = ast_switch_new(ctx, operand);
3019 if (parser->tok != ')') {
3020 ast_delete(switchnode);
3021 parseerror(parser, "expected closing paren after 'switch' operand");
3025 /* parse over the opening paren */
3026 if (!parser_next(parser) || parser->tok != '{') {
3027 ast_delete(switchnode);
3028 parseerror(parser, "expected list of cases");
3032 if (!parser_next(parser)) {
3033 ast_delete(switchnode);
3034 parseerror(parser, "expected 'case' or 'default'");
3038 /* new block; allow some variables to be declared here */
3039 parser_enterblock(parser);
3042 if (parser->tok == TOKEN_IDENT)
3043 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3044 if (typevar || parser->tok == TOKEN_TYPENAME) {
3045 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3046 ast_delete(switchnode);
3051 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3053 if (cvq == CV_WRONG) {
3054 ast_delete(switchnode);
3057 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3058 ast_delete(switchnode);
3067 while (parser->tok != '}') {
3068 ast_block *caseblock;
3070 if (!strcmp(parser_tokval(parser), "case")) {
3071 if (!parser_next(parser)) {
3072 ast_delete(switchnode);
3073 parseerror(parser, "expected expression for case");
3076 swcase.value = parse_expression_leave(parser, false, false, false);
3077 if (!swcase.value) {
3078 ast_delete(switchnode);
3079 parseerror(parser, "expected expression for case");
3082 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3083 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3084 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3090 else if (!strcmp(parser_tokval(parser), "default")) {
3091 swcase.value = NULL;
3092 if (!parser_next(parser)) {
3093 ast_delete(switchnode);
3094 parseerror(parser, "expected colon");
3099 ast_delete(switchnode);
3100 parseerror(parser, "expected 'case' or 'default'");
3104 /* Now the colon and body */
3105 if (parser->tok != ':') {
3106 if (swcase.value) ast_unref(swcase.value);
3107 ast_delete(switchnode);
3108 parseerror(parser, "expected colon");
3112 if (!parser_next(parser)) {
3113 if (swcase.value) ast_unref(swcase.value);
3114 ast_delete(switchnode);
3115 parseerror(parser, "expected statements or case");
3118 caseblock = ast_block_new(parser_ctx(parser));
3120 if (swcase.value) ast_unref(swcase.value);
3121 ast_delete(switchnode);
3124 swcase.code = (ast_expression*)caseblock;
3125 vec_push(switchnode->cases, swcase);
3127 ast_expression *expr;
3128 if (parser->tok == '}')
3130 if (parser->tok == TOKEN_KEYWORD) {
3131 if (!strcmp(parser_tokval(parser), "case") ||
3132 !strcmp(parser_tokval(parser), "default"))
3137 if (!parse_statement(parser, caseblock, &expr, true)) {
3138 ast_delete(switchnode);
3143 if (!ast_block_add_expr(caseblock, expr)) {
3144 ast_delete(switchnode);
3150 parser_leaveblock(parser);
3153 if (parser->tok != '}') {
3154 ast_delete(switchnode);
3155 parseerror(parser, "expected closing paren of case list");
3158 if (!parser_next(parser)) {
3159 ast_delete(switchnode);
3160 parseerror(parser, "parse error after switch");
3163 *out = (ast_expression*)switchnode;
3167 /* parse computed goto sides */
3168 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3169 ast_expression *on_true;
3170 ast_expression *on_false;
3171 ast_expression *cond;
3176 if (ast_istype(*side, ast_ternary)) {
3177 ast_ternary *tern = (ast_ternary*)*side;
3178 on_true = parse_goto_computed(parser, &tern->on_true);
3179 on_false = parse_goto_computed(parser, &tern->on_false);
3181 if (!on_true || !on_false) {
3182 parseerror(parser, "expected label or expression in ternary");
3183 if (on_true) ast_unref(on_true);
3184 if (on_false) ast_unref(on_false);
3192 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3193 } else if (ast_istype(*side, ast_label)) {
3194 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3195 ast_goto_set_label(gt, ((ast_label*)*side));
3197 return (ast_expression*)gt;
3202 static bool parse_goto(parser_t *parser, ast_expression **out)
3204 ast_goto *gt = NULL;
3205 ast_expression *lbl;
3207 if (!parser_next(parser))
3210 if (parser->tok != TOKEN_IDENT) {
3211 ast_expression *expression;
3213 /* could be an expression i.e computed goto :-) */
3214 if (parser->tok != '(') {
3215 parseerror(parser, "expected label name after `goto`");
3219 /* failed to parse expression for goto */
3220 if (!(expression = parse_expression(parser, false, true)) ||
3221 !(*out = parse_goto_computed(parser, &expression))) {
3222 parseerror(parser, "invalid goto expression");
3224 ast_unref(expression);
3231 /* not computed goto */
3232 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3233 lbl = parser_find_label(parser, gt->name);
3235 if (!ast_istype(lbl, ast_label)) {
3236 parseerror(parser, "internal error: label is not an ast_label");
3240 ast_goto_set_label(gt, (ast_label*)lbl);
3243 vec_push(parser->gotos, gt);
3245 if (!parser_next(parser) || parser->tok != ';') {
3246 parseerror(parser, "semicolon expected after goto label");
3249 if (!parser_next(parser)) {
3250 parseerror(parser, "parse error after goto");
3254 *out = (ast_expression*)gt;
3258 static bool parse_skipwhite(parser_t *parser)
3261 if (!parser_next(parser))
3263 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3264 return parser->tok < TOKEN_ERROR;
3267 static bool parse_eol(parser_t *parser)
3269 if (!parse_skipwhite(parser))
3271 return parser->tok == TOKEN_EOL;
3274 static bool parse_pragma_do(parser_t *parser)
3276 if (!parser_next(parser) ||
3277 parser->tok != TOKEN_IDENT ||
3278 strcmp(parser_tokval(parser), "pragma"))
3280 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3283 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3284 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3288 if (!strcmp(parser_tokval(parser), "noref")) {
3289 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3290 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3293 parser->noref = !!parser_token(parser)->constval.i;
3294 if (!parse_eol(parser)) {
3295 parseerror(parser, "parse error after `noref` pragma");
3301 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3304 while (!parse_eol(parser)) {
3305 parser_next(parser);
3314 static bool parse_pragma(parser_t *parser)
3317 parser->lex->flags.preprocessing = true;
3318 parser->lex->flags.mergelines = true;
3319 rv = parse_pragma_do(parser);
3320 if (parser->tok != TOKEN_EOL) {
3321 parseerror(parser, "junk after pragma");
3324 parser->lex->flags.preprocessing = false;
3325 parser->lex->flags.mergelines = false;
3326 if (!parser_next(parser)) {
3327 parseerror(parser, "parse error after pragma");
3333 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3335 bool noref, is_static;
3337 uint32_t qflags = 0;
3338 ast_value *typevar = NULL;
3339 char *vstring = NULL;
3343 if (parser->tok == TOKEN_IDENT)
3344 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3346 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3348 /* local variable */
3350 parseerror(parser, "cannot declare a variable from here");
3353 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3354 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3357 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3361 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3363 if (cvq == CV_WRONG)
3365 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3367 else if (parser->tok == TOKEN_KEYWORD)
3369 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3374 if (!parser_next(parser)) {
3375 parseerror(parser, "parse error after __builtin_debug_printtype");
3379 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3381 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3382 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3383 if (!parser_next(parser)) {
3384 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3390 if (!parse_statement(parser, block, out, allow_cases))
3393 con_out("__builtin_debug_printtype: got no output node\n");
3396 ast_type_to_string(*out, ty, sizeof(ty));
3397 con_out("__builtin_debug_printtype: `%s`\n", ty);
3402 else if (!strcmp(parser_tokval(parser), "return"))
3404 return parse_return(parser, block, out);
3406 else if (!strcmp(parser_tokval(parser), "if"))
3408 return parse_if(parser, block, out);
3410 else if (!strcmp(parser_tokval(parser), "while"))
3412 return parse_while(parser, block, out);
3414 else if (!strcmp(parser_tokval(parser), "do"))
3416 return parse_dowhile(parser, block, out);
3418 else if (!strcmp(parser_tokval(parser), "for"))
3420 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3421 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3424 return parse_for(parser, block, out);
3426 else if (!strcmp(parser_tokval(parser), "break"))
3428 return parse_break_continue(parser, block, out, false);
3430 else if (!strcmp(parser_tokval(parser), "continue"))
3432 return parse_break_continue(parser, block, out, true);
3434 else if (!strcmp(parser_tokval(parser), "switch"))
3436 return parse_switch(parser, block, out);
3438 else if (!strcmp(parser_tokval(parser), "case") ||
3439 !strcmp(parser_tokval(parser), "default"))
3442 parseerror(parser, "unexpected 'case' label");
3447 else if (!strcmp(parser_tokval(parser), "goto"))
3449 return parse_goto(parser, out);
3451 else if (!strcmp(parser_tokval(parser), "typedef"))
3453 if (!parser_next(parser)) {
3454 parseerror(parser, "expected type definition after 'typedef'");
3457 return parse_typedef(parser);
3459 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3462 else if (parser->tok == '{')
3465 inner = parse_block(parser);
3468 *out = (ast_expression*)inner;
3471 else if (parser->tok == ':')
3475 if (!parser_next(parser)) {
3476 parseerror(parser, "expected label name");
3479 if (parser->tok != TOKEN_IDENT) {
3480 parseerror(parser, "label must be an identifier");
3483 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3485 if (!label->undefined) {
3486 parseerror(parser, "label `%s` already defined", label->name);
3489 label->undefined = false;
3492 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3493 vec_push(parser->labels, label);
3495 *out = (ast_expression*)label;
3496 if (!parser_next(parser)) {
3497 parseerror(parser, "parse error after label");
3500 for (i = 0; i < vec_size(parser->gotos); ++i) {
3501 if (!strcmp(parser->gotos[i]->name, label->name)) {
3502 ast_goto_set_label(parser->gotos[i], label);
3503 vec_remove(parser->gotos, i, 1);
3509 else if (parser->tok == ';')
3511 if (!parser_next(parser)) {
3512 parseerror(parser, "parse error after empty statement");
3519 lex_ctx_t ctx = parser_ctx(parser);
3520 ast_expression *exp = parse_expression(parser, false, false);
3524 if (!ast_side_effects(exp)) {
3525 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3532 static bool parse_enum(parser_t *parser)
3535 bool reverse = false;
3537 ast_value **values = NULL;
3538 ast_value *var = NULL;
3541 ast_expression *old;
3543 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3544 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3548 /* enumeration attributes (can add more later) */
3549 if (parser->tok == ':') {
3550 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3551 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3556 if (!strcmp(parser_tokval(parser), "flag")) {
3560 else if (!strcmp(parser_tokval(parser), "reverse")) {
3564 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3568 if (!parser_next(parser) || parser->tok != '{') {
3569 parseerror(parser, "expected `{` after enum attribute ");
3575 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3576 if (parser->tok == '}') {
3577 /* allow an empty enum */
3580 parseerror(parser, "expected identifier or `}`");
3584 old = parser_find_field(parser, parser_tokval(parser));
3586 old = parser_find_global(parser, parser_tokval(parser));
3588 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3589 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3593 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3594 vec_push(values, var);
3595 var->cvq = CV_CONST;
3596 var->hasvalue = true;
3598 /* for flagged enumerations increment in POTs of TWO */
3599 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3600 parser_addglobal(parser, var->name, (ast_expression*)var);
3602 if (!parser_next(parser)) {
3603 parseerror(parser, "expected `=`, `}` or comma after identifier");
3607 if (parser->tok == ',')
3609 if (parser->tok == '}')
3611 if (parser->tok != '=') {
3612 parseerror(parser, "expected `=`, `}` or comma after identifier");
3616 if (!parser_next(parser)) {
3617 parseerror(parser, "expected expression after `=`");
3621 /* We got a value! */
3622 old = parse_expression_leave(parser, true, false, false);
3623 asvalue = (ast_value*)old;
3624 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3625 compile_error(ast_ctx(var), "constant value or expression expected");
3628 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3630 if (parser->tok == '}')
3632 if (parser->tok != ',') {
3633 parseerror(parser, "expected `}` or comma after expression");
3638 /* patch them all (for reversed attribute) */
3641 for (i = 0; i < vec_size(values); i++)
3642 values[i]->constval.vfloat = vec_size(values) - i - 1;
3645 if (parser->tok != '}') {
3646 parseerror(parser, "internal error: breaking without `}`");
3650 if (!parser_next(parser) || parser->tok != ';') {
3651 parseerror(parser, "expected semicolon after enumeration");
3655 if (!parser_next(parser)) {
3656 parseerror(parser, "parse error after enumeration");
3668 static bool parse_block_into(parser_t *parser, ast_block *block)
3672 parser_enterblock(parser);
3674 if (!parser_next(parser)) { /* skip the '{' */
3675 parseerror(parser, "expected function body");
3679 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3681 ast_expression *expr = NULL;
3682 if (parser->tok == '}')
3685 if (!parse_statement(parser, block, &expr, false)) {
3686 /* parseerror(parser, "parse error"); */
3692 if (!ast_block_add_expr(block, expr)) {
3699 if (parser->tok != '}') {
3702 (void)parser_next(parser);
3706 if (!parser_leaveblock(parser))
3708 return retval && !!block;
3711 static ast_block* parse_block(parser_t *parser)
3714 block = ast_block_new(parser_ctx(parser));
3717 if (!parse_block_into(parser, block)) {
3718 ast_block_delete(block);
3724 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3726 if (parser->tok == '{') {
3727 *out = (ast_expression*)parse_block(parser);
3730 return parse_statement(parser, NULL, out, false);
3733 static bool create_vector_members(ast_value *var, ast_member **me)
3736 size_t len = strlen(var->name);
3738 for (i = 0; i < 3; ++i) {
3739 char *name = (char*)mem_a(len+3);
3740 memcpy(name, var->name, len);
3742 name[len+1] = 'x'+i;
3744 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3753 do { ast_member_delete(me[--i]); } while(i);
3757 static bool parse_function_body(parser_t *parser, ast_value *var)
3759 ast_block *block = NULL;
3764 ast_expression *framenum = NULL;
3765 ast_expression *nextthink = NULL;
3766 /* None of the following have to be deleted */
3767 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3768 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3769 bool has_frame_think;
3773 has_frame_think = false;
3774 old = parser->function;
3776 if (var->expression.flags & AST_FLAG_ALIAS) {
3777 parseerror(parser, "function aliases cannot have bodies");
3781 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3782 parseerror(parser, "gotos/labels leaking");
3786 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3787 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3788 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3794 if (parser->tok == '[') {
3795 /* got a frame definition: [ framenum, nextthink ]
3796 * this translates to:
3797 * self.frame = framenum;
3798 * self.nextthink = time + 0.1;
3799 * self.think = nextthink;
3803 fld_think = parser_find_field(parser, "think");
3804 fld_nextthink = parser_find_field(parser, "nextthink");
3805 fld_frame = parser_find_field(parser, "frame");
3806 if (!fld_think || !fld_nextthink || !fld_frame) {
3807 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3808 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3811 gbl_time = parser_find_global(parser, "time");
3812 gbl_self = parser_find_global(parser, "self");
3813 if (!gbl_time || !gbl_self) {
3814 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3815 parseerror(parser, "please declare the following globals: `time`, `self`");
3819 if (!parser_next(parser))
3822 framenum = parse_expression_leave(parser, true, false, false);
3824 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3827 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3828 ast_unref(framenum);
3829 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3833 if (parser->tok != ',') {
3834 ast_unref(framenum);
3835 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3836 parseerror(parser, "Got a %i\n", parser->tok);
3840 if (!parser_next(parser)) {
3841 ast_unref(framenum);
3845 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3847 /* qc allows the use of not-yet-declared functions here
3848 * - this automatically creates a prototype */
3849 ast_value *thinkfunc;
3850 ast_expression *functype = fld_think->next;
3852 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3853 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3854 ast_unref(framenum);
3855 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3858 ast_type_adopt(thinkfunc, functype);
3860 if (!parser_next(parser)) {
3861 ast_unref(framenum);
3862 ast_delete(thinkfunc);
3866 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3868 nextthink = (ast_expression*)thinkfunc;
3871 nextthink = parse_expression_leave(parser, true, false, false);
3873 ast_unref(framenum);
3874 parseerror(parser, "expected a think-function in [frame,think] notation");
3879 if (!ast_istype(nextthink, ast_value)) {
3880 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3884 if (retval && parser->tok != ']') {
3885 parseerror(parser, "expected closing `]` for [frame,think] notation");
3889 if (retval && !parser_next(parser)) {
3893 if (retval && parser->tok != '{') {
3894 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3899 ast_unref(nextthink);
3900 ast_unref(framenum);
3904 has_frame_think = true;
3907 block = ast_block_new(parser_ctx(parser));
3909 parseerror(parser, "failed to allocate block");
3910 if (has_frame_think) {
3911 ast_unref(nextthink);
3912 ast_unref(framenum);
3917 if (has_frame_think) {
3919 ast_expression *self_frame;
3920 ast_expression *self_nextthink;
3921 ast_expression *self_think;
3922 ast_expression *time_plus_1;
3923 ast_store *store_frame;
3924 ast_store *store_nextthink;
3925 ast_store *store_think;
3927 ctx = parser_ctx(parser);
3928 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3929 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3930 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3932 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3933 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3935 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3936 if (self_frame) ast_delete(self_frame);
3937 if (self_nextthink) ast_delete(self_nextthink);
3938 if (self_think) ast_delete(self_think);
3939 if (time_plus_1) ast_delete(time_plus_1);
3945 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3946 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3947 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3950 ast_delete(self_frame);
3953 if (!store_nextthink) {
3954 ast_delete(self_nextthink);
3958 ast_delete(self_think);
3962 if (store_frame) ast_delete(store_frame);
3963 if (store_nextthink) ast_delete(store_nextthink);
3964 if (store_think) ast_delete(store_think);
3967 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3968 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3969 !ast_block_add_expr(block, (ast_expression*)store_think))
3976 parseerror(parser, "failed to generate code for [frame,think]");
3977 ast_unref(nextthink);
3978 ast_unref(framenum);
3984 if (var->hasvalue) {
3985 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3986 ast_block_delete(block);
3990 func = ast_function_new(ast_ctx(var), var->name, var);
3992 parseerror(parser, "failed to allocate function for `%s`", var->name);
3993 ast_block_delete(block);
3996 vec_push(parser->functions, func);
3998 parser_enterblock(parser);
4000 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4002 ast_value *param = var->expression.params[parami];
4005 if (param->expression.vtype != TYPE_VECTOR &&
4006 (param->expression.vtype != TYPE_FIELD ||
4007 param->expression.next->vtype != TYPE_VECTOR))
4012 if (!create_vector_members(param, me)) {
4013 ast_block_delete(block);
4017 for (e = 0; e < 3; ++e) {
4018 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4019 ast_block_collect(block, (ast_expression*)me[e]);
4023 if (var->argcounter) {
4024 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4025 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4029 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4031 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4032 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4033 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4034 varargs->expression.count = 0;
4035 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4036 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4037 ast_delete(varargs);
4038 ast_block_delete(block);
4041 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4042 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4043 ast_delete(varargs);
4044 ast_block_delete(block);
4047 func->varargs = varargs;
4048 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4051 parser->function = func;
4052 if (!parse_block_into(parser, block)) {
4053 ast_block_delete(block);
4057 vec_push(func->blocks, block);
4060 parser->function = old;
4061 if (!parser_leaveblock(parser))
4063 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4064 parseerror(parser, "internal error: local scopes left");
4068 if (parser->tok == ';')
4069 return parser_next(parser);
4070 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4071 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4075 (void)!parser_leaveblock(parser);
4076 vec_pop(parser->functions);
4077 ast_function_delete(func);
4078 var->constval.vfunc = NULL;
4081 parser->function = old;
4085 static ast_expression *array_accessor_split(
4090 ast_expression *left,
4091 ast_expression *right
4097 lex_ctx_t ctx = ast_ctx(array);
4099 if (!left || !right) {
4100 if (left) ast_delete(left);
4101 if (right) ast_delete(right);
4105 cmp = ast_binary_new(ctx, INSTR_LT,
4106 (ast_expression*)index,
4107 (ast_expression*)fold_constgen_float(parser->fold, middle));
4111 parseerror(parser, "internal error: failed to create comparison for array setter");
4115 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4117 ast_delete(cmp); /* will delete left and right */
4118 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4122 return (ast_expression*)ifthen;
4125 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4127 lex_ctx_t ctx = ast_ctx(array);
4129 if (from+1 == afterend) {
4130 /* set this value */
4133 ast_array_index *subscript;
4135 int assignop = type_store_instr[value->expression.vtype];
4137 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4138 assignop = INSTR_STORE_V;
4140 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4144 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4146 ast_delete(subscript);
4150 block = ast_block_new(ctx);
4156 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4161 ret = ast_return_new(ctx, NULL);
4167 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4172 return (ast_expression*)block;
4174 ast_expression *left, *right;
4175 size_t diff = afterend - from;
4176 size_t middle = from + diff/2;
4177 left = array_setter_node(parser, array, index, value, from, middle);
4178 right = array_setter_node(parser, array, index, value, middle, afterend);
4179 return array_accessor_split(parser, array, index, middle, left, right);
4183 static ast_expression *array_field_setter_node(
4192 lex_ctx_t ctx = ast_ctx(array);
4194 if (from+1 == afterend) {
4195 /* set this value */
4198 ast_entfield *entfield;
4199 ast_array_index *subscript;
4201 int assignop = type_storep_instr[value->expression.vtype];
4203 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4204 assignop = INSTR_STOREP_V;
4206 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4210 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4211 subscript->expression.vtype = TYPE_FIELD;
4213 entfield = ast_entfield_new_force(ctx,
4214 (ast_expression*)entity,
4215 (ast_expression*)subscript,
4216 (ast_expression*)subscript);
4218 ast_delete(subscript);
4222 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4224 ast_delete(entfield);
4228 block = ast_block_new(ctx);
4234 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4239 ret = ast_return_new(ctx, NULL);
4245 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4250 return (ast_expression*)block;
4252 ast_expression *left, *right;
4253 size_t diff = afterend - from;
4254 size_t middle = from + diff/2;
4255 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4256 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4257 return array_accessor_split(parser, array, index, middle, left, right);
4261 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4263 lex_ctx_t ctx = ast_ctx(array);
4265 if (from+1 == afterend) {
4267 ast_array_index *subscript;
4269 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4273 ret = ast_return_new(ctx, (ast_expression*)subscript);
4275 ast_delete(subscript);
4279 return (ast_expression*)ret;
4281 ast_expression *left, *right;
4282 size_t diff = afterend - from;
4283 size_t middle = from + diff/2;
4284 left = array_getter_node(parser, array, index, from, middle);
4285 right = array_getter_node(parser, array, index, middle, afterend);
4286 return array_accessor_split(parser, array, index, middle, left, right);
4290 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4292 ast_function *func = NULL;
4293 ast_value *fval = NULL;
4294 ast_block *body = NULL;
4296 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4298 parseerror(parser, "failed to create accessor function value");
4302 func = ast_function_new(ast_ctx(array), funcname, fval);
4305 parseerror(parser, "failed to create accessor function node");
4309 body = ast_block_new(ast_ctx(array));
4311 parseerror(parser, "failed to create block for array accessor");
4317 vec_push(func->blocks, body);
4320 vec_push(parser->accessors, fval);
4325 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4327 ast_value *index = NULL;
4328 ast_value *value = NULL;
4332 if (!ast_istype(array->expression.next, ast_value)) {
4333 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4337 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4339 func = fval->constval.vfunc;
4340 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4342 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4343 value = ast_value_copy((ast_value*)array->expression.next);
4345 if (!index || !value) {
4346 parseerror(parser, "failed to create locals for array accessor");
4349 (void)!ast_value_set_name(value, "value"); /* not important */
4350 vec_push(fval->expression.params, index);
4351 vec_push(fval->expression.params, value);
4353 array->setter = fval;
4356 if (index) ast_delete(index);
4357 if (value) ast_delete(value);
4363 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4365 ast_expression *root = NULL;
4366 root = array_setter_node(parser, array,
4367 array->setter->expression.params[0],
4368 array->setter->expression.params[1],
4369 0, array->expression.count);
4371 parseerror(parser, "failed to build accessor search tree");
4374 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4381 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4383 if (!parser_create_array_setter_proto(parser, array, funcname))
4385 return parser_create_array_setter_impl(parser, array);
4388 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4390 ast_expression *root = NULL;
4391 ast_value *entity = NULL;
4392 ast_value *index = NULL;
4393 ast_value *value = NULL;
4397 if (!ast_istype(array->expression.next, ast_value)) {
4398 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4402 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4404 func = fval->constval.vfunc;
4405 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4407 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4408 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4409 value = ast_value_copy((ast_value*)array->expression.next);
4410 if (!entity || !index || !value) {
4411 parseerror(parser, "failed to create locals for array accessor");
4414 (void)!ast_value_set_name(value, "value"); /* not important */
4415 vec_push(fval->expression.params, entity);
4416 vec_push(fval->expression.params, index);
4417 vec_push(fval->expression.params, value);
4419 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4421 parseerror(parser, "failed to build accessor search tree");
4425 array->setter = fval;
4426 return ast_block_add_expr(func->blocks[0], root);
4428 if (entity) ast_delete(entity);
4429 if (index) ast_delete(index);
4430 if (value) ast_delete(value);
4431 if (root) ast_delete(root);
4437 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4439 ast_value *index = NULL;
4443 /* NOTE: checking array->expression.next rather than elemtype since
4444 * for fields elemtype is a temporary fieldtype.
4446 if (!ast_istype(array->expression.next, ast_value)) {
4447 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4451 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4453 func = fval->constval.vfunc;
4454 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4456 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4459 parseerror(parser, "failed to create locals for array accessor");
4462 vec_push(fval->expression.params, index);
4464 array->getter = fval;
4467 if (index) ast_delete(index);
4473 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4475 ast_expression *root = NULL;
4477 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4479 parseerror(parser, "failed to build accessor search tree");
4482 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4489 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4491 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4493 return parser_create_array_getter_impl(parser, array);
4496 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4497 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4505 bool variadic = false;
4506 ast_value *varparam = NULL;
4507 char *argcounter = NULL;
4509 ctx = parser_ctx(parser);
4511 /* for the sake of less code we parse-in in this function */
4512 if (!parser_next(parser)) {
4514 parseerror(parser, "expected parameter list");
4520 /* parse variables until we hit a closing paren */
4521 while (parser->tok != ')') {
4523 /* there must be commas between them */
4524 if (parser->tok != ',') {
4525 parseerror(parser, "expected comma or end of parameter list");
4528 if (!parser_next(parser)) {
4529 parseerror(parser, "expected parameter");
4535 if (parser->tok == TOKEN_DOTS) {
4536 /* '...' indicates a varargs function */
4538 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4539 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4542 if (parser->tok == TOKEN_IDENT) {
4543 argcounter = util_strdup(parser_tokval(parser));
4544 if (!parser_next(parser) || parser->tok != ')') {
4545 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4552 /* for anything else just parse a typename */
4553 param = parse_typename(parser, NULL, NULL);
4556 vec_push(params, param);
4557 if (param->expression.vtype >= TYPE_VARIANT) {
4558 char tname[1024]; /* typename is reserved in C++ */
4559 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4560 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4563 /* type-restricted varargs */
4564 if (parser->tok == TOKEN_DOTS) {
4566 varparam = vec_last(params);
4568 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4569 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4572 if (parser->tok == TOKEN_IDENT) {
4573 argcounter = util_strdup(parser_tokval(parser));
4574 if (!parser_next(parser) || parser->tok != ')') {
4575 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4583 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4587 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4588 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4591 if (!parser_next(parser)) {
4592 parseerror(parser, "parse error after typename");
4596 /* now turn 'var' into a function type */
4597 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4598 fval->expression.next = (ast_expression*)var;
4600 fval->expression.flags |= AST_FLAG_VARIADIC;
4603 var->expression.params = params;
4604 var->expression.varparam = (ast_expression*)varparam;
4605 var->argcounter = argcounter;
4614 ast_delete(varparam);
4616 for (i = 0; i < vec_size(params); ++i)
4617 ast_delete(params[i]);
4622 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4624 ast_expression *cexp;
4625 ast_value *cval, *tmp;
4628 ctx = parser_ctx(parser);
4630 if (!parser_next(parser)) {
4632 parseerror(parser, "expected array-size");
4636 if (parser->tok != ']') {
4637 cexp = parse_expression_leave(parser, true, false, false);
4639 if (!cexp || !ast_istype(cexp, ast_value)) {
4643 parseerror(parser, "expected array-size as constant positive integer");
4646 cval = (ast_value*)cexp;
4653 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4654 tmp->expression.next = (ast_expression*)var;
4658 if (cval->expression.vtype == TYPE_INTEGER)
4659 tmp->expression.count = cval->constval.vint;
4660 else if (cval->expression.vtype == TYPE_FLOAT)
4661 tmp->expression.count = cval->constval.vfloat;
4665 parseerror(parser, "array-size must be a positive integer constant");
4671 var->expression.count = -1;
4672 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4675 if (parser->tok != ']') {
4677 parseerror(parser, "expected ']' after array-size");
4680 if (!parser_next(parser)) {
4682 parseerror(parser, "error after parsing array size");
4688 /* Parse a complete typename.
4689 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4690 * but when parsing variables separated by comma
4691 * 'storebase' should point to where the base-type should be kept.
4692 * The base type makes up every bit of type information which comes *before* the
4695 * NOTE: The value must either be named, have a NULL name, or a name starting
4696 * with '<'. In the first case, this will be the actual variable or type
4697 * name, in the other cases it is assumed that the name will appear
4698 * later, and an error is generated otherwise.
4700 * The following will be parsed in its entirety:
4702 * The 'basetype' in this case is 'void()'
4703 * and if there's a comma after it, say:
4705 * then the type-information 'void()' can be stored in 'storebase'
4707 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4709 ast_value *var, *tmp;
4712 const char *name = NULL;
4713 bool isfield = false;
4714 bool wasarray = false;
4715 size_t morefields = 0;
4717 ctx = parser_ctx(parser);
4719 /* types may start with a dot */
4720 if (parser->tok == '.') {
4722 /* if we parsed a dot we need a typename now */
4723 if (!parser_next(parser)) {
4724 parseerror(parser, "expected typename for field definition");
4728 /* Further dots are handled seperately because they won't be part of the
4731 while (parser->tok == '.') {
4733 if (!parser_next(parser)) {
4734 parseerror(parser, "expected typename for field definition");
4739 if (parser->tok == TOKEN_IDENT)
4740 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4741 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4742 parseerror(parser, "expected typename");
4746 /* generate the basic type value */
4747 if (cached_typedef) {
4748 var = ast_value_copy(cached_typedef);
4749 ast_value_set_name(var, "<type(from_def)>");
4751 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4753 for (; morefields; --morefields) {
4754 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4755 tmp->expression.next = (ast_expression*)var;
4759 /* do not yet turn into a field - remember:
4760 * .void() foo; is a field too
4761 * .void()() foo; is a function
4765 if (!parser_next(parser)) {
4767 parseerror(parser, "parse error after typename");
4771 /* an opening paren now starts the parameter-list of a function
4772 * this is where original-QC has parameter lists.
4773 * We allow a single parameter list here.
4774 * Much like fteqcc we don't allow `float()() x`
4776 if (parser->tok == '(') {
4777 var = parse_parameter_list(parser, var);
4782 /* store the base if requested */
4784 *storebase = ast_value_copy(var);
4786 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4787 tmp->expression.next = (ast_expression*)*storebase;
4792 /* there may be a name now */
4793 if (parser->tok == TOKEN_IDENT) {
4794 name = util_strdup(parser_tokval(parser));
4796 if (!parser_next(parser)) {
4799 parseerror(parser, "error after variable or field declaration");
4804 /* now this may be an array */
4805 if (parser->tok == '[') {
4807 var = parse_arraysize(parser, var);
4809 if (name) mem_d(name);
4814 /* This is the point where we can turn it into a field */
4816 /* turn it into a field if desired */
4817 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4818 tmp->expression.next = (ast_expression*)var;
4822 /* now there may be function parens again */
4823 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4824 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4825 if (parser->tok == '(' && wasarray)
4826 parseerror(parser, "arrays as part of a return type is not supported");
4827 while (parser->tok == '(') {
4828 var = parse_parameter_list(parser, var);
4830 if (name) mem_d(name);
4835 /* finally name it */
4837 if (!ast_value_set_name(var, name)) {
4840 parseerror(parser, "internal error: failed to set name");
4843 /* free the name, ast_value_set_name duplicates */
4850 static bool parse_typedef(parser_t *parser)
4852 ast_value *typevar, *oldtype;
4853 ast_expression *old;
4855 typevar = parse_typename(parser, NULL, NULL);
4860 /* while parsing types, the ast_value's get named '<something>' */
4861 if (!typevar->name || typevar->name[0] == '<') {
4862 parseerror(parser, "missing name in typedef");
4863 ast_delete(typevar);
4867 if ( (old = parser_find_var(parser, typevar->name)) ) {
4868 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4869 " -> `%s` has been declared here: %s:%i",
4870 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4871 ast_delete(typevar);
4875 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4876 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4877 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4878 ast_delete(typevar);
4882 vec_push(parser->_typedefs, typevar);
4883 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4885 if (parser->tok != ';') {
4886 parseerror(parser, "expected semicolon after typedef");
4889 if (!parser_next(parser)) {
4890 parseerror(parser, "parse error after typedef");
4897 static const char *cvq_to_str(int cvq) {
4899 case CV_NONE: return "none";
4900 case CV_VAR: return "`var`";
4901 case CV_CONST: return "`const`";
4902 default: return "<INVALID>";
4906 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4909 if (proto->cvq != var->cvq) {
4910 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4911 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4912 parser->tok == '='))
4914 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4915 "`%s` declared with different qualifiers: %s\n"
4916 " -> previous declaration here: %s:%i uses %s",
4917 var->name, cvq_to_str(var->cvq),
4918 ast_ctx(proto).file, ast_ctx(proto).line,
4919 cvq_to_str(proto->cvq));
4922 av = (var ->expression.flags & AST_FLAG_NORETURN);
4923 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4925 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4926 "`%s` declared with different attributes%s\n"
4927 " -> previous declaration here: %s:%i",
4928 var->name, (av ? ": noreturn" : ""),
4929 ast_ctx(proto).file, ast_ctx(proto).line,
4930 (ao ? ": noreturn" : ""));
4935 static bool create_array_accessors(parser_t *parser, ast_value *var)
4938 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4939 if (!parser_create_array_setter(parser, var, name))
4941 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4942 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4947 static bool parse_array(parser_t *parser, ast_value *array)
4950 if (array->initlist) {
4951 parseerror(parser, "array already initialized elsewhere");
4954 if (!parser_next(parser)) {
4955 parseerror(parser, "parse error in array initializer");
4959 while (parser->tok != '}') {
4960 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4963 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4965 parseerror(parser, "initializing element must be a compile time constant");
4968 vec_push(array->initlist, v->constval);
4969 if (v->expression.vtype == TYPE_STRING) {
4970 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4974 if (parser->tok == '}')
4976 if (parser->tok != ',' || !parser_next(parser)) {
4977 parseerror(parser, "expected comma or '}' in element list");
4981 if (!parser_next(parser) || parser->tok != ';') {
4982 parseerror(parser, "expected semicolon after initializer, got %s");
4986 if (!parser_next(parser)) {
4987 parseerror(parser, "parse error after initializer");
4992 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4993 if (array->expression.count != (size_t)-1) {
4994 parseerror(parser, "array `%s' has already been initialized with %u elements",
4995 array->name, (unsigned)array->expression.count);
4997 array->expression.count = vec_size(array->initlist);
4998 if (!create_array_accessors(parser, array))
5004 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)
5008 ast_expression *old;
5012 ast_value *basetype = NULL;
5014 bool isparam = false;
5015 bool isvector = false;
5016 bool cleanvar = true;
5017 bool wasarray = false;
5019 ast_member *me[3] = { NULL, NULL, NULL };
5021 if (!localblock && is_static)
5022 parseerror(parser, "`static` qualifier is not supported in global scope");
5024 /* get the first complete variable */
5025 var = parse_typename(parser, &basetype, cached_typedef);
5028 ast_delete(basetype);
5032 /* while parsing types, the ast_value's get named '<something>' */
5033 if (!var->name || var->name[0] == '<') {
5034 parseerror(parser, "declaration does not declare anything");
5036 ast_delete(basetype);
5044 /* Part 0: finish the type */
5045 if (parser->tok == '(') {
5046 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5047 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5048 var = parse_parameter_list(parser, var);
5054 /* we only allow 1-dimensional arrays */
5055 if (parser->tok == '[') {
5057 var = parse_arraysize(parser, var);
5063 if (parser->tok == '(' && wasarray) {
5064 parseerror(parser, "arrays as part of a return type is not supported");
5065 /* we'll still parse the type completely for now */
5067 /* for functions returning functions */
5068 while (parser->tok == '(') {
5069 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5070 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5071 var = parse_parameter_list(parser, var);
5078 var->cvq = qualifier;
5079 var->expression.flags |= qflags;
5082 * store the vstring back to var for alias and
5083 * deprecation messages.
5085 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5086 var->expression.flags & AST_FLAG_ALIAS)
5087 var->desc = vstring;
5090 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5091 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5092 * is then filled with the previous definition and the parameter-names replaced.
5094 if (!strcmp(var->name, "nil")) {
5095 if (OPTS_FLAG(UNTYPED_NIL)) {
5096 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5097 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5099 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5102 /* Deal with end_sys_ vars */
5104 if (!strcmp(var->name, "end_sys_globals")) {
5106 parser->crc_globals = vec_size(parser->globals);
5109 else if (!strcmp(var->name, "end_sys_fields")) {
5111 parser->crc_fields = vec_size(parser->fields);
5114 if (was_end && var->expression.vtype == TYPE_FIELD) {
5115 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5116 "global '%s' hint should not be a field",
5117 parser_tokval(parser)))
5124 if (!nofields && var->expression.vtype == TYPE_FIELD)
5126 /* deal with field declarations */
5127 old = parser_find_field(parser, var->name);
5129 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5130 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5139 parseerror(parser, "field `%s` already declared here: %s:%i",
5140 var->name, ast_ctx(old).file, ast_ctx(old).line);
5145 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5146 (old = parser_find_global(parser, var->name)))
5148 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5149 parseerror(parser, "field `%s` already declared here: %s:%i",
5150 var->name, ast_ctx(old).file, ast_ctx(old).line);
5157 /* deal with other globals */
5158 old = parser_find_global(parser, var->name);
5159 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5161 /* This is a function which had a prototype */
5162 if (!ast_istype(old, ast_value)) {
5163 parseerror(parser, "internal error: prototype is not an ast_value");
5167 proto = (ast_value*)old;
5168 proto->desc = var->desc;
5169 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5170 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5172 ast_ctx(proto).file, ast_ctx(proto).line);
5176 /* we need the new parameter-names */
5177 for (i = 0; i < vec_size(proto->expression.params); ++i)
5178 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5179 if (!parser_check_qualifiers(parser, var, proto)) {
5186 proto->expression.flags |= var->expression.flags;
5194 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5195 "global `%s` already declared here: %s:%i",
5196 var->name, ast_ctx(old).file, ast_ctx(old).line))
5201 proto = (ast_value*)old;
5202 if (!ast_istype(old, ast_value)) {
5203 parseerror(parser, "internal error: not an ast_value");
5208 if (!parser_check_qualifiers(parser, var, proto)) {
5213 proto->expression.flags |= var->expression.flags;
5217 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5218 (old = parser_find_field(parser, var->name)))
5220 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5221 parseerror(parser, "global `%s` already declared here: %s:%i",
5222 var->name, ast_ctx(old).file, ast_ctx(old).line);
5229 else /* it's not a global */
5231 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5232 if (old && !isparam) {
5233 parseerror(parser, "local `%s` already declared here: %s:%i",
5234 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5238 /* doing this here as the above is just for a single scope */
5239 old = parser_find_local(parser, var->name, 0, &isparam);
5240 if (old && isparam) {
5241 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5242 "local `%s` is shadowing a parameter", var->name))
5244 parseerror(parser, "local `%s` already declared here: %s:%i",
5245 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5249 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5251 if (ast_istype(old, ast_value))
5252 var = proto = (ast_value*)old;
5261 /* in a noref section we simply bump the usecount */
5262 if (noref || parser->noref)
5266 * Create the global/local, and deal with vector types.
5269 if (var->expression.vtype == TYPE_VECTOR)
5271 else if (var->expression.vtype == TYPE_FIELD &&
5272 var->expression.next->vtype == TYPE_VECTOR)
5276 if (!create_vector_members(var, me)) {
5283 /* deal with global variables, fields, functions */
5284 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5285 var->isfield = true;
5286 vec_push(parser->fields, (ast_expression*)var);
5287 util_htset(parser->htfields, var->name, var);
5289 for (i = 0; i < 3; ++i) {
5290 vec_push(parser->fields, (ast_expression*)me[i]);
5291 util_htset(parser->htfields, me[i]->name, me[i]);
5296 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5297 parser_addglobal(parser, var->name, (ast_expression*)var);
5299 for (i = 0; i < 3; ++i) {
5300 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5304 ast_expression *find = parser_find_global(parser, var->desc);
5307 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5311 if (!ast_compare_type((ast_expression*)var, find)) {
5315 ast_type_to_string(find, ty1, sizeof(ty1));
5316 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5318 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5325 * add alias to aliases table and to corrector
5326 * so corrections can apply for aliases as well.
5328 util_htset(parser->aliases, var->name, find);
5331 * add to corrector so corrections can work
5332 * even for aliases too.
5335 vec_last(parser->correct_variables),
5336 &vec_last(parser->correct_variables_score),
5340 /* generate aliases for vector components */
5344 util_asprintf(&buffer[0], "%s_x", var->desc);
5345 util_asprintf(&buffer[1], "%s_y", var->desc);
5346 util_asprintf(&buffer[2], "%s_z", var->desc);
5348 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5349 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5350 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5357 * add to corrector so corrections can work
5358 * even for aliases too.
5361 vec_last(parser->correct_variables),
5362 &vec_last(parser->correct_variables_score),
5366 vec_last(parser->correct_variables),
5367 &vec_last(parser->correct_variables_score),
5371 vec_last(parser->correct_variables),
5372 &vec_last(parser->correct_variables_score),
5380 /* a static adds itself to be generated like any other global
5381 * but is added to the local namespace instead
5383 char *defname = NULL;
5384 size_t prefix_len, ln;
5386 ln = strlen(parser->function->name);
5387 vec_append(defname, ln, parser->function->name);
5389 vec_append(defname, 2, "::");
5390 /* remember the length up to here */
5391 prefix_len = vec_size(defname);
5393 /* Add it to the local scope */
5394 util_htset(vec_last(parser->variables), var->name, (void*)var);
5398 vec_last(parser->correct_variables),
5399 &vec_last(parser->correct_variables_score),
5403 /* now rename the global */
5404 ln = strlen(var->name);
5405 vec_append(defname, ln, var->name);
5406 ast_value_set_name(var, defname);
5408 /* push it to the to-be-generated globals */
5409 vec_push(parser->globals, (ast_expression*)var);
5411 /* same game for the vector members */
5413 for (i = 0; i < 3; ++i) {
5414 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5418 vec_last(parser->correct_variables),
5419 &vec_last(parser->correct_variables_score),
5423 vec_shrinkto(defname, prefix_len);
5424 ln = strlen(me[i]->name);
5425 vec_append(defname, ln, me[i]->name);
5426 ast_member_set_name(me[i], defname);
5428 vec_push(parser->globals, (ast_expression*)me[i]);
5433 vec_push(localblock->locals, var);
5434 parser_addlocal(parser, var->name, (ast_expression*)var);
5436 for (i = 0; i < 3; ++i) {
5437 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5438 ast_block_collect(localblock, (ast_expression*)me[i]);
5444 me[0] = me[1] = me[2] = NULL;
5449 if (var->expression.vtype == TYPE_ARRAY) {
5450 if (var->expression.count != (size_t)-1) {
5451 if (!create_array_accessors(parser, var))
5455 else if (!localblock && !nofields &&
5456 var->expression.vtype == TYPE_FIELD &&
5457 var->expression.next->vtype == TYPE_ARRAY)
5460 ast_expression *telem;
5462 ast_value *array = (ast_value*)var->expression.next;
5464 if (!ast_istype(var->expression.next, ast_value)) {
5465 parseerror(parser, "internal error: field element type must be an ast_value");
5469 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5470 if (!parser_create_array_field_setter(parser, array, name))
5473 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5474 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5475 tfield->expression.next = telem;
5476 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5477 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5485 if (parser->tok == ';') {
5486 ast_delete(basetype);
5487 if (!parser_next(parser)) {
5488 parseerror(parser, "error after variable declaration");
5494 if (parser->tok == ',')
5498 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5501 parseerror(parser, "missing comma or semicolon while parsing variables");
5505 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5506 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5507 "initializing expression turns variable `%s` into a constant in this standard",
5514 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5515 if (parser->tok != '=') {
5516 if (!strcmp(parser_tokval(parser), "break")) {
5517 if (!parser_next(parser)) {
5518 parseerror(parser, "error parsing break definition");
5521 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5523 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5528 if (!parser_next(parser)) {
5529 parseerror(parser, "error parsing initializer");
5533 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5534 parseerror(parser, "expected '=' before function body in this standard");
5537 if (parser->tok == '#') {
5538 ast_function *func = NULL;
5539 ast_value *number = NULL;
5545 parseerror(parser, "cannot declare builtins within functions");
5548 if (var->expression.vtype != TYPE_FUNCTION) {
5549 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5552 if (!parser_next(parser)) {
5553 parseerror(parser, "expected builtin number");
5557 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5558 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5560 parseerror(parser, "builtin number expected");
5563 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5566 parseerror(parser, "builtin number must be a compile time constant");
5569 if (number->expression.vtype == TYPE_INTEGER)
5570 builtin_num = number->constval.vint;
5571 else if (number->expression.vtype == TYPE_FLOAT)
5572 builtin_num = number->constval.vfloat;
5575 parseerror(parser, "builtin number must be an integer constant");
5580 fractional = modff(builtin_num, &integral);
5581 if (builtin_num < 0 || fractional != 0) {
5582 parseerror(parser, "builtin number must be an integer greater than zero");
5586 /* we only want the integral part anyways */
5587 builtin_num = integral;
5588 } else if (parser->tok == TOKEN_INTCONST) {
5589 builtin_num = parser_token(parser)->constval.i;
5591 parseerror(parser, "builtin number must be a compile time constant");
5595 if (var->hasvalue) {
5596 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5597 "builtin `%s` has already been defined\n"
5598 " -> previous declaration here: %s:%i",
5599 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5603 func = ast_function_new(ast_ctx(var), var->name, var);
5605 parseerror(parser, "failed to allocate function for `%s`", var->name);
5608 vec_push(parser->functions, func);
5610 func->builtin = -builtin_num-1;
5613 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5614 ? (parser->tok != ',' && parser->tok != ';')
5615 : (!parser_next(parser)))
5617 parseerror(parser, "expected comma or semicolon");
5619 ast_function_delete(func);
5620 var->constval.vfunc = NULL;
5624 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5627 /* Note that fteqcc and most others don't even *have*
5628 * local arrays, so this is not a high priority.
5630 parseerror(parser, "TODO: initializers for local arrays");
5634 var->hasvalue = true;
5635 if (!parse_array(parser, var))
5638 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5641 parseerror(parser, "cannot declare functions within functions");
5646 ast_ctx(proto) = parser_ctx(parser);
5648 if (!parse_function_body(parser, var))
5650 ast_delete(basetype);
5651 for (i = 0; i < vec_size(parser->gotos); ++i)
5652 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5653 vec_free(parser->gotos);
5654 vec_free(parser->labels);
5657 ast_expression *cexp;
5660 cexp = parse_expression_leave(parser, true, false, false);
5665 cval = (ast_value*)cexp;
5666 if (cval != parser->nil &&
5667 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5670 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5674 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5675 qualifier != CV_VAR)
5677 var->cvq = CV_CONST;
5679 if (cval == parser->nil)
5680 var->expression.flags |= AST_FLAG_INITIALIZED;
5683 var->hasvalue = true;
5684 if (cval->expression.vtype == TYPE_STRING)
5685 var->constval.vstring = parser_strdup(cval->constval.vstring);
5686 else if (cval->expression.vtype == TYPE_FIELD)
5687 var->constval.vfield = cval;
5689 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5695 shunt sy = { NULL, NULL, NULL, NULL };
5698 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5699 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5700 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5701 if (!parser_sy_apply_operator(parser, &sy))
5704 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5705 parseerror(parser, "internal error: leaked operands");
5706 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5717 if (parser->tok == ',') {
5718 if (!parser_next(parser)) {
5719 parseerror(parser, "expected another variable");
5723 if (parser->tok != TOKEN_IDENT) {
5724 parseerror(parser, "expected another variable");
5727 var = ast_value_copy(basetype);
5729 ast_value_set_name(var, parser_tokval(parser));
5730 if (!parser_next(parser)) {
5731 parseerror(parser, "error parsing variable declaration");
5737 if (parser->tok != ';') {
5738 parseerror(parser, "missing semicolon after variables");
5742 if (!parser_next(parser)) {
5743 parseerror(parser, "parse error after variable declaration");
5747 ast_delete(basetype);
5751 if (cleanvar && var)
5753 ast_delete(basetype);
5757 ast_delete(basetype);
5758 if (cleanvar && var)
5760 if (me[0]) ast_member_delete(me[0]);
5761 if (me[1]) ast_member_delete(me[1]);
5762 if (me[2]) ast_member_delete(me[2]);
5766 static bool parser_global_statement(parser_t *parser)
5770 bool is_static = false;
5771 uint32_t qflags = 0;
5772 ast_value *istype = NULL;
5773 char *vstring = NULL;
5775 if (parser->tok == TOKEN_IDENT)
5776 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5778 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5780 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5782 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5784 if (cvq == CV_WRONG)
5786 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5788 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5790 return parse_enum(parser);
5792 else if (parser->tok == TOKEN_KEYWORD)
5794 if (!strcmp(parser_tokval(parser), "typedef")) {
5795 if (!parser_next(parser)) {
5796 parseerror(parser, "expected type definition after 'typedef'");
5799 return parse_typedef(parser);
5801 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5804 else if (parser->tok == '#')
5806 return parse_pragma(parser);
5808 else if (parser->tok == '$')
5810 if (!parser_next(parser)) {
5811 parseerror(parser, "parse error");
5817 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5823 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5825 return util_crc16(old, str, strlen(str));
5828 static void progdefs_crc_file(const char *str)
5830 /* write to progdefs.h here */
5834 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5836 old = progdefs_crc_sum(old, str);
5837 progdefs_crc_file(str);
5841 static void generate_checksum(parser_t *parser, ir_builder *ir)
5843 uint16_t crc = 0xFFFF;
5847 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5848 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5850 progdefs_crc_file("\tint\tpad;\n");
5851 progdefs_crc_file("\tint\tofs_return[3];\n");
5852 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5853 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5854 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5855 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5856 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5857 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5858 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5859 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5861 for (i = 0; i < parser->crc_globals; ++i) {
5862 if (!ast_istype(parser->globals[i], ast_value))
5864 value = (ast_value*)(parser->globals[i]);
5865 switch (value->expression.vtype) {
5866 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5867 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5868 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5869 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5871 crc = progdefs_crc_both(crc, "\tint\t");
5874 crc = progdefs_crc_both(crc, value->name);
5875 crc = progdefs_crc_both(crc, ";\n");
5877 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5878 for (i = 0; i < parser->crc_fields; ++i) {
5879 if (!ast_istype(parser->fields[i], ast_value))
5881 value = (ast_value*)(parser->fields[i]);
5882 switch (value->expression.next->vtype) {
5883 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5884 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5885 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5886 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5888 crc = progdefs_crc_both(crc, "\tint\t");
5891 crc = progdefs_crc_both(crc, value->name);
5892 crc = progdefs_crc_both(crc, ";\n");
5894 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5895 ir->code->crc = crc;
5898 parser_t *parser_create()
5901 lex_ctx_t empty_ctx;
5904 parser = (parser_t*)mem_a(sizeof(parser_t));
5908 memset(parser, 0, sizeof(*parser));
5910 for (i = 0; i < operator_count; ++i) {
5911 if (operators[i].id == opid1('=')) {
5912 parser->assign_op = operators+i;
5916 if (!parser->assign_op) {
5917 printf("internal error: initializing parser: failed to find assign operator\n");
5922 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5923 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5924 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5925 vec_push(parser->_blocktypedefs, 0);
5927 parser->aliases = util_htnew(PARSER_HT_SIZE);
5930 vec_push(parser->correct_variables, correct_trie_new());
5931 vec_push(parser->correct_variables_score, NULL);
5933 empty_ctx.file = "<internal>";
5935 empty_ctx.column = 0;
5936 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5937 parser->nil->cvq = CV_CONST;
5938 if (OPTS_FLAG(UNTYPED_NIL))
5939 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5941 parser->max_param_count = 1;
5943 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5944 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5945 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5947 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5948 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5949 parser->reserved_version->cvq = CV_CONST;
5950 parser->reserved_version->hasvalue = true;
5951 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5952 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5954 parser->reserved_version = NULL;
5957 parser->fold = fold_init (parser);
5958 parser->intrin = intrin_init(parser);
5962 static bool parser_compile(parser_t *parser)
5964 /* initial lexer/parser state */
5965 parser->lex->flags.noops = true;
5967 if (parser_next(parser))
5969 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5971 if (!parser_global_statement(parser)) {
5972 if (parser->tok == TOKEN_EOF)
5973 parseerror(parser, "unexpected end of file");
5974 else if (compile_errors)
5975 parseerror(parser, "there have been errors, bailing out");
5976 lex_close(parser->lex);
5982 parseerror(parser, "parse error");
5983 lex_close(parser->lex);
5988 lex_close(parser->lex);
5991 return !compile_errors;
5994 bool parser_compile_file(parser_t *parser, const char *filename)
5996 parser->lex = lex_open(filename);
5998 con_err("failed to open file \"%s\"\n", filename);
6001 return parser_compile(parser);
6004 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6006 parser->lex = lex_open_string(str, len, name);
6008 con_err("failed to create lexer for string \"%s\"\n", name);
6011 return parser_compile(parser);
6014 static void parser_remove_ast(parser_t *parser)
6017 if (parser->ast_cleaned)
6019 parser->ast_cleaned = true;
6020 for (i = 0; i < vec_size(parser->accessors); ++i) {
6021 ast_delete(parser->accessors[i]->constval.vfunc);
6022 parser->accessors[i]->constval.vfunc = NULL;
6023 ast_delete(parser->accessors[i]);
6025 for (i = 0; i < vec_size(parser->functions); ++i) {
6026 ast_delete(parser->functions[i]);
6028 for (i = 0; i < vec_size(parser->fields); ++i) {
6029 ast_delete(parser->fields[i]);
6031 for (i = 0; i < vec_size(parser->globals); ++i) {
6032 ast_delete(parser->globals[i]);
6034 vec_free(parser->accessors);
6035 vec_free(parser->functions);
6036 vec_free(parser->globals);
6037 vec_free(parser->fields);
6039 for (i = 0; i < vec_size(parser->variables); ++i)
6040 util_htdel(parser->variables[i]);
6041 vec_free(parser->variables);
6042 vec_free(parser->_blocklocals);
6043 vec_free(parser->_locals);
6046 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6047 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6049 vec_free(parser->correct_variables);
6050 vec_free(parser->correct_variables_score);
6052 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6053 ast_delete(parser->_typedefs[i]);
6054 vec_free(parser->_typedefs);
6055 for (i = 0; i < vec_size(parser->typedefs); ++i)
6056 util_htdel(parser->typedefs[i]);
6057 vec_free(parser->typedefs);
6058 vec_free(parser->_blocktypedefs);
6060 vec_free(parser->_block_ctx);
6062 vec_free(parser->labels);
6063 vec_free(parser->gotos);
6064 vec_free(parser->breaks);
6065 vec_free(parser->continues);
6067 ast_value_delete(parser->nil);
6069 ast_value_delete(parser->const_vec[0]);
6070 ast_value_delete(parser->const_vec[1]);
6071 ast_value_delete(parser->const_vec[2]);
6073 if (parser->reserved_version)
6074 ast_value_delete(parser->reserved_version);
6076 util_htdel(parser->aliases);
6077 fold_cleanup(parser->fold);
6078 intrin_cleanup(parser->intrin);
6081 void parser_cleanup(parser_t *parser)
6083 parser_remove_ast(parser);
6087 bool parser_finish(parser_t *parser, const char *output)
6093 if (compile_errors) {
6094 con_out("*** there were compile errors\n");
6098 ir = ir_builder_new("gmqcc_out");
6100 con_out("failed to allocate builder\n");
6104 for (i = 0; i < vec_size(parser->fields); ++i) {
6107 if (!ast_istype(parser->fields[i], ast_value))
6109 field = (ast_value*)parser->fields[i];
6110 hasvalue = field->hasvalue;
6111 field->hasvalue = false;
6112 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6113 con_out("failed to generate field %s\n", field->name);
6114 ir_builder_delete(ir);
6119 ast_expression *subtype;
6120 field->hasvalue = true;
6121 subtype = field->expression.next;
6122 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6123 if (subtype->vtype == TYPE_FIELD)
6124 ifld->fieldtype = subtype->next->vtype;
6125 else if (subtype->vtype == TYPE_FUNCTION)
6126 ifld->outtype = subtype->next->vtype;
6127 (void)!ir_value_set_field(field->ir_v, ifld);
6130 for (i = 0; i < vec_size(parser->globals); ++i) {
6132 if (!ast_istype(parser->globals[i], ast_value))
6134 asvalue = (ast_value*)(parser->globals[i]);
6135 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6136 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6137 "unused global: `%s`", asvalue->name);
6139 if (!ast_global_codegen(asvalue, ir, false)) {
6140 con_out("failed to generate global %s\n", asvalue->name);
6141 ir_builder_delete(ir);
6145 /* Build function vararg accessor ast tree now before generating
6146 * immediates, because the accessors may add new immediates
6148 for (i = 0; i < vec_size(parser->functions); ++i) {
6149 ast_function *f = parser->functions[i];
6151 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6152 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6153 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6154 con_out("failed to generate vararg setter for %s\n", f->name);
6155 ir_builder_delete(ir);
6158 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6159 con_out("failed to generate vararg getter for %s\n", f->name);
6160 ir_builder_delete(ir);
6164 ast_delete(f->varargs);
6169 /* Now we can generate immediates */
6170 if (!fold_generate(parser->fold, ir))
6173 for (i = 0; i < vec_size(parser->globals); ++i) {
6175 if (!ast_istype(parser->globals[i], ast_value))
6177 asvalue = (ast_value*)(parser->globals[i]);
6178 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6180 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6181 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6182 "uninitialized constant: `%s`",
6184 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6185 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6186 "uninitialized global: `%s`",
6189 if (!ast_generate_accessors(asvalue, ir)) {
6190 ir_builder_delete(ir);
6194 for (i = 0; i < vec_size(parser->fields); ++i) {
6196 asvalue = (ast_value*)(parser->fields[i]->next);
6198 if (!ast_istype((ast_expression*)asvalue, ast_value))
6200 if (asvalue->expression.vtype != TYPE_ARRAY)
6202 if (!ast_generate_accessors(asvalue, ir)) {
6203 ir_builder_delete(ir);
6207 if (parser->reserved_version &&
6208 !ast_global_codegen(parser->reserved_version, ir, false))
6210 con_out("failed to generate reserved::version");
6211 ir_builder_delete(ir);
6214 for (i = 0; i < vec_size(parser->functions); ++i) {
6215 ast_function *f = parser->functions[i];
6216 if (!ast_function_codegen(f, ir)) {
6217 con_out("failed to generate function %s\n", f->name);
6218 ir_builder_delete(ir);
6223 generate_checksum(parser, ir);
6225 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6226 ir_builder_dump(ir, con_out);
6227 for (i = 0; i < vec_size(parser->functions); ++i) {
6228 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6229 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6230 ir_builder_delete(ir);
6234 parser_remove_ast(parser);
6236 if (compile_Werrors) {
6237 con_out("*** there were warnings treated as errors\n");
6238 compile_show_werrors();
6243 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6244 ir_builder_dump(ir, con_out);
6246 if (!ir_builder_generate(ir, output)) {
6247 con_out("*** failed to generate output file\n");
6248 ir_builder_delete(ir);
6252 ir_builder_delete(ir);