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;
1123 fid = vec_last(sy->ops).off;
1124 vec_shrinkby(sy->ops, 1);
1126 /* out[fid] is the function
1127 * everything above is parameters...
1129 if (!vec_size(sy->argc)) {
1130 parseerror(parser, "internal error: no argument counter available");
1134 paramcount = vec_last(sy->argc);
1137 if (vec_size(sy->out) < fid) {
1138 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1139 (unsigned long)vec_size(sy->out),
1141 (unsigned long)paramcount);
1146 * TODO handle this at the intrinsic level with an ast_intrinsic
1149 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1151 if (fid+2 != vec_size(sy->out) ||
1152 vec_last(sy->out).block)
1154 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1157 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1158 ast_unref(vec_last(sy->out).out);
1159 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1160 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1161 vec_shrinkby(sy->out, 1);
1164 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1169 if (fid+1 < vec_size(sy->out))
1172 if (fid+1 + paramcount != vec_size(sy->out)) {
1173 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1174 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1178 for (i = 0; i < paramcount; ++i)
1179 vec_push(call->params, sy->out[fid+1 + i].out);
1180 vec_shrinkby(sy->out, paramcount);
1181 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1182 if (parser->max_param_count < paramcount)
1183 parser->max_param_count = paramcount;
1185 if (ast_istype(fun, ast_value)) {
1186 funval = (ast_value*)fun;
1187 if ((fun->flags & AST_FLAG_VARIADIC) &&
1188 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1190 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1194 /* overwrite fid, the function, with a call */
1195 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1197 if (fun->vtype != TYPE_FUNCTION) {
1198 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1203 parseerror(parser, "could not determine function return type");
1206 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1208 if (fun->flags & AST_FLAG_DEPRECATED) {
1210 return !parsewarning(parser, WARN_DEPRECATED,
1211 "call to function (which is marked deprecated)\n",
1212 "-> it has been declared here: %s:%i",
1213 ast_ctx(fun).file, ast_ctx(fun).line);
1216 return !parsewarning(parser, WARN_DEPRECATED,
1217 "call to `%s` (which is marked deprecated)\n"
1218 "-> `%s` declared here: %s:%i",
1219 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1221 return !parsewarning(parser, WARN_DEPRECATED,
1222 "call to `%s` (deprecated: %s)\n"
1223 "-> `%s` declared here: %s:%i",
1224 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1228 if (vec_size(fun->params) != paramcount &&
1229 !((fun->flags & AST_FLAG_VARIADIC) &&
1230 vec_size(fun->params) < paramcount))
1232 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1234 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1235 "too %s parameters for call to %s: expected %i, got %i\n"
1236 " -> `%s` has been declared here: %s:%i",
1237 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1238 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1240 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1241 "too %s parameters for function call: expected %i, got %i\n"
1242 " -> it has been declared here: %s:%i",
1243 fewmany, (int)vec_size(fun->params), (int)paramcount,
1244 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1251 static bool parser_close_paren(parser_t *parser, shunt *sy)
1253 if (!vec_size(sy->ops)) {
1254 parseerror(parser, "unmatched closing paren");
1258 while (vec_size(sy->ops)) {
1259 if (vec_last(sy->ops).isparen) {
1260 if (vec_last(sy->paren) == PAREN_FUNC) {
1262 if (!parser_close_call(parser, sy))
1266 if (vec_last(sy->paren) == PAREN_EXPR) {
1268 if (!vec_size(sy->out)) {
1269 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1270 vec_shrinkby(sy->ops, 1);
1273 vec_shrinkby(sy->ops, 1);
1276 if (vec_last(sy->paren) == PAREN_INDEX) {
1278 /* pop off the parenthesis */
1279 vec_shrinkby(sy->ops, 1);
1280 /* then apply the index operator */
1281 if (!parser_sy_apply_operator(parser, sy))
1285 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1286 vec_last(sy->paren) = PAREN_TERNARY2;
1287 /* pop off the parenthesis */
1288 vec_shrinkby(sy->ops, 1);
1291 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1294 if (!parser_sy_apply_operator(parser, sy))
1300 static void parser_reclassify_token(parser_t *parser)
1303 if (parser->tok >= TOKEN_START)
1305 for (i = 0; i < operator_count; ++i) {
1306 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1307 parser->tok = TOKEN_OPERATOR;
1313 static ast_expression* parse_vararg_do(parser_t *parser)
1315 ast_expression *idx, *out;
1317 ast_value *funtype = parser->function->vtype;
1318 lex_ctx_t ctx = parser_ctx(parser);
1320 if (!parser->function->varargs) {
1321 parseerror(parser, "function has no variable argument list");
1325 if (!parser_next(parser) || parser->tok != '(') {
1326 parseerror(parser, "expected parameter index and type in parenthesis");
1329 if (!parser_next(parser)) {
1330 parseerror(parser, "error parsing parameter index");
1334 idx = parse_expression_leave(parser, true, false, false);
1338 if (parser->tok != ',') {
1339 if (parser->tok != ')') {
1341 parseerror(parser, "expected comma after parameter index");
1344 /* vararg piping: ...(start) */
1345 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1349 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1351 parseerror(parser, "expected typename for vararg");
1355 typevar = parse_typename(parser, NULL, NULL);
1361 if (parser->tok != ')') {
1363 ast_delete(typevar);
1364 parseerror(parser, "expected closing paren");
1368 if (funtype->expression.varparam &&
1369 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1373 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1374 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1375 compile_error(ast_ctx(typevar),
1376 "function was declared to take varargs of type `%s`, requested type is: %s",
1380 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1381 ast_type_adopt(out, typevar);
1382 ast_delete(typevar);
1386 static ast_expression* parse_vararg(parser_t *parser)
1388 bool old_noops = parser->lex->flags.noops;
1390 ast_expression *out;
1392 parser->lex->flags.noops = true;
1393 out = parse_vararg_do(parser);
1395 parser->lex->flags.noops = old_noops;
1399 /* not to be exposed */
1400 bool ftepp_predef_exists(const char *name);
1401 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1403 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1404 parser->tok == TOKEN_IDENT &&
1405 !strcmp(parser_tokval(parser), "_"))
1407 /* a translatable string */
1410 parser->lex->flags.noops = true;
1411 if (!parser_next(parser) || parser->tok != '(') {
1412 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1415 parser->lex->flags.noops = false;
1416 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1417 parseerror(parser, "expected a constant string in translatable-string extension");
1420 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1423 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1425 if (!parser_next(parser) || parser->tok != ')') {
1426 parseerror(parser, "expected closing paren after translatable string");
1431 else if (parser->tok == TOKEN_DOTS)
1434 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1435 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1438 va = parse_vararg(parser);
1441 vec_push(sy->out, syexp(parser_ctx(parser), va));
1444 else if (parser->tok == TOKEN_FLOATCONST) {
1445 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1448 vec_push(sy->out, syexp(parser_ctx(parser), val));
1451 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1452 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1455 vec_push(sy->out, syexp(parser_ctx(parser), val));
1458 else if (parser->tok == TOKEN_STRINGCONST) {
1459 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1462 vec_push(sy->out, syexp(parser_ctx(parser), val));
1465 else if (parser->tok == TOKEN_VECTORCONST) {
1466 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1469 vec_push(sy->out, syexp(parser_ctx(parser), val));
1472 else if (parser->tok == TOKEN_IDENT)
1474 const char *ctoken = parser_tokval(parser);
1475 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1476 ast_expression *var;
1477 /* a_vector.{x,y,z} */
1478 if (!vec_size(sy->ops) ||
1479 !vec_last(sy->ops).etype ||
1480 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1482 /* When adding more intrinsics, fix the above condition */
1485 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1487 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1489 var = parser_find_var(parser, parser_tokval(parser));
1491 var = parser_find_field(parser, parser_tokval(parser));
1493 if (!var && with_labels) {
1494 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1496 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1497 var = (ast_expression*)lbl;
1498 vec_push(parser->labels, lbl);
1501 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1502 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1505 * now we try for the real intrinsic hashtable. If the string
1506 * begins with __builtin, we simply skip past it, otherwise we
1507 * use the identifier as is.
1509 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1510 var = intrin_func(parser->intrin, parser_tokval(parser));
1514 char *correct = NULL;
1518 * sometimes people use preprocessing predefs without enabling them
1519 * i've done this thousands of times already myself. Lets check for
1520 * it in the predef table. And diagnose it better :)
1522 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1523 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1528 * TODO: determine the best score for the identifier: be it
1529 * a variable, a field.
1531 * We should also consider adding correction tables for
1532 * other things as well.
1534 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1536 correct_init(&corr);
1538 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1539 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1540 if (strcmp(correct, parser_tokval(parser))) {
1547 correct_free(&corr);
1550 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1555 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1561 if (ast_istype(var, ast_value)) {
1562 ((ast_value*)var)->uses++;
1564 else if (ast_istype(var, ast_member)) {
1565 ast_member *mem = (ast_member*)var;
1566 if (ast_istype(mem->owner, ast_value))
1567 ((ast_value*)(mem->owner))->uses++;
1570 vec_push(sy->out, syexp(parser_ctx(parser), var));
1573 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1577 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1579 ast_expression *expr = NULL;
1582 bool wantop = false;
1583 /* only warn once about an assignment in a truth value because the current code
1584 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1586 bool warn_truthvalue = true;
1588 /* count the parens because an if starts with one, so the
1589 * end of a condition is an unmatched closing paren
1593 memset(&sy, 0, sizeof(sy));
1595 parser->lex->flags.noops = false;
1597 parser_reclassify_token(parser);
1601 if (parser->tok == TOKEN_TYPENAME) {
1602 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1606 if (parser->tok == TOKEN_OPERATOR)
1608 /* classify the operator */
1609 const oper_info *op;
1610 const oper_info *olast = NULL;
1612 for (o = 0; o < operator_count; ++o) {
1613 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1614 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1615 !strcmp(parser_tokval(parser), operators[o].op))
1620 if (o == operator_count) {
1621 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1624 /* found an operator */
1627 /* when declaring variables, a comma starts a new variable */
1628 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1629 /* fixup the token */
1634 /* a colon without a pervious question mark cannot be a ternary */
1635 if (!ternaries && op->id == opid2(':','?')) {
1640 if (op->id == opid1(',')) {
1641 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1642 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1646 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1647 olast = &operators[vec_last(sy.ops).etype-1];
1649 #define IsAssignOp(x) (\
1650 (x) == opid1('=') || \
1651 (x) == opid2('+','=') || \
1652 (x) == opid2('-','=') || \
1653 (x) == opid2('*','=') || \
1654 (x) == opid2('/','=') || \
1655 (x) == opid2('%','=') || \
1656 (x) == opid2('&','=') || \
1657 (x) == opid2('|','=') || \
1658 (x) == opid3('&','~','=') \
1660 if (warn_truthvalue) {
1661 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1662 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1663 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1666 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1667 warn_truthvalue = false;
1672 (op->prec < olast->prec) ||
1673 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1675 if (!parser_sy_apply_operator(parser, &sy))
1677 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1678 olast = &operators[vec_last(sy.ops).etype-1];
1683 if (op->id == opid1('(')) {
1685 size_t sycount = vec_size(sy.out);
1686 /* we expected an operator, this is the function-call operator */
1687 vec_push(sy.paren, PAREN_FUNC);
1688 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1689 vec_push(sy.argc, 0);
1691 vec_push(sy.paren, PAREN_EXPR);
1692 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1695 } else if (op->id == opid1('[')) {
1697 parseerror(parser, "unexpected array subscript");
1700 vec_push(sy.paren, PAREN_INDEX);
1701 /* push both the operator and the paren, this makes life easier */
1702 vec_push(sy.ops, syop(parser_ctx(parser), op));
1703 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1705 } else if (op->id == opid2('?',':')) {
1706 vec_push(sy.ops, syop(parser_ctx(parser), op));
1707 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1710 vec_push(sy.paren, PAREN_TERNARY1);
1711 } else if (op->id == opid2(':','?')) {
1712 if (!vec_size(sy.paren)) {
1713 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1716 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1717 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1720 if (!parser_close_paren(parser, &sy))
1722 vec_push(sy.ops, syop(parser_ctx(parser), op));
1726 vec_push(sy.ops, syop(parser_ctx(parser), op));
1727 wantop = !!(op->flags & OP_SUFFIX);
1730 else if (parser->tok == ')') {
1731 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1732 if (!parser_sy_apply_operator(parser, &sy))
1735 if (!vec_size(sy.paren))
1738 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1739 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1742 if (!parser_close_paren(parser, &sy))
1745 /* must be a function call without parameters */
1746 if (vec_last(sy.paren) != PAREN_FUNC) {
1747 parseerror(parser, "closing paren in invalid position");
1750 if (!parser_close_paren(parser, &sy))
1755 else if (parser->tok == '(') {
1756 parseerror(parser, "internal error: '(' should be classified as operator");
1759 else if (parser->tok == '[') {
1760 parseerror(parser, "internal error: '[' should be classified as operator");
1763 else if (parser->tok == ']') {
1764 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1765 if (!parser_sy_apply_operator(parser, &sy))
1768 if (!vec_size(sy.paren))
1770 if (vec_last(sy.paren) != PAREN_INDEX) {
1771 parseerror(parser, "mismatched parentheses, unexpected ']'");
1774 if (!parser_close_paren(parser, &sy))
1779 if (!parse_sya_operand(parser, &sy, with_labels))
1782 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1783 vec_last(sy.argc)++;
1788 /* in this case we might want to allow constant string concatenation */
1789 bool concatenated = false;
1790 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1791 ast_expression *lexpr = vec_last(sy.out).out;
1792 if (ast_istype(lexpr, ast_value)) {
1793 ast_value *last = (ast_value*)lexpr;
1794 if (last->isimm == true && last->cvq == CV_CONST &&
1795 last->hasvalue && last->expression.vtype == TYPE_STRING)
1797 char *newstr = NULL;
1798 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1799 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1801 concatenated = true;
1805 if (!concatenated) {
1806 parseerror(parser, "expected operator or end of statement");
1811 if (!parser_next(parser)) {
1814 if (parser->tok == ';' ||
1815 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1816 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1822 while (vec_size(sy.ops)) {
1823 if (!parser_sy_apply_operator(parser, &sy))
1827 parser->lex->flags.noops = true;
1828 if (vec_size(sy.out) != 1) {
1829 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
1832 expr = sy.out[0].out;
1835 if (vec_size(sy.paren)) {
1836 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1844 parser->lex->flags.noops = true;
1845 for (i = 0; i < vec_size(sy.out); ++i) {
1847 ast_unref(sy.out[i].out);
1856 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1858 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1861 if (parser->tok != ';') {
1862 parseerror(parser, "semicolon expected after expression");
1866 if (!parser_next(parser)) {
1873 static void parser_enterblock(parser_t *parser)
1875 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1876 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1877 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1878 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1879 vec_push(parser->_block_ctx, parser_ctx(parser));
1882 vec_push(parser->correct_variables, correct_trie_new());
1883 vec_push(parser->correct_variables_score, NULL);
1886 static bool parser_leaveblock(parser_t *parser)
1889 size_t locals, typedefs;
1891 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1892 parseerror(parser, "internal error: parser_leaveblock with no block");
1896 util_htdel(vec_last(parser->variables));
1897 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1899 vec_pop(parser->variables);
1900 vec_pop(parser->correct_variables);
1901 vec_pop(parser->correct_variables_score);
1902 if (!vec_size(parser->_blocklocals)) {
1903 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1907 locals = vec_last(parser->_blocklocals);
1908 vec_pop(parser->_blocklocals);
1909 while (vec_size(parser->_locals) != locals) {
1910 ast_expression *e = vec_last(parser->_locals);
1911 ast_value *v = (ast_value*)e;
1912 vec_pop(parser->_locals);
1913 if (ast_istype(e, ast_value) && !v->uses) {
1914 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1919 typedefs = vec_last(parser->_blocktypedefs);
1920 while (vec_size(parser->_typedefs) != typedefs) {
1921 ast_delete(vec_last(parser->_typedefs));
1922 vec_pop(parser->_typedefs);
1924 util_htdel(vec_last(parser->typedefs));
1925 vec_pop(parser->typedefs);
1927 vec_pop(parser->_block_ctx);
1932 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1934 vec_push(parser->_locals, e);
1935 util_htset(vec_last(parser->variables), name, (void*)e);
1939 vec_last(parser->correct_variables),
1940 &vec_last(parser->correct_variables_score),
1945 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
1947 vec_push(parser->globals, e);
1948 util_htset(parser->htglobals, name, e);
1952 parser->correct_variables[0],
1953 &parser->correct_variables_score[0],
1958 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1962 ast_expression *prev;
1964 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
1966 ast_type_to_string(cond, ty, sizeof(ty));
1967 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
1970 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
1973 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1976 parseerror(parser, "internal error: failed to process condition");
1981 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
1983 /* vector types need to be cast to true booleans */
1984 ast_binary *bin = (ast_binary*)cond;
1985 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1987 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1989 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1992 parseerror(parser, "internal error: failed to process condition");
1999 unary = (ast_unary*)cond;
2000 /* ast_istype dereferences cond, should test here for safety */
2001 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2003 cond = unary->operand;
2004 unary->operand = NULL;
2007 unary = (ast_unary*)cond;
2011 parseerror(parser, "internal error: failed to process condition");
2013 if (ifnot) *_ifnot = !*_ifnot;
2017 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2020 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2023 lex_ctx_t ctx = parser_ctx(parser);
2025 (void)block; /* not touching */
2027 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2028 if (!parser_next(parser)) {
2029 parseerror(parser, "expected condition or 'not'");
2032 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2034 if (!parser_next(parser)) {
2035 parseerror(parser, "expected condition in parenthesis");
2039 if (parser->tok != '(') {
2040 parseerror(parser, "expected 'if' condition in parenthesis");
2043 /* parse into the expression */
2044 if (!parser_next(parser)) {
2045 parseerror(parser, "expected 'if' condition after opening paren");
2048 /* parse the condition */
2049 cond = parse_expression_leave(parser, false, true, false);
2053 if (parser->tok != ')') {
2054 parseerror(parser, "expected closing paren after 'if' condition");
2058 /* parse into the 'then' branch */
2059 if (!parser_next(parser)) {
2060 parseerror(parser, "expected statement for on-true branch of 'if'");
2064 if (!parse_statement_or_block(parser, &ontrue)) {
2069 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2070 /* check for an else */
2071 if (!strcmp(parser_tokval(parser), "else")) {
2072 /* parse into the 'else' branch */
2073 if (!parser_next(parser)) {
2074 parseerror(parser, "expected on-false branch after 'else'");
2079 if (!parse_statement_or_block(parser, &onfalse)) {
2086 cond = process_condition(parser, cond, &ifnot);
2088 if (ontrue) ast_delete(ontrue);
2089 if (onfalse) ast_delete(onfalse);
2094 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2096 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2097 *out = (ast_expression*)ifthen;
2101 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2102 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2107 /* skip the 'while' and get the body */
2108 if (!parser_next(parser)) {
2109 if (OPTS_FLAG(LOOP_LABELS))
2110 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2112 parseerror(parser, "expected 'while' condition in parenthesis");
2116 if (parser->tok == ':') {
2117 if (!OPTS_FLAG(LOOP_LABELS))
2118 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2119 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2120 parseerror(parser, "expected loop label");
2123 label = util_strdup(parser_tokval(parser));
2124 if (!parser_next(parser)) {
2126 parseerror(parser, "expected 'while' condition in parenthesis");
2131 if (parser->tok != '(') {
2132 parseerror(parser, "expected 'while' condition in parenthesis");
2136 vec_push(parser->breaks, label);
2137 vec_push(parser->continues, label);
2139 rv = parse_while_go(parser, block, out);
2142 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2143 parseerror(parser, "internal error: label stack corrupted");
2149 vec_pop(parser->breaks);
2150 vec_pop(parser->continues);
2155 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2158 ast_expression *cond, *ontrue;
2162 lex_ctx_t ctx = parser_ctx(parser);
2164 (void)block; /* not touching */
2166 /* parse into the expression */
2167 if (!parser_next(parser)) {
2168 parseerror(parser, "expected 'while' condition after opening paren");
2171 /* parse the condition */
2172 cond = parse_expression_leave(parser, false, true, false);
2176 if (parser->tok != ')') {
2177 parseerror(parser, "expected closing paren after 'while' condition");
2181 /* parse into the 'then' branch */
2182 if (!parser_next(parser)) {
2183 parseerror(parser, "expected while-loop body");
2187 if (!parse_statement_or_block(parser, &ontrue)) {
2192 cond = process_condition(parser, cond, &ifnot);
2197 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2198 *out = (ast_expression*)aloop;
2202 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2203 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2208 /* skip the 'do' and get the body */
2209 if (!parser_next(parser)) {
2210 if (OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "expected loop label or body");
2213 parseerror(parser, "expected loop body");
2217 if (parser->tok == ':') {
2218 if (!OPTS_FLAG(LOOP_LABELS))
2219 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2220 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2221 parseerror(parser, "expected loop label");
2224 label = util_strdup(parser_tokval(parser));
2225 if (!parser_next(parser)) {
2227 parseerror(parser, "expected loop body");
2232 vec_push(parser->breaks, label);
2233 vec_push(parser->continues, label);
2235 rv = parse_dowhile_go(parser, block, out);
2238 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2239 parseerror(parser, "internal error: label stack corrupted");
2242 * Test for NULL otherwise ast_delete dereferences null pointer
2250 vec_pop(parser->breaks);
2251 vec_pop(parser->continues);
2256 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2259 ast_expression *cond, *ontrue;
2263 lex_ctx_t ctx = parser_ctx(parser);
2265 (void)block; /* not touching */
2267 if (!parse_statement_or_block(parser, &ontrue))
2270 /* expect the "while" */
2271 if (parser->tok != TOKEN_KEYWORD ||
2272 strcmp(parser_tokval(parser), "while"))
2274 parseerror(parser, "expected 'while' and condition");
2279 /* skip the 'while' and check for opening paren */
2280 if (!parser_next(parser) || parser->tok != '(') {
2281 parseerror(parser, "expected 'while' condition in parenthesis");
2285 /* parse into the expression */
2286 if (!parser_next(parser)) {
2287 parseerror(parser, "expected 'while' condition after opening paren");
2291 /* parse the condition */
2292 cond = parse_expression_leave(parser, false, true, false);
2296 if (parser->tok != ')') {
2297 parseerror(parser, "expected closing paren after 'while' condition");
2303 if (!parser_next(parser) || parser->tok != ';') {
2304 parseerror(parser, "expected semicolon after condition");
2310 if (!parser_next(parser)) {
2311 parseerror(parser, "parse error");
2317 cond = process_condition(parser, cond, &ifnot);
2322 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2323 *out = (ast_expression*)aloop;
2327 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2328 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2333 /* skip the 'for' and check for opening paren */
2334 if (!parser_next(parser)) {
2335 if (OPTS_FLAG(LOOP_LABELS))
2336 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2338 parseerror(parser, "expected 'for' expressions in parenthesis");
2342 if (parser->tok == ':') {
2343 if (!OPTS_FLAG(LOOP_LABELS))
2344 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2345 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2346 parseerror(parser, "expected loop label");
2349 label = util_strdup(parser_tokval(parser));
2350 if (!parser_next(parser)) {
2352 parseerror(parser, "expected 'for' expressions in parenthesis");
2357 if (parser->tok != '(') {
2358 parseerror(parser, "expected 'for' expressions in parenthesis");
2362 vec_push(parser->breaks, label);
2363 vec_push(parser->continues, label);
2365 rv = parse_for_go(parser, block, out);
2368 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2369 parseerror(parser, "internal error: label stack corrupted");
2375 vec_pop(parser->breaks);
2376 vec_pop(parser->continues);
2380 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2383 ast_expression *initexpr, *cond, *increment, *ontrue;
2388 lex_ctx_t ctx = parser_ctx(parser);
2390 parser_enterblock(parser);
2397 /* parse into the expression */
2398 if (!parser_next(parser)) {
2399 parseerror(parser, "expected 'for' initializer after opening paren");
2404 if (parser->tok == TOKEN_IDENT)
2405 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2407 if (typevar || parser->tok == TOKEN_TYPENAME) {
2409 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2410 if (parsewarning(parser, WARN_EXTENSIONS,
2411 "current standard does not allow variable declarations in for-loop initializers"))
2415 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2418 else if (parser->tok != ';')
2420 initexpr = parse_expression_leave(parser, false, false, false);
2425 /* move on to condition */
2426 if (parser->tok != ';') {
2427 parseerror(parser, "expected semicolon after for-loop initializer");
2430 if (!parser_next(parser)) {
2431 parseerror(parser, "expected for-loop condition");
2435 /* parse the condition */
2436 if (parser->tok != ';') {
2437 cond = parse_expression_leave(parser, false, true, false);
2442 /* move on to incrementor */
2443 if (parser->tok != ';') {
2444 parseerror(parser, "expected semicolon after for-loop initializer");
2447 if (!parser_next(parser)) {
2448 parseerror(parser, "expected for-loop condition");
2452 /* parse the incrementor */
2453 if (parser->tok != ')') {
2454 lex_ctx_t condctx = parser_ctx(parser);
2455 increment = parse_expression_leave(parser, false, false, false);
2458 if (!ast_side_effects(increment)) {
2459 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2465 if (parser->tok != ')') {
2466 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2469 /* parse into the 'then' branch */
2470 if (!parser_next(parser)) {
2471 parseerror(parser, "expected for-loop body");
2474 if (!parse_statement_or_block(parser, &ontrue))
2478 cond = process_condition(parser, cond, &ifnot);
2482 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2483 *out = (ast_expression*)aloop;
2485 if (!parser_leaveblock(parser)) {
2491 if (initexpr) ast_unref(initexpr);
2492 if (cond) ast_unref(cond);
2493 if (increment) ast_unref(increment);
2494 (void)!parser_leaveblock(parser);
2498 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2500 ast_expression *exp = NULL;
2501 ast_expression *var = NULL;
2502 ast_return *ret = NULL;
2503 ast_value *retval = parser->function->return_value;
2504 ast_value *expected = parser->function->vtype;
2506 lex_ctx_t ctx = parser_ctx(parser);
2508 (void)block; /* not touching */
2510 if (!parser_next(parser)) {
2511 parseerror(parser, "expected return expression");
2515 /* return assignments */
2516 if (parser->tok == '=') {
2517 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2518 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2522 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2524 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2525 parseerror(parser, "invalid return type: `%s'", ty1);
2529 if (!parser_next(parser)) {
2530 parseerror(parser, "expected return assignment expression");
2534 if (!(exp = parse_expression_leave(parser, false, false, false)))
2537 /* prepare the return value */
2539 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2540 ast_type_adopt(retval, expected->expression.next);
2541 parser->function->return_value = retval;
2544 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2545 char ty1[1024], ty2[1024];
2546 ast_type_to_string(exp, ty1, sizeof(ty1));
2547 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2548 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2551 /* store to 'return' local variable */
2552 var = (ast_expression*)ast_store_new(
2554 type_store_instr[expected->expression.next->vtype],
2555 (ast_expression*)retval, exp);
2562 if (parser->tok != ';')
2563 parseerror(parser, "missing semicolon after return assignment");
2564 else if (!parser_next(parser))
2565 parseerror(parser, "parse error after return assignment");
2571 if (parser->tok != ';') {
2572 exp = parse_expression(parser, false, false);
2576 if (exp->vtype != TYPE_NIL &&
2577 exp->vtype != ((ast_expression*)expected)->next->vtype)
2579 parseerror(parser, "return with invalid expression");
2582 ret = ast_return_new(ctx, exp);
2588 if (!parser_next(parser))
2589 parseerror(parser, "parse error");
2591 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2593 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2595 ret = ast_return_new(ctx, (ast_expression*)retval);
2597 *out = (ast_expression*)ret;
2601 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2604 unsigned int levels = 0;
2605 lex_ctx_t ctx = parser_ctx(parser);
2606 const char **loops = (is_continue ? parser->continues : parser->breaks);
2608 (void)block; /* not touching */
2609 if (!parser_next(parser)) {
2610 parseerror(parser, "expected semicolon or loop label");
2614 if (!vec_size(loops)) {
2616 parseerror(parser, "`continue` can only be used inside loops");
2618 parseerror(parser, "`break` can only be used inside loops or switches");
2621 if (parser->tok == TOKEN_IDENT) {
2622 if (!OPTS_FLAG(LOOP_LABELS))
2623 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2624 i = vec_size(loops);
2626 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2629 parseerror(parser, "no such loop to %s: `%s`",
2630 (is_continue ? "continue" : "break out of"),
2631 parser_tokval(parser));
2636 if (!parser_next(parser)) {
2637 parseerror(parser, "expected semicolon");
2642 if (parser->tok != ';') {
2643 parseerror(parser, "expected semicolon");
2647 if (!parser_next(parser))
2648 parseerror(parser, "parse error");
2650 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2654 /* returns true when it was a variable qualifier, false otherwise!
2655 * on error, cvq is set to CV_WRONG
2657 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2659 bool had_const = false;
2660 bool had_var = false;
2661 bool had_noref = false;
2662 bool had_attrib = false;
2663 bool had_static = false;
2668 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2670 /* parse an attribute */
2671 if (!parser_next(parser)) {
2672 parseerror(parser, "expected attribute after `[[`");
2676 if (!strcmp(parser_tokval(parser), "noreturn")) {
2677 flags |= AST_FLAG_NORETURN;
2678 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2679 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2684 else if (!strcmp(parser_tokval(parser), "noref")) {
2686 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2687 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2692 else if (!strcmp(parser_tokval(parser), "inline")) {
2693 flags |= AST_FLAG_INLINE;
2694 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2695 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2700 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2701 flags |= AST_FLAG_ALIAS;
2704 if (!parser_next(parser)) {
2705 parseerror(parser, "parse error in attribute");
2709 if (parser->tok == '(') {
2710 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2711 parseerror(parser, "`alias` attribute missing parameter");
2715 *message = util_strdup(parser_tokval(parser));
2717 if (!parser_next(parser)) {
2718 parseerror(parser, "parse error in attribute");
2722 if (parser->tok != ')') {
2723 parseerror(parser, "`alias` attribute expected `)` after parameter");
2727 if (!parser_next(parser)) {
2728 parseerror(parser, "parse error in attribute");
2733 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2734 parseerror(parser, "`alias` attribute expected `]]`");
2738 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2739 flags |= AST_FLAG_DEPRECATED;
2742 if (!parser_next(parser)) {
2743 parseerror(parser, "parse error in attribute");
2747 if (parser->tok == '(') {
2748 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2749 parseerror(parser, "`deprecated` attribute missing parameter");
2753 *message = util_strdup(parser_tokval(parser));
2755 if (!parser_next(parser)) {
2756 parseerror(parser, "parse error in attribute");
2760 if(parser->tok != ')') {
2761 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2765 if (!parser_next(parser)) {
2766 parseerror(parser, "parse error in attribute");
2771 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2772 parseerror(parser, "`deprecated` attribute expected `]]`");
2775 if (*message) mem_d(*message);
2783 /* Skip tokens until we hit a ]] */
2784 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2785 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2786 if (!parser_next(parser)) {
2787 parseerror(parser, "error inside attribute");
2794 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2796 else if (!strcmp(parser_tokval(parser), "const"))
2798 else if (!strcmp(parser_tokval(parser), "var"))
2800 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2802 else if (!strcmp(parser_tokval(parser), "noref"))
2804 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2809 if (!parser_next(parser))
2819 *is_static = had_static;
2823 parseerror(parser, "parse error after variable qualifier");
2828 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2829 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2834 /* skip the 'while' and get the body */
2835 if (!parser_next(parser)) {
2836 if (OPTS_FLAG(LOOP_LABELS))
2837 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2839 parseerror(parser, "expected 'switch' operand in parenthesis");
2843 if (parser->tok == ':') {
2844 if (!OPTS_FLAG(LOOP_LABELS))
2845 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2846 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2847 parseerror(parser, "expected loop label");
2850 label = util_strdup(parser_tokval(parser));
2851 if (!parser_next(parser)) {
2853 parseerror(parser, "expected 'switch' operand in parenthesis");
2858 if (parser->tok != '(') {
2859 parseerror(parser, "expected 'switch' operand in parenthesis");
2863 vec_push(parser->breaks, label);
2865 rv = parse_switch_go(parser, block, out);
2868 if (vec_last(parser->breaks) != label) {
2869 parseerror(parser, "internal error: label stack corrupted");
2875 vec_pop(parser->breaks);
2880 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2882 ast_expression *operand;
2885 ast_switch *switchnode;
2886 ast_switch_case swcase;
2889 bool noref, is_static;
2890 uint32_t qflags = 0;
2892 lex_ctx_t ctx = parser_ctx(parser);
2894 (void)block; /* not touching */
2897 /* parse into the expression */
2898 if (!parser_next(parser)) {
2899 parseerror(parser, "expected switch operand");
2902 /* parse the operand */
2903 operand = parse_expression_leave(parser, false, false, false);
2907 switchnode = ast_switch_new(ctx, operand);
2910 if (parser->tok != ')') {
2911 ast_delete(switchnode);
2912 parseerror(parser, "expected closing paren after 'switch' operand");
2916 /* parse over the opening paren */
2917 if (!parser_next(parser) || parser->tok != '{') {
2918 ast_delete(switchnode);
2919 parseerror(parser, "expected list of cases");
2923 if (!parser_next(parser)) {
2924 ast_delete(switchnode);
2925 parseerror(parser, "expected 'case' or 'default'");
2929 /* new block; allow some variables to be declared here */
2930 parser_enterblock(parser);
2933 if (parser->tok == TOKEN_IDENT)
2934 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2935 if (typevar || parser->tok == TOKEN_TYPENAME) {
2936 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2937 ast_delete(switchnode);
2942 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2944 if (cvq == CV_WRONG) {
2945 ast_delete(switchnode);
2948 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2949 ast_delete(switchnode);
2958 while (parser->tok != '}') {
2959 ast_block *caseblock;
2961 if (!strcmp(parser_tokval(parser), "case")) {
2962 if (!parser_next(parser)) {
2963 ast_delete(switchnode);
2964 parseerror(parser, "expected expression for case");
2967 swcase.value = parse_expression_leave(parser, false, false, false);
2968 if (!swcase.value) {
2969 ast_delete(switchnode);
2970 parseerror(parser, "expected expression for case");
2973 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2974 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2975 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2981 else if (!strcmp(parser_tokval(parser), "default")) {
2982 swcase.value = NULL;
2983 if (!parser_next(parser)) {
2984 ast_delete(switchnode);
2985 parseerror(parser, "expected colon");
2990 ast_delete(switchnode);
2991 parseerror(parser, "expected 'case' or 'default'");
2995 /* Now the colon and body */
2996 if (parser->tok != ':') {
2997 if (swcase.value) ast_unref(swcase.value);
2998 ast_delete(switchnode);
2999 parseerror(parser, "expected colon");
3003 if (!parser_next(parser)) {
3004 if (swcase.value) ast_unref(swcase.value);
3005 ast_delete(switchnode);
3006 parseerror(parser, "expected statements or case");
3009 caseblock = ast_block_new(parser_ctx(parser));
3011 if (swcase.value) ast_unref(swcase.value);
3012 ast_delete(switchnode);
3015 swcase.code = (ast_expression*)caseblock;
3016 vec_push(switchnode->cases, swcase);
3018 ast_expression *expr;
3019 if (parser->tok == '}')
3021 if (parser->tok == TOKEN_KEYWORD) {
3022 if (!strcmp(parser_tokval(parser), "case") ||
3023 !strcmp(parser_tokval(parser), "default"))
3028 if (!parse_statement(parser, caseblock, &expr, true)) {
3029 ast_delete(switchnode);
3034 if (!ast_block_add_expr(caseblock, expr)) {
3035 ast_delete(switchnode);
3041 parser_leaveblock(parser);
3044 if (parser->tok != '}') {
3045 ast_delete(switchnode);
3046 parseerror(parser, "expected closing paren of case list");
3049 if (!parser_next(parser)) {
3050 ast_delete(switchnode);
3051 parseerror(parser, "parse error after switch");
3054 *out = (ast_expression*)switchnode;
3058 /* parse computed goto sides */
3059 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3060 ast_expression *on_true;
3061 ast_expression *on_false;
3062 ast_expression *cond;
3067 if (ast_istype(*side, ast_ternary)) {
3068 ast_ternary *tern = (ast_ternary*)*side;
3069 on_true = parse_goto_computed(parser, &tern->on_true);
3070 on_false = parse_goto_computed(parser, &tern->on_false);
3072 if (!on_true || !on_false) {
3073 parseerror(parser, "expected label or expression in ternary");
3074 if (on_true) ast_unref(on_true);
3075 if (on_false) ast_unref(on_false);
3083 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3084 } else if (ast_istype(*side, ast_label)) {
3085 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3086 ast_goto_set_label(gt, ((ast_label*)*side));
3088 return (ast_expression*)gt;
3093 static bool parse_goto(parser_t *parser, ast_expression **out)
3095 ast_goto *gt = NULL;
3096 ast_expression *lbl;
3098 if (!parser_next(parser))
3101 if (parser->tok != TOKEN_IDENT) {
3102 ast_expression *expression;
3104 /* could be an expression i.e computed goto :-) */
3105 if (parser->tok != '(') {
3106 parseerror(parser, "expected label name after `goto`");
3110 /* failed to parse expression for goto */
3111 if (!(expression = parse_expression(parser, false, true)) ||
3112 !(*out = parse_goto_computed(parser, &expression))) {
3113 parseerror(parser, "invalid goto expression");
3115 ast_unref(expression);
3122 /* not computed goto */
3123 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3124 lbl = parser_find_label(parser, gt->name);
3126 if (!ast_istype(lbl, ast_label)) {
3127 parseerror(parser, "internal error: label is not an ast_label");
3131 ast_goto_set_label(gt, (ast_label*)lbl);
3134 vec_push(parser->gotos, gt);
3136 if (!parser_next(parser) || parser->tok != ';') {
3137 parseerror(parser, "semicolon expected after goto label");
3140 if (!parser_next(parser)) {
3141 parseerror(parser, "parse error after goto");
3145 *out = (ast_expression*)gt;
3149 static bool parse_skipwhite(parser_t *parser)
3152 if (!parser_next(parser))
3154 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3155 return parser->tok < TOKEN_ERROR;
3158 static bool parse_eol(parser_t *parser)
3160 if (!parse_skipwhite(parser))
3162 return parser->tok == TOKEN_EOL;
3165 static bool parse_pragma_do(parser_t *parser)
3167 if (!parser_next(parser) ||
3168 parser->tok != TOKEN_IDENT ||
3169 strcmp(parser_tokval(parser), "pragma"))
3171 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3174 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3175 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3179 if (!strcmp(parser_tokval(parser), "noref")) {
3180 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3181 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3184 parser->noref = !!parser_token(parser)->constval.i;
3185 if (!parse_eol(parser)) {
3186 parseerror(parser, "parse error after `noref` pragma");
3192 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3199 static bool parse_pragma(parser_t *parser)
3202 parser->lex->flags.preprocessing = true;
3203 parser->lex->flags.mergelines = true;
3204 rv = parse_pragma_do(parser);
3205 if (parser->tok != TOKEN_EOL) {
3206 parseerror(parser, "junk after pragma");
3209 parser->lex->flags.preprocessing = false;
3210 parser->lex->flags.mergelines = false;
3211 if (!parser_next(parser)) {
3212 parseerror(parser, "parse error after pragma");
3218 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3220 bool noref, is_static;
3222 uint32_t qflags = 0;
3223 ast_value *typevar = NULL;
3224 char *vstring = NULL;
3228 if (parser->tok == TOKEN_IDENT)
3229 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3231 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3233 /* local variable */
3235 parseerror(parser, "cannot declare a variable from here");
3238 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3239 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3242 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3246 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3248 if (cvq == CV_WRONG)
3250 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3252 else if (parser->tok == TOKEN_KEYWORD)
3254 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3259 if (!parser_next(parser)) {
3260 parseerror(parser, "parse error after __builtin_debug_printtype");
3264 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3266 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3267 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3268 if (!parser_next(parser)) {
3269 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3275 if (!parse_statement(parser, block, out, allow_cases))
3278 con_out("__builtin_debug_printtype: got no output node\n");
3281 ast_type_to_string(*out, ty, sizeof(ty));
3282 con_out("__builtin_debug_printtype: `%s`\n", ty);
3287 else if (!strcmp(parser_tokval(parser), "return"))
3289 return parse_return(parser, block, out);
3291 else if (!strcmp(parser_tokval(parser), "if"))
3293 return parse_if(parser, block, out);
3295 else if (!strcmp(parser_tokval(parser), "while"))
3297 return parse_while(parser, block, out);
3299 else if (!strcmp(parser_tokval(parser), "do"))
3301 return parse_dowhile(parser, block, out);
3303 else if (!strcmp(parser_tokval(parser), "for"))
3305 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3306 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3309 return parse_for(parser, block, out);
3311 else if (!strcmp(parser_tokval(parser), "break"))
3313 return parse_break_continue(parser, block, out, false);
3315 else if (!strcmp(parser_tokval(parser), "continue"))
3317 return parse_break_continue(parser, block, out, true);
3319 else if (!strcmp(parser_tokval(parser), "switch"))
3321 return parse_switch(parser, block, out);
3323 else if (!strcmp(parser_tokval(parser), "case") ||
3324 !strcmp(parser_tokval(parser), "default"))
3327 parseerror(parser, "unexpected 'case' label");
3332 else if (!strcmp(parser_tokval(parser), "goto"))
3334 return parse_goto(parser, out);
3336 else if (!strcmp(parser_tokval(parser), "typedef"))
3338 if (!parser_next(parser)) {
3339 parseerror(parser, "expected type definition after 'typedef'");
3342 return parse_typedef(parser);
3344 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3347 else if (parser->tok == '{')
3350 inner = parse_block(parser);
3353 *out = (ast_expression*)inner;
3356 else if (parser->tok == ':')
3360 if (!parser_next(parser)) {
3361 parseerror(parser, "expected label name");
3364 if (parser->tok != TOKEN_IDENT) {
3365 parseerror(parser, "label must be an identifier");
3368 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3370 if (!label->undefined) {
3371 parseerror(parser, "label `%s` already defined", label->name);
3374 label->undefined = false;
3377 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3378 vec_push(parser->labels, label);
3380 *out = (ast_expression*)label;
3381 if (!parser_next(parser)) {
3382 parseerror(parser, "parse error after label");
3385 for (i = 0; i < vec_size(parser->gotos); ++i) {
3386 if (!strcmp(parser->gotos[i]->name, label->name)) {
3387 ast_goto_set_label(parser->gotos[i], label);
3388 vec_remove(parser->gotos, i, 1);
3394 else if (parser->tok == ';')
3396 if (!parser_next(parser)) {
3397 parseerror(parser, "parse error after empty statement");
3404 lex_ctx_t ctx = parser_ctx(parser);
3405 ast_expression *exp = parse_expression(parser, false, false);
3409 if (!ast_side_effects(exp)) {
3410 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3417 static bool parse_enum(parser_t *parser)
3420 bool reverse = false;
3422 ast_value **values = NULL;
3423 ast_value *var = NULL;
3426 ast_expression *old;
3428 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3429 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3433 /* enumeration attributes (can add more later) */
3434 if (parser->tok == ':') {
3435 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3436 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3441 if (!strcmp(parser_tokval(parser), "flag")) {
3445 else if (!strcmp(parser_tokval(parser), "reverse")) {
3449 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3453 if (!parser_next(parser) || parser->tok != '{') {
3454 parseerror(parser, "expected `{` after enum attribute ");
3460 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3461 if (parser->tok == '}') {
3462 /* allow an empty enum */
3465 parseerror(parser, "expected identifier or `}`");
3469 old = parser_find_field(parser, parser_tokval(parser));
3471 old = parser_find_global(parser, parser_tokval(parser));
3473 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3474 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3478 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3479 vec_push(values, var);
3480 var->cvq = CV_CONST;
3481 var->hasvalue = true;
3483 /* for flagged enumerations increment in POTs of TWO */
3484 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3485 parser_addglobal(parser, var->name, (ast_expression*)var);
3487 if (!parser_next(parser)) {
3488 parseerror(parser, "expected `=`, `}` or comma after identifier");
3492 if (parser->tok == ',')
3494 if (parser->tok == '}')
3496 if (parser->tok != '=') {
3497 parseerror(parser, "expected `=`, `}` or comma after identifier");
3501 if (!parser_next(parser)) {
3502 parseerror(parser, "expected expression after `=`");
3506 /* We got a value! */
3507 old = parse_expression_leave(parser, true, false, false);
3508 asvalue = (ast_value*)old;
3509 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3510 compile_error(ast_ctx(var), "constant value or expression expected");
3513 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3515 if (parser->tok == '}')
3517 if (parser->tok != ',') {
3518 parseerror(parser, "expected `}` or comma after expression");
3523 /* patch them all (for reversed attribute) */
3526 for (i = 0; i < vec_size(values); i++)
3527 values[i]->constval.vfloat = vec_size(values) - i - 1;
3530 if (parser->tok != '}') {
3531 parseerror(parser, "internal error: breaking without `}`");
3535 if (!parser_next(parser) || parser->tok != ';') {
3536 parseerror(parser, "expected semicolon after enumeration");
3540 if (!parser_next(parser)) {
3541 parseerror(parser, "parse error after enumeration");
3553 static bool parse_block_into(parser_t *parser, ast_block *block)
3557 parser_enterblock(parser);
3559 if (!parser_next(parser)) { /* skip the '{' */
3560 parseerror(parser, "expected function body");
3564 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3566 ast_expression *expr = NULL;
3567 if (parser->tok == '}')
3570 if (!parse_statement(parser, block, &expr, false)) {
3571 /* parseerror(parser, "parse error"); */
3577 if (!ast_block_add_expr(block, expr)) {
3584 if (parser->tok != '}') {
3587 (void)parser_next(parser);
3591 if (!parser_leaveblock(parser))
3593 return retval && !!block;
3596 static ast_block* parse_block(parser_t *parser)
3599 block = ast_block_new(parser_ctx(parser));
3602 if (!parse_block_into(parser, block)) {
3603 ast_block_delete(block);
3609 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3611 if (parser->tok == '{') {
3612 *out = (ast_expression*)parse_block(parser);
3615 return parse_statement(parser, NULL, out, false);
3618 static bool create_vector_members(ast_value *var, ast_member **me)
3621 size_t len = strlen(var->name);
3623 for (i = 0; i < 3; ++i) {
3624 char *name = (char*)mem_a(len+3);
3625 memcpy(name, var->name, len);
3627 name[len+1] = 'x'+i;
3629 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3638 do { ast_member_delete(me[--i]); } while(i);
3642 static bool parse_function_body(parser_t *parser, ast_value *var)
3644 ast_block *block = NULL;
3649 ast_expression *framenum = NULL;
3650 ast_expression *nextthink = NULL;
3651 /* None of the following have to be deleted */
3652 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3653 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3654 bool has_frame_think;
3658 has_frame_think = false;
3659 old = parser->function;
3661 if (var->expression.flags & AST_FLAG_ALIAS) {
3662 parseerror(parser, "function aliases cannot have bodies");
3666 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3667 parseerror(parser, "gotos/labels leaking");
3671 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3672 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3673 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3679 if (parser->tok == '[') {
3680 /* got a frame definition: [ framenum, nextthink ]
3681 * this translates to:
3682 * self.frame = framenum;
3683 * self.nextthink = time + 0.1;
3684 * self.think = nextthink;
3688 fld_think = parser_find_field(parser, "think");
3689 fld_nextthink = parser_find_field(parser, "nextthink");
3690 fld_frame = parser_find_field(parser, "frame");
3691 if (!fld_think || !fld_nextthink || !fld_frame) {
3692 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3693 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3696 gbl_time = parser_find_global(parser, "time");
3697 gbl_self = parser_find_global(parser, "self");
3698 if (!gbl_time || !gbl_self) {
3699 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3700 parseerror(parser, "please declare the following globals: `time`, `self`");
3704 if (!parser_next(parser))
3707 framenum = parse_expression_leave(parser, true, false, false);
3709 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3712 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3713 ast_unref(framenum);
3714 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3718 if (parser->tok != ',') {
3719 ast_unref(framenum);
3720 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3721 parseerror(parser, "Got a %i\n", parser->tok);
3725 if (!parser_next(parser)) {
3726 ast_unref(framenum);
3730 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3732 /* qc allows the use of not-yet-declared functions here
3733 * - this automatically creates a prototype */
3734 ast_value *thinkfunc;
3735 ast_expression *functype = fld_think->next;
3737 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3738 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3739 ast_unref(framenum);
3740 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3743 ast_type_adopt(thinkfunc, functype);
3745 if (!parser_next(parser)) {
3746 ast_unref(framenum);
3747 ast_delete(thinkfunc);
3751 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3753 nextthink = (ast_expression*)thinkfunc;
3756 nextthink = parse_expression_leave(parser, true, false, false);
3758 ast_unref(framenum);
3759 parseerror(parser, "expected a think-function in [frame,think] notation");
3764 if (!ast_istype(nextthink, ast_value)) {
3765 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3769 if (retval && parser->tok != ']') {
3770 parseerror(parser, "expected closing `]` for [frame,think] notation");
3774 if (retval && !parser_next(parser)) {
3778 if (retval && parser->tok != '{') {
3779 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3784 ast_unref(nextthink);
3785 ast_unref(framenum);
3789 has_frame_think = true;
3792 block = ast_block_new(parser_ctx(parser));
3794 parseerror(parser, "failed to allocate block");
3795 if (has_frame_think) {
3796 ast_unref(nextthink);
3797 ast_unref(framenum);
3802 if (has_frame_think) {
3804 ast_expression *self_frame;
3805 ast_expression *self_nextthink;
3806 ast_expression *self_think;
3807 ast_expression *time_plus_1;
3808 ast_store *store_frame;
3809 ast_store *store_nextthink;
3810 ast_store *store_think;
3812 ctx = parser_ctx(parser);
3813 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3814 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3815 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3817 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3818 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3820 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3821 if (self_frame) ast_delete(self_frame);
3822 if (self_nextthink) ast_delete(self_nextthink);
3823 if (self_think) ast_delete(self_think);
3824 if (time_plus_1) ast_delete(time_plus_1);
3830 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3831 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3832 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3835 ast_delete(self_frame);
3838 if (!store_nextthink) {
3839 ast_delete(self_nextthink);
3843 ast_delete(self_think);
3847 if (store_frame) ast_delete(store_frame);
3848 if (store_nextthink) ast_delete(store_nextthink);
3849 if (store_think) ast_delete(store_think);
3852 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3853 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3854 !ast_block_add_expr(block, (ast_expression*)store_think))
3861 parseerror(parser, "failed to generate code for [frame,think]");
3862 ast_unref(nextthink);
3863 ast_unref(framenum);
3869 if (var->hasvalue) {
3870 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3871 ast_block_delete(block);
3875 func = ast_function_new(ast_ctx(var), var->name, var);
3877 parseerror(parser, "failed to allocate function for `%s`", var->name);
3878 ast_block_delete(block);
3881 vec_push(parser->functions, func);
3883 parser_enterblock(parser);
3885 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3887 ast_value *param = var->expression.params[parami];
3890 if (param->expression.vtype != TYPE_VECTOR &&
3891 (param->expression.vtype != TYPE_FIELD ||
3892 param->expression.next->vtype != TYPE_VECTOR))
3897 if (!create_vector_members(param, me)) {
3898 ast_block_delete(block);
3902 for (e = 0; e < 3; ++e) {
3903 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3904 ast_block_collect(block, (ast_expression*)me[e]);
3908 if (var->argcounter) {
3909 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3910 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3914 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3916 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3917 varargs->expression.flags |= AST_FLAG_IS_VARARG;
3918 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3919 varargs->expression.count = 0;
3920 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
3921 if (!parser_create_array_setter_proto(parser, varargs, name)) {
3922 ast_delete(varargs);
3923 ast_block_delete(block);
3926 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
3927 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
3928 ast_delete(varargs);
3929 ast_block_delete(block);
3932 func->varargs = varargs;
3933 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
3936 parser->function = func;
3937 if (!parse_block_into(parser, block)) {
3938 ast_block_delete(block);
3942 vec_push(func->blocks, block);
3945 parser->function = old;
3946 if (!parser_leaveblock(parser))
3948 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3949 parseerror(parser, "internal error: local scopes left");
3953 if (parser->tok == ';')
3954 return parser_next(parser);
3955 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
3956 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3960 (void)!parser_leaveblock(parser);
3961 vec_pop(parser->functions);
3962 ast_function_delete(func);
3963 var->constval.vfunc = NULL;
3966 parser->function = old;
3970 static ast_expression *array_accessor_split(
3975 ast_expression *left,
3976 ast_expression *right
3982 lex_ctx_t ctx = ast_ctx(array);
3984 if (!left || !right) {
3985 if (left) ast_delete(left);
3986 if (right) ast_delete(right);
3990 cmp = ast_binary_new(ctx, INSTR_LT,
3991 (ast_expression*)index,
3992 (ast_expression*)fold_constgen_float(parser->fold, middle));
3996 parseerror(parser, "internal error: failed to create comparison for array setter");
4000 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4002 ast_delete(cmp); /* will delete left and right */
4003 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4007 return (ast_expression*)ifthen;
4010 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4012 lex_ctx_t ctx = ast_ctx(array);
4014 if (from+1 == afterend) {
4015 /* set this value */
4018 ast_array_index *subscript;
4020 int assignop = type_store_instr[value->expression.vtype];
4022 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4023 assignop = INSTR_STORE_V;
4025 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4029 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4031 ast_delete(subscript);
4035 block = ast_block_new(ctx);
4041 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4046 ret = ast_return_new(ctx, NULL);
4052 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4057 return (ast_expression*)block;
4059 ast_expression *left, *right;
4060 size_t diff = afterend - from;
4061 size_t middle = from + diff/2;
4062 left = array_setter_node(parser, array, index, value, from, middle);
4063 right = array_setter_node(parser, array, index, value, middle, afterend);
4064 return array_accessor_split(parser, array, index, middle, left, right);
4068 static ast_expression *array_field_setter_node(
4077 lex_ctx_t ctx = ast_ctx(array);
4079 if (from+1 == afterend) {
4080 /* set this value */
4083 ast_entfield *entfield;
4084 ast_array_index *subscript;
4086 int assignop = type_storep_instr[value->expression.vtype];
4088 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4089 assignop = INSTR_STOREP_V;
4091 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4095 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4096 subscript->expression.vtype = TYPE_FIELD;
4098 entfield = ast_entfield_new_force(ctx,
4099 (ast_expression*)entity,
4100 (ast_expression*)subscript,
4101 (ast_expression*)subscript);
4103 ast_delete(subscript);
4107 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4109 ast_delete(entfield);
4113 block = ast_block_new(ctx);
4119 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4124 ret = ast_return_new(ctx, NULL);
4130 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4135 return (ast_expression*)block;
4137 ast_expression *left, *right;
4138 size_t diff = afterend - from;
4139 size_t middle = from + diff/2;
4140 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4141 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4142 return array_accessor_split(parser, array, index, middle, left, right);
4146 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4148 lex_ctx_t ctx = ast_ctx(array);
4150 if (from+1 == afterend) {
4152 ast_array_index *subscript;
4154 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4158 ret = ast_return_new(ctx, (ast_expression*)subscript);
4160 ast_delete(subscript);
4164 return (ast_expression*)ret;
4166 ast_expression *left, *right;
4167 size_t diff = afterend - from;
4168 size_t middle = from + diff/2;
4169 left = array_getter_node(parser, array, index, from, middle);
4170 right = array_getter_node(parser, array, index, middle, afterend);
4171 return array_accessor_split(parser, array, index, middle, left, right);
4175 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4177 ast_function *func = NULL;
4178 ast_value *fval = NULL;
4179 ast_block *body = NULL;
4181 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4183 parseerror(parser, "failed to create accessor function value");
4187 func = ast_function_new(ast_ctx(array), funcname, fval);
4190 parseerror(parser, "failed to create accessor function node");
4194 body = ast_block_new(ast_ctx(array));
4196 parseerror(parser, "failed to create block for array accessor");
4202 vec_push(func->blocks, body);
4205 vec_push(parser->accessors, fval);
4210 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4212 ast_value *index = NULL;
4213 ast_value *value = NULL;
4217 if (!ast_istype(array->expression.next, ast_value)) {
4218 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4222 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4224 func = fval->constval.vfunc;
4225 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4227 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4228 value = ast_value_copy((ast_value*)array->expression.next);
4230 if (!index || !value) {
4231 parseerror(parser, "failed to create locals for array accessor");
4234 (void)!ast_value_set_name(value, "value"); /* not important */
4235 vec_push(fval->expression.params, index);
4236 vec_push(fval->expression.params, value);
4238 array->setter = fval;
4241 if (index) ast_delete(index);
4242 if (value) ast_delete(value);
4248 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4250 ast_expression *root = NULL;
4251 root = array_setter_node(parser, array,
4252 array->setter->expression.params[0],
4253 array->setter->expression.params[1],
4254 0, array->expression.count);
4256 parseerror(parser, "failed to build accessor search tree");
4259 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4266 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4268 if (!parser_create_array_setter_proto(parser, array, funcname))
4270 return parser_create_array_setter_impl(parser, array);
4273 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4275 ast_expression *root = NULL;
4276 ast_value *entity = NULL;
4277 ast_value *index = NULL;
4278 ast_value *value = NULL;
4282 if (!ast_istype(array->expression.next, ast_value)) {
4283 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4287 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4289 func = fval->constval.vfunc;
4290 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4292 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4293 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4294 value = ast_value_copy((ast_value*)array->expression.next);
4295 if (!entity || !index || !value) {
4296 parseerror(parser, "failed to create locals for array accessor");
4299 (void)!ast_value_set_name(value, "value"); /* not important */
4300 vec_push(fval->expression.params, entity);
4301 vec_push(fval->expression.params, index);
4302 vec_push(fval->expression.params, value);
4304 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4306 parseerror(parser, "failed to build accessor search tree");
4310 array->setter = fval;
4311 return ast_block_add_expr(func->blocks[0], root);
4313 if (entity) ast_delete(entity);
4314 if (index) ast_delete(index);
4315 if (value) ast_delete(value);
4316 if (root) ast_delete(root);
4322 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4324 ast_value *index = NULL;
4328 /* NOTE: checking array->expression.next rather than elemtype since
4329 * for fields elemtype is a temporary fieldtype.
4331 if (!ast_istype(array->expression.next, ast_value)) {
4332 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4336 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4338 func = fval->constval.vfunc;
4339 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4341 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4344 parseerror(parser, "failed to create locals for array accessor");
4347 vec_push(fval->expression.params, index);
4349 array->getter = fval;
4352 if (index) ast_delete(index);
4358 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4360 ast_expression *root = NULL;
4362 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4364 parseerror(parser, "failed to build accessor search tree");
4367 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4374 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4376 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4378 return parser_create_array_getter_impl(parser, array);
4381 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4382 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4390 bool variadic = false;
4391 ast_value *varparam = NULL;
4392 char *argcounter = NULL;
4394 ctx = parser_ctx(parser);
4396 /* for the sake of less code we parse-in in this function */
4397 if (!parser_next(parser)) {
4399 parseerror(parser, "expected parameter list");
4405 /* parse variables until we hit a closing paren */
4406 while (parser->tok != ')') {
4408 /* there must be commas between them */
4409 if (parser->tok != ',') {
4410 parseerror(parser, "expected comma or end of parameter list");
4413 if (!parser_next(parser)) {
4414 parseerror(parser, "expected parameter");
4420 if (parser->tok == TOKEN_DOTS) {
4421 /* '...' indicates a varargs function */
4423 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4424 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4427 if (parser->tok == TOKEN_IDENT) {
4428 argcounter = util_strdup(parser_tokval(parser));
4429 if (!parser_next(parser) || parser->tok != ')') {
4430 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4437 /* for anything else just parse a typename */
4438 param = parse_typename(parser, NULL, NULL);
4441 vec_push(params, param);
4442 if (param->expression.vtype >= TYPE_VARIANT) {
4443 char tname[1024]; /* typename is reserved in C++ */
4444 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4445 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4448 /* type-restricted varargs */
4449 if (parser->tok == TOKEN_DOTS) {
4451 varparam = vec_last(params);
4453 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4454 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4457 if (parser->tok == TOKEN_IDENT) {
4458 argcounter = util_strdup(parser_tokval(parser));
4459 if (!parser_next(parser) || parser->tok != ')') {
4460 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4468 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4472 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4473 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4476 if (!parser_next(parser)) {
4477 parseerror(parser, "parse error after typename");
4481 /* now turn 'var' into a function type */
4482 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4483 fval->expression.next = (ast_expression*)var;
4485 fval->expression.flags |= AST_FLAG_VARIADIC;
4488 var->expression.params = params;
4489 var->expression.varparam = (ast_expression*)varparam;
4490 var->argcounter = argcounter;
4499 ast_delete(varparam);
4501 for (i = 0; i < vec_size(params); ++i)
4502 ast_delete(params[i]);
4507 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4509 ast_expression *cexp;
4510 ast_value *cval, *tmp;
4513 ctx = parser_ctx(parser);
4515 if (!parser_next(parser)) {
4517 parseerror(parser, "expected array-size");
4521 if (parser->tok != ']') {
4522 cexp = parse_expression_leave(parser, true, false, false);
4524 if (!cexp || !ast_istype(cexp, ast_value)) {
4528 parseerror(parser, "expected array-size as constant positive integer");
4531 cval = (ast_value*)cexp;
4538 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4539 tmp->expression.next = (ast_expression*)var;
4543 if (cval->expression.vtype == TYPE_INTEGER)
4544 tmp->expression.count = cval->constval.vint;
4545 else if (cval->expression.vtype == TYPE_FLOAT)
4546 tmp->expression.count = cval->constval.vfloat;
4550 parseerror(parser, "array-size must be a positive integer constant");
4556 var->expression.count = -1;
4557 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4560 if (parser->tok != ']') {
4562 parseerror(parser, "expected ']' after array-size");
4565 if (!parser_next(parser)) {
4567 parseerror(parser, "error after parsing array size");
4573 /* Parse a complete typename.
4574 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4575 * but when parsing variables separated by comma
4576 * 'storebase' should point to where the base-type should be kept.
4577 * The base type makes up every bit of type information which comes *before* the
4580 * The following will be parsed in its entirety:
4582 * The 'basetype' in this case is 'void()'
4583 * and if there's a comma after it, say:
4585 * then the type-information 'void()' can be stored in 'storebase'
4587 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4589 ast_value *var, *tmp;
4592 const char *name = NULL;
4593 bool isfield = false;
4594 bool wasarray = false;
4595 size_t morefields = 0;
4597 ctx = parser_ctx(parser);
4599 /* types may start with a dot */
4600 if (parser->tok == '.') {
4602 /* if we parsed a dot we need a typename now */
4603 if (!parser_next(parser)) {
4604 parseerror(parser, "expected typename for field definition");
4608 /* Further dots are handled seperately because they won't be part of the
4611 while (parser->tok == '.') {
4613 if (!parser_next(parser)) {
4614 parseerror(parser, "expected typename for field definition");
4619 if (parser->tok == TOKEN_IDENT)
4620 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4621 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4622 parseerror(parser, "expected typename");
4626 /* generate the basic type value */
4627 if (cached_typedef) {
4628 var = ast_value_copy(cached_typedef);
4629 ast_value_set_name(var, "<type(from_def)>");
4631 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4633 for (; morefields; --morefields) {
4634 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4635 tmp->expression.next = (ast_expression*)var;
4639 /* do not yet turn into a field - remember:
4640 * .void() foo; is a field too
4641 * .void()() foo; is a function
4645 if (!parser_next(parser)) {
4647 parseerror(parser, "parse error after typename");
4651 /* an opening paren now starts the parameter-list of a function
4652 * this is where original-QC has parameter lists.
4653 * We allow a single parameter list here.
4654 * Much like fteqcc we don't allow `float()() x`
4656 if (parser->tok == '(') {
4657 var = parse_parameter_list(parser, var);
4662 /* store the base if requested */
4664 *storebase = ast_value_copy(var);
4666 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4667 tmp->expression.next = (ast_expression*)*storebase;
4672 /* there may be a name now */
4673 if (parser->tok == TOKEN_IDENT) {
4674 name = util_strdup(parser_tokval(parser));
4676 if (!parser_next(parser)) {
4679 parseerror(parser, "error after variable or field declaration");
4684 /* now this may be an array */
4685 if (parser->tok == '[') {
4687 var = parse_arraysize(parser, var);
4689 if (name) mem_d(name);
4694 /* This is the point where we can turn it into a field */
4696 /* turn it into a field if desired */
4697 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4698 tmp->expression.next = (ast_expression*)var;
4702 /* now there may be function parens again */
4703 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4704 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4705 if (parser->tok == '(' && wasarray)
4706 parseerror(parser, "arrays as part of a return type is not supported");
4707 while (parser->tok == '(') {
4708 var = parse_parameter_list(parser, var);
4710 if (name) mem_d(name);
4715 /* finally name it */
4717 if (!ast_value_set_name(var, name)) {
4720 parseerror(parser, "internal error: failed to set name");
4723 /* free the name, ast_value_set_name duplicates */
4730 static bool parse_typedef(parser_t *parser)
4732 ast_value *typevar, *oldtype;
4733 ast_expression *old;
4735 typevar = parse_typename(parser, NULL, NULL);
4740 if ( (old = parser_find_var(parser, typevar->name)) ) {
4741 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4742 " -> `%s` has been declared here: %s:%i",
4743 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4744 ast_delete(typevar);
4748 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4749 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4750 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4751 ast_delete(typevar);
4755 vec_push(parser->_typedefs, typevar);
4756 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4758 if (parser->tok != ';') {
4759 parseerror(parser, "expected semicolon after typedef");
4762 if (!parser_next(parser)) {
4763 parseerror(parser, "parse error after typedef");
4770 static const char *cvq_to_str(int cvq) {
4772 case CV_NONE: return "none";
4773 case CV_VAR: return "`var`";
4774 case CV_CONST: return "`const`";
4775 default: return "<INVALID>";
4779 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4782 if (proto->cvq != var->cvq) {
4783 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4784 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4785 parser->tok == '='))
4787 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4788 "`%s` declared with different qualifiers: %s\n"
4789 " -> previous declaration here: %s:%i uses %s",
4790 var->name, cvq_to_str(var->cvq),
4791 ast_ctx(proto).file, ast_ctx(proto).line,
4792 cvq_to_str(proto->cvq));
4795 av = (var ->expression.flags & AST_FLAG_NORETURN);
4796 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4798 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4799 "`%s` declared with different attributes%s\n"
4800 " -> previous declaration here: %s:%i",
4801 var->name, (av ? ": noreturn" : ""),
4802 ast_ctx(proto).file, ast_ctx(proto).line,
4803 (ao ? ": noreturn" : ""));
4808 static bool create_array_accessors(parser_t *parser, ast_value *var)
4811 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4812 if (!parser_create_array_setter(parser, var, name))
4814 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4815 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4820 static bool parse_array(parser_t *parser, ast_value *array)
4823 if (array->initlist) {
4824 parseerror(parser, "array already initialized elsewhere");
4827 if (!parser_next(parser)) {
4828 parseerror(parser, "parse error in array initializer");
4832 while (parser->tok != '}') {
4833 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4836 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4838 parseerror(parser, "initializing element must be a compile time constant");
4841 vec_push(array->initlist, v->constval);
4842 if (v->expression.vtype == TYPE_STRING) {
4843 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4847 if (parser->tok == '}')
4849 if (parser->tok != ',' || !parser_next(parser)) {
4850 parseerror(parser, "expected comma or '}' in element list");
4854 if (!parser_next(parser) || parser->tok != ';') {
4855 parseerror(parser, "expected semicolon after initializer, got %s");
4859 if (!parser_next(parser)) {
4860 parseerror(parser, "parse error after initializer");
4865 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4866 if (array->expression.count != (size_t)-1) {
4867 parseerror(parser, "array `%s' has already been initialized with %u elements",
4868 array->name, (unsigned)array->expression.count);
4870 array->expression.count = vec_size(array->initlist);
4871 if (!create_array_accessors(parser, array))
4877 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)
4881 ast_expression *old;
4885 ast_value *basetype = NULL;
4887 bool isparam = false;
4888 bool isvector = false;
4889 bool cleanvar = true;
4890 bool wasarray = false;
4892 ast_member *me[3] = { NULL, NULL, NULL };
4894 if (!localblock && is_static)
4895 parseerror(parser, "`static` qualifier is not supported in global scope");
4897 /* get the first complete variable */
4898 var = parse_typename(parser, &basetype, cached_typedef);
4901 ast_delete(basetype);
4909 /* Part 0: finish the type */
4910 if (parser->tok == '(') {
4911 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4912 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4913 var = parse_parameter_list(parser, var);
4919 /* we only allow 1-dimensional arrays */
4920 if (parser->tok == '[') {
4922 var = parse_arraysize(parser, var);
4928 if (parser->tok == '(' && wasarray) {
4929 parseerror(parser, "arrays as part of a return type is not supported");
4930 /* we'll still parse the type completely for now */
4932 /* for functions returning functions */
4933 while (parser->tok == '(') {
4934 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4935 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4936 var = parse_parameter_list(parser, var);
4943 var->cvq = qualifier;
4944 var->expression.flags |= qflags;
4947 * store the vstring back to var for alias and
4948 * deprecation messages.
4950 if (var->expression.flags & AST_FLAG_DEPRECATED ||
4951 var->expression.flags & AST_FLAG_ALIAS)
4952 var->desc = vstring;
4955 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4956 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4957 * is then filled with the previous definition and the parameter-names replaced.
4959 if (!strcmp(var->name, "nil")) {
4960 if (OPTS_FLAG(UNTYPED_NIL)) {
4961 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4962 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4964 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4967 /* Deal with end_sys_ vars */
4969 if (!strcmp(var->name, "end_sys_globals")) {
4971 parser->crc_globals = vec_size(parser->globals);
4974 else if (!strcmp(var->name, "end_sys_fields")) {
4976 parser->crc_fields = vec_size(parser->fields);
4979 if (was_end && var->expression.vtype == TYPE_FIELD) {
4980 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4981 "global '%s' hint should not be a field",
4982 parser_tokval(parser)))
4989 if (!nofields && var->expression.vtype == TYPE_FIELD)
4991 /* deal with field declarations */
4992 old = parser_find_field(parser, var->name);
4994 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4995 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5004 parseerror(parser, "field `%s` already declared here: %s:%i",
5005 var->name, ast_ctx(old).file, ast_ctx(old).line);
5010 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5011 (old = parser_find_global(parser, var->name)))
5013 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5014 parseerror(parser, "field `%s` already declared here: %s:%i",
5015 var->name, ast_ctx(old).file, ast_ctx(old).line);
5022 /* deal with other globals */
5023 old = parser_find_global(parser, var->name);
5024 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5026 /* This is a function which had a prototype */
5027 if (!ast_istype(old, ast_value)) {
5028 parseerror(parser, "internal error: prototype is not an ast_value");
5032 proto = (ast_value*)old;
5033 proto->desc = var->desc;
5034 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5035 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5037 ast_ctx(proto).file, ast_ctx(proto).line);
5041 /* we need the new parameter-names */
5042 for (i = 0; i < vec_size(proto->expression.params); ++i)
5043 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5044 if (!parser_check_qualifiers(parser, var, proto)) {
5051 proto->expression.flags |= var->expression.flags;
5059 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5060 "global `%s` already declared here: %s:%i",
5061 var->name, ast_ctx(old).file, ast_ctx(old).line))
5066 proto = (ast_value*)old;
5067 if (!ast_istype(old, ast_value)) {
5068 parseerror(parser, "internal error: not an ast_value");
5073 if (!parser_check_qualifiers(parser, var, proto)) {
5078 proto->expression.flags |= var->expression.flags;
5082 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5083 (old = parser_find_field(parser, var->name)))
5085 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5086 parseerror(parser, "global `%s` already declared here: %s:%i",
5087 var->name, ast_ctx(old).file, ast_ctx(old).line);
5094 else /* it's not a global */
5096 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5097 if (old && !isparam) {
5098 parseerror(parser, "local `%s` already declared here: %s:%i",
5099 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5103 old = parser_find_local(parser, var->name, 0, &isparam);
5104 if (old && isparam) {
5105 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5106 "local `%s` is shadowing a parameter", var->name))
5108 parseerror(parser, "local `%s` already declared here: %s:%i",
5109 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5113 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5121 /* in a noref section we simply bump the usecount */
5122 if (noref || parser->noref)
5126 * Create the global/local, and deal with vector types.
5129 if (var->expression.vtype == TYPE_VECTOR)
5131 else if (var->expression.vtype == TYPE_FIELD &&
5132 var->expression.next->vtype == TYPE_VECTOR)
5136 if (!create_vector_members(var, me)) {
5143 /* deal with global variables, fields, functions */
5144 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5145 var->isfield = true;
5146 vec_push(parser->fields, (ast_expression*)var);
5147 util_htset(parser->htfields, var->name, var);
5149 for (i = 0; i < 3; ++i) {
5150 vec_push(parser->fields, (ast_expression*)me[i]);
5151 util_htset(parser->htfields, me[i]->name, me[i]);
5156 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5157 parser_addglobal(parser, var->name, (ast_expression*)var);
5159 for (i = 0; i < 3; ++i) {
5160 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5164 ast_expression *find = parser_find_global(parser, var->desc);
5167 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5171 if (var->expression.vtype != find->vtype) {
5175 ast_type_to_string(find, ty1, sizeof(ty1));
5176 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5178 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5185 * add alias to aliases table and to corrector
5186 * so corrections can apply for aliases as well.
5188 util_htset(parser->aliases, var->name, find);
5191 * add to corrector so corrections can work
5192 * even for aliases too.
5195 vec_last(parser->correct_variables),
5196 &vec_last(parser->correct_variables_score),
5200 /* generate aliases for vector components */
5204 util_asprintf(&buffer[0], "%s_x", var->desc);
5205 util_asprintf(&buffer[1], "%s_y", var->desc);
5206 util_asprintf(&buffer[2], "%s_z", var->desc);
5208 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5209 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5210 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5217 * add to corrector so corrections can work
5218 * even for aliases too.
5221 vec_last(parser->correct_variables),
5222 &vec_last(parser->correct_variables_score),
5226 vec_last(parser->correct_variables),
5227 &vec_last(parser->correct_variables_score),
5231 vec_last(parser->correct_variables),
5232 &vec_last(parser->correct_variables_score),
5240 /* a static adds itself to be generated like any other global
5241 * but is added to the local namespace instead
5243 char *defname = NULL;
5244 size_t prefix_len, ln;
5246 ln = strlen(parser->function->name);
5247 vec_append(defname, ln, parser->function->name);
5249 vec_append(defname, 2, "::");
5250 /* remember the length up to here */
5251 prefix_len = vec_size(defname);
5253 /* Add it to the local scope */
5254 util_htset(vec_last(parser->variables), var->name, (void*)var);
5258 vec_last(parser->correct_variables),
5259 &vec_last(parser->correct_variables_score),
5263 /* now rename the global */
5264 ln = strlen(var->name);
5265 vec_append(defname, ln, var->name);
5266 ast_value_set_name(var, defname);
5268 /* push it to the to-be-generated globals */
5269 vec_push(parser->globals, (ast_expression*)var);
5271 /* same game for the vector members */
5273 for (i = 0; i < 3; ++i) {
5274 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5278 vec_last(parser->correct_variables),
5279 &vec_last(parser->correct_variables_score),
5283 vec_shrinkto(defname, prefix_len);
5284 ln = strlen(me[i]->name);
5285 vec_append(defname, ln, me[i]->name);
5286 ast_member_set_name(me[i], defname);
5288 vec_push(parser->globals, (ast_expression*)me[i]);
5293 vec_push(localblock->locals, var);
5294 parser_addlocal(parser, var->name, (ast_expression*)var);
5296 for (i = 0; i < 3; ++i) {
5297 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5298 ast_block_collect(localblock, (ast_expression*)me[i]);
5304 me[0] = me[1] = me[2] = NULL;
5309 if (var->expression.vtype == TYPE_ARRAY) {
5310 if (var->expression.count != (size_t)-1) {
5311 if (!create_array_accessors(parser, var))
5315 else if (!localblock && !nofields &&
5316 var->expression.vtype == TYPE_FIELD &&
5317 var->expression.next->vtype == TYPE_ARRAY)
5320 ast_expression *telem;
5322 ast_value *array = (ast_value*)var->expression.next;
5324 if (!ast_istype(var->expression.next, ast_value)) {
5325 parseerror(parser, "internal error: field element type must be an ast_value");
5329 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5330 if (!parser_create_array_field_setter(parser, array, name))
5333 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5334 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5335 tfield->expression.next = telem;
5336 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5337 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5345 if (parser->tok == ';') {
5346 ast_delete(basetype);
5347 if (!parser_next(parser)) {
5348 parseerror(parser, "error after variable declaration");
5354 if (parser->tok == ',')
5358 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5361 parseerror(parser, "missing comma or semicolon while parsing variables");
5365 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5366 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5367 "initializing expression turns variable `%s` into a constant in this standard",
5374 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5375 if (parser->tok != '=') {
5376 if (!strcmp(parser_tokval(parser), "break")) {
5377 if (!parser_next(parser)) {
5378 parseerror(parser, "error parsing break definition");
5381 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5383 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5388 if (!parser_next(parser)) {
5389 parseerror(parser, "error parsing initializer");
5393 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5394 parseerror(parser, "expected '=' before function body in this standard");
5397 if (parser->tok == '#') {
5398 ast_function *func = NULL;
5399 ast_value *number = NULL;
5405 parseerror(parser, "cannot declare builtins within functions");
5408 if (var->expression.vtype != TYPE_FUNCTION) {
5409 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5412 if (!parser_next(parser)) {
5413 parseerror(parser, "expected builtin number");
5417 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5418 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5420 parseerror(parser, "builtin number expected");
5423 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5426 parseerror(parser, "builtin number must be a compile time constant");
5429 if (number->expression.vtype == TYPE_INTEGER)
5430 builtin_num = number->constval.vint;
5431 else if (number->expression.vtype == TYPE_FLOAT)
5432 builtin_num = number->constval.vfloat;
5435 parseerror(parser, "builtin number must be an integer constant");
5440 fractional = modff(builtin_num, &integral);
5441 if (builtin_num < 0 || fractional != 0) {
5442 parseerror(parser, "builtin number must be an integer greater than zero");
5446 /* we only want the integral part anyways */
5447 builtin_num = integral;
5448 } else if (parser->tok == TOKEN_INTCONST) {
5449 builtin_num = parser_token(parser)->constval.i;
5451 parseerror(parser, "builtin number must be a compile time constant");
5455 if (var->hasvalue) {
5456 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5457 "builtin `%s` has already been defined\n"
5458 " -> previous declaration here: %s:%i",
5459 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5463 func = ast_function_new(ast_ctx(var), var->name, var);
5465 parseerror(parser, "failed to allocate function for `%s`", var->name);
5468 vec_push(parser->functions, func);
5470 func->builtin = -builtin_num-1;
5473 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5474 ? (parser->tok != ',' && parser->tok != ';')
5475 : (!parser_next(parser)))
5477 parseerror(parser, "expected comma or semicolon");
5479 ast_function_delete(func);
5480 var->constval.vfunc = NULL;
5484 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5487 /* Note that fteqcc and most others don't even *have*
5488 * local arrays, so this is not a high priority.
5490 parseerror(parser, "TODO: initializers for local arrays");
5494 var->hasvalue = true;
5495 if (!parse_array(parser, var))
5498 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5501 parseerror(parser, "cannot declare functions within functions");
5506 ast_ctx(proto) = parser_ctx(parser);
5508 if (!parse_function_body(parser, var))
5510 ast_delete(basetype);
5511 for (i = 0; i < vec_size(parser->gotos); ++i)
5512 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5513 vec_free(parser->gotos);
5514 vec_free(parser->labels);
5517 ast_expression *cexp;
5520 cexp = parse_expression_leave(parser, true, false, false);
5525 cval = (ast_value*)cexp;
5526 if (cval != parser->nil &&
5527 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5530 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5534 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5535 qualifier != CV_VAR)
5537 var->cvq = CV_CONST;
5539 if (cval == parser->nil)
5540 var->expression.flags |= AST_FLAG_INITIALIZED;
5543 var->hasvalue = true;
5544 if (cval->expression.vtype == TYPE_STRING)
5545 var->constval.vstring = parser_strdup(cval->constval.vstring);
5546 else if (cval->expression.vtype == TYPE_FIELD)
5547 var->constval.vfield = cval;
5549 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5555 shunt sy = { NULL, NULL, NULL, NULL };
5558 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5559 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5560 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5561 if (!parser_sy_apply_operator(parser, &sy))
5564 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5565 parseerror(parser, "internal error: leaked operands");
5566 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5577 if (parser->tok == ',') {
5578 if (!parser_next(parser)) {
5579 parseerror(parser, "expected another variable");
5583 if (parser->tok != TOKEN_IDENT) {
5584 parseerror(parser, "expected another variable");
5587 var = ast_value_copy(basetype);
5589 ast_value_set_name(var, parser_tokval(parser));
5590 if (!parser_next(parser)) {
5591 parseerror(parser, "error parsing variable declaration");
5597 if (parser->tok != ';') {
5598 parseerror(parser, "missing semicolon after variables");
5602 if (!parser_next(parser)) {
5603 parseerror(parser, "parse error after variable declaration");
5607 ast_delete(basetype);
5611 if (cleanvar && var)
5613 ast_delete(basetype);
5617 ast_delete(basetype);
5618 if (cleanvar && var)
5620 if (me[0]) ast_member_delete(me[0]);
5621 if (me[1]) ast_member_delete(me[1]);
5622 if (me[2]) ast_member_delete(me[2]);
5626 static bool parser_global_statement(parser_t *parser)
5630 bool is_static = false;
5631 uint32_t qflags = 0;
5632 ast_value *istype = NULL;
5633 char *vstring = NULL;
5635 if (parser->tok == TOKEN_IDENT)
5636 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5638 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5640 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5642 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5644 if (cvq == CV_WRONG)
5646 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5648 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5650 return parse_enum(parser);
5652 else if (parser->tok == TOKEN_KEYWORD)
5654 if (!strcmp(parser_tokval(parser), "typedef")) {
5655 if (!parser_next(parser)) {
5656 parseerror(parser, "expected type definition after 'typedef'");
5659 return parse_typedef(parser);
5661 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5664 else if (parser->tok == '#')
5666 return parse_pragma(parser);
5668 else if (parser->tok == '$')
5670 if (!parser_next(parser)) {
5671 parseerror(parser, "parse error");
5677 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5683 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5685 return util_crc16(old, str, strlen(str));
5688 static void progdefs_crc_file(const char *str)
5690 /* write to progdefs.h here */
5694 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5696 old = progdefs_crc_sum(old, str);
5697 progdefs_crc_file(str);
5701 static void generate_checksum(parser_t *parser, ir_builder *ir)
5703 uint16_t crc = 0xFFFF;
5707 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5708 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5710 progdefs_crc_file("\tint\tpad;\n");
5711 progdefs_crc_file("\tint\tofs_return[3];\n");
5712 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5713 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5714 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5715 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5716 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5717 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5718 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5719 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5721 for (i = 0; i < parser->crc_globals; ++i) {
5722 if (!ast_istype(parser->globals[i], ast_value))
5724 value = (ast_value*)(parser->globals[i]);
5725 switch (value->expression.vtype) {
5726 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5727 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5728 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5729 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5731 crc = progdefs_crc_both(crc, "\tint\t");
5734 crc = progdefs_crc_both(crc, value->name);
5735 crc = progdefs_crc_both(crc, ";\n");
5737 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5738 for (i = 0; i < parser->crc_fields; ++i) {
5739 if (!ast_istype(parser->fields[i], ast_value))
5741 value = (ast_value*)(parser->fields[i]);
5742 switch (value->expression.next->vtype) {
5743 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5744 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5745 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5746 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5748 crc = progdefs_crc_both(crc, "\tint\t");
5751 crc = progdefs_crc_both(crc, value->name);
5752 crc = progdefs_crc_both(crc, ";\n");
5754 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5755 ir->code->crc = crc;
5758 parser_t *parser_create()
5761 lex_ctx_t empty_ctx;
5764 parser = (parser_t*)mem_a(sizeof(parser_t));
5768 memset(parser, 0, sizeof(*parser));
5770 for (i = 0; i < operator_count; ++i) {
5771 if (operators[i].id == opid1('=')) {
5772 parser->assign_op = operators+i;
5776 if (!parser->assign_op) {
5777 printf("internal error: initializing parser: failed to find assign operator\n");
5782 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5783 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5784 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5785 vec_push(parser->_blocktypedefs, 0);
5787 parser->aliases = util_htnew(PARSER_HT_SIZE);
5790 vec_push(parser->correct_variables, correct_trie_new());
5791 vec_push(parser->correct_variables_score, NULL);
5793 empty_ctx.file = "<internal>";
5795 empty_ctx.column = 0;
5796 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5797 parser->nil->cvq = CV_CONST;
5798 if (OPTS_FLAG(UNTYPED_NIL))
5799 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5801 parser->max_param_count = 1;
5803 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5804 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5805 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5807 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5808 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5809 parser->reserved_version->cvq = CV_CONST;
5810 parser->reserved_version->hasvalue = true;
5811 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5812 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5814 parser->reserved_version = NULL;
5817 parser->fold = fold_init (parser);
5818 parser->intrin = intrin_init(parser);
5822 static bool parser_compile(parser_t *parser)
5824 /* initial lexer/parser state */
5825 parser->lex->flags.noops = true;
5827 if (parser_next(parser))
5829 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5831 if (!parser_global_statement(parser)) {
5832 if (parser->tok == TOKEN_EOF)
5833 parseerror(parser, "unexpected end of file");
5834 else if (compile_errors)
5835 parseerror(parser, "there have been errors, bailing out");
5836 lex_close(parser->lex);
5842 parseerror(parser, "parse error");
5843 lex_close(parser->lex);
5848 lex_close(parser->lex);
5851 return !compile_errors;
5854 bool parser_compile_file(parser_t *parser, const char *filename)
5856 parser->lex = lex_open(filename);
5858 con_err("failed to open file \"%s\"\n", filename);
5861 return parser_compile(parser);
5864 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5866 parser->lex = lex_open_string(str, len, name);
5868 con_err("failed to create lexer for string \"%s\"\n", name);
5871 return parser_compile(parser);
5874 static void parser_remove_ast(parser_t *parser)
5877 if (parser->ast_cleaned)
5879 parser->ast_cleaned = true;
5880 for (i = 0; i < vec_size(parser->accessors); ++i) {
5881 ast_delete(parser->accessors[i]->constval.vfunc);
5882 parser->accessors[i]->constval.vfunc = NULL;
5883 ast_delete(parser->accessors[i]);
5885 for (i = 0; i < vec_size(parser->functions); ++i) {
5886 ast_delete(parser->functions[i]);
5888 for (i = 0; i < vec_size(parser->fields); ++i) {
5889 ast_delete(parser->fields[i]);
5891 for (i = 0; i < vec_size(parser->globals); ++i) {
5892 ast_delete(parser->globals[i]);
5894 vec_free(parser->accessors);
5895 vec_free(parser->functions);
5896 vec_free(parser->globals);
5897 vec_free(parser->fields);
5899 for (i = 0; i < vec_size(parser->variables); ++i)
5900 util_htdel(parser->variables[i]);
5901 vec_free(parser->variables);
5902 vec_free(parser->_blocklocals);
5903 vec_free(parser->_locals);
5906 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5907 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5909 vec_free(parser->correct_variables);
5910 vec_free(parser->correct_variables_score);
5912 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5913 ast_delete(parser->_typedefs[i]);
5914 vec_free(parser->_typedefs);
5915 for (i = 0; i < vec_size(parser->typedefs); ++i)
5916 util_htdel(parser->typedefs[i]);
5917 vec_free(parser->typedefs);
5918 vec_free(parser->_blocktypedefs);
5920 vec_free(parser->_block_ctx);
5922 vec_free(parser->labels);
5923 vec_free(parser->gotos);
5924 vec_free(parser->breaks);
5925 vec_free(parser->continues);
5927 ast_value_delete(parser->nil);
5929 ast_value_delete(parser->const_vec[0]);
5930 ast_value_delete(parser->const_vec[1]);
5931 ast_value_delete(parser->const_vec[2]);
5933 if (parser->reserved_version)
5934 ast_value_delete(parser->reserved_version);
5936 util_htdel(parser->aliases);
5937 fold_cleanup(parser->fold);
5938 intrin_cleanup(parser->intrin);
5941 void parser_cleanup(parser_t *parser)
5943 parser_remove_ast(parser);
5947 bool parser_finish(parser_t *parser, const char *output)
5953 if (compile_errors) {
5954 con_out("*** there were compile errors\n");
5958 ir = ir_builder_new("gmqcc_out");
5960 con_out("failed to allocate builder\n");
5964 for (i = 0; i < vec_size(parser->fields); ++i) {
5967 if (!ast_istype(parser->fields[i], ast_value))
5969 field = (ast_value*)parser->fields[i];
5970 hasvalue = field->hasvalue;
5971 field->hasvalue = false;
5972 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5973 con_out("failed to generate field %s\n", field->name);
5974 ir_builder_delete(ir);
5979 ast_expression *subtype;
5980 field->hasvalue = true;
5981 subtype = field->expression.next;
5982 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
5983 if (subtype->vtype == TYPE_FIELD)
5984 ifld->fieldtype = subtype->next->vtype;
5985 else if (subtype->vtype == TYPE_FUNCTION)
5986 ifld->outtype = subtype->next->vtype;
5987 (void)!ir_value_set_field(field->ir_v, ifld);
5990 for (i = 0; i < vec_size(parser->globals); ++i) {
5992 if (!ast_istype(parser->globals[i], ast_value))
5994 asvalue = (ast_value*)(parser->globals[i]);
5995 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5996 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5997 "unused global: `%s`", asvalue->name);
5999 if (!ast_global_codegen(asvalue, ir, false)) {
6000 con_out("failed to generate global %s\n", asvalue->name);
6001 ir_builder_delete(ir);
6005 /* Build function vararg accessor ast tree now before generating
6006 * immediates, because the accessors may add new immediates
6008 for (i = 0; i < vec_size(parser->functions); ++i) {
6009 ast_function *f = parser->functions[i];
6011 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6012 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6013 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6014 con_out("failed to generate vararg setter for %s\n", f->name);
6015 ir_builder_delete(ir);
6018 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6019 con_out("failed to generate vararg getter for %s\n", f->name);
6020 ir_builder_delete(ir);
6024 ast_delete(f->varargs);
6029 /* Now we can generate immediates */
6030 if (!fold_generate(parser->fold, ir))
6033 for (i = 0; i < vec_size(parser->globals); ++i) {
6035 if (!ast_istype(parser->globals[i], ast_value))
6037 asvalue = (ast_value*)(parser->globals[i]);
6038 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6040 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6041 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6042 "uninitialized constant: `%s`",
6044 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6045 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6046 "uninitialized global: `%s`",
6049 if (!ast_generate_accessors(asvalue, ir)) {
6050 ir_builder_delete(ir);
6054 for (i = 0; i < vec_size(parser->fields); ++i) {
6056 asvalue = (ast_value*)(parser->fields[i]->next);
6058 if (!ast_istype((ast_expression*)asvalue, ast_value))
6060 if (asvalue->expression.vtype != TYPE_ARRAY)
6062 if (!ast_generate_accessors(asvalue, ir)) {
6063 ir_builder_delete(ir);
6067 if (parser->reserved_version &&
6068 !ast_global_codegen(parser->reserved_version, ir, false))
6070 con_out("failed to generate reserved::version");
6071 ir_builder_delete(ir);
6074 for (i = 0; i < vec_size(parser->functions); ++i) {
6075 ast_function *f = parser->functions[i];
6076 if (!ast_function_codegen(f, ir)) {
6077 con_out("failed to generate function %s\n", f->name);
6078 ir_builder_delete(ir);
6083 generate_checksum(parser, ir);
6085 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6086 ir_builder_dump(ir, con_out);
6087 for (i = 0; i < vec_size(parser->functions); ++i) {
6088 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6089 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6090 ir_builder_delete(ir);
6094 parser_remove_ast(parser);
6096 if (compile_Werrors) {
6097 con_out("*** there were warnings treated as errors\n");
6098 compile_show_werrors();
6103 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6104 ir_builder_dump(ir, con_out);
6106 if (!ir_builder_generate(ir, output)) {
6107 con_out("*** failed to generate output file\n");
6108 ir_builder_delete(ir);
6112 ir_builder_delete(ir);