2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 #define PARSER_HT_LOCALS 2
29 #define PARSER_HT_SIZE 512
30 #define TYPEDEF_HT_SIZE 512
32 static void parser_enterblock(parser_t *parser);
33 static bool parser_leaveblock(parser_t *parser);
34 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
35 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
36 static bool parse_typedef(parser_t *parser);
37 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
38 static ast_block* parse_block(parser_t *parser);
39 static bool parse_block_into(parser_t *parser, ast_block *block);
40 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
41 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
42 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
43 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
44 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
45 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
46 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
48 static void parseerror(parser_t *parser, const char *fmt, ...)
52 vcompile_error(parser->lex->tok.ctx, fmt, ap);
56 /* returns true if it counts as an error */
57 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
62 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
67 /**********************************************************************
71 static bool parser_next(parser_t *parser)
73 /* lex_do kills the previous token */
74 parser->tok = lex_do(parser->lex);
75 if (parser->tok == TOKEN_EOF)
77 if (parser->tok >= TOKEN_ERROR) {
78 parseerror(parser, "lex error");
84 #define parser_tokval(p) ((p)->lex->tok.value)
85 #define parser_token(p) (&((p)->lex->tok))
87 char *parser_strdup(const char *str)
90 /* actually dup empty strings */
91 char *out = (char*)mem_a(1);
95 return util_strdup(str);
98 static ast_expression* parser_find_field(parser_t *parser, const char *name)
100 return ( ast_expression*)util_htget(parser->htfields, name);
103 static ast_expression* parser_find_label(parser_t *parser, const char *name)
106 for(i = 0; i < vec_size(parser->labels); i++)
107 if (!strcmp(parser->labels[i]->name, name))
108 return (ast_expression*)parser->labels[i];
112 ast_expression* parser_find_global(parser_t *parser, const char *name)
114 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
117 return (ast_expression*)util_htget(parser->htglobals, name);
120 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->vtype;
127 for (i = 0; i < vec_size(fun->expression.params); ++i) {
128 if (!strcmp(fun->expression.params[i]->name, name))
129 return (ast_expression*)(fun->expression.params[i]);
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = vec_size(parser->variables); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_var(parser_t *parser, const char *name)
155 v = parser_find_local(parser, name, 0, &dummy);
156 if (!v) v = parser_find_global(parser, name);
160 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
164 hash = util_hthash(parser->typedefs[0], name);
166 for (i = vec_size(parser->typedefs); i > upto;) {
168 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 size_t etype; /* 0 = expression, others are operators */
180 ast_block *block; /* for commas and function calls */
199 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
210 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
214 e.out = (ast_expression*)v;
221 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
223 e.etype = 1 + (op - operators);
232 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
243 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
244 * so we need to rotate it to become ent.(foo[n]).
246 static bool rotate_entfield_array_index_nodes(ast_expression **out)
248 ast_array_index *index, *oldindex;
249 ast_entfield *entfield;
253 ast_expression *entity;
255 lex_ctx_t ctx = ast_ctx(*out);
257 if (!ast_istype(*out, ast_array_index))
259 index = (ast_array_index*)*out;
261 if (!ast_istype(index->array, ast_entfield))
263 entfield = (ast_entfield*)index->array;
265 if (!ast_istype(entfield->field, ast_value))
267 field = (ast_value*)entfield->field;
270 entity = entfield->entity;
274 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
275 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
276 *out = (ast_expression*)entfield;
278 oldindex->array = NULL;
279 oldindex->index = NULL;
280 ast_delete(oldindex);
285 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
287 if (ast_istype(expr, ast_value)) {
288 ast_value *val = (ast_value*)expr;
289 if (val->cvq == CV_CONST) {
290 if (val->name[0] == '#') {
291 compile_error(ctx, "invalid assignment to a literal constant");
295 * To work around quakeworld we must elide the error and make it
298 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
299 compile_error(ctx, "assignment to constant `%s`", val->name);
301 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
308 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
312 ast_expression *out = NULL;
313 ast_expression *exprs[3];
314 ast_block *blocks[3];
315 ast_binstore *asbinstore;
316 size_t i, assignop, addop, subop;
317 qcint_t generated_op = 0;
322 if (!vec_size(sy->ops)) {
323 parseerror(parser, "internal error: missing operator");
327 if (vec_last(sy->ops).isparen) {
328 parseerror(parser, "unmatched parenthesis");
332 op = &operators[vec_last(sy->ops).etype - 1];
333 ctx = vec_last(sy->ops).ctx;
335 if (vec_size(sy->out) < op->operands) {
336 if (op->flags & OP_PREFIX)
337 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
338 else /* this should have errored previously already */
339 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
343 vec_shrinkby(sy->ops, 1);
345 /* op(:?) has no input and no output */
349 vec_shrinkby(sy->out, op->operands);
350 for (i = 0; i < op->operands; ++i) {
351 exprs[i] = sy->out[vec_size(sy->out)+i].out;
352 blocks[i] = sy->out[vec_size(sy->out)+i].block;
354 if (exprs[i]->vtype == TYPE_NOEXPR &&
355 !(i != 0 && op->id == opid2('?',':')) &&
356 !(i == 1 && op->id == opid1('.')))
358 if (ast_istype(exprs[i], ast_label))
359 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
361 compile_error(ast_ctx(exprs[i]), "not an expression");
362 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
366 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
367 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
371 #define NotSameType(T) \
372 (exprs[0]->vtype != exprs[1]->vtype || \
373 exprs[0]->vtype != T)
377 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
381 if (exprs[0]->vtype == TYPE_VECTOR &&
382 exprs[1]->vtype == TYPE_NOEXPR)
384 if (exprs[1] == (ast_expression*)parser->const_vec[0])
385 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
386 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
387 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
388 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
389 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
391 compile_error(ctx, "access to invalid vector component");
395 else if (exprs[0]->vtype == TYPE_ENTITY) {
396 if (exprs[1]->vtype != TYPE_FIELD) {
397 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
400 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
402 else if (exprs[0]->vtype == TYPE_VECTOR) {
403 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
407 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
413 if (exprs[0]->vtype != TYPE_ARRAY &&
414 !(exprs[0]->vtype == TYPE_FIELD &&
415 exprs[0]->next->vtype == TYPE_ARRAY))
417 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
418 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
421 if (exprs[1]->vtype != TYPE_FLOAT) {
422 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
423 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
426 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
427 if (rotate_entfield_array_index_nodes(&out))
430 /* This is not broken in fteqcc anymore */
431 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
432 /* this error doesn't need to make us bail out */
433 (void)!parsewarning(parser, WARN_EXTENSIONS,
434 "accessing array-field members of an entity without parenthesis\n"
435 " -> this is an extension from -std=gmqcc");
442 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
443 vec_push(sy->out, syexp(ctx, exprs[0]));
444 vec_push(sy->out, syexp(ctx, exprs[1]));
445 vec_last(sy->argc)++;
449 if (!ast_block_add_expr(blocks[0], exprs[1]))
452 blocks[0] = ast_block_new(ctx);
453 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
454 !ast_block_add_expr(blocks[0], exprs[1]))
459 ast_block_set_type(blocks[0], exprs[1]);
461 vec_push(sy->out, syblock(ctx, blocks[0]));
468 if ((out = fold_op(parser->fold, op, exprs)))
470 if (exprs[0]->vtype != TYPE_FLOAT &&
471 exprs[0]->vtype != TYPE_VECTOR) {
472 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
473 type_name[exprs[0]->vtype]);
476 out = (ast_expression*)ast_unary_new(ctx, (VINSTR_NEG_F-TYPE_FLOAT) + exprs[0]->vtype, exprs[0]);
480 if (!(out = fold_op(parser->fold, op, exprs))) {
481 switch (exprs[0]->vtype) {
483 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
486 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
489 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
490 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
494 /* we don't constant-fold NOT for these types */
496 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
499 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
502 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
503 type_name[exprs[0]->vtype]);
510 if (exprs[0]->vtype != exprs[1]->vtype ||
511 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
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]);
518 if (!(out = fold_op(parser->fold, op, exprs))) {
519 switch (exprs[0]->vtype) {
521 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
524 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
527 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
528 type_name[exprs[0]->vtype],
529 type_name[exprs[1]->vtype]);
535 if (exprs[0]->vtype != exprs[1]->vtype ||
536 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
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]);
543 if (!(out = fold_op(parser->fold, op, exprs))) {
544 switch (exprs[0]->vtype) {
546 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
549 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
552 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
553 type_name[exprs[1]->vtype],
554 type_name[exprs[0]->vtype]);
560 if (exprs[0]->vtype != exprs[1]->vtype &&
561 !(exprs[0]->vtype == TYPE_VECTOR &&
562 exprs[1]->vtype == TYPE_FLOAT) &&
563 !(exprs[1]->vtype == TYPE_VECTOR &&
564 exprs[0]->vtype == TYPE_FLOAT)
567 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
568 type_name[exprs[1]->vtype],
569 type_name[exprs[0]->vtype]);
572 if (!(out = fold_op(parser->fold, op, exprs))) {
573 switch (exprs[0]->vtype) {
575 if (exprs[1]->vtype == TYPE_VECTOR)
576 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
578 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
581 if (exprs[1]->vtype == TYPE_FLOAT)
582 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
584 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
587 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
588 type_name[exprs[1]->vtype],
589 type_name[exprs[0]->vtype]);
596 if (exprs[1]->vtype != TYPE_FLOAT) {
597 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
598 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
599 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
602 if (!(out = fold_op(parser->fold, op, exprs))) {
603 if (exprs[0]->vtype == TYPE_FLOAT)
604 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
606 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
607 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
608 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
615 if (NotSameType(TYPE_FLOAT)) {
616 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
617 type_name[exprs[0]->vtype],
618 type_name[exprs[1]->vtype]);
620 } else if (!(out = fold_op(parser->fold, op, exprs))) {
621 /* generate a call to __builtin_mod */
622 ast_expression *mod = intrin_func(parser->intrin, "mod");
623 ast_call *call = NULL;
624 if (!mod) return false; /* can return null for missing floor */
626 call = ast_call_new(parser_ctx(parser), mod);
627 vec_push(call->params, exprs[0]);
628 vec_push(call->params, exprs[1]);
630 out = (ast_expression*)call;
635 compile_error(ctx, "%= is unimplemented");
641 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
642 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
643 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
645 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
646 type_name[exprs[0]->vtype],
647 type_name[exprs[1]->vtype]);
651 if (!(out = fold_op(parser->fold, op, exprs))) {
653 * IF the first expression is float, the following will be too
654 * since scalar ^ vector is not allowed.
656 if (exprs[0]->vtype == TYPE_FLOAT) {
657 out = (ast_expression*)ast_binary_new(ctx,
658 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
662 * The first is a vector: vector is allowed to bitop with vector and
663 * with scalar, branch here for the second operand.
665 if (exprs[1]->vtype == TYPE_VECTOR) {
667 * Bitop all the values of the vector components against the
668 * vectors components in question.
670 out = (ast_expression*)ast_binary_new(ctx,
671 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
674 out = (ast_expression*)ast_binary_new(ctx,
675 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
684 case opid3('<','<','='):
685 case opid3('>','>','='):
686 if(!(out = fold_op(parser->fold, op, exprs))) {
687 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
693 generated_op += 1; /* INSTR_OR */
695 generated_op += INSTR_AND;
696 if (!(out = fold_op(parser->fold, op, exprs))) {
697 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
698 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
699 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
700 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
703 for (i = 0; i < 2; ++i) {
704 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
705 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
707 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
709 exprs[i] = out; out = NULL;
710 if (OPTS_FLAG(PERL_LOGIC)) {
711 /* here we want to keep the right expressions' type */
715 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
716 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
718 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
720 exprs[i] = out; out = NULL;
721 if (OPTS_FLAG(PERL_LOGIC)) {
722 /* here we want to keep the right expressions' type */
727 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
732 if (vec_last(sy->paren) != PAREN_TERNARY2) {
733 compile_error(ctx, "mismatched parenthesis/ternary");
737 if (!ast_compare_type(exprs[1], exprs[2])) {
738 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
739 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
740 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
743 if (!(out = fold_op(parser->fold, op, exprs)))
744 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
747 case opid2('*', '*'):
748 if (NotSameType(TYPE_FLOAT)) {
749 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
750 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
751 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
756 if (!(out = fold_op(parser->fold, op, exprs))) {
757 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
758 vec_push(gencall->params, exprs[0]);
759 vec_push(gencall->params, exprs[1]);
760 out = (ast_expression*)gencall;
764 case opid2('>', '<'):
765 if (NotSameType(TYPE_VECTOR)) {
766 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
767 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
768 compile_error(ctx, "invalid types used in cross product: %s and %s",
773 if (!(out = fold_op(parser->fold, op, exprs))) {
774 out = (ast_expression*)ast_binary_new(
784 case opid3('<','=','>'): /* -1, 0, or 1 */
785 if (NotSameType(TYPE_FLOAT)) {
786 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
787 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
788 compile_error(ctx, "invalid types used in comparision: %s and %s",
794 if (!(out = fold_op(parser->fold, op, exprs))) {
795 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
797 eq->refs = AST_REF_NONE;
800 out = (ast_expression*)ast_ternary_new(ctx,
801 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
803 (ast_expression*)parser->fold->imm_float[2],
806 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
808 (ast_expression*)parser->fold->imm_float[0],
811 (ast_expression*)parser->fold->imm_float[1]
821 generated_op += 1; /* INSTR_GT */
823 generated_op += 1; /* INSTR_LT */
824 case opid2('>', '='):
825 generated_op += 1; /* INSTR_GE */
826 case opid2('<', '='):
827 generated_op += INSTR_LE;
828 if (NotSameType(TYPE_FLOAT)) {
829 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
830 type_name[exprs[0]->vtype],
831 type_name[exprs[1]->vtype]);
834 if (!(out = fold_op(parser->fold, op, exprs)))
835 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
837 case opid2('!', '='):
838 if (exprs[0]->vtype != exprs[1]->vtype) {
839 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
840 type_name[exprs[0]->vtype],
841 type_name[exprs[1]->vtype]);
844 if (!(out = fold_op(parser->fold, op, exprs)))
845 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
847 case opid2('=', '='):
848 if (exprs[0]->vtype != exprs[1]->vtype) {
849 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
850 type_name[exprs[0]->vtype],
851 type_name[exprs[1]->vtype]);
854 if (!(out = fold_op(parser->fold, op, exprs)))
855 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
859 if (ast_istype(exprs[0], ast_entfield)) {
860 ast_expression *field = ((ast_entfield*)exprs[0])->field;
861 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
862 exprs[0]->vtype == TYPE_FIELD &&
863 exprs[0]->next->vtype == TYPE_VECTOR)
865 assignop = type_storep_instr[TYPE_VECTOR];
868 assignop = type_storep_instr[exprs[0]->vtype];
869 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
871 ast_type_to_string(field->next, ty1, sizeof(ty1));
872 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
873 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
874 field->next->vtype == TYPE_FUNCTION &&
875 exprs[1]->vtype == TYPE_FUNCTION)
877 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
878 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
881 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
886 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
887 exprs[0]->vtype == TYPE_FIELD &&
888 exprs[0]->next->vtype == TYPE_VECTOR)
890 assignop = type_store_instr[TYPE_VECTOR];
893 assignop = type_store_instr[exprs[0]->vtype];
896 if (assignop == VINSTR_END) {
897 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
898 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
899 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
901 else if (!ast_compare_type(exprs[0], exprs[1]))
903 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
904 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
905 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
906 exprs[0]->vtype == TYPE_FUNCTION &&
907 exprs[1]->vtype == TYPE_FUNCTION)
909 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
910 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
913 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
916 (void)check_write_to(ctx, exprs[0]);
917 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
919 case opid3('+','+','P'):
920 case opid3('-','-','P'):
922 if (exprs[0]->vtype != TYPE_FLOAT) {
923 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
924 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
927 if (op->id == opid3('+','+','P'))
931 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
932 if (ast_istype(exprs[0], ast_entfield)) {
933 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
935 (ast_expression*)parser->fold->imm_float[1]);
937 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
939 (ast_expression*)parser->fold->imm_float[1]);
942 case opid3('S','+','+'):
943 case opid3('S','-','-'):
945 if (exprs[0]->vtype != TYPE_FLOAT) {
946 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
947 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
950 if (op->id == opid3('S','+','+')) {
957 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
958 if (ast_istype(exprs[0], ast_entfield)) {
959 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
961 (ast_expression*)parser->fold->imm_float[1]);
963 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
965 (ast_expression*)parser->fold->imm_float[1]);
969 out = (ast_expression*)ast_binary_new(ctx, subop,
971 (ast_expression*)parser->fold->imm_float[1]);
975 if (exprs[0]->vtype != exprs[1]->vtype ||
976 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
978 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
979 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
980 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
984 (void)check_write_to(ctx, exprs[0]);
985 if (ast_istype(exprs[0], ast_entfield))
986 assignop = type_storep_instr[exprs[0]->vtype];
988 assignop = type_store_instr[exprs[0]->vtype];
989 switch (exprs[0]->vtype) {
991 out = (ast_expression*)ast_binstore_new(ctx, assignop,
992 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
996 out = (ast_expression*)ast_binstore_new(ctx, assignop,
997 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1001 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1002 type_name[exprs[0]->vtype],
1003 type_name[exprs[1]->vtype]);
1007 case opid2('*','='):
1008 case opid2('/','='):
1009 if (exprs[1]->vtype != TYPE_FLOAT ||
1010 !(exprs[0]->vtype == TYPE_FLOAT ||
1011 exprs[0]->vtype == TYPE_VECTOR))
1013 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1014 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1015 compile_error(ctx, "invalid types used in expression: %s and %s",
1019 (void)check_write_to(ctx, exprs[0]);
1020 if (ast_istype(exprs[0], ast_entfield))
1021 assignop = type_storep_instr[exprs[0]->vtype];
1023 assignop = type_store_instr[exprs[0]->vtype];
1024 switch (exprs[0]->vtype) {
1026 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1027 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1028 exprs[0], exprs[1]);
1031 if (op->id == opid2('*','=')) {
1032 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1033 exprs[0], exprs[1]);
1035 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1036 (ast_expression*)parser->fold->imm_float[1],
1039 compile_error(ctx, "internal error: failed to generate division");
1042 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1047 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1048 type_name[exprs[0]->vtype],
1049 type_name[exprs[1]->vtype]);
1053 case opid2('&','='):
1054 case opid2('|','='):
1055 case opid2('^','='):
1056 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1057 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1058 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1059 compile_error(ctx, "invalid types used in expression: %s and %s",
1063 (void)check_write_to(ctx, exprs[0]);
1064 if (ast_istype(exprs[0], ast_entfield))
1065 assignop = type_storep_instr[exprs[0]->vtype];
1067 assignop = type_store_instr[exprs[0]->vtype];
1068 if (exprs[0]->vtype == TYPE_FLOAT)
1069 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1070 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1071 exprs[0], exprs[1]);
1073 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1074 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1075 exprs[0], exprs[1]);
1077 case opid3('&','~','='):
1078 /* This is like: a &= ~(b);
1079 * But QC has no bitwise-not, so we implement it as
1082 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1083 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1084 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1085 compile_error(ctx, "invalid types used in expression: %s and %s",
1089 if (ast_istype(exprs[0], ast_entfield))
1090 assignop = type_storep_instr[exprs[0]->vtype];
1092 assignop = type_store_instr[exprs[0]->vtype];
1093 if (exprs[0]->vtype == TYPE_FLOAT)
1094 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1096 out = (ast_expression*)ast_binary_new(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1099 (void)check_write_to(ctx, exprs[0]);
1100 if (exprs[0]->vtype == TYPE_FLOAT)
1101 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1103 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1104 asbinstore->keep_dest = true;
1105 out = (ast_expression*)asbinstore;
1108 case opid2('~', 'P'):
1109 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1110 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1111 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1114 if (!(out = fold_op(parser->fold, op, exprs))) {
1115 if (exprs[0]->vtype == TYPE_FLOAT) {
1116 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1118 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1125 compile_error(ctx, "failed to apply operator %s", op->op);
1129 vec_push(sy->out, syexp(ctx, out));
1133 static bool parser_close_call(parser_t *parser, shunt *sy)
1135 /* was a function call */
1136 ast_expression *fun;
1137 ast_value *funval = NULL;
1141 size_t paramcount, i;
1144 fid = vec_last(sy->ops).off;
1145 vec_shrinkby(sy->ops, 1);
1147 /* out[fid] is the function
1148 * everything above is parameters...
1150 if (!vec_size(sy->argc)) {
1151 parseerror(parser, "internal error: no argument counter available");
1155 paramcount = vec_last(sy->argc);
1158 if (vec_size(sy->out) < fid) {
1159 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1160 (unsigned long)vec_size(sy->out),
1162 (unsigned long)paramcount);
1167 * TODO handle this at the intrinsic level with an ast_intrinsic
1170 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1172 if (fid+2 != vec_size(sy->out) ||
1173 vec_last(sy->out).block)
1175 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1178 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1179 ast_unref(vec_last(sy->out).out);
1180 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1181 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1182 vec_shrinkby(sy->out, 1);
1187 * Now we need to determine if the function that is being called is
1188 * an intrinsic so we can evaluate if the arguments to it are constant
1189 * and than fruitfully fold them.
1191 #define fold_can_1(X) \
1192 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1193 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1195 if (fid + 1 < vec_size(sy->out))
1198 for (i = 0; i < paramcount; ++i) {
1199 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1206 * All is well which ends well, if we make it into here we can ignore the
1207 * intrinsic call and just evaluate it i.e constant fold it.
1209 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1210 ast_expression **exprs = NULL;
1211 ast_expression *foldval = NULL;
1213 for (i = 0; i < paramcount; i++)
1214 vec_push(exprs, sy->out[fid+1 + i].out);
1216 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1222 * Blub: what sorts of unreffing and resizing of
1223 * sy->out should I be doing here?
1225 sy->out[fid] = syexp(foldval->node.context, foldval);
1226 vec_shrinkby(sy->out, 1);
1233 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1238 if (fid+1 + paramcount != vec_size(sy->out)) {
1239 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1240 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1244 for (i = 0; i < paramcount; ++i)
1245 vec_push(call->params, sy->out[fid+1 + i].out);
1246 vec_shrinkby(sy->out, paramcount);
1247 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1248 if (parser->max_param_count < paramcount)
1249 parser->max_param_count = paramcount;
1251 if (ast_istype(fun, ast_value)) {
1252 funval = (ast_value*)fun;
1253 if ((fun->flags & AST_FLAG_VARIADIC) &&
1254 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1256 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1260 /* overwrite fid, the function, with a call */
1261 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1263 if (fun->vtype != TYPE_FUNCTION) {
1264 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1269 parseerror(parser, "could not determine function return type");
1272 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1274 if (fun->flags & AST_FLAG_DEPRECATED) {
1276 return !parsewarning(parser, WARN_DEPRECATED,
1277 "call to function (which is marked deprecated)\n",
1278 "-> it has been declared here: %s:%i",
1279 ast_ctx(fun).file, ast_ctx(fun).line);
1282 return !parsewarning(parser, WARN_DEPRECATED,
1283 "call to `%s` (which is marked deprecated)\n"
1284 "-> `%s` declared here: %s:%i",
1285 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1287 return !parsewarning(parser, WARN_DEPRECATED,
1288 "call to `%s` (deprecated: %s)\n"
1289 "-> `%s` declared here: %s:%i",
1290 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1294 if (vec_size(fun->params) != paramcount &&
1295 !((fun->flags & AST_FLAG_VARIADIC) &&
1296 vec_size(fun->params) < paramcount))
1298 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1300 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1301 "too %s parameters for call to %s: expected %i, got %i\n"
1302 " -> `%s` has been declared here: %s:%i",
1303 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1304 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1306 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1307 "too %s parameters for function call: expected %i, got %i\n"
1308 " -> it has been declared here: %s:%i",
1309 fewmany, (int)vec_size(fun->params), (int)paramcount,
1310 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1317 static bool parser_close_paren(parser_t *parser, shunt *sy)
1319 if (!vec_size(sy->ops)) {
1320 parseerror(parser, "unmatched closing paren");
1324 while (vec_size(sy->ops)) {
1325 if (vec_last(sy->ops).isparen) {
1326 if (vec_last(sy->paren) == PAREN_FUNC) {
1328 if (!parser_close_call(parser, sy))
1332 if (vec_last(sy->paren) == PAREN_EXPR) {
1334 if (!vec_size(sy->out)) {
1335 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1336 vec_shrinkby(sy->ops, 1);
1339 vec_shrinkby(sy->ops, 1);
1342 if (vec_last(sy->paren) == PAREN_INDEX) {
1344 /* pop off the parenthesis */
1345 vec_shrinkby(sy->ops, 1);
1346 /* then apply the index operator */
1347 if (!parser_sy_apply_operator(parser, sy))
1351 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1352 vec_last(sy->paren) = PAREN_TERNARY2;
1353 /* pop off the parenthesis */
1354 vec_shrinkby(sy->ops, 1);
1357 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1360 if (!parser_sy_apply_operator(parser, sy))
1366 static void parser_reclassify_token(parser_t *parser)
1369 if (parser->tok >= TOKEN_START)
1371 for (i = 0; i < operator_count; ++i) {
1372 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1373 parser->tok = TOKEN_OPERATOR;
1379 static ast_expression* parse_vararg_do(parser_t *parser)
1381 ast_expression *idx, *out;
1383 ast_value *funtype = parser->function->vtype;
1384 lex_ctx_t ctx = parser_ctx(parser);
1386 if (!parser->function->varargs) {
1387 parseerror(parser, "function has no variable argument list");
1391 if (!parser_next(parser) || parser->tok != '(') {
1392 parseerror(parser, "expected parameter index and type in parenthesis");
1395 if (!parser_next(parser)) {
1396 parseerror(parser, "error parsing parameter index");
1400 idx = parse_expression_leave(parser, true, false, false);
1404 if (parser->tok != ',') {
1405 if (parser->tok != ')') {
1407 parseerror(parser, "expected comma after parameter index");
1410 /* vararg piping: ...(start) */
1411 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1415 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1417 parseerror(parser, "expected typename for vararg");
1421 typevar = parse_typename(parser, NULL, NULL);
1427 if (parser->tok != ')') {
1429 ast_delete(typevar);
1430 parseerror(parser, "expected closing paren");
1434 if (funtype->expression.varparam &&
1435 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1439 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1440 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1441 compile_error(ast_ctx(typevar),
1442 "function was declared to take varargs of type `%s`, requested type is: %s",
1446 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1447 ast_type_adopt(out, typevar);
1448 ast_delete(typevar);
1452 static ast_expression* parse_vararg(parser_t *parser)
1454 bool old_noops = parser->lex->flags.noops;
1456 ast_expression *out;
1458 parser->lex->flags.noops = true;
1459 out = parse_vararg_do(parser);
1461 parser->lex->flags.noops = old_noops;
1465 /* not to be exposed */
1466 bool ftepp_predef_exists(const char *name);
1467 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1469 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1470 parser->tok == TOKEN_IDENT &&
1471 !strcmp(parser_tokval(parser), "_"))
1473 /* a translatable string */
1476 parser->lex->flags.noops = true;
1477 if (!parser_next(parser) || parser->tok != '(') {
1478 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1481 parser->lex->flags.noops = false;
1482 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1483 parseerror(parser, "expected a constant string in translatable-string extension");
1486 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1489 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1491 if (!parser_next(parser) || parser->tok != ')') {
1492 parseerror(parser, "expected closing paren after translatable string");
1497 else if (parser->tok == TOKEN_DOTS)
1500 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1501 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1504 va = parse_vararg(parser);
1507 vec_push(sy->out, syexp(parser_ctx(parser), va));
1510 else if (parser->tok == TOKEN_FLOATCONST) {
1511 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1514 vec_push(sy->out, syexp(parser_ctx(parser), val));
1517 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1518 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1521 vec_push(sy->out, syexp(parser_ctx(parser), val));
1524 else if (parser->tok == TOKEN_STRINGCONST) {
1525 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1528 vec_push(sy->out, syexp(parser_ctx(parser), val));
1531 else if (parser->tok == TOKEN_VECTORCONST) {
1532 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1535 vec_push(sy->out, syexp(parser_ctx(parser), val));
1538 else if (parser->tok == TOKEN_IDENT)
1540 const char *ctoken = parser_tokval(parser);
1541 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1542 ast_expression *var;
1543 /* a_vector.{x,y,z} */
1544 if (!vec_size(sy->ops) ||
1545 !vec_last(sy->ops).etype ||
1546 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1548 /* When adding more intrinsics, fix the above condition */
1551 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1553 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1555 var = parser_find_var(parser, parser_tokval(parser));
1557 var = parser_find_field(parser, parser_tokval(parser));
1559 if (!var && with_labels) {
1560 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1562 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1563 var = (ast_expression*)lbl;
1564 vec_push(parser->labels, lbl);
1567 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1568 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1571 * now we try for the real intrinsic hashtable. If the string
1572 * begins with __builtin, we simply skip past it, otherwise we
1573 * use the identifier as is.
1575 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1576 var = intrin_func(parser->intrin, parser_tokval(parser));
1580 char *correct = NULL;
1584 * sometimes people use preprocessing predefs without enabling them
1585 * i've done this thousands of times already myself. Lets check for
1586 * it in the predef table. And diagnose it better :)
1588 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1589 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1594 * TODO: determine the best score for the identifier: be it
1595 * a variable, a field.
1597 * We should also consider adding correction tables for
1598 * other things as well.
1600 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1602 correct_init(&corr);
1604 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1605 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1606 if (strcmp(correct, parser_tokval(parser))) {
1613 correct_free(&corr);
1616 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1621 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1627 if (ast_istype(var, ast_value)) {
1628 ((ast_value*)var)->uses++;
1630 else if (ast_istype(var, ast_member)) {
1631 ast_member *mem = (ast_member*)var;
1632 if (ast_istype(mem->owner, ast_value))
1633 ((ast_value*)(mem->owner))->uses++;
1636 vec_push(sy->out, syexp(parser_ctx(parser), var));
1639 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1643 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1645 ast_expression *expr = NULL;
1648 bool wantop = false;
1649 /* only warn once about an assignment in a truth value because the current code
1650 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1652 bool warn_parenthesis = true;
1654 /* count the parens because an if starts with one, so the
1655 * end of a condition is an unmatched closing paren
1659 memset(&sy, 0, sizeof(sy));
1661 parser->lex->flags.noops = false;
1663 parser_reclassify_token(parser);
1667 if (parser->tok == TOKEN_TYPENAME) {
1668 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1672 if (parser->tok == TOKEN_OPERATOR)
1674 /* classify the operator */
1675 const oper_info *op;
1676 const oper_info *olast = NULL;
1678 for (o = 0; o < operator_count; ++o) {
1679 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1680 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1681 !strcmp(parser_tokval(parser), operators[o].op))
1686 if (o == operator_count) {
1687 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1690 /* found an operator */
1693 /* when declaring variables, a comma starts a new variable */
1694 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1695 /* fixup the token */
1700 /* a colon without a pervious question mark cannot be a ternary */
1701 if (!ternaries && op->id == opid2(':','?')) {
1706 if (op->id == opid1(',')) {
1707 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1708 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1712 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1713 olast = &operators[vec_last(sy.ops).etype-1];
1715 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1716 while (olast && op->prec < olast->prec)
1718 if (!parser_sy_apply_operator(parser, &sy))
1720 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1721 olast = &operators[vec_last(sy.ops).etype-1];
1726 #define IsAssignOp(x) (\
1727 (x) == opid1('=') || \
1728 (x) == opid2('+','=') || \
1729 (x) == opid2('-','=') || \
1730 (x) == opid2('*','=') || \
1731 (x) == opid2('/','=') || \
1732 (x) == opid2('%','=') || \
1733 (x) == opid2('&','=') || \
1734 (x) == opid2('|','=') || \
1735 (x) == opid3('&','~','=') \
1737 if (warn_parenthesis) {
1738 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1739 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1740 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1743 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1744 warn_parenthesis = false;
1747 if (olast && olast->id != op->id) {
1748 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1749 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1751 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1752 warn_parenthesis = false;
1754 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1755 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1757 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1758 warn_parenthesis = false;
1764 (op->prec < olast->prec) ||
1765 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1767 if (!parser_sy_apply_operator(parser, &sy))
1769 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1770 olast = &operators[vec_last(sy.ops).etype-1];
1775 if (op->id == opid1('(')) {
1777 size_t sycount = vec_size(sy.out);
1778 /* we expected an operator, this is the function-call operator */
1779 vec_push(sy.paren, PAREN_FUNC);
1780 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1781 vec_push(sy.argc, 0);
1783 vec_push(sy.paren, PAREN_EXPR);
1784 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1787 } else if (op->id == opid1('[')) {
1789 parseerror(parser, "unexpected array subscript");
1792 vec_push(sy.paren, PAREN_INDEX);
1793 /* push both the operator and the paren, this makes life easier */
1794 vec_push(sy.ops, syop(parser_ctx(parser), op));
1795 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1797 } else if (op->id == opid2('?',':')) {
1798 vec_push(sy.ops, syop(parser_ctx(parser), op));
1799 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1802 vec_push(sy.paren, PAREN_TERNARY1);
1803 } else if (op->id == opid2(':','?')) {
1804 if (!vec_size(sy.paren)) {
1805 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1808 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1809 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1812 if (!parser_close_paren(parser, &sy))
1814 vec_push(sy.ops, syop(parser_ctx(parser), op));
1818 vec_push(sy.ops, syop(parser_ctx(parser), op));
1819 wantop = !!(op->flags & OP_SUFFIX);
1822 else if (parser->tok == ')') {
1823 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1824 if (!parser_sy_apply_operator(parser, &sy))
1827 if (!vec_size(sy.paren))
1830 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1831 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1834 if (!parser_close_paren(parser, &sy))
1837 /* must be a function call without parameters */
1838 if (vec_last(sy.paren) != PAREN_FUNC) {
1839 parseerror(parser, "closing paren in invalid position");
1842 if (!parser_close_paren(parser, &sy))
1847 else if (parser->tok == '(') {
1848 parseerror(parser, "internal error: '(' should be classified as operator");
1851 else if (parser->tok == '[') {
1852 parseerror(parser, "internal error: '[' should be classified as operator");
1855 else if (parser->tok == ']') {
1856 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1857 if (!parser_sy_apply_operator(parser, &sy))
1860 if (!vec_size(sy.paren))
1862 if (vec_last(sy.paren) != PAREN_INDEX) {
1863 parseerror(parser, "mismatched parentheses, unexpected ']'");
1866 if (!parser_close_paren(parser, &sy))
1871 if (!parse_sya_operand(parser, &sy, with_labels))
1874 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1875 vec_last(sy.argc)++;
1880 /* in this case we might want to allow constant string concatenation */
1881 bool concatenated = false;
1882 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1883 ast_expression *lexpr = vec_last(sy.out).out;
1884 if (ast_istype(lexpr, ast_value)) {
1885 ast_value *last = (ast_value*)lexpr;
1886 if (last->isimm == true && last->cvq == CV_CONST &&
1887 last->hasvalue && last->expression.vtype == TYPE_STRING)
1889 char *newstr = NULL;
1890 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1891 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1893 concatenated = true;
1897 if (!concatenated) {
1898 parseerror(parser, "expected operator or end of statement");
1903 if (!parser_next(parser)) {
1906 if (parser->tok == ';' ||
1907 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1908 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1914 while (vec_size(sy.ops)) {
1915 if (!parser_sy_apply_operator(parser, &sy))
1919 parser->lex->flags.noops = true;
1920 if (vec_size(sy.out) != 1) {
1921 parseerror(parser, "expression expected");
1924 expr = sy.out[0].out;
1927 if (vec_size(sy.paren)) {
1928 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1936 parser->lex->flags.noops = true;
1937 for (i = 0; i < vec_size(sy.out); ++i) {
1939 ast_unref(sy.out[i].out);
1948 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1950 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1953 if (parser->tok != ';') {
1954 parseerror(parser, "semicolon expected after expression");
1958 if (!parser_next(parser)) {
1965 static void parser_enterblock(parser_t *parser)
1967 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1968 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1969 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1970 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1971 vec_push(parser->_block_ctx, parser_ctx(parser));
1974 vec_push(parser->correct_variables, correct_trie_new());
1975 vec_push(parser->correct_variables_score, NULL);
1978 static bool parser_leaveblock(parser_t *parser)
1981 size_t locals, typedefs;
1983 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1984 parseerror(parser, "internal error: parser_leaveblock with no block");
1988 util_htdel(vec_last(parser->variables));
1989 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1991 vec_pop(parser->variables);
1992 vec_pop(parser->correct_variables);
1993 vec_pop(parser->correct_variables_score);
1994 if (!vec_size(parser->_blocklocals)) {
1995 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1999 locals = vec_last(parser->_blocklocals);
2000 vec_pop(parser->_blocklocals);
2001 while (vec_size(parser->_locals) != locals) {
2002 ast_expression *e = vec_last(parser->_locals);
2003 ast_value *v = (ast_value*)e;
2004 vec_pop(parser->_locals);
2005 if (ast_istype(e, ast_value) && !v->uses) {
2006 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2011 typedefs = vec_last(parser->_blocktypedefs);
2012 while (vec_size(parser->_typedefs) != typedefs) {
2013 ast_delete(vec_last(parser->_typedefs));
2014 vec_pop(parser->_typedefs);
2016 util_htdel(vec_last(parser->typedefs));
2017 vec_pop(parser->typedefs);
2019 vec_pop(parser->_block_ctx);
2024 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2026 vec_push(parser->_locals, e);
2027 util_htset(vec_last(parser->variables), name, (void*)e);
2031 vec_last(parser->correct_variables),
2032 &vec_last(parser->correct_variables_score),
2037 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2039 vec_push(parser->globals, e);
2040 util_htset(parser->htglobals, name, e);
2044 parser->correct_variables[0],
2045 &parser->correct_variables_score[0],
2050 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2054 ast_expression *prev;
2056 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2058 ast_type_to_string(cond, ty, sizeof(ty));
2059 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2062 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2065 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2068 parseerror(parser, "internal error: failed to process condition");
2073 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2075 /* vector types need to be cast to true booleans */
2076 ast_binary *bin = (ast_binary*)cond;
2077 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2079 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2081 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2084 parseerror(parser, "internal error: failed to process condition");
2091 unary = (ast_unary*)cond;
2092 /* ast_istype dereferences cond, should test here for safety */
2093 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2095 cond = unary->operand;
2096 unary->operand = NULL;
2099 unary = (ast_unary*)cond;
2103 parseerror(parser, "internal error: failed to process condition");
2105 if (ifnot) *_ifnot = !*_ifnot;
2109 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2112 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2115 lex_ctx_t ctx = parser_ctx(parser);
2117 (void)block; /* not touching */
2119 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2120 if (!parser_next(parser)) {
2121 parseerror(parser, "expected condition or 'not'");
2124 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2126 if (!parser_next(parser)) {
2127 parseerror(parser, "expected condition in parenthesis");
2131 if (parser->tok != '(') {
2132 parseerror(parser, "expected 'if' condition in parenthesis");
2135 /* parse into the expression */
2136 if (!parser_next(parser)) {
2137 parseerror(parser, "expected 'if' condition after opening paren");
2140 /* parse the condition */
2141 cond = parse_expression_leave(parser, false, true, false);
2145 if (parser->tok != ')') {
2146 parseerror(parser, "expected closing paren after 'if' condition");
2150 /* parse into the 'then' branch */
2151 if (!parser_next(parser)) {
2152 parseerror(parser, "expected statement for on-true branch of 'if'");
2156 if (!parse_statement_or_block(parser, &ontrue)) {
2161 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2162 /* check for an else */
2163 if (!strcmp(parser_tokval(parser), "else")) {
2164 /* parse into the 'else' branch */
2165 if (!parser_next(parser)) {
2166 parseerror(parser, "expected on-false branch after 'else'");
2171 if (!parse_statement_or_block(parser, &onfalse)) {
2178 cond = process_condition(parser, cond, &ifnot);
2180 if (ontrue) ast_delete(ontrue);
2181 if (onfalse) ast_delete(onfalse);
2186 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2188 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2189 *out = (ast_expression*)ifthen;
2193 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2194 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2199 /* skip the 'while' and get the body */
2200 if (!parser_next(parser)) {
2201 if (OPTS_FLAG(LOOP_LABELS))
2202 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2204 parseerror(parser, "expected 'while' condition in parenthesis");
2208 if (parser->tok == ':') {
2209 if (!OPTS_FLAG(LOOP_LABELS))
2210 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2211 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2212 parseerror(parser, "expected loop label");
2215 label = util_strdup(parser_tokval(parser));
2216 if (!parser_next(parser)) {
2218 parseerror(parser, "expected 'while' condition in parenthesis");
2223 if (parser->tok != '(') {
2224 parseerror(parser, "expected 'while' condition in parenthesis");
2228 vec_push(parser->breaks, label);
2229 vec_push(parser->continues, label);
2231 rv = parse_while_go(parser, block, out);
2234 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2235 parseerror(parser, "internal error: label stack corrupted");
2241 vec_pop(parser->breaks);
2242 vec_pop(parser->continues);
2247 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2250 ast_expression *cond, *ontrue;
2254 lex_ctx_t ctx = parser_ctx(parser);
2256 (void)block; /* not touching */
2258 /* parse into the expression */
2259 if (!parser_next(parser)) {
2260 parseerror(parser, "expected 'while' condition after opening paren");
2263 /* parse the condition */
2264 cond = parse_expression_leave(parser, false, true, false);
2268 if (parser->tok != ')') {
2269 parseerror(parser, "expected closing paren after 'while' condition");
2273 /* parse into the 'then' branch */
2274 if (!parser_next(parser)) {
2275 parseerror(parser, "expected while-loop body");
2279 if (!parse_statement_or_block(parser, &ontrue)) {
2284 cond = process_condition(parser, cond, &ifnot);
2289 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2290 *out = (ast_expression*)aloop;
2294 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2295 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2300 /* skip the 'do' and get the body */
2301 if (!parser_next(parser)) {
2302 if (OPTS_FLAG(LOOP_LABELS))
2303 parseerror(parser, "expected loop label or body");
2305 parseerror(parser, "expected loop body");
2309 if (parser->tok == ':') {
2310 if (!OPTS_FLAG(LOOP_LABELS))
2311 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2312 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2313 parseerror(parser, "expected loop label");
2316 label = util_strdup(parser_tokval(parser));
2317 if (!parser_next(parser)) {
2319 parseerror(parser, "expected loop body");
2324 vec_push(parser->breaks, label);
2325 vec_push(parser->continues, label);
2327 rv = parse_dowhile_go(parser, block, out);
2330 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2331 parseerror(parser, "internal error: label stack corrupted");
2334 * Test for NULL otherwise ast_delete dereferences null pointer
2342 vec_pop(parser->breaks);
2343 vec_pop(parser->continues);
2348 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2351 ast_expression *cond, *ontrue;
2355 lex_ctx_t ctx = parser_ctx(parser);
2357 (void)block; /* not touching */
2359 if (!parse_statement_or_block(parser, &ontrue))
2362 /* expect the "while" */
2363 if (parser->tok != TOKEN_KEYWORD ||
2364 strcmp(parser_tokval(parser), "while"))
2366 parseerror(parser, "expected 'while' and condition");
2371 /* skip the 'while' and check for opening paren */
2372 if (!parser_next(parser) || parser->tok != '(') {
2373 parseerror(parser, "expected 'while' condition in parenthesis");
2377 /* parse into the expression */
2378 if (!parser_next(parser)) {
2379 parseerror(parser, "expected 'while' condition after opening paren");
2383 /* parse the condition */
2384 cond = parse_expression_leave(parser, false, true, false);
2388 if (parser->tok != ')') {
2389 parseerror(parser, "expected closing paren after 'while' condition");
2395 if (!parser_next(parser) || parser->tok != ';') {
2396 parseerror(parser, "expected semicolon after condition");
2402 if (!parser_next(parser)) {
2403 parseerror(parser, "parse error");
2409 cond = process_condition(parser, cond, &ifnot);
2414 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2415 *out = (ast_expression*)aloop;
2419 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2420 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2425 /* skip the 'for' and check for opening paren */
2426 if (!parser_next(parser)) {
2427 if (OPTS_FLAG(LOOP_LABELS))
2428 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2430 parseerror(parser, "expected 'for' expressions in parenthesis");
2434 if (parser->tok == ':') {
2435 if (!OPTS_FLAG(LOOP_LABELS))
2436 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2437 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2438 parseerror(parser, "expected loop label");
2441 label = util_strdup(parser_tokval(parser));
2442 if (!parser_next(parser)) {
2444 parseerror(parser, "expected 'for' expressions in parenthesis");
2449 if (parser->tok != '(') {
2450 parseerror(parser, "expected 'for' expressions in parenthesis");
2454 vec_push(parser->breaks, label);
2455 vec_push(parser->continues, label);
2457 rv = parse_for_go(parser, block, out);
2460 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2461 parseerror(parser, "internal error: label stack corrupted");
2467 vec_pop(parser->breaks);
2468 vec_pop(parser->continues);
2472 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2475 ast_expression *initexpr, *cond, *increment, *ontrue;
2480 lex_ctx_t ctx = parser_ctx(parser);
2482 parser_enterblock(parser);
2489 /* parse into the expression */
2490 if (!parser_next(parser)) {
2491 parseerror(parser, "expected 'for' initializer after opening paren");
2496 if (parser->tok == TOKEN_IDENT)
2497 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2499 if (typevar || parser->tok == TOKEN_TYPENAME) {
2501 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2502 if (parsewarning(parser, WARN_EXTENSIONS,
2503 "current standard does not allow variable declarations in for-loop initializers"))
2507 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2510 else if (parser->tok != ';')
2512 initexpr = parse_expression_leave(parser, false, false, false);
2517 /* move on to condition */
2518 if (parser->tok != ';') {
2519 parseerror(parser, "expected semicolon after for-loop initializer");
2522 if (!parser_next(parser)) {
2523 parseerror(parser, "expected for-loop condition");
2527 /* parse the condition */
2528 if (parser->tok != ';') {
2529 cond = parse_expression_leave(parser, false, true, false);
2534 /* move on to incrementor */
2535 if (parser->tok != ';') {
2536 parseerror(parser, "expected semicolon after for-loop initializer");
2539 if (!parser_next(parser)) {
2540 parseerror(parser, "expected for-loop condition");
2544 /* parse the incrementor */
2545 if (parser->tok != ')') {
2546 lex_ctx_t condctx = parser_ctx(parser);
2547 increment = parse_expression_leave(parser, false, false, false);
2550 if (!ast_side_effects(increment)) {
2551 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2557 if (parser->tok != ')') {
2558 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2561 /* parse into the 'then' branch */
2562 if (!parser_next(parser)) {
2563 parseerror(parser, "expected for-loop body");
2566 if (!parse_statement_or_block(parser, &ontrue))
2570 cond = process_condition(parser, cond, &ifnot);
2574 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2575 *out = (ast_expression*)aloop;
2577 if (!parser_leaveblock(parser)) {
2583 if (initexpr) ast_unref(initexpr);
2584 if (cond) ast_unref(cond);
2585 if (increment) ast_unref(increment);
2586 (void)!parser_leaveblock(parser);
2590 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2592 ast_expression *exp = NULL;
2593 ast_expression *var = NULL;
2594 ast_return *ret = NULL;
2595 ast_value *retval = parser->function->return_value;
2596 ast_value *expected = parser->function->vtype;
2598 lex_ctx_t ctx = parser_ctx(parser);
2600 (void)block; /* not touching */
2602 if (!parser_next(parser)) {
2603 parseerror(parser, "expected return expression");
2607 /* return assignments */
2608 if (parser->tok == '=') {
2609 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2610 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2614 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2616 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2617 parseerror(parser, "invalid return type: `%s'", ty1);
2621 if (!parser_next(parser)) {
2622 parseerror(parser, "expected return assignment expression");
2626 if (!(exp = parse_expression_leave(parser, false, false, false)))
2629 /* prepare the return value */
2631 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2632 ast_type_adopt(retval, expected->expression.next);
2633 parser->function->return_value = retval;
2636 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2637 char ty1[1024], ty2[1024];
2638 ast_type_to_string(exp, ty1, sizeof(ty1));
2639 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2640 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2643 /* store to 'return' local variable */
2644 var = (ast_expression*)ast_store_new(
2646 type_store_instr[expected->expression.next->vtype],
2647 (ast_expression*)retval, exp);
2654 if (parser->tok != ';')
2655 parseerror(parser, "missing semicolon after return assignment");
2656 else if (!parser_next(parser))
2657 parseerror(parser, "parse error after return assignment");
2663 if (parser->tok != ';') {
2664 exp = parse_expression(parser, false, false);
2668 if (exp->vtype != TYPE_NIL &&
2669 exp->vtype != ((ast_expression*)expected)->next->vtype)
2671 parseerror(parser, "return with invalid expression");
2674 ret = ast_return_new(ctx, exp);
2680 if (!parser_next(parser))
2681 parseerror(parser, "parse error");
2683 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2685 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2687 ret = ast_return_new(ctx, (ast_expression*)retval);
2689 *out = (ast_expression*)ret;
2693 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2696 unsigned int levels = 0;
2697 lex_ctx_t ctx = parser_ctx(parser);
2698 const char **loops = (is_continue ? parser->continues : parser->breaks);
2700 (void)block; /* not touching */
2701 if (!parser_next(parser)) {
2702 parseerror(parser, "expected semicolon or loop label");
2706 if (!vec_size(loops)) {
2708 parseerror(parser, "`continue` can only be used inside loops");
2710 parseerror(parser, "`break` can only be used inside loops or switches");
2713 if (parser->tok == TOKEN_IDENT) {
2714 if (!OPTS_FLAG(LOOP_LABELS))
2715 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2716 i = vec_size(loops);
2718 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2721 parseerror(parser, "no such loop to %s: `%s`",
2722 (is_continue ? "continue" : "break out of"),
2723 parser_tokval(parser));
2728 if (!parser_next(parser)) {
2729 parseerror(parser, "expected semicolon");
2734 if (parser->tok != ';') {
2735 parseerror(parser, "expected semicolon");
2739 if (!parser_next(parser))
2740 parseerror(parser, "parse error");
2742 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2746 /* returns true when it was a variable qualifier, false otherwise!
2747 * on error, cvq is set to CV_WRONG
2749 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2751 bool had_const = false;
2752 bool had_var = false;
2753 bool had_noref = false;
2754 bool had_attrib = false;
2755 bool had_static = false;
2760 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2762 /* parse an attribute */
2763 if (!parser_next(parser)) {
2764 parseerror(parser, "expected attribute after `[[`");
2768 if (!strcmp(parser_tokval(parser), "noreturn")) {
2769 flags |= AST_FLAG_NORETURN;
2770 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2771 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2776 else if (!strcmp(parser_tokval(parser), "noref")) {
2778 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2779 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2784 else if (!strcmp(parser_tokval(parser), "inline")) {
2785 flags |= AST_FLAG_INLINE;
2786 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2787 parseerror(parser, "`inline` attribute has no parameters, expected `]]`");
2792 else if (!strcmp(parser_tokval(parser), "eraseable")) {
2793 flags |= AST_FLAG_ERASEABLE;
2794 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2795 parseerror(parser, "`eraseable` attribute has no parameters, expected `]]`");
2800 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2801 flags |= AST_FLAG_ALIAS;
2804 if (!parser_next(parser)) {
2805 parseerror(parser, "parse error in attribute");
2809 if (parser->tok == '(') {
2810 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2811 parseerror(parser, "`alias` attribute missing parameter");
2815 *message = util_strdup(parser_tokval(parser));
2817 if (!parser_next(parser)) {
2818 parseerror(parser, "parse error in attribute");
2822 if (parser->tok != ')') {
2823 parseerror(parser, "`alias` attribute expected `)` after parameter");
2827 if (!parser_next(parser)) {
2828 parseerror(parser, "parse error in attribute");
2833 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2834 parseerror(parser, "`alias` attribute expected `]]`");
2838 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2839 flags |= AST_FLAG_DEPRECATED;
2842 if (!parser_next(parser)) {
2843 parseerror(parser, "parse error in attribute");
2847 if (parser->tok == '(') {
2848 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2849 parseerror(parser, "`deprecated` attribute missing parameter");
2853 *message = util_strdup(parser_tokval(parser));
2855 if (!parser_next(parser)) {
2856 parseerror(parser, "parse error in attribute");
2860 if(parser->tok != ')') {
2861 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2865 if (!parser_next(parser)) {
2866 parseerror(parser, "parse error in attribute");
2871 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2872 parseerror(parser, "`deprecated` attribute expected `]]`");
2875 if (*message) mem_d(*message);
2883 /* Skip tokens until we hit a ]] */
2884 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2885 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2886 if (!parser_next(parser)) {
2887 parseerror(parser, "error inside attribute");
2894 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2896 else if (!strcmp(parser_tokval(parser), "const"))
2898 else if (!strcmp(parser_tokval(parser), "var"))
2900 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2902 else if (!strcmp(parser_tokval(parser), "noref"))
2904 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2909 if (!parser_next(parser))
2919 *is_static = had_static;
2923 parseerror(parser, "parse error after variable qualifier");
2928 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2929 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2934 /* skip the 'while' and get the body */
2935 if (!parser_next(parser)) {
2936 if (OPTS_FLAG(LOOP_LABELS))
2937 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2939 parseerror(parser, "expected 'switch' operand in parenthesis");
2943 if (parser->tok == ':') {
2944 if (!OPTS_FLAG(LOOP_LABELS))
2945 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2946 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2947 parseerror(parser, "expected loop label");
2950 label = util_strdup(parser_tokval(parser));
2951 if (!parser_next(parser)) {
2953 parseerror(parser, "expected 'switch' operand in parenthesis");
2958 if (parser->tok != '(') {
2959 parseerror(parser, "expected 'switch' operand in parenthesis");
2963 vec_push(parser->breaks, label);
2965 rv = parse_switch_go(parser, block, out);
2968 if (vec_last(parser->breaks) != label) {
2969 parseerror(parser, "internal error: label stack corrupted");
2975 vec_pop(parser->breaks);
2980 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2982 ast_expression *operand;
2985 ast_switch *switchnode;
2986 ast_switch_case swcase;
2989 bool noref, is_static;
2990 uint32_t qflags = 0;
2992 lex_ctx_t ctx = parser_ctx(parser);
2994 (void)block; /* not touching */
2997 /* parse into the expression */
2998 if (!parser_next(parser)) {
2999 parseerror(parser, "expected switch operand");
3002 /* parse the operand */
3003 operand = parse_expression_leave(parser, false, false, false);
3007 switchnode = ast_switch_new(ctx, operand);
3010 if (parser->tok != ')') {
3011 ast_delete(switchnode);
3012 parseerror(parser, "expected closing paren after 'switch' operand");
3016 /* parse over the opening paren */
3017 if (!parser_next(parser) || parser->tok != '{') {
3018 ast_delete(switchnode);
3019 parseerror(parser, "expected list of cases");
3023 if (!parser_next(parser)) {
3024 ast_delete(switchnode);
3025 parseerror(parser, "expected 'case' or 'default'");
3029 /* new block; allow some variables to be declared here */
3030 parser_enterblock(parser);
3033 if (parser->tok == TOKEN_IDENT)
3034 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3035 if (typevar || parser->tok == TOKEN_TYPENAME) {
3036 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3037 ast_delete(switchnode);
3042 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3044 if (cvq == CV_WRONG) {
3045 ast_delete(switchnode);
3048 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3049 ast_delete(switchnode);
3058 while (parser->tok != '}') {
3059 ast_block *caseblock;
3061 if (!strcmp(parser_tokval(parser), "case")) {
3062 if (!parser_next(parser)) {
3063 ast_delete(switchnode);
3064 parseerror(parser, "expected expression for case");
3067 swcase.value = parse_expression_leave(parser, false, false, false);
3068 if (!swcase.value) {
3069 ast_delete(switchnode);
3070 parseerror(parser, "expected expression for case");
3073 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3074 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3075 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3081 else if (!strcmp(parser_tokval(parser), "default")) {
3082 swcase.value = NULL;
3083 if (!parser_next(parser)) {
3084 ast_delete(switchnode);
3085 parseerror(parser, "expected colon");
3090 ast_delete(switchnode);
3091 parseerror(parser, "expected 'case' or 'default'");
3095 /* Now the colon and body */
3096 if (parser->tok != ':') {
3097 if (swcase.value) ast_unref(swcase.value);
3098 ast_delete(switchnode);
3099 parseerror(parser, "expected colon");
3103 if (!parser_next(parser)) {
3104 if (swcase.value) ast_unref(swcase.value);
3105 ast_delete(switchnode);
3106 parseerror(parser, "expected statements or case");
3109 caseblock = ast_block_new(parser_ctx(parser));
3111 if (swcase.value) ast_unref(swcase.value);
3112 ast_delete(switchnode);
3115 swcase.code = (ast_expression*)caseblock;
3116 vec_push(switchnode->cases, swcase);
3118 ast_expression *expr;
3119 if (parser->tok == '}')
3121 if (parser->tok == TOKEN_KEYWORD) {
3122 if (!strcmp(parser_tokval(parser), "case") ||
3123 !strcmp(parser_tokval(parser), "default"))
3128 if (!parse_statement(parser, caseblock, &expr, true)) {
3129 ast_delete(switchnode);
3134 if (!ast_block_add_expr(caseblock, expr)) {
3135 ast_delete(switchnode);
3141 parser_leaveblock(parser);
3144 if (parser->tok != '}') {
3145 ast_delete(switchnode);
3146 parseerror(parser, "expected closing paren of case list");
3149 if (!parser_next(parser)) {
3150 ast_delete(switchnode);
3151 parseerror(parser, "parse error after switch");
3154 *out = (ast_expression*)switchnode;
3158 /* parse computed goto sides */
3159 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3160 ast_expression *on_true;
3161 ast_expression *on_false;
3162 ast_expression *cond;
3167 if (ast_istype(*side, ast_ternary)) {
3168 ast_ternary *tern = (ast_ternary*)*side;
3169 on_true = parse_goto_computed(parser, &tern->on_true);
3170 on_false = parse_goto_computed(parser, &tern->on_false);
3172 if (!on_true || !on_false) {
3173 parseerror(parser, "expected label or expression in ternary");
3174 if (on_true) ast_unref(on_true);
3175 if (on_false) ast_unref(on_false);
3183 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3184 } else if (ast_istype(*side, ast_label)) {
3185 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3186 ast_goto_set_label(gt, ((ast_label*)*side));
3188 return (ast_expression*)gt;
3193 static bool parse_goto(parser_t *parser, ast_expression **out)
3195 ast_goto *gt = NULL;
3196 ast_expression *lbl;
3198 if (!parser_next(parser))
3201 if (parser->tok != TOKEN_IDENT) {
3202 ast_expression *expression;
3204 /* could be an expression i.e computed goto :-) */
3205 if (parser->tok != '(') {
3206 parseerror(parser, "expected label name after `goto`");
3210 /* failed to parse expression for goto */
3211 if (!(expression = parse_expression(parser, false, true)) ||
3212 !(*out = parse_goto_computed(parser, &expression))) {
3213 parseerror(parser, "invalid goto expression");
3215 ast_unref(expression);
3222 /* not computed goto */
3223 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3224 lbl = parser_find_label(parser, gt->name);
3226 if (!ast_istype(lbl, ast_label)) {
3227 parseerror(parser, "internal error: label is not an ast_label");
3231 ast_goto_set_label(gt, (ast_label*)lbl);
3234 vec_push(parser->gotos, gt);
3236 if (!parser_next(parser) || parser->tok != ';') {
3237 parseerror(parser, "semicolon expected after goto label");
3240 if (!parser_next(parser)) {
3241 parseerror(parser, "parse error after goto");
3245 *out = (ast_expression*)gt;
3249 static bool parse_skipwhite(parser_t *parser)
3252 if (!parser_next(parser))
3254 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3255 return parser->tok < TOKEN_ERROR;
3258 static bool parse_eol(parser_t *parser)
3260 if (!parse_skipwhite(parser))
3262 return parser->tok == TOKEN_EOL;
3265 static bool parse_pragma_do(parser_t *parser)
3267 if (!parser_next(parser) ||
3268 parser->tok != TOKEN_IDENT ||
3269 strcmp(parser_tokval(parser), "pragma"))
3271 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3274 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3275 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3279 if (!strcmp(parser_tokval(parser), "noref")) {
3280 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3281 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3284 parser->noref = !!parser_token(parser)->constval.i;
3285 if (!parse_eol(parser)) {
3286 parseerror(parser, "parse error after `noref` pragma");
3292 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3295 while (!parse_eol(parser)) {
3296 parser_next(parser);
3305 static bool parse_pragma(parser_t *parser)
3308 parser->lex->flags.preprocessing = true;
3309 parser->lex->flags.mergelines = true;
3310 rv = parse_pragma_do(parser);
3311 if (parser->tok != TOKEN_EOL) {
3312 parseerror(parser, "junk after pragma");
3315 parser->lex->flags.preprocessing = false;
3316 parser->lex->flags.mergelines = false;
3317 if (!parser_next(parser)) {
3318 parseerror(parser, "parse error after pragma");
3324 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3326 bool noref, is_static;
3328 uint32_t qflags = 0;
3329 ast_value *typevar = NULL;
3330 char *vstring = NULL;
3334 if (parser->tok == TOKEN_IDENT)
3335 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3337 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3339 /* local variable */
3341 parseerror(parser, "cannot declare a variable from here");
3344 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3345 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3348 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3352 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3354 if (cvq == CV_WRONG)
3356 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3358 else if (parser->tok == TOKEN_KEYWORD)
3360 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3365 if (!parser_next(parser)) {
3366 parseerror(parser, "parse error after __builtin_debug_printtype");
3370 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3372 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3373 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3374 if (!parser_next(parser)) {
3375 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3381 if (!parse_statement(parser, block, out, allow_cases))
3384 con_out("__builtin_debug_printtype: got no output node\n");
3387 ast_type_to_string(*out, ty, sizeof(ty));
3388 con_out("__builtin_debug_printtype: `%s`\n", ty);
3393 else if (!strcmp(parser_tokval(parser), "return"))
3395 return parse_return(parser, block, out);
3397 else if (!strcmp(parser_tokval(parser), "if"))
3399 return parse_if(parser, block, out);
3401 else if (!strcmp(parser_tokval(parser), "while"))
3403 return parse_while(parser, block, out);
3405 else if (!strcmp(parser_tokval(parser), "do"))
3407 return parse_dowhile(parser, block, out);
3409 else if (!strcmp(parser_tokval(parser), "for"))
3411 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3412 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3415 return parse_for(parser, block, out);
3417 else if (!strcmp(parser_tokval(parser), "break"))
3419 return parse_break_continue(parser, block, out, false);
3421 else if (!strcmp(parser_tokval(parser), "continue"))
3423 return parse_break_continue(parser, block, out, true);
3425 else if (!strcmp(parser_tokval(parser), "switch"))
3427 return parse_switch(parser, block, out);
3429 else if (!strcmp(parser_tokval(parser), "case") ||
3430 !strcmp(parser_tokval(parser), "default"))
3433 parseerror(parser, "unexpected 'case' label");
3438 else if (!strcmp(parser_tokval(parser), "goto"))
3440 return parse_goto(parser, out);
3442 else if (!strcmp(parser_tokval(parser), "typedef"))
3444 if (!parser_next(parser)) {
3445 parseerror(parser, "expected type definition after 'typedef'");
3448 return parse_typedef(parser);
3450 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3453 else if (parser->tok == '{')
3456 inner = parse_block(parser);
3459 *out = (ast_expression*)inner;
3462 else if (parser->tok == ':')
3466 if (!parser_next(parser)) {
3467 parseerror(parser, "expected label name");
3470 if (parser->tok != TOKEN_IDENT) {
3471 parseerror(parser, "label must be an identifier");
3474 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3476 if (!label->undefined) {
3477 parseerror(parser, "label `%s` already defined", label->name);
3480 label->undefined = false;
3483 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3484 vec_push(parser->labels, label);
3486 *out = (ast_expression*)label;
3487 if (!parser_next(parser)) {
3488 parseerror(parser, "parse error after label");
3491 for (i = 0; i < vec_size(parser->gotos); ++i) {
3492 if (!strcmp(parser->gotos[i]->name, label->name)) {
3493 ast_goto_set_label(parser->gotos[i], label);
3494 vec_remove(parser->gotos, i, 1);
3500 else if (parser->tok == ';')
3502 if (!parser_next(parser)) {
3503 parseerror(parser, "parse error after empty statement");
3510 lex_ctx_t ctx = parser_ctx(parser);
3511 ast_expression *exp = parse_expression(parser, false, false);
3515 if (!ast_side_effects(exp)) {
3516 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3523 static bool parse_enum(parser_t *parser)
3526 bool reverse = false;
3528 ast_value **values = NULL;
3529 ast_value *var = NULL;
3532 ast_expression *old;
3534 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3535 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3539 /* enumeration attributes (can add more later) */
3540 if (parser->tok == ':') {
3541 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3542 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3547 if (!strcmp(parser_tokval(parser), "flag")) {
3551 else if (!strcmp(parser_tokval(parser), "reverse")) {
3555 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3559 if (!parser_next(parser) || parser->tok != '{') {
3560 parseerror(parser, "expected `{` after enum attribute ");
3566 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3567 if (parser->tok == '}') {
3568 /* allow an empty enum */
3571 parseerror(parser, "expected identifier or `}`");
3575 old = parser_find_field(parser, parser_tokval(parser));
3577 old = parser_find_global(parser, parser_tokval(parser));
3579 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3580 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3584 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3585 vec_push(values, var);
3586 var->cvq = CV_CONST;
3587 var->hasvalue = true;
3589 /* for flagged enumerations increment in POTs of TWO */
3590 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3591 parser_addglobal(parser, var->name, (ast_expression*)var);
3593 if (!parser_next(parser)) {
3594 parseerror(parser, "expected `=`, `}` or comma after identifier");
3598 if (parser->tok == ',')
3600 if (parser->tok == '}')
3602 if (parser->tok != '=') {
3603 parseerror(parser, "expected `=`, `}` or comma after identifier");
3607 if (!parser_next(parser)) {
3608 parseerror(parser, "expected expression after `=`");
3612 /* We got a value! */
3613 old = parse_expression_leave(parser, true, false, false);
3614 asvalue = (ast_value*)old;
3615 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3616 compile_error(ast_ctx(var), "constant value or expression expected");
3619 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3621 if (parser->tok == '}')
3623 if (parser->tok != ',') {
3624 parseerror(parser, "expected `}` or comma after expression");
3629 /* patch them all (for reversed attribute) */
3632 for (i = 0; i < vec_size(values); i++)
3633 values[i]->constval.vfloat = vec_size(values) - i - 1;
3636 if (parser->tok != '}') {
3637 parseerror(parser, "internal error: breaking without `}`");
3641 if (!parser_next(parser) || parser->tok != ';') {
3642 parseerror(parser, "expected semicolon after enumeration");
3646 if (!parser_next(parser)) {
3647 parseerror(parser, "parse error after enumeration");
3659 static bool parse_block_into(parser_t *parser, ast_block *block)
3663 parser_enterblock(parser);
3665 if (!parser_next(parser)) { /* skip the '{' */
3666 parseerror(parser, "expected function body");
3670 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3672 ast_expression *expr = NULL;
3673 if (parser->tok == '}')
3676 if (!parse_statement(parser, block, &expr, false)) {
3677 /* parseerror(parser, "parse error"); */
3683 if (!ast_block_add_expr(block, expr)) {
3690 if (parser->tok != '}') {
3693 (void)parser_next(parser);
3697 if (!parser_leaveblock(parser))
3699 return retval && !!block;
3702 static ast_block* parse_block(parser_t *parser)
3705 block = ast_block_new(parser_ctx(parser));
3708 if (!parse_block_into(parser, block)) {
3709 ast_block_delete(block);
3715 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3717 if (parser->tok == '{') {
3718 *out = (ast_expression*)parse_block(parser);
3721 return parse_statement(parser, NULL, out, false);
3724 static bool create_vector_members(ast_value *var, ast_member **me)
3727 size_t len = strlen(var->name);
3729 for (i = 0; i < 3; ++i) {
3730 char *name = (char*)mem_a(len+3);
3731 memcpy(name, var->name, len);
3733 name[len+1] = 'x'+i;
3735 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3744 do { ast_member_delete(me[--i]); } while(i);
3748 static bool parse_function_body(parser_t *parser, ast_value *var)
3750 ast_block *block = NULL;
3755 ast_expression *framenum = NULL;
3756 ast_expression *nextthink = NULL;
3757 /* None of the following have to be deleted */
3758 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3759 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3760 bool has_frame_think;
3764 has_frame_think = false;
3765 old = parser->function;
3767 if (var->expression.flags & AST_FLAG_ALIAS) {
3768 parseerror(parser, "function aliases cannot have bodies");
3772 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3773 parseerror(parser, "gotos/labels leaking");
3777 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3778 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3779 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3785 if (parser->tok == '[') {
3786 /* got a frame definition: [ framenum, nextthink ]
3787 * this translates to:
3788 * self.frame = framenum;
3789 * self.nextthink = time + 0.1;
3790 * self.think = nextthink;
3794 fld_think = parser_find_field(parser, "think");
3795 fld_nextthink = parser_find_field(parser, "nextthink");
3796 fld_frame = parser_find_field(parser, "frame");
3797 if (!fld_think || !fld_nextthink || !fld_frame) {
3798 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3799 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3802 gbl_time = parser_find_global(parser, "time");
3803 gbl_self = parser_find_global(parser, "self");
3804 if (!gbl_time || !gbl_self) {
3805 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3806 parseerror(parser, "please declare the following globals: `time`, `self`");
3810 if (!parser_next(parser))
3813 framenum = parse_expression_leave(parser, true, false, false);
3815 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3818 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3819 ast_unref(framenum);
3820 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3824 if (parser->tok != ',') {
3825 ast_unref(framenum);
3826 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3827 parseerror(parser, "Got a %i\n", parser->tok);
3831 if (!parser_next(parser)) {
3832 ast_unref(framenum);
3836 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3838 /* qc allows the use of not-yet-declared functions here
3839 * - this automatically creates a prototype */
3840 ast_value *thinkfunc;
3841 ast_expression *functype = fld_think->next;
3843 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3844 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3845 ast_unref(framenum);
3846 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3849 ast_type_adopt(thinkfunc, functype);
3851 if (!parser_next(parser)) {
3852 ast_unref(framenum);
3853 ast_delete(thinkfunc);
3857 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3859 nextthink = (ast_expression*)thinkfunc;
3862 nextthink = parse_expression_leave(parser, true, false, false);
3864 ast_unref(framenum);
3865 parseerror(parser, "expected a think-function in [frame,think] notation");
3870 if (!ast_istype(nextthink, ast_value)) {
3871 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3875 if (retval && parser->tok != ']') {
3876 parseerror(parser, "expected closing `]` for [frame,think] notation");
3880 if (retval && !parser_next(parser)) {
3884 if (retval && parser->tok != '{') {
3885 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3890 ast_unref(nextthink);
3891 ast_unref(framenum);
3895 has_frame_think = true;
3898 block = ast_block_new(parser_ctx(parser));
3900 parseerror(parser, "failed to allocate block");
3901 if (has_frame_think) {
3902 ast_unref(nextthink);
3903 ast_unref(framenum);
3908 if (has_frame_think) {
3910 ast_expression *self_frame;
3911 ast_expression *self_nextthink;
3912 ast_expression *self_think;
3913 ast_expression *time_plus_1;
3914 ast_store *store_frame;
3915 ast_store *store_nextthink;
3916 ast_store *store_think;
3918 ctx = parser_ctx(parser);
3919 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3920 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3921 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3923 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3924 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f));
3926 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3927 if (self_frame) ast_delete(self_frame);
3928 if (self_nextthink) ast_delete(self_nextthink);
3929 if (self_think) ast_delete(self_think);
3930 if (time_plus_1) ast_delete(time_plus_1);
3936 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3937 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3938 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3941 ast_delete(self_frame);
3944 if (!store_nextthink) {
3945 ast_delete(self_nextthink);
3949 ast_delete(self_think);
3953 if (store_frame) ast_delete(store_frame);
3954 if (store_nextthink) ast_delete(store_nextthink);
3955 if (store_think) ast_delete(store_think);
3958 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3959 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3960 !ast_block_add_expr(block, (ast_expression*)store_think))
3967 parseerror(parser, "failed to generate code for [frame,think]");
3968 ast_unref(nextthink);
3969 ast_unref(framenum);
3975 if (var->hasvalue) {
3976 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3977 ast_block_delete(block);
3981 func = ast_function_new(ast_ctx(var), var->name, var);
3983 parseerror(parser, "failed to allocate function for `%s`", var->name);
3984 ast_block_delete(block);
3987 vec_push(parser->functions, func);
3989 parser_enterblock(parser);
3991 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3993 ast_value *param = var->expression.params[parami];
3996 if (param->expression.vtype != TYPE_VECTOR &&
3997 (param->expression.vtype != TYPE_FIELD ||
3998 param->expression.next->vtype != TYPE_VECTOR))
4003 if (!create_vector_members(param, me)) {
4004 ast_block_delete(block);
4008 for (e = 0; e < 3; ++e) {
4009 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4010 ast_block_collect(block, (ast_expression*)me[e]);
4014 if (var->argcounter) {
4015 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4016 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4020 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4022 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4023 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4024 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4025 varargs->expression.count = 0;
4026 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4027 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4028 ast_delete(varargs);
4029 ast_block_delete(block);
4032 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4033 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4034 ast_delete(varargs);
4035 ast_block_delete(block);
4038 func->varargs = varargs;
4039 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4042 parser->function = func;
4043 if (!parse_block_into(parser, block)) {
4044 ast_block_delete(block);
4048 vec_push(func->blocks, block);
4051 parser->function = old;
4052 if (!parser_leaveblock(parser))
4054 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4055 parseerror(parser, "internal error: local scopes left");
4059 if (parser->tok == ';')
4060 return parser_next(parser);
4061 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4062 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4066 (void)!parser_leaveblock(parser);
4067 vec_pop(parser->functions);
4068 ast_function_delete(func);
4069 var->constval.vfunc = NULL;
4072 parser->function = old;
4076 static ast_expression *array_accessor_split(
4081 ast_expression *left,
4082 ast_expression *right
4088 lex_ctx_t ctx = ast_ctx(array);
4090 if (!left || !right) {
4091 if (left) ast_delete(left);
4092 if (right) ast_delete(right);
4096 cmp = ast_binary_new(ctx, INSTR_LT,
4097 (ast_expression*)index,
4098 (ast_expression*)fold_constgen_float(parser->fold, middle));
4102 parseerror(parser, "internal error: failed to create comparison for array setter");
4106 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4108 ast_delete(cmp); /* will delete left and right */
4109 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4113 return (ast_expression*)ifthen;
4116 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4118 lex_ctx_t ctx = ast_ctx(array);
4120 if (from+1 == afterend) {
4121 /* set this value */
4124 ast_array_index *subscript;
4126 int assignop = type_store_instr[value->expression.vtype];
4128 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4129 assignop = INSTR_STORE_V;
4131 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4135 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4137 ast_delete(subscript);
4141 block = ast_block_new(ctx);
4147 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4152 ret = ast_return_new(ctx, NULL);
4158 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4163 return (ast_expression*)block;
4165 ast_expression *left, *right;
4166 size_t diff = afterend - from;
4167 size_t middle = from + diff/2;
4168 left = array_setter_node(parser, array, index, value, from, middle);
4169 right = array_setter_node(parser, array, index, value, middle, afterend);
4170 return array_accessor_split(parser, array, index, middle, left, right);
4174 static ast_expression *array_field_setter_node(
4183 lex_ctx_t ctx = ast_ctx(array);
4185 if (from+1 == afterend) {
4186 /* set this value */
4189 ast_entfield *entfield;
4190 ast_array_index *subscript;
4192 int assignop = type_storep_instr[value->expression.vtype];
4194 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4195 assignop = INSTR_STOREP_V;
4197 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4201 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4202 subscript->expression.vtype = TYPE_FIELD;
4204 entfield = ast_entfield_new_force(ctx,
4205 (ast_expression*)entity,
4206 (ast_expression*)subscript,
4207 (ast_expression*)subscript);
4209 ast_delete(subscript);
4213 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4215 ast_delete(entfield);
4219 block = ast_block_new(ctx);
4225 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4230 ret = ast_return_new(ctx, NULL);
4236 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4241 return (ast_expression*)block;
4243 ast_expression *left, *right;
4244 size_t diff = afterend - from;
4245 size_t middle = from + diff/2;
4246 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4247 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4248 return array_accessor_split(parser, array, index, middle, left, right);
4252 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4254 lex_ctx_t ctx = ast_ctx(array);
4256 if (from+1 == afterend) {
4258 ast_array_index *subscript;
4260 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4264 ret = ast_return_new(ctx, (ast_expression*)subscript);
4266 ast_delete(subscript);
4270 return (ast_expression*)ret;
4272 ast_expression *left, *right;
4273 size_t diff = afterend - from;
4274 size_t middle = from + diff/2;
4275 left = array_getter_node(parser, array, index, from, middle);
4276 right = array_getter_node(parser, array, index, middle, afterend);
4277 return array_accessor_split(parser, array, index, middle, left, right);
4281 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4283 ast_function *func = NULL;
4284 ast_value *fval = NULL;
4285 ast_block *body = NULL;
4287 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4289 parseerror(parser, "failed to create accessor function value");
4293 func = ast_function_new(ast_ctx(array), funcname, fval);
4296 parseerror(parser, "failed to create accessor function node");
4300 body = ast_block_new(ast_ctx(array));
4302 parseerror(parser, "failed to create block for array accessor");
4308 vec_push(func->blocks, body);
4311 vec_push(parser->accessors, fval);
4316 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4318 ast_value *index = NULL;
4319 ast_value *value = NULL;
4323 if (!ast_istype(array->expression.next, ast_value)) {
4324 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4328 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4330 func = fval->constval.vfunc;
4331 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4333 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4334 value = ast_value_copy((ast_value*)array->expression.next);
4336 if (!index || !value) {
4337 parseerror(parser, "failed to create locals for array accessor");
4340 (void)!ast_value_set_name(value, "value"); /* not important */
4341 vec_push(fval->expression.params, index);
4342 vec_push(fval->expression.params, value);
4344 array->setter = fval;
4347 if (index) ast_delete(index);
4348 if (value) ast_delete(value);
4354 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4356 ast_expression *root = NULL;
4357 root = array_setter_node(parser, array,
4358 array->setter->expression.params[0],
4359 array->setter->expression.params[1],
4360 0, array->expression.count);
4362 parseerror(parser, "failed to build accessor search tree");
4365 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4372 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4374 if (!parser_create_array_setter_proto(parser, array, funcname))
4376 return parser_create_array_setter_impl(parser, array);
4379 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4381 ast_expression *root = NULL;
4382 ast_value *entity = NULL;
4383 ast_value *index = NULL;
4384 ast_value *value = NULL;
4388 if (!ast_istype(array->expression.next, ast_value)) {
4389 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4393 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4395 func = fval->constval.vfunc;
4396 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4398 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4399 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4400 value = ast_value_copy((ast_value*)array->expression.next);
4401 if (!entity || !index || !value) {
4402 parseerror(parser, "failed to create locals for array accessor");
4405 (void)!ast_value_set_name(value, "value"); /* not important */
4406 vec_push(fval->expression.params, entity);
4407 vec_push(fval->expression.params, index);
4408 vec_push(fval->expression.params, value);
4410 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4412 parseerror(parser, "failed to build accessor search tree");
4416 array->setter = fval;
4417 return ast_block_add_expr(func->blocks[0], root);
4419 if (entity) ast_delete(entity);
4420 if (index) ast_delete(index);
4421 if (value) ast_delete(value);
4422 if (root) ast_delete(root);
4428 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4430 ast_value *index = NULL;
4434 /* NOTE: checking array->expression.next rather than elemtype since
4435 * for fields elemtype is a temporary fieldtype.
4437 if (!ast_istype(array->expression.next, ast_value)) {
4438 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4442 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4444 func = fval->constval.vfunc;
4445 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4447 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4450 parseerror(parser, "failed to create locals for array accessor");
4453 vec_push(fval->expression.params, index);
4455 array->getter = fval;
4458 if (index) ast_delete(index);
4464 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4466 ast_expression *root = NULL;
4468 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4470 parseerror(parser, "failed to build accessor search tree");
4473 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4480 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4482 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4484 return parser_create_array_getter_impl(parser, array);
4487 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4488 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4496 bool variadic = false;
4497 ast_value *varparam = NULL;
4498 char *argcounter = NULL;
4500 ctx = parser_ctx(parser);
4502 /* for the sake of less code we parse-in in this function */
4503 if (!parser_next(parser)) {
4505 parseerror(parser, "expected parameter list");
4511 /* parse variables until we hit a closing paren */
4512 while (parser->tok != ')') {
4514 /* there must be commas between them */
4515 if (parser->tok != ',') {
4516 parseerror(parser, "expected comma or end of parameter list");
4519 if (!parser_next(parser)) {
4520 parseerror(parser, "expected parameter");
4526 if (parser->tok == TOKEN_DOTS) {
4527 /* '...' indicates a varargs function */
4529 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4530 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4533 if (parser->tok == TOKEN_IDENT) {
4534 argcounter = util_strdup(parser_tokval(parser));
4535 if (!parser_next(parser) || parser->tok != ')') {
4536 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4543 /* for anything else just parse a typename */
4544 param = parse_typename(parser, NULL, NULL);
4547 vec_push(params, param);
4548 if (param->expression.vtype >= TYPE_VARIANT) {
4549 char tname[1024]; /* typename is reserved in C++ */
4550 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4551 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4554 /* type-restricted varargs */
4555 if (parser->tok == TOKEN_DOTS) {
4557 varparam = vec_last(params);
4559 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4560 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4563 if (parser->tok == TOKEN_IDENT) {
4564 argcounter = util_strdup(parser_tokval(parser));
4565 if (!parser_next(parser) || parser->tok != ')') {
4566 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4574 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4578 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4579 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4582 if (!parser_next(parser)) {
4583 parseerror(parser, "parse error after typename");
4587 /* now turn 'var' into a function type */
4588 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4589 fval->expression.next = (ast_expression*)var;
4591 fval->expression.flags |= AST_FLAG_VARIADIC;
4594 var->expression.params = params;
4595 var->expression.varparam = (ast_expression*)varparam;
4596 var->argcounter = argcounter;
4605 ast_delete(varparam);
4607 for (i = 0; i < vec_size(params); ++i)
4608 ast_delete(params[i]);
4613 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4615 ast_expression *cexp;
4616 ast_value *cval, *tmp;
4619 ctx = parser_ctx(parser);
4621 if (!parser_next(parser)) {
4623 parseerror(parser, "expected array-size");
4627 if (parser->tok != ']') {
4628 cexp = parse_expression_leave(parser, true, false, false);
4630 if (!cexp || !ast_istype(cexp, ast_value)) {
4634 parseerror(parser, "expected array-size as constant positive integer");
4637 cval = (ast_value*)cexp;
4644 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4645 tmp->expression.next = (ast_expression*)var;
4649 if (cval->expression.vtype == TYPE_INTEGER)
4650 tmp->expression.count = cval->constval.vint;
4651 else if (cval->expression.vtype == TYPE_FLOAT)
4652 tmp->expression.count = cval->constval.vfloat;
4656 parseerror(parser, "array-size must be a positive integer constant");
4662 var->expression.count = -1;
4663 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4666 if (parser->tok != ']') {
4668 parseerror(parser, "expected ']' after array-size");
4671 if (!parser_next(parser)) {
4673 parseerror(parser, "error after parsing array size");
4679 /* Parse a complete typename.
4680 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4681 * but when parsing variables separated by comma
4682 * 'storebase' should point to where the base-type should be kept.
4683 * The base type makes up every bit of type information which comes *before* the
4686 * NOTE: The value must either be named, have a NULL name, or a name starting
4687 * with '<'. In the first case, this will be the actual variable or type
4688 * name, in the other cases it is assumed that the name will appear
4689 * later, and an error is generated otherwise.
4691 * The following will be parsed in its entirety:
4693 * The 'basetype' in this case is 'void()'
4694 * and if there's a comma after it, say:
4696 * then the type-information 'void()' can be stored in 'storebase'
4698 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4700 ast_value *var, *tmp;
4703 const char *name = NULL;
4704 bool isfield = false;
4705 bool wasarray = false;
4706 size_t morefields = 0;
4708 ctx = parser_ctx(parser);
4710 /* types may start with a dot */
4711 if (parser->tok == '.') {
4713 /* if we parsed a dot we need a typename now */
4714 if (!parser_next(parser)) {
4715 parseerror(parser, "expected typename for field definition");
4719 /* Further dots are handled seperately because they won't be part of the
4722 while (parser->tok == '.') {
4724 if (!parser_next(parser)) {
4725 parseerror(parser, "expected typename for field definition");
4730 if (parser->tok == TOKEN_IDENT)
4731 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4732 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4733 parseerror(parser, "expected typename");
4737 /* generate the basic type value */
4738 if (cached_typedef) {
4739 var = ast_value_copy(cached_typedef);
4740 ast_value_set_name(var, "<type(from_def)>");
4742 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4744 for (; morefields; --morefields) {
4745 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4746 tmp->expression.next = (ast_expression*)var;
4750 /* do not yet turn into a field - remember:
4751 * .void() foo; is a field too
4752 * .void()() foo; is a function
4756 if (!parser_next(parser)) {
4758 parseerror(parser, "parse error after typename");
4762 /* an opening paren now starts the parameter-list of a function
4763 * this is where original-QC has parameter lists.
4764 * We allow a single parameter list here.
4765 * Much like fteqcc we don't allow `float()() x`
4767 if (parser->tok == '(') {
4768 var = parse_parameter_list(parser, var);
4773 /* store the base if requested */
4775 *storebase = ast_value_copy(var);
4777 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4778 tmp->expression.next = (ast_expression*)*storebase;
4783 /* there may be a name now */
4784 if (parser->tok == TOKEN_IDENT) {
4785 name = util_strdup(parser_tokval(parser));
4787 if (!parser_next(parser)) {
4790 parseerror(parser, "error after variable or field declaration");
4795 /* now this may be an array */
4796 if (parser->tok == '[') {
4798 var = parse_arraysize(parser, var);
4800 if (name) mem_d(name);
4805 /* This is the point where we can turn it into a field */
4807 /* turn it into a field if desired */
4808 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4809 tmp->expression.next = (ast_expression*)var;
4813 /* now there may be function parens again */
4814 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4815 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4816 if (parser->tok == '(' && wasarray)
4817 parseerror(parser, "arrays as part of a return type is not supported");
4818 while (parser->tok == '(') {
4819 var = parse_parameter_list(parser, var);
4821 if (name) mem_d(name);
4826 /* finally name it */
4828 if (!ast_value_set_name(var, name)) {
4831 parseerror(parser, "internal error: failed to set name");
4834 /* free the name, ast_value_set_name duplicates */
4841 static bool parse_typedef(parser_t *parser)
4843 ast_value *typevar, *oldtype;
4844 ast_expression *old;
4846 typevar = parse_typename(parser, NULL, NULL);
4851 /* while parsing types, the ast_value's get named '<something>' */
4852 if (!typevar->name || typevar->name[0] == '<') {
4853 parseerror(parser, "missing name in typedef");
4854 ast_delete(typevar);
4858 if ( (old = parser_find_var(parser, typevar->name)) ) {
4859 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4860 " -> `%s` has been declared here: %s:%i",
4861 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4862 ast_delete(typevar);
4866 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4867 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4868 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4869 ast_delete(typevar);
4873 vec_push(parser->_typedefs, typevar);
4874 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4876 if (parser->tok != ';') {
4877 parseerror(parser, "expected semicolon after typedef");
4880 if (!parser_next(parser)) {
4881 parseerror(parser, "parse error after typedef");
4888 static const char *cvq_to_str(int cvq) {
4890 case CV_NONE: return "none";
4891 case CV_VAR: return "`var`";
4892 case CV_CONST: return "`const`";
4893 default: return "<INVALID>";
4897 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4900 if (proto->cvq != var->cvq) {
4901 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4902 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4903 parser->tok == '='))
4905 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4906 "`%s` declared with different qualifiers: %s\n"
4907 " -> previous declaration here: %s:%i uses %s",
4908 var->name, cvq_to_str(var->cvq),
4909 ast_ctx(proto).file, ast_ctx(proto).line,
4910 cvq_to_str(proto->cvq));
4913 av = (var ->expression.flags & AST_FLAG_NORETURN);
4914 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4916 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4917 "`%s` declared with different attributes%s\n"
4918 " -> previous declaration here: %s:%i",
4919 var->name, (av ? ": noreturn" : ""),
4920 ast_ctx(proto).file, ast_ctx(proto).line,
4921 (ao ? ": noreturn" : ""));
4926 static bool create_array_accessors(parser_t *parser, ast_value *var)
4929 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4930 if (!parser_create_array_setter(parser, var, name))
4932 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4933 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4938 static bool parse_array(parser_t *parser, ast_value *array)
4941 if (array->initlist) {
4942 parseerror(parser, "array already initialized elsewhere");
4945 if (!parser_next(parser)) {
4946 parseerror(parser, "parse error in array initializer");
4950 while (parser->tok != '}') {
4951 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4954 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4956 parseerror(parser, "initializing element must be a compile time constant");
4959 vec_push(array->initlist, v->constval);
4960 if (v->expression.vtype == TYPE_STRING) {
4961 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4965 if (parser->tok == '}')
4967 if (parser->tok != ',' || !parser_next(parser)) {
4968 parseerror(parser, "expected comma or '}' in element list");
4972 if (!parser_next(parser) || parser->tok != ';') {
4973 parseerror(parser, "expected semicolon after initializer, got %s");
4977 if (!parser_next(parser)) {
4978 parseerror(parser, "parse error after initializer");
4983 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4984 if (array->expression.count != (size_t)-1) {
4985 parseerror(parser, "array `%s' has already been initialized with %u elements",
4986 array->name, (unsigned)array->expression.count);
4988 array->expression.count = vec_size(array->initlist);
4989 if (!create_array_accessors(parser, array))
4995 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)
4999 ast_expression *old;
5003 ast_value *basetype = NULL;
5005 bool isparam = false;
5006 bool isvector = false;
5007 bool cleanvar = true;
5008 bool wasarray = false;
5010 ast_member *me[3] = { NULL, NULL, NULL };
5012 if (!localblock && is_static)
5013 parseerror(parser, "`static` qualifier is not supported in global scope");
5015 /* get the first complete variable */
5016 var = parse_typename(parser, &basetype, cached_typedef);
5019 ast_delete(basetype);
5023 /* while parsing types, the ast_value's get named '<something>' */
5024 if (!var->name || var->name[0] == '<') {
5025 parseerror(parser, "declaration does not declare anything");
5027 ast_delete(basetype);
5035 /* Part 0: finish the type */
5036 if (parser->tok == '(') {
5037 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5038 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5039 var = parse_parameter_list(parser, var);
5045 /* we only allow 1-dimensional arrays */
5046 if (parser->tok == '[') {
5048 var = parse_arraysize(parser, var);
5054 if (parser->tok == '(' && wasarray) {
5055 parseerror(parser, "arrays as part of a return type is not supported");
5056 /* we'll still parse the type completely for now */
5058 /* for functions returning functions */
5059 while (parser->tok == '(') {
5060 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5061 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5062 var = parse_parameter_list(parser, var);
5069 var->cvq = qualifier;
5070 var->expression.flags |= qflags;
5073 * store the vstring back to var for alias and
5074 * deprecation messages.
5076 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5077 var->expression.flags & AST_FLAG_ALIAS)
5078 var->desc = vstring;
5081 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5082 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5083 * is then filled with the previous definition and the parameter-names replaced.
5085 if (!strcmp(var->name, "nil")) {
5086 if (OPTS_FLAG(UNTYPED_NIL)) {
5087 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5088 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5090 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5093 /* Deal with end_sys_ vars */
5095 if (!strcmp(var->name, "end_sys_globals")) {
5097 parser->crc_globals = vec_size(parser->globals);
5100 else if (!strcmp(var->name, "end_sys_fields")) {
5102 parser->crc_fields = vec_size(parser->fields);
5105 if (was_end && var->expression.vtype == TYPE_FIELD) {
5106 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5107 "global '%s' hint should not be a field",
5108 parser_tokval(parser)))
5115 if (!nofields && var->expression.vtype == TYPE_FIELD)
5117 /* deal with field declarations */
5118 old = parser_find_field(parser, var->name);
5120 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5121 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5130 parseerror(parser, "field `%s` already declared here: %s:%i",
5131 var->name, ast_ctx(old).file, ast_ctx(old).line);
5136 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5137 (old = parser_find_global(parser, var->name)))
5139 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5140 parseerror(parser, "field `%s` already declared here: %s:%i",
5141 var->name, ast_ctx(old).file, ast_ctx(old).line);
5148 /* deal with other globals */
5149 old = parser_find_global(parser, var->name);
5150 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5152 /* This is a function which had a prototype */
5153 if (!ast_istype(old, ast_value)) {
5154 parseerror(parser, "internal error: prototype is not an ast_value");
5158 proto = (ast_value*)old;
5159 proto->desc = var->desc;
5160 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5161 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5163 ast_ctx(proto).file, ast_ctx(proto).line);
5167 /* we need the new parameter-names */
5168 for (i = 0; i < vec_size(proto->expression.params); ++i)
5169 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5170 if (!parser_check_qualifiers(parser, var, proto)) {
5177 proto->expression.flags |= var->expression.flags;
5185 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5186 "global `%s` already declared here: %s:%i",
5187 var->name, ast_ctx(old).file, ast_ctx(old).line))
5192 proto = (ast_value*)old;
5193 if (!ast_istype(old, ast_value)) {
5194 parseerror(parser, "internal error: not an ast_value");
5199 if (!parser_check_qualifiers(parser, var, proto)) {
5204 proto->expression.flags |= var->expression.flags;
5208 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5209 (old = parser_find_field(parser, var->name)))
5211 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5212 parseerror(parser, "global `%s` already declared here: %s:%i",
5213 var->name, ast_ctx(old).file, ast_ctx(old).line);
5220 else /* it's not a global */
5222 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5223 if (old && !isparam) {
5224 parseerror(parser, "local `%s` already declared here: %s:%i",
5225 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5229 /* doing this here as the above is just for a single scope */
5230 old = parser_find_local(parser, var->name, 0, &isparam);
5231 if (old && isparam) {
5232 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5233 "local `%s` is shadowing a parameter", var->name))
5235 parseerror(parser, "local `%s` already declared here: %s:%i",
5236 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5240 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5242 if (ast_istype(old, ast_value))
5243 var = proto = (ast_value*)old;
5252 /* in a noref section we simply bump the usecount */
5253 if (noref || parser->noref)
5257 * Create the global/local, and deal with vector types.
5260 if (var->expression.vtype == TYPE_VECTOR)
5262 else if (var->expression.vtype == TYPE_FIELD &&
5263 var->expression.next->vtype == TYPE_VECTOR)
5267 if (!create_vector_members(var, me)) {
5274 /* deal with global variables, fields, functions */
5275 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5276 var->isfield = true;
5277 vec_push(parser->fields, (ast_expression*)var);
5278 util_htset(parser->htfields, var->name, var);
5280 for (i = 0; i < 3; ++i) {
5281 vec_push(parser->fields, (ast_expression*)me[i]);
5282 util_htset(parser->htfields, me[i]->name, me[i]);
5287 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5288 parser_addglobal(parser, var->name, (ast_expression*)var);
5290 for (i = 0; i < 3; ++i) {
5291 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5295 ast_expression *find = parser_find_global(parser, var->desc);
5298 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5302 if (!ast_compare_type((ast_expression*)var, find)) {
5306 ast_type_to_string(find, ty1, sizeof(ty1));
5307 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5309 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5316 * add alias to aliases table and to corrector
5317 * so corrections can apply for aliases as well.
5319 util_htset(parser->aliases, var->name, find);
5322 * add to corrector so corrections can work
5323 * even for aliases too.
5326 vec_last(parser->correct_variables),
5327 &vec_last(parser->correct_variables_score),
5331 /* generate aliases for vector components */
5335 util_asprintf(&buffer[0], "%s_x", var->desc);
5336 util_asprintf(&buffer[1], "%s_y", var->desc);
5337 util_asprintf(&buffer[2], "%s_z", var->desc);
5339 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5340 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5341 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5348 * add to corrector so corrections can work
5349 * even for aliases too.
5352 vec_last(parser->correct_variables),
5353 &vec_last(parser->correct_variables_score),
5357 vec_last(parser->correct_variables),
5358 &vec_last(parser->correct_variables_score),
5362 vec_last(parser->correct_variables),
5363 &vec_last(parser->correct_variables_score),
5371 /* a static adds itself to be generated like any other global
5372 * but is added to the local namespace instead
5374 char *defname = NULL;
5375 size_t prefix_len, ln;
5377 ln = strlen(parser->function->name);
5378 vec_append(defname, ln, parser->function->name);
5380 vec_append(defname, 2, "::");
5381 /* remember the length up to here */
5382 prefix_len = vec_size(defname);
5384 /* Add it to the local scope */
5385 util_htset(vec_last(parser->variables), var->name, (void*)var);
5389 vec_last(parser->correct_variables),
5390 &vec_last(parser->correct_variables_score),
5394 /* now rename the global */
5395 ln = strlen(var->name);
5396 vec_append(defname, ln, var->name);
5397 ast_value_set_name(var, defname);
5399 /* push it to the to-be-generated globals */
5400 vec_push(parser->globals, (ast_expression*)var);
5402 /* same game for the vector members */
5404 for (i = 0; i < 3; ++i) {
5405 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5409 vec_last(parser->correct_variables),
5410 &vec_last(parser->correct_variables_score),
5414 vec_shrinkto(defname, prefix_len);
5415 ln = strlen(me[i]->name);
5416 vec_append(defname, ln, me[i]->name);
5417 ast_member_set_name(me[i], defname);
5419 vec_push(parser->globals, (ast_expression*)me[i]);
5424 vec_push(localblock->locals, var);
5425 parser_addlocal(parser, var->name, (ast_expression*)var);
5427 for (i = 0; i < 3; ++i) {
5428 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5429 ast_block_collect(localblock, (ast_expression*)me[i]);
5435 me[0] = me[1] = me[2] = NULL;
5440 if (var->expression.vtype == TYPE_ARRAY) {
5441 if (var->expression.count != (size_t)-1) {
5442 if (!create_array_accessors(parser, var))
5446 else if (!localblock && !nofields &&
5447 var->expression.vtype == TYPE_FIELD &&
5448 var->expression.next->vtype == TYPE_ARRAY)
5451 ast_expression *telem;
5453 ast_value *array = (ast_value*)var->expression.next;
5455 if (!ast_istype(var->expression.next, ast_value)) {
5456 parseerror(parser, "internal error: field element type must be an ast_value");
5460 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5461 if (!parser_create_array_field_setter(parser, array, name))
5464 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5465 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5466 tfield->expression.next = telem;
5467 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5468 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5476 if (parser->tok == ';') {
5477 ast_delete(basetype);
5478 if (!parser_next(parser)) {
5479 parseerror(parser, "error after variable declaration");
5485 if (parser->tok == ',')
5489 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5492 parseerror(parser, "missing comma or semicolon while parsing variables");
5496 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5497 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5498 "initializing expression turns variable `%s` into a constant in this standard",
5505 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5506 if (parser->tok != '=') {
5507 if (!strcmp(parser_tokval(parser), "break")) {
5508 if (!parser_next(parser)) {
5509 parseerror(parser, "error parsing break definition");
5512 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5514 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5519 if (!parser_next(parser)) {
5520 parseerror(parser, "error parsing initializer");
5524 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5525 parseerror(parser, "expected '=' before function body in this standard");
5528 if (parser->tok == '#') {
5529 ast_function *func = NULL;
5530 ast_value *number = NULL;
5536 parseerror(parser, "cannot declare builtins within functions");
5539 if (var->expression.vtype != TYPE_FUNCTION) {
5540 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5543 if (!parser_next(parser)) {
5544 parseerror(parser, "expected builtin number");
5548 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5549 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5551 parseerror(parser, "builtin number expected");
5554 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5557 parseerror(parser, "builtin number must be a compile time constant");
5560 if (number->expression.vtype == TYPE_INTEGER)
5561 builtin_num = number->constval.vint;
5562 else if (number->expression.vtype == TYPE_FLOAT)
5563 builtin_num = number->constval.vfloat;
5566 parseerror(parser, "builtin number must be an integer constant");
5571 fractional = modff(builtin_num, &integral);
5572 if (builtin_num < 0 || fractional != 0) {
5573 parseerror(parser, "builtin number must be an integer greater than zero");
5577 /* we only want the integral part anyways */
5578 builtin_num = integral;
5579 } else if (parser->tok == TOKEN_INTCONST) {
5580 builtin_num = parser_token(parser)->constval.i;
5582 parseerror(parser, "builtin number must be a compile time constant");
5586 if (var->hasvalue) {
5587 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5588 "builtin `%s` has already been defined\n"
5589 " -> previous declaration here: %s:%i",
5590 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5594 func = ast_function_new(ast_ctx(var), var->name, var);
5596 parseerror(parser, "failed to allocate function for `%s`", var->name);
5599 vec_push(parser->functions, func);
5601 func->builtin = -builtin_num-1;
5604 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5605 ? (parser->tok != ',' && parser->tok != ';')
5606 : (!parser_next(parser)))
5608 parseerror(parser, "expected comma or semicolon");
5610 ast_function_delete(func);
5611 var->constval.vfunc = NULL;
5615 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5618 /* Note that fteqcc and most others don't even *have*
5619 * local arrays, so this is not a high priority.
5621 parseerror(parser, "TODO: initializers for local arrays");
5625 var->hasvalue = true;
5626 if (!parse_array(parser, var))
5629 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5632 parseerror(parser, "cannot declare functions within functions");
5637 ast_ctx(proto) = parser_ctx(parser);
5639 if (!parse_function_body(parser, var))
5641 ast_delete(basetype);
5642 for (i = 0; i < vec_size(parser->gotos); ++i)
5643 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5644 vec_free(parser->gotos);
5645 vec_free(parser->labels);
5648 ast_expression *cexp;
5651 cexp = parse_expression_leave(parser, true, false, false);
5656 cval = (ast_value*)cexp;
5657 if (cval != parser->nil &&
5658 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5661 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5665 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5666 qualifier != CV_VAR)
5668 var->cvq = CV_CONST;
5670 if (cval == parser->nil)
5671 var->expression.flags |= AST_FLAG_INITIALIZED;
5674 var->hasvalue = true;
5675 if (cval->expression.vtype == TYPE_STRING)
5676 var->constval.vstring = parser_strdup(cval->constval.vstring);
5677 else if (cval->expression.vtype == TYPE_FIELD)
5678 var->constval.vfield = cval;
5680 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5686 shunt sy = { NULL, NULL, NULL, NULL };
5689 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5690 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5691 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5692 if (!parser_sy_apply_operator(parser, &sy))
5695 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5696 parseerror(parser, "internal error: leaked operands");
5697 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5708 if (parser->tok == ',') {
5709 if (!parser_next(parser)) {
5710 parseerror(parser, "expected another variable");
5714 if (parser->tok != TOKEN_IDENT) {
5715 parseerror(parser, "expected another variable");
5718 var = ast_value_copy(basetype);
5720 ast_value_set_name(var, parser_tokval(parser));
5721 if (!parser_next(parser)) {
5722 parseerror(parser, "error parsing variable declaration");
5728 if (parser->tok != ';') {
5729 parseerror(parser, "missing semicolon after variables");
5733 if (!parser_next(parser)) {
5734 parseerror(parser, "parse error after variable declaration");
5738 ast_delete(basetype);
5742 if (cleanvar && var)
5744 ast_delete(basetype);
5748 ast_delete(basetype);
5749 if (cleanvar && var)
5751 if (me[0]) ast_member_delete(me[0]);
5752 if (me[1]) ast_member_delete(me[1]);
5753 if (me[2]) ast_member_delete(me[2]);
5757 static bool parser_global_statement(parser_t *parser)
5761 bool is_static = false;
5762 uint32_t qflags = 0;
5763 ast_value *istype = NULL;
5764 char *vstring = NULL;
5766 if (parser->tok == TOKEN_IDENT)
5767 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5769 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5771 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5773 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5775 if (cvq == CV_WRONG)
5777 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5779 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5781 return parse_enum(parser);
5783 else if (parser->tok == TOKEN_KEYWORD)
5785 if (!strcmp(parser_tokval(parser), "typedef")) {
5786 if (!parser_next(parser)) {
5787 parseerror(parser, "expected type definition after 'typedef'");
5790 return parse_typedef(parser);
5792 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5795 else if (parser->tok == '#')
5797 return parse_pragma(parser);
5799 else if (parser->tok == '$')
5801 if (!parser_next(parser)) {
5802 parseerror(parser, "parse error");
5808 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5814 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5816 return util_crc16(old, str, strlen(str));
5819 static void progdefs_crc_file(const char *str)
5821 /* write to progdefs.h here */
5825 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5827 old = progdefs_crc_sum(old, str);
5828 progdefs_crc_file(str);
5832 static void generate_checksum(parser_t *parser, ir_builder *ir)
5834 uint16_t crc = 0xFFFF;
5838 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5839 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5841 progdefs_crc_file("\tint\tpad;\n");
5842 progdefs_crc_file("\tint\tofs_return[3];\n");
5843 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5844 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5845 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5846 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5847 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5848 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5849 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5850 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5852 for (i = 0; i < parser->crc_globals; ++i) {
5853 if (!ast_istype(parser->globals[i], ast_value))
5855 value = (ast_value*)(parser->globals[i]);
5856 switch (value->expression.vtype) {
5857 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5858 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5859 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5860 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5862 crc = progdefs_crc_both(crc, "\tint\t");
5865 crc = progdefs_crc_both(crc, value->name);
5866 crc = progdefs_crc_both(crc, ";\n");
5868 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5869 for (i = 0; i < parser->crc_fields; ++i) {
5870 if (!ast_istype(parser->fields[i], ast_value))
5872 value = (ast_value*)(parser->fields[i]);
5873 switch (value->expression.next->vtype) {
5874 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5875 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5876 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5877 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5879 crc = progdefs_crc_both(crc, "\tint\t");
5882 crc = progdefs_crc_both(crc, value->name);
5883 crc = progdefs_crc_both(crc, ";\n");
5885 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5886 ir->code->crc = crc;
5889 parser_t *parser_create()
5892 lex_ctx_t empty_ctx;
5895 parser = (parser_t*)mem_a(sizeof(parser_t));
5899 memset(parser, 0, sizeof(*parser));
5901 for (i = 0; i < operator_count; ++i) {
5902 if (operators[i].id == opid1('=')) {
5903 parser->assign_op = operators+i;
5907 if (!parser->assign_op) {
5908 printf("internal error: initializing parser: failed to find assign operator\n");
5913 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5914 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5915 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5916 vec_push(parser->_blocktypedefs, 0);
5918 parser->aliases = util_htnew(PARSER_HT_SIZE);
5921 vec_push(parser->correct_variables, correct_trie_new());
5922 vec_push(parser->correct_variables_score, NULL);
5924 empty_ctx.file = "<internal>";
5926 empty_ctx.column = 0;
5927 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5928 parser->nil->cvq = CV_CONST;
5929 if (OPTS_FLAG(UNTYPED_NIL))
5930 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5932 parser->max_param_count = 1;
5934 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5935 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5936 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5938 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5939 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5940 parser->reserved_version->cvq = CV_CONST;
5941 parser->reserved_version->hasvalue = true;
5942 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5943 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5945 parser->reserved_version = NULL;
5948 parser->fold = fold_init (parser);
5949 parser->intrin = intrin_init(parser);
5953 static bool parser_compile(parser_t *parser)
5955 /* initial lexer/parser state */
5956 parser->lex->flags.noops = true;
5958 if (parser_next(parser))
5960 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5962 if (!parser_global_statement(parser)) {
5963 if (parser->tok == TOKEN_EOF)
5964 parseerror(parser, "unexpected end of file");
5965 else if (compile_errors)
5966 parseerror(parser, "there have been errors, bailing out");
5967 lex_close(parser->lex);
5973 parseerror(parser, "parse error");
5974 lex_close(parser->lex);
5979 lex_close(parser->lex);
5982 return !compile_errors;
5985 bool parser_compile_file(parser_t *parser, const char *filename)
5987 parser->lex = lex_open(filename);
5989 con_err("failed to open file \"%s\"\n", filename);
5992 return parser_compile(parser);
5995 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5997 parser->lex = lex_open_string(str, len, name);
5999 con_err("failed to create lexer for string \"%s\"\n", name);
6002 return parser_compile(parser);
6005 static void parser_remove_ast(parser_t *parser)
6008 if (parser->ast_cleaned)
6010 parser->ast_cleaned = true;
6011 for (i = 0; i < vec_size(parser->accessors); ++i) {
6012 ast_delete(parser->accessors[i]->constval.vfunc);
6013 parser->accessors[i]->constval.vfunc = NULL;
6014 ast_delete(parser->accessors[i]);
6016 for (i = 0; i < vec_size(parser->functions); ++i) {
6017 ast_delete(parser->functions[i]);
6019 for (i = 0; i < vec_size(parser->fields); ++i) {
6020 ast_delete(parser->fields[i]);
6022 for (i = 0; i < vec_size(parser->globals); ++i) {
6023 ast_delete(parser->globals[i]);
6025 vec_free(parser->accessors);
6026 vec_free(parser->functions);
6027 vec_free(parser->globals);
6028 vec_free(parser->fields);
6030 for (i = 0; i < vec_size(parser->variables); ++i)
6031 util_htdel(parser->variables[i]);
6032 vec_free(parser->variables);
6033 vec_free(parser->_blocklocals);
6034 vec_free(parser->_locals);
6037 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6038 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6040 vec_free(parser->correct_variables);
6041 vec_free(parser->correct_variables_score);
6043 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6044 ast_delete(parser->_typedefs[i]);
6045 vec_free(parser->_typedefs);
6046 for (i = 0; i < vec_size(parser->typedefs); ++i)
6047 util_htdel(parser->typedefs[i]);
6048 vec_free(parser->typedefs);
6049 vec_free(parser->_blocktypedefs);
6051 vec_free(parser->_block_ctx);
6053 vec_free(parser->labels);
6054 vec_free(parser->gotos);
6055 vec_free(parser->breaks);
6056 vec_free(parser->continues);
6058 ast_value_delete(parser->nil);
6060 ast_value_delete(parser->const_vec[0]);
6061 ast_value_delete(parser->const_vec[1]);
6062 ast_value_delete(parser->const_vec[2]);
6064 if (parser->reserved_version)
6065 ast_value_delete(parser->reserved_version);
6067 util_htdel(parser->aliases);
6068 fold_cleanup(parser->fold);
6069 intrin_cleanup(parser->intrin);
6072 void parser_cleanup(parser_t *parser)
6074 parser_remove_ast(parser);
6078 bool parser_finish(parser_t *parser, const char *output)
6084 if (compile_errors) {
6085 con_out("*** there were compile errors\n");
6089 ir = ir_builder_new("gmqcc_out");
6091 con_out("failed to allocate builder\n");
6095 for (i = 0; i < vec_size(parser->fields); ++i) {
6098 if (!ast_istype(parser->fields[i], ast_value))
6100 field = (ast_value*)parser->fields[i];
6101 hasvalue = field->hasvalue;
6102 field->hasvalue = false;
6103 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6104 con_out("failed to generate field %s\n", field->name);
6105 ir_builder_delete(ir);
6110 ast_expression *subtype;
6111 field->hasvalue = true;
6112 subtype = field->expression.next;
6113 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6114 if (subtype->vtype == TYPE_FIELD)
6115 ifld->fieldtype = subtype->next->vtype;
6116 else if (subtype->vtype == TYPE_FUNCTION)
6117 ifld->outtype = subtype->next->vtype;
6118 (void)!ir_value_set_field(field->ir_v, ifld);
6121 for (i = 0; i < vec_size(parser->globals); ++i) {
6123 if (!ast_istype(parser->globals[i], ast_value))
6125 asvalue = (ast_value*)(parser->globals[i]);
6126 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6127 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6128 "unused global: `%s`", asvalue->name);
6130 if (!ast_global_codegen(asvalue, ir, false)) {
6131 con_out("failed to generate global %s\n", asvalue->name);
6132 ir_builder_delete(ir);
6136 /* Build function vararg accessor ast tree now before generating
6137 * immediates, because the accessors may add new immediates
6139 for (i = 0; i < vec_size(parser->functions); ++i) {
6140 ast_function *f = parser->functions[i];
6142 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6143 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6144 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6145 con_out("failed to generate vararg setter for %s\n", f->name);
6146 ir_builder_delete(ir);
6149 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6150 con_out("failed to generate vararg getter for %s\n", f->name);
6151 ir_builder_delete(ir);
6155 ast_delete(f->varargs);
6160 /* Now we can generate immediates */
6161 if (!fold_generate(parser->fold, ir))
6164 for (i = 0; i < vec_size(parser->globals); ++i) {
6166 if (!ast_istype(parser->globals[i], ast_value))
6168 asvalue = (ast_value*)(parser->globals[i]);
6169 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6171 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6172 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6173 "uninitialized constant: `%s`",
6175 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6176 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6177 "uninitialized global: `%s`",
6180 if (!ast_generate_accessors(asvalue, ir)) {
6181 ir_builder_delete(ir);
6185 for (i = 0; i < vec_size(parser->fields); ++i) {
6187 asvalue = (ast_value*)(parser->fields[i]->next);
6189 if (!ast_istype((ast_expression*)asvalue, ast_value))
6191 if (asvalue->expression.vtype != TYPE_ARRAY)
6193 if (!ast_generate_accessors(asvalue, ir)) {
6194 ir_builder_delete(ir);
6198 if (parser->reserved_version &&
6199 !ast_global_codegen(parser->reserved_version, ir, false))
6201 con_out("failed to generate reserved::version");
6202 ir_builder_delete(ir);
6205 for (i = 0; i < vec_size(parser->functions); ++i) {
6206 ast_function *f = parser->functions[i];
6207 if (!ast_function_codegen(f, ir)) {
6208 con_out("failed to generate function %s\n", f->name);
6209 ir_builder_delete(ir);
6214 generate_checksum(parser, ir);
6216 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6217 ir_builder_dump(ir, con_out);
6218 for (i = 0; i < vec_size(parser->functions); ++i) {
6219 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6220 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6221 ir_builder_delete(ir);
6225 parser_remove_ast(parser);
6227 if (compile_Werrors) {
6228 con_out("*** there were warnings treated as errors\n");
6229 compile_show_werrors();
6234 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6235 ir_builder_dump(ir, con_out);
6237 if (!ir_builder_generate(ir, output)) {
6238 con_out("*** failed to generate output file\n");
6239 ir_builder_delete(ir);
6243 ir_builder_delete(ir);