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 parser_sy_apply_operator(parser_t *parser, shunt *sy)
289 ast_expression *out = NULL;
290 ast_expression *exprs[3];
291 ast_block *blocks[3];
292 ast_value *asvalue[3];
293 ast_binstore *asbinstore;
294 size_t i, assignop, addop, subop;
295 qcint_t generated_op = 0;
300 if (!vec_size(sy->ops)) {
301 parseerror(parser, "internal error: missing operator");
305 if (vec_last(sy->ops).isparen) {
306 parseerror(parser, "unmatched parenthesis");
310 op = &operators[vec_last(sy->ops).etype - 1];
311 ctx = vec_last(sy->ops).ctx;
313 if (vec_size(sy->out) < op->operands) {
314 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
315 op->op, (int)op->id);
319 vec_shrinkby(sy->ops, 1);
321 /* op(:?) has no input and no output */
325 vec_shrinkby(sy->out, op->operands);
326 for (i = 0; i < op->operands; ++i) {
327 exprs[i] = sy->out[vec_size(sy->out)+i].out;
328 blocks[i] = sy->out[vec_size(sy->out)+i].block;
329 asvalue[i] = (ast_value*)exprs[i];
331 if (exprs[i]->vtype == TYPE_NOEXPR &&
332 !(i != 0 && op->id == opid2('?',':')) &&
333 !(i == 1 && op->id == opid1('.')))
335 if (ast_istype(exprs[i], ast_label))
336 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
338 compile_error(ast_ctx(exprs[i]), "not an expression");
339 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
343 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
344 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
348 #define NotSameType(T) \
349 (exprs[0]->vtype != exprs[1]->vtype || \
350 exprs[0]->vtype != T)
354 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
358 if (exprs[0]->vtype == TYPE_VECTOR &&
359 exprs[1]->vtype == TYPE_NOEXPR)
361 if (exprs[1] == (ast_expression*)parser->const_vec[0])
362 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
363 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
364 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
365 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
366 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
368 compile_error(ctx, "access to invalid vector component");
372 else if (exprs[0]->vtype == TYPE_ENTITY) {
373 if (exprs[1]->vtype != TYPE_FIELD) {
374 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
377 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
379 else if (exprs[0]->vtype == TYPE_VECTOR) {
380 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
384 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
390 if (exprs[0]->vtype != TYPE_ARRAY &&
391 !(exprs[0]->vtype == TYPE_FIELD &&
392 exprs[0]->next->vtype == TYPE_ARRAY))
394 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
395 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
398 if (exprs[1]->vtype != TYPE_FLOAT) {
399 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
400 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
403 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
404 if (rotate_entfield_array_index_nodes(&out))
407 /* This is not broken in fteqcc anymore */
408 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
409 /* this error doesn't need to make us bail out */
410 (void)!parsewarning(parser, WARN_EXTENSIONS,
411 "accessing array-field members of an entity without parenthesis\n"
412 " -> this is an extension from -std=gmqcc");
419 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
420 vec_push(sy->out, syexp(ctx, exprs[0]));
421 vec_push(sy->out, syexp(ctx, exprs[1]));
422 vec_last(sy->argc)++;
426 if (!ast_block_add_expr(blocks[0], exprs[1]))
429 blocks[0] = ast_block_new(ctx);
430 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
431 !ast_block_add_expr(blocks[0], exprs[1]))
436 ast_block_set_type(blocks[0], exprs[1]);
438 vec_push(sy->out, syblock(ctx, blocks[0]));
445 if (!(out = fold_op(parser->fold, op, exprs))) {
446 switch (exprs[0]->vtype) {
448 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
449 (ast_expression*)parser->fold->imm_float[0],
453 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
454 (ast_expression*)parser->fold->imm_vector[0],
458 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
459 type_name[exprs[0]->vtype]);
466 if (!(out = fold_op(parser->fold, op, exprs))) {
467 switch (exprs[0]->vtype) {
469 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
472 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
475 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
476 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
478 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
480 /* we don't constant-fold NOT for these types */
482 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
485 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
488 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
489 type_name[exprs[0]->vtype]);
496 if (exprs[0]->vtype != exprs[1]->vtype ||
497 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
499 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
500 type_name[exprs[0]->vtype],
501 type_name[exprs[1]->vtype]);
504 if (!(out = fold_op(parser->fold, op, exprs))) {
505 switch (exprs[0]->vtype) {
507 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
510 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
513 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
514 type_name[exprs[0]->vtype],
515 type_name[exprs[1]->vtype]);
521 if (exprs[0]->vtype != exprs[1]->vtype ||
522 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
524 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
525 type_name[exprs[1]->vtype],
526 type_name[exprs[0]->vtype]);
529 if (!(out = fold_op(parser->fold, op, exprs))) {
530 switch (exprs[0]->vtype) {
532 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
535 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
538 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
539 type_name[exprs[1]->vtype],
540 type_name[exprs[0]->vtype]);
546 if (exprs[0]->vtype != exprs[1]->vtype &&
547 !(exprs[0]->vtype == TYPE_VECTOR &&
548 exprs[1]->vtype == TYPE_FLOAT) &&
549 !(exprs[1]->vtype == TYPE_VECTOR &&
550 exprs[0]->vtype == TYPE_FLOAT)
553 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
554 type_name[exprs[1]->vtype],
555 type_name[exprs[0]->vtype]);
558 if (!(out = fold_op(parser->fold, op, exprs))) {
559 switch (exprs[0]->vtype) {
561 if (exprs[1]->vtype == TYPE_VECTOR)
562 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
564 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
567 if (exprs[1]->vtype == TYPE_FLOAT)
568 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
570 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
573 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
574 type_name[exprs[1]->vtype],
575 type_name[exprs[0]->vtype]);
582 if (exprs[1]->vtype != TYPE_FLOAT) {
583 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
584 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
585 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
588 if (!(out = fold_op(parser->fold, op, exprs))) {
589 if (exprs[0]->vtype == TYPE_FLOAT)
590 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
592 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
593 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
594 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
601 if (NotSameType(TYPE_FLOAT)) {
602 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
603 type_name[exprs[0]->vtype],
604 type_name[exprs[1]->vtype]);
606 } else if (!(out = fold_op(parser->fold, op, exprs))) {
607 /* generate a call to __builtin_mod */
608 ast_expression *mod = intrin_func(parser->intrin, "mod");
609 ast_call *call = NULL;
610 if (!mod) return false; /* can return null for missing floor */
612 call = ast_call_new(parser_ctx(parser), mod);
613 vec_push(call->params, exprs[0]);
614 vec_push(call->params, exprs[1]);
616 out = (ast_expression*)call;
621 compile_error(ctx, "%= is unimplemented");
627 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
628 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
629 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
631 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
632 type_name[exprs[0]->vtype],
633 type_name[exprs[1]->vtype]);
637 if (!(out = fold_op(parser->fold, op, exprs))) {
639 * IF the first expression is float, the following will be too
640 * since scalar ^ vector is not allowed.
642 if (exprs[0]->vtype == TYPE_FLOAT) {
643 out = (ast_expression*)ast_binary_new(ctx,
644 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
648 * The first is a vector: vector is allowed to bitop with vector and
649 * with scalar, branch here for the second operand.
651 if (exprs[1]->vtype == TYPE_VECTOR) {
653 * Bitop all the values of the vector components against the
654 * vectors components in question.
656 out = (ast_expression*)ast_binary_new(ctx,
657 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
660 out = (ast_expression*)ast_binary_new(ctx,
661 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
670 case opid3('<','<','='):
671 case opid3('>','>','='):
672 if(!(out = fold_op(parser->fold, op, exprs))) {
673 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
679 generated_op += 1; /* INSTR_OR */
681 generated_op += INSTR_AND;
682 if (!(out = fold_op(parser->fold, op, exprs))) {
683 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
684 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
685 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
686 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
689 for (i = 0; i < 2; ++i) {
690 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
691 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
693 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
695 exprs[i] = out; out = NULL;
696 if (OPTS_FLAG(PERL_LOGIC)) {
697 /* here we want to keep the right expressions' type */
701 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
702 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
704 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
706 exprs[i] = out; out = NULL;
707 if (OPTS_FLAG(PERL_LOGIC)) {
708 /* here we want to keep the right expressions' type */
713 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
718 if (vec_last(sy->paren) != PAREN_TERNARY2) {
719 compile_error(ctx, "mismatched parenthesis/ternary");
723 if (!ast_compare_type(exprs[1], exprs[2])) {
724 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
725 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
726 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
729 if (!(out = fold_op(parser->fold, op, exprs)))
730 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
733 case opid2('*', '*'):
734 if (NotSameType(TYPE_FLOAT)) {
735 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
736 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
737 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
742 if (!(out = fold_op(parser->fold, op, exprs))) {
743 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
744 vec_push(gencall->params, exprs[0]);
745 vec_push(gencall->params, exprs[1]);
746 out = (ast_expression*)gencall;
750 case opid3('<','=','>'): /* -1, 0, or 1 */
751 if (NotSameType(TYPE_FLOAT)) {
752 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
753 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
754 compile_error(ctx, "invalid types used in comparision: %s and %s",
760 if (!(out = fold_op(parser->fold, op, exprs))) {
761 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
763 eq->refs = AST_REF_NONE;
766 out = (ast_expression*)ast_ternary_new(ctx,
767 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
769 (ast_expression*)parser->fold->imm_float[2],
772 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
774 (ast_expression*)parser->fold->imm_float[0],
777 (ast_expression*)parser->fold->imm_float[1]
787 generated_op += 1; /* INSTR_GT */
789 generated_op += 1; /* INSTR_LT */
790 case opid2('>', '='):
791 generated_op += 1; /* INSTR_GE */
792 case opid2('<', '='):
793 generated_op += INSTR_LE;
794 if (NotSameType(TYPE_FLOAT)) {
795 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
796 type_name[exprs[0]->vtype],
797 type_name[exprs[1]->vtype]);
800 if (!(out = fold_op(parser->fold, op, exprs)))
801 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
803 case opid2('!', '='):
804 if (exprs[0]->vtype != exprs[1]->vtype) {
805 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
806 type_name[exprs[0]->vtype],
807 type_name[exprs[1]->vtype]);
810 if (!(out = fold_op(parser->fold, op, exprs)))
811 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
813 case opid2('=', '='):
814 if (exprs[0]->vtype != exprs[1]->vtype) {
815 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
816 type_name[exprs[0]->vtype],
817 type_name[exprs[1]->vtype]);
820 if (!(out = fold_op(parser->fold, op, exprs)))
821 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
825 if (ast_istype(exprs[0], ast_entfield)) {
826 ast_expression *field = ((ast_entfield*)exprs[0])->field;
827 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
828 exprs[0]->vtype == TYPE_FIELD &&
829 exprs[0]->next->vtype == TYPE_VECTOR)
831 assignop = type_storep_instr[TYPE_VECTOR];
834 assignop = type_storep_instr[exprs[0]->vtype];
835 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
837 ast_type_to_string(field->next, ty1, sizeof(ty1));
838 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
839 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
840 field->next->vtype == TYPE_FUNCTION &&
841 exprs[1]->vtype == TYPE_FUNCTION)
843 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
844 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
847 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
852 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
853 exprs[0]->vtype == TYPE_FIELD &&
854 exprs[0]->next->vtype == TYPE_VECTOR)
856 assignop = type_store_instr[TYPE_VECTOR];
859 assignop = type_store_instr[exprs[0]->vtype];
862 if (assignop == VINSTR_END) {
863 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
864 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
865 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
867 else if (!ast_compare_type(exprs[0], exprs[1]))
869 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
870 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
871 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
872 exprs[0]->vtype == TYPE_FUNCTION &&
873 exprs[1]->vtype == TYPE_FUNCTION)
875 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
876 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
879 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
882 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
883 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
885 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
887 case opid3('+','+','P'):
888 case opid3('-','-','P'):
890 if (exprs[0]->vtype != TYPE_FLOAT) {
891 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
892 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
895 if (op->id == opid3('+','+','P'))
899 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
900 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
902 if (ast_istype(exprs[0], ast_entfield)) {
903 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
905 (ast_expression*)parser->fold->imm_float[1]);
907 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
909 (ast_expression*)parser->fold->imm_float[1]);
912 case opid3('S','+','+'):
913 case opid3('S','-','-'):
915 if (exprs[0]->vtype != TYPE_FLOAT) {
916 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
917 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
920 if (op->id == opid3('S','+','+')) {
927 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
928 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
930 if (ast_istype(exprs[0], ast_entfield)) {
931 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
933 (ast_expression*)parser->fold->imm_float[1]);
935 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
937 (ast_expression*)parser->fold->imm_float[1]);
941 out = (ast_expression*)ast_binary_new(ctx, subop,
943 (ast_expression*)parser->fold->imm_float[1]);
947 if (exprs[0]->vtype != exprs[1]->vtype ||
948 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
950 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
951 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
952 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
956 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
957 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
959 if (ast_istype(exprs[0], ast_entfield))
960 assignop = type_storep_instr[exprs[0]->vtype];
962 assignop = type_store_instr[exprs[0]->vtype];
963 switch (exprs[0]->vtype) {
965 out = (ast_expression*)ast_binstore_new(ctx, assignop,
966 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
970 out = (ast_expression*)ast_binstore_new(ctx, assignop,
971 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
975 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
976 type_name[exprs[0]->vtype],
977 type_name[exprs[1]->vtype]);
983 if (exprs[1]->vtype != TYPE_FLOAT ||
984 !(exprs[0]->vtype == TYPE_FLOAT ||
985 exprs[0]->vtype == TYPE_VECTOR))
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: %s and %s",
993 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
994 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
996 if (ast_istype(exprs[0], ast_entfield))
997 assignop = type_storep_instr[exprs[0]->vtype];
999 assignop = type_store_instr[exprs[0]->vtype];
1000 switch (exprs[0]->vtype) {
1002 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1003 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1004 exprs[0], exprs[1]);
1007 if (op->id == opid2('*','=')) {
1008 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1009 exprs[0], exprs[1]);
1011 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1012 (ast_expression*)parser->fold->imm_float[1],
1015 compile_error(ctx, "internal error: failed to generate division");
1018 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1023 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1024 type_name[exprs[0]->vtype],
1025 type_name[exprs[1]->vtype]);
1029 case opid2('&','='):
1030 case opid2('|','='):
1031 case opid2('^','='):
1032 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1033 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1034 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1035 compile_error(ctx, "invalid types used in expression: %s and %s",
1039 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1040 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1042 if (ast_istype(exprs[0], ast_entfield))
1043 assignop = type_storep_instr[exprs[0]->vtype];
1045 assignop = type_store_instr[exprs[0]->vtype];
1046 if (exprs[0]->vtype == TYPE_FLOAT)
1047 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1048 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1049 exprs[0], exprs[1]);
1051 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1052 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1053 exprs[0], exprs[1]);
1055 case opid3('&','~','='):
1056 /* This is like: a &= ~(b);
1057 * But QC has no bitwise-not, so we implement it as
1060 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1061 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1062 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1063 compile_error(ctx, "invalid types used in expression: %s and %s",
1067 if (ast_istype(exprs[0], ast_entfield))
1068 assignop = type_storep_instr[exprs[0]->vtype];
1070 assignop = type_store_instr[exprs[0]->vtype];
1071 if (exprs[0]->vtype == TYPE_FLOAT)
1072 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1074 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1077 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1078 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1080 if (exprs[0]->vtype == TYPE_FLOAT)
1081 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1083 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1084 asbinstore->keep_dest = true;
1085 out = (ast_expression*)asbinstore;
1088 case opid2('~', 'P'):
1089 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1090 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1091 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1094 if (!(out = fold_op(parser->fold, op, exprs))) {
1095 if (exprs[0]->vtype == TYPE_FLOAT) {
1096 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1098 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1105 compile_error(ctx, "failed to apply operator %s", op->op);
1109 vec_push(sy->out, syexp(ctx, out));
1113 static bool parser_close_call(parser_t *parser, shunt *sy)
1115 /* was a function call */
1116 ast_expression *fun;
1117 ast_value *funval = NULL;
1121 size_t paramcount, i;
1124 fid = vec_last(sy->ops).off;
1125 vec_shrinkby(sy->ops, 1);
1127 /* out[fid] is the function
1128 * everything above is parameters...
1130 if (!vec_size(sy->argc)) {
1131 parseerror(parser, "internal error: no argument counter available");
1135 paramcount = vec_last(sy->argc);
1138 if (vec_size(sy->out) < fid) {
1139 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1140 (unsigned long)vec_size(sy->out),
1142 (unsigned long)paramcount);
1147 * TODO handle this at the intrinsic level with an ast_intrinsic
1150 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1152 if (fid+2 != vec_size(sy->out) ||
1153 vec_last(sy->out).block)
1155 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1158 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1159 ast_unref(vec_last(sy->out).out);
1160 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1161 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1162 vec_shrinkby(sy->out, 1);
1167 * Now we need to determine if the function that is being called is
1168 * an intrinsic so we can evaluate if the arguments to it are constant
1169 * and than fruitfully fold them.
1171 #define fold_can_1(X) \
1172 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1173 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1175 if (fid + 1 < vec_size(sy->out))
1178 for (i = 0; i < paramcount; ++i) {
1179 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1186 * All is well which ends well, if we make it into here we can ignore the
1187 * intrinsic call and just evaluate it i.e constant fold it.
1189 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1190 ast_expression **exprs = NULL;
1191 ast_expression *foldval = NULL;
1193 for (i = 0; i < paramcount; i++)
1194 vec_push(exprs, sy->out[fid+1 + i].out);
1196 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1202 * Blub: what sorts of unreffing and resizing of
1203 * sy->out should I be doing here?
1205 sy->out[fid] = syexp(foldval->node.context, foldval);
1206 vec_shrinkby(sy->out, 1);
1213 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1218 if (fid+1 + paramcount != vec_size(sy->out)) {
1219 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1220 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1224 for (i = 0; i < paramcount; ++i)
1225 vec_push(call->params, sy->out[fid+1 + i].out);
1226 vec_shrinkby(sy->out, paramcount);
1227 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1228 if (parser->max_param_count < paramcount)
1229 parser->max_param_count = paramcount;
1231 if (ast_istype(fun, ast_value)) {
1232 funval = (ast_value*)fun;
1233 if ((fun->flags & AST_FLAG_VARIADIC) &&
1234 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1236 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1240 /* overwrite fid, the function, with a call */
1241 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1243 if (fun->vtype != TYPE_FUNCTION) {
1244 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1249 parseerror(parser, "could not determine function return type");
1252 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1254 if (fun->flags & AST_FLAG_DEPRECATED) {
1256 return !parsewarning(parser, WARN_DEPRECATED,
1257 "call to function (which is marked deprecated)\n",
1258 "-> it has been declared here: %s:%i",
1259 ast_ctx(fun).file, ast_ctx(fun).line);
1262 return !parsewarning(parser, WARN_DEPRECATED,
1263 "call to `%s` (which is marked deprecated)\n"
1264 "-> `%s` declared here: %s:%i",
1265 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1267 return !parsewarning(parser, WARN_DEPRECATED,
1268 "call to `%s` (deprecated: %s)\n"
1269 "-> `%s` declared here: %s:%i",
1270 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1274 if (vec_size(fun->params) != paramcount &&
1275 !((fun->flags & AST_FLAG_VARIADIC) &&
1276 vec_size(fun->params) < paramcount))
1278 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1280 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1281 "too %s parameters for call to %s: expected %i, got %i\n"
1282 " -> `%s` has been declared here: %s:%i",
1283 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1284 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1286 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1287 "too %s parameters for function call: expected %i, got %i\n"
1288 " -> it has been declared here: %s:%i",
1289 fewmany, (int)vec_size(fun->params), (int)paramcount,
1290 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1297 static bool parser_close_paren(parser_t *parser, shunt *sy)
1299 if (!vec_size(sy->ops)) {
1300 parseerror(parser, "unmatched closing paren");
1304 while (vec_size(sy->ops)) {
1305 if (vec_last(sy->ops).isparen) {
1306 if (vec_last(sy->paren) == PAREN_FUNC) {
1308 if (!parser_close_call(parser, sy))
1312 if (vec_last(sy->paren) == PAREN_EXPR) {
1314 if (!vec_size(sy->out)) {
1315 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1316 vec_shrinkby(sy->ops, 1);
1319 vec_shrinkby(sy->ops, 1);
1322 if (vec_last(sy->paren) == PAREN_INDEX) {
1324 /* pop off the parenthesis */
1325 vec_shrinkby(sy->ops, 1);
1326 /* then apply the index operator */
1327 if (!parser_sy_apply_operator(parser, sy))
1331 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1332 vec_last(sy->paren) = PAREN_TERNARY2;
1333 /* pop off the parenthesis */
1334 vec_shrinkby(sy->ops, 1);
1337 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1340 if (!parser_sy_apply_operator(parser, sy))
1346 static void parser_reclassify_token(parser_t *parser)
1349 if (parser->tok >= TOKEN_START)
1351 for (i = 0; i < operator_count; ++i) {
1352 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1353 parser->tok = TOKEN_OPERATOR;
1359 static ast_expression* parse_vararg_do(parser_t *parser)
1361 ast_expression *idx, *out;
1363 ast_value *funtype = parser->function->vtype;
1364 lex_ctx_t ctx = parser_ctx(parser);
1366 if (!parser->function->varargs) {
1367 parseerror(parser, "function has no variable argument list");
1371 if (!parser_next(parser) || parser->tok != '(') {
1372 parseerror(parser, "expected parameter index and type in parenthesis");
1375 if (!parser_next(parser)) {
1376 parseerror(parser, "error parsing parameter index");
1380 idx = parse_expression_leave(parser, true, false, false);
1384 if (parser->tok != ',') {
1385 if (parser->tok != ')') {
1387 parseerror(parser, "expected comma after parameter index");
1390 /* vararg piping: ...(start) */
1391 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1395 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1397 parseerror(parser, "expected typename for vararg");
1401 typevar = parse_typename(parser, NULL, NULL);
1407 if (parser->tok != ')') {
1409 ast_delete(typevar);
1410 parseerror(parser, "expected closing paren");
1414 if (funtype->expression.varparam &&
1415 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1419 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1420 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1421 compile_error(ast_ctx(typevar),
1422 "function was declared to take varargs of type `%s`, requested type is: %s",
1426 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1427 ast_type_adopt(out, typevar);
1428 ast_delete(typevar);
1432 static ast_expression* parse_vararg(parser_t *parser)
1434 bool old_noops = parser->lex->flags.noops;
1436 ast_expression *out;
1438 parser->lex->flags.noops = true;
1439 out = parse_vararg_do(parser);
1441 parser->lex->flags.noops = old_noops;
1445 /* not to be exposed */
1446 bool ftepp_predef_exists(const char *name);
1447 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1449 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1450 parser->tok == TOKEN_IDENT &&
1451 !strcmp(parser_tokval(parser), "_"))
1453 /* a translatable string */
1456 parser->lex->flags.noops = true;
1457 if (!parser_next(parser) || parser->tok != '(') {
1458 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1461 parser->lex->flags.noops = false;
1462 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1463 parseerror(parser, "expected a constant string in translatable-string extension");
1466 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1469 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1471 if (!parser_next(parser) || parser->tok != ')') {
1472 parseerror(parser, "expected closing paren after translatable string");
1477 else if (parser->tok == TOKEN_DOTS)
1480 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1481 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1484 va = parse_vararg(parser);
1487 vec_push(sy->out, syexp(parser_ctx(parser), va));
1490 else if (parser->tok == TOKEN_FLOATCONST) {
1491 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1494 vec_push(sy->out, syexp(parser_ctx(parser), val));
1497 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1498 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1501 vec_push(sy->out, syexp(parser_ctx(parser), val));
1504 else if (parser->tok == TOKEN_STRINGCONST) {
1505 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1508 vec_push(sy->out, syexp(parser_ctx(parser), val));
1511 else if (parser->tok == TOKEN_VECTORCONST) {
1512 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1515 vec_push(sy->out, syexp(parser_ctx(parser), val));
1518 else if (parser->tok == TOKEN_IDENT)
1520 const char *ctoken = parser_tokval(parser);
1521 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1522 ast_expression *var;
1523 /* a_vector.{x,y,z} */
1524 if (!vec_size(sy->ops) ||
1525 !vec_last(sy->ops).etype ||
1526 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1528 /* When adding more intrinsics, fix the above condition */
1531 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1533 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1535 var = parser_find_var(parser, parser_tokval(parser));
1537 var = parser_find_field(parser, parser_tokval(parser));
1539 if (!var && with_labels) {
1540 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1542 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1543 var = (ast_expression*)lbl;
1544 vec_push(parser->labels, lbl);
1547 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1548 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1551 * now we try for the real intrinsic hashtable. If the string
1552 * begins with __builtin, we simply skip past it, otherwise we
1553 * use the identifier as is.
1555 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1556 var = intrin_func(parser->intrin, parser_tokval(parser));
1560 char *correct = NULL;
1564 * sometimes people use preprocessing predefs without enabling them
1565 * i've done this thousands of times already myself. Lets check for
1566 * it in the predef table. And diagnose it better :)
1568 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1569 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1574 * TODO: determine the best score for the identifier: be it
1575 * a variable, a field.
1577 * We should also consider adding correction tables for
1578 * other things as well.
1580 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1582 correct_init(&corr);
1584 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1585 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1586 if (strcmp(correct, parser_tokval(parser))) {
1593 correct_free(&corr);
1596 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1601 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1607 if (ast_istype(var, ast_value)) {
1608 ((ast_value*)var)->uses++;
1610 else if (ast_istype(var, ast_member)) {
1611 ast_member *mem = (ast_member*)var;
1612 if (ast_istype(mem->owner, ast_value))
1613 ((ast_value*)(mem->owner))->uses++;
1616 vec_push(sy->out, syexp(parser_ctx(parser), var));
1619 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1623 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1625 ast_expression *expr = NULL;
1628 bool wantop = false;
1629 /* only warn once about an assignment in a truth value because the current code
1630 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1632 bool warn_parenthesis = true;
1634 /* count the parens because an if starts with one, so the
1635 * end of a condition is an unmatched closing paren
1639 memset(&sy, 0, sizeof(sy));
1641 parser->lex->flags.noops = false;
1643 parser_reclassify_token(parser);
1647 if (parser->tok == TOKEN_TYPENAME) {
1648 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1652 if (parser->tok == TOKEN_OPERATOR)
1654 /* classify the operator */
1655 const oper_info *op;
1656 const oper_info *olast = NULL;
1658 for (o = 0; o < operator_count; ++o) {
1659 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1660 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1661 !strcmp(parser_tokval(parser), operators[o].op))
1666 if (o == operator_count) {
1667 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1670 /* found an operator */
1673 /* when declaring variables, a comma starts a new variable */
1674 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1675 /* fixup the token */
1680 /* a colon without a pervious question mark cannot be a ternary */
1681 if (!ternaries && op->id == opid2(':','?')) {
1686 if (op->id == opid1(',')) {
1687 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1688 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1692 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1693 olast = &operators[vec_last(sy.ops).etype-1];
1695 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1696 while (olast && op->prec < olast->prec)
1698 if (!parser_sy_apply_operator(parser, &sy))
1700 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1701 olast = &operators[vec_last(sy.ops).etype-1];
1706 #define IsAssignOp(x) (\
1707 (x) == opid1('=') || \
1708 (x) == opid2('+','=') || \
1709 (x) == opid2('-','=') || \
1710 (x) == opid2('*','=') || \
1711 (x) == opid2('/','=') || \
1712 (x) == opid2('%','=') || \
1713 (x) == opid2('&','=') || \
1714 (x) == opid2('|','=') || \
1715 (x) == opid3('&','~','=') \
1717 if (warn_parenthesis) {
1718 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1719 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1720 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1723 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1724 warn_parenthesis = false;
1727 if (olast && olast->id != op->id) {
1728 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1729 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1731 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1732 warn_parenthesis = false;
1734 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1735 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1737 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1738 warn_parenthesis = false;
1744 (op->prec < olast->prec) ||
1745 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1747 if (!parser_sy_apply_operator(parser, &sy))
1749 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1750 olast = &operators[vec_last(sy.ops).etype-1];
1755 if (op->id == opid1('(')) {
1757 size_t sycount = vec_size(sy.out);
1758 /* we expected an operator, this is the function-call operator */
1759 vec_push(sy.paren, PAREN_FUNC);
1760 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1761 vec_push(sy.argc, 0);
1763 vec_push(sy.paren, PAREN_EXPR);
1764 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1767 } else if (op->id == opid1('[')) {
1769 parseerror(parser, "unexpected array subscript");
1772 vec_push(sy.paren, PAREN_INDEX);
1773 /* push both the operator and the paren, this makes life easier */
1774 vec_push(sy.ops, syop(parser_ctx(parser), op));
1775 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1777 } else if (op->id == opid2('?',':')) {
1778 vec_push(sy.ops, syop(parser_ctx(parser), op));
1779 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1782 vec_push(sy.paren, PAREN_TERNARY1);
1783 } else if (op->id == opid2(':','?')) {
1784 if (!vec_size(sy.paren)) {
1785 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1788 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1789 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1792 if (!parser_close_paren(parser, &sy))
1794 vec_push(sy.ops, syop(parser_ctx(parser), op));
1798 vec_push(sy.ops, syop(parser_ctx(parser), op));
1799 wantop = !!(op->flags & OP_SUFFIX);
1802 else if (parser->tok == ')') {
1803 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1804 if (!parser_sy_apply_operator(parser, &sy))
1807 if (!vec_size(sy.paren))
1810 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1811 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1814 if (!parser_close_paren(parser, &sy))
1817 /* must be a function call without parameters */
1818 if (vec_last(sy.paren) != PAREN_FUNC) {
1819 parseerror(parser, "closing paren in invalid position");
1822 if (!parser_close_paren(parser, &sy))
1827 else if (parser->tok == '(') {
1828 parseerror(parser, "internal error: '(' should be classified as operator");
1831 else if (parser->tok == '[') {
1832 parseerror(parser, "internal error: '[' should be classified as operator");
1835 else if (parser->tok == ']') {
1836 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1837 if (!parser_sy_apply_operator(parser, &sy))
1840 if (!vec_size(sy.paren))
1842 if (vec_last(sy.paren) != PAREN_INDEX) {
1843 parseerror(parser, "mismatched parentheses, unexpected ']'");
1846 if (!parser_close_paren(parser, &sy))
1851 if (!parse_sya_operand(parser, &sy, with_labels))
1854 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1855 vec_last(sy.argc)++;
1860 /* in this case we might want to allow constant string concatenation */
1861 bool concatenated = false;
1862 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1863 ast_expression *lexpr = vec_last(sy.out).out;
1864 if (ast_istype(lexpr, ast_value)) {
1865 ast_value *last = (ast_value*)lexpr;
1866 if (last->isimm == true && last->cvq == CV_CONST &&
1867 last->hasvalue && last->expression.vtype == TYPE_STRING)
1869 char *newstr = NULL;
1870 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1871 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1873 concatenated = true;
1877 if (!concatenated) {
1878 parseerror(parser, "expected operator or end of statement");
1883 if (!parser_next(parser)) {
1886 if (parser->tok == ';' ||
1887 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1888 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1894 while (vec_size(sy.ops)) {
1895 if (!parser_sy_apply_operator(parser, &sy))
1899 parser->lex->flags.noops = true;
1900 if (vec_size(sy.out) != 1) {
1901 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
1904 expr = sy.out[0].out;
1907 if (vec_size(sy.paren)) {
1908 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1916 parser->lex->flags.noops = true;
1917 for (i = 0; i < vec_size(sy.out); ++i) {
1919 ast_unref(sy.out[i].out);
1928 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1930 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1933 if (parser->tok != ';') {
1934 parseerror(parser, "semicolon expected after expression");
1938 if (!parser_next(parser)) {
1945 static void parser_enterblock(parser_t *parser)
1947 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1948 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1949 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1950 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1951 vec_push(parser->_block_ctx, parser_ctx(parser));
1954 vec_push(parser->correct_variables, correct_trie_new());
1955 vec_push(parser->correct_variables_score, NULL);
1958 static bool parser_leaveblock(parser_t *parser)
1961 size_t locals, typedefs;
1963 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1964 parseerror(parser, "internal error: parser_leaveblock with no block");
1968 util_htdel(vec_last(parser->variables));
1969 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1971 vec_pop(parser->variables);
1972 vec_pop(parser->correct_variables);
1973 vec_pop(parser->correct_variables_score);
1974 if (!vec_size(parser->_blocklocals)) {
1975 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1979 locals = vec_last(parser->_blocklocals);
1980 vec_pop(parser->_blocklocals);
1981 while (vec_size(parser->_locals) != locals) {
1982 ast_expression *e = vec_last(parser->_locals);
1983 ast_value *v = (ast_value*)e;
1984 vec_pop(parser->_locals);
1985 if (ast_istype(e, ast_value) && !v->uses) {
1986 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1991 typedefs = vec_last(parser->_blocktypedefs);
1992 while (vec_size(parser->_typedefs) != typedefs) {
1993 ast_delete(vec_last(parser->_typedefs));
1994 vec_pop(parser->_typedefs);
1996 util_htdel(vec_last(parser->typedefs));
1997 vec_pop(parser->typedefs);
1999 vec_pop(parser->_block_ctx);
2004 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2006 vec_push(parser->_locals, e);
2007 util_htset(vec_last(parser->variables), name, (void*)e);
2011 vec_last(parser->correct_variables),
2012 &vec_last(parser->correct_variables_score),
2017 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2019 vec_push(parser->globals, e);
2020 util_htset(parser->htglobals, name, e);
2024 parser->correct_variables[0],
2025 &parser->correct_variables_score[0],
2030 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2034 ast_expression *prev;
2036 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2038 ast_type_to_string(cond, ty, sizeof(ty));
2039 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2042 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2045 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2048 parseerror(parser, "internal error: failed to process condition");
2053 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2055 /* vector types need to be cast to true booleans */
2056 ast_binary *bin = (ast_binary*)cond;
2057 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2059 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2061 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2064 parseerror(parser, "internal error: failed to process condition");
2071 unary = (ast_unary*)cond;
2072 /* ast_istype dereferences cond, should test here for safety */
2073 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2075 cond = unary->operand;
2076 unary->operand = NULL;
2079 unary = (ast_unary*)cond;
2083 parseerror(parser, "internal error: failed to process condition");
2085 if (ifnot) *_ifnot = !*_ifnot;
2089 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2092 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2095 lex_ctx_t ctx = parser_ctx(parser);
2097 (void)block; /* not touching */
2099 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2100 if (!parser_next(parser)) {
2101 parseerror(parser, "expected condition or 'not'");
2104 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2106 if (!parser_next(parser)) {
2107 parseerror(parser, "expected condition in parenthesis");
2111 if (parser->tok != '(') {
2112 parseerror(parser, "expected 'if' condition in parenthesis");
2115 /* parse into the expression */
2116 if (!parser_next(parser)) {
2117 parseerror(parser, "expected 'if' condition after opening paren");
2120 /* parse the condition */
2121 cond = parse_expression_leave(parser, false, true, false);
2125 if (parser->tok != ')') {
2126 parseerror(parser, "expected closing paren after 'if' condition");
2130 /* parse into the 'then' branch */
2131 if (!parser_next(parser)) {
2132 parseerror(parser, "expected statement for on-true branch of 'if'");
2136 if (!parse_statement_or_block(parser, &ontrue)) {
2141 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2142 /* check for an else */
2143 if (!strcmp(parser_tokval(parser), "else")) {
2144 /* parse into the 'else' branch */
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "expected on-false branch after 'else'");
2151 if (!parse_statement_or_block(parser, &onfalse)) {
2158 cond = process_condition(parser, cond, &ifnot);
2160 if (ontrue) ast_delete(ontrue);
2161 if (onfalse) ast_delete(onfalse);
2166 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2168 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2169 *out = (ast_expression*)ifthen;
2173 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2174 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2179 /* skip the 'while' and get the body */
2180 if (!parser_next(parser)) {
2181 if (OPTS_FLAG(LOOP_LABELS))
2182 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2184 parseerror(parser, "expected 'while' condition in parenthesis");
2188 if (parser->tok == ':') {
2189 if (!OPTS_FLAG(LOOP_LABELS))
2190 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2191 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2192 parseerror(parser, "expected loop label");
2195 label = util_strdup(parser_tokval(parser));
2196 if (!parser_next(parser)) {
2198 parseerror(parser, "expected 'while' condition in parenthesis");
2203 if (parser->tok != '(') {
2204 parseerror(parser, "expected 'while' condition in parenthesis");
2208 vec_push(parser->breaks, label);
2209 vec_push(parser->continues, label);
2211 rv = parse_while_go(parser, block, out);
2214 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2215 parseerror(parser, "internal error: label stack corrupted");
2221 vec_pop(parser->breaks);
2222 vec_pop(parser->continues);
2227 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2230 ast_expression *cond, *ontrue;
2234 lex_ctx_t ctx = parser_ctx(parser);
2236 (void)block; /* not touching */
2238 /* parse into the expression */
2239 if (!parser_next(parser)) {
2240 parseerror(parser, "expected 'while' condition after opening paren");
2243 /* parse the condition */
2244 cond = parse_expression_leave(parser, false, true, false);
2248 if (parser->tok != ')') {
2249 parseerror(parser, "expected closing paren after 'while' condition");
2253 /* parse into the 'then' branch */
2254 if (!parser_next(parser)) {
2255 parseerror(parser, "expected while-loop body");
2259 if (!parse_statement_or_block(parser, &ontrue)) {
2264 cond = process_condition(parser, cond, &ifnot);
2269 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2270 *out = (ast_expression*)aloop;
2274 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2275 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2280 /* skip the 'do' and get the body */
2281 if (!parser_next(parser)) {
2282 if (OPTS_FLAG(LOOP_LABELS))
2283 parseerror(parser, "expected loop label or body");
2285 parseerror(parser, "expected loop body");
2289 if (parser->tok == ':') {
2290 if (!OPTS_FLAG(LOOP_LABELS))
2291 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2292 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2293 parseerror(parser, "expected loop label");
2296 label = util_strdup(parser_tokval(parser));
2297 if (!parser_next(parser)) {
2299 parseerror(parser, "expected loop body");
2304 vec_push(parser->breaks, label);
2305 vec_push(parser->continues, label);
2307 rv = parse_dowhile_go(parser, block, out);
2310 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2311 parseerror(parser, "internal error: label stack corrupted");
2314 * Test for NULL otherwise ast_delete dereferences null pointer
2322 vec_pop(parser->breaks);
2323 vec_pop(parser->continues);
2328 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2331 ast_expression *cond, *ontrue;
2335 lex_ctx_t ctx = parser_ctx(parser);
2337 (void)block; /* not touching */
2339 if (!parse_statement_or_block(parser, &ontrue))
2342 /* expect the "while" */
2343 if (parser->tok != TOKEN_KEYWORD ||
2344 strcmp(parser_tokval(parser), "while"))
2346 parseerror(parser, "expected 'while' and condition");
2351 /* skip the 'while' and check for opening paren */
2352 if (!parser_next(parser) || parser->tok != '(') {
2353 parseerror(parser, "expected 'while' condition in parenthesis");
2357 /* parse into the expression */
2358 if (!parser_next(parser)) {
2359 parseerror(parser, "expected 'while' condition after opening paren");
2363 /* parse the condition */
2364 cond = parse_expression_leave(parser, false, true, false);
2368 if (parser->tok != ')') {
2369 parseerror(parser, "expected closing paren after 'while' condition");
2375 if (!parser_next(parser) || parser->tok != ';') {
2376 parseerror(parser, "expected semicolon after condition");
2382 if (!parser_next(parser)) {
2383 parseerror(parser, "parse error");
2389 cond = process_condition(parser, cond, &ifnot);
2394 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2395 *out = (ast_expression*)aloop;
2399 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2400 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2405 /* skip the 'for' and check for opening paren */
2406 if (!parser_next(parser)) {
2407 if (OPTS_FLAG(LOOP_LABELS))
2408 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2410 parseerror(parser, "expected 'for' expressions in parenthesis");
2414 if (parser->tok == ':') {
2415 if (!OPTS_FLAG(LOOP_LABELS))
2416 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2417 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2418 parseerror(parser, "expected loop label");
2421 label = util_strdup(parser_tokval(parser));
2422 if (!parser_next(parser)) {
2424 parseerror(parser, "expected 'for' expressions in parenthesis");
2429 if (parser->tok != '(') {
2430 parseerror(parser, "expected 'for' expressions in parenthesis");
2434 vec_push(parser->breaks, label);
2435 vec_push(parser->continues, label);
2437 rv = parse_for_go(parser, block, out);
2440 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2441 parseerror(parser, "internal error: label stack corrupted");
2447 vec_pop(parser->breaks);
2448 vec_pop(parser->continues);
2452 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2455 ast_expression *initexpr, *cond, *increment, *ontrue;
2460 lex_ctx_t ctx = parser_ctx(parser);
2462 parser_enterblock(parser);
2469 /* parse into the expression */
2470 if (!parser_next(parser)) {
2471 parseerror(parser, "expected 'for' initializer after opening paren");
2476 if (parser->tok == TOKEN_IDENT)
2477 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2479 if (typevar || parser->tok == TOKEN_TYPENAME) {
2481 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2482 if (parsewarning(parser, WARN_EXTENSIONS,
2483 "current standard does not allow variable declarations in for-loop initializers"))
2487 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2490 else if (parser->tok != ';')
2492 initexpr = parse_expression_leave(parser, false, false, false);
2497 /* move on to condition */
2498 if (parser->tok != ';') {
2499 parseerror(parser, "expected semicolon after for-loop initializer");
2502 if (!parser_next(parser)) {
2503 parseerror(parser, "expected for-loop condition");
2507 /* parse the condition */
2508 if (parser->tok != ';') {
2509 cond = parse_expression_leave(parser, false, true, false);
2514 /* move on to incrementor */
2515 if (parser->tok != ';') {
2516 parseerror(parser, "expected semicolon after for-loop initializer");
2519 if (!parser_next(parser)) {
2520 parseerror(parser, "expected for-loop condition");
2524 /* parse the incrementor */
2525 if (parser->tok != ')') {
2526 lex_ctx_t condctx = parser_ctx(parser);
2527 increment = parse_expression_leave(parser, false, false, false);
2530 if (!ast_side_effects(increment)) {
2531 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2537 if (parser->tok != ')') {
2538 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2541 /* parse into the 'then' branch */
2542 if (!parser_next(parser)) {
2543 parseerror(parser, "expected for-loop body");
2546 if (!parse_statement_or_block(parser, &ontrue))
2550 cond = process_condition(parser, cond, &ifnot);
2554 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2555 *out = (ast_expression*)aloop;
2557 if (!parser_leaveblock(parser)) {
2563 if (initexpr) ast_unref(initexpr);
2564 if (cond) ast_unref(cond);
2565 if (increment) ast_unref(increment);
2566 (void)!parser_leaveblock(parser);
2570 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2572 ast_expression *exp = NULL;
2573 ast_expression *var = NULL;
2574 ast_return *ret = NULL;
2575 ast_value *retval = parser->function->return_value;
2576 ast_value *expected = parser->function->vtype;
2578 lex_ctx_t ctx = parser_ctx(parser);
2580 (void)block; /* not touching */
2582 if (!parser_next(parser)) {
2583 parseerror(parser, "expected return expression");
2587 /* return assignments */
2588 if (parser->tok == '=') {
2589 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2590 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2594 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2596 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2597 parseerror(parser, "invalid return type: `%s'", ty1);
2601 if (!parser_next(parser)) {
2602 parseerror(parser, "expected return assignment expression");
2606 if (!(exp = parse_expression_leave(parser, false, false, false)))
2609 /* prepare the return value */
2611 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2612 ast_type_adopt(retval, expected->expression.next);
2613 parser->function->return_value = retval;
2616 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2617 char ty1[1024], ty2[1024];
2618 ast_type_to_string(exp, ty1, sizeof(ty1));
2619 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2620 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2623 /* store to 'return' local variable */
2624 var = (ast_expression*)ast_store_new(
2626 type_store_instr[expected->expression.next->vtype],
2627 (ast_expression*)retval, exp);
2634 if (parser->tok != ';')
2635 parseerror(parser, "missing semicolon after return assignment");
2636 else if (!parser_next(parser))
2637 parseerror(parser, "parse error after return assignment");
2643 if (parser->tok != ';') {
2644 exp = parse_expression(parser, false, false);
2648 if (exp->vtype != TYPE_NIL &&
2649 exp->vtype != ((ast_expression*)expected)->next->vtype)
2651 parseerror(parser, "return with invalid expression");
2654 ret = ast_return_new(ctx, exp);
2660 if (!parser_next(parser))
2661 parseerror(parser, "parse error");
2663 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2665 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2667 ret = ast_return_new(ctx, (ast_expression*)retval);
2669 *out = (ast_expression*)ret;
2673 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2676 unsigned int levels = 0;
2677 lex_ctx_t ctx = parser_ctx(parser);
2678 const char **loops = (is_continue ? parser->continues : parser->breaks);
2680 (void)block; /* not touching */
2681 if (!parser_next(parser)) {
2682 parseerror(parser, "expected semicolon or loop label");
2686 if (!vec_size(loops)) {
2688 parseerror(parser, "`continue` can only be used inside loops");
2690 parseerror(parser, "`break` can only be used inside loops or switches");
2693 if (parser->tok == TOKEN_IDENT) {
2694 if (!OPTS_FLAG(LOOP_LABELS))
2695 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2696 i = vec_size(loops);
2698 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2701 parseerror(parser, "no such loop to %s: `%s`",
2702 (is_continue ? "continue" : "break out of"),
2703 parser_tokval(parser));
2708 if (!parser_next(parser)) {
2709 parseerror(parser, "expected semicolon");
2714 if (parser->tok != ';') {
2715 parseerror(parser, "expected semicolon");
2719 if (!parser_next(parser))
2720 parseerror(parser, "parse error");
2722 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2726 /* returns true when it was a variable qualifier, false otherwise!
2727 * on error, cvq is set to CV_WRONG
2729 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2731 bool had_const = false;
2732 bool had_var = false;
2733 bool had_noref = false;
2734 bool had_attrib = false;
2735 bool had_static = false;
2740 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2742 /* parse an attribute */
2743 if (!parser_next(parser)) {
2744 parseerror(parser, "expected attribute after `[[`");
2748 if (!strcmp(parser_tokval(parser), "noreturn")) {
2749 flags |= AST_FLAG_NORETURN;
2750 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2751 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2756 else if (!strcmp(parser_tokval(parser), "noref")) {
2758 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2759 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2764 else if (!strcmp(parser_tokval(parser), "inline")) {
2765 flags |= AST_FLAG_INLINE;
2766 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2767 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2772 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2773 flags |= AST_FLAG_ERASEABLE;
2774 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2775 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2780 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2781 flags |= AST_FLAG_ALIAS;
2784 if (!parser_next(parser)) {
2785 parseerror(parser, "parse error in attribute");
2789 if (parser->tok == '(') {
2790 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2791 parseerror(parser, "`alias` attribute missing parameter");
2795 *message = util_strdup(parser_tokval(parser));
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "parse error in attribute");
2802 if (parser->tok != ')') {
2803 parseerror(parser, "`alias` attribute expected `)` after parameter");
2807 if (!parser_next(parser)) {
2808 parseerror(parser, "parse error in attribute");
2813 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2814 parseerror(parser, "`alias` attribute expected `]]`");
2818 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2819 flags |= AST_FLAG_DEPRECATED;
2822 if (!parser_next(parser)) {
2823 parseerror(parser, "parse error in attribute");
2827 if (parser->tok == '(') {
2828 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2829 parseerror(parser, "`deprecated` attribute missing parameter");
2833 *message = util_strdup(parser_tokval(parser));
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "parse error in attribute");
2840 if(parser->tok != ')') {
2841 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2845 if (!parser_next(parser)) {
2846 parseerror(parser, "parse error in attribute");
2851 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2852 parseerror(parser, "`deprecated` attribute expected `]]`");
2855 if (*message) mem_d(*message);
2863 /* Skip tokens until we hit a ]] */
2864 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2865 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2866 if (!parser_next(parser)) {
2867 parseerror(parser, "error inside attribute");
2874 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2876 else if (!strcmp(parser_tokval(parser), "const"))
2878 else if (!strcmp(parser_tokval(parser), "var"))
2880 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2882 else if (!strcmp(parser_tokval(parser), "noref"))
2884 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2889 if (!parser_next(parser))
2899 *is_static = had_static;
2903 parseerror(parser, "parse error after variable qualifier");
2908 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2909 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2914 /* skip the 'while' and get the body */
2915 if (!parser_next(parser)) {
2916 if (OPTS_FLAG(LOOP_LABELS))
2917 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2919 parseerror(parser, "expected 'switch' operand in parenthesis");
2923 if (parser->tok == ':') {
2924 if (!OPTS_FLAG(LOOP_LABELS))
2925 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2926 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2927 parseerror(parser, "expected loop label");
2930 label = util_strdup(parser_tokval(parser));
2931 if (!parser_next(parser)) {
2933 parseerror(parser, "expected 'switch' operand in parenthesis");
2938 if (parser->tok != '(') {
2939 parseerror(parser, "expected 'switch' operand in parenthesis");
2943 vec_push(parser->breaks, label);
2945 rv = parse_switch_go(parser, block, out);
2948 if (vec_last(parser->breaks) != label) {
2949 parseerror(parser, "internal error: label stack corrupted");
2955 vec_pop(parser->breaks);
2960 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2962 ast_expression *operand;
2965 ast_switch *switchnode;
2966 ast_switch_case swcase;
2969 bool noref, is_static;
2970 uint32_t qflags = 0;
2972 lex_ctx_t ctx = parser_ctx(parser);
2974 (void)block; /* not touching */
2977 /* parse into the expression */
2978 if (!parser_next(parser)) {
2979 parseerror(parser, "expected switch operand");
2982 /* parse the operand */
2983 operand = parse_expression_leave(parser, false, false, false);
2987 switchnode = ast_switch_new(ctx, operand);
2990 if (parser->tok != ')') {
2991 ast_delete(switchnode);
2992 parseerror(parser, "expected closing paren after 'switch' operand");
2996 /* parse over the opening paren */
2997 if (!parser_next(parser) || parser->tok != '{') {
2998 ast_delete(switchnode);
2999 parseerror(parser, "expected list of cases");
3003 if (!parser_next(parser)) {
3004 ast_delete(switchnode);
3005 parseerror(parser, "expected 'case' or 'default'");
3009 /* new block; allow some variables to be declared here */
3010 parser_enterblock(parser);
3013 if (parser->tok == TOKEN_IDENT)
3014 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3015 if (typevar || parser->tok == TOKEN_TYPENAME) {
3016 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3017 ast_delete(switchnode);
3022 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3024 if (cvq == CV_WRONG) {
3025 ast_delete(switchnode);
3028 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3029 ast_delete(switchnode);
3038 while (parser->tok != '}') {
3039 ast_block *caseblock;
3041 if (!strcmp(parser_tokval(parser), "case")) {
3042 if (!parser_next(parser)) {
3043 ast_delete(switchnode);
3044 parseerror(parser, "expected expression for case");
3047 swcase.value = parse_expression_leave(parser, false, false, false);
3048 if (!swcase.value) {
3049 ast_delete(switchnode);
3050 parseerror(parser, "expected expression for case");
3053 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3054 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3055 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3061 else if (!strcmp(parser_tokval(parser), "default")) {
3062 swcase.value = NULL;
3063 if (!parser_next(parser)) {
3064 ast_delete(switchnode);
3065 parseerror(parser, "expected colon");
3070 ast_delete(switchnode);
3071 parseerror(parser, "expected 'case' or 'default'");
3075 /* Now the colon and body */
3076 if (parser->tok != ':') {
3077 if (swcase.value) ast_unref(swcase.value);
3078 ast_delete(switchnode);
3079 parseerror(parser, "expected colon");
3083 if (!parser_next(parser)) {
3084 if (swcase.value) ast_unref(swcase.value);
3085 ast_delete(switchnode);
3086 parseerror(parser, "expected statements or case");
3089 caseblock = ast_block_new(parser_ctx(parser));
3091 if (swcase.value) ast_unref(swcase.value);
3092 ast_delete(switchnode);
3095 swcase.code = (ast_expression*)caseblock;
3096 vec_push(switchnode->cases, swcase);
3098 ast_expression *expr;
3099 if (parser->tok == '}')
3101 if (parser->tok == TOKEN_KEYWORD) {
3102 if (!strcmp(parser_tokval(parser), "case") ||
3103 !strcmp(parser_tokval(parser), "default"))
3108 if (!parse_statement(parser, caseblock, &expr, true)) {
3109 ast_delete(switchnode);
3114 if (!ast_block_add_expr(caseblock, expr)) {
3115 ast_delete(switchnode);
3121 parser_leaveblock(parser);
3124 if (parser->tok != '}') {
3125 ast_delete(switchnode);
3126 parseerror(parser, "expected closing paren of case list");
3129 if (!parser_next(parser)) {
3130 ast_delete(switchnode);
3131 parseerror(parser, "parse error after switch");
3134 *out = (ast_expression*)switchnode;
3138 /* parse computed goto sides */
3139 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3140 ast_expression *on_true;
3141 ast_expression *on_false;
3142 ast_expression *cond;
3147 if (ast_istype(*side, ast_ternary)) {
3148 ast_ternary *tern = (ast_ternary*)*side;
3149 on_true = parse_goto_computed(parser, &tern->on_true);
3150 on_false = parse_goto_computed(parser, &tern->on_false);
3152 if (!on_true || !on_false) {
3153 parseerror(parser, "expected label or expression in ternary");
3154 if (on_true) ast_unref(on_true);
3155 if (on_false) ast_unref(on_false);
3163 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3164 } else if (ast_istype(*side, ast_label)) {
3165 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3166 ast_goto_set_label(gt, ((ast_label*)*side));
3168 return (ast_expression*)gt;
3173 static bool parse_goto(parser_t *parser, ast_expression **out)
3175 ast_goto *gt = NULL;
3176 ast_expression *lbl;
3178 if (!parser_next(parser))
3181 if (parser->tok != TOKEN_IDENT) {
3182 ast_expression *expression;
3184 /* could be an expression i.e computed goto :-) */
3185 if (parser->tok != '(') {
3186 parseerror(parser, "expected label name after `goto`");
3190 /* failed to parse expression for goto */
3191 if (!(expression = parse_expression(parser, false, true)) ||
3192 !(*out = parse_goto_computed(parser, &expression))) {
3193 parseerror(parser, "invalid goto expression");
3195 ast_unref(expression);
3202 /* not computed goto */
3203 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3204 lbl = parser_find_label(parser, gt->name);
3206 if (!ast_istype(lbl, ast_label)) {
3207 parseerror(parser, "internal error: label is not an ast_label");
3211 ast_goto_set_label(gt, (ast_label*)lbl);
3214 vec_push(parser->gotos, gt);
3216 if (!parser_next(parser) || parser->tok != ';') {
3217 parseerror(parser, "semicolon expected after goto label");
3220 if (!parser_next(parser)) {
3221 parseerror(parser, "parse error after goto");
3225 *out = (ast_expression*)gt;
3229 static bool parse_skipwhite(parser_t *parser)
3232 if (!parser_next(parser))
3234 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3235 return parser->tok < TOKEN_ERROR;
3238 static bool parse_eol(parser_t *parser)
3240 if (!parse_skipwhite(parser))
3242 return parser->tok == TOKEN_EOL;
3245 static bool parse_pragma_do(parser_t *parser)
3247 if (!parser_next(parser) ||
3248 parser->tok != TOKEN_IDENT ||
3249 strcmp(parser_tokval(parser), "pragma"))
3251 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3254 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3255 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3259 if (!strcmp(parser_tokval(parser), "noref")) {
3260 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3261 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3264 parser->noref = !!parser_token(parser)->constval.i;
3265 if (!parse_eol(parser)) {
3266 parseerror(parser, "parse error after `noref` pragma");
3272 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3279 static bool parse_pragma(parser_t *parser)
3282 parser->lex->flags.preprocessing = true;
3283 parser->lex->flags.mergelines = true;
3284 rv = parse_pragma_do(parser);
3285 if (parser->tok != TOKEN_EOL) {
3286 parseerror(parser, "junk after pragma");
3289 parser->lex->flags.preprocessing = false;
3290 parser->lex->flags.mergelines = false;
3291 if (!parser_next(parser)) {
3292 parseerror(parser, "parse error after pragma");
3298 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3300 bool noref, is_static;
3302 uint32_t qflags = 0;
3303 ast_value *typevar = NULL;
3304 char *vstring = NULL;
3308 if (parser->tok == TOKEN_IDENT)
3309 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3311 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3313 /* local variable */
3315 parseerror(parser, "cannot declare a variable from here");
3318 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3319 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3322 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3326 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3328 if (cvq == CV_WRONG)
3330 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3332 else if (parser->tok == TOKEN_KEYWORD)
3334 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3339 if (!parser_next(parser)) {
3340 parseerror(parser, "parse error after __builtin_debug_printtype");
3344 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3346 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3347 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3348 if (!parser_next(parser)) {
3349 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3355 if (!parse_statement(parser, block, out, allow_cases))
3358 con_out("__builtin_debug_printtype: got no output node\n");
3361 ast_type_to_string(*out, ty, sizeof(ty));
3362 con_out("__builtin_debug_printtype: `%s`\n", ty);
3367 else if (!strcmp(parser_tokval(parser), "return"))
3369 return parse_return(parser, block, out);
3371 else if (!strcmp(parser_tokval(parser), "if"))
3373 return parse_if(parser, block, out);
3375 else if (!strcmp(parser_tokval(parser), "while"))
3377 return parse_while(parser, block, out);
3379 else if (!strcmp(parser_tokval(parser), "do"))
3381 return parse_dowhile(parser, block, out);
3383 else if (!strcmp(parser_tokval(parser), "for"))
3385 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3386 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3389 return parse_for(parser, block, out);
3391 else if (!strcmp(parser_tokval(parser), "break"))
3393 return parse_break_continue(parser, block, out, false);
3395 else if (!strcmp(parser_tokval(parser), "continue"))
3397 return parse_break_continue(parser, block, out, true);
3399 else if (!strcmp(parser_tokval(parser), "switch"))
3401 return parse_switch(parser, block, out);
3403 else if (!strcmp(parser_tokval(parser), "case") ||
3404 !strcmp(parser_tokval(parser), "default"))
3407 parseerror(parser, "unexpected 'case' label");
3412 else if (!strcmp(parser_tokval(parser), "goto"))
3414 return parse_goto(parser, out);
3416 else if (!strcmp(parser_tokval(parser), "typedef"))
3418 if (!parser_next(parser)) {
3419 parseerror(parser, "expected type definition after 'typedef'");
3422 return parse_typedef(parser);
3424 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3427 else if (parser->tok == '{')
3430 inner = parse_block(parser);
3433 *out = (ast_expression*)inner;
3436 else if (parser->tok == ':')
3440 if (!parser_next(parser)) {
3441 parseerror(parser, "expected label name");
3444 if (parser->tok != TOKEN_IDENT) {
3445 parseerror(parser, "label must be an identifier");
3448 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3450 if (!label->undefined) {
3451 parseerror(parser, "label `%s` already defined", label->name);
3454 label->undefined = false;
3457 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3458 vec_push(parser->labels, label);
3460 *out = (ast_expression*)label;
3461 if (!parser_next(parser)) {
3462 parseerror(parser, "parse error after label");
3465 for (i = 0; i < vec_size(parser->gotos); ++i) {
3466 if (!strcmp(parser->gotos[i]->name, label->name)) {
3467 ast_goto_set_label(parser->gotos[i], label);
3468 vec_remove(parser->gotos, i, 1);
3474 else if (parser->tok == ';')
3476 if (!parser_next(parser)) {
3477 parseerror(parser, "parse error after empty statement");
3484 lex_ctx_t ctx = parser_ctx(parser);
3485 ast_expression *exp = parse_expression(parser, false, false);
3489 if (!ast_side_effects(exp)) {
3490 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3497 static bool parse_enum(parser_t *parser)
3500 bool reverse = false;
3502 ast_value **values = NULL;
3503 ast_value *var = NULL;
3506 ast_expression *old;
3508 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3509 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3513 /* enumeration attributes (can add more later) */
3514 if (parser->tok == ':') {
3515 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3516 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3521 if (!strcmp(parser_tokval(parser), "flag")) {
3525 else if (!strcmp(parser_tokval(parser), "reverse")) {
3529 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3533 if (!parser_next(parser) || parser->tok != '{') {
3534 parseerror(parser, "expected `{` after enum attribute ");
3540 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3541 if (parser->tok == '}') {
3542 /* allow an empty enum */
3545 parseerror(parser, "expected identifier or `}`");
3549 old = parser_find_field(parser, parser_tokval(parser));
3551 old = parser_find_global(parser, parser_tokval(parser));
3553 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3554 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3558 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3559 vec_push(values, var);
3560 var->cvq = CV_CONST;
3561 var->hasvalue = true;
3563 /* for flagged enumerations increment in POTs of TWO */
3564 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3565 parser_addglobal(parser, var->name, (ast_expression*)var);
3567 if (!parser_next(parser)) {
3568 parseerror(parser, "expected `=`, `}` or comma after identifier");
3572 if (parser->tok == ',')
3574 if (parser->tok == '}')
3576 if (parser->tok != '=') {
3577 parseerror(parser, "expected `=`, `}` or comma after identifier");
3581 if (!parser_next(parser)) {
3582 parseerror(parser, "expected expression after `=`");
3586 /* We got a value! */
3587 old = parse_expression_leave(parser, true, false, false);
3588 asvalue = (ast_value*)old;
3589 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3590 compile_error(ast_ctx(var), "constant value or expression expected");
3593 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3595 if (parser->tok == '}')
3597 if (parser->tok != ',') {
3598 parseerror(parser, "expected `}` or comma after expression");
3603 /* patch them all (for reversed attribute) */
3606 for (i = 0; i < vec_size(values); i++)
3607 values[i]->constval.vfloat = vec_size(values) - i - 1;
3610 if (parser->tok != '}') {
3611 parseerror(parser, "internal error: breaking without `}`");
3615 if (!parser_next(parser) || parser->tok != ';') {
3616 parseerror(parser, "expected semicolon after enumeration");
3620 if (!parser_next(parser)) {
3621 parseerror(parser, "parse error after enumeration");
3633 static bool parse_block_into(parser_t *parser, ast_block *block)
3637 parser_enterblock(parser);
3639 if (!parser_next(parser)) { /* skip the '{' */
3640 parseerror(parser, "expected function body");
3644 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3646 ast_expression *expr = NULL;
3647 if (parser->tok == '}')
3650 if (!parse_statement(parser, block, &expr, false)) {
3651 /* parseerror(parser, "parse error"); */
3657 if (!ast_block_add_expr(block, expr)) {
3664 if (parser->tok != '}') {
3667 (void)parser_next(parser);
3671 if (!parser_leaveblock(parser))
3673 return retval && !!block;
3676 static ast_block* parse_block(parser_t *parser)
3679 block = ast_block_new(parser_ctx(parser));
3682 if (!parse_block_into(parser, block)) {
3683 ast_block_delete(block);
3689 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3691 if (parser->tok == '{') {
3692 *out = (ast_expression*)parse_block(parser);
3695 return parse_statement(parser, NULL, out, false);
3698 static bool create_vector_members(ast_value *var, ast_member **me)
3701 size_t len = strlen(var->name);
3703 for (i = 0; i < 3; ++i) {
3704 char *name = (char*)mem_a(len+3);
3705 memcpy(name, var->name, len);
3707 name[len+1] = 'x'+i;
3709 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3718 do { ast_member_delete(me[--i]); } while(i);
3722 static bool parse_function_body(parser_t *parser, ast_value *var)
3724 ast_block *block = NULL;
3729 ast_expression *framenum = NULL;
3730 ast_expression *nextthink = NULL;
3731 /* None of the following have to be deleted */
3732 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3733 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3734 bool has_frame_think;
3738 has_frame_think = false;
3739 old = parser->function;
3741 if (var->expression.flags & AST_FLAG_ALIAS) {
3742 parseerror(parser, "function aliases cannot have bodies");
3746 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3747 parseerror(parser, "gotos/labels leaking");
3751 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3752 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3753 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3759 if (parser->tok == '[') {
3760 /* got a frame definition: [ framenum, nextthink ]
3761 * this translates to:
3762 * self.frame = framenum;
3763 * self.nextthink = time + 0.1;
3764 * self.think = nextthink;
3768 fld_think = parser_find_field(parser, "think");
3769 fld_nextthink = parser_find_field(parser, "nextthink");
3770 fld_frame = parser_find_field(parser, "frame");
3771 if (!fld_think || !fld_nextthink || !fld_frame) {
3772 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3773 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3776 gbl_time = parser_find_global(parser, "time");
3777 gbl_self = parser_find_global(parser, "self");
3778 if (!gbl_time || !gbl_self) {
3779 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3780 parseerror(parser, "please declare the following globals: `time`, `self`");
3784 if (!parser_next(parser))
3787 framenum = parse_expression_leave(parser, true, false, false);
3789 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3792 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3793 ast_unref(framenum);
3794 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3798 if (parser->tok != ',') {
3799 ast_unref(framenum);
3800 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3801 parseerror(parser, "Got a %i\n", parser->tok);
3805 if (!parser_next(parser)) {
3806 ast_unref(framenum);
3810 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3812 /* qc allows the use of not-yet-declared functions here
3813 * - this automatically creates a prototype */
3814 ast_value *thinkfunc;
3815 ast_expression *functype = fld_think->next;
3817 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3818 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3819 ast_unref(framenum);
3820 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3823 ast_type_adopt(thinkfunc, functype);
3825 if (!parser_next(parser)) {
3826 ast_unref(framenum);
3827 ast_delete(thinkfunc);
3831 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3833 nextthink = (ast_expression*)thinkfunc;
3836 nextthink = parse_expression_leave(parser, true, false, false);
3838 ast_unref(framenum);
3839 parseerror(parser, "expected a think-function in [frame,think] notation");
3844 if (!ast_istype(nextthink, ast_value)) {
3845 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3849 if (retval && parser->tok != ']') {
3850 parseerror(parser, "expected closing `]` for [frame,think] notation");
3854 if (retval && !parser_next(parser)) {
3858 if (retval && parser->tok != '{') {
3859 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3864 ast_unref(nextthink);
3865 ast_unref(framenum);
3869 has_frame_think = true;
3872 block = ast_block_new(parser_ctx(parser));
3874 parseerror(parser, "failed to allocate block");
3875 if (has_frame_think) {
3876 ast_unref(nextthink);
3877 ast_unref(framenum);
3882 if (has_frame_think) {
3884 ast_expression *self_frame;
3885 ast_expression *self_nextthink;
3886 ast_expression *self_think;
3887 ast_expression *time_plus_1;
3888 ast_store *store_frame;
3889 ast_store *store_nextthink;
3890 ast_store *store_think;
3892 ctx = parser_ctx(parser);
3893 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3894 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3895 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3897 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3898 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3900 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3901 if (self_frame) ast_delete(self_frame);
3902 if (self_nextthink) ast_delete(self_nextthink);
3903 if (self_think) ast_delete(self_think);
3904 if (time_plus_1) ast_delete(time_plus_1);
3910 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3911 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3912 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3915 ast_delete(self_frame);
3918 if (!store_nextthink) {
3919 ast_delete(self_nextthink);
3923 ast_delete(self_think);
3927 if (store_frame) ast_delete(store_frame);
3928 if (store_nextthink) ast_delete(store_nextthink);
3929 if (store_think) ast_delete(store_think);
3932 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3933 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3934 !ast_block_add_expr(block, (ast_expression*)store_think))
3941 parseerror(parser, "failed to generate code for [frame,think]");
3942 ast_unref(nextthink);
3943 ast_unref(framenum);
3949 if (var->hasvalue) {
3950 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3951 ast_block_delete(block);
3955 func = ast_function_new(ast_ctx(var), var->name, var);
3957 parseerror(parser, "failed to allocate function for `%s`", var->name);
3958 ast_block_delete(block);
3961 vec_push(parser->functions, func);
3963 parser_enterblock(parser);
3965 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3967 ast_value *param = var->expression.params[parami];
3970 if (param->expression.vtype != TYPE_VECTOR &&
3971 (param->expression.vtype != TYPE_FIELD ||
3972 param->expression.next->vtype != TYPE_VECTOR))
3977 if (!create_vector_members(param, me)) {
3978 ast_block_delete(block);
3982 for (e = 0; e < 3; ++e) {
3983 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3984 ast_block_collect(block, (ast_expression*)me[e]);
3988 if (var->argcounter) {
3989 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3990 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3994 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3996 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3997 varargs->expression.flags |= AST_FLAG_IS_VARARG;
3998 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3999 varargs->expression.count = 0;
4000 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4001 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4002 ast_delete(varargs);
4003 ast_block_delete(block);
4006 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4007 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4008 ast_delete(varargs);
4009 ast_block_delete(block);
4012 func->varargs = varargs;
4013 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4016 parser->function = func;
4017 if (!parse_block_into(parser, block)) {
4018 ast_block_delete(block);
4022 vec_push(func->blocks, block);
4025 parser->function = old;
4026 if (!parser_leaveblock(parser))
4028 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4029 parseerror(parser, "internal error: local scopes left");
4033 if (parser->tok == ';')
4034 return parser_next(parser);
4035 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4036 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4040 (void)!parser_leaveblock(parser);
4041 vec_pop(parser->functions);
4042 ast_function_delete(func);
4043 var->constval.vfunc = NULL;
4046 parser->function = old;
4050 static ast_expression *array_accessor_split(
4055 ast_expression *left,
4056 ast_expression *right
4062 lex_ctx_t ctx = ast_ctx(array);
4064 if (!left || !right) {
4065 if (left) ast_delete(left);
4066 if (right) ast_delete(right);
4070 cmp = ast_binary_new(ctx, INSTR_LT,
4071 (ast_expression*)index,
4072 (ast_expression*)fold_constgen_float(parser->fold, middle));
4076 parseerror(parser, "internal error: failed to create comparison for array setter");
4080 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4082 ast_delete(cmp); /* will delete left and right */
4083 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4087 return (ast_expression*)ifthen;
4090 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4092 lex_ctx_t ctx = ast_ctx(array);
4094 if (from+1 == afterend) {
4095 /* set this value */
4098 ast_array_index *subscript;
4100 int assignop = type_store_instr[value->expression.vtype];
4102 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4103 assignop = INSTR_STORE_V;
4105 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4109 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4111 ast_delete(subscript);
4115 block = ast_block_new(ctx);
4121 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4126 ret = ast_return_new(ctx, NULL);
4132 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4137 return (ast_expression*)block;
4139 ast_expression *left, *right;
4140 size_t diff = afterend - from;
4141 size_t middle = from + diff/2;
4142 left = array_setter_node(parser, array, index, value, from, middle);
4143 right = array_setter_node(parser, array, index, value, middle, afterend);
4144 return array_accessor_split(parser, array, index, middle, left, right);
4148 static ast_expression *array_field_setter_node(
4157 lex_ctx_t ctx = ast_ctx(array);
4159 if (from+1 == afterend) {
4160 /* set this value */
4163 ast_entfield *entfield;
4164 ast_array_index *subscript;
4166 int assignop = type_storep_instr[value->expression.vtype];
4168 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4169 assignop = INSTR_STOREP_V;
4171 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4175 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4176 subscript->expression.vtype = TYPE_FIELD;
4178 entfield = ast_entfield_new_force(ctx,
4179 (ast_expression*)entity,
4180 (ast_expression*)subscript,
4181 (ast_expression*)subscript);
4183 ast_delete(subscript);
4187 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4189 ast_delete(entfield);
4193 block = ast_block_new(ctx);
4199 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4204 ret = ast_return_new(ctx, NULL);
4210 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4215 return (ast_expression*)block;
4217 ast_expression *left, *right;
4218 size_t diff = afterend - from;
4219 size_t middle = from + diff/2;
4220 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4221 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4222 return array_accessor_split(parser, array, index, middle, left, right);
4226 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4228 lex_ctx_t ctx = ast_ctx(array);
4230 if (from+1 == afterend) {
4232 ast_array_index *subscript;
4234 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4238 ret = ast_return_new(ctx, (ast_expression*)subscript);
4240 ast_delete(subscript);
4244 return (ast_expression*)ret;
4246 ast_expression *left, *right;
4247 size_t diff = afterend - from;
4248 size_t middle = from + diff/2;
4249 left = array_getter_node(parser, array, index, from, middle);
4250 right = array_getter_node(parser, array, index, middle, afterend);
4251 return array_accessor_split(parser, array, index, middle, left, right);
4255 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4257 ast_function *func = NULL;
4258 ast_value *fval = NULL;
4259 ast_block *body = NULL;
4261 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4263 parseerror(parser, "failed to create accessor function value");
4267 func = ast_function_new(ast_ctx(array), funcname, fval);
4270 parseerror(parser, "failed to create accessor function node");
4274 body = ast_block_new(ast_ctx(array));
4276 parseerror(parser, "failed to create block for array accessor");
4282 vec_push(func->blocks, body);
4285 vec_push(parser->accessors, fval);
4290 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4292 ast_value *index = NULL;
4293 ast_value *value = NULL;
4297 if (!ast_istype(array->expression.next, ast_value)) {
4298 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4302 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4304 func = fval->constval.vfunc;
4305 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4307 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4308 value = ast_value_copy((ast_value*)array->expression.next);
4310 if (!index || !value) {
4311 parseerror(parser, "failed to create locals for array accessor");
4314 (void)!ast_value_set_name(value, "value"); /* not important */
4315 vec_push(fval->expression.params, index);
4316 vec_push(fval->expression.params, value);
4318 array->setter = fval;
4321 if (index) ast_delete(index);
4322 if (value) ast_delete(value);
4328 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4330 ast_expression *root = NULL;
4331 root = array_setter_node(parser, array,
4332 array->setter->expression.params[0],
4333 array->setter->expression.params[1],
4334 0, array->expression.count);
4336 parseerror(parser, "failed to build accessor search tree");
4339 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4346 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4348 if (!parser_create_array_setter_proto(parser, array, funcname))
4350 return parser_create_array_setter_impl(parser, array);
4353 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4355 ast_expression *root = NULL;
4356 ast_value *entity = NULL;
4357 ast_value *index = NULL;
4358 ast_value *value = NULL;
4362 if (!ast_istype(array->expression.next, ast_value)) {
4363 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4367 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4369 func = fval->constval.vfunc;
4370 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4372 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4373 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4374 value = ast_value_copy((ast_value*)array->expression.next);
4375 if (!entity || !index || !value) {
4376 parseerror(parser, "failed to create locals for array accessor");
4379 (void)!ast_value_set_name(value, "value"); /* not important */
4380 vec_push(fval->expression.params, entity);
4381 vec_push(fval->expression.params, index);
4382 vec_push(fval->expression.params, value);
4384 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4386 parseerror(parser, "failed to build accessor search tree");
4390 array->setter = fval;
4391 return ast_block_add_expr(func->blocks[0], root);
4393 if (entity) ast_delete(entity);
4394 if (index) ast_delete(index);
4395 if (value) ast_delete(value);
4396 if (root) ast_delete(root);
4402 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4404 ast_value *index = NULL;
4408 /* NOTE: checking array->expression.next rather than elemtype since
4409 * for fields elemtype is a temporary fieldtype.
4411 if (!ast_istype(array->expression.next, ast_value)) {
4412 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4416 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4418 func = fval->constval.vfunc;
4419 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4421 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4424 parseerror(parser, "failed to create locals for array accessor");
4427 vec_push(fval->expression.params, index);
4429 array->getter = fval;
4432 if (index) ast_delete(index);
4438 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4440 ast_expression *root = NULL;
4442 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4444 parseerror(parser, "failed to build accessor search tree");
4447 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4454 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4456 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4458 return parser_create_array_getter_impl(parser, array);
4461 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4462 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4470 bool variadic = false;
4471 ast_value *varparam = NULL;
4472 char *argcounter = NULL;
4474 ctx = parser_ctx(parser);
4476 /* for the sake of less code we parse-in in this function */
4477 if (!parser_next(parser)) {
4479 parseerror(parser, "expected parameter list");
4485 /* parse variables until we hit a closing paren */
4486 while (parser->tok != ')') {
4488 /* there must be commas between them */
4489 if (parser->tok != ',') {
4490 parseerror(parser, "expected comma or end of parameter list");
4493 if (!parser_next(parser)) {
4494 parseerror(parser, "expected parameter");
4500 if (parser->tok == TOKEN_DOTS) {
4501 /* '...' indicates a varargs function */
4503 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4504 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4507 if (parser->tok == TOKEN_IDENT) {
4508 argcounter = util_strdup(parser_tokval(parser));
4509 if (!parser_next(parser) || parser->tok != ')') {
4510 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4517 /* for anything else just parse a typename */
4518 param = parse_typename(parser, NULL, NULL);
4521 vec_push(params, param);
4522 if (param->expression.vtype >= TYPE_VARIANT) {
4523 char tname[1024]; /* typename is reserved in C++ */
4524 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4525 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4528 /* type-restricted varargs */
4529 if (parser->tok == TOKEN_DOTS) {
4531 varparam = vec_last(params);
4533 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4534 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4537 if (parser->tok == TOKEN_IDENT) {
4538 argcounter = util_strdup(parser_tokval(parser));
4539 if (!parser_next(parser) || parser->tok != ')') {
4540 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4548 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4552 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4553 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4556 if (!parser_next(parser)) {
4557 parseerror(parser, "parse error after typename");
4561 /* now turn 'var' into a function type */
4562 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4563 fval->expression.next = (ast_expression*)var;
4565 fval->expression.flags |= AST_FLAG_VARIADIC;
4568 var->expression.params = params;
4569 var->expression.varparam = (ast_expression*)varparam;
4570 var->argcounter = argcounter;
4579 ast_delete(varparam);
4581 for (i = 0; i < vec_size(params); ++i)
4582 ast_delete(params[i]);
4587 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4589 ast_expression *cexp;
4590 ast_value *cval, *tmp;
4593 ctx = parser_ctx(parser);
4595 if (!parser_next(parser)) {
4597 parseerror(parser, "expected array-size");
4601 if (parser->tok != ']') {
4602 cexp = parse_expression_leave(parser, true, false, false);
4604 if (!cexp || !ast_istype(cexp, ast_value)) {
4608 parseerror(parser, "expected array-size as constant positive integer");
4611 cval = (ast_value*)cexp;
4618 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4619 tmp->expression.next = (ast_expression*)var;
4623 if (cval->expression.vtype == TYPE_INTEGER)
4624 tmp->expression.count = cval->constval.vint;
4625 else if (cval->expression.vtype == TYPE_FLOAT)
4626 tmp->expression.count = cval->constval.vfloat;
4630 parseerror(parser, "array-size must be a positive integer constant");
4636 var->expression.count = -1;
4637 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4640 if (parser->tok != ']') {
4642 parseerror(parser, "expected ']' after array-size");
4645 if (!parser_next(parser)) {
4647 parseerror(parser, "error after parsing array size");
4653 /* Parse a complete typename.
4654 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4655 * but when parsing variables separated by comma
4656 * 'storebase' should point to where the base-type should be kept.
4657 * The base type makes up every bit of type information which comes *before* the
4660 * The following will be parsed in its entirety:
4662 * The 'basetype' in this case is 'void()'
4663 * and if there's a comma after it, say:
4665 * then the type-information 'void()' can be stored in 'storebase'
4667 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4669 ast_value *var, *tmp;
4672 const char *name = NULL;
4673 bool isfield = false;
4674 bool wasarray = false;
4675 size_t morefields = 0;
4677 ctx = parser_ctx(parser);
4679 /* types may start with a dot */
4680 if (parser->tok == '.') {
4682 /* if we parsed a dot we need a typename now */
4683 if (!parser_next(parser)) {
4684 parseerror(parser, "expected typename for field definition");
4688 /* Further dots are handled seperately because they won't be part of the
4691 while (parser->tok == '.') {
4693 if (!parser_next(parser)) {
4694 parseerror(parser, "expected typename for field definition");
4699 if (parser->tok == TOKEN_IDENT)
4700 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4701 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4702 parseerror(parser, "expected typename");
4706 /* generate the basic type value */
4707 if (cached_typedef) {
4708 var = ast_value_copy(cached_typedef);
4709 ast_value_set_name(var, "<type(from_def)>");
4711 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4713 for (; morefields; --morefields) {
4714 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4715 tmp->expression.next = (ast_expression*)var;
4719 /* do not yet turn into a field - remember:
4720 * .void() foo; is a field too
4721 * .void()() foo; is a function
4725 if (!parser_next(parser)) {
4727 parseerror(parser, "parse error after typename");
4731 /* an opening paren now starts the parameter-list of a function
4732 * this is where original-QC has parameter lists.
4733 * We allow a single parameter list here.
4734 * Much like fteqcc we don't allow `float()() x`
4736 if (parser->tok == '(') {
4737 var = parse_parameter_list(parser, var);
4742 /* store the base if requested */
4744 *storebase = ast_value_copy(var);
4746 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4747 tmp->expression.next = (ast_expression*)*storebase;
4752 /* there may be a name now */
4753 if (parser->tok == TOKEN_IDENT) {
4754 name = util_strdup(parser_tokval(parser));
4756 if (!parser_next(parser)) {
4759 parseerror(parser, "error after variable or field declaration");
4764 /* now this may be an array */
4765 if (parser->tok == '[') {
4767 var = parse_arraysize(parser, var);
4769 if (name) mem_d(name);
4774 /* This is the point where we can turn it into a field */
4776 /* turn it into a field if desired */
4777 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4778 tmp->expression.next = (ast_expression*)var;
4782 /* now there may be function parens again */
4783 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4784 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4785 if (parser->tok == '(' && wasarray)
4786 parseerror(parser, "arrays as part of a return type is not supported");
4787 while (parser->tok == '(') {
4788 var = parse_parameter_list(parser, var);
4790 if (name) mem_d(name);
4795 /* finally name it */
4797 if (!ast_value_set_name(var, name)) {
4800 parseerror(parser, "internal error: failed to set name");
4803 /* free the name, ast_value_set_name duplicates */
4810 static bool parse_typedef(parser_t *parser)
4812 ast_value *typevar, *oldtype;
4813 ast_expression *old;
4815 typevar = parse_typename(parser, NULL, NULL);
4820 if ( (old = parser_find_var(parser, typevar->name)) ) {
4821 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4822 " -> `%s` has been declared here: %s:%i",
4823 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4824 ast_delete(typevar);
4828 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4829 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4830 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4831 ast_delete(typevar);
4835 vec_push(parser->_typedefs, typevar);
4836 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4838 if (parser->tok != ';') {
4839 parseerror(parser, "expected semicolon after typedef");
4842 if (!parser_next(parser)) {
4843 parseerror(parser, "parse error after typedef");
4850 static const char *cvq_to_str(int cvq) {
4852 case CV_NONE: return "none";
4853 case CV_VAR: return "`var`";
4854 case CV_CONST: return "`const`";
4855 default: return "<INVALID>";
4859 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4862 if (proto->cvq != var->cvq) {
4863 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4864 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4865 parser->tok == '='))
4867 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4868 "`%s` declared with different qualifiers: %s\n"
4869 " -> previous declaration here: %s:%i uses %s",
4870 var->name, cvq_to_str(var->cvq),
4871 ast_ctx(proto).file, ast_ctx(proto).line,
4872 cvq_to_str(proto->cvq));
4875 av = (var ->expression.flags & AST_FLAG_NORETURN);
4876 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4878 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4879 "`%s` declared with different attributes%s\n"
4880 " -> previous declaration here: %s:%i",
4881 var->name, (av ? ": noreturn" : ""),
4882 ast_ctx(proto).file, ast_ctx(proto).line,
4883 (ao ? ": noreturn" : ""));
4888 static bool create_array_accessors(parser_t *parser, ast_value *var)
4891 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4892 if (!parser_create_array_setter(parser, var, name))
4894 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4895 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4900 static bool parse_array(parser_t *parser, ast_value *array)
4903 if (array->initlist) {
4904 parseerror(parser, "array already initialized elsewhere");
4907 if (!parser_next(parser)) {
4908 parseerror(parser, "parse error in array initializer");
4912 while (parser->tok != '}') {
4913 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4916 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4918 parseerror(parser, "initializing element must be a compile time constant");
4921 vec_push(array->initlist, v->constval);
4922 if (v->expression.vtype == TYPE_STRING) {
4923 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4927 if (parser->tok == '}')
4929 if (parser->tok != ',' || !parser_next(parser)) {
4930 parseerror(parser, "expected comma or '}' in element list");
4934 if (!parser_next(parser) || parser->tok != ';') {
4935 parseerror(parser, "expected semicolon after initializer, got %s");
4939 if (!parser_next(parser)) {
4940 parseerror(parser, "parse error after initializer");
4945 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4946 if (array->expression.count != (size_t)-1) {
4947 parseerror(parser, "array `%s' has already been initialized with %u elements",
4948 array->name, (unsigned)array->expression.count);
4950 array->expression.count = vec_size(array->initlist);
4951 if (!create_array_accessors(parser, array))
4957 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)
4961 ast_expression *old;
4965 ast_value *basetype = NULL;
4967 bool isparam = false;
4968 bool isvector = false;
4969 bool cleanvar = true;
4970 bool wasarray = false;
4972 ast_member *me[3] = { NULL, NULL, NULL };
4974 if (!localblock && is_static)
4975 parseerror(parser, "`static` qualifier is not supported in global scope");
4977 /* get the first complete variable */
4978 var = parse_typename(parser, &basetype, cached_typedef);
4981 ast_delete(basetype);
4989 /* Part 0: finish the type */
4990 if (parser->tok == '(') {
4991 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4992 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4993 var = parse_parameter_list(parser, var);
4999 /* we only allow 1-dimensional arrays */
5000 if (parser->tok == '[') {
5002 var = parse_arraysize(parser, var);
5008 if (parser->tok == '(' && wasarray) {
5009 parseerror(parser, "arrays as part of a return type is not supported");
5010 /* we'll still parse the type completely for now */
5012 /* for functions returning functions */
5013 while (parser->tok == '(') {
5014 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5015 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5016 var = parse_parameter_list(parser, var);
5023 var->cvq = qualifier;
5024 var->expression.flags |= qflags;
5027 * store the vstring back to var for alias and
5028 * deprecation messages.
5030 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5031 var->expression.flags & AST_FLAG_ALIAS)
5032 var->desc = vstring;
5035 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5036 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5037 * is then filled with the previous definition and the parameter-names replaced.
5039 if (!strcmp(var->name, "nil")) {
5040 if (OPTS_FLAG(UNTYPED_NIL)) {
5041 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5042 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5044 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5047 /* Deal with end_sys_ vars */
5049 if (!strcmp(var->name, "end_sys_globals")) {
5051 parser->crc_globals = vec_size(parser->globals);
5054 else if (!strcmp(var->name, "end_sys_fields")) {
5056 parser->crc_fields = vec_size(parser->fields);
5059 if (was_end && var->expression.vtype == TYPE_FIELD) {
5060 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5061 "global '%s' hint should not be a field",
5062 parser_tokval(parser)))
5069 if (!nofields && var->expression.vtype == TYPE_FIELD)
5071 /* deal with field declarations */
5072 old = parser_find_field(parser, var->name);
5074 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5075 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5084 parseerror(parser, "field `%s` already declared here: %s:%i",
5085 var->name, ast_ctx(old).file, ast_ctx(old).line);
5090 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5091 (old = parser_find_global(parser, var->name)))
5093 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5094 parseerror(parser, "field `%s` already declared here: %s:%i",
5095 var->name, ast_ctx(old).file, ast_ctx(old).line);
5102 /* deal with other globals */
5103 old = parser_find_global(parser, var->name);
5104 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5106 /* This is a function which had a prototype */
5107 if (!ast_istype(old, ast_value)) {
5108 parseerror(parser, "internal error: prototype is not an ast_value");
5112 proto = (ast_value*)old;
5113 proto->desc = var->desc;
5114 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5115 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5117 ast_ctx(proto).file, ast_ctx(proto).line);
5121 /* we need the new parameter-names */
5122 for (i = 0; i < vec_size(proto->expression.params); ++i)
5123 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5124 if (!parser_check_qualifiers(parser, var, proto)) {
5131 proto->expression.flags |= var->expression.flags;
5139 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5140 "global `%s` already declared here: %s:%i",
5141 var->name, ast_ctx(old).file, ast_ctx(old).line))
5146 proto = (ast_value*)old;
5147 if (!ast_istype(old, ast_value)) {
5148 parseerror(parser, "internal error: not an ast_value");
5153 if (!parser_check_qualifiers(parser, var, proto)) {
5158 proto->expression.flags |= var->expression.flags;
5162 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5163 (old = parser_find_field(parser, var->name)))
5165 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5166 parseerror(parser, "global `%s` already declared here: %s:%i",
5167 var->name, ast_ctx(old).file, ast_ctx(old).line);
5174 else /* it's not a global */
5176 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5177 if (old && !isparam) {
5178 parseerror(parser, "local `%s` already declared here: %s:%i",
5179 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5183 old = parser_find_local(parser, var->name, 0, &isparam);
5184 if (old && isparam) {
5185 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5186 "local `%s` is shadowing a parameter", var->name))
5188 parseerror(parser, "local `%s` already declared here: %s:%i",
5189 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5193 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5195 if (ast_istype(old, ast_value))
5196 var = (ast_value*)old;
5205 /* in a noref section we simply bump the usecount */
5206 if (noref || parser->noref)
5210 * Create the global/local, and deal with vector types.
5213 if (var->expression.vtype == TYPE_VECTOR)
5215 else if (var->expression.vtype == TYPE_FIELD &&
5216 var->expression.next->vtype == TYPE_VECTOR)
5220 if (!create_vector_members(var, me)) {
5227 /* deal with global variables, fields, functions */
5228 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5229 var->isfield = true;
5230 vec_push(parser->fields, (ast_expression*)var);
5231 util_htset(parser->htfields, var->name, var);
5233 for (i = 0; i < 3; ++i) {
5234 vec_push(parser->fields, (ast_expression*)me[i]);
5235 util_htset(parser->htfields, me[i]->name, me[i]);
5240 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5241 parser_addglobal(parser, var->name, (ast_expression*)var);
5243 for (i = 0; i < 3; ++i) {
5244 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5248 ast_expression *find = parser_find_global(parser, var->desc);
5251 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5255 if (var->expression.vtype != find->vtype) {
5259 ast_type_to_string(find, ty1, sizeof(ty1));
5260 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5262 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5269 * add alias to aliases table and to corrector
5270 * so corrections can apply for aliases as well.
5272 util_htset(parser->aliases, var->name, find);
5275 * add to corrector so corrections can work
5276 * even for aliases too.
5279 vec_last(parser->correct_variables),
5280 &vec_last(parser->correct_variables_score),
5284 /* generate aliases for vector components */
5288 util_asprintf(&buffer[0], "%s_x", var->desc);
5289 util_asprintf(&buffer[1], "%s_y", var->desc);
5290 util_asprintf(&buffer[2], "%s_z", var->desc);
5292 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5293 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5294 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5301 * add to corrector so corrections can work
5302 * even for aliases too.
5305 vec_last(parser->correct_variables),
5306 &vec_last(parser->correct_variables_score),
5310 vec_last(parser->correct_variables),
5311 &vec_last(parser->correct_variables_score),
5315 vec_last(parser->correct_variables),
5316 &vec_last(parser->correct_variables_score),
5324 /* a static adds itself to be generated like any other global
5325 * but is added to the local namespace instead
5327 char *defname = NULL;
5328 size_t prefix_len, ln;
5330 ln = strlen(parser->function->name);
5331 vec_append(defname, ln, parser->function->name);
5333 vec_append(defname, 2, "::");
5334 /* remember the length up to here */
5335 prefix_len = vec_size(defname);
5337 /* Add it to the local scope */
5338 util_htset(vec_last(parser->variables), var->name, (void*)var);
5342 vec_last(parser->correct_variables),
5343 &vec_last(parser->correct_variables_score),
5347 /* now rename the global */
5348 ln = strlen(var->name);
5349 vec_append(defname, ln, var->name);
5350 ast_value_set_name(var, defname);
5352 /* push it to the to-be-generated globals */
5353 vec_push(parser->globals, (ast_expression*)var);
5355 /* same game for the vector members */
5357 for (i = 0; i < 3; ++i) {
5358 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5362 vec_last(parser->correct_variables),
5363 &vec_last(parser->correct_variables_score),
5367 vec_shrinkto(defname, prefix_len);
5368 ln = strlen(me[i]->name);
5369 vec_append(defname, ln, me[i]->name);
5370 ast_member_set_name(me[i], defname);
5372 vec_push(parser->globals, (ast_expression*)me[i]);
5377 vec_push(localblock->locals, var);
5378 parser_addlocal(parser, var->name, (ast_expression*)var);
5380 for (i = 0; i < 3; ++i) {
5381 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5382 ast_block_collect(localblock, (ast_expression*)me[i]);
5388 me[0] = me[1] = me[2] = NULL;
5393 if (var->expression.vtype == TYPE_ARRAY) {
5394 if (var->expression.count != (size_t)-1) {
5395 if (!create_array_accessors(parser, var))
5399 else if (!localblock && !nofields &&
5400 var->expression.vtype == TYPE_FIELD &&
5401 var->expression.next->vtype == TYPE_ARRAY)
5404 ast_expression *telem;
5406 ast_value *array = (ast_value*)var->expression.next;
5408 if (!ast_istype(var->expression.next, ast_value)) {
5409 parseerror(parser, "internal error: field element type must be an ast_value");
5413 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5414 if (!parser_create_array_field_setter(parser, array, name))
5417 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5418 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5419 tfield->expression.next = telem;
5420 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5421 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5429 if (parser->tok == ';') {
5430 ast_delete(basetype);
5431 if (!parser_next(parser)) {
5432 parseerror(parser, "error after variable declaration");
5438 if (parser->tok == ',')
5442 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5445 parseerror(parser, "missing comma or semicolon while parsing variables");
5449 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5450 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5451 "initializing expression turns variable `%s` into a constant in this standard",
5458 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5459 if (parser->tok != '=') {
5460 if (!strcmp(parser_tokval(parser), "break")) {
5461 if (!parser_next(parser)) {
5462 parseerror(parser, "error parsing break definition");
5465 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5467 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5472 if (!parser_next(parser)) {
5473 parseerror(parser, "error parsing initializer");
5477 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5478 parseerror(parser, "expected '=' before function body in this standard");
5481 if (parser->tok == '#') {
5482 ast_function *func = NULL;
5483 ast_value *number = NULL;
5489 parseerror(parser, "cannot declare builtins within functions");
5492 if (var->expression.vtype != TYPE_FUNCTION) {
5493 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5496 if (!parser_next(parser)) {
5497 parseerror(parser, "expected builtin number");
5501 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5502 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5504 parseerror(parser, "builtin number expected");
5507 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5510 parseerror(parser, "builtin number must be a compile time constant");
5513 if (number->expression.vtype == TYPE_INTEGER)
5514 builtin_num = number->constval.vint;
5515 else if (number->expression.vtype == TYPE_FLOAT)
5516 builtin_num = number->constval.vfloat;
5519 parseerror(parser, "builtin number must be an integer constant");
5524 fractional = modff(builtin_num, &integral);
5525 if (builtin_num < 0 || fractional != 0) {
5526 parseerror(parser, "builtin number must be an integer greater than zero");
5530 /* we only want the integral part anyways */
5531 builtin_num = integral;
5532 } else if (parser->tok == TOKEN_INTCONST) {
5533 builtin_num = parser_token(parser)->constval.i;
5535 parseerror(parser, "builtin number must be a compile time constant");
5539 if (var->hasvalue) {
5540 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5541 "builtin `%s` has already been defined\n"
5542 " -> previous declaration here: %s:%i",
5543 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5547 func = ast_function_new(ast_ctx(var), var->name, var);
5549 parseerror(parser, "failed to allocate function for `%s`", var->name);
5552 vec_push(parser->functions, func);
5554 func->builtin = -builtin_num-1;
5557 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5558 ? (parser->tok != ',' && parser->tok != ';')
5559 : (!parser_next(parser)))
5561 parseerror(parser, "expected comma or semicolon");
5563 ast_function_delete(func);
5564 var->constval.vfunc = NULL;
5568 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5571 /* Note that fteqcc and most others don't even *have*
5572 * local arrays, so this is not a high priority.
5574 parseerror(parser, "TODO: initializers for local arrays");
5578 var->hasvalue = true;
5579 if (!parse_array(parser, var))
5582 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5585 parseerror(parser, "cannot declare functions within functions");
5590 ast_ctx(proto) = parser_ctx(parser);
5592 if (!parse_function_body(parser, var))
5594 ast_delete(basetype);
5595 for (i = 0; i < vec_size(parser->gotos); ++i)
5596 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5597 vec_free(parser->gotos);
5598 vec_free(parser->labels);
5601 ast_expression *cexp;
5604 cexp = parse_expression_leave(parser, true, false, false);
5609 cval = (ast_value*)cexp;
5610 if (cval != parser->nil &&
5611 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5614 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5618 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5619 qualifier != CV_VAR)
5621 var->cvq = CV_CONST;
5623 if (cval == parser->nil)
5624 var->expression.flags |= AST_FLAG_INITIALIZED;
5627 var->hasvalue = true;
5628 if (cval->expression.vtype == TYPE_STRING)
5629 var->constval.vstring = parser_strdup(cval->constval.vstring);
5630 else if (cval->expression.vtype == TYPE_FIELD)
5631 var->constval.vfield = cval;
5633 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5639 shunt sy = { NULL, NULL, NULL, NULL };
5642 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5643 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5644 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5645 if (!parser_sy_apply_operator(parser, &sy))
5648 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5649 parseerror(parser, "internal error: leaked operands");
5650 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5661 if (parser->tok == ',') {
5662 if (!parser_next(parser)) {
5663 parseerror(parser, "expected another variable");
5667 if (parser->tok != TOKEN_IDENT) {
5668 parseerror(parser, "expected another variable");
5671 var = ast_value_copy(basetype);
5673 ast_value_set_name(var, parser_tokval(parser));
5674 if (!parser_next(parser)) {
5675 parseerror(parser, "error parsing variable declaration");
5681 if (parser->tok != ';') {
5682 parseerror(parser, "missing semicolon after variables");
5686 if (!parser_next(parser)) {
5687 parseerror(parser, "parse error after variable declaration");
5691 ast_delete(basetype);
5695 if (cleanvar && var)
5697 ast_delete(basetype);
5701 ast_delete(basetype);
5702 if (cleanvar && var)
5704 if (me[0]) ast_member_delete(me[0]);
5705 if (me[1]) ast_member_delete(me[1]);
5706 if (me[2]) ast_member_delete(me[2]);
5710 static bool parser_global_statement(parser_t *parser)
5714 bool is_static = false;
5715 uint32_t qflags = 0;
5716 ast_value *istype = NULL;
5717 char *vstring = NULL;
5719 if (parser->tok == TOKEN_IDENT)
5720 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5722 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5724 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5726 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5728 if (cvq == CV_WRONG)
5730 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5732 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5734 return parse_enum(parser);
5736 else if (parser->tok == TOKEN_KEYWORD)
5738 if (!strcmp(parser_tokval(parser), "typedef")) {
5739 if (!parser_next(parser)) {
5740 parseerror(parser, "expected type definition after 'typedef'");
5743 return parse_typedef(parser);
5745 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5748 else if (parser->tok == '#')
5750 return parse_pragma(parser);
5752 else if (parser->tok == '$')
5754 if (!parser_next(parser)) {
5755 parseerror(parser, "parse error");
5761 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5767 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5769 return util_crc16(old, str, strlen(str));
5772 static void progdefs_crc_file(const char *str)
5774 /* write to progdefs.h here */
5778 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5780 old = progdefs_crc_sum(old, str);
5781 progdefs_crc_file(str);
5785 static void generate_checksum(parser_t *parser, ir_builder *ir)
5787 uint16_t crc = 0xFFFF;
5791 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5792 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5794 progdefs_crc_file("\tint\tpad;\n");
5795 progdefs_crc_file("\tint\tofs_return[3];\n");
5796 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5797 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5798 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5799 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5800 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5801 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5802 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5803 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5805 for (i = 0; i < parser->crc_globals; ++i) {
5806 if (!ast_istype(parser->globals[i], ast_value))
5808 value = (ast_value*)(parser->globals[i]);
5809 switch (value->expression.vtype) {
5810 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5811 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5812 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5813 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5815 crc = progdefs_crc_both(crc, "\tint\t");
5818 crc = progdefs_crc_both(crc, value->name);
5819 crc = progdefs_crc_both(crc, ";\n");
5821 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5822 for (i = 0; i < parser->crc_fields; ++i) {
5823 if (!ast_istype(parser->fields[i], ast_value))
5825 value = (ast_value*)(parser->fields[i]);
5826 switch (value->expression.next->vtype) {
5827 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5828 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5829 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5830 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5832 crc = progdefs_crc_both(crc, "\tint\t");
5835 crc = progdefs_crc_both(crc, value->name);
5836 crc = progdefs_crc_both(crc, ";\n");
5838 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5839 ir->code->crc = crc;
5842 parser_t *parser_create()
5845 lex_ctx_t empty_ctx;
5848 parser = (parser_t*)mem_a(sizeof(parser_t));
5852 memset(parser, 0, sizeof(*parser));
5854 for (i = 0; i < operator_count; ++i) {
5855 if (operators[i].id == opid1('=')) {
5856 parser->assign_op = operators+i;
5860 if (!parser->assign_op) {
5861 printf("internal error: initializing parser: failed to find assign operator\n");
5866 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5867 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5868 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5869 vec_push(parser->_blocktypedefs, 0);
5871 parser->aliases = util_htnew(PARSER_HT_SIZE);
5874 vec_push(parser->correct_variables, correct_trie_new());
5875 vec_push(parser->correct_variables_score, NULL);
5877 empty_ctx.file = "<internal>";
5879 empty_ctx.column = 0;
5880 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5881 parser->nil->cvq = CV_CONST;
5882 if (OPTS_FLAG(UNTYPED_NIL))
5883 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5885 parser->max_param_count = 1;
5887 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5888 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5889 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5891 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5892 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5893 parser->reserved_version->cvq = CV_CONST;
5894 parser->reserved_version->hasvalue = true;
5895 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5896 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5898 parser->reserved_version = NULL;
5901 parser->fold = fold_init (parser);
5902 parser->intrin = intrin_init(parser);
5906 static bool parser_compile(parser_t *parser)
5908 /* initial lexer/parser state */
5909 parser->lex->flags.noops = true;
5911 if (parser_next(parser))
5913 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5915 if (!parser_global_statement(parser)) {
5916 if (parser->tok == TOKEN_EOF)
5917 parseerror(parser, "unexpected end of file");
5918 else if (compile_errors)
5919 parseerror(parser, "there have been errors, bailing out");
5920 lex_close(parser->lex);
5926 parseerror(parser, "parse error");
5927 lex_close(parser->lex);
5932 lex_close(parser->lex);
5935 return !compile_errors;
5938 bool parser_compile_file(parser_t *parser, const char *filename)
5940 parser->lex = lex_open(filename);
5942 con_err("failed to open file \"%s\"\n", filename);
5945 return parser_compile(parser);
5948 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5950 parser->lex = lex_open_string(str, len, name);
5952 con_err("failed to create lexer for string \"%s\"\n", name);
5955 return parser_compile(parser);
5958 static void parser_remove_ast(parser_t *parser)
5961 if (parser->ast_cleaned)
5963 parser->ast_cleaned = true;
5964 for (i = 0; i < vec_size(parser->accessors); ++i) {
5965 ast_delete(parser->accessors[i]->constval.vfunc);
5966 parser->accessors[i]->constval.vfunc = NULL;
5967 ast_delete(parser->accessors[i]);
5969 for (i = 0; i < vec_size(parser->functions); ++i) {
5970 ast_delete(parser->functions[i]);
5972 for (i = 0; i < vec_size(parser->fields); ++i) {
5973 ast_delete(parser->fields[i]);
5975 for (i = 0; i < vec_size(parser->globals); ++i) {
5976 ast_delete(parser->globals[i]);
5978 vec_free(parser->accessors);
5979 vec_free(parser->functions);
5980 vec_free(parser->globals);
5981 vec_free(parser->fields);
5983 for (i = 0; i < vec_size(parser->variables); ++i)
5984 util_htdel(parser->variables[i]);
5985 vec_free(parser->variables);
5986 vec_free(parser->_blocklocals);
5987 vec_free(parser->_locals);
5990 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5991 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5993 vec_free(parser->correct_variables);
5994 vec_free(parser->correct_variables_score);
5996 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5997 ast_delete(parser->_typedefs[i]);
5998 vec_free(parser->_typedefs);
5999 for (i = 0; i < vec_size(parser->typedefs); ++i)
6000 util_htdel(parser->typedefs[i]);
6001 vec_free(parser->typedefs);
6002 vec_free(parser->_blocktypedefs);
6004 vec_free(parser->_block_ctx);
6006 vec_free(parser->labels);
6007 vec_free(parser->gotos);
6008 vec_free(parser->breaks);
6009 vec_free(parser->continues);
6011 ast_value_delete(parser->nil);
6013 ast_value_delete(parser->const_vec[0]);
6014 ast_value_delete(parser->const_vec[1]);
6015 ast_value_delete(parser->const_vec[2]);
6017 if (parser->reserved_version)
6018 ast_value_delete(parser->reserved_version);
6020 util_htdel(parser->aliases);
6021 fold_cleanup(parser->fold);
6022 intrin_cleanup(parser->intrin);
6025 void parser_cleanup(parser_t *parser)
6027 parser_remove_ast(parser);
6031 bool parser_finish(parser_t *parser, const char *output)
6037 if (compile_errors) {
6038 con_out("*** there were compile errors\n");
6042 ir = ir_builder_new("gmqcc_out");
6044 con_out("failed to allocate builder\n");
6048 for (i = 0; i < vec_size(parser->fields); ++i) {
6051 if (!ast_istype(parser->fields[i], ast_value))
6053 field = (ast_value*)parser->fields[i];
6054 hasvalue = field->hasvalue;
6055 field->hasvalue = false;
6056 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6057 con_out("failed to generate field %s\n", field->name);
6058 ir_builder_delete(ir);
6063 ast_expression *subtype;
6064 field->hasvalue = true;
6065 subtype = field->expression.next;
6066 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6067 if (subtype->vtype == TYPE_FIELD)
6068 ifld->fieldtype = subtype->next->vtype;
6069 else if (subtype->vtype == TYPE_FUNCTION)
6070 ifld->outtype = subtype->next->vtype;
6071 (void)!ir_value_set_field(field->ir_v, ifld);
6074 for (i = 0; i < vec_size(parser->globals); ++i) {
6076 if (!ast_istype(parser->globals[i], ast_value))
6078 asvalue = (ast_value*)(parser->globals[i]);
6079 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6080 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6081 "unused global: `%s`", asvalue->name);
6083 if (!ast_global_codegen(asvalue, ir, false)) {
6084 con_out("failed to generate global %s\n", asvalue->name);
6085 ir_builder_delete(ir);
6089 /* Build function vararg accessor ast tree now before generating
6090 * immediates, because the accessors may add new immediates
6092 for (i = 0; i < vec_size(parser->functions); ++i) {
6093 ast_function *f = parser->functions[i];
6095 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6096 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6097 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6098 con_out("failed to generate vararg setter for %s\n", f->name);
6099 ir_builder_delete(ir);
6102 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6103 con_out("failed to generate vararg getter for %s\n", f->name);
6104 ir_builder_delete(ir);
6108 ast_delete(f->varargs);
6113 /* Now we can generate immediates */
6114 if (!fold_generate(parser->fold, ir))
6117 for (i = 0; i < vec_size(parser->globals); ++i) {
6119 if (!ast_istype(parser->globals[i], ast_value))
6121 asvalue = (ast_value*)(parser->globals[i]);
6122 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6124 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6125 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6126 "uninitialized constant: `%s`",
6128 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6129 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6130 "uninitialized global: `%s`",
6133 if (!ast_generate_accessors(asvalue, ir)) {
6134 ir_builder_delete(ir);
6138 for (i = 0; i < vec_size(parser->fields); ++i) {
6140 asvalue = (ast_value*)(parser->fields[i]->next);
6142 if (!ast_istype((ast_expression*)asvalue, ast_value))
6144 if (asvalue->expression.vtype != TYPE_ARRAY)
6146 if (!ast_generate_accessors(asvalue, ir)) {
6147 ir_builder_delete(ir);
6151 if (parser->reserved_version &&
6152 !ast_global_codegen(parser->reserved_version, ir, false))
6154 con_out("failed to generate reserved::version");
6155 ir_builder_delete(ir);
6158 for (i = 0; i < vec_size(parser->functions); ++i) {
6159 ast_function *f = parser->functions[i];
6160 if (!ast_function_codegen(f, ir)) {
6161 con_out("failed to generate function %s\n", f->name);
6162 ir_builder_delete(ir);
6167 generate_checksum(parser, ir);
6169 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6170 ir_builder_dump(ir, con_out);
6171 for (i = 0; i < vec_size(parser->functions); ++i) {
6172 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6173 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6174 ir_builder_delete(ir);
6178 parser_remove_ast(parser);
6180 if (compile_Werrors) {
6181 con_out("*** there were warnings treated as errors\n");
6182 compile_show_werrors();
6187 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6188 ir_builder_dump(ir, con_out);
6190 if (!ir_builder_generate(ir, output)) {
6191 con_out("*** failed to generate output file\n");
6192 ir_builder_delete(ir);
6196 ir_builder_delete(ir);